{"text":"\/\/\n\/\/ Name:\t\tSceneGraphDlg.cpp\n\/\/\n\/\/ Copyright (c) 2001-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"SceneGraphDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"wx\/treectrl.h\"\n#include \"wx\/image.h\"\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Engine.h\"\n#include \"vtui\/wxString2.h\"\n#include \"SceneGraphDlg.h\"\n\n#include \nusing namespace std;\n\n#if defined(__WXGTK__) || defined(__WXMOTIF__)\n# include \"icon1.xpm\"\n# include \"icon2.xpm\"\n# include \"icon3.xpm\"\n# include \"icon4.xpm\"\n# include \"icon5.xpm\"\n# include \"icon6.xpm\"\n# include \"icon7.xpm\"\n# include \"icon8.xpm\"\n# include \"icon9.xpm\"\n# include \"icon10.xpm\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass MyTreeItemData : public wxTreeItemData\n{\npublic:\n\tMyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine)\n\t{\n\t\tm_pNode = pNode;\n\t\tm_pEngine = pEngine;\n\t}\n\tvtNodeBase *m_pNode;\n\tvtEngine *m_pEngine;\n};\n\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ SceneGraphDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for SceneGraphDlg\n\nBEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog)\n\tEVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog)\n\tEVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged )\n\tEVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled )\n\tEVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo )\n\tEVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh )\nEND_EVENT_TABLE()\n\nSceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\twxDialog( parent, id, title, position, size, style )\n{\n\tSceneGraphFunc( this, TRUE );\n\n\tm_pZoomTo = GetZoomto();\n\tm_pEnabled = GetEnabled();\n\tm_pTree = GetScenetree();\n\n\tm_pZoomTo->Enable(false);\n\n\tm_imageListNormal = NULL;\n\tCreateImageList(16);\n}\n\nSceneGraphDlg::~SceneGraphDlg()\n{\n\tdelete m_imageListNormal;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SceneGraphDlg::CreateImageList(int size)\n{\n\tdelete m_imageListNormal;\n\n\tif ( size == -1 )\n\t{\n\t\tm_imageListNormal = NULL;\n\t\treturn;\n\t}\n\t\/\/ Make an image list containing small icons\n\tm_imageListNormal = new wxImageList(size, size, TRUE);\n\n\twxIcon icons[10];\n\ticons[0] = wxICON(icon1);\n\ticons[1] = wxICON(icon2);\n\ticons[2] = wxICON(icon3);\n\ticons[3] = wxICON(icon4);\n\ticons[4] = wxICON(icon5);\n\ticons[5] = wxICON(icon6);\n\ticons[6] = wxICON(icon7);\n\ticons[7] = wxICON(icon8);\n\ticons[8] = wxICON(icon9);\n\ticons[9] = wxICON(icon10);\n\n\tint sizeOrig = icons[0].GetWidth();\n\tfor ( size_t i = 0; i < WXSIZEOF(icons); i++ )\n\t{\n\t\tif ( size == sizeOrig )\n\t\t\tm_imageListNormal->Add(icons[i]);\n\t\telse\n\t\t\tm_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\n\t}\n\tm_pTree->SetImageList(m_imageListNormal);\n}\n\n\nvoid SceneGraphDlg::RefreshTreeContents()\n{\n\tvtScene* scene = vtGetScene();\n\tif (!scene)\n\t\treturn;\n\n\t\/\/ start with a blank slate\n\tm_pTree->DeleteAllItems();\n\n\t\/\/ Fill in the tree with nodes\n\tm_bFirst = true;\n\tvtNodeBase *pRoot = scene->GetRoot();\n\tif (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0);\n\n\twxTreeItemId hRoot = m_pTree->GetRootItem();\n\twxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _(\"Engines\"), 7, 7);\n\n\t\/\/ Fill in the tree with engines\n\tint num = scene->GetNumEngines();\n\tvtTarget *target;\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tvtEngine *pEng = scene->GetEngine(i);\n\t\twxString2 str = pEng->GetName2();\n\t\tint targets = pEng->NumTargets();\n\t\ttarget = pEng->GetTarget();\n\t\tif (target)\n\t\t{\n\t\t\tstr += _T(\" -> \");\n\t\t\tvtNodeBase *node = dynamic_cast(target);\n\t\t\tif (node)\n\t\t\t{\n\t\t\t\tstr += _T(\"\\\"\");\n\t\t\t\tstr += wxString::FromAscii(node->GetName2());\n\t\t\t\tstr += _T(\"\\\"\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr += _(\"(non-node)\");\n\t\t}\n\t\tif (targets > 1)\n\t\t{\n\t\t\twxString2 plus;\n\t\t\tplus.Printf(_(\" (%d targets total)\"), targets);\n\t\t\tstr += plus;\n\t\t}\n\t\twxTreeItemId hEng = m_pTree->AppendItem(hEngRoot, str, 1, 1);\n\t\tm_pTree->SetItemData(hEng, new MyTreeItemData(NULL, pEng));\n\t}\n\tm_pTree->Expand(hEngRoot);\n\n\tm_pSelectedEngine = NULL;\n\tm_pSelectedNode = NULL;\n}\n\n\nvoid SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem,\n\t\t\t\t\t\t\t\t\t\tvtNodeBase *pNode, int depth)\n{\n\twxString str;\n\tint nImage;\n\twxTreeItemId hNewItem;\n\n\tif (!pNode) return;\n\n\tif (dynamic_cast(pNode))\n\t{\n\t\tstr = _(\"Light\");\n\t\tnImage = 4;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _(\"Geometry\");\n\t\tnImage = 2;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _T(\"LOD\");\n\t\tnImage = 5;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _T(\"XForm\");\n\t\tnImage = 9;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\t\/\/ must be just a group for grouping's sake\n\t\tstr = _(\"Group\");\n\t\tnImage = 3;\n\t}\n\telse\n\t{\n\t\t\/\/ must be something else\n\t\tstr = _(\"Other\");\n\t\tnImage = 8;\n\t}\n\tif (pNode->GetName2())\n\t{\n\t\tstr += _T(\" \\\"\");\n\t\tstr += wxString::FromAscii(pNode->GetName2());\n\t\tstr += _T(\"\\\"\");\n\t}\n\n\tif (m_bFirst)\n\t{\n\t\thNewItem = m_pTree->AddRoot(str);\n\t\tm_bFirst = false;\n\t}\n\telse\n\t\thNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage);\n\n\tconst std::type_info &t1 = typeid(*pNode);\n\tif (t1 == typeid(vtGeom))\n\t{\n\t\tvtGeom *pGeom = dynamic_cast(pNode);\n\t\tint num_mesh = pGeom->GetNumMeshes();\n\t\twxTreeItemId\thGeomItem;\n\n\t\tfor (int i = 0; i < num_mesh; i++)\n\t\t{\n\t\t\tvtMesh *pMesh = pGeom->GetMesh(i);\n\t\t\tif (pMesh)\n\t\t\t{\n\t\t\t\tint iNumPrim = pMesh->GetNumPrims();\n\t\t\t\tint iNumVert = pMesh->GetNumVertices();\n\n\t\t\t\tGLenum pt = pMesh->GetPrimType();\n\t\t\t\tconst char *mtype;\n\t\t\t\tswitch (pt)\n\t\t\t\t{\n\t\t\t\tcase GL_POINTS: mtype = \"Points\"; break;\n\t\t\t\tcase GL_LINES: mtype = \"Lines\"; break;\n\t\t\t\tcase GL_LINE_LOOP: mtype = \"LineLoop\"; break;\n\t\t\t\tcase GL_LINE_STRIP: mtype = \"LineStrip\"; break;\n\t\t\t\tcase GL_TRIANGLES: mtype = \"Triangles\"; break;\n\t\t\t\tcase GL_TRIANGLE_STRIP: mtype = \"TriStrip\"; break;\n\t\t\t\tcase GL_TRIANGLE_FAN: mtype = \"TriFan\"; break;\n\t\t\t\tcase GL_QUADS: mtype = \"Quads\"; break;\n\t\t\t\tcase GL_QUAD_STRIP: mtype = \"QuadStrip\"; break;\n\t\t\t\tcase GL_POLYGON: mtype = \"Polygon\"; break;\n\t\t\t\t}\n\t\t\t\tstr.Printf(_(\"Mesh %d, %hs, %d verts, %d prims\"), i, mtype, iNumVert, iNumPrim);\n\t\t\t\thGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6);\n\t\t\t}\n\t\t\telse\n\t\t\t\thGeomItem = m_pTree->AppendItem(hNewItem, _(\"Text Mesh\"), 6, 6);\n\t\t}\n\t}\n\n\tm_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL));\n\n\twxTreeItemId hSubItem;\n\tvtGroupBase *pGroup = dynamic_cast(pNode);\n\tif (pGroup)\n\t{\n\t\tint num_children = pGroup->GetNumChildren();\n\t\tif (num_children > 200)\n\t\t{\n\t\t\tstr.Printf(_(\"(%d children)\"), num_children);\n\t\t\thSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < num_children; i++)\n\t\t\t{\n\t\t\t\tvtNode *pChild = pGroup->GetChild(i);\n\t\t\t\tif (pChild)\n\t\t\t\t\tAddNodeItemsRecursively(hNewItem, pChild, depth+1);\n\t\t\t\telse\n\t\t\t\t\thSubItem = m_pTree->AppendItem(hNewItem, _(\"(internal node)\"), 8, 8);\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ expand a bit so that the tree is initially partially exposed\n\tif (depth < 2)\n\t\tm_pTree->Expand(hNewItem);\n}\n\n\n\/\/ WDR: handler implementations for SceneGraphDlg\n\nvoid SceneGraphDlg::OnRefresh( wxCommandEvent &event )\n{\n\tRefreshTreeContents();\n}\n\nvoid SceneGraphDlg::OnZoomTo( wxCommandEvent &event )\n{\n\tif (m_pSelectedNode)\n\t{\n\t\tFSphere sph;\n\t\tm_pSelectedNode->GetBoundSphere(sph, true);\t\/\/ global bounds\n\t\tvtGetScene()->GetCamera()->ZoomToSphere(sph);\n\t}\n}\n\nvoid SceneGraphDlg::OnEnabled( wxCommandEvent &event )\n{\n\tif (m_pSelectedEngine)\n\t\tm_pSelectedEngine->SetEnabled(m_pEnabled->GetValue());\n\tif (m_pSelectedNode)\n\t\tm_pSelectedNode->SetEnabled(m_pEnabled->GetValue());\n}\n\nvoid SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event )\n{\n\twxTreeItemId item = event.GetItem();\n\tMyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item);\n\n\tm_pEnabled->Enable(data != NULL);\n\n\tm_pSelectedEngine = NULL;\n\tm_pSelectedNode = NULL;\n\n\tif (data && data->m_pEngine)\n\t{\n\t\tm_pSelectedEngine = data->m_pEngine;\n\t\tm_pEnabled->SetValue(m_pSelectedEngine->GetEnabled());\n\t}\n\tif (data && data->m_pNode)\n\t{\n\t\tm_pSelectedNode = data->m_pNode;\n\t\tm_pEnabled->SetValue(m_pSelectedNode->GetEnabled());\n\t\tm_pZoomTo->Enable(true);\n\t}\n\telse\n\t\tm_pZoomTo->Enable(false);\n}\n\nvoid SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\tRefreshTreeContents();\n\n\twxWindow::OnInitDialog(event);\n}\n\nimproved 'Zoom To' in layer and scenegraph dialogs to consider vertical FOV to place whole object in view\/\/\n\/\/ Name:\t\tSceneGraphDlg.cpp\n\/\/\n\/\/ Copyright (c) 2001-2004 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"SceneGraphDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n#include \"wx\/treectrl.h\"\n#include \"wx\/image.h\"\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Engine.h\"\n#include \"vtui\/wxString2.h\"\n#include \"SceneGraphDlg.h\"\n\n#include \nusing namespace std;\n\n#if defined(__WXGTK__) || defined(__WXMOTIF__)\n# include \"icon1.xpm\"\n# include \"icon2.xpm\"\n# include \"icon3.xpm\"\n# include \"icon4.xpm\"\n# include \"icon5.xpm\"\n# include \"icon6.xpm\"\n# include \"icon7.xpm\"\n# include \"icon8.xpm\"\n# include \"icon9.xpm\"\n# include \"icon10.xpm\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass MyTreeItemData : public wxTreeItemData\n{\npublic:\n\tMyTreeItemData(vtNodeBase *pNode, vtEngine *pEngine)\n\t{\n\t\tm_pNode = pNode;\n\t\tm_pEngine = pEngine;\n\t}\n\tvtNodeBase *m_pNode;\n\tvtEngine *m_pEngine;\n};\n\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ SceneGraphDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for SceneGraphDlg\n\nBEGIN_EVENT_TABLE(SceneGraphDlg,wxDialog)\n\tEVT_INIT_DIALOG (SceneGraphDlg::OnInitDialog)\n\tEVT_TREE_SEL_CHANGED( ID_SCENETREE, SceneGraphDlg::OnTreeSelChanged )\n\tEVT_CHECKBOX( ID_ENABLED, SceneGraphDlg::OnEnabled )\n\tEVT_BUTTON( ID_ZOOMTO, SceneGraphDlg::OnZoomTo )\n\tEVT_BUTTON( ID_REFRESH, SceneGraphDlg::OnRefresh )\nEND_EVENT_TABLE()\n\nSceneGraphDlg::SceneGraphDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\twxDialog( parent, id, title, position, size, style )\n{\n\tSceneGraphFunc( this, TRUE );\n\n\tm_pZoomTo = GetZoomto();\n\tm_pEnabled = GetEnabled();\n\tm_pTree = GetScenetree();\n\n\tm_pZoomTo->Enable(false);\n\n\tm_imageListNormal = NULL;\n\tCreateImageList(16);\n}\n\nSceneGraphDlg::~SceneGraphDlg()\n{\n\tdelete m_imageListNormal;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SceneGraphDlg::CreateImageList(int size)\n{\n\tdelete m_imageListNormal;\n\n\tif ( size == -1 )\n\t{\n\t\tm_imageListNormal = NULL;\n\t\treturn;\n\t}\n\t\/\/ Make an image list containing small icons\n\tm_imageListNormal = new wxImageList(size, size, TRUE);\n\n\twxIcon icons[10];\n\ticons[0] = wxICON(icon1);\n\ticons[1] = wxICON(icon2);\n\ticons[2] = wxICON(icon3);\n\ticons[3] = wxICON(icon4);\n\ticons[4] = wxICON(icon5);\n\ticons[5] = wxICON(icon6);\n\ticons[6] = wxICON(icon7);\n\ticons[7] = wxICON(icon8);\n\ticons[8] = wxICON(icon9);\n\ticons[9] = wxICON(icon10);\n\n\tint sizeOrig = icons[0].GetWidth();\n\tfor ( size_t i = 0; i < WXSIZEOF(icons); i++ )\n\t{\n\t\tif ( size == sizeOrig )\n\t\t\tm_imageListNormal->Add(icons[i]);\n\t\telse\n\t\t\tm_imageListNormal->Add(wxBitmap(wxBitmap(icons[i]).ConvertToImage().Rescale(size, size)));\n\t}\n\tm_pTree->SetImageList(m_imageListNormal);\n}\n\n\nvoid SceneGraphDlg::RefreshTreeContents()\n{\n\tvtScene* scene = vtGetScene();\n\tif (!scene)\n\t\treturn;\n\n\t\/\/ start with a blank slate\n\tm_pTree->DeleteAllItems();\n\n\t\/\/ Fill in the tree with nodes\n\tm_bFirst = true;\n\tvtNodeBase *pRoot = scene->GetRoot();\n\tif (pRoot) AddNodeItemsRecursively(wxTreeItemId(), pRoot, 0);\n\n\twxTreeItemId hRoot = m_pTree->GetRootItem();\n\twxTreeItemId hEngRoot = m_pTree->AppendItem(hRoot, _(\"Engines\"), 7, 7);\n\n\t\/\/ Fill in the tree with engines\n\tint num = scene->GetNumEngines();\n\tvtTarget *target;\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tvtEngine *pEng = scene->GetEngine(i);\n\t\twxString2 str = pEng->GetName2();\n\t\tint targets = pEng->NumTargets();\n\t\ttarget = pEng->GetTarget();\n\t\tif (target)\n\t\t{\n\t\t\tstr += _T(\" -> \");\n\t\t\tvtNodeBase *node = dynamic_cast(target);\n\t\t\tif (node)\n\t\t\t{\n\t\t\t\tstr += _T(\"\\\"\");\n\t\t\t\tstr += wxString::FromAscii(node->GetName2());\n\t\t\t\tstr += _T(\"\\\"\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr += _(\"(non-node)\");\n\t\t}\n\t\tif (targets > 1)\n\t\t{\n\t\t\twxString2 plus;\n\t\t\tplus.Printf(_(\" (%d targets total)\"), targets);\n\t\t\tstr += plus;\n\t\t}\n\t\twxTreeItemId hEng = m_pTree->AppendItem(hEngRoot, str, 1, 1);\n\t\tm_pTree->SetItemData(hEng, new MyTreeItemData(NULL, pEng));\n\t}\n\tm_pTree->Expand(hEngRoot);\n\n\tm_pSelectedEngine = NULL;\n\tm_pSelectedNode = NULL;\n}\n\n\nvoid SceneGraphDlg::AddNodeItemsRecursively(wxTreeItemId hParentItem,\n\t\t\t\t\t\t\t\t\t\tvtNodeBase *pNode, int depth)\n{\n\twxString str;\n\tint nImage;\n\twxTreeItemId hNewItem;\n\n\tif (!pNode) return;\n\n\tif (dynamic_cast(pNode))\n\t{\n\t\tstr = _(\"Light\");\n\t\tnImage = 4;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _(\"Geometry\");\n\t\tnImage = 2;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _T(\"LOD\");\n\t\tnImage = 5;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\tstr = _T(\"XForm\");\n\t\tnImage = 9;\n\t}\n\telse if (dynamic_cast(pNode))\n\t{\n\t\t\/\/ must be just a group for grouping's sake\n\t\tstr = _(\"Group\");\n\t\tnImage = 3;\n\t}\n\telse\n\t{\n\t\t\/\/ must be something else\n\t\tstr = _(\"Other\");\n\t\tnImage = 8;\n\t}\n\tif (pNode->GetName2())\n\t{\n\t\tstr += _T(\" \\\"\");\n\t\tstr += wxString::FromAscii(pNode->GetName2());\n\t\tstr += _T(\"\\\"\");\n\t}\n\n\tif (m_bFirst)\n\t{\n\t\thNewItem = m_pTree->AddRoot(str);\n\t\tm_bFirst = false;\n\t}\n\telse\n\t\thNewItem = m_pTree->AppendItem(hParentItem, str, nImage, nImage);\n\n\tconst std::type_info &t1 = typeid(*pNode);\n\tif (t1 == typeid(vtGeom))\n\t{\n\t\tvtGeom *pGeom = dynamic_cast(pNode);\n\t\tint num_mesh = pGeom->GetNumMeshes();\n\t\twxTreeItemId\thGeomItem;\n\n\t\tfor (int i = 0; i < num_mesh; i++)\n\t\t{\n\t\t\tvtMesh *pMesh = pGeom->GetMesh(i);\n\t\t\tif (pMesh)\n\t\t\t{\n\t\t\t\tint iNumPrim = pMesh->GetNumPrims();\n\t\t\t\tint iNumVert = pMesh->GetNumVertices();\n\n\t\t\t\tGLenum pt = pMesh->GetPrimType();\n\t\t\t\tconst char *mtype;\n\t\t\t\tswitch (pt)\n\t\t\t\t{\n\t\t\t\tcase GL_POINTS: mtype = \"Points\"; break;\n\t\t\t\tcase GL_LINES: mtype = \"Lines\"; break;\n\t\t\t\tcase GL_LINE_LOOP: mtype = \"LineLoop\"; break;\n\t\t\t\tcase GL_LINE_STRIP: mtype = \"LineStrip\"; break;\n\t\t\t\tcase GL_TRIANGLES: mtype = \"Triangles\"; break;\n\t\t\t\tcase GL_TRIANGLE_STRIP: mtype = \"TriStrip\"; break;\n\t\t\t\tcase GL_TRIANGLE_FAN: mtype = \"TriFan\"; break;\n\t\t\t\tcase GL_QUADS: mtype = \"Quads\"; break;\n\t\t\t\tcase GL_QUAD_STRIP: mtype = \"QuadStrip\"; break;\n\t\t\t\tcase GL_POLYGON: mtype = \"Polygon\"; break;\n\t\t\t\t}\n\t\t\t\tstr.Printf(_(\"Mesh %d, %hs, %d verts, %d prims\"), i, mtype, iNumVert, iNumPrim);\n\t\t\t\thGeomItem = m_pTree->AppendItem(hNewItem, str, 6, 6);\n\t\t\t}\n\t\t\telse\n\t\t\t\thGeomItem = m_pTree->AppendItem(hNewItem, _(\"Text Mesh\"), 6, 6);\n\t\t}\n\t}\n\n\tm_pTree->SetItemData(hNewItem, new MyTreeItemData(pNode, NULL));\n\n\twxTreeItemId hSubItem;\n\tvtGroupBase *pGroup = dynamic_cast(pNode);\n\tif (pGroup)\n\t{\n\t\tint num_children = pGroup->GetNumChildren();\n\t\tif (num_children > 200)\n\t\t{\n\t\t\tstr.Printf(_(\"(%d children)\"), num_children);\n\t\t\thSubItem = m_pTree->AppendItem(hNewItem, str, 8, 8);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < num_children; i++)\n\t\t\t{\n\t\t\t\tvtNode *pChild = pGroup->GetChild(i);\n\t\t\t\tif (pChild)\n\t\t\t\t\tAddNodeItemsRecursively(hNewItem, pChild, depth+1);\n\t\t\t\telse\n\t\t\t\t\thSubItem = m_pTree->AppendItem(hNewItem, _(\"(internal node)\"), 8, 8);\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ expand a bit so that the tree is initially partially exposed\n\tif (depth < 2)\n\t\tm_pTree->Expand(hNewItem);\n}\n\n\n\/\/ WDR: handler implementations for SceneGraphDlg\n\nvoid SceneGraphDlg::OnRefresh( wxCommandEvent &event )\n{\n\tRefreshTreeContents();\n}\n\nvoid SceneGraphDlg::OnZoomTo( wxCommandEvent &event )\n{\n\tif (m_pSelectedNode)\n\t{\n\t\tFSphere sph;\n\t\tm_pSelectedNode->GetBoundSphere(sph, true);\t\/\/ global bounds\n\n\t\t\/\/ a bit back to make sure whole volume of bounding sphere is in view\n\t\tvtCamera *pCam = vtGetScene()->GetCamera();\n\t\tfloat smallest = min(pCam->GetFOV(), pCam->GetVertFOV());\n\t\tfloat alpha = smallest \/ 2.0f;\n\t\tfloat distance = sph.radius \/ tanf(alpha);\n\t\tsph.radius = distance;\n\n\t\tpCam->ZoomToSphere(sph);\n\t}\n}\n\nvoid SceneGraphDlg::OnEnabled( wxCommandEvent &event )\n{\n\tif (m_pSelectedEngine)\n\t\tm_pSelectedEngine->SetEnabled(m_pEnabled->GetValue());\n\tif (m_pSelectedNode)\n\t\tm_pSelectedNode->SetEnabled(m_pEnabled->GetValue());\n}\n\nvoid SceneGraphDlg::OnTreeSelChanged( wxTreeEvent &event )\n{\n\twxTreeItemId item = event.GetItem();\n\tMyTreeItemData *data = (MyTreeItemData *)m_pTree->GetItemData(item);\n\n\tm_pEnabled->Enable(data != NULL);\n\n\tm_pSelectedEngine = NULL;\n\tm_pSelectedNode = NULL;\n\n\tif (data && data->m_pEngine)\n\t{\n\t\tm_pSelectedEngine = data->m_pEngine;\n\t\tm_pEnabled->SetValue(m_pSelectedEngine->GetEnabled());\n\t}\n\tif (data && data->m_pNode)\n\t{\n\t\tm_pSelectedNode = data->m_pNode;\n\t\tm_pEnabled->SetValue(m_pSelectedNode->GetEnabled());\n\t\tm_pZoomTo->Enable(true);\n\t}\n\telse\n\t\tm_pZoomTo->Enable(false);\n}\n\nvoid SceneGraphDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\tRefreshTreeContents();\n\n\twxWindow::OnInitDialog(event);\n}\n\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n#define DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n\n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\n\nnamespace LocalFunction {\n\ntemplate \nclass Difference;\n\ntemplate \nclass DifferenceTraits;\n\n\ntemplate \nclass DifferenceTraits\n{\n static_assert(\n std::is_base_of, MinuendType>::value,\n \"MinuendType has to be derived from Stuff::LocalFunctionInterface< ..., D, d, R, r, 1 >\");\n static_assert(std::is_base_of,\n SubtrahendType>::value,\n \"SubtrahendType has to be derived from Stuff::LocalFunctionInterface< ..., D, d, R, r, 1 >\");\n static_assert(std::is_same::value,\n \"EntityType of MinuendType and SubtrahendType do not match!\");\n\npublic:\n typedef Difference derived_type;\n typedef typename MinuendType::EntityType EntityType;\n};\n\n\ntemplate \nclass Difference\n : public Stuff::LocalFunctionInterface, D, d, R, r, 1>\n{\npublic:\n typedef DifferenceTraits Traits;\n typedef typename Traits::EntityType EntityType;\n\n typedef D DomainFieldType;\n static const unsigned int dimDomain = d;\n typedef Dune::FieldVector DomainType;\n\n typedef R RangeFieldType;\n static const unsigned int dimRange = r;\n static const unsigned int dimRangeRows = dimRange;\n static const unsigned int dimRangeCols = 1;\n typedef Dune::FieldVector RangeType;\n\n typedef Dune::FieldMatrix JacobianRangeType;\n\n Difference(const MinuendType& minuend, const SubtrahendType& subtrahend)\n : minuend_(minuend)\n , subtrahend_(subtrahend)\n , tmp_value_(0)\n , tmp_jacobian_value_(0)\n {\n assert(minuend_.entity() == subtrahend_.entity());\n }\n\n const EntityType& entity() const\n {\n return minuend_.entity();\n }\n\n virtual int order() const\n {\n if ((minuend_.order() < 0) || (subtrahend_.order() < 0))\n return -1;\n else\n return std::max(minuend_.order(), subtrahend_.order());\n }\n\n void evaluate(const DomainType& xx, RangeType& ret) const\n {\n minuend_.evaluate(xx, ret);\n subtrahend_.evaluate(xx, tmp_value_);\n ret -= tmp_value_;\n }\n\n void jacobian(const DomainType& xx, JacobianRangeType& ret) const\n {\n minuend_.evaluate(xx, ret);\n subtrahend_.evaluate(xx, tmp_jacobian_value_);\n ret -= tmp_jacobian_value_;\n }\n\nprivate:\n const MinuendType& minuend_;\n const SubtrahendType& subtrahend_;\n mutable RangeType tmp_value_;\n mutable JacobianRangeType tmp_jacobian_value_;\n};\n\n\n} \/\/ namespace LocalFunction\n\nnamespace DiscreteFunction {\n\n\ntemplate \nclass Difference : public Stuff::LocalizableFunction\n{\npublic:\n template \n class LocalFunction\n {\n typedef typename MinuendType::template LocalFunction LocalMinuendType;\n typedef typename SubtrahendType::template LocalFunction LocalSubtrahendType;\n typedef typename LocalMinuendType::DomainFieldType DomainFieldType;\n static_assert(std::is_same::value,\n \"DomainFieldType of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimDomain = LocalMinuendType::dimDomain;\n static_assert(dimDomain == LocalSubtrahendType::dimDomain,\n \"dimDomain of LocalMinuendType and LocalSubtrahendType do not match!\");\n typedef typename LocalMinuendType::RangeFieldType RangeFieldType;\n static_assert(std::is_same::value,\n \"RangeFieldType of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimRangeRows = LocalMinuendType::dimRangeRows;\n static_assert(dimRangeRows == LocalSubtrahendType::dimRangeRows,\n \"dimRangeRows of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimRangeCols = LocalMinuendType::dimRangeCols;\n static_assert(dimRangeCols == LocalSubtrahendType::dimRangeCols,\n \"dimRangeCols of LocalMinuendType and LocalSubtrahendType do not match!\");\n\n public:\n typedef GDT::LocalFunction::Difference Type;\n };\n\n Difference(const MinuendType& minuend, const SubtrahendType& subtrahend)\n : minuend_(minuend)\n , subtrahend_(subtrahend)\n {\n }\n\n template \n typename LocalFunction::Type localFunction(const EntityType& entity) const\n {\n return typename LocalFunction::Type(minuend_.localFunction(entity), subtrahend_.localFunction(entity));\n }\n\nprivate:\n const MinuendType& minuend_;\n const SubtrahendType& subtrahend_;\n}; \/\/ class Difference\n\n\n} \/\/ namespace DiscreteFunction\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n[discretefunction.difference] is now usable\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n#define DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n\n#include \n\n#include \n\nnamespace Dune {\nnamespace GDT {\n\nnamespace LocalFunction {\n\ntemplate \nclass Difference;\n\n\ntemplate \nclass DifferenceTraits\n{\npublic:\n typedef typename MinuendType::template LocalFunction::Type LocalMinuendType;\n typedef typename SubtrahendType::template LocalFunction::Type LocalSubtrahendType;\n typedef typename LocalMinuendType::DomainFieldType DomainFieldType;\n static_assert(std::is_same::value,\n \"DomainFieldType of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimDomain = LocalMinuendType::dimDomain;\n static_assert(dimDomain == LocalSubtrahendType::dimDomain,\n \"dimDomain of LocalMinuendType and LocalSubtrahendType do not match!\");\n typedef typename LocalMinuendType::RangeFieldType RangeFieldType;\n static_assert(std::is_same::value,\n \"RangeFieldType of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimRangeRows = LocalMinuendType::dimRangeRows;\n static_assert(dimRangeRows == LocalSubtrahendType::dimRangeRows,\n \"dimRangeRows of LocalMinuendType and LocalSubtrahendType do not match!\");\n static const unsigned int dimRangeCols = LocalMinuendType::dimRangeCols;\n static_assert(dimRangeCols == LocalSubtrahendType::dimRangeCols,\n \"dimRangeCols of LocalMinuendType and LocalSubtrahendType do not match!\");\n typedef EntityImp EntityType;\n typedef Difference derived_type;\n static_assert(std::is_base_of,\n LocalMinuendType>::value,\n \"LocalMinuendType has to be derived from Stuff::LocalFunctionInterface!\");\n static_assert(std::is_base_of,\n LocalSubtrahendType>::value,\n \"LocalSubtrahendType has to be derived from Stuff::LocalFunctionInterface!\");\n};\n\n\ntemplate \nclass Difference\n : public Stuff::\n LocalFunctionInterface,\n typename DifferenceTraits::DomainFieldType,\n DifferenceTraits::dimDomain,\n typename DifferenceTraits::RangeFieldType,\n DifferenceTraits::dimRangeRows,\n DifferenceTraits::dimRangeCols>\n{\n typedef Stuff::\n LocalFunctionInterface,\n typename DifferenceTraits::DomainFieldType,\n DifferenceTraits::dimDomain,\n typename DifferenceTraits::RangeFieldType,\n DifferenceTraits::dimRangeRows,\n DifferenceTraits::dimRangeCols> BaseType;\n\npublic:\n typedef DifferenceTraits Traits;\n typedef typename Traits::EntityType EntityType;\n\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeType RangeType;\n typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n Difference(const EntityType& entity, const MinuendType& minuend, const SubtrahendType& subtrahend)\n : entity_(entity)\n , minuend_(minuend.localFunction(entity))\n , subtrahend_(subtrahend.localFunction(entity))\n , tmp_value_(0)\n , tmp_jacobian_value_(0)\n {\n }\n\n const EntityType& entity() const\n {\n return entity_;\n }\n\n virtual int order() const\n {\n if ((minuend_.order() < 0) || (subtrahend_.order() < 0))\n return -1;\n else\n return std::max(minuend_.order(), subtrahend_.order());\n }\n\n void evaluate(const DomainType& xx, RangeType& ret) const\n {\n minuend_.evaluate(xx, ret);\n subtrahend_.evaluate(xx, tmp_value_);\n ret -= tmp_value_;\n }\n\n void jacobian(const DomainType& xx, JacobianRangeType& ret) const\n {\n minuend_.evaluate(xx, ret);\n subtrahend_.evaluate(xx, tmp_jacobian_value_);\n ret -= tmp_jacobian_value_;\n }\n\nprivate:\n const EntityType& entity_;\n const typename Traits::LocalMinuendType& minuend_;\n const typename Traits::LocalSubtrahendType& subtrahend_;\n mutable RangeType tmp_value_;\n mutable JacobianRangeType tmp_jacobian_value_;\n};\n\n\n} \/\/ namespace LocalFunction\n\nnamespace DiscreteFunction {\n\n\ntemplate \nclass Difference : public Stuff::LocalizableFunction\n{\n static_assert(std::is_base_of::value,\n \"MinuendType has to be derived from Stuff::LocalizableFunction!\");\n static_assert(std::is_base_of::value,\n \"SubtrahendType has to be derived from Stuff::LocalizableFunction!\");\n\npublic:\n template \n class LocalFunction\n {\n public:\n typedef GDT::LocalFunction::Difference Type;\n };\n\n Difference(const MinuendType& minuend, const SubtrahendType& subtrahend)\n : minuend_(minuend)\n , subtrahend_(subtrahend)\n {\n }\n\n template \n typename LocalFunction::Type localFunction(const EntityType& entity) const\n {\n return typename LocalFunction::Type(entity, minuend_, subtrahend_);\n }\n\nprivate:\n const MinuendType& minuend_;\n const SubtrahendType& subtrahend_;\n}; \/\/ class Difference\n\n\n} \/\/ namespace DiscreteFunction\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_DISCRETEFUNCTION_DIFFERENCE_HH\n<|endoftext|>"} {"text":"#include \"VDUtils.h\"\n\nusing namespace VideoDromm;\n\nVDUtils::VDUtils(VDSettingsRef aVDSettings)\n{\n\tmVDSettings = aVDSettings;\n\tCI_LOG_V(\"VDUtils constructor\");\n\tx1LeftOrTop = 0;\n\ty1LeftOrTop = 0;\n\tx2LeftOrTop = mVDSettings->mFboWidth;\n\ty2LeftOrTop = mVDSettings->mFboHeight;\n\tx1RightOrBottom = 0;\n\ty1RightOrBottom = 0;\n\tx2RightOrBottom = mVDSettings->mFboWidth;\n\ty2RightOrBottom = mVDSettings->mFboHeight;\n\n}\nfloat VDUtils::formatFloat(float f)\n{\n\tint i;\n\tf *= 100;\n\ti = ((int)f) \/ 100;\n\treturn (float)i;\n}\n\nvoid VDUtils::setup()\n{\n\tcreateWarpFbos();\n}\n\nvoid VDUtils::createWarpFbos()\n{\n\t\/\/ vector + dynamic resize\n\t\/*for (int a = 0; a < 12; a++)\n\t{\n\tWarpFbo newWarpFbo;\n\tif (a == 0)\n\t{\n\tnewWarpFbo.textureIndex = 0; \/\/ spout\n\tnewWarpFbo.textureMode = mVDSettings->TEXTUREMODEINPUT;\n\tnewWarpFbo.active = true;\n\tnewWarpFbo.fbo = gl::Fbo::create(mVDSettings->mFboWidth, mVDSettings->mFboHeight);\n\t}\n\telse\n\t{\n\tnewWarpFbo.textureIndex = 0; \/\/ index of MixFbo for shadamixa\n\tnewWarpFbo.textureMode = mVDSettings->TEXTUREMODESHADER;\n\tnewWarpFbo.active = false;\n\tnewWarpFbo.fbo = gl::Fbo::create(mVDSettings->mPreviewFboWidth, mVDSettings->mPreviewFboHeight);\n\t}\n\tmVDSettings->mWarpFbos.push_back(newWarpFbo);\n\t}*\/\n}\n\nint VDUtils::getWindowsResolution()\n{\n\tCI_LOG_V(\"VDUtils::getWindowsResolution start\");\n\n\tmVDSettings->mDisplayCount = 0;\n\tint w = 1024;\/\/ Display::getMainDisplay()->getWidth();\n\tint h = 768;\/\/Display::getMainDisplay()->getHeight();\n\tCI_LOG_V(\"VDUtils::getWindowsResolution 1\");\n\n\t\/\/ Display sizes\n\tif (mVDSettings->mAutoLayout)\n\t{\n\tCI_LOG_V(\"VDUtils::getWindowsResolution 2\");\n\n\t\tmVDSettings->mMainWindowWidth = w;\n\t\tmVDSettings->mMainWindowHeight = h;\n\t\tmVDSettings->mRenderX = mVDSettings->mMainWindowWidth;\n\t\t\/\/ for MODE_MIX and triplehead(or doublehead), we only want 1\/3 of the screen centered\t\n\t\tfor (auto display : Display::getDisplays())\n\t\t{\n\t\t\tCI_LOG_V(\"VDUtils Window #\" + toString(mVDSettings->mDisplayCount) + \": \" + toString(display->getWidth()) + \"x\" + toString(display->getHeight()));\n\t\t\tmVDSettings->mDisplayCount++;\n\t\t\tmVDSettings->mRenderWidth = display->getWidth();\n\t\t\tmVDSettings->mRenderHeight = display->getHeight();\n\t\t}\n\t}\n\telse\n\t{\n\tCI_LOG_V(\"VDUtils::getWindowsResolution 3\");\n\n\t\tfor (auto display : Display::getDisplays())\n\t\t{\n\t\t\tCI_LOG_V(\"VDUtils Window #\" + toString(mVDSettings->mDisplayCount) + \": \" + toString(display->getWidth()) + \"x\" + toString(display->getHeight()));\n\t\t\tmVDSettings->mDisplayCount++;\n\t\t}\n\t}\n\tmVDSettings->mRenderY = 0;\n\n\tCI_LOG_V(\"VDUtils mMainDisplayWidth:\" + toString(mVDSettings->mMainWindowWidth) + \" mMainDisplayHeight:\" + toString(mVDSettings->mMainWindowHeight));\n\tCI_LOG_V(\"VDUtils mRenderWidth:\" + toString(mVDSettings->mRenderWidth) + \" mRenderHeight:\" + toString(mVDSettings->mRenderHeight));\n\tCI_LOG_V(\"VDUtils mRenderX:\" + toString(mVDSettings->mRenderX) + \" mRenderY:\" + toString(mVDSettings->mRenderY));\n\t\/\/mVDSettings->mRenderResoXY = vec2(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);\n\t\/\/ in case only one screen , render from x = 0\n\tif (mVDSettings->mDisplayCount == 1) mVDSettings->mRenderX = 0;\n\tsplitWarp(mVDSettings->mFboWidth, mVDSettings->mFboHeight);\n\treturn w;\n}\nvoid VDUtils::splitWarp(int fboWidth, int fboHeight) {\n\n\tx1LeftOrTop = x1RightOrBottom = 0;\n\ty1LeftOrTop = y1RightOrBottom = 0;\n\tx2LeftOrTop = x2RightOrBottom = mVDSettings->mFboWidth;\n\ty2LeftOrTop = y2RightOrBottom = mVDSettings->mFboHeight;\n\n\tif (mVDSettings->mSplitWarpH) {\n\t\tx2LeftOrTop = (fboWidth \/ 2) - 1;\n\n\t\tx1RightOrBottom = fboWidth \/ 2;\n\t\tx2RightOrBottom = fboWidth;\n\t}\n\telse if (mVDSettings->mSplitWarpV) {\n\t\ty2LeftOrTop = (fboHeight \/ 2) - 1;\n\t\ty1RightOrBottom = fboHeight \/ 2;\n\t\ty2RightOrBottom = fboHeight;\n\t}\n\telse\n\t{\n\t\t\/\/ no change\n\t}\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n\tmSrcAreaRightOrBottom = Area(x1RightOrBottom, y1RightOrBottom, x2RightOrBottom, y2RightOrBottom);\n\n}\nvoid VDUtils::moveX1LeftOrTop(int x1) {\n\tx1LeftOrTop = x1;\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n}\nvoid VDUtils::moveY1LeftOrTop(int y1) {\n\ty1LeftOrTop = y1;\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n}\n\nArea VDUtils::getSrcAreaLeftOrTop() {\n\treturn mSrcAreaLeftOrTop;\n}\nArea VDUtils::getSrcAreaRightOrBottom() {\n\treturn mSrcAreaRightOrBottom;\n}\n\nfs::path VDUtils::getPath(string path)\n{\n\tfs::path p = app::getAssetPath(\"\");\n\tif (path.length() > 0) { p += fs::path(\"\/\" + path); }\n\treturn p;\n}\nstring VDUtils::getFileNameFromFullPath(string path)\n{\n\tfs::path fullPath = path;\n\treturn fullPath.filename().string();\n}\nDisplays not working on linux#include \"VDUtils.h\"\n\nusing namespace VideoDromm;\n\nVDUtils::VDUtils(VDSettingsRef aVDSettings)\n{\n\tmVDSettings = aVDSettings;\n\tCI_LOG_V(\"VDUtils constructor\");\n\tx1LeftOrTop = 0;\n\ty1LeftOrTop = 0;\n\tx2LeftOrTop = mVDSettings->mFboWidth;\n\ty2LeftOrTop = mVDSettings->mFboHeight;\n\tx1RightOrBottom = 0;\n\ty1RightOrBottom = 0;\n\tx2RightOrBottom = mVDSettings->mFboWidth;\n\ty2RightOrBottom = mVDSettings->mFboHeight;\n\n}\nfloat VDUtils::formatFloat(float f)\n{\n\tint i;\n\tf *= 100;\n\ti = ((int)f) \/ 100;\n\treturn (float)i;\n}\n\nvoid VDUtils::setup()\n{\n\tcreateWarpFbos();\n}\n\nvoid VDUtils::createWarpFbos()\n{\n\t\/\/ vector + dynamic resize\n\t\/*for (int a = 0; a < 12; a++)\n\t{\n\tWarpFbo newWarpFbo;\n\tif (a == 0)\n\t{\n\tnewWarpFbo.textureIndex = 0; \/\/ spout\n\tnewWarpFbo.textureMode = mVDSettings->TEXTUREMODEINPUT;\n\tnewWarpFbo.active = true;\n\tnewWarpFbo.fbo = gl::Fbo::create(mVDSettings->mFboWidth, mVDSettings->mFboHeight);\n\t}\n\telse\n\t{\n\tnewWarpFbo.textureIndex = 0; \/\/ index of MixFbo for shadamixa\n\tnewWarpFbo.textureMode = mVDSettings->TEXTUREMODESHADER;\n\tnewWarpFbo.active = false;\n\tnewWarpFbo.fbo = gl::Fbo::create(mVDSettings->mPreviewFboWidth, mVDSettings->mPreviewFboHeight);\n\t}\n\tmVDSettings->mWarpFbos.push_back(newWarpFbo);\n\t}*\/\n}\n\nint VDUtils::getWindowsResolution()\n{\n\n\tmVDSettings->mDisplayCount = 0;\n\tint w = Display::getMainDisplay()->getWidth();\n\tint h = Display::getMainDisplay()->getHeight();\n\n\t\/\/ Display sizes\n\tif (mVDSettings->mAutoLayout)\n\t{\n\t\tmVDSettings->mMainWindowWidth = w;\n\t\tmVDSettings->mMainWindowHeight = h;\n\t\tmVDSettings->mRenderX = mVDSettings->mMainWindowWidth;\n\t\t\/\/ for MODE_MIX and triplehead(or doublehead), we only want 1\/3 of the screen centered\t\n\t\tfor (auto display : Display::getDisplays())\n\t\t{\n\t\t\tCI_LOG_V(\"VDUtils Window #\" + toString(mVDSettings->mDisplayCount) + \": \" + toString(display->getWidth()) + \"x\" + toString(display->getHeight()));\n\t\t\tmVDSettings->mDisplayCount++;\n\t\t\tmVDSettings->mRenderWidth = display->getWidth();\n\t\t\tmVDSettings->mRenderHeight = display->getHeight();\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (auto display : Display::getDisplays())\n\t\t{\n\t\t\tCI_LOG_V(\"VDUtils Window #\" + toString(mVDSettings->mDisplayCount) + \": \" + toString(display->getWidth()) + \"x\" + toString(display->getHeight()));\n\t\t\tmVDSettings->mDisplayCount++;\n\t\t}\n\t}\n\tmVDSettings->mRenderY = 0;\n\n\tCI_LOG_V(\"VDUtils mMainDisplayWidth:\" + toString(mVDSettings->mMainWindowWidth) + \" mMainDisplayHeight:\" + toString(mVDSettings->mMainWindowHeight));\n\tCI_LOG_V(\"VDUtils mRenderWidth:\" + toString(mVDSettings->mRenderWidth) + \" mRenderHeight:\" + toString(mVDSettings->mRenderHeight));\n\tCI_LOG_V(\"VDUtils mRenderX:\" + toString(mVDSettings->mRenderX) + \" mRenderY:\" + toString(mVDSettings->mRenderY));\n\t\/\/mVDSettings->mRenderResoXY = vec2(mVDSettings->mRenderWidth, mVDSettings->mRenderHeight);\n\t\/\/ in case only one screen , render from x = 0\n\tif (mVDSettings->mDisplayCount == 1) mVDSettings->mRenderX = 0;\n\tsplitWarp(mVDSettings->mFboWidth, mVDSettings->mFboHeight);\n\t\n\treturn w;\n}\nvoid VDUtils::splitWarp(int fboWidth, int fboHeight) {\n\n\tx1LeftOrTop = x1RightOrBottom = 0;\n\ty1LeftOrTop = y1RightOrBottom = 0;\n\tx2LeftOrTop = x2RightOrBottom = mVDSettings->mFboWidth;\n\ty2LeftOrTop = y2RightOrBottom = mVDSettings->mFboHeight;\n\n\tif (mVDSettings->mSplitWarpH) {\n\t\tx2LeftOrTop = (fboWidth \/ 2) - 1;\n\n\t\tx1RightOrBottom = fboWidth \/ 2;\n\t\tx2RightOrBottom = fboWidth;\n\t}\n\telse if (mVDSettings->mSplitWarpV) {\n\t\ty2LeftOrTop = (fboHeight \/ 2) - 1;\n\t\ty1RightOrBottom = fboHeight \/ 2;\n\t\ty2RightOrBottom = fboHeight;\n\t}\n\telse\n\t{\n\t\t\/\/ no change\n\t}\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n\tmSrcAreaRightOrBottom = Area(x1RightOrBottom, y1RightOrBottom, x2RightOrBottom, y2RightOrBottom);\n\n}\nvoid VDUtils::moveX1LeftOrTop(int x1) {\n\tx1LeftOrTop = x1;\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n}\nvoid VDUtils::moveY1LeftOrTop(int y1) {\n\ty1LeftOrTop = y1;\n\tmSrcAreaLeftOrTop = Area(x1LeftOrTop, y1LeftOrTop, x2LeftOrTop, y2LeftOrTop);\n}\n\nArea VDUtils::getSrcAreaLeftOrTop() {\n\treturn mSrcAreaLeftOrTop;\n}\nArea VDUtils::getSrcAreaRightOrBottom() {\n\treturn mSrcAreaRightOrBottom;\n}\n\nfs::path VDUtils::getPath(string path)\n{\n\tfs::path p = app::getAssetPath(\"\");\n\tif (path.length() > 0) { p += fs::path(\"\/\" + path); }\n\treturn p;\n}\nstring VDUtils::getFileNameFromFullPath(string path)\n{\n\tfs::path fullPath = path;\n\treturn fullPath.filename().string();\n}\n<|endoftext|>"} {"text":"\/*===================================================================\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief Waypoint class\n *\n * @author Benjamin Knecht \n * @author Petri Tanskanen \n *\n *\/\n\n#include \"QsLog.h\"\n#include \"Waypoint.h\"\n#include \n\n\nWaypoint::Waypoint(quint16 _id, double _x, double _y, double _z, double _param1, double _param2, double _param3, double _param4,\n bool _autocontinue, bool _current, MAV_FRAME _frame, MAV_CMD _action, const QString& _description)\n : id(_id),\n x(_x),\n y(_y),\n z(_z),\n yaw(_param4),\n frame(_frame),\n action(_action),\n autocontinue(_autocontinue),\n current(_current),\n orbit(_param3),\n param1(_param1),\n param2(_param2),\n name(QString(\"WP%1\").arg(id, 2, 10, QChar('0'))),\n description(_description),\n reachedTime(0)\n{\n}\n\nWaypoint::Waypoint(const Waypoint& waypoint)\n : id(waypoint.getId()),\n x(waypoint.getX()),\n y(waypoint.getY()),\n z(waypoint.getZ()),\n yaw(waypoint.getYaw()),\n frame(waypoint.getFrame()),\n action(waypoint.getAction()),\n autocontinue(waypoint.getAutoContinue()),\n current(waypoint.getCurrent()),\n orbit(waypoint.getParam3()),\n param1(waypoint.getParam1()),\n param2(waypoint.getParam2()),\n name(waypoint.getName()),\n description(waypoint.getDescription()),\n reachedTime(waypoint.getReachedTime())\n{\n \/\/ Copy Constrcutor\n}\n\nWaypoint::~Waypoint()\n{ \n}\n\nbool Waypoint::isNavigationType()\n{\n return (action < MAV_CMD_NAV_LAST);\n}\n\nvoid Waypoint::save(QTextStream &saveStream)\n{\n QString position(\"%1\\t%2\\t%3\");\n position = position.arg(x, 0, 'g', 18);\n position = position.arg(y, 0, 'g', 18);\n position = position.arg(z, 0, 'g', 18);\n QString parameters(\"%1\\t%2\\t%3\\t%4\");\n parameters = parameters.arg(param1, 0, 'g', 18).arg(param2, 0, 'g', 18).arg(orbit, 0, 'g', 18).arg(yaw, 0, 'g', 18);\n \/\/ FORMAT: \n \/\/ as documented here: http:\/\/qgroundcontrol.org\/waypoint_protocol\n saveStream << this->getId() << \"\\t\" << this->getCurrent() << \"\\t\" << this->getFrame() << \"\\t\" << this->getAction() << \"\\t\" << parameters << \"\\t\" << position << \"\\t\" << this->getAutoContinue() << \"\\r\\n\"; \/\/\"\\t\" << this->getDescription() << \"\\r\\n\";\n}\n\nbool Waypoint::load(QTextStream &loadStream)\n{\n QString readLine;\n do {\n readLine = loadStream.readLine();\n } while(readLine.startsWith(\"#\"));\n\n const QStringList& wpParams = readLine.split(\"\\t\");\n\n if (wpParams.size() == 12) {\n this->id = wpParams[0].toInt();\n this->current = (wpParams[1].toInt() == 1 ? true : false);\n this->frame = (MAV_FRAME) wpParams[2].toInt();\n this->action = (MAV_CMD) wpParams[3].toInt();\n this->param1 = wpParams[4].toDouble();\n this->param2 = wpParams[5].toDouble();\n this->orbit = wpParams[6].toDouble();\n this->yaw = wpParams[7].toDouble();\n this->x = wpParams[8].toDouble();\n this->y = wpParams[9].toDouble();\n this->z = wpParams[10].toDouble();\n this->autocontinue = (wpParams[11].toInt() == 1 ? true : false);\n \/\/this->description = wpParams[12];\n return true;\n }\n return false;\n}\n\n\nvoid Waypoint::setId(quint16 id)\n{\n this->id = id;\n this->name = QString(\"WP%1\").arg(id, 2, 10, QChar('0'));\n emit changed(this);\n}\n\nvoid Waypoint::setX(double x)\n{\n if (!isinf(x) && !isnan(x) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->x = x;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setY(double y)\n{\n if (!isinf(y) && !isnan(y) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->y = y;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setZ(double z)\n{\n if (!isinf(z) && !isnan(z) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->z = z;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLatitude(double lat)\n{\n if (this->x != lat && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->x = lat;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLongitude(double lon)\n{\n if (this->y != lon && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->y = lon;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAltitude(double altitude)\n{\n if (this->z != altitude && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->z = altitude;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setYaw(int yaw)\n{\n if (this->yaw != yaw)\n {\n this->yaw = yaw;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setYaw(double yaw)\n{\n if (this->yaw != yaw)\n {\n this->yaw = yaw;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAction(int action)\n{\n if (this->action != (MAV_CMD)action)\n {\n this->action = (MAV_CMD)action;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAction(MAV_CMD action)\n{\n if (this->action != action) {\n this->action = action;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setFrame(MAV_FRAME frame)\n{\n if (this->frame != frame) {\n this->frame = frame;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAutocontinue(bool autoContinue)\n{\n if (this->autocontinue != autoContinue) {\n this->autocontinue = autoContinue;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setCurrent(bool current)\n{\n if (this->current != current)\n {\n this->current = current;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAcceptanceRadius(double radius)\n{\n if (this->param2 != radius)\n {\n this->param2 = radius;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam1(double param1)\n{\n QLOG_DEBUG() << \"SENDER:\" << QObject::sender();\n QLOG_DEBUG() << \"PARAM1 SET REQ:\" << param1;\n if (this->param1 != param1)\n {\n this->param1 = param1;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam2(double param2)\n{\n if (this->param2 != param2)\n {\n this->param2 = param2;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam3(double param3)\n{\n if (this->orbit != param3) {\n this->orbit = param3;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam4(double param4)\n{\n if (this->yaw != param4) {\n this->yaw = param4;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam5(double param5)\n{\n if (this->x != param5) {\n this->x = param5;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam6(double param6)\n{\n if (this->y != param6) {\n this->y = param6;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam7(double param7)\n{\n if (this->z != param7) {\n this->z = param7;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLoiterOrbit(double orbit)\n{\n if (this->orbit != orbit) {\n this->orbit = orbit;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setHoldTime(int holdTime)\n{\n if (this->param1 != holdTime) {\n this->param1 = holdTime;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setHoldTime(double holdTime)\n{\n if (this->param1 != holdTime) {\n this->param1 = holdTime;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setTurns(int turns)\n{\n if (this->param1 != turns) {\n this->param1 = turns;\n emit changed(this);\n }\n}\n\nQString Waypoint::debugString()\n{\n QString debugString(\"Waypoint: \" + name\n + \" id: \" + QString::number(id)\n + \" x:\" + QString::number(x)\n + \" y:\" + QString::number(y)\n + \" z:\" + QString::number(z)\n + \" yaw:\" + QString::number(yaw)\n + \" MAV_FRAME:\" + QString::number(frame)\n + \" MAV_CMD:\" + QString::number(action)\n + \" autocontinue:\" + autocontinue\n + \" current:\" + current\n + \" orbit:\" + QString::number(orbit)\n + \" param1:\" + QString::number(param1)\n + \" param2:\" + QString::number(param2)\n + \" turns:\" + QString::number(turns)\n + \" description:\" + description\n + \" reachedTime:\" + QString::number(reachedTime)) ;\n return debugString;\n}\nMission Widget: Fix issue where optional description field created a crash\/*===================================================================\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n\/**\n * @file\n * @brief Waypoint class\n *\n * @author Benjamin Knecht \n * @author Petri Tanskanen \n *\n *\/\n\n#include \"QsLog.h\"\n#include \"Waypoint.h\"\n#include \n\n\nWaypoint::Waypoint(quint16 _id, double _x, double _y, double _z, double _param1, double _param2, double _param3, double _param4,\n bool _autocontinue, bool _current, MAV_FRAME _frame, MAV_CMD _action, const QString& _description)\n : id(_id),\n x(_x),\n y(_y),\n z(_z),\n yaw(_param4),\n frame(_frame),\n action(_action),\n autocontinue(_autocontinue),\n current(_current),\n orbit(_param3),\n param1(_param1),\n param2(_param2),\n name(QString(\"WP%1\").arg(id, 2, 10, QChar('0'))),\n description(_description),\n reachedTime(0)\n{\n}\n\nWaypoint::Waypoint(const Waypoint& waypoint)\n : id(waypoint.getId()),\n x(waypoint.getX()),\n y(waypoint.getY()),\n z(waypoint.getZ()),\n yaw(waypoint.getYaw()),\n frame(waypoint.getFrame()),\n action(waypoint.getAction()),\n autocontinue(waypoint.getAutoContinue()),\n current(waypoint.getCurrent()),\n orbit(waypoint.getParam3()),\n param1(waypoint.getParam1()),\n param2(waypoint.getParam2()),\n name(waypoint.getName()),\n description(waypoint.getDescription()),\n reachedTime(waypoint.getReachedTime())\n{\n \/\/ Copy Constrcutor\n}\n\nWaypoint::~Waypoint()\n{ \n}\n\nbool Waypoint::isNavigationType()\n{\n return (action < MAV_CMD_NAV_LAST);\n}\n\nvoid Waypoint::save(QTextStream &saveStream)\n{\n QString position(\"%1\\t%2\\t%3\");\n position = position.arg(x, 0, 'g', 18);\n position = position.arg(y, 0, 'g', 18);\n position = position.arg(z, 0, 'g', 18);\n QString parameters(\"%1\\t%2\\t%3\\t%4\");\n parameters = parameters.arg(param1, 0, 'g', 18).arg(param2, 0, 'g', 18).arg(orbit, 0, 'g', 18).arg(yaw, 0, 'g', 18);\n \/\/ FORMAT: \n \/\/ as documented here: http:\/\/qgroundcontrol.org\/waypoint_protocol\n saveStream << this->getId() << \"\\t\" << this->getCurrent() << \"\\t\" << this->getFrame() << \"\\t\" << this->getAction() << \"\\t\" << parameters << \"\\t\" << position << \"\\t\" << this->getAutoContinue() << \"\\r\\n\"; \/\/\"\\t\" << this->getDescription() << \"\\r\\n\";\n}\n\nbool Waypoint::load(QTextStream &loadStream)\n{\n QString readLine;\n do {\n readLine = loadStream.readLine();\n } while(readLine.startsWith(\"#\"));\n\n const QStringList& wpParams = readLine.split(\"\\t\");\n\n if ((wpParams.size() >= 12)\n &&(wpParams.size() <= 13)){\n this->id = wpParams[0].toInt();\n this->current = (wpParams[1].toInt() == 1 ? true : false);\n this->frame = (MAV_FRAME) wpParams[2].toInt();\n this->action = (MAV_CMD) wpParams[3].toInt();\n this->param1 = wpParams[4].toDouble();\n this->param2 = wpParams[5].toDouble();\n this->orbit = wpParams[6].toDouble();\n this->yaw = wpParams[7].toDouble();\n this->x = wpParams[8].toDouble();\n this->y = wpParams[9].toDouble();\n this->z = wpParams[10].toDouble();\n this->autocontinue = (wpParams[11].toInt() == 1 ? true : false);\n if(wpParams.size() == 13) { \/\/ Optional Description\n this->description = wpParams[12];\n }\n return true;\n }\n return false;\n}\n\n\nvoid Waypoint::setId(quint16 id)\n{\n this->id = id;\n this->name = QString(\"WP%1\").arg(id, 2, 10, QChar('0'));\n emit changed(this);\n}\n\nvoid Waypoint::setX(double x)\n{\n if (!isinf(x) && !isnan(x) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->x = x;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setY(double y)\n{\n if (!isinf(y) && !isnan(y) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->y = y;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setZ(double z)\n{\n if (!isinf(z) && !isnan(z) && ((this->frame == MAV_FRAME_LOCAL_NED) || (this->frame == MAV_FRAME_LOCAL_ENU)))\n {\n this->z = z;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLatitude(double lat)\n{\n if (this->x != lat && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->x = lat;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLongitude(double lon)\n{\n if (this->y != lon && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->y = lon;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAltitude(double altitude)\n{\n if (this->z != altitude && ((this->frame == MAV_FRAME_GLOBAL) || (this->frame == MAV_FRAME_GLOBAL_RELATIVE_ALT)))\n {\n this->z = altitude;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setYaw(int yaw)\n{\n if (this->yaw != yaw)\n {\n this->yaw = yaw;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setYaw(double yaw)\n{\n if (this->yaw != yaw)\n {\n this->yaw = yaw;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAction(int action)\n{\n if (this->action != (MAV_CMD)action)\n {\n this->action = (MAV_CMD)action;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAction(MAV_CMD action)\n{\n if (this->action != action) {\n this->action = action;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setFrame(MAV_FRAME frame)\n{\n if (this->frame != frame) {\n this->frame = frame;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAutocontinue(bool autoContinue)\n{\n if (this->autocontinue != autoContinue) {\n this->autocontinue = autoContinue;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setCurrent(bool current)\n{\n if (this->current != current)\n {\n this->current = current;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setAcceptanceRadius(double radius)\n{\n if (this->param2 != radius)\n {\n this->param2 = radius;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam1(double param1)\n{\n QLOG_DEBUG() << \"SENDER:\" << QObject::sender();\n QLOG_DEBUG() << \"PARAM1 SET REQ:\" << param1;\n if (this->param1 != param1)\n {\n this->param1 = param1;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam2(double param2)\n{\n if (this->param2 != param2)\n {\n this->param2 = param2;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam3(double param3)\n{\n if (this->orbit != param3) {\n this->orbit = param3;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam4(double param4)\n{\n if (this->yaw != param4) {\n this->yaw = param4;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam5(double param5)\n{\n if (this->x != param5) {\n this->x = param5;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam6(double param6)\n{\n if (this->y != param6) {\n this->y = param6;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setParam7(double param7)\n{\n if (this->z != param7) {\n this->z = param7;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setLoiterOrbit(double orbit)\n{\n if (this->orbit != orbit) {\n this->orbit = orbit;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setHoldTime(int holdTime)\n{\n if (this->param1 != holdTime) {\n this->param1 = holdTime;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setHoldTime(double holdTime)\n{\n if (this->param1 != holdTime) {\n this->param1 = holdTime;\n emit changed(this);\n }\n}\n\nvoid Waypoint::setTurns(int turns)\n{\n if (this->param1 != turns) {\n this->param1 = turns;\n emit changed(this);\n }\n}\n\nQString Waypoint::debugString()\n{\n QString debugString(\"Waypoint: \" + name\n + \" id: \" + QString::number(id)\n + \" x:\" + QString::number(x)\n + \" y:\" + QString::number(y)\n + \" z:\" + QString::number(z)\n + \" yaw:\" + QString::number(yaw)\n + \" MAV_FRAME:\" + QString::number(frame)\n + \" MAV_CMD:\" + QString::number(action)\n + \" autocontinue:\" + autocontinue\n + \" current:\" + current\n + \" orbit:\" + QString::number(orbit)\n + \" param1:\" + QString::number(param1)\n + \" param2:\" + QString::number(param2)\n + \" turns:\" + QString::number(turns)\n + \" description:\" + description\n + \" reachedTime:\" + QString::number(reachedTime)) ;\n return debugString;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \"..\/..\/core\/Setup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if OUZEL_SUPPORTS_X11\n# include \n#endif\n#include \"InputSystemLinux.hpp\"\n#include \"CursorLinux.hpp\"\n#include \"..\/..\/core\/linux\/EngineLinux.hpp\"\n#include \"..\/..\/core\/linux\/NativeWindowLinux.hpp\"\n\nnamespace ouzel::input::linux\n{\n InputSystem::InputSystem(const std::function(const Event&)>& initCallback):\n#if OUZEL_SUPPORTS_X11\n input::InputSystem(initCallback),\n keyboardDevice(std::make_unique(*this, getNextDeviceId())),\n mouseDevice(std::make_unique(*this, getNextDeviceId())),\n touchpadDevice(std::make_unique(*this, getNextDeviceId(), true))\n#else\n InputSystem(initCallback)\n#endif\n {\n#if OUZEL_SUPPORTS_X11\n auto engineLinux = static_cast(engine);\n auto display = engineLinux->getDisplay();\n\n char data[1] = {0};\n\n Pixmap pixmap = XCreateBitmapFromData(display, DefaultRootWindow(display), data, 1, 1);\n if (pixmap)\n {\n XColor color;\n color.red = color.green = color.blue = 0;\n\n emptyCursor = XCreatePixmapCursor(display, pixmap, pixmap, &color, &color, 0, 0);\n XFreePixmap(display, pixmap);\n }\n#endif\n\n using CloseDirFunction = int(*)(DIR*);\n std::unique_ptr dir(opendir(\"\/dev\/input\"), closedir);\n if (!dir)\n throw std::system_error(errno, std::system_category(), \"Failed to open directory\");\n\n while (const dirent* ent = readdir(dir.get()))\n {\n if (std::strncmp(\"event\", ent->d_name, 5) == 0)\n {\n try\n {\n std::string filename = std::string(\"\/dev\/input\/\") + ent->d_name;\n auto eventDevice = std::make_unique(*this, filename);\n eventDevices.insert(std::pair(eventDevice->getFd(), std::move(eventDevice)));\n }\n catch (const std::exception&)\n {\n }\n }\n }\n }\n\n InputSystem::~InputSystem()\n {\n#if OUZEL_SUPPORTS_X11\n auto engineLinux = static_cast(engine);\n if (emptyCursor != None) XFreeCursor(engineLinux->getDisplay(), emptyCursor);\n#endif\n }\n\n void InputSystem::executeCommand(const Command& command)\n {\n switch (command.type)\n {\n case Command::Type::startDeviceDiscovery:\n discovering = true;\n break;\n case Command::Type::stopDeviceDiscovery:\n discovering = false;\n break;\n case Command::Type::setPlayerIndex:\n {\n break;\n }\n case Command::Type::setVibration:\n {\n break;\n }\n case Command::Type::setPosition:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setPosition(command.position);\n }\n break;\n }\n case Command::Type::initCursor:\n {\n if (command.cursorResource > cursors.size())\n cursors.resize(command.cursorResource);\n\n if (command.data.empty())\n {\n auto cursor = std::make_unique(command.systemCursor);\n cursors[command.cursorResource - 1] = std::move(cursor);\n }\n else\n {\n auto cursor = std::make_unique(command.data, command.size,\n command.pixelFormat, command.hotSpot);\n cursors[command.cursorResource - 1] = std::move(cursor);\n }\n break;\n }\n case Command::Type::destroyCursor:\n {\n#if OUZEL_SUPPORTS_X11\n Cursor* cursor = cursors[command.cursorResource - 1].get();\n\n if (mouseDevice->getCursor() == cursor)\n {\n mouseDevice->setCursor(nullptr);\n updateCursor();\n }\n#endif\n\n cursors[command.cursorResource - 1].reset();\n break;\n }\n case Command::Type::setCursor:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n {\n if (command.cursorResource)\n mouseDevice->setCursor(cursors[command.cursorResource - 1].get());\n else\n mouseDevice->setCursor(nullptr);\n#if OUZEL_SUPPORTS_X11\n updateCursor();\n#endif\n }\n }\n break;\n }\n case Command::Type::setCursorVisible:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setCursorVisible(command.visible);\n }\n break;\n }\n case Command::Type::setCursorLocked:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setCursorLocked(command.locked);\n }\n break;\n }\n default:\n break;\n }\n }\n\n void InputSystem::update()\n {\n fd_set rfds;\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n\n FD_ZERO(&rfds);\n\n int maxFd = 0;\n\n for (const auto& i : eventDevices)\n {\n FD_SET(i.first, &rfds);\n if (i.first > maxFd) maxFd = i.first;\n }\n\n int retval;\n if ((retval = select(maxFd + 1, &rfds, nullptr, nullptr, &tv)) == -1)\n throw std::system_error(errno, std::system_category(), \"Select failed\");\n\n if (retval > 0)\n {\n for (auto i = eventDevices.begin(); i != eventDevices.end();)\n {\n if (FD_ISSET(i->first, &rfds))\n {\n try\n {\n i->second->update();\n ++i;\n }\n catch (const std::exception&)\n {\n i = eventDevices.erase(i);\n }\n }\n else\n ++i;\n }\n }\n\n if (discovering)\n {\n using CloseDirFunction = int(*)(DIR*);\n std::unique_ptr dir(opendir(\"\/dev\/input\"), closedir);\n\n if (!dir)\n throw std::system_error(errno, std::system_category(), \"Failed to open directory\");\n\n while (const dirent* ent = readdir(dir.get()))\n {\n if (std::strncmp(\"event\", ent->d_name, 5) == 0)\n {\n try\n {\n std::string filename = std::string(\"\/dev\/input\/\") + ent->d_name;\n auto eventDevice = std::make_unique(*this, filename);\n eventDevices.insert(std::pair(eventDevice->getFd(), std::move(eventDevice)));\n }\n catch (const std::exception&)\n {\n }\n }\n }\n }\n }\n\n#if OUZEL_SUPPORTS_X11\n void InputSystem::updateCursor() const\n {\n auto engineLinux = static_cast(engine);\n auto windowLinux = static_cast(engine->getWindow()->getNativeWindow());\n auto display = engineLinux->getDisplay();\n auto window = windowLinux->getNativeWindow();\n\n if (mouseDevice->isCursorVisible())\n {\n if (mouseDevice->getCursor())\n XDefineCursor(display, window, mouseDevice->getCursor()->getCursor());\n else\n XUndefineCursor(display, window);\n }\n else\n XDefineCursor(display, window, emptyCursor);\n }\n#endif\n}\nFix the initialization of the input system on raspberry Pi\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \"..\/..\/core\/Setup.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if OUZEL_SUPPORTS_X11\n# include \n#endif\n#include \"InputSystemLinux.hpp\"\n#include \"CursorLinux.hpp\"\n#include \"..\/..\/core\/linux\/EngineLinux.hpp\"\n#include \"..\/..\/core\/linux\/NativeWindowLinux.hpp\"\n\nnamespace ouzel::input::linux\n{\n InputSystem::InputSystem(const std::function(const Event&)>& initCallback):\n#if OUZEL_SUPPORTS_X11\n input::InputSystem(initCallback),\n keyboardDevice(std::make_unique(*this, getNextDeviceId())),\n mouseDevice(std::make_unique(*this, getNextDeviceId())),\n touchpadDevice(std::make_unique(*this, getNextDeviceId(), true))\n#else\n input::InputSystem(initCallback)\n#endif\n {\n#if OUZEL_SUPPORTS_X11\n auto engineLinux = static_cast(engine);\n auto display = engineLinux->getDisplay();\n\n char data[1] = {0};\n\n Pixmap pixmap = XCreateBitmapFromData(display, DefaultRootWindow(display), data, 1, 1);\n if (pixmap)\n {\n XColor color;\n color.red = color.green = color.blue = 0;\n\n emptyCursor = XCreatePixmapCursor(display, pixmap, pixmap, &color, &color, 0, 0);\n XFreePixmap(display, pixmap);\n }\n#endif\n\n using CloseDirFunction = int(*)(DIR*);\n std::unique_ptr dir(opendir(\"\/dev\/input\"), closedir);\n if (!dir)\n throw std::system_error(errno, std::system_category(), \"Failed to open directory\");\n\n while (const dirent* ent = readdir(dir.get()))\n {\n if (std::strncmp(\"event\", ent->d_name, 5) == 0)\n {\n try\n {\n std::string filename = std::string(\"\/dev\/input\/\") + ent->d_name;\n auto eventDevice = std::make_unique(*this, filename);\n eventDevices.insert(std::pair(eventDevice->getFd(), std::move(eventDevice)));\n }\n catch (const std::exception&)\n {\n }\n }\n }\n }\n\n InputSystem::~InputSystem()\n {\n#if OUZEL_SUPPORTS_X11\n auto engineLinux = static_cast(engine);\n if (emptyCursor != None) XFreeCursor(engineLinux->getDisplay(), emptyCursor);\n#endif\n }\n\n void InputSystem::executeCommand(const Command& command)\n {\n switch (command.type)\n {\n case Command::Type::startDeviceDiscovery:\n discovering = true;\n break;\n case Command::Type::stopDeviceDiscovery:\n discovering = false;\n break;\n case Command::Type::setPlayerIndex:\n {\n break;\n }\n case Command::Type::setVibration:\n {\n break;\n }\n case Command::Type::setPosition:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setPosition(command.position);\n }\n break;\n }\n case Command::Type::initCursor:\n {\n if (command.cursorResource > cursors.size())\n cursors.resize(command.cursorResource);\n\n if (command.data.empty())\n {\n auto cursor = std::make_unique(command.systemCursor);\n cursors[command.cursorResource - 1] = std::move(cursor);\n }\n else\n {\n auto cursor = std::make_unique(command.data, command.size,\n command.pixelFormat, command.hotSpot);\n cursors[command.cursorResource - 1] = std::move(cursor);\n }\n break;\n }\n case Command::Type::destroyCursor:\n {\n#if OUZEL_SUPPORTS_X11\n Cursor* cursor = cursors[command.cursorResource - 1].get();\n\n if (mouseDevice->getCursor() == cursor)\n {\n mouseDevice->setCursor(nullptr);\n updateCursor();\n }\n#endif\n\n cursors[command.cursorResource - 1].reset();\n break;\n }\n case Command::Type::setCursor:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n {\n if (command.cursorResource)\n mouseDevice->setCursor(cursors[command.cursorResource - 1].get());\n else\n mouseDevice->setCursor(nullptr);\n#if OUZEL_SUPPORTS_X11\n updateCursor();\n#endif\n }\n }\n break;\n }\n case Command::Type::setCursorVisible:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setCursorVisible(command.visible);\n }\n break;\n }\n case Command::Type::setCursorLocked:\n {\n if (InputDevice* inputDevice = getInputDevice(command.deviceId))\n {\n if (inputDevice == mouseDevice.get())\n mouseDevice->setCursorLocked(command.locked);\n }\n break;\n }\n default:\n break;\n }\n }\n\n void InputSystem::update()\n {\n fd_set rfds;\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n\n FD_ZERO(&rfds);\n\n int maxFd = 0;\n\n for (const auto& i : eventDevices)\n {\n FD_SET(i.first, &rfds);\n if (i.first > maxFd) maxFd = i.first;\n }\n\n int retval;\n if ((retval = select(maxFd + 1, &rfds, nullptr, nullptr, &tv)) == -1)\n throw std::system_error(errno, std::system_category(), \"Select failed\");\n\n if (retval > 0)\n {\n for (auto i = eventDevices.begin(); i != eventDevices.end();)\n {\n if (FD_ISSET(i->first, &rfds))\n {\n try\n {\n i->second->update();\n ++i;\n }\n catch (const std::exception&)\n {\n i = eventDevices.erase(i);\n }\n }\n else\n ++i;\n }\n }\n\n if (discovering)\n {\n using CloseDirFunction = int(*)(DIR*);\n std::unique_ptr dir(opendir(\"\/dev\/input\"), closedir);\n\n if (!dir)\n throw std::system_error(errno, std::system_category(), \"Failed to open directory\");\n\n while (const dirent* ent = readdir(dir.get()))\n {\n if (std::strncmp(\"event\", ent->d_name, 5) == 0)\n {\n try\n {\n std::string filename = std::string(\"\/dev\/input\/\") + ent->d_name;\n auto eventDevice = std::make_unique(*this, filename);\n eventDevices.insert(std::pair(eventDevice->getFd(), std::move(eventDevice)));\n }\n catch (const std::exception&)\n {\n }\n }\n }\n }\n }\n\n#if OUZEL_SUPPORTS_X11\n void InputSystem::updateCursor() const\n {\n auto engineLinux = static_cast(engine);\n auto windowLinux = static_cast(engine->getWindow()->getNativeWindow());\n auto display = engineLinux->getDisplay();\n auto window = windowLinux->getNativeWindow();\n\n if (mouseDevice->isCursorVisible())\n {\n if (mouseDevice->getCursor())\n XDefineCursor(display, window, mouseDevice->getCursor()->getCursor());\n else\n XUndefineCursor(display, window);\n }\n else\n XDefineCursor(display, window, emptyCursor);\n }\n#endif\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 1999-2004 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANMEMMGRHELPER_HEADER_GUARD_1357924680)\n#define XALANMEMMGRHELPER_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include \n\n\n\n#include \n\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\ntemplate \nType*\ncloneObjWithMemMgr(const Type& other, MemoryManagerType& theManager)\n{\n\n XalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\n Type* theResult = theGuard.get();\n\n new (theResult) Type(other, theManager);\n\n theGuard.release();\n \n return theResult;\n}\n\n\n\ntemplate \nType*\ncloneObj(const Type& other, MemoryManagerType& theManager)\n{\n\n XalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\n Type* theResult = theGuard.get();\n\n new (theResult) Type(other);\n\n theGuard.release();\n \n return theResult;\n}\n\ntemplate \nclass CreateObjFunctor\n{\npublic:\n\tType*\n\toperator()(MemoryManagerType& theManager)\n\t{\n\t\t\n\t\tXalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\t\t\n\t\tType* theResult = theGuard.get();\n\t\t\n\t\tnew (theResult) Type(theManager);\n\t\t\n\t\ttheGuard.release();\n\t\t\n\t\treturn theResult;\n\t}\n};\n\ntemplate \nvoid\ndestroyObjWithMemMgr( Type* ptr, MemoryManagerType& theManager)\n{\n if( ptr == 0 )\n return;\n\n ptr->~Type();\n\n theManager.deallocate((void*)ptr);\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ if !defined(XALANMEMMGRHELPER_HEADER_GUARD_1357924680)\nFix for Jira issue XALANC-504.\/*\n * Copyright 1999-2004 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANMEMMGRHELPER_HEADER_GUARD_1357924680)\n#define XALANMEMMGRHELPER_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include \n\n\n\n#include \n\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\ntemplate \nType*\ncloneObjWithMemMgr(const Type& other, MemoryManagerType& theManager)\n{\n\n XalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\n Type* theResult = theGuard.get();\n\n new (theResult) Type(other, theManager);\n\n theGuard.release();\n \n return theResult;\n}\n\n\n\ntemplate \nType*\ncloneObj(const Type& other, MemoryManagerType& theManager)\n{\n\n XalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\n Type* theResult = theGuard.get();\n\n new (theResult) Type(other);\n\n theGuard.release();\n \n return theResult;\n}\n\ntemplate \nclass CreateObjFunctor\n{\npublic:\n\tType*\n\toperator()(MemoryManagerType& theManager)\n\t{\n\t\t\n\t\tXalanMemMgrAutoPtr theGuard( theManager , (Type*)theManager.allocate(sizeof(Type)));\n\t\t\n\t\tType* theResult = theGuard.get();\n\t\t\n\t\tnew (theResult) Type(theManager);\n\t\t\n\t\ttheGuard.release();\n\t\t\n\t\treturn theResult;\n\t}\n};\n\ntemplate \nvoid\ndestroyObjWithMemMgr(const Type* ptr, MemoryManagerType& theManager)\n{\n if (ptr != 0)\n {\n Type* const nonConstPointer =\n#if defined(XALAN_OLD_STYLE_CASTS)\n (const Type*)ptr;\n#else\n const_cast(ptr);\n#endif\n nonConstPointer->~Type();\n\n theManager.deallocate(nonConstPointer);\n }\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ if !defined(XALANMEMMGRHELPER_HEADER_GUARD_1357924680)\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"Gui\/mvdPixelDescriptionWidget.h\"\n#include \"Gui\/ui_mvdPixelDescriptionWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Core\/mvdAlgorithm.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::PixelDescriptionWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::PixelDescriptionWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::PixelDescriptionWidget() )\n{\n m_UI->setupUi( this );\n\n SetupUI();\n}\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::~PixelDescriptionWidget()\n{\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::SetupUI()\n{\n \/\/\n \/\/ Cartographic coordiantes\n m_CartographicRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n \/\/m_CartographicRootItem->setText(0, tr(\"Cartographic\"));\n m_CartographicRootItem->setExpanded(true);\n\n \/\/ m_CartographicItem = new QTreeWidgetItem( m_CartographicRootItem );\n \/\/ m_CartographicItem->setText(0, tr(\"Coordinates\"));\n\n \/\/\n \/\/ Geographic coordinates\n m_GeographicRootItem = new QTreeWidgetItem( GetDescriptionTree() );\n m_GeographicRootItem->setText(0, tr(\"Geographic\"));\n m_GeographicRootItem->setExpanded(true);\n\n \/\/m_GeographicItem = new QTreeWidgetItem( m_GeographicRootItem ); \n \/\/m_GeographicItem->setText(0, tr(\"Coordinates\"));\n\n \/\/\n \/\/ Child items will be created + updated in a dedicated slot\n m_PixelValueRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n m_PixelValueRootItem->setText(0, tr(\"Pixel Values\"));\n m_PixelValueRootItem->setExpanded(true);\n}\n\n\/*******************************************************************************\/\nQTreeWidget *\nPixelDescriptionWidget\n::GetDescriptionTree()\n{\n return m_UI->m_DescriptionTree;\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPhysicalUpdated(const QStringList & currentPhysical)\n{ \n \/\/m_CartographicItem->setText(1, currentPhysical);\n\n if (!currentPhysical.empty())\n {\n \/\/ remove the previous QTreeWidgetItem of m_GeographicRootItem\n while( m_CartographicRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_CartographicRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \n m_CartographicRootItem->setText(0, QString(\"%1\").arg(currentPhysical[0]));\n \n \/\/ fill with the new values\n QTreeWidgetItem * iCartoXItem = new QTreeWidgetItem( m_CartographicRootItem );\n iCartoXItem->setText(0,QString( tr(\"X\") ));\n iCartoXItem->setText(1, QString(\"%1\").arg(currentPhysical[1] ) );\n\n QTreeWidgetItem * iCartoYItem = new QTreeWidgetItem( m_CartographicRootItem );\n iCartoYItem->setText(0,QString( tr(\"Y\") ));\n iCartoYItem->setText(1, QString(\"%1\").arg(currentPhysical[2] ) );\n }\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentGeographicUpdated(const QStringList&\/*const QString &*\/ currentGeo)\n{\n if (!currentGeo.empty())\n {\n \/\/ remove the previous QTreeWidgetItem of m_GeographicRootItem\n while( m_GeographicRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_GeographicRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \n m_GeographicRootItem->setText(0, QString(\"%1\").arg(currentGeo[0]));\n \/\/ fill with the new values\n QTreeWidgetItem * iGeoLongItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoLongItem->setText(0,QString( tr(\"Long\") ));\n iGeoLongItem->setText(1, QString(\"%1\").arg(currentGeo[1] ) );\n\n QTreeWidgetItem * iGeoLatItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoLatItem->setText(0,QString( tr(\"Lat\") ));\n iGeoLatItem->setText(1, QString(\"%1\").arg(currentGeo[2] ) );\n\n QTreeWidgetItem * iGeoElevationItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoElevationItem->setText(0,QString( tr(\"Elevation\") ));\n if(currentGeo.size() > 3)\n {\n iGeoElevationItem->setText(1, QString(\"%1\").arg(currentGeo[3] ) );\n }\n else\n {\n iGeoElevationItem->setText(1, QString(tr(\"Not available\")));\n }\n }\n} \n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPixelValueUpdated(const VectorImageType::PixelType & currentPixel, \n const QStringList& bandNames)\n{\n \/\/\n \/\/ remove the previous QTreeWidgetItem of m_PixelValueRootItem\n while( m_PixelValueRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_PixelValueRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \/\/ fill with the new values\n for (unsigned int idx = 0; idx < currentPixel.GetSize(); idx++)\n {\n QTreeWidgetItem * iBandItem = new QTreeWidgetItem( m_PixelValueRootItem );\n\n \/\/ figure out if a band name is available, if not use Band idx\n if( !bandNames[ idx ].isEmpty() &&\n\tstatic_cast< unsigned int >( bandNames.size() )==currentPixel.GetSize() )\n {\n iBandItem->setText(0, bandNames[ idx ] );\n }\n else\n {\n iBandItem->setText(0, QString( tr(\"Band\") )+ QString(\" %1\").arg(idx) );\n }\n \/\/ set the value\n iBandItem->setText(1, QString(\"%1\").arg(currentPixel.GetElement( idx )) );\n }\n}\n\n\/*******************************************************************************\/\n\n} \/\/ end namespace 'mvd'\nENH: let pixel description for radiometric value\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"Gui\/mvdPixelDescriptionWidget.h\"\n#include \"Gui\/ui_mvdPixelDescriptionWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Core\/mvdAlgorithm.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::PixelDescriptionWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::PixelDescriptionWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::PixelDescriptionWidget() )\n{\n m_UI->setupUi( this );\n\n SetupUI();\n}\n\n\/*******************************************************************************\/\nPixelDescriptionWidget\n::~PixelDescriptionWidget()\n{\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::SetupUI()\n{\n \/\/\n \/\/ Cartographic coordiantes\n m_CartographicRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n \/\/m_CartographicRootItem->setText(0, tr(\"Cartographic\"));\n m_CartographicRootItem->setExpanded(true);\n\n \/\/ m_CartographicItem = new QTreeWidgetItem( m_CartographicRootItem );\n \/\/ m_CartographicItem->setText(0, tr(\"Coordinates\"));\n\n \/\/\n \/\/ Geographic coordinates\n m_GeographicRootItem = new QTreeWidgetItem( GetDescriptionTree() );\n m_GeographicRootItem->setText(0, tr(\"Geographic\"));\n m_GeographicRootItem->setExpanded(true);\n\n \/\/m_GeographicItem = new QTreeWidgetItem( m_GeographicRootItem ); \n \/\/m_GeographicItem->setText(0, tr(\"Coordinates\"));\n\n \/\/\n \/\/ Child items will be created + updated in a dedicated slot\n m_PixelValueRootItem = new QTreeWidgetItem( GetDescriptionTree() ); \n m_PixelValueRootItem->setText(0, tr(\"Pixel Values\"));\n m_PixelValueRootItem->setExpanded(true);\n}\n\n\/*******************************************************************************\/\nQTreeWidget *\nPixelDescriptionWidget\n::GetDescriptionTree()\n{\n return m_UI->m_DescriptionTree;\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPhysicalUpdated(const QStringList & currentPhysical)\n{ \n \/\/m_CartographicItem->setText(1, currentPhysical);\n\n if (!currentPhysical.empty())\n {\n \/\/ remove the previous QTreeWidgetItem of m_GeographicRootItem\n while( m_CartographicRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_CartographicRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \n m_CartographicRootItem->setText(0, QString(\"%1\").arg(currentPhysical[0]));\n \n \/\/ fill with the new values\n QTreeWidgetItem * iCartoXItem = new QTreeWidgetItem( m_CartographicRootItem );\n iCartoXItem->setText(0,QString( tr(\"X\") ));\n iCartoXItem->setText(1, QString(\"%1\").arg(currentPhysical[1] ) );\n\n QTreeWidgetItem * iCartoYItem = new QTreeWidgetItem( m_CartographicRootItem );\n iCartoYItem->setText(0,QString( tr(\"Y\") ));\n iCartoYItem->setText(1, QString(\"%1\").arg(currentPhysical[2] ) );\n }\n}\n\n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentGeographicUpdated(const QStringList&\/*const QString &*\/ currentGeo)\n{\n if (!currentGeo.empty())\n {\n \/\/ remove the previous QTreeWidgetItem of m_GeographicRootItem\n while( m_GeographicRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_GeographicRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \n m_GeographicRootItem->setText(0, QString(\"%1\").arg(currentGeo[0]));\n \/\/ fill with the new values\n QTreeWidgetItem * iGeoLongItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoLongItem->setText(0,QString( tr(\"Long\") ));\n iGeoLongItem->setText(1, QString(\"%1\").arg(currentGeo[1] ) );\n\n QTreeWidgetItem * iGeoLatItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoLatItem->setText(0,QString( tr(\"Lat\") ));\n iGeoLatItem->setText(1, QString(\"%1\").arg(currentGeo[2] ) );\n\n QTreeWidgetItem * iGeoElevationItem = new QTreeWidgetItem( m_GeographicRootItem );\n iGeoElevationItem->setText(0,QString( tr(\"Elevation\") ));\n if(currentGeo.size() > 3)\n {\n iGeoElevationItem->setText(1, QString(\"%1\").arg(currentGeo[3] ) );\n }\n else\n {\n iGeoElevationItem->setText(1, QString(tr(\"Not available\")));\n }\n }\n} \n\/*******************************************************************************\/\nvoid\nPixelDescriptionWidget\n::OnCurrentPixelValueUpdated(const VectorImageType::PixelType & currentPixel, \n const QStringList& bandNames)\n{\n if (!bandNames.empty() || currentPixel.GetSize() != 0)\n {\n \/\/\n \/\/ remove the previous QTreeWidgetItem of m_PixelValueRootItem\n while( m_PixelValueRootItem->childCount()>0 )\n {\n \/\/ Remove QTreeWidgetItem\n QTreeWidgetItem* child = m_PixelValueRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \/\/ fill with the new values\n for (unsigned int idx = 0; idx < currentPixel.GetSize(); idx++)\n {\n QTreeWidgetItem * iBandItem = new QTreeWidgetItem( m_PixelValueRootItem );\n\n \/\/ figure out if a band name is available, if not use Band idx\n if( !bandNames[ idx ].isEmpty() &&\n static_cast< unsigned int >( bandNames.size() )==currentPixel.GetSize() )\n {\n iBandItem->setText(0, bandNames[ idx ] );\n }\n else\n {\n iBandItem->setText(0, QString( tr(\"Band\") )+ QString(\" %1\").arg(idx) );\n }\n \/\/ set the value\n iBandItem->setText(1, QString(\"%1\").arg(currentPixel.GetElement( idx )) );\n }\n }\n}\n\n\/*******************************************************************************\/\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"} {"text":"\/*\n Hume Library\n Copyright (C) 2015 Marshall Clyburn\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n USA\n*\/\n\n#include \"Graphics.h\"\n\nnamespace hume\n{\n\tGraphics::Graphics() : window(nullptr)\n\t{\n\t}\n\n\tGraphics::~Graphics()\n\t{\n\t\tif(window) delete window;\n\t}\n\n\tvoid Graphics::initialize()\n\t{\n\t\tconst int types = IMG_INIT_JPG | IMG_INIT_PNG;\n\t\tint result = IMG_Init(types);\n\t\tif(result != types) throw SDLException();\n \n\t\tresult = TTF_Init();\n\t\tif(result != 0) throw SDLTTFException();\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::shutdown()\n\t{\n\t\tIMG_Quit();\n\t\tTTF_Quit();\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::set_window(Window* const w)\n\t{\n\t\twindow = w;\n\t\treturn;\n\t}\n\n\tWindow* Graphics::get_window() const\n\t{\n\t\treturn window;\n\t}\n\n\tImage* Graphics::load_image(const std::string& filename)\n\t{\n\t\tImage* image = new Image();\n\t\timage->open(filename, window->get_renderer());\n\n\t\treturn image;\n\t}\n\n\tImage* Graphics::load_image(const std::string& filename, const Uint8 r, const Uint8 g, const Uint8 b)\n\t{\n\t\tImage* image = new Image(r, g, b);\n\t\timage->open(filename, window->get_renderer());\n\n\t\treturn image;\n\t}\n\n\tvoid Graphics::draw(const Blittable* const b, const Properties& p)\n\t{\n\t\twindow->draw(b, p);\n\t\treturn;\n\t}\n\n\tvoid Graphics::draw_rect(const Properties& p, uint8_t r, uint8_t g, uint8_t b, uint8_t a)\n\t{\n\t\tdraw_rect(p.x, p.y, p.w, p.h, r, g, b, a);\n\t\treturn;\n\t}\n\n\tvoid Graphics::draw_rect(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t r, uint8_t g, uint8_t b, uint8_t a)\n\t{\n\t\tSDL_Renderer* const renderer = window->get_renderer();\n\n\t\t\/\/ We'll be restoring the blend mode and colors back to what they were.\n\t\tSDL_BlendMode previous;\n\t\tuint8_t rgba[4];\n\t\tSDL_GetRenderDrawBlendMode(renderer, &previous);\n\t\tSDL_GetRenderDrawColor(renderer, &rgba[0], &rgba[1], &rgba[2], &rgba[3]);\n\t\tSDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);\n\t\tSDL_SetRenderDrawColor(renderer, r, g, b, a);\n\n\t\tSDL_Rect rect;\n\t\trect.x = x;\n\t\trect.y = y;\n\t\trect.w = w;\n\t\trect.h = h;\n\t\tSDL_RenderFillRect(renderer, &rect);\n\n\t\t\/\/ Restore blend mode.\n\t\tSDL_SetRenderDrawBlendMode(renderer, previous);\n\t\tSDL_SetRenderDrawColor(renderer, rgba[0], rgba[1], rgba[2], rgba[3]);\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::clear()\n\t{\n\t\twindow->clear();\n\t\treturn;\n\t}\n\n\tvoid Graphics::refresh()\n\t{\n\t\twindow->present();\n\t\treturn;\n\t}\n}\nCatch SDL errors as exceptions.\/*\n Hume Library\n Copyright (C) 2015 Marshall Clyburn\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n USA\n*\/\n\n#include \"Graphics.h\"\n\nnamespace hume\n{\n\tGraphics::Graphics() : window(nullptr)\n\t{\n\t}\n\n\tGraphics::~Graphics()\n\t{\n\t\tif(window) delete window;\n\t}\n\n\tvoid Graphics::initialize()\n\t{\n\t\tconst int types = IMG_INIT_JPG | IMG_INIT_PNG;\n\t\tint result = IMG_Init(types);\n\t\tif(result != types) throw SDLException();\n \n\t\tresult = TTF_Init();\n\t\tif(result != 0) throw SDLTTFException();\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::shutdown()\n\t{\n\t\tIMG_Quit();\n\t\tTTF_Quit();\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::set_window(Window* const w)\n\t{\n\t\twindow = w;\n\t\treturn;\n\t}\n\n\tWindow* Graphics::get_window() const\n\t{\n\t\treturn window;\n\t}\n\n\tImage* Graphics::load_image(const std::string& filename)\n\t{\n\t\tImage* image = new Image();\n\t\timage->open(filename, window->get_renderer());\n\n\t\treturn image;\n\t}\n\n\tImage* Graphics::load_image(const std::string& filename, const Uint8 r, const Uint8 g, const Uint8 b)\n\t{\n\t\tImage* image = new Image(r, g, b);\n\t\timage->open(filename, window->get_renderer());\n\n\t\treturn image;\n\t}\n\n\tvoid Graphics::draw(const Blittable* const b, const Properties& p)\n\t{\n\t\twindow->draw(b, p);\n\t\treturn;\n\t}\n\n\tvoid Graphics::draw_rect(const Properties& p, uint8_t r, uint8_t g, uint8_t b, uint8_t a)\n\t{\n\t\tdraw_rect(p.x, p.y, p.w, p.h, r, g, b, a);\n\t\treturn;\n\t}\n\n\tvoid Graphics::draw_rect(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint8_t r, uint8_t g, uint8_t b, uint8_t a)\n\t{\n\t\tSDL_Renderer* const renderer = window->get_renderer();\n\n\t\t\/\/ We'll be restoring the blend mode and colors back to what they were.\n\t\tSDL_BlendMode previous;\n\t\tuint8_t rgba[4];\n\t\tif(SDL_GetRenderDrawBlendMode(renderer, &previous) != 0) throw SDLException();\n\t\tif(SDL_GetRenderDrawColor(renderer, &rgba[0], &rgba[1], &rgba[2], &rgba[3]) != 0) throw SDLException();\n\t\tif(SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND) != 0) throw SDLException();\n\t\tif(SDL_SetRenderDrawColor(renderer, r, g, b, a) != 0) throw SDLException();\n\n\t\tSDL_Rect rect;\n\t\trect.x = x;\n\t\trect.y = y;\n\t\trect.w = w;\n\t\trect.h = h;\n\t\tif(SDL_RenderFillRect(renderer, &rect) != 0) throw SDLException();\n\n\t\t\/\/ Restore blend mode.\n\t\tif(SDL_SetRenderDrawBlendMode(renderer, previous) != 0) throw SDLException();\n\t\tif(SDL_SetRenderDrawColor(renderer, rgba[0], rgba[1], rgba[2], rgba[3]) != 0) throw SDLException();\n\n\t\treturn;\n\t}\n\n\tvoid Graphics::clear()\n\t{\n\t\twindow->clear();\n\t\treturn;\n\t}\n\n\tvoid Graphics::refresh()\n\t{\n\t\twindow->present();\n\t\treturn;\n\t}\n}\n<|endoftext|>"} {"text":"#include \"MarkupSTL.h\"\n\/\/#include \"io.h\"\n#include \n#include \n#include \n#include \"util.h\"\n#include \"graph.h\"\n#include \"io.h\"\n#include \"opRelate.h\"\n\nusing namespace std;\n\n#define TEST_DESCR 1\n#define GEOM_A_IN 2\n#define GEOM_A_OUT 4\n#define GEOM_B_IN 8\n#define GEOM_B_OUT 16\n#define TEST_OP 32\n#define TEST_RESULT 64\n#define PRED 128\n\nint main(int argC, char* argV[]) {\n\/\/\tint out=TEST_DESCR+GEOM_A_IN+GEOM_A_OUT+GEOM_B_IN+GEOM_B_OUT+TEST_OP+TEST_RESULT;\n\tint out=TEST_DESCR+GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT;\n\/\/\tint out=GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT+PRED;\n\/\/\tint out=TEST_DESCR+GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT;\n\/\/\tint out=TEST_DESCR+TEST_RESULT;\n\/\/\tint out=0;\n\tint failed=0;\n\tint succeeded=0;\n\tstring source=\"d:\/\/test.xml\";\n\/\/\tstring source=\".\/test.xml\";\n\tstring precisionModel=\"\";\n\tstring desc=\"\";\n\tstring geomAin=\"\";\n\tstring geomBin=\"\";\n\tstring geomAout=\"\";\n\tstring geomBout=\"\";\n\tstring opName=\"\";\n\tstring opSig=\"\";\n\tstring opRes=\"\";\n\tint testCount=0;\n\n\tWKTReader *r = new WKTReader(GeometryFactory(PrecisionModel(),10));\n\tWKTWriter *w=new WKTWriter();\n\tGeometry *gA;\n\tGeometry *gB;\n\n\tCMarkupSTL xml;\n\tbool a=xml.Load(source.c_str());\n\n\txml.ResetPos();\n\txml.FindElem(\"run\");\n\txml.FindChildElem(\"precisionModel\");\n\tprecisionModel=xml.GetChildAttrib(\"type\");\n\tcout << \"Precision Model: \" << precisionModel << endl;\n\twhile (xml.FindChildElem(\"case\")) {\n\t\txml.IntoElem();\n\t\ttestCount++;\n\t\txml.FindChildElem(\"desc\");\n\t\tdesc=xml.GetChildData();\n\t\tif (out & TEST_DESCR) {\n\t\t\tcout << \"Test #\" << testCount << endl;\n\t\t\tcout << \"\\t\" << desc << endl;\n\t\t}\n\t\txml.FindChildElem(\"a\");\n\t\tgeomAin=xml.GetChildData();\n\t\tgA=r->read(geomAin);\n\t\tgeomAout=w->write(gA);\n\t\tif (out &(GEOM_A_IN | GEOM_A_OUT)) {\n\t\t\tcout << \"\\tGeometry A\" << endl;\n\t\t\tif (out & GEOM_A_IN)\n\t\t\t\tcout << \"\\t\\tIn:\" << geomAin << endl;\n\t\t\tif (out & GEOM_A_OUT)\n\t\t\t\tcout << \"\\t\\tOut:\" << geomAout << endl;\n\t\t}\n\n\t\txml.FindChildElem(\"b\");\n\t\tgeomBin=xml.GetChildData();\n\t\tgB=r->read(geomBin);\n\t\tgeomBout=w->write(gB);\n\t\tif (out &(GEOM_B_IN | GEOM_B_OUT)) {\n\t\t\tcout << \"\\tGeometry B\" << endl;\n\t\t\tif (out & GEOM_B_IN)\n\t\t\t\tcout << \"\\t\\tIn:\" << geomBin << endl;\n\t\t\tif (out & GEOM_B_OUT)\n\t\t\t\tcout << \"\\t\\tOut:\" << geomBout << endl;\n\t\t}\n\n\t\txml.FindChildElem(\"test\");\n\t\txml.IntoElem();\n xml.FindChildElem(\"op\");\n\t\topName=xml.GetChildAttrib(\"name\");\n\t\topSig=xml.GetChildAttrib(\"arg3\");\n\t\topRes=xml.GetChildData();\n\t\tif (out & TEST_OP)\n\t\t\tcout << \"\\tOperation '\" << opName << \"[\" << opSig <<\"]' should be \" << opRes << endl;\n\t\tif (opName==\"relate\") {\n\t\t\tIntersectionMatrix im(gA->relate(gB));\n\t\t\tif (out & TEST_RESULT)\n\t\t\t\tcout << \"\\tResult: matrix='\" << im.toString() << \"' result=\" << (im.matches(opSig)?\"true\":\"false\") <equals(gB)?\"T\":\"F\") << \", BA=\" << (gB->equals(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tDisjoint:\\tAB=\" << (gA->disjoint(gB)?\"T\":\"F\") << \", BA=\" << (gB->disjoint(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tIntersects:\\tAB=\" << (gA->intersects(gB)?\"T\":\"F\") << \", BA=\" << (gB->intersects(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tTouches:\\tAB=\" << (gA->touches(gB)?\"T\":\"F\") << \", BA=\" << (gB->touches(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tCrosses:\\tAB=\" << (gA->crosses(gB)?\"T\":\"F\") << \", BA=\" << (gB->crosses(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tWithin:\\t\\tAB=\" << (gA->within(gB)?\"T\":\"F\") << \", BA=\" << (gB->within(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tContains:\\tAB=\" << (gA->contains(gB)?\"T\":\"F\") << \", BA=\" << (gB->contains(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tOverlaps:\\tAB=\" << (gA->overlaps(gB)?\"T\":\"F\") << \", BA=\" << (gB->overlaps(gA)?\"T\":\"F\") << endl;\n\t\t}\n\n\t\txml.OutOfElem();\n\t\txml.OutOfElem();\n\t}\n\tcout << \"Failed: \";\n\tcout << failed << endl;\n\tcout << \"Succeeded: \";\n\tcout << succeeded << endl;\n\tcout << \"End Test\";\n}Make path to test file relative.#include \"MarkupSTL.h\"\n\/\/#include \"io.h\"\n#include \n#include \n#include \n#include \"util.h\"\n#include \"graph.h\"\n#include \"io.h\"\n#include \"opRelate.h\"\n\nusing namespace std;\n\n#define TEST_DESCR 1\n#define GEOM_A_IN 2\n#define GEOM_A_OUT 4\n#define GEOM_B_IN 8\n#define GEOM_B_OUT 16\n#define TEST_OP 32\n#define TEST_RESULT 64\n#define PRED 128\n\nint main(int argC, char* argV[]) {\n\/\/\tint out=TEST_DESCR+GEOM_A_IN+GEOM_A_OUT+GEOM_B_IN+GEOM_B_OUT+TEST_OP+TEST_RESULT;\n\tint out=TEST_DESCR+GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT;\n\/\/\tint out=GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT+PRED;\n\/\/\tint out=TEST_DESCR+GEOM_A_IN+GEOM_B_IN+TEST_OP+TEST_RESULT;\n\/\/\tint out=TEST_DESCR+TEST_RESULT;\n\/\/\tint out=0;\n\tint failed=0;\n\tint succeeded=0;\n\/\/\tstring source=\"d:\/\/test.xml\";\n\tstring source=\".\/test.xml\";\n\tstring precisionModel=\"\";\n\tstring desc=\"\";\n\tstring geomAin=\"\";\n\tstring geomBin=\"\";\n\tstring geomAout=\"\";\n\tstring geomBout=\"\";\n\tstring opName=\"\";\n\tstring opSig=\"\";\n\tstring opRes=\"\";\n\tint testCount=0;\n\n\tWKTReader *r = new WKTReader(GeometryFactory(PrecisionModel(),10));\n\tWKTWriter *w=new WKTWriter();\n\tGeometry *gA;\n\tGeometry *gB;\n\n\tCMarkupSTL xml;\n\tbool a=xml.Load(source.c_str());\n\n\txml.ResetPos();\n\txml.FindElem(\"run\");\n\txml.FindChildElem(\"precisionModel\");\n\tprecisionModel=xml.GetChildAttrib(\"type\");\n\tcout << \"Precision Model: \" << precisionModel << endl;\n\twhile (xml.FindChildElem(\"case\")) {\n\t\txml.IntoElem();\n\t\ttestCount++;\n\t\txml.FindChildElem(\"desc\");\n\t\tdesc=xml.GetChildData();\n\t\tif (out & TEST_DESCR) {\n\t\t\tcout << \"Test #\" << testCount << endl;\n\t\t\tcout << \"\\t\" << desc << endl;\n\t\t}\n\t\txml.FindChildElem(\"a\");\n\t\tgeomAin=xml.GetChildData();\n\t\tgA=r->read(geomAin);\n\t\tgeomAout=w->write(gA);\n\t\tif (out &(GEOM_A_IN | GEOM_A_OUT)) {\n\t\t\tcout << \"\\tGeometry A\" << endl;\n\t\t\tif (out & GEOM_A_IN)\n\t\t\t\tcout << \"\\t\\tIn:\" << geomAin << endl;\n\t\t\tif (out & GEOM_A_OUT)\n\t\t\t\tcout << \"\\t\\tOut:\" << geomAout << endl;\n\t\t}\n\n\t\txml.FindChildElem(\"b\");\n\t\tgeomBin=xml.GetChildData();\n\t\tgB=r->read(geomBin);\n\t\tgeomBout=w->write(gB);\n\t\tif (out &(GEOM_B_IN | GEOM_B_OUT)) {\n\t\t\tcout << \"\\tGeometry B\" << endl;\n\t\t\tif (out & GEOM_B_IN)\n\t\t\t\tcout << \"\\t\\tIn:\" << geomBin << endl;\n\t\t\tif (out & GEOM_B_OUT)\n\t\t\t\tcout << \"\\t\\tOut:\" << geomBout << endl;\n\t\t}\n\n\t\txml.FindChildElem(\"test\");\n\t\txml.IntoElem();\n xml.FindChildElem(\"op\");\n\t\topName=xml.GetChildAttrib(\"name\");\n\t\topSig=xml.GetChildAttrib(\"arg3\");\n\t\topRes=xml.GetChildData();\n\t\tif (out & TEST_OP)\n\t\t\tcout << \"\\tOperation '\" << opName << \"[\" << opSig <<\"]' should be \" << opRes << endl;\n\t\tif (opName==\"relate\") {\n\t\t\tIntersectionMatrix im(gA->relate(gB));\n\t\t\tif (out & TEST_RESULT)\n\t\t\t\tcout << \"\\tResult: matrix='\" << im.toString() << \"' result=\" << (im.matches(opSig)?\"true\":\"false\") <equals(gB)?\"T\":\"F\") << \", BA=\" << (gB->equals(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tDisjoint:\\tAB=\" << (gA->disjoint(gB)?\"T\":\"F\") << \", BA=\" << (gB->disjoint(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tIntersects:\\tAB=\" << (gA->intersects(gB)?\"T\":\"F\") << \", BA=\" << (gB->intersects(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tTouches:\\tAB=\" << (gA->touches(gB)?\"T\":\"F\") << \", BA=\" << (gB->touches(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tCrosses:\\tAB=\" << (gA->crosses(gB)?\"T\":\"F\") << \", BA=\" << (gB->crosses(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tWithin:\\t\\tAB=\" << (gA->within(gB)?\"T\":\"F\") << \", BA=\" << (gB->within(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tContains:\\tAB=\" << (gA->contains(gB)?\"T\":\"F\") << \", BA=\" << (gB->contains(gA)?\"T\":\"F\") << endl;\n\t\t\tcout << \"\\tOverlaps:\\tAB=\" << (gA->overlaps(gB)?\"T\":\"F\") << \", BA=\" << (gB->overlaps(gA)?\"T\":\"F\") << endl;\n\t\t}\n\n\t\txml.OutOfElem();\n\t\txml.OutOfElem();\n\t}\n\tcout << \"Failed: \";\n\tcout << failed << endl;\n\tcout << \"Succeeded: \";\n\tcout << succeeded << endl;\n\tcout << \"End Test\";\n}\n<|endoftext|>"} {"text":"\/*!\n \\file timestamp.cpp\n \\brief Timestamp implementation\n \\author Ivan Shynkarenka\n \\date 26.01.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/timestamp.h\"\n\n#include \"errors\/exceptions.h\"\n\n#if defined(__APPLE__)\n#include \n#include \n#include \n#include \n#include \n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include \n#elif defined(_WIN32) || defined(_WIN64)\n#include \n#endif\n\nnamespace CppCommon {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\n#if defined(__APPLE__)\n\nuint32_t CeilLog2(uint32_t x)\n{\n uint32_t result = 0;\n\n --x;\n while (x > 0)\n {\n ++result;\n x >>= 1;\n }\n\n return result;\n}\n\n\/\/ This function returns the rational number inside the given interval with\n\/\/ the smallest denominator (and smallest numerator breaks ties; correctness\n\/\/ proof neglects floating-point errors).\nmach_timebase_info_data_t BestFrac(double a, double b)\n{\n if (floor(a) < floor(b))\n {\n mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };\n return rv;\n }\n\n double m = floor(a);\n mach_timebase_info_data_t next = BestFrac(1 \/ (b - m), 1 \/ (a - m));\n mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };\n return rv;\n}\n\n\/\/ This is just less than the smallest thing we can multiply numer by without\n\/\/ overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer\nuint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)\n{\n uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;\n return maxDiffWithoutOverflow * numer \/ denom;\n}\n\n\/\/ The clock may run up to 0.1% faster or slower than the \"exact\" tick count.\n\/\/ However, although the bound on the error is the same as for the pragmatic\n\/\/ answer, the error is actually minimized over the given accuracy bound.\nuint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)\n{\n tb.numer = 0;\n tb.denom = 1;\n\n kern_return_t mtiStatus = mach_timebase_info(&tb);\n if (mtiStatus != KERN_SUCCESS)\n return 0;\n\n double frac = (double)tb.numer \/ tb.denom;\n uint64_t spanTarget = 315360000000000000llu;\n if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)\n return 0;\n\n for (double errorTarget = 1 \/ 1024.0; errorTarget > 0.000001;)\n {\n mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);\n if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)\n break;\n tb = newFrac;\n errorTarget = fabs((double)tb.numer \/ tb.denom - frac) \/ frac \/ 8;\n }\n\n return mach_absolute_time();\n}\n\n#endif\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\nuint64_t Timestamp::utc()\n{\n#if defined(__APPLE__)\n clock_serv_t cclock;\n mach_timespec_t mts = { 0 };\n mach_port_t host_port = mach_host_self();\n if (host_port == MACH_PORT_NULL)\n throwex SystemException(\"Cannot get the current host port!\");\n kern_return_t result = host_get_clock_service(host_port, CALENDAR_CLOCK, &cclock);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot get the current host clock service!\");\n result = clock_get_time(cclock, &mts);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot get the current clock time!\");\n mach_port_t task_port = mach_task_self();\n if (task_port == MACH_PORT_NULL)\n throwex SystemException(\"Cannot get the current task port!\");\n result = mach_port_deallocate(task_port, cclock);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot release the current host clock service!\");\n return (mts.tv_sec * 1000 * 1000 * 1000) + mts.tv_nsec;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp;\n if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_REALTIME timer!\");\n return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n ULARGE_INTEGER result;\n result.LowPart = ft.dwLowDateTime;\n result.HighPart = ft.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::local()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n uint64_t timestamp = utc();\n\n \/\/ Adjust UTC time with local timezone offset\n struct tm local;\n time_t seconds = timestamp \/ (1000 * 1000 * 1000);\n if (localtime_r(&seconds, &local) != &local)\n throwex SystemException(\"Cannot convert CLOCK_REALTIME time to local date & time structure!\");\n return timestamp + (local.tm_gmtoff * 1000 * 1000 * 1000);\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n FILETIME ft_local;\n if (!FileTimeToLocalFileTime(&ft, &ft_local))\n throwex SystemException(\"Cannot convert UTC file time to local file time structure!\");\n\n ULARGE_INTEGER result;\n result.LowPart = ft_local.dwLowDateTime;\n result.HighPart = ft_local.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::nano()\n{\n#if defined(__APPLE__)\n static mach_timebase_info_data_t info;\n static uint64_t bias = Internals::PrepareTimebaseInfo(info);\n return (mach_absolute_time() - bias) * info.numer \/ info.denom;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp = { 0 };\n if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_MONOTONIC timer!\");\n return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n static uint64_t offset = 0;\n static LARGE_INTEGER first = { 0 };\n static LARGE_INTEGER frequency = { 0 };\n static bool initialized = false;\n static bool qpc = true;\n\n if (!initialized)\n {\n \/\/ Calculate timestamp offset\n FILETIME timestamp;\n GetSystemTimePreciseAsFileTime(×tamp);\n\n ULARGE_INTEGER result;\n result.LowPart = timestamp.dwLowDateTime;\n result.HighPart = timestamp.dwHighDateTime;\n\n \/\/ Convert 01.01.1601 to 01.01.1970\n result.QuadPart -= 116444736000000000ll;\n offset = result.QuadPart * 100;\n\n \/\/ Setup performance counter\n qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);\n\n initialized = true;\n }\n\n if (qpc)\n {\n LARGE_INTEGER timestamp = { 0 };\n QueryPerformanceCounter(×tamp);\n timestamp.QuadPart -= first.QuadPart;\n return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) \/ frequency.QuadPart);\n }\n else\n return offset;\n#else\n #error Unsupported platform\n#endif\n}\n\nuint64_t Timestamp::rdts()\n{\n#if defined(_MSC_VER)\n return __rdtsc();\n#elif defined(__i386__)\n uint64_t x;\n __asm__ volatile (\".byte 0x0f, 0x31\" : \"=A\" (x));\n return x;\n#elif defined(__x86_64__)\n unsigned hi, lo;\n __asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n return ((uint64_t)lo) | (((uint64_t)hi) << 32);\n#endif\n}\n\n} \/\/ namespace CppCommon\nTest OSX build\/*!\n \\file timestamp.cpp\n \\brief Timestamp implementation\n \\author Ivan Shynkarenka\n \\date 26.01.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/timestamp.h\"\n\n#include \"errors\/exceptions.h\"\n\n#include \n\n#if defined(__APPLE__)\n#include \n#include \n#include \n#include \n#include \n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include \n#elif defined(_WIN32) || defined(_WIN64)\n#include \n#endif\n\nnamespace CppCommon {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\n#if defined(__APPLE__)\n\nuint32_t CeilLog2(uint32_t x)\n{\n uint32_t result = 0;\n\n --x;\n while (x > 0)\n {\n ++result;\n x >>= 1;\n }\n\n return result;\n}\n\n\/\/ This function returns the rational number inside the given interval with\n\/\/ the smallest denominator (and smallest numerator breaks ties; correctness\n\/\/ proof neglects floating-point errors).\nmach_timebase_info_data_t BestFrac(double a, double b)\n{\n if (floor(a) < floor(b))\n {\n mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };\n return rv;\n }\n\n double m = floor(a);\n mach_timebase_info_data_t next = BestFrac(1 \/ (b - m), 1 \/ (a - m));\n mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };\n return rv;\n}\n\n\/\/ This is just less than the smallest thing we can multiply numer by without\n\/\/ overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer\nuint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)\n{\n uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;\n return maxDiffWithoutOverflow * numer \/ denom;\n}\n\n\/\/ The clock may run up to 0.1% faster or slower than the \"exact\" tick count.\n\/\/ However, although the bound on the error is the same as for the pragmatic\n\/\/ answer, the error is actually minimized over the given accuracy bound.\nuint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)\n{\n tb.numer = 0;\n tb.denom = 1;\n\n kern_return_t mtiStatus = mach_timebase_info(&tb);\n if (mtiStatus != KERN_SUCCESS)\n return 0;\n\n double frac = (double)tb.numer \/ tb.denom;\n uint64_t spanTarget = 315360000000000000llu;\n if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)\n return 0;\n\n for (double errorTarget = 1 \/ 1024.0; errorTarget > 0.000001;)\n {\n mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);\n if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)\n break;\n tb = newFrac;\n errorTarget = fabs((double)tb.numer \/ tb.denom - frac) \/ frac \/ 8;\n }\n\n return mach_absolute_time();\n}\n\n#endif\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\nuint64_t Timestamp::utc()\n{\n#if defined(__APPLE__)\n clock_serv_t cclock;\n mach_timespec_t mts = { 0 };\n mach_port_t host_port = mach_host_self();\n if (host_port == MACH_PORT_NULL)\n throwex SystemException(\"Cannot get the current host port!\");\n kern_return_t result = host_get_clock_service(host_port, CALENDAR_CLOCK, &cclock);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot get the current host clock service!\");\n result = clock_get_time(cclock, &mts);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot get the current clock time!\");\n mach_port_t task_port = mach_task_self();\n if (task_port == MACH_PORT_NULL)\n throwex SystemException(\"Cannot get the current task port!\");\n result = mach_port_deallocate(task_port, cclock);\n if (result != KERN_SUCCESS)\n throwex SystemException(\"Cannot release the current host clock service!\");\n std::cerr << \"Sec: \" << mts.tv_sec << \" - Nano: \" << mts.tv_nsec << std::endl;\n return (mts.tv_sec * 1000 * 1000 * 1000) + mts.tv_nsec;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp;\n if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_REALTIME timer!\");\n return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n ULARGE_INTEGER result;\n result.LowPart = ft.dwLowDateTime;\n result.HighPart = ft.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::local()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n uint64_t timestamp = utc();\n\n \/\/ Adjust UTC time with local timezone offset\n struct tm local;\n time_t seconds = timestamp \/ (1000 * 1000 * 1000);\n if (localtime_r(&seconds, &local) != &local)\n throwex SystemException(\"Cannot convert CLOCK_REALTIME time to local date & time structure!\");\n return timestamp + (local.tm_gmtoff * 1000 * 1000 * 1000);\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n FILETIME ft_local;\n if (!FileTimeToLocalFileTime(&ft, &ft_local))\n throwex SystemException(\"Cannot convert UTC file time to local file time structure!\");\n\n ULARGE_INTEGER result;\n result.LowPart = ft_local.dwLowDateTime;\n result.HighPart = ft_local.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::nano()\n{\n#if defined(__APPLE__)\n static mach_timebase_info_data_t info;\n static uint64_t bias = Internals::PrepareTimebaseInfo(info);\n return (mach_absolute_time() - bias) * info.numer \/ info.denom;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp = { 0 };\n if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_MONOTONIC timer!\");\n return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n static uint64_t offset = 0;\n static LARGE_INTEGER first = { 0 };\n static LARGE_INTEGER frequency = { 0 };\n static bool initialized = false;\n static bool qpc = true;\n\n if (!initialized)\n {\n \/\/ Calculate timestamp offset\n FILETIME timestamp;\n GetSystemTimePreciseAsFileTime(×tamp);\n\n ULARGE_INTEGER result;\n result.LowPart = timestamp.dwLowDateTime;\n result.HighPart = timestamp.dwHighDateTime;\n\n \/\/ Convert 01.01.1601 to 01.01.1970\n result.QuadPart -= 116444736000000000ll;\n offset = result.QuadPart * 100;\n\n \/\/ Setup performance counter\n qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);\n\n initialized = true;\n }\n\n if (qpc)\n {\n LARGE_INTEGER timestamp = { 0 };\n QueryPerformanceCounter(×tamp);\n timestamp.QuadPart -= first.QuadPart;\n return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) \/ frequency.QuadPart);\n }\n else\n return offset;\n#else\n #error Unsupported platform\n#endif\n}\n\nuint64_t Timestamp::rdts()\n{\n#if defined(_MSC_VER)\n return __rdtsc();\n#elif defined(__i386__)\n uint64_t x;\n __asm__ volatile (\".byte 0x0f, 0x31\" : \"=A\" (x));\n return x;\n#elif defined(__x86_64__)\n unsigned hi, lo;\n __asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n return ((uint64_t)lo) | (((uint64_t)hi) << 32);\n#endif\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"#define _HAS_EXCEPTIONS 0\n#define _STATIC_CPPLIB\n\n#include \"platform_api.h\"\n\n#ifdef GAME_PROJECT\n#include \"game.cpp\"\n#elif defined(RESOURCE_CONVERTER_PROJECT)\n#include \"resource_converter.cpp\"\n#else\n#error \"You did not specified project type!\"\n#endif\n\n#include \n\nu64 PlatformGetFileSize(char* path)\n{\n HANDLE fileHandle = CreateFile(\n path,\n FILE_READ_ATTRIBUTES,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to open a file!\\n\");\n return 0;\n }\n\n LARGE_INTEGER size;\n BOOL getFileSizeResult = GetFileSizeEx(\n fileHandle,\n &size\n );\n\n if (!getFileSizeResult)\n {\n OutputDebugStringA(\"Was not able to get a file size!\\n\");\n return 0;\n }\n\n CloseHandle(fileHandle);\n return u64(size.QuadPart);\n}\n\nu32 PlatformLoadFile(char* path, void* memory, u32 memorySize)\n{\n HANDLE fileHandle = CreateFile(\n path,\n GENERIC_READ,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to open a file!\\n\");\n return 0;\n }\n\n DWORD bytesRead;\n BOOL readResult = ReadFile(\n fileHandle,\n memory,\n memorySize,\n &bytesRead,\n nullptr\n );\n\n if (!readResult)\n {\n OutputDebugStringA(\"Was not able to read from a file!\\n\");\n return 0;\n }\n\n CloseHandle(fileHandle);\n return bytesRead;\n}\n\nbool PlatformWriteFile(char* path, void* memory, u32 bytesToWrite)\n{\n \/\/ TODO: handle directory creation\n\n HANDLE fileHandle = CreateFile(\n path,\n GENERIC_WRITE,\n 0,\n nullptr,\n CREATE_ALWAYS,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to create or owerwrite a file!\\n\");\n return false;\n }\n\n DWORD bytesWritten;\n BOOL writeResult = WriteFile(\n fileHandle,\n memory,\n bytesToWrite,\n &bytesWritten,\n nullptr\n );\n\n if (!writeResult)\n {\n OutputDebugStringA(\"Was not able to write to a file!\\n\");\n CloseHandle(fileHandle);\n return false;\n }\n\n if (bytesToWrite != bytesWritten)\n {\n OutputDebugStringA(\"Bytes to write was not equal to bytes written!\\n\");\n CloseHandle(fileHandle);\n return false;\n }\n\n CloseHandle(fileHandle);\n return true;\n}\n\nstruct Win32BackBuffer\n{\n BITMAPINFO info;\n u32* memory;\n};\n\nstruct\n{\n bool shouldRun;\n u32 windowWidth;\n u32 windowHeight;\n\n void* memory;\n u32 memorySize;\n RenderTarget renderBuffer;\n Win32BackBuffer backBuffer;\n\n} g_platformData\n{\n true,\n 640,\n 480,\n nullptr,\n 0,\n {},\n {}\n};\n\nvoid Win32SetupRenderingBuffers(u32 width, u32 height)\n{\n u8* platformMemory = (u8*)g_platformData.memory;\n\n BITMAPINFO info {};\n info.bmiHeader.biSize = sizeof(info.bmiHeader);\n info.bmiHeader.biWidth = width;\n info.bmiHeader.biHeight = height;\n info.bmiHeader.biPlanes = 1;\n info.bmiHeader.biBitCount = 32;\n info.bmiHeader.biCompression = BI_RGB;\n\n g_platformData.backBuffer.info = info;\n g_platformData.backBuffer.memory = (u32*)platformMemory;\n platformMemory += width * height * sizeof(u32);\n\n Texture** texture = &g_platformData.renderBuffer.texture;\n *texture = (Texture*)platformMemory;\n (*texture)->width = width;\n (*texture)->height = height;\n platformMemory += width * height * sizeof(Color32) + sizeof(Texture);\n\n g_platformData.renderBuffer.zBuffer = (float*)platformMemory;\n platformMemory += width * height * sizeof(float);\n\n assert(u32(platformMemory - (u8*)g_platformData.memory) <= g_platformData.memorySize);\n}\n\nvoid Win32PresentToWindow(\n HDC windowDC,\n u32 windowWidth,\n u32 windowHeight,\n Win32BackBuffer* backBuffer,\n RenderTarget* renderBuffer)\n{\n u32 bufferWidth = renderBuffer->texture->width;\n u32 bufferHeight = renderBuffer->texture->height;\n\n \/\/ TODO: think about just allocating back-buffer here, on the stack\n for (u32 y = 0; y < bufferHeight; ++y)\n {\n for (u32 x = 0; x < bufferWidth; ++x)\n {\n Color32 bufferColor = renderBuffer->texture->GetTexel(x, y);\n\n backBuffer->memory[y * bufferWidth + x] = \n u32(bufferColor.b) |\n u32(bufferColor.g) << 8 |\n u32(bufferColor.r) << 16;\n }\n }\n\n StretchDIBits(\n windowDC,\n 0,\n 0,\n windowWidth,\n windowHeight,\n 0,\n 0,\n backBuffer->info.bmiHeader.biWidth,\n backBuffer->info.bmiHeader.biHeight,\n backBuffer->memory,\n &backBuffer->info,\n DIB_RGB_COLORS,\n SRCCOPY);\n}\n\nLRESULT CALLBACK Win32WindowProc(\n HWND window,\n UINT message,\n WPARAM wParam,\n LPARAM lParam)\n{\n switch (message)\n {\n case WM_SIZE:\n {\n g_platformData.windowWidth = LOWORD(lParam);\n g_platformData.windowHeight = HIWORD(lParam);\n } break;\n case WM_EXITSIZEMOVE:\n {\n \/\/ this is basically free with manual memory management\n Win32SetupRenderingBuffers(g_platformData.windowWidth, g_platformData.windowHeight);\n } break;\n case WM_PAINT:\n {\n PAINTSTRUCT ps;\n HDC windowDC = BeginPaint(window, &ps);\n\n Win32PresentToWindow(\n windowDC,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n &g_platformData.backBuffer,\n &g_platformData.renderBuffer);\n\n EndPaint(window, &ps);\n } break;\n case WM_CLOSE:\n case WM_DESTROY:\n {\n g_platformData.shouldRun = false;\n } break;\n default:\n {\n return DefWindowProc(window, message, wParam, lParam);\n } break;\n }\n\n return 0;\n}\n\n\nglobal const u32 g_keyMapSize = 0xA5 + 1;\nglobal u32 g_keyMap[g_keyMapSize] {};\n\nint CALLBACK WinMain(\n HINSTANCE instance,\n HINSTANCE \/* prevInstance *\/,\n char* \/* cmdLine *\/,\n int \/* cmdShow *\/)\n{\n \/\/ damn vs2013 can't do array initialization proper\n {\n g_keyMap[VK_BACK] = KbKey::Backspace;\n g_keyMap[VK_TAB] = KbKey::Tab;\n g_keyMap[VK_RETURN] = KbKey::Return;\n g_keyMap[VK_ESCAPE] = KbKey::Escape;\n g_keyMap[VK_SPACE] = KbKey::Space;\n g_keyMap[VK_END] = KbKey::End;\n g_keyMap[VK_HOME] = KbKey::Home;\n g_keyMap[VK_LEFT] = KbKey::Left;\n g_keyMap[VK_UP] = KbKey::Up;\n g_keyMap[VK_RIGHT] = KbKey::Right;\n g_keyMap[VK_DOWN] = KbKey::Down;\n g_keyMap[VK_DELETE] = KbKey::Delete;\n g_keyMap[0x30] = KbKey::N_0;\n g_keyMap[0x31] = KbKey::N_1;\n g_keyMap[0x32] = KbKey::N_2;\n g_keyMap[0x33] = KbKey::N_3;\n g_keyMap[0x34] = KbKey::N_4;\n g_keyMap[0x35] = KbKey::N_5;\n g_keyMap[0x36] = KbKey::N_6;\n g_keyMap[0x37] = KbKey::N_7;\n g_keyMap[0x38] = KbKey::N_8;\n g_keyMap[0x39] = KbKey::N_9;\n g_keyMap[0x41] = KbKey::A;\n g_keyMap[0x42] = KbKey::B;\n g_keyMap[0x43] = KbKey::C;\n g_keyMap[0x44] = KbKey::D;\n g_keyMap[0x45] = KbKey::E;\n g_keyMap[0x46] = KbKey::F;\n g_keyMap[0x47] = KbKey::G;\n g_keyMap[0x48] = KbKey::H;\n g_keyMap[0x49] = KbKey::I;\n g_keyMap[0x4A] = KbKey::J;\n g_keyMap[0x4B] = KbKey::K;\n g_keyMap[0x4C] = KbKey::L;\n g_keyMap[0x4D] = KbKey::M;\n g_keyMap[0x4E] = KbKey::N;\n g_keyMap[0x4F] = KbKey::O;\n g_keyMap[0x50] = KbKey::P;\n g_keyMap[0x51] = KbKey::Q;\n g_keyMap[0x52] = KbKey::R;\n g_keyMap[0x53] = KbKey::S;\n g_keyMap[0x54] = KbKey::T;\n g_keyMap[0x55] = KbKey::U;\n g_keyMap[0x56] = KbKey::V;\n g_keyMap[0x57] = KbKey::W;\n g_keyMap[0x58] = KbKey::X;\n g_keyMap[0x59] = KbKey::Y;\n g_keyMap[0x5A] = KbKey::Z;\n g_keyMap[VK_F1] = KbKey::F1;\n g_keyMap[VK_F2] = KbKey::F2;\n g_keyMap[VK_F3] = KbKey::F3;\n g_keyMap[VK_F4] = KbKey::F4;\n g_keyMap[VK_F5] = KbKey::F5;\n g_keyMap[VK_F6] = KbKey::F6;\n g_keyMap[VK_F7] = KbKey::F7;\n g_keyMap[VK_F8] = KbKey::F8;\n g_keyMap[VK_F9] = KbKey::F9;\n g_keyMap[VK_F10] = KbKey::F10;\n g_keyMap[VK_F11] = KbKey::F11;\n g_keyMap[VK_F12] = KbKey::F12;\n g_keyMap[VK_LSHIFT] = KbKey::ShiftL;\n g_keyMap[VK_RSHIFT] = KbKey::ShiftR;\n g_keyMap[VK_LCONTROL] = KbKey::ControlL;\n g_keyMap[VK_RCONTROL] = KbKey::ControlR;\n g_keyMap[VK_LMENU] = KbKey::AltL;\n g_keyMap[VK_RMENU] = KbKey::AltR; \/\/ 0xA5 Right MENU key\n }\n\n \/\/*****CREATING A WINDOW*****\/\/\n WNDCLASSEX wndClass {};\n wndClass.cbSize = sizeof(wndClass);\n wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n wndClass.lpfnWndProc = Win32WindowProc;\n wndClass.hInstance = instance;\n wndClass.lpszClassName = \"Software Renderer Window Class Name\";\n\n RegisterClassEx(&wndClass);\n\n HWND window = CreateWindowEx(\n 0,\n wndClass.lpszClassName,\n \"Software Renderer\",\n WS_OVERLAPPEDWINDOW | WS_VISIBLE,\n CW_USEDEFAULT,\n CW_USEDEFAULT,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n 0,\n 0,\n instance,\n nullptr\n );\n\n \/\/*****ALLOCATING MEMORY*****\/\/\n g_platformData.memorySize = 128 * Mb;\n g_platformData.memory = VirtualAlloc(\n nullptr,\n g_platformData.memorySize,\n MEM_RESERVE | MEM_COMMIT,\n PAGE_READWRITE\n );\n assert(g_platformData.memory);\n\n u32 gameMemorySize = 512 * Mb;\n void* gameMemory = VirtualAlloc(\n nullptr,\n gameMemorySize,\n MEM_RESERVE | MEM_COMMIT,\n PAGE_READWRITE\n );\n assert(gameMemory);\n\n \/\/*****MISC SETUP*****\/\/\n Win32SetupRenderingBuffers(g_platformData.windowWidth, g_platformData.windowHeight);\n\n HDC windowDC = GetDC(window);\n MSG message {};\n bool kbState[KbKey::LastKey] {};\n\n LARGE_INTEGER lastFrameTime;\n LARGE_INTEGER queryFrequency;\n QueryPerformanceCounter(&lastFrameTime);\n QueryPerformanceFrequency(&queryFrequency);\n\n GameInitialize(gameMemory, gameMemorySize);\n\n \/\/*****RENDERING LOOP*****\/\/\n while (g_platformData.shouldRun)\n {\n LARGE_INTEGER currentFrameTime;\n QueryPerformanceCounter(¤tFrameTime);\n u64 ticksElapsed = currentFrameTime.QuadPart - lastFrameTime.QuadPart;\n float deltaTime = float(ticksElapsed) \/ float(queryFrequency.QuadPart);\n lastFrameTime = currentFrameTime;\n\n \/\/ TODO: sort this out\n char windowTitle[256];\n wsprintf(windowTitle, \"Software Renderer \\t %ums per frame\", u32(deltaTime * 1000.0f));\n SetWindowText(window, windowTitle);\n\n while (PeekMessage(&message, window, 0, 0, PM_REMOVE))\n {\n TranslateMessage(&message);\n\n if (message.message == WM_KEYDOWN || message.message == WM_KEYUP)\n {\n u32 keyMapIdx = message.wParam;\n if (keyMapIdx < g_keyMapSize)\n {\n u32 kbStateIdx = g_keyMap[keyMapIdx];\n assert(kbStateIdx < KbKey::LastKey);\n\n kbState[kbStateIdx] = message.message == WM_KEYDOWN;\n }\n }\n\n DispatchMessage(&message);\n }\n\n bool gameWantsToContinue = GameUpdate(\n deltaTime,\n gameMemory,\n gameMemorySize,\n &g_platformData.renderBuffer,\n kbState);\n\n g_platformData.shouldRun &= gameWantsToContinue;\n\n Win32PresentToWindow(\n windowDC,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n &g_platformData.backBuffer,\n &g_platformData.renderBuffer);\n }\n \n return 0;\n}\ncompiling under msvc 2013#define _HAS_EXCEPTIONS 0\n#define _STATIC_CPPLIB\n\n#include \"platform_api.h\"\n\n#ifdef GAME_PROJECT\n#include \"game.cpp\"\n#elif defined(RESOURCE_CONVERTER_PROJECT)\n#include \"resource_converter.cpp\"\n#else\n#error \"You did not specified project type!\"\n#endif\n\n#include \n\nu64 PlatformGetFileSize(const char* path)\n{\n HANDLE fileHandle = CreateFile(\n path,\n FILE_READ_ATTRIBUTES,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to open a file!\\n\");\n return 0;\n }\n\n LARGE_INTEGER size;\n BOOL getFileSizeResult = GetFileSizeEx(\n fileHandle,\n &size\n );\n\n if (!getFileSizeResult)\n {\n OutputDebugStringA(\"Was not able to get a file size!\\n\");\n return 0;\n }\n\n CloseHandle(fileHandle);\n return u64(size.QuadPart);\n}\n\nu32 PlatformLoadFile(const char* path, void* memory, u32 memorySize)\n{\n HANDLE fileHandle = CreateFile(\n path,\n GENERIC_READ,\n FILE_SHARE_READ,\n nullptr,\n OPEN_EXISTING,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to open a file!\\n\");\n return 0;\n }\n\n DWORD bytesRead;\n BOOL readResult = ReadFile(\n fileHandle,\n memory,\n memorySize,\n &bytesRead,\n nullptr\n );\n\n if (!readResult)\n {\n OutputDebugStringA(\"Was not able to read from a file!\\n\");\n return 0;\n }\n\n CloseHandle(fileHandle);\n return bytesRead;\n}\n\nbool PlatformWriteFile(const char* path, void* memory, u32 bytesToWrite)\n{\n \/\/ TODO: handle directory creation\n\n HANDLE fileHandle = CreateFile(\n path,\n GENERIC_WRITE,\n 0,\n nullptr,\n CREATE_ALWAYS,\n FILE_ATTRIBUTE_NORMAL,\n 0\n );\n\n if (fileHandle == INVALID_HANDLE_VALUE)\n {\n OutputDebugStringA(\"Was not able to create or owerwrite a file!\\n\");\n return false;\n }\n\n DWORD bytesWritten;\n BOOL writeResult = WriteFile(\n fileHandle,\n memory,\n bytesToWrite,\n &bytesWritten,\n nullptr\n );\n\n if (!writeResult)\n {\n OutputDebugStringA(\"Was not able to write to a file!\\n\");\n CloseHandle(fileHandle);\n return false;\n }\n\n if (bytesToWrite != bytesWritten)\n {\n OutputDebugStringA(\"Bytes to write was not equal to bytes written!\\n\");\n CloseHandle(fileHandle);\n return false;\n }\n\n CloseHandle(fileHandle);\n return true;\n}\n\nstruct Win32BackBuffer\n{\n BITMAPINFO info;\n u32* memory;\n};\n\nstruct\n{\n bool shouldRun;\n u32 windowWidth;\n u32 windowHeight;\n\n void* memory;\n u32 memorySize;\n RenderTarget renderBuffer;\n Win32BackBuffer backBuffer;\n\n} g_platformData\n{\n true,\n 640,\n 480,\n nullptr,\n 0,\n {},\n {}\n};\n\nvoid Win32SetupRenderingBuffers(u32 width, u32 height)\n{\n u8* platformMemory = (u8*)g_platformData.memory;\n\n BITMAPINFO info {};\n info.bmiHeader.biSize = sizeof(info.bmiHeader);\n info.bmiHeader.biWidth = width;\n info.bmiHeader.biHeight = height;\n info.bmiHeader.biPlanes = 1;\n info.bmiHeader.biBitCount = 32;\n info.bmiHeader.biCompression = BI_RGB;\n\n g_platformData.backBuffer.info = info;\n g_platformData.backBuffer.memory = (u32*)platformMemory;\n platformMemory += width * height * sizeof(u32);\n\n Texture** texture = &g_platformData.renderBuffer.texture;\n *texture = (Texture*)platformMemory;\n (*texture)->width = width;\n (*texture)->height = height;\n platformMemory += width * height * sizeof(Color32) + sizeof(Texture);\n\n g_platformData.renderBuffer.zBuffer = (float*)platformMemory;\n platformMemory += width * height * sizeof(float);\n\n assert(u32(platformMemory - (u8*)g_platformData.memory) <= g_platformData.memorySize);\n}\n\nvoid Win32PresentToWindow(\n HDC windowDC,\n u32 windowWidth,\n u32 windowHeight,\n Win32BackBuffer* backBuffer,\n RenderTarget* renderBuffer)\n{\n u32 bufferWidth = renderBuffer->texture->width;\n u32 bufferHeight = renderBuffer->texture->height;\n\n \/\/ TODO: think about just allocating back-buffer here, on the stack\n for (u32 y = 0; y < bufferHeight; ++y)\n {\n for (u32 x = 0; x < bufferWidth; ++x)\n {\n Color32 bufferColor = renderBuffer->texture->GetTexel(x, y);\n\n backBuffer->memory[y * bufferWidth + x] = \n u32(bufferColor.b) |\n u32(bufferColor.g) << 8 |\n u32(bufferColor.r) << 16;\n }\n }\n\n StretchDIBits(\n windowDC,\n 0,\n 0,\n windowWidth,\n windowHeight,\n 0,\n 0,\n backBuffer->info.bmiHeader.biWidth,\n backBuffer->info.bmiHeader.biHeight,\n backBuffer->memory,\n &backBuffer->info,\n DIB_RGB_COLORS,\n SRCCOPY);\n}\n\nLRESULT CALLBACK Win32WindowProc(\n HWND window,\n UINT message,\n WPARAM wParam,\n LPARAM lParam)\n{\n switch (message)\n {\n case WM_SIZE:\n {\n g_platformData.windowWidth = LOWORD(lParam);\n g_platformData.windowHeight = HIWORD(lParam);\n } break;\n case WM_EXITSIZEMOVE:\n {\n \/\/ this is basically free with manual memory management\n Win32SetupRenderingBuffers(g_platformData.windowWidth, g_platformData.windowHeight);\n } break;\n case WM_PAINT:\n {\n PAINTSTRUCT ps;\n HDC windowDC = BeginPaint(window, &ps);\n\n Win32PresentToWindow(\n windowDC,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n &g_platformData.backBuffer,\n &g_platformData.renderBuffer);\n\n EndPaint(window, &ps);\n } break;\n case WM_CLOSE:\n case WM_DESTROY:\n {\n g_platformData.shouldRun = false;\n } break;\n default:\n {\n return DefWindowProc(window, message, wParam, lParam);\n } break;\n }\n\n return 0;\n}\n\n\nglobal const u32 g_keyMapSize = 0xA5 + 1;\nglobal u32 g_keyMap[g_keyMapSize] {};\n\nint CALLBACK WinMain(\n HINSTANCE instance,\n HINSTANCE \/* prevInstance *\/,\n char* \/* cmdLine *\/,\n int \/* cmdShow *\/)\n{\n \/\/ damn vs2013 can't do array initialization proper\n {\n g_keyMap[VK_BACK] = KbKey::Backspace;\n g_keyMap[VK_TAB] = KbKey::Tab;\n g_keyMap[VK_RETURN] = KbKey::Return;\n g_keyMap[VK_ESCAPE] = KbKey::Escape;\n g_keyMap[VK_SPACE] = KbKey::Space;\n g_keyMap[VK_END] = KbKey::End;\n g_keyMap[VK_HOME] = KbKey::Home;\n g_keyMap[VK_LEFT] = KbKey::Left;\n g_keyMap[VK_UP] = KbKey::Up;\n g_keyMap[VK_RIGHT] = KbKey::Right;\n g_keyMap[VK_DOWN] = KbKey::Down;\n g_keyMap[VK_DELETE] = KbKey::Delete;\n g_keyMap[0x30] = KbKey::N_0;\n g_keyMap[0x31] = KbKey::N_1;\n g_keyMap[0x32] = KbKey::N_2;\n g_keyMap[0x33] = KbKey::N_3;\n g_keyMap[0x34] = KbKey::N_4;\n g_keyMap[0x35] = KbKey::N_5;\n g_keyMap[0x36] = KbKey::N_6;\n g_keyMap[0x37] = KbKey::N_7;\n g_keyMap[0x38] = KbKey::N_8;\n g_keyMap[0x39] = KbKey::N_9;\n g_keyMap[0x41] = KbKey::A;\n g_keyMap[0x42] = KbKey::B;\n g_keyMap[0x43] = KbKey::C;\n g_keyMap[0x44] = KbKey::D;\n g_keyMap[0x45] = KbKey::E;\n g_keyMap[0x46] = KbKey::F;\n g_keyMap[0x47] = KbKey::G;\n g_keyMap[0x48] = KbKey::H;\n g_keyMap[0x49] = KbKey::I;\n g_keyMap[0x4A] = KbKey::J;\n g_keyMap[0x4B] = KbKey::K;\n g_keyMap[0x4C] = KbKey::L;\n g_keyMap[0x4D] = KbKey::M;\n g_keyMap[0x4E] = KbKey::N;\n g_keyMap[0x4F] = KbKey::O;\n g_keyMap[0x50] = KbKey::P;\n g_keyMap[0x51] = KbKey::Q;\n g_keyMap[0x52] = KbKey::R;\n g_keyMap[0x53] = KbKey::S;\n g_keyMap[0x54] = KbKey::T;\n g_keyMap[0x55] = KbKey::U;\n g_keyMap[0x56] = KbKey::V;\n g_keyMap[0x57] = KbKey::W;\n g_keyMap[0x58] = KbKey::X;\n g_keyMap[0x59] = KbKey::Y;\n g_keyMap[0x5A] = KbKey::Z;\n g_keyMap[VK_F1] = KbKey::F1;\n g_keyMap[VK_F2] = KbKey::F2;\n g_keyMap[VK_F3] = KbKey::F3;\n g_keyMap[VK_F4] = KbKey::F4;\n g_keyMap[VK_F5] = KbKey::F5;\n g_keyMap[VK_F6] = KbKey::F6;\n g_keyMap[VK_F7] = KbKey::F7;\n g_keyMap[VK_F8] = KbKey::F8;\n g_keyMap[VK_F9] = KbKey::F9;\n g_keyMap[VK_F10] = KbKey::F10;\n g_keyMap[VK_F11] = KbKey::F11;\n g_keyMap[VK_F12] = KbKey::F12;\n g_keyMap[VK_LSHIFT] = KbKey::ShiftL;\n g_keyMap[VK_RSHIFT] = KbKey::ShiftR;\n g_keyMap[VK_LCONTROL] = KbKey::ControlL;\n g_keyMap[VK_RCONTROL] = KbKey::ControlR;\n g_keyMap[VK_LMENU] = KbKey::AltL;\n g_keyMap[VK_RMENU] = KbKey::AltR; \/\/ 0xA5 Right MENU key\n }\n\n \/\/*****CREATING A WINDOW*****\/\/\n WNDCLASSEX wndClass {};\n wndClass.cbSize = sizeof(wndClass);\n wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n wndClass.lpfnWndProc = Win32WindowProc;\n wndClass.hInstance = instance;\n wndClass.lpszClassName = \"Software Renderer Window Class Name\";\n\n RegisterClassEx(&wndClass);\n\n HWND window = CreateWindowEx(\n 0,\n wndClass.lpszClassName,\n \"Software Renderer\",\n WS_OVERLAPPEDWINDOW | WS_VISIBLE,\n CW_USEDEFAULT,\n CW_USEDEFAULT,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n 0,\n 0,\n instance,\n nullptr\n );\n\n \/\/*****ALLOCATING MEMORY*****\/\/\n g_platformData.memorySize = 128 * Mb;\n g_platformData.memory = VirtualAlloc(\n nullptr,\n g_platformData.memorySize,\n MEM_RESERVE | MEM_COMMIT,\n PAGE_READWRITE\n );\n assert(g_platformData.memory);\n\n u32 gameMemorySize = 512 * Mb;\n void* gameMemory = VirtualAlloc(\n nullptr,\n gameMemorySize,\n MEM_RESERVE | MEM_COMMIT,\n PAGE_READWRITE\n );\n assert(gameMemory);\n\n \/\/*****MISC SETUP*****\/\/\n Win32SetupRenderingBuffers(g_platformData.windowWidth, g_platformData.windowHeight);\n\n HDC windowDC = GetDC(window);\n MSG message {};\n bool kbState[KbKey::LastKey] {};\n\n LARGE_INTEGER lastFrameTime;\n LARGE_INTEGER queryFrequency;\n QueryPerformanceCounter(&lastFrameTime);\n QueryPerformanceFrequency(&queryFrequency);\n\n GameInitialize(gameMemory, gameMemorySize);\n\n \/\/*****RENDERING LOOP*****\/\/\n while (g_platformData.shouldRun)\n {\n LARGE_INTEGER currentFrameTime;\n QueryPerformanceCounter(¤tFrameTime);\n u64 ticksElapsed = currentFrameTime.QuadPart - lastFrameTime.QuadPart;\n float deltaTime = float(ticksElapsed) \/ float(queryFrequency.QuadPart);\n lastFrameTime = currentFrameTime;\n\n \/\/ TODO: sort this out\n char windowTitle[256];\n wsprintf(windowTitle, \"Software Renderer \\t %ums per frame\", u32(deltaTime * 1000.0f));\n SetWindowText(window, windowTitle);\n\n while (PeekMessage(&message, window, 0, 0, PM_REMOVE))\n {\n TranslateMessage(&message);\n\n if (message.message == WM_KEYDOWN || message.message == WM_KEYUP)\n {\n u32 keyMapIdx = message.wParam;\n if (keyMapIdx < g_keyMapSize)\n {\n u32 kbStateIdx = g_keyMap[keyMapIdx];\n assert(kbStateIdx < KbKey::LastKey);\n\n kbState[kbStateIdx] = message.message == WM_KEYDOWN;\n }\n }\n\n DispatchMessage(&message);\n }\n\n bool gameWantsToContinue = GameUpdate(\n deltaTime,\n gameMemory,\n gameMemorySize,\n &g_platformData.renderBuffer,\n kbState);\n\n g_platformData.shouldRun &= gameWantsToContinue;\n\n Win32PresentToWindow(\n windowDC,\n g_platformData.windowWidth,\n g_platformData.windowHeight,\n &g_platformData.backBuffer,\n &g_platformData.renderBuffer);\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP\n#define STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/** Apply an error check to a container, signal failure with `false`.\n * Apply a predicate like is_positive to the double underlying every scalar in a\n * container, producing true if the predicate holds everywhere and `false` if it\n * fails anywhere.\n * @tparam F type of predicate\n *\/\ntemplate \nclass Iser {\n const F& is_good;\n\n public:\n \/**\n * @param is_good predicate to check, must accept doubles and produce bools\n *\/\n explicit Iser(const F& is_good) : is_good(is_good) {}\n\n \/**\n * Check the scalar.\n * @tparam T type of scalar\n * @param x scalar\n * @return `false` if the scalar fails the error check\n *\/\n template >\n bool is(const T& x) {\n return is_good(value_of_rec(x));\n }\n\n \/**\n * Check all the scalars inside the container.\n * @tparam T type of scalar\n * @param x container\n * @return `false` if any of the scalars fail the error check\n *\/\n template ,\n typename = void>\n bool is(const T& x) {\n for (size_t i = 0; i < stan::math::size(x); ++i)\n if (!is(stan::get(x, i)))\n return false;\n return true;\n }\n};\n\n\/**\n * No-op.\n *\/\ninline void pipe_in(std::stringstream& ss) {}\n\/**\n * Pipes given arguments into a stringstream.\n *\n * @tparam Arg0 type of the first argument\n * @tparam Args types of remaining arguments\n * @param ss stringstream to pipe arguments in\n * @param arg0 the first argument\n * @param args remining arguments\n *\/\ntemplate \ninline void pipe_in(std::stringstream& ss, Arg0 arg0, const Args... args) {\n ss << arg0;\n pipe_in(ss, args...);\n}\n\n\/**\n * Throws domain error with concatenation of arguments for the error message.\n * @tparam Args types of arguments\n * @param args arguments\n *\/\ntemplate \nvoid elementwise_throw_domain_error(const Args... args) {\n std::stringstream ss;\n pipe_in(ss, args...);\n throw std::domain_error(ss.str());\n}\n\n} \/\/ namespace internal\n\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on scalars.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n if (unlikely(!is_good(value_of_rec(x)))) {\n internal::elementwise_throw_domain_error(function, \": \", name, indexings...,\n \" is \", x, \", but must be \",\n must_be, \"!\");\n }\n}\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on Eigen types that support linear indexing.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr,\n std::enable_if_t(Eigen::internal::traits::Flags&(\n Eigen::LinearAccessBit | Eigen::DirectAccessBit))>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t i = 0; i < x.size(); i++) {\n auto scal = value_of_rec(x.coeff(i));\n if (unlikely(!is_good(scal))) {\n if (is_eigen_vector::value) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \"] is \", scal, \", but must be \", must_be, \"!\");\n } else if (Eigen::internal::traits::Flags & Eigen::RowMajorBit) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\",\n i \/ x.cols() + error_index::value, \", \",\n i % x.cols() + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n } else {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\",\n i % x.rows() + error_index::value, \", \",\n i \/ x.rows() + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on col-major Eigen types that do not support linear indexing.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate <\n typename F, typename T, typename... Indexings,\n require_eigen_t* = nullptr,\n std::enable_if_t::Flags\n & (Eigen::LinearAccessBit | Eigen::DirectAccessBit))\n && !(Eigen::internal::traits::Flags\n & Eigen::RowMajorBit)>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t i = 0; i < x.rows(); i++) {\n for (size_t j = 0; j < x.cols(); j++) {\n auto scal = value_of_rec(x.coeff(i, j));\n if (unlikely(!is_good(scal))) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \", \", j + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on row-major Eigen types that do not support linear indexing.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate <\n typename F, typename T, typename... Indexings,\n require_eigen_t* = nullptr,\n std::enable_if_t::Flags\n & (Eigen::LinearAccessBit | Eigen::DirectAccessBit))\n && static_cast(Eigen::internal::traits::Flags\n & Eigen::RowMajorBit)>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t j = 0; j < x.cols(); j++) {\n for (size_t i = 0; i < x.rows(); i++) {\n auto scal = value_of_rec(x.coeff(i, j));\n if (unlikely(!is_good(scal))) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \", \", j + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on `std::vector`s.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t j = 0; j < x.size(); j++) {\n elementwise_check(is_good, function, name, x[j], must_be, indexings..., \"[\",\n j + error_index::value, \"]\");\n }\n}\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively. This overload\n * works on `var`s containing Eigen types.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n elementwise_check(is_good, function, name, x.val(), must_be, indexings...);\n}\n\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively.\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @return `false` if any of the scalars fail the error check\n *\/\ntemplate \ninline bool elementwise_is(const F& is_good, const T& x) {\n return internal::Iser{is_good}.is(x);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\napplied Ben's suggestion#ifndef STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP\n#define STAN_MATH_PRIM_ERR_ELEMENTWISE_ERROR_CHECKER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/** Apply an error check to a container, signal failure with `false`.\n * Apply a predicate like is_positive to the double underlying every scalar in a\n * container, producing true if the predicate holds everywhere and `false` if it\n * fails anywhere.\n * @tparam F type of predicate\n *\/\ntemplate \nclass Iser {\n const F& is_good;\n\n public:\n \/**\n * @param is_good predicate to check, must accept doubles and produce bools\n *\/\n explicit Iser(const F& is_good) : is_good(is_good) {}\n\n \/**\n * Check the scalar.\n * @tparam T type of scalar\n * @param x scalar\n * @return `false` if the scalar fails the error check\n *\/\n template >\n bool is(const T& x) {\n return is_good(value_of_rec(x));\n }\n\n \/**\n * Check all the scalars inside the container.\n * @tparam T type of scalar\n * @param x container\n * @return `false` if any of the scalars fail the error check\n *\/\n template ,\n typename = void>\n bool is(const T& x) {\n for (size_t i = 0; i < stan::math::size(x); ++i)\n if (!is(stan::get(x, i)))\n return false;\n return true;\n }\n};\n\n\/**\n * No-op.\n *\/\ninline void pipe_in(std::stringstream& ss) {}\n\/**\n * Pipes given arguments into a stringstream.\n *\n * @tparam Arg0 type of the first argument\n * @tparam Args types of remaining arguments\n * @param ss stringstream to pipe arguments in\n * @param arg0 the first argument\n * @param args remining arguments\n *\/\ntemplate \ninline void pipe_in(std::stringstream& ss, Arg0 arg0, const Args... args) {\n ss << arg0;\n pipe_in(ss, args...);\n}\n\n\/**\n * Throws domain error with concatenation of arguments for the error message.\n * @tparam Args types of arguments\n * @param args arguments\n *\/\ntemplate \nvoid elementwise_throw_domain_error(const Args... args) {\n std::stringstream ss;\n pipe_in(ss, args...);\n throw std::domain_error(ss.str());\n}\n\n} \/\/ namespace internal\n\n\/**\n * Check that the predicate holds for the value of `x`. This overload\n * works on scalars.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n if (unlikely(!is_good(value_of_rec(x)))) {\n internal::elementwise_throw_domain_error(function, \": \", name, indexings...,\n \" is \", x, \", but must be \",\n must_be, \"!\");\n }\n}\n\/**\n * Check that the predicate holds for all elements of the value of `x`. This overload\n * works on Eigen types that support linear indexing.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr,\n std::enable_if_t(Eigen::internal::traits::Flags&(\n Eigen::LinearAccessBit | Eigen::DirectAccessBit))>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t i = 0; i < x.size(); i++) {\n auto scal = value_of_rec(x.coeff(i));\n if (unlikely(!is_good(scal))) {\n if (is_eigen_vector::value) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \"] is \", scal, \", but must be \", must_be, \"!\");\n } else if (Eigen::internal::traits::Flags & Eigen::RowMajorBit) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\",\n i \/ x.cols() + error_index::value, \", \",\n i % x.cols() + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n } else {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\",\n i % x.rows() + error_index::value, \", \",\n i \/ x.rows() + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\n\/**\n * Check that the predicate holds for all elements of the value of `x`. This overload\n * works on col-major Eigen types that do not support linear indexing.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate <\n typename F, typename T, typename... Indexings,\n require_eigen_t* = nullptr,\n std::enable_if_t::Flags\n & (Eigen::LinearAccessBit | Eigen::DirectAccessBit))\n && !(Eigen::internal::traits::Flags\n & Eigen::RowMajorBit)>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t i = 0; i < x.rows(); i++) {\n for (size_t j = 0; j < x.cols(); j++) {\n auto scal = value_of_rec(x.coeff(i, j));\n if (unlikely(!is_good(scal))) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \", \", j + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\n\/**\n * Check that the predicate holds for all the elements of the value of `x`. This overload\n * works on row-major Eigen types that do not support linear indexing.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate <\n typename F, typename T, typename... Indexings,\n require_eigen_t* = nullptr,\n std::enable_if_t::Flags\n & (Eigen::LinearAccessBit | Eigen::DirectAccessBit))\n && static_cast(Eigen::internal::traits::Flags\n & Eigen::RowMajorBit)>* = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t j = 0; j < x.cols(); j++) {\n for (size_t i = 0; i < x.rows(); i++) {\n auto scal = value_of_rec(x.coeff(i, j));\n if (unlikely(!is_good(scal))) {\n internal::elementwise_throw_domain_error(\n function, \": \", name, indexings..., \"[\", i + error_index::value,\n \", \", j + error_index::value, \"] is \", scal, \", but must be \",\n must_be, \"!\");\n }\n }\n }\n}\n\n\/**\n * Check that the predicate holds for all elements of the value of `x`. This overload\n * works on `std::vector` types.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n for (size_t j = 0; j < x.size(); j++) {\n elementwise_check(is_good, function, name, x[j], must_be, indexings..., \"[\",\n j + error_index::value, \"]\");\n }\n}\n\n\/**\n * Check that the predicate holds for all elements of the value of `x`. This overload\n * works on `var`s containing Eigen types.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @tparam Indexings types of `indexings`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param function function name (for error messages)\n * @param name variable name (for error messages)\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @param must_be message describing what the value should be\n * @param indexings any additional indexing to print. Intended for internal use\n * in `elementwise_check` only.\n * @throws `std::domain_error` if `is_good` returns `false` for the value\n * of any element in `x`\n *\/\ntemplate * = nullptr>\ninline void elementwise_check(const F& is_good, const char* function,\n const char* name, const T& x, const char* must_be,\n const Indexings&... indexings) {\n elementwise_check(is_good, function, name, x.val(), must_be, indexings...);\n}\n\n\/**\n * Check that the predicate holds for the value of `x`, working elementwise on\n * containers. If `x` is a scalar, check the double underlying the scalar. If\n * `x` is a container, check each element inside `x`, recursively.\n *\n * @tparam F type of predicate\n * @tparam T type of `x`\n * @param is_good predicate to check, must accept doubles and produce bools\n * @param x variable to check, can be a scalar, a container of scalars, a\n * container of containers of scalars, etc\n * @return `false` if any of the scalars fail the error check\n *\/\ntemplate \ninline bool elementwise_is(const F& is_good, const T& x) {\n return internal::Iser{is_good}.is(x);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \"stream.hpp\"\n#include \"chunker.hpp\"\n\n\nnamespace vg {\n\nusing namespace std;\nusing namespace xg;\n\n\n\nPathChunker::PathChunker(xg::XG* xindex) : xg(xindex) {\n \n}\n\nPathChunker::~PathChunker() {\n\n}\n\nvoid PathChunker::extract_subgraph(const Region& region, int context, int length,\n bool forward_only, VG& subgraph, Region& out_region) {\n\n \/\/ extract our path range into the graph\n Graph g;\n xg->for_path_range(region.seq, region.start, region.end, [&](int64_t id, bool) {\n *g.add_node() = xg->node(id);\n });\n \n \/\/ expand the context and get path information\n \/\/ if forward_only true, then we only go forward.\n xg->expand_context(g, context, true, true, true, !forward_only);\n if (length) {\n xg->expand_context(g, context, true, false, true, !forward_only);\n }\n \n \/\/ build the vg of the subgraph\n subgraph.extend(g);\n subgraph.remove_orphan_edges();\n\n \/\/ get our range endpoints before context expansion\n list& mappings = subgraph.paths.get_path(region.seq);\n size_t mappings_size = mappings.size();\n int64_t input_start_node = xg->node_at_path_position(region.seq, region.start);\n vector first_positions = xg->position_in_path(input_start_node, region.seq);\n int64_t input_end_node = xg->node_at_path_position(region.seq, region.end);\n vector last_positions = xg->position_in_path(input_end_node, region.seq);\n\n \/\/ the distance between then and the nodes in our input range\n size_t left_padding = 0;\n size_t right_padding = 0;\n \/\/ do we need to rewrite back to our graph?\n bool rewrite_paths = false;\n \n \/\/ Endpoints not in cycles: we can get our output region directly from xg lookups\n if (first_positions.size() == 1 && last_positions.size() == 1) {\n \/\/ start and end of our expanded chunk\n auto start_it = mappings.begin();\n auto end_it = --mappings.end();\n\n \/\/ find our input range in the expanded path. we know these nodes only appear once.\n for (; start_it != mappings.end() && start_it->node_id() != input_start_node; ++start_it);\n for (; end_it != mappings.begin() && end_it->node_id() != input_end_node; --end_it);\n\n \/\/ walk back our start point as we can without rank discontinuities. doesn't matter\n \/\/ if we encounter cycles here, because we keep a running path length\n auto cur_it = start_it;\n auto prev_it = cur_it;\n if (prev_it != mappings.begin()) {\n for (; prev_it != mappings.begin(); --prev_it) {\n cur_it = prev_it;\n --cur_it;\n if ((prev_it->rank > 0 || cur_it->rank > 0) && cur_it->rank + 1 != prev_it->rank) {\n break;\n }\n left_padding += cur_it->length;\n }\n }\n start_it = prev_it;\n \/\/ walk forward the end point\n cur_it = end_it;\n prev_it = cur_it;\n for (++cur_it; cur_it != mappings.end(); ++prev_it, ++cur_it) {\n if ((prev_it->rank > 0 || cur_it->rank > 0) && prev_it->rank + 1 != cur_it->rank) {\n break;\n }\n right_padding += cur_it->length;\n }\n end_it = prev_it;\n\n rewrite_paths = start_it != mappings.begin() || end_it != --mappings.end();\n \n \/\/ cut out nodes before and after discontinuity\n mappings.erase(mappings.begin(), start_it);\n mappings.erase(++end_it, mappings.end());\n }\n \/\/ We're clipping at a cycle in the reference path. Just preserve the path as-is from the\n \/\/ input region. \n else {\n mappings.clear();\n xg->for_path_range(region.seq, region.start, region.end, [&](int64_t id, bool rev) {\n mapping_t mapping;\n mapping.set_node_id(id);\n mapping.set_is_reverse(rev);\n mappings.push_back(mapping);\n });\n rewrite_paths = true;\n }\n\n \/\/ Cut our graph so that our reference path end points are graph tips. This will let the\n \/\/ snarl finder use the path to find telomeres.\n Node* start_node = subgraph.get_node(mappings.begin()->node_id());\n if (!mappings.begin()->is_reverse() && subgraph.start_degree(start_node) != 0) {\n for (auto edge : subgraph.edges_to(start_node)) {\n subgraph.destroy_edge(edge);\n }\n } else if (mappings.begin()->is_reverse() && subgraph.end_degree(start_node) != 0) {\n for (auto edge : subgraph.edges_from(start_node)) {\n subgraph.destroy_edge(edge);\n }\n }\n Node* end_node = subgraph.get_node(mappings.rbegin()->node_id());\n if (!mappings.rbegin()->is_reverse() && subgraph.end_degree(end_node) != 0) {\n for (auto edge : subgraph.edges_from(end_node)) {\n subgraph.destroy_edge(edge);\n }\n } else if (mappings.rbegin()->is_reverse() && subgraph.start_degree(end_node) != 0) {\n for (auto edge : subgraph.edges_to(end_node)) {\n subgraph.destroy_edge(edge);\n }\n }\n \n \/\/ Sync our updated paths lists back into the Graph protobuf\n if (rewrite_paths) {\n subgraph.paths.rebuild_node_mapping();\n subgraph.paths.rebuild_mapping_aux();\n subgraph.graph.clear_path();\n subgraph.paths.to_graph(subgraph.graph);\n }\n\n \/\/ start could fall inside a node. we find out where in the path the\n \/\/ 0-offset point of the node is. \n int64_t input_start_pos = xg->node_start_at_path_position(region.seq, region.start);\n int64_t input_end_pos = xg->node_start_at_path_position(region.seq, region.end);\n out_region.seq = region.seq;\n out_region.start = input_start_pos - left_padding;\n out_region.end = input_end_pos + xg->node_length(input_end_node) + right_padding - 1;\n}\n\nvoid PathChunker::extract_id_range(vg::id_t start, vg::id_t end, int context, int length,\n bool forward_only, VG& subgraph, Region& out_region) {\n\n Graph g;\n\n for (vg::id_t i = start; i <= end; ++i) {\n *g.add_node() = xg->node(i);\n }\n \n \/\/ expand the context and get path information\n \/\/ if forward_only true, then we only go forward.\n xg->expand_context(g, context, true, true, true, !forward_only);\n if (length) {\n xg->expand_context(g, context, true, false, true, !forward_only);\n }\n\n \/\/ build the vg\n subgraph.extend(g);\n subgraph.remove_orphan_edges();\n\n out_region.start = subgraph.min_node_id();\n out_region.end = subgraph.max_node_id();\n}\n\n}\ndont cut chunk ends in cycles#include \n#include \n#include \"stream.hpp\"\n#include \"chunker.hpp\"\n\n\nnamespace vg {\n\nusing namespace std;\nusing namespace xg;\n\n\n\nPathChunker::PathChunker(xg::XG* xindex) : xg(xindex) {\n \n}\n\nPathChunker::~PathChunker() {\n\n}\n\nvoid PathChunker::extract_subgraph(const Region& region, int context, int length,\n bool forward_only, VG& subgraph, Region& out_region) {\n\n \/\/ extract our path range into the graph\n Graph g;\n xg->for_path_range(region.seq, region.start, region.end, [&](int64_t id, bool) {\n *g.add_node() = xg->node(id);\n });\n \n \/\/ expand the context and get path information\n \/\/ if forward_only true, then we only go forward.\n xg->expand_context(g, context, true, true, true, !forward_only);\n if (length) {\n xg->expand_context(g, context, true, false, true, !forward_only);\n }\n \n \/\/ build the vg of the subgraph\n subgraph.extend(g);\n subgraph.remove_orphan_edges();\n\n \/\/ get our range endpoints before context expansion\n list& mappings = subgraph.paths.get_path(region.seq);\n size_t mappings_size = mappings.size();\n int64_t input_start_node = xg->node_at_path_position(region.seq, region.start);\n vector first_positions = xg->position_in_path(input_start_node, region.seq);\n int64_t input_end_node = xg->node_at_path_position(region.seq, region.end);\n vector last_positions = xg->position_in_path(input_end_node, region.seq);\n\n \/\/ the distance between then and the nodes in our input range\n size_t left_padding = 0;\n size_t right_padding = 0;\n \/\/ do we need to rewrite back to our graph?\n bool rewrite_paths = false;\n \n \/\/ Endpoints not in cycles: we can get our output region directly from xg lookups\n if (first_positions.size() == 1 && last_positions.size() == 1) {\n \/\/ start and end of our expanded chunk\n auto start_it = mappings.begin();\n auto end_it = --mappings.end();\n\n \/\/ find our input range in the expanded path. we know these nodes only appear once.\n for (; start_it != mappings.end() && start_it->node_id() != input_start_node; ++start_it);\n for (; end_it != mappings.begin() && end_it->node_id() != input_end_node; --end_it);\n\n \/\/ walk back our start point as we can without rank discontinuities. doesn't matter\n \/\/ if we encounter cycles here, because we keep a running path length\n auto cur_it = start_it;\n auto prev_it = cur_it;\n if (prev_it != mappings.begin()) {\n for (; prev_it != mappings.begin(); --prev_it) {\n cur_it = prev_it;\n --cur_it;\n if ((prev_it->rank > 0 || cur_it->rank > 0) && cur_it->rank + 1 != prev_it->rank) {\n break;\n }\n left_padding += cur_it->length;\n }\n }\n start_it = prev_it;\n \/\/ walk forward the end point\n cur_it = end_it;\n prev_it = cur_it;\n for (++cur_it; cur_it != mappings.end(); ++prev_it, ++cur_it) {\n if ((prev_it->rank > 0 || cur_it->rank > 0) && prev_it->rank + 1 != cur_it->rank) {\n break;\n }\n right_padding += cur_it->length;\n }\n end_it = prev_it;\n\n rewrite_paths = start_it != mappings.begin() || end_it != --mappings.end();\n \n \/\/ cut out nodes before and after discontinuity\n mappings.erase(mappings.begin(), start_it);\n mappings.erase(++end_it, mappings.end());\n }\n \/\/ We're clipping at a cycle in the reference path. Just preserve the path as-is from the\n \/\/ input region. \n else {\n mappings.clear();\n xg->for_path_range(region.seq, region.start, region.end, [&](int64_t id, bool rev) {\n mapping_t mapping;\n mapping.set_node_id(id);\n mapping.set_is_reverse(rev);\n mappings.push_back(mapping);\n });\n rewrite_paths = true;\n }\n\n \/\/ Cut our graph so that our reference path end points are graph tips. This will let the\n \/\/ snarl finder use the path to find telomeres.\n Node* start_node = subgraph.get_node(mappings.begin()->node_id());\n if (rewrite_paths && xg->position_in_path(start_node->id(), region.seq).size() == 1) {\n if (!mappings.begin()->is_reverse() && subgraph.start_degree(start_node) != 0) {\n for (auto edge : subgraph.edges_to(start_node)) {\n subgraph.destroy_edge(edge);\n }\n } else if (mappings.begin()->is_reverse() && subgraph.end_degree(start_node) != 0) {\n for (auto edge : subgraph.edges_from(start_node)) {\n subgraph.destroy_edge(edge);\n }\n }\n }\n Node* end_node = subgraph.get_node(mappings.rbegin()->node_id());\n if (rewrite_paths && xg->position_in_path(end_node->id(), region.seq).size() == 1) {\n if (!mappings.rbegin()->is_reverse() && subgraph.end_degree(end_node) != 0) {\n for (auto edge : subgraph.edges_from(end_node)) {\n subgraph.destroy_edge(edge);\n }\n } else if (mappings.rbegin()->is_reverse() && subgraph.start_degree(end_node) != 0) {\n for (auto edge : subgraph.edges_to(end_node)) {\n subgraph.destroy_edge(edge);\n }\n }\n }\n \n \/\/ Sync our updated paths lists back into the Graph protobuf\n if (rewrite_paths) {\n subgraph.paths.rebuild_node_mapping();\n subgraph.paths.rebuild_mapping_aux();\n subgraph.graph.clear_path();\n subgraph.paths.to_graph(subgraph.graph);\n }\n\n \/\/ start could fall inside a node. we find out where in the path the\n \/\/ 0-offset point of the node is. \n int64_t input_start_pos = xg->node_start_at_path_position(region.seq, region.start);\n int64_t input_end_pos = xg->node_start_at_path_position(region.seq, region.end);\n out_region.seq = region.seq;\n out_region.start = input_start_pos - left_padding;\n out_region.end = input_end_pos + xg->node_length(input_end_node) + right_padding - 1;\n}\n\nvoid PathChunker::extract_id_range(vg::id_t start, vg::id_t end, int context, int length,\n bool forward_only, VG& subgraph, Region& out_region) {\n\n Graph g;\n\n for (vg::id_t i = start; i <= end; ++i) {\n *g.add_node() = xg->node(i);\n }\n \n \/\/ expand the context and get path information\n \/\/ if forward_only true, then we only go forward.\n xg->expand_context(g, context, true, true, true, !forward_only);\n if (length) {\n xg->expand_context(g, context, true, false, true, !forward_only);\n }\n\n \/\/ build the vg\n subgraph.extend(g);\n subgraph.remove_orphan_edges();\n\n out_region.start = subgraph.min_node_id();\n out_region.end = subgraph.max_node_id();\n}\n\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n\nThis file is part of the QtMediaHub project on http:\/\/www.gitorious.org.\n\nCopyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).*\nAll rights reserved.\n\nContact: Nokia Corporation (qt-info@nokia.com)**\n\nYou may use this file under the terms of the BSD license as follows:\n\n\"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* 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.\n* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n\n****************************************************************************\/\n\n#include \"backend.h\"\n#include \"plugins\/qmhplugininterface.h\"\n#include \"plugins\/qmhplugin.h\"\n#include \"dataproviders\/proxymodel.h\"\n#include \"dataproviders\/dirmodel.h\"\n#include \"dataproviders\/modelindexiterator.h\"\n#include \"qmh-config.h\"\n#include \"qml-extensions\/qmlfilewrapper.h\"\n#include \"qml-extensions\/actionmapper.h\"\n#include \"dataproviders\/playlist.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef GL\n#include \n#endif\n\n#include \n\nBackend* Backend::pSelf = 0;\n\nclass BackendPrivate : public QObject\n{\n Q_OBJECT\npublic:\n BackendPrivate(Backend *p)\n : QObject(p),\n #ifdef Q_OS_MAC\n platformOffset(\"\/..\/..\/..\"),\n #endif\n basePath(QCoreApplication::applicationDirPath() + platformOffset),\n skinPath(basePath % \"\/skins\"),\n pluginPath(basePath % \"\/plugins\"),\n resourcePath(basePath % \"\/resources\"),\n \/\/ Use \"large\" instead of appName to fit freedesktop spec\n thumbnailPath(Config::value(\"thumbnail-path\", QDir::homePath() + \"\/.thumbnails\/\" + qApp->applicationName() + \"\/\")),\n inputIdleTimer(this),\n qmlEngine(0),\n backendTranslator(0),\n logFile(qApp->applicationName().append(\".log\")),\n pSelf(p)\n {\n qApp->installEventFilter(this);\n\n inputIdleTimer.setInterval(Config::value(\"idle-timeout\", 2*60)*1000);\n inputIdleTimer.setSingleShot(true);\n inputIdleTimer.start();\n\n connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle()));\n\n logFile.open(QIODevice::Text|QIODevice::ReadWrite);\n log.setDevice(&logFile);\n\n connect(&resourcePathMonitor,\n SIGNAL(directoryChanged(const QString &)),\n this,\n SLOT(handleDirChanged(const QString &)));\n\n resourcePathMonitor.addPath(skinPath);\n resourcePathMonitor.addPath(pluginPath);\n\n QFileInfo thumbnailFolderInfo(thumbnailPath);\n if (!thumbnailFolderInfo.exists()) {\n QDir dir;\n dir.mkpath(thumbnailFolderInfo.absoluteFilePath());\n }\n\n discoverSkins();\n }\n\n ~BackendPrivate()\n {\n delete backendTranslator;\n backendTranslator = 0;\n qDeleteAll(pluginTranslators.begin(), pluginTranslators.end());\n }\npublic slots:\n void handleDirChanged(const QString &dir);\npublic:\n void resetLanguage();\n void discoverSkins();\n void discoverEngines();\n bool eventFilter(QObject *obj, QEvent *event);\n\n QSet advertizedEngineRoles;\n\n QList advertizedEngines;\n\n const QString platformOffset;\n\n const QString basePath;\n const QString skinPath;\n const QString pluginPath;\n const QString resourcePath;\n const QString thumbnailPath;\n\n QTimer inputIdleTimer;\n QDeclarativeEngine *qmlEngine;\n QTranslator *backendTranslator;\n QList pluginTranslators;\n QFile logFile;\n QTextStream log;\n QFileSystemWatcher resourcePathMonitor;\n QStringList skins;\n\n Backend *pSelf;\n};\n\nvoid BackendPrivate::handleDirChanged(const QString &dir)\n{\n if(dir == pluginPath) {\n qWarning() << \"Changes in plugin path, probably about to eat your poodle\";\n discoverEngines();\n } else if(dir == skinPath) {\n qWarning() << \"Changes in skin path, repopulating skins\";\n discoverSkins();\n }\n}\n\nvoid BackendPrivate::resetLanguage()\n{\n static QString baseTranslationPath(basePath % \"\/translations\/\");\n const QString language = Backend::instance()->language();\n delete backendTranslator;\n backendTranslator = new QTranslator(this);\n backendTranslator->load(baseTranslationPath % language % \".qm\");\n qApp->installTranslator(backendTranslator);\n\n qDeleteAll(pluginTranslators.begin(), pluginTranslators.end());\n\n foreach(QObject *pluginObject, advertizedEngines) {\n QMHPlugin *plugin = qobject_cast(pluginObject);\n QTranslator *pluginTranslator = new QTranslator(this);\n pluginTranslator->load(baseTranslationPath % plugin->role() % \"_\" % language % \".qm\");\n pluginTranslators << pluginTranslator;\n qApp->installTranslator(pluginTranslator);\n }\n}\n\nvoid BackendPrivate::discoverSkins()\n{\n skins.clear();\n\n QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot);\n\n foreach(const QString ¤tPath, potentialSkins)\n if(QFile(skinPath % \"\/\" % currentPath % \"\/\" % currentPath).exists())\n skins << currentPath;\n\n qWarning() << \"Available skins\" << skins;\n}\n\nvoid BackendPrivate::discoverEngines()\n{\n foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) {\n QString qualifiedFileName(pluginPath % \"\/\" % fileName);\n QPluginLoader pluginLoader(qualifiedFileName);\n\n if (!pluginLoader.load()) {\n qWarning() << tr(\"Cant load plugin: %1 returns %2\").arg(qualifiedFileName).arg(pluginLoader.errorString());\n continue;\n }\n\n QMHPluginInterface* pluginInterface = qobject_cast(pluginLoader.instance());\n if (!pluginInterface)\n qWarning() << tr(\"Invalid QMH plugin present: %1\").arg(qualifiedFileName);\n else if (!pluginInterface->dependenciesSatisfied())\n qWarning() << tr(\"Can't meet dependencies for %1\").arg(qualifiedFileName);\n else if (pluginInterface->role() == \"undefined\")\n qWarning() << tr(\"Plugin %1 has an undefined role\").arg(qualifiedFileName);\n else {\n QMHPlugin *plugin = new QMHPlugin(qobject_cast(pluginLoader.instance()), this);\n plugin->setParent(this);\n if(qmlEngine)\n plugin->registerPlugin(qmlEngine->rootContext());\n Backend::instance()->advertizeEngine(plugin);\n }\n }\n resetLanguage();\n}\n\nbool BackendPrivate::eventFilter(QObject *obj, QEvent *event) {\n if (event->type() == QEvent::MouseMove\n || event->type() == QEvent::MouseButtonPress\n || event->type() == QEvent::KeyPress\n || event->type() == QEvent::KeyRelease)\n {\n inputIdleTimer.start();\n }\n\n return QObject::eventFilter(obj, event);\n}\n\nBackend::Backend(QObject *parent)\n : QObject(parent),\n d(new BackendPrivate(this))\n{\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-Bold.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-Oblique.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-BoldOblique.ttf\");\n QApplication::setFont(QFont(\"DejaVu Sans\"));\n}\n\nBackend::~Backend()\n{\n delete d;\n d = 0;\n}\n\nvoid Backend::initialize(QDeclarativeEngine *qmlEngine)\n{\n \/\/ register dataproviders to QML\n qmlRegisterType(\"ActionMapper\", 1, 0, \"ActionMapper\");\n qmlRegisterType(\"QMHPlugin\", 1, 0, \"QMHPlugin\");\n qmlRegisterType(\"ProxyModel\", 1, 0, \"ProxyModel\");\n qmlRegisterType(\"ProxyModel\", 1, 0, \"ProxyModelItem\");\n qmlRegisterType(\"DirModel\", 1, 0, \"DirModel\");\n qmlRegisterType(\"ModelIndexIterator\", 1, 0, \"ModelIndexIterator\");\n qmlRegisterType(\"QMLFileWrapper\", 1, 0, \"QMLFileWrapper\");\n qmlRegisterType(\"Playlist\", 1, 0, \"Playlist\");\n\n\n if (qmlEngine) {\n \/\/FIXME: We are clearly failing to keep the backend Declarative free :p\n d->qmlEngine = qmlEngine;\n qmlEngine->rootContext()->setContextProperty(\"backend\", this);\n qmlEngine->rootContext()->setContextProperty(\"playlist\", new Playlist);\n }\n\n d->discoverEngines();\n}\n\n\nQString Backend::language() const \n{\n \/\/FIXME: derive from locale\n \/\/Allow override\n return QString();\n \/\/Bob is a testing translation placeholder\n \/\/return QString(\"bob\");\n}\n\nQList Backend::engines() const\n{\n return d->advertizedEngines;\n}\n\nQStringList Backend::skins() const\n{\n return d->skins;\n}\n\nBackend* Backend::instance()\n{\n if (!pSelf) {\n pSelf = new Backend();\n }\n return pSelf;\n}\n\nvoid Backend::destroy()\n{\n delete pSelf;\n pSelf = 0;\n}\n\nQString Backend::skinPath() const \n{\n return d->skinPath;\n}\n\nQString Backend::pluginPath() const \n{\n return d->pluginPath;\n}\n\nQString Backend::resourcePath() const \n{\n return d->resourcePath;\n}\n\nQString Backend::thumbnailPath() const \n{\n return d->thumbnailPath;\n}\n\nbool Backend::transforms() const \n{\n#ifdef GL\n return (QGLFormat::hasOpenGL() && Config::isEnabled(\"transforms\", true));\n#else\n return false;\n#endif\n}\n\nvoid Backend::advertizeEngine(QMHPlugin *engine) \n{\n QString role = engine->property(\"role\").toString();\n if (role.isEmpty())\n return;\n if (d->advertizedEngineRoles.contains(role)) {\n qWarning() << tr(\"Duplicate engine found for role %1\").arg(role);\n return;\n }\n d->advertizedEngines << engine;\n if (d->qmlEngine)\n d->qmlEngine->rootContext()->setContextProperty(role % \"Engine\", engine);\n d->advertizedEngineRoles << role;\n emit enginesChanged();\n}\n\nvoid Backend::openUrlExternally(const QUrl & url) const\n{\n QDesktopServices::openUrl(url);\n}\n\nvoid Backend::log(const QString &logMsg) \n{\n qDebug() << logMsg;\n d->log << logMsg << endl;\n}\n\n\/\/ again dependent on declarative, needs to be fixed\nvoid Backend::clearComponentCache() \n{\n if (d->qmlEngine) {\n d->qmlEngine->clearComponentCache();\n }\n}\n\nQObject* Backend::engine(const QString &role) \n{\n foreach (QObject *currentEngine, d->advertizedEngines)\n if (qobject_cast(currentEngine)->role() == role)\n return currentEngine;\n qWarning() << tr(\"Seeking a non-existant plugin, prepare to die\");\n return 0;\n}\n\n#include \"backend.moc\"\nPrevent screensaver from coming on in the background\/****************************************************************************\n\nThis file is part of the QtMediaHub project on http:\/\/www.gitorious.org.\n\nCopyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).*\nAll rights reserved.\n\nContact: Nokia Corporation (qt-info@nokia.com)**\n\nYou may use this file under the terms of the BSD license as follows:\n\n\"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* 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.\n* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n\n****************************************************************************\/\n\n#include \"backend.h\"\n#include \"plugins\/qmhplugininterface.h\"\n#include \"plugins\/qmhplugin.h\"\n#include \"dataproviders\/proxymodel.h\"\n#include \"dataproviders\/dirmodel.h\"\n#include \"dataproviders\/modelindexiterator.h\"\n#include \"qmh-config.h\"\n#include \"qml-extensions\/qmlfilewrapper.h\"\n#include \"qml-extensions\/actionmapper.h\"\n#include \"dataproviders\/playlist.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef GL\n#include \n#endif\n\n#include \n\nBackend* Backend::pSelf = 0;\n\nclass BackendPrivate : public QObject\n{\n Q_OBJECT\npublic:\n BackendPrivate(Backend *p)\n : QObject(p),\n #ifdef Q_OS_MAC\n platformOffset(\"\/..\/..\/..\"),\n #endif\n basePath(QCoreApplication::applicationDirPath() + platformOffset),\n skinPath(basePath % \"\/skins\"),\n pluginPath(basePath % \"\/plugins\"),\n resourcePath(basePath % \"\/resources\"),\n \/\/ Use \"large\" instead of appName to fit freedesktop spec\n thumbnailPath(Config::value(\"thumbnail-path\", QDir::homePath() + \"\/.thumbnails\/\" + qApp->applicationName() + \"\/\")),\n inputIdleTimer(this),\n qmlEngine(0),\n backendTranslator(0),\n logFile(qApp->applicationName().append(\".log\")),\n pSelf(p)\n {\n qApp->installEventFilter(this);\n\n inputIdleTimer.setInterval(Config::value(\"idle-timeout\", 120)*1000);\n inputIdleTimer.setSingleShot(true);\n inputIdleTimer.start();\n\n connect(&inputIdleTimer, SIGNAL(timeout()), pSelf, SIGNAL(inputIdle()));\n\n logFile.open(QIODevice::Text|QIODevice::ReadWrite);\n log.setDevice(&logFile);\n\n connect(&resourcePathMonitor,\n SIGNAL(directoryChanged(const QString &)),\n this,\n SLOT(handleDirChanged(const QString &)));\n\n resourcePathMonitor.addPath(skinPath);\n resourcePathMonitor.addPath(pluginPath);\n\n QFileInfo thumbnailFolderInfo(thumbnailPath);\n if (!thumbnailFolderInfo.exists()) {\n QDir dir;\n dir.mkpath(thumbnailFolderInfo.absoluteFilePath());\n }\n\n discoverSkins();\n }\n\n ~BackendPrivate()\n {\n delete backendTranslator;\n backendTranslator = 0;\n qDeleteAll(pluginTranslators.begin(), pluginTranslators.end());\n }\npublic slots:\n void handleDirChanged(const QString &dir);\npublic:\n void resetLanguage();\n void discoverSkins();\n void discoverEngines();\n bool eventFilter(QObject *obj, QEvent *event);\n\n QSet advertizedEngineRoles;\n\n QList advertizedEngines;\n\n const QString platformOffset;\n\n const QString basePath;\n const QString skinPath;\n const QString pluginPath;\n const QString resourcePath;\n const QString thumbnailPath;\n\n QTimer inputIdleTimer;\n QDeclarativeEngine *qmlEngine;\n QTranslator *backendTranslator;\n QList pluginTranslators;\n QFile logFile;\n QTextStream log;\n QFileSystemWatcher resourcePathMonitor;\n QStringList skins;\n\n Backend *pSelf;\n};\n\nvoid BackendPrivate::handleDirChanged(const QString &dir)\n{\n if(dir == pluginPath) {\n qWarning() << \"Changes in plugin path, probably about to eat your poodle\";\n discoverEngines();\n } else if(dir == skinPath) {\n qWarning() << \"Changes in skin path, repopulating skins\";\n discoverSkins();\n }\n}\n\nvoid BackendPrivate::resetLanguage()\n{\n static QString baseTranslationPath(basePath % \"\/translations\/\");\n const QString language = Backend::instance()->language();\n delete backendTranslator;\n backendTranslator = new QTranslator(this);\n backendTranslator->load(baseTranslationPath % language % \".qm\");\n qApp->installTranslator(backendTranslator);\n\n qDeleteAll(pluginTranslators.begin(), pluginTranslators.end());\n\n foreach(QObject *pluginObject, advertizedEngines) {\n QMHPlugin *plugin = qobject_cast(pluginObject);\n QTranslator *pluginTranslator = new QTranslator(this);\n pluginTranslator->load(baseTranslationPath % plugin->role() % \"_\" % language % \".qm\");\n pluginTranslators << pluginTranslator;\n qApp->installTranslator(pluginTranslator);\n }\n}\n\nvoid BackendPrivate::discoverSkins()\n{\n skins.clear();\n\n QStringList potentialSkins = QDir(skinPath).entryList(QDir::Dirs | QDir::NoDotAndDotDot);\n\n foreach(const QString ¤tPath, potentialSkins)\n if(QFile(skinPath % \"\/\" % currentPath % \"\/\" % currentPath).exists())\n skins << currentPath;\n\n qWarning() << \"Available skins\" << skins;\n}\n\nvoid BackendPrivate::discoverEngines()\n{\n foreach(const QString fileName, QDir(pluginPath).entryList(QDir::Files)) {\n QString qualifiedFileName(pluginPath % \"\/\" % fileName);\n QPluginLoader pluginLoader(qualifiedFileName);\n\n if (!pluginLoader.load()) {\n qWarning() << tr(\"Cant load plugin: %1 returns %2\").arg(qualifiedFileName).arg(pluginLoader.errorString());\n continue;\n }\n\n QMHPluginInterface* pluginInterface = qobject_cast(pluginLoader.instance());\n if (!pluginInterface)\n qWarning() << tr(\"Invalid QMH plugin present: %1\").arg(qualifiedFileName);\n else if (!pluginInterface->dependenciesSatisfied())\n qWarning() << tr(\"Can't meet dependencies for %1\").arg(qualifiedFileName);\n else if (pluginInterface->role() == \"undefined\")\n qWarning() << tr(\"Plugin %1 has an undefined role\").arg(qualifiedFileName);\n else {\n QMHPlugin *plugin = new QMHPlugin(qobject_cast(pluginLoader.instance()), this);\n plugin->setParent(this);\n if(qmlEngine)\n plugin->registerPlugin(qmlEngine->rootContext());\n Backend::instance()->advertizeEngine(plugin);\n }\n }\n resetLanguage();\n}\n\nbool BackendPrivate::eventFilter(QObject *obj, QEvent *event) {\n if (event->type() == QEvent::MouseMove\n || event->type() == QEvent::MouseButtonPress\n || event->type() == QEvent::KeyPress\n || event->type() == QEvent::KeyRelease)\n {\n inputIdleTimer.start();\n }\n\n return QObject::eventFilter(obj, event);\n}\n\nBackend::Backend(QObject *parent)\n : QObject(parent),\n d(new BackendPrivate(this))\n{\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-Bold.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-Oblique.ttf\");\n QFontDatabase::addApplicationFont(d->resourcePath + \"\/dejavu-fonts-ttf-2.32\/ttf\/DejaVuSans-BoldOblique.ttf\");\n QApplication::setFont(QFont(\"DejaVu Sans\"));\n}\n\nBackend::~Backend()\n{\n delete d;\n d = 0;\n}\n\nvoid Backend::initialize(QDeclarativeEngine *qmlEngine)\n{\n \/\/ register dataproviders to QML\n qmlRegisterType(\"ActionMapper\", 1, 0, \"ActionMapper\");\n qmlRegisterType(\"QMHPlugin\", 1, 0, \"QMHPlugin\");\n qmlRegisterType(\"ProxyModel\", 1, 0, \"ProxyModel\");\n qmlRegisterType(\"ProxyModel\", 1, 0, \"ProxyModelItem\");\n qmlRegisterType(\"DirModel\", 1, 0, \"DirModel\");\n qmlRegisterType(\"ModelIndexIterator\", 1, 0, \"ModelIndexIterator\");\n qmlRegisterType(\"QMLFileWrapper\", 1, 0, \"QMLFileWrapper\");\n qmlRegisterType(\"Playlist\", 1, 0, \"Playlist\");\n\n\n if (qmlEngine) {\n \/\/FIXME: We are clearly failing to keep the backend Declarative free :p\n d->qmlEngine = qmlEngine;\n qmlEngine->rootContext()->setContextProperty(\"backend\", this);\n qmlEngine->rootContext()->setContextProperty(\"playlist\", new Playlist);\n }\n\n d->discoverEngines();\n}\n\n\nQString Backend::language() const \n{\n \/\/FIXME: derive from locale\n \/\/Allow override\n return QString();\n \/\/Bob is a testing translation placeholder\n \/\/return QString(\"bob\");\n}\n\nQList Backend::engines() const\n{\n return d->advertizedEngines;\n}\n\nQStringList Backend::skins() const\n{\n return d->skins;\n}\n\nBackend* Backend::instance()\n{\n if (!pSelf) {\n pSelf = new Backend();\n }\n return pSelf;\n}\n\nvoid Backend::destroy()\n{\n delete pSelf;\n pSelf = 0;\n}\n\nQString Backend::skinPath() const \n{\n return d->skinPath;\n}\n\nQString Backend::pluginPath() const \n{\n return d->pluginPath;\n}\n\nQString Backend::resourcePath() const \n{\n return d->resourcePath;\n}\n\nQString Backend::thumbnailPath() const \n{\n return d->thumbnailPath;\n}\n\nbool Backend::transforms() const \n{\n#ifdef GL\n return (QGLFormat::hasOpenGL() && Config::isEnabled(\"transforms\", true));\n#else\n return false;\n#endif\n}\n\nvoid Backend::advertizeEngine(QMHPlugin *engine) \n{\n QString role = engine->property(\"role\").toString();\n if (role.isEmpty())\n return;\n if (d->advertizedEngineRoles.contains(role)) {\n qWarning() << tr(\"Duplicate engine found for role %1\").arg(role);\n return;\n }\n d->advertizedEngines << engine;\n if (d->qmlEngine)\n d->qmlEngine->rootContext()->setContextProperty(role % \"Engine\", engine);\n d->advertizedEngineRoles << role;\n emit enginesChanged();\n}\n\nvoid Backend::openUrlExternally(const QUrl & url) const\n{\n QDesktopServices::openUrl(url);\n}\n\nvoid Backend::log(const QString &logMsg) \n{\n qDebug() << logMsg;\n d->log << logMsg << endl;\n}\n\n\/\/ again dependent on declarative, needs to be fixed\nvoid Backend::clearComponentCache() \n{\n if (d->qmlEngine) {\n d->qmlEngine->clearComponentCache();\n }\n}\n\nQObject* Backend::engine(const QString &role) \n{\n foreach (QObject *currentEngine, d->advertizedEngines)\n if (qobject_cast(currentEngine)->role() == role)\n return currentEngine;\n qWarning() << tr(\"Seeking a non-existant plugin, prepare to die\");\n return 0;\n}\n\n#include \"backend.moc\"\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"text.hh\"\n\nint\nmain(\n int argc,\n char* const* const argv)\n{\n if (argc != 3) {\n std::cerr << \"usage: \" << argv[0] << \" LEN STRING\\n\";\n return 1;\n }\n\n size_t const length(atoi(argv[1]));\n string const str(argv[2]);\n\n std::cout << palide(str, length, ELLIPSIS, '~', 0.75) << \"\\n\"\n << std::string(length, '=') << \"\\n\";\n return 0;\n}\n\n\nClean up.<|endoftext|>"} {"text":"#define SECURITY_WIN32 1\n\n#include \n#include \n#include \n\n#include \n\nnamespace {\n\n std::string GetLastErrorAsString() {\n DWORD errorMessageID = ::GetLastError();\n if (errorMessageID == 0)\n return std::string();\n\n DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;\n DWORD languageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);\n LPSTR messageBuffer = NULL;\n size_t size = FormatMessageA(flags, NULL, errorMessageID, languageId, (LPSTR)&messageBuffer, 0, NULL);\n\n std::string message(messageBuffer, size);\n LocalFree(messageBuffer);\n return message;\n }\n\n class CheckUserPassword : public Nan::AsyncWorker {\n public:\n CheckUserPassword(Nan::Callback *callback, const std::string& domain, const std::string& user, const std::string& password)\n : Nan::AsyncWorker(callback), domain(domain), user(user), password(password), success(false) { }\n\n ~CheckUserPassword() { }\n\n virtual void Execute() {\n\n std::wstring swDomain = std::wstring(domain.begin(), domain.end());\n std::wstring swUser = std::wstring(user.begin(), user.end());\n std::wstring swPassword = std::wstring(password.begin(), password.end());\n\n HANDLE hdl;\n if (LogonUser(swUser.c_str(), swDomain.c_str(), swPassword.c_str(), LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hdl)) {\n success = true;\n return;\n }\n\n switch(::GetLastError()) {\n \/\/ expected error cases\n case ERROR_LOGON_FAILURE:\n case ERROR_ACCOUNT_EXPIRED:\n success = false;\n break;\n \/\/ unexpected error cases\n default:\n SetErrorMessage(GetLastErrorAsString().c_str());\n success = false;\n break;\n }\n }\n\n void HandleErrorCallback() {\n Nan::HandleScope scope;\n v8::Local argv[] = { Nan::Error(ErrorMessage()) };\n callback->Call(1, argv);\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n v8::Local returnValue = Nan::New(success);\n v8::Local argv[] = { Nan::Null(), returnValue };\n callback->Call(2, argv);\n }\n\n private:\n std::string domain;\n std::string user;\n std::string password;\n bool success;\n\n };\n\n NAN_METHOD(checkUserPassword) {\n Nan::Utf8String domain(info[0]->ToString());\n Nan::Utf8String user(info[1]->ToString());\n Nan::Utf8String password(info[2]->ToString());\n Nan::Callback *callback = new Nan::Callback(info[3].As());\n Nan::AsyncQueueWorker(new CheckUserPassword(callback, *domain, *user, *password));\n }\n\n NAN_MODULE_INIT(init) {\n Nan::HandleScope scope;\n Nan::SetMethod(target, \"checkUserPassword\", checkUserPassword);\n }\n\n NODE_MODULE(windows_local_auth, init)\n\n} \/\/ anonymous namespace\nAuth call now returns an error on non-Windows.#define SECURITY_WIN32 1\n\n#include \n#include \n#include \n\n#ifdef _WIN32\n#include \n#endif\n\nnamespace {\n\n#ifdef _WIN32\n std::string GetLastErrorAsString() {\n DWORD errorMessageID = ::GetLastError();\n if (errorMessageID == 0)\n return std::string();\n\n DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;\n DWORD languageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);\n LPSTR messageBuffer = NULL;\n size_t size = FormatMessageA(flags, NULL, errorMessageID, languageId, (LPSTR)&messageBuffer, 0, NULL);\n\n std::string message(messageBuffer, size);\n LocalFree(messageBuffer);\n return message;\n }\n#endif\n\n class CheckUserPassword : public Nan::AsyncWorker {\n public:\n CheckUserPassword(Nan::Callback *callback, const std::string& domain, const std::string& user, const std::string& password)\n : Nan::AsyncWorker(callback), domain(domain), user(user), password(password), success(false) { }\n\n ~CheckUserPassword() { }\n\n virtual void Execute() {\n#ifdef _WIN32\n std::wstring swDomain = std::wstring(domain.begin(), domain.end());\n std::wstring swUser = std::wstring(user.begin(), user.end());\n std::wstring swPassword = std::wstring(password.begin(), password.end());\n\n HANDLE hdl;\n if (LogonUser(swUser.c_str(), swDomain.c_str(), swPassword.c_str(), LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hdl)) {\n success = true;\n return;\n }\n\n switch(::GetLastError()) {\n \/\/ expected error cases\n case ERROR_LOGON_FAILURE:\n case ERROR_ACCOUNT_EXPIRED:\n success = false;\n break;\n \/\/ unexpected error cases\n default:\n SetErrorMessage(GetLastErrorAsString().c_str());\n success = false;\n break;\n }\n#else\n SetErrorMessage(\"Your operating system is not supported.\");\n success = false;\n#endif\n }\n\n void HandleErrorCallback() {\n Nan::HandleScope scope;\n v8::Local argv[] = { Nan::Error(ErrorMessage()) };\n callback->Call(1, argv);\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n v8::Local returnValue = Nan::New(success);\n v8::Local argv[] = { Nan::Null(), returnValue };\n callback->Call(2, argv);\n }\n\n private:\n std::string domain;\n std::string user;\n std::string password;\n bool success;\n\n };\n\n NAN_METHOD(checkUserPassword) {\n Nan::Utf8String domain(info[0]->ToString());\n Nan::Utf8String user(info[1]->ToString());\n Nan::Utf8String password(info[2]->ToString());\n Nan::Callback *callback = new Nan::Callback(info[3].As());\n Nan::AsyncQueueWorker(new CheckUserPassword(callback, *domain, *user, *password));\n }\n\n NAN_MODULE_INIT(init) {\n Nan::HandleScope scope;\n Nan::SetMethod(target, \"checkUserPassword\", checkUserPassword);\n }\n\n NODE_MODULE(windows_local_auth, init)\n\n} \/\/ anonymous namespace\n<|endoftext|>"} {"text":"\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \"ChatSession.h\"\r\n\r\nnamespace OpensimIM\r\n{\r\n\tChatSession::ChatSession(Foundation::Framework* framework, const QString &id, bool public_chat): framework_(framework), server_(\"0\", \"Server\"), private_im_session_(!public_chat), self_(\"\", \"You\"), state_(STATE_OPEN)\r\n\t{\r\n\t\t\/\/! \\todo Add support to different channel numbers\r\n\t\t\/\/! This requires changes to SendChatFromViewerPacket method or \r\n\t\t\/\/! chat packet must be construaed by hand.\r\n\t\tif ( public_chat )\r\n\t\t{\r\n\t\t\tchannel_id_ = id;\r\n\t\t\tif ( channel_id_.compare(\"0\") != 0 )\r\n\t\t\t\tthrow Exception(\"Cannot create chat session, channel id now allowed\"); \r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tChatSessionParticipant* p = new ChatSessionParticipant(id, \"\");\r\n\t\t\tparticipants_.push_back(p);\r\n\t\t}\r\n\t}\r\n\r\n ChatSession::~ChatSession()\r\n {\r\n for (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n {\r\n ChatSessionParticipant* participant = *i;\r\n SAFE_DELETE(participant);\r\n }\r\n participants_.clear();\r\n\r\n for (ChatMessageVector::iterator i = message_history_.begin(); i != message_history_.end(); ++i)\r\n {\r\n ChatMessage* message = *i;\r\n SAFE_DELETE(message);\r\n }\r\n message_history_.clear();\r\n }\r\n\r\n\tvoid ChatSession::SendMessage(const QString &text)\r\n\t{\r\n\t\tif (private_im_session_)\r\n\t\t\tSendPrivateIMMessage(text);\r\n\t\telse\r\n\t\t\tSendPublicChatMessage(text);\r\n\t}\r\n\r\n\tCommunication::ChatSessionInterface::State ChatSession::GetState() const\r\n\t{\r\n\t\treturn state_;\r\n\t}\r\n\r\n\tvoid ChatSession::SendPrivateIMMessage(const QString &text)\r\n\t{\r\n\t\tif (state_ != STATE_OPEN)\r\n\t\t\tthrow Exception(\"Chat session is closed\");\r\n\r\n\t\tRexLogic::RexLogicModule *rexlogic_ = dynamic_cast(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());\r\n\r\n\t\tif (rexlogic_ == NULL)\r\n\t\t\tthrow Exception(\"Cannot send IM message, RexLogicModule is not found\");\r\n\t\tRexLogic::WorldStreamConnectionPtr connection = rexlogic_->GetServerConnection();\r\n\r\n\t\tif ( connection == NULL )\r\n\t\t\tthrow Exception(\"Cannot send IM message, rex server connection is not found\");\r\n\r\n\t\tif ( !connection->IsConnected() )\r\n\t\t\tthrow Exception(\"Cannot send IM message, rex server connection is not established\");\r\n\r\n\t\tChatMessage* m = new ChatMessage(&self_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\tfor (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tconnection->SendImprovedInstantMessagePacket(RexUUID( (*i)->GetID().toStdString() ), text.toStdString() );\r\n\t\t}\r\n\t}\r\n\r\n\tvoid ChatSession::SendPublicChatMessage(const QString &text)\r\n\t{\r\n\t\tRexLogic::RexLogicModule *rexlogic_ = dynamic_cast(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());\r\n\r\n\t\tif (rexlogic_ == NULL)\r\n\t\t\tthrow Exception(\"Cannot send text message, RexLogicModule is not found\");\r\n\t\tRexLogic::WorldStreamConnectionPtr connection = rexlogic_->GetServerConnection();\r\n\r\n\t\tif ( connection == NULL )\r\n\t\t\tthrow Exception(\"Cannot send text message, rex server connection is not found\");\r\n\r\n\t\tif ( !connection->IsConnected() )\r\n\t\t\tthrow Exception(\"Cannot send text message, rex server connection is not established\");\r\n\r\n\t\tChatMessage* m = new ChatMessage(&self_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\tconnection->SendChatFromViewerPacket( text.toStdString() );\r\n\t}\r\n\r\n\tvoid ChatSession::Close()\r\n\t{\r\n\t\t\/\/! \\todo IMPLEMENT\r\n\t\tstate_ = STATE_CLOSED;\r\n\t\temit( Closed(this) );\r\n\t}\r\n\r\n\tCommunication::ChatMessageVector ChatSession::GetMessageHistory() \r\n\t{\r\n\t\tCommunication::ChatMessageVector message_history;\r\n\t\tfor (ChatMessageVector::iterator i = message_history_.begin(); i != message_history_.end(); ++i)\r\n\t\t{\r\n\t\t\tassert( (*i) != NULL );\r\n\t\t\tmessage_history.push_back( (*i) );\r\n\t\t}\r\n\t\treturn message_history;\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromAgent(const QString &avatar_id, const QString &from_name, const QString &text)\r\n\t{\r\n\t\tChatSessionParticipant* participant = FindParticipant(avatar_id);\r\n\t\tif ( !participant )\r\n\t\t{\r\n\t\t\tparticipant = new ChatSessionParticipant(avatar_id, from_name);\r\n\t\t\tparticipants_.push_back(participant);\r\n\t\t}\r\n\r\n\t\tif (participant->GetName().size() == 0)\r\n\t\t\t((ChatSessionParticipant*)participant)->SetName(from_name); \/\/! @HACK We should get the name from some another source!\r\n\r\n\t\tChatMessage* m = new ChatMessage(participant, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromServer(const QString &text)\r\n\t{\r\n\t\tChatMessage* m = new ChatMessage(&server_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromObject(const QString &object_id, const QString &text)\r\n\t{\r\n\t\tChatSessionParticipant* originator = FindParticipant(object_id);\r\n\t\tif ( !originator )\r\n\t\t{\r\n\t\t\t\/\/! @todo Find out the name of this object and give it as argument for participant object constructor\r\n\t\t\tChatSessionParticipant* originator = new ChatSessionParticipant(object_id, object_id);\r\n\t\t\tparticipants_.push_back(originator);\r\n\t\t}\r\n\t\tChatMessage* m = new ChatMessage(originator, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tChatSessionParticipant* ChatSession::FindParticipant(const QString &uuid)\r\n\t{\r\n\t\tfor (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tif ( (*i)->GetID().compare(uuid) == 0 )\r\n\t\t\t\treturn *i;\r\n\t\t}\r\n\t\treturn NULL;\r\n\t}\r\n\r\n\tCommunication::ChatSessionParticipantVector ChatSession::GetParticipants() const\r\n\t{\r\n\t\tCommunication::ChatSessionParticipantVector participants;\r\n\t\tfor (ChatSessionParticipantVector::const_iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tparticipants.push_back(*i);\r\n\t\t}\r\n\t\treturn participants;\r\n\t}\r\n\r\n\tQString ChatSession::GetID() const\r\n\t{\r\n\t\treturn channel_id_;\r\n\t}\r\n\r\n\tbool ChatSession::IsPrivateIMSession()\r\n\t{\r\n\t\treturn private_im_session_;\r\n\t}\r\n\r\n} \/\/ end of namespace: OpensimIM\r\ncode cleanup.\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \r\n#include \r\n\r\n#include \"ChatSession.h\"\r\n\r\nnamespace OpensimIM\r\n{\r\n\tChatSession::ChatSession(Foundation::Framework* framework, const QString &id, bool public_chat): framework_(framework), server_(\"0\", \"Server\"), private_im_session_(!public_chat), self_(\"\", \"You\"), state_(STATE_OPEN)\r\n\t{\r\n\t\t\/\/! \\todo Add support to different channel numbers\r\n\t\t\/\/! This requires changes to SendChatFromViewerPacket method or \r\n\t\t\/\/! chat packet must be construaed by hand.\r\n\t\tif ( public_chat )\r\n\t\t{\r\n\t\t\tchannel_id_ = id;\r\n\t\t\tif ( channel_id_.compare(\"0\") != 0 )\r\n\t\t\t\tthrow Exception(\"Cannot create chat session, channel id now allowed\"); \r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tChatSessionParticipant* p = new ChatSessionParticipant(id, \"\");\r\n\t\t\tparticipants_.push_back(p);\r\n\t\t}\r\n\t}\r\n\r\n ChatSession::~ChatSession()\r\n {\r\n for (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n {\r\n ChatSessionParticipant* participant = *i;\r\n SAFE_DELETE(participant);\r\n }\r\n participants_.clear();\r\n\r\n for (ChatMessageVector::iterator i = message_history_.begin(); i != message_history_.end(); ++i)\r\n {\r\n ChatMessage* message = *i;\r\n SAFE_DELETE(message);\r\n }\r\n message_history_.clear();\r\n }\r\n\r\n\tvoid ChatSession::SendMessage(const QString &text)\r\n\t{\r\n\t\tif (private_im_session_)\r\n\t\t\tSendPrivateIMMessage(text);\r\n\t\telse\r\n\t\t\tSendPublicChatMessage(text);\r\n\t}\r\n\r\n\tCommunication::ChatSessionInterface::State ChatSession::GetState() const\r\n\t{\r\n\t\treturn state_;\r\n\t}\r\n\r\n\tvoid ChatSession::SendPrivateIMMessage(const QString &text)\r\n\t{\r\n\t\tif (state_ != STATE_OPEN)\r\n\t\t\tthrow Exception(\"Chat session is closed\");\r\n\r\n\t\tRexLogic::RexLogicModule *rexlogic_ = dynamic_cast(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());\r\n\r\n\t\tif (rexlogic_ == NULL)\r\n\t\t\tthrow Exception(\"Cannot send IM message, RexLogicModule is not found\");\r\n\t\tRexLogic::WorldStreamConnectionPtr connection = rexlogic_->GetServerConnection();\r\n\r\n\t\tif ( connection == NULL )\r\n\t\t\tthrow Exception(\"Cannot send IM message, rex server connection is not found\");\r\n\r\n\t\tif ( !connection->IsConnected() )\r\n\t\t\tthrow Exception(\"Cannot send IM message, rex server connection is not established\");\r\n\r\n\t\tChatMessage* m = new ChatMessage(&self_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\tfor (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tconnection->SendImprovedInstantMessagePacket(RexUUID( (*i)->GetID().toStdString() ), text.toStdString() );\r\n\t\t}\r\n\t}\r\n\r\n\tvoid ChatSession::SendPublicChatMessage(const QString &text)\r\n\t{\r\n\t\tRexLogic::RexLogicModule *rexlogic_ = dynamic_cast(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());\r\n\r\n\t\tif (rexlogic_ == NULL)\r\n\t\t\tthrow Exception(\"Cannot send text message, RexLogicModule is not found\");\r\n\t\tRexLogic::WorldStreamConnectionPtr connection = rexlogic_->GetServerConnection();\r\n\r\n\t\tif ( connection == NULL )\r\n\t\t\tthrow Exception(\"Cannot send text message, rex server connection is not found\");\r\n\r\n\t\tif ( !connection->IsConnected() )\r\n\t\t\tthrow Exception(\"Cannot send text message, rex server connection is not established\");\r\n\r\n\t\tChatMessage* m = new ChatMessage(&self_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\tconnection->SendChatFromViewerPacket( text.toStdString() );\r\n\t}\r\n\r\n\tvoid ChatSession::Close()\r\n\t{\r\n\t\t\/\/! \\todo IMPLEMENT\r\n\t\tstate_ = STATE_CLOSED;\r\n\t\temit( Closed(this) );\r\n\t}\r\n\r\n\tCommunication::ChatMessageVector ChatSession::GetMessageHistory() \r\n\t{\r\n\t\tCommunication::ChatMessageVector message_history;\r\n\t\tfor (ChatMessageVector::iterator i = message_history_.begin(); i != message_history_.end(); ++i)\r\n\t\t{\r\n ChatMessage* message = *i;\r\n\t\t\tassert( message != NULL );\r\n\t\t\tmessage_history.push_back( message );\r\n\t\t}\r\n\t\treturn message_history;\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromAgent(const QString &avatar_id, const QString &from_name, const QString &text)\r\n\t{\r\n\t\tChatSessionParticipant* participant = FindParticipant(avatar_id);\r\n\t\tif ( !participant )\r\n\t\t{\r\n\t\t\tparticipant = new ChatSessionParticipant(avatar_id, from_name);\r\n\t\t\tparticipants_.push_back(participant);\r\n\t\t}\r\n\r\n\t\tif (participant->GetName().size() == 0)\r\n\t\t\t((ChatSessionParticipant*)participant)->SetName(from_name); \/\/! @HACK We should get the name from some another source!\r\n\r\n\t\tChatMessage* m = new ChatMessage(participant, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromServer(const QString &text)\r\n\t{\r\n\t\tChatMessage* m = new ChatMessage(&server_, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tvoid ChatSession::MessageFromObject(const QString &object_id, const QString &text)\r\n\t{\r\n\t\tChatSessionParticipant* originator = FindParticipant(object_id);\r\n\t\tif ( !originator )\r\n\t\t{\r\n\t\t\t\/\/! @todo Find out the name of this object and give it as argument for participant object constructor\r\n\t\t\tChatSessionParticipant* originator = new ChatSessionParticipant(object_id, object_id);\r\n\t\t\tparticipants_.push_back(originator);\r\n\t\t}\r\n\t\tChatMessage* m = new ChatMessage(originator, QDateTime::currentDateTime(), text);\r\n\t\tmessage_history_.push_back(m);\r\n\t\temit MessageReceived(*m);\r\n\t}\r\n\r\n\tChatSessionParticipant* ChatSession::FindParticipant(const QString &uuid)\r\n\t{\r\n\t\tfor (ChatSessionParticipantVector::iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tif ( (*i)->GetID().compare(uuid) == 0 )\r\n\t\t\t\treturn *i;\r\n\t\t}\r\n\t\treturn NULL;\r\n\t}\r\n\r\n\tCommunication::ChatSessionParticipantVector ChatSession::GetParticipants() const\r\n\t{\r\n\t\tCommunication::ChatSessionParticipantVector participants;\r\n\t\tfor (ChatSessionParticipantVector::const_iterator i = participants_.begin(); i != participants_.end(); ++i)\r\n\t\t{\r\n\t\t\tparticipants.push_back(*i);\r\n\t\t}\r\n\t\treturn participants;\r\n\t}\r\n\r\n\tQString ChatSession::GetID() const\r\n\t{\r\n\t\treturn channel_id_;\r\n\t}\r\n\r\n\tbool ChatSession::IsPrivateIMSession()\r\n\t{\r\n\t\treturn private_im_session_;\r\n\t}\r\n\r\n} \/\/ end of namespace: OpensimIM\r\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Medical Imaging & Interaction Toolkit\n Module: $RCSfile$\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/ for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \n#include \"mitkGeometry2DDataMapper2D.h\"\n\n#include \"mitkBaseRenderer.h\"\n\n#include \"mitkPlaneGeometry.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkSmartPointerProperty.h\"\n\n#include \"mitkGeometry2DDataToSurfaceFilter.h\"\n#include \"mitkSurfaceMapper2D.h\"\n\n#include \"GL\/glu.h\"\n\n\/\/##ModelId=3E639E100243\nmitk::Geometry2DDataMapper2D::Geometry2DDataMapper2D() : m_SurfaceMapper(NULL)\n{\n}\n\n\/\/##ModelId=3E639E100257\nmitk::Geometry2DDataMapper2D::~Geometry2DDataMapper2D()\n{\n}\n\n\/\/##ModelId=3E6423D20341\nconst mitk::Geometry2DData *mitk::Geometry2DDataMapper2D::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n return 0;\n }\n \n return static_cast ( GetData() );\n}\n\n\n\/\/##ModelId=3E67D77A0109\nvoid mitk::Geometry2DDataMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n \n \/\/\t@FIXME: Logik fuer update\n bool updateNeccesary=true;\n \n if (updateNeccesary) {\n \/\/ ok, das ist aus GenerateData kopiert\n \n mitk::Geometry2DData::Pointer input = const_cast(this->GetInput());\n \n \/\/intersecting with ourself?\n if(input->GetGeometry2D()==renderer->GetCurrentWorldGeometry2D())\n return; \/\/do nothing!\n \n PlaneGeometry::ConstPointer input_planeGeometry = dynamic_cast(input->GetGeometry2D());\n PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast(renderer->GetCurrentWorldGeometry2D()); \n \n if(worldPlaneGeometry.IsNotNull() && (input_planeGeometry.IsNotNull()))\n {\n mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();\n assert(displayGeometry);\n \n \/\/calculate intersection of the plane data with the border of the world geometry rectangle\n \/\/float aaaa[2]={10,11};\n Point2D lineFrom;\/\/ =(float[2]){10,11}; \n Point2D lineTo;\n bool intersecting = worldPlaneGeometry->IntersectWithPlane2D( input_planeGeometry, lineFrom, lineTo );\n \n if(intersecting)\n {\n \/\/convert intersection points (until now mm) to display coordinates (units )\n displayGeometry->MMToDisplay(lineFrom, lineFrom);\n displayGeometry->MMToDisplay(lineTo, lineTo);\n \n \/\/convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )\n \/\/ float toGL=\/\/displayGeometry->GetDisplayHeight(); displayGeometry->GetCurrentWorldGeometry2D()->GetHeightInUnits();\n \/\/ lineFrom[1]=toGL-lineFrom[1];\n \/\/ lineTo[1]=toGL-lineTo[1];\n \n \/\/apply color and opacity read from the PropertyList\n ApplyProperties(renderer);\n\n \/\/draw\n glBegin (GL_LINE_LOOP);\n glVertex2f(lineFrom[0],lineFrom[1]);\n glVertex2f(lineTo[0],lineTo[1]);\n glVertex2f(lineFrom[0],lineFrom[1]);\n glEnd ();\n }\n }\n else\n {\n mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;\n mitk::SmartPointerProperty::Pointer surfacecreatorprop;\n surfacecreatorprop=dynamic_cast(GetDataTreeNode()->GetProperty(\"surfacegeometry\", renderer).GetPointer());\n if( (surfacecreatorprop.IsNull()) || \n (surfacecreatorprop->GetSmartPointer().IsNull()) ||\n ((surfaceCreator=dynamic_cast(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())\n )\n {\n surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();\n surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);\n GetDataTreeNode()->SetProperty(\"surfacegeometry\", surfacecreatorprop);\n }\n \n surfaceCreator->SetInput(input);\n \n int res;\n bool usegeometryparametricbounds=true;\n if(GetDataTreeNode()->GetIntProperty(\"xresolution\", res, renderer))\n {\n surfaceCreator->SetXResolution(res);\n usegeometryparametricbounds=false; \n }\n if(GetDataTreeNode()->GetIntProperty(\"yresolution\", res, renderer))\n {\n surfaceCreator->SetYResolution(res);\n usegeometryparametricbounds=false; \n }\n surfaceCreator->SetUseGeometryParametricBounds(usegeometryparametricbounds);\n\n surfaceCreator->Update(); \/\/@FIXME ohne das crash\n \n if(m_SurfaceMapper.IsNull())\n m_SurfaceMapper=mitk::SurfaceMapper2D::New();\n m_SurfaceMapper->SetInput(GetDataTreeNode());\n m_SurfaceMapper->SetSurface(surfaceCreator->GetOutput());\n \n m_SurfaceMapper->Paint(renderer);\n }\n }\n}\n\n\/\/##ModelId=3E67E1B90237\nvoid mitk::Geometry2DDataMapper2D::Update()\n{\n}\n\n\/\/##ModelId=3E67E285024E\nvoid mitk::Geometry2DDataMapper2D::GenerateOutputInformation()\n{\n}\nFIX: bool from int\/*=========================================================================\n\n Program: Medical Imaging & Interaction Toolkit\n Module: $RCSfile$\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/ for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \n#include \"mitkGeometry2DDataMapper2D.h\"\n\n#include \"mitkBaseRenderer.h\"\n\n#include \"mitkPlaneGeometry.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkSmartPointerProperty.h\"\n\n#include \"mitkGeometry2DDataToSurfaceFilter.h\"\n#include \"mitkSurfaceMapper2D.h\"\n\n#include \"GL\/glu.h\"\n\n\/\/##ModelId=3E639E100243\nmitk::Geometry2DDataMapper2D::Geometry2DDataMapper2D() : m_SurfaceMapper(NULL)\n{\n}\n\n\/\/##ModelId=3E639E100257\nmitk::Geometry2DDataMapper2D::~Geometry2DDataMapper2D()\n{\n}\n\n\/\/##ModelId=3E6423D20341\nconst mitk::Geometry2DData *mitk::Geometry2DDataMapper2D::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n return 0;\n }\n \n return static_cast ( GetData() );\n}\n\n\n\/\/##ModelId=3E67D77A0109\nvoid mitk::Geometry2DDataMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n \n \/\/\t@FIXME: Logik fuer update\n bool updateNeccesary=true;\n \n if (updateNeccesary) {\n \/\/ ok, das ist aus GenerateData kopiert\n \n mitk::Geometry2DData::Pointer input = const_cast(this->GetInput());\n \n \/\/intersecting with ourself?\n if(input->GetGeometry2D()==renderer->GetCurrentWorldGeometry2D())\n return; \/\/do nothing!\n \n PlaneGeometry::ConstPointer input_planeGeometry = dynamic_cast(input->GetGeometry2D());\n PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast(renderer->GetCurrentWorldGeometry2D()); \n \n if(worldPlaneGeometry.IsNotNull() && (input_planeGeometry.IsNotNull()))\n {\n mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();\n assert(displayGeometry);\n \n \/\/calculate intersection of the plane data with the border of the world geometry rectangle\n \/\/float aaaa[2]={10,11};\n Point2D lineFrom;\/\/ =(float[2]){10,11}; \n Point2D lineTo;\n bool intersecting = worldPlaneGeometry->IntersectWithPlane2D( input_planeGeometry, lineFrom, lineTo ) > 0;\n \n if(intersecting)\n {\n \/\/convert intersection points (until now mm) to display coordinates (units )\n displayGeometry->MMToDisplay(lineFrom, lineFrom);\n displayGeometry->MMToDisplay(lineTo, lineTo);\n \n \/\/convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left )\n \/\/ float toGL=\/\/displayGeometry->GetDisplayHeight(); displayGeometry->GetCurrentWorldGeometry2D()->GetHeightInUnits();\n \/\/ lineFrom[1]=toGL-lineFrom[1];\n \/\/ lineTo[1]=toGL-lineTo[1];\n \n \/\/apply color and opacity read from the PropertyList\n ApplyProperties(renderer);\n\n \/\/draw\n glBegin (GL_LINE_LOOP);\n glVertex2f(lineFrom[0],lineFrom[1]);\n glVertex2f(lineTo[0],lineTo[1]);\n glVertex2f(lineFrom[0],lineFrom[1]);\n glEnd ();\n }\n }\n else\n {\n mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;\n mitk::SmartPointerProperty::Pointer surfacecreatorprop;\n surfacecreatorprop=dynamic_cast(GetDataTreeNode()->GetProperty(\"surfacegeometry\", renderer).GetPointer());\n if( (surfacecreatorprop.IsNull()) || \n (surfacecreatorprop->GetSmartPointer().IsNull()) ||\n ((surfaceCreator=dynamic_cast(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())\n )\n {\n surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();\n surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);\n GetDataTreeNode()->SetProperty(\"surfacegeometry\", surfacecreatorprop);\n }\n \n surfaceCreator->SetInput(input);\n \n int res;\n bool usegeometryparametricbounds=true;\n if(GetDataTreeNode()->GetIntProperty(\"xresolution\", res, renderer))\n {\n surfaceCreator->SetXResolution(res);\n usegeometryparametricbounds=false; \n }\n if(GetDataTreeNode()->GetIntProperty(\"yresolution\", res, renderer))\n {\n surfaceCreator->SetYResolution(res);\n usegeometryparametricbounds=false; \n }\n surfaceCreator->SetUseGeometryParametricBounds(usegeometryparametricbounds);\n\n surfaceCreator->Update(); \/\/@FIXME ohne das crash\n \n if(m_SurfaceMapper.IsNull())\n m_SurfaceMapper=mitk::SurfaceMapper2D::New();\n m_SurfaceMapper->SetInput(GetDataTreeNode());\n m_SurfaceMapper->SetSurface(surfaceCreator->GetOutput());\n \n m_SurfaceMapper->Paint(renderer);\n }\n }\n}\n\n\/\/##ModelId=3E67E1B90237\nvoid mitk::Geometry2DDataMapper2D::Update()\n{\n}\n\n\/\/##ModelId=3E67E285024E\nvoid mitk::Geometry2DDataMapper2D::GenerateOutputInformation()\n{\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"DeclarationVisitor.h\"\n#include \"ExpressionVisitor.h\"\n#include \"StatementVisitor.h\"\n#include \"ElementVisitor.h\"\n\n#include \"OOModel\/src\/declarations\/Project.h\"\n#include \"OOModel\/src\/declarations\/Module.h\"\n#include \"OOModel\/src\/declarations\/Class.h\"\n#include \"OOModel\/src\/declarations\/Declaration.h\"\n#include \"OOModel\/src\/declarations\/Method.h\"\n#include \"OOModel\/src\/declarations\/NameImport.h\"\n#include \"OOModel\/src\/declarations\/VariableDeclaration.h\"\n#include \"OOModel\/src\/declarations\/ExplicitTemplateInstantiation.h\"\n#include \"OOModel\/src\/declarations\/TypeAlias.h\"\n\n#include \"Export\/src\/tree\/SourceDir.h\"\n#include \"Export\/src\/tree\/SourceFile.h\"\n#include \"Export\/src\/tree\/CompositeFragment.h\"\n#include \"Export\/src\/tree\/TextFragment.h\"\n\n#include \"Comments\/src\/nodes\/CommentNode.h\"\n\nusing namespace Export;\nusing namespace OOModel;\n\nnamespace CppExport {\n\nSourceFragment* DeclarationVisitor::visit(Declaration* declaration)\n{\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\n\tnotAllowed(declaration);\n\n\tauto fragment = new CompositeFragment(declaration);\n\t*fragment << \"Invalid Declaration\";\n\treturn fragment;\n}\n\nSourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent)\n{\n\tauto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, \"src\");\n\n\tfor (auto node : *project->projects()) visitProject(node, projectDir);\n\tfor (auto node : *project->modules()) visitModule(node, projectDir);\n\tfor (auto node : *project->classes()) visitTopLevelClass(node, projectDir);\n\n\tnotAllowed(project->methods());\n\tnotAllowed(project->fields());\n\n\treturn projectDir;\n}\n\nSourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent)\n{\n\tQ_ASSERT(parent);\n\tauto moduleDir = &parent->subDir(module->name());\n\n\tfor (auto node : *module->modules()) visitModule(node, moduleDir);\n\tfor (auto node : *module->classes()) visitTopLevelClass(node, moduleDir);\n\n\tnotAllowed(module->methods());\n\tnotAllowed(module->fields());\n\n\treturn moduleDir;\n}\n\nSourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent)\n{\n\tQ_ASSERT(parent);\n\tauto classFile = &parent->file(classs->name() + \".cpp\");\n\n\tauto fragment = classFile->append(new CompositeFragment(classs, \"sections\"));\n\n\tauto imports = fragment->append(new CompositeFragment(classs, \"vertical\"));\n\tfor (auto node : *classs->subDeclarations())\n\t{\n\t\tif (auto ni = DCast(node)) *imports << visit(ni);\n\t\telse notAllowed(node);\n\t}\n\n\t*fragment << visit(classs);\n\n\treturn classFile;\n}\n\nSourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs)\n{\n\tif (!headerVisitor()) return visit(classs);\n\n\tauto fragment = new CompositeFragment(classs, \"spacedSections\");\n\t*fragment << visit(classs);\n\n\tauto filter = [](Method* method) { return !method->typeArguments()->isEmpty() ||\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmethod->modifiers()->isSet(OOModel::Modifier::Inline); };\n\t*fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), \"spacedSections\", filter);\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(Class* classs)\n{\n\tauto fragment = new CompositeFragment(classs);\n\n\tif (!headerVisitor())\n\t{\n\t\t\/\/TODO\n\t\tauto sections = fragment->append( new CompositeFragment(classs, \"sections\"));\n\t\t*sections << list(classs->enumerators(), ElementVisitor(data()), \"enumerators\");\n\t\t*sections << list(classs->classes(), this, \"sections\");\n\n\t\tauto filter = [](Method* method) { return method->typeArguments()->isEmpty() &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t!method->modifiers()->isSet(OOModel::Modifier::Inline); };\n\t\t*sections << list(classs->methods(), this, \"spacedSections\", filter);\n\t\t*sections << list(classs->fields(), this, \"vertical\");\n\t}\n\telse\n\t{\n\t\t*fragment << declarationComments(classs);\n\n\t\tif (!classs->typeArguments()->isEmpty())\n\t\t\t*fragment << list(classs->typeArguments(), ElementVisitor(data()), \"templateArgsList\");\n\n\t\t*fragment << printAnnotationsAndModifiers(classs);\n\t\tif (Class::ConstructKind::Class == classs->constructKind()) *fragment << \"class \";\n\t\telse if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << \"struct \";\n\t\telse if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << \"enum \";\n\t\telse notAllowed(classs);\n\n\t\tif (auto namespaceModule = classs->firstAncestorOfType())\n\t\t\t*fragment << namespaceModule->name().toUpper() + \"_API \";\n\n\t\t*fragment << classs->nameNode();\n\n\t\tif (!classs->baseClasses()->isEmpty())\n\t\t\t\/\/ TODO: inheritance modifiers like private, virtual... (not only public)\n\t\t\t*fragment << \" : public \" << list(classs->baseClasses(), ExpressionVisitor(data()), \"comma\");\n\n\t\tnotAllowed(classs->friends());\n\n\t\tauto sections = fragment->append( new CompositeFragment(classs, \"bodySections\"));\n\n\t\tif (classs->enumerators()->size() > 0)\n\t\t\terror(classs->enumerators(), \"Enum unhandled\"); \/\/ TODO\n\n\t\tauto publicSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); };\n\t\tbool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter);\n\t\tif (hasPublicSection)\n\t\t{\n\t\t\t*sections << \"public:\";\n\t\t\tsections->append(publicSection);\n\t\t}\n\n\t\tauto protectedSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); };\n\t\tbool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter);\n\t\tif (hasProtectedSection)\n\t\t{\n\t\t\tif (hasPublicSection) *sections << \"\\n\"; \/\/ add newline between two accessor sections\n\n\t\t\t*sections << \"protected:\";\n\t\t\tsections->append(protectedSection);\n\t\t}\n\n\t\tauto privateSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t !declaration->modifiers()->isSet(Modifier::Protected); };\n\t\tbool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter);\n\t\tif (hasPrivateSection)\n\t\t{\n\t\t\tif (hasPublicSection || hasProtectedSection) *sections << \"\\n\"; \/\/ add newline between two accessor sections\n\n\t\t\t*sections << \"private:\";\n\t\t\tsections->append(privateSection);\n\t\t}\n\n\t\t*fragment << \";\";\n\t}\n\n\treturn fragment;\n}\n\ntemplate\nbool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter)\n{\n\tauto subDeclarations = list(classs->subDeclarations(), this, \"sections\", filter);\n\tauto fields = list(classs->fields(), this, \"vertical\", filter);\n\tauto classes = list(classs->classes(), this, \"sections\", filter);\n\tauto methods = list(classs->methods(), this, \"sections\", filter);\n\n\t*section << subDeclarations << fields << classes << methods;\n\treturn !subDeclarations->fragments().empty() ||\n\t\t\t !fields->fragments().empty() ||\n\t\t\t !classes->fragments().empty() ||\n\t\t\t !methods->fragments().empty();\n}\n\nSourceFragment* DeclarationVisitor::visit(Method* method)\n{\n\tauto fragment = new CompositeFragment(method);\n\n\tif (headerVisitor())\n\t\t*fragment << declarationComments(method);\n\n\tif (!method->typeArguments()->isEmpty())\n\t\t*fragment << list(method->typeArguments(), ElementVisitor(data()), \"templateArgsList\");\n\n\tif (headerVisitor())\n\t\t*fragment << printAnnotationsAndModifiers(method);\n\telse\n\t\tif (method->modifiers()->isSet(Modifier::Inline))\n\t\t\t*fragment << new TextFragment(method->modifiers(), \"inline\") << \" \";\n\n\tif (method->results()->size() > 1)\n\t\terror(method->results(), \"Cannot have more than one return value in C++\");\n\n\tif (method->methodKind() != Method::MethodKind::Constructor &&\n\t\t method->methodKind() != Method::MethodKind::Destructor)\n\t{\n\t\tif (!method->results()->isEmpty())\n\t\t\t*fragment << expression(method->results()->at(0)->typeExpression()) << \" \";\n\t\telse\n\t\t\t*fragment << \"void \";\n\t}\n\n\tif (!headerVisitor())\n\t\tif (auto parentClass = method->firstAncestorOfType())\n\t\t\t*fragment << parentClass->name() << \"::\";\n\n\tif (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith(\"~\")) *fragment << \"~\";\n\t*fragment << method->nameNode();\n\n\t*fragment << list(method->arguments(), ElementVisitor(data()), \"argsList\");\n\tif (method->modifiers()->isSet(Modifier::Const))\n\t\t*fragment << \" \" << new TextFragment(method->modifiers(), \"const\");\n\n\tif (!headerVisitor())\n\t\tif (!method->memberInitializers()->isEmpty())\n\t\t\t*fragment << \" : \" << list(method->memberInitializers(), ElementVisitor(data()), \"comma\");\n\n\tif (!method->throws()->isEmpty())\n\t{\n\t\t*fragment << \" throw (\";\n\t\t*fragment << list(method->throws(), ExpressionVisitor(data()), \"comma\");\n\t\t*fragment << \")\";\n\t}\n\n\tif (headerVisitor())\n\t{\n\t\tif (method->modifiers()->isSet(Modifier::Override))\n\t\t\t\t*fragment << \" \" << new TextFragment(method->modifiers(), \"override\");\n\t\t*fragment << \";\";\n\t}\n\telse\n\t\t*fragment << list(method->items(), StatementVisitor(data()), \"body\");\n\n\tnotAllowed(method->subDeclarations());\n\tnotAllowed(method->memberInitializers());\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::declarationComments(Declaration* declaration)\n{\n\tif (auto commentNode = DCast(declaration->comment()))\n\t{\n\t\tauto commentFragment = new CompositeFragment(commentNode->lines(), \"declarationComment\");\n\t\tfor (auto line : *(commentNode->lines()))\n\t\t\t*commentFragment << line;\n\t\treturn commentFragment;\n\t}\n\n\treturn nullptr;\n}\n\nSourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration)\n{\n\tauto fragment = new CompositeFragment(variableDeclaration);\n\tif (headerVisitor())\n\t{\n\t\t*fragment << declarationComments(variableDeclaration);\n\t\t*fragment << printAnnotationsAndModifiers(variableDeclaration);\n\t\t*fragment << expression(variableDeclaration->typeExpression()) << \" \" << variableDeclaration->nameNode();\n\t\tif (variableDeclaration->initialValue())\n\t\t\t*fragment << \" = \" << expression(variableDeclaration->initialValue());\n\n\t\tif (!DCast(variableDeclaration->parent())) *fragment << \";\";\n\t}\n\telse\n\t{\n\t\tbool isField = DCast(variableDeclaration);\n\n\t\tif (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static))\n\t\t{\n\t\t\t*fragment << printAnnotationsAndModifiers(variableDeclaration);\n\t\t\t*fragment << expression(variableDeclaration->typeExpression()) << \" \";\n\n\t\t\tif (isField)\n\t\t\t\tif (auto parentClass = variableDeclaration->firstAncestorOfType())\n\t\t\t\t\t*fragment << parentClass->name() << \"::\";\n\n\t\t\t*fragment << variableDeclaration->nameNode();\n\t\t\tif (variableDeclaration->initialValue())\n\t\t\t\t*fragment << \" = \" << expression(variableDeclaration->initialValue());\n\n\t\t\tif (!DCast(variableDeclaration->parent())) *fragment << \";\";\n\t\t}\n\t}\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration)\n{\n\tauto fragment = new CompositeFragment(declaration, \"vertical\");\n\tif (!declaration->annotations()->isEmpty()) \/\/ avoid an extra new line if there are no annotations\n\t\t*fragment << list(declaration->annotations(), StatementVisitor(data()), \"vertical\");\n\tauto header = fragment->append(new CompositeFragment(declaration, \"space\"));\n\n\tif (declaration->modifiers()->isSet(Modifier::Static))\n\t\t*header << new TextFragment(declaration->modifiers(), \"static\");\n\n\tif (declaration->modifiers()->isSet(Modifier::Final))\n\t\t*header << new TextFragment(declaration->modifiers(), \"final\");\n\tif (declaration->modifiers()->isSet(Modifier::Abstract))\n\t\t*header << new TextFragment(declaration->modifiers(), \"abstract\");\n\n\tif (declaration->modifiers()->isSet(Modifier::Virtual))\n\t\t*header << new TextFragment(declaration->modifiers(), \"virtual\");\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(NameImport* nameImport)\n{\n\tauto fragment = new CompositeFragment(nameImport);\n\tnotAllowed(nameImport->annotations());\n\n\t*fragment << \"import \" << expression(nameImport->importedName());\n\tif (nameImport->importAll()) *fragment << \".*\";\n\t*fragment << \";\";\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti)\n{\n\tnotAllowed(eti);\n\treturn new TextFragment(eti);\n}\n\nSourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias)\n{\n\tauto fragment = new CompositeFragment(typeAlias);\n\t*fragment << \"using \" << typeAlias->nameNode() << \" = \" << expression(typeAlias->typeExpression()) << \";\";\n\treturn fragment;\n}\n}\nexport conversion methods\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"DeclarationVisitor.h\"\n#include \"ExpressionVisitor.h\"\n#include \"StatementVisitor.h\"\n#include \"ElementVisitor.h\"\n\n#include \"OOModel\/src\/declarations\/Project.h\"\n#include \"OOModel\/src\/declarations\/Module.h\"\n#include \"OOModel\/src\/declarations\/Class.h\"\n#include \"OOModel\/src\/declarations\/Declaration.h\"\n#include \"OOModel\/src\/declarations\/Method.h\"\n#include \"OOModel\/src\/declarations\/NameImport.h\"\n#include \"OOModel\/src\/declarations\/VariableDeclaration.h\"\n#include \"OOModel\/src\/declarations\/ExplicitTemplateInstantiation.h\"\n#include \"OOModel\/src\/declarations\/TypeAlias.h\"\n\n#include \"Export\/src\/tree\/SourceDir.h\"\n#include \"Export\/src\/tree\/SourceFile.h\"\n#include \"Export\/src\/tree\/CompositeFragment.h\"\n#include \"Export\/src\/tree\/TextFragment.h\"\n\n#include \"Comments\/src\/nodes\/CommentNode.h\"\n\nusing namespace Export;\nusing namespace OOModel;\n\nnamespace CppExport {\n\nSourceFragment* DeclarationVisitor::visit(Declaration* declaration)\n{\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\tif (auto castDeclaration = DCast(declaration)) return visit(castDeclaration);\n\n\tnotAllowed(declaration);\n\n\tauto fragment = new CompositeFragment(declaration);\n\t*fragment << \"Invalid Declaration\";\n\treturn fragment;\n}\n\nSourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent)\n{\n\tauto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, \"src\");\n\n\tfor (auto node : *project->projects()) visitProject(node, projectDir);\n\tfor (auto node : *project->modules()) visitModule(node, projectDir);\n\tfor (auto node : *project->classes()) visitTopLevelClass(node, projectDir);\n\n\tnotAllowed(project->methods());\n\tnotAllowed(project->fields());\n\n\treturn projectDir;\n}\n\nSourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent)\n{\n\tQ_ASSERT(parent);\n\tauto moduleDir = &parent->subDir(module->name());\n\n\tfor (auto node : *module->modules()) visitModule(node, moduleDir);\n\tfor (auto node : *module->classes()) visitTopLevelClass(node, moduleDir);\n\n\tnotAllowed(module->methods());\n\tnotAllowed(module->fields());\n\n\treturn moduleDir;\n}\n\nSourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent)\n{\n\tQ_ASSERT(parent);\n\tauto classFile = &parent->file(classs->name() + \".cpp\");\n\n\tauto fragment = classFile->append(new CompositeFragment(classs, \"sections\"));\n\n\tauto imports = fragment->append(new CompositeFragment(classs, \"vertical\"));\n\tfor (auto node : *classs->subDeclarations())\n\t{\n\t\tif (auto ni = DCast(node)) *imports << visit(ni);\n\t\telse notAllowed(node);\n\t}\n\n\t*fragment << visit(classs);\n\n\treturn classFile;\n}\n\nSourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs)\n{\n\tif (!headerVisitor()) return visit(classs);\n\n\tauto fragment = new CompositeFragment(classs, \"spacedSections\");\n\t*fragment << visit(classs);\n\n\tauto filter = [](Method* method) { return !method->typeArguments()->isEmpty() ||\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmethod->modifiers()->isSet(OOModel::Modifier::Inline); };\n\t*fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), \"spacedSections\", filter);\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(Class* classs)\n{\n\tauto fragment = new CompositeFragment(classs);\n\n\tif (!headerVisitor())\n\t{\n\t\t\/\/TODO\n\t\tauto sections = fragment->append( new CompositeFragment(classs, \"sections\"));\n\t\t*sections << list(classs->enumerators(), ElementVisitor(data()), \"enumerators\");\n\t\t*sections << list(classs->classes(), this, \"sections\");\n\n\t\tauto filter = [](Method* method) { return method->typeArguments()->isEmpty() &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t!method->modifiers()->isSet(OOModel::Modifier::Inline); };\n\t\t*sections << list(classs->methods(), this, \"spacedSections\", filter);\n\t\t*sections << list(classs->fields(), this, \"vertical\");\n\t}\n\telse\n\t{\n\t\t*fragment << declarationComments(classs);\n\n\t\tif (!classs->typeArguments()->isEmpty())\n\t\t\t*fragment << list(classs->typeArguments(), ElementVisitor(data()), \"templateArgsList\");\n\n\t\t*fragment << printAnnotationsAndModifiers(classs);\n\t\tif (Class::ConstructKind::Class == classs->constructKind()) *fragment << \"class \";\n\t\telse if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << \"struct \";\n\t\telse if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << \"enum \";\n\t\telse notAllowed(classs);\n\n\t\tif (auto namespaceModule = classs->firstAncestorOfType())\n\t\t\t*fragment << namespaceModule->name().toUpper() + \"_API \";\n\n\t\t*fragment << classs->nameNode();\n\n\t\tif (!classs->baseClasses()->isEmpty())\n\t\t\t\/\/ TODO: inheritance modifiers like private, virtual... (not only public)\n\t\t\t*fragment << \" : public \" << list(classs->baseClasses(), ExpressionVisitor(data()), \"comma\");\n\n\t\tnotAllowed(classs->friends());\n\n\t\tauto sections = fragment->append( new CompositeFragment(classs, \"bodySections\"));\n\n\t\tif (classs->enumerators()->size() > 0)\n\t\t\terror(classs->enumerators(), \"Enum unhandled\"); \/\/ TODO\n\n\t\tauto publicSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); };\n\t\tbool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter);\n\t\tif (hasPublicSection)\n\t\t{\n\t\t\t*sections << \"public:\";\n\t\t\tsections->append(publicSection);\n\t\t}\n\n\t\tauto protectedSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); };\n\t\tbool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter);\n\t\tif (hasProtectedSection)\n\t\t{\n\t\t\tif (hasPublicSection) *sections << \"\\n\"; \/\/ add newline between two accessor sections\n\n\t\t\t*sections << \"protected:\";\n\t\t\tsections->append(protectedSection);\n\t\t}\n\n\t\tauto privateSection = new CompositeFragment(classs, \"accessorSections\");\n\t\tauto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t !declaration->modifiers()->isSet(Modifier::Protected); };\n\t\tbool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter);\n\t\tif (hasPrivateSection)\n\t\t{\n\t\t\tif (hasPublicSection || hasProtectedSection) *sections << \"\\n\"; \/\/ add newline between two accessor sections\n\n\t\t\t*sections << \"private:\";\n\t\t\tsections->append(privateSection);\n\t\t}\n\n\t\t*fragment << \";\";\n\t}\n\n\treturn fragment;\n}\n\ntemplate\nbool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter)\n{\n\tauto subDeclarations = list(classs->subDeclarations(), this, \"sections\", filter);\n\tauto fields = list(classs->fields(), this, \"vertical\", filter);\n\tauto classes = list(classs->classes(), this, \"sections\", filter);\n\tauto methods = list(classs->methods(), this, \"sections\", filter);\n\n\t*section << subDeclarations << fields << classes << methods;\n\treturn !subDeclarations->fragments().empty() ||\n\t\t\t !fields->fragments().empty() ||\n\t\t\t !classes->fragments().empty() ||\n\t\t\t !methods->fragments().empty();\n}\n\nSourceFragment* DeclarationVisitor::visit(Method* method)\n{\n\tauto fragment = new CompositeFragment(method);\n\n\tif (headerVisitor())\n\t\t*fragment << declarationComments(method);\n\n\tif (!method->typeArguments()->isEmpty())\n\t\t*fragment << list(method->typeArguments(), ElementVisitor(data()), \"templateArgsList\");\n\n\tif (headerVisitor())\n\t\t*fragment << printAnnotationsAndModifiers(method);\n\telse\n\t\tif (method->modifiers()->isSet(Modifier::Inline))\n\t\t\t*fragment << new TextFragment(method->modifiers(), \"inline\") << \" \";\n\n\tif (method->results()->size() > 1)\n\t\terror(method->results(), \"Cannot have more than one return value in C++\");\n\n\tif (method->methodKind() == Method::MethodKind::Conversion)\n\t{\n\t\tif (!headerVisitor())\n\t\t\tif (auto parentClass = method->firstAncestorOfType())\n\t\t\t\t*fragment << parentClass->name() << \"::\";\n\t\t*fragment << \"operator \";\n\t}\n\n\tif (method->methodKind() != Method::MethodKind::Constructor &&\n\t\t method->methodKind() != Method::MethodKind::Destructor)\n\t{\n\t\tif (!method->results()->isEmpty())\n\t\t\t*fragment << expression(method->results()->at(0)->typeExpression()) << \" \";\n\t\telse\n\t\t\t*fragment << \"void \";\n\t}\n\n\tif (!headerVisitor() && method->methodKind() != Method::MethodKind::Conversion)\n\t\tif (auto parentClass = method->firstAncestorOfType())\n\t\t\t*fragment << parentClass->name() << \"::\";\n\n\tif (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith(\"~\")) *fragment << \"~\";\n\t*fragment << method->nameNode();\n\n\t*fragment << list(method->arguments(), ElementVisitor(data()), \"argsList\");\n\tif (method->modifiers()->isSet(Modifier::Const))\n\t\t*fragment << \" \" << new TextFragment(method->modifiers(), \"const\");\n\n\tif (!headerVisitor())\n\t\tif (!method->memberInitializers()->isEmpty())\n\t\t\t*fragment << \" : \" << list(method->memberInitializers(), ElementVisitor(data()), \"comma\");\n\n\tif (!method->throws()->isEmpty())\n\t{\n\t\t*fragment << \" throw (\";\n\t\t*fragment << list(method->throws(), ExpressionVisitor(data()), \"comma\");\n\t\t*fragment << \")\";\n\t}\n\n\tif (headerVisitor())\n\t{\n\t\tif (method->modifiers()->isSet(Modifier::Override))\n\t\t\t\t*fragment << \" \" << new TextFragment(method->modifiers(), \"override\");\n\t\t*fragment << \";\";\n\t}\n\telse\n\t\t*fragment << list(method->items(), StatementVisitor(data()), \"body\");\n\n\tnotAllowed(method->subDeclarations());\n\tnotAllowed(method->memberInitializers());\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::declarationComments(Declaration* declaration)\n{\n\tif (auto commentNode = DCast(declaration->comment()))\n\t{\n\t\tauto commentFragment = new CompositeFragment(commentNode->lines(), \"declarationComment\");\n\t\tfor (auto line : *(commentNode->lines()))\n\t\t\t*commentFragment << line;\n\t\treturn commentFragment;\n\t}\n\n\treturn nullptr;\n}\n\nSourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration)\n{\n\tauto fragment = new CompositeFragment(variableDeclaration);\n\tif (headerVisitor())\n\t{\n\t\t*fragment << declarationComments(variableDeclaration);\n\t\t*fragment << printAnnotationsAndModifiers(variableDeclaration);\n\t\t*fragment << expression(variableDeclaration->typeExpression()) << \" \" << variableDeclaration->nameNode();\n\t\tif (variableDeclaration->initialValue())\n\t\t\t*fragment << \" = \" << expression(variableDeclaration->initialValue());\n\n\t\tif (!DCast(variableDeclaration->parent())) *fragment << \";\";\n\t}\n\telse\n\t{\n\t\tbool isField = DCast(variableDeclaration);\n\n\t\tif (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static))\n\t\t{\n\t\t\t*fragment << printAnnotationsAndModifiers(variableDeclaration);\n\t\t\t*fragment << expression(variableDeclaration->typeExpression()) << \" \";\n\n\t\t\tif (isField)\n\t\t\t\tif (auto parentClass = variableDeclaration->firstAncestorOfType())\n\t\t\t\t\t*fragment << parentClass->name() << \"::\";\n\n\t\t\t*fragment << variableDeclaration->nameNode();\n\t\t\tif (variableDeclaration->initialValue())\n\t\t\t\t*fragment << \" = \" << expression(variableDeclaration->initialValue());\n\n\t\t\tif (!DCast(variableDeclaration->parent())) *fragment << \";\";\n\t\t}\n\t}\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration)\n{\n\tauto fragment = new CompositeFragment(declaration, \"vertical\");\n\tif (!declaration->annotations()->isEmpty()) \/\/ avoid an extra new line if there are no annotations\n\t\t*fragment << list(declaration->annotations(), StatementVisitor(data()), \"vertical\");\n\tauto header = fragment->append(new CompositeFragment(declaration, \"space\"));\n\n\tif (declaration->modifiers()->isSet(Modifier::Static))\n\t\t*header << new TextFragment(declaration->modifiers(), \"static\");\n\n\tif (declaration->modifiers()->isSet(Modifier::Final))\n\t\t*header << new TextFragment(declaration->modifiers(), \"final\");\n\tif (declaration->modifiers()->isSet(Modifier::Abstract))\n\t\t*header << new TextFragment(declaration->modifiers(), \"abstract\");\n\n\tif (declaration->modifiers()->isSet(Modifier::Virtual))\n\t\t*header << new TextFragment(declaration->modifiers(), \"virtual\");\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(NameImport* nameImport)\n{\n\tauto fragment = new CompositeFragment(nameImport);\n\tnotAllowed(nameImport->annotations());\n\n\t*fragment << \"import \" << expression(nameImport->importedName());\n\tif (nameImport->importAll()) *fragment << \".*\";\n\t*fragment << \";\";\n\n\treturn fragment;\n}\n\nSourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti)\n{\n\tnotAllowed(eti);\n\treturn new TextFragment(eti);\n}\n\nSourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias)\n{\n\tauto fragment = new CompositeFragment(typeAlias);\n\t*fragment << \"using \" << typeAlias->nameNode() << \" = \" << expression(typeAlias->typeExpression()) << \";\";\n\treturn fragment;\n}\n}\n<|endoftext|>"} {"text":"\/\/ GeometryTiler.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef _DEBUG\n #pragma comment(lib, \"lib\/FileGDBAPI.lib\")\n#else\n #pragma comment(lib, \"lib\/FileGDBAPID.lib\")\n#endif\n\n\/\/ Nicely logs the provided error message and error code.\nvoid LogError(std::wstring errorMessage, fgdbError errorCode)\n{\n std::wcout << errorMessage << std::endl;\n \n std::wstring errorText;\n FileGDBAPI::ErrorInfo::GetErrorDescription(errorCode, errorText);\n std::wcout << \"Error: \" << errorText << \"[\" << errorCode << \"]\" << std::endl;\n}\n\n\/\/ Processes an individual row.\nvoid ProcessRow(FileGDBAPI::Row& row)\n{\n \/\/ TODO this is a good point to move into a class. \n fgdbError result;\n FileGDBAPI::ShapeBuffer shapeBuffer;\n if ((result = row.GetGeometry(shapeBuffer)) != S_OK)\n {\n LogError(L\"Error loading the shape buffer!\", result);\n return;\n }\n}\n\n\/\/ Processes the provided Table.\nvoid ProcessTable(FileGDBAPI::Table& table)\n{\n std::string tableDefinition;\n\n fgdbError result;\n if ((result = table.GetDefinition(tableDefinition)) != S_OK)\n {\n LogError(L\"Error loading the table definition!\", result);\n return;\n }\n\n std::ofstream defFile(\"table.xml\");\n if (!defFile)\n {\n std::cout << \"Could not open the file to write the table definition to!\" << std::endl;\n return;\n }\n\n defFile << tableDefinition.c_str();\n defFile.close();\n std::cout << \"Table definition has been written to a readable file.\" << std::endl;\n\n std::string documentation;\n if ((result = table.GetDocumentation(documentation)) != S_OK)\n {\n LogError(L\"Error loading the table documentation!\", result);\n return;\n }\n\n std::ofstream docFile(\"documentation.xml\");\n if (!docFile)\n {\n std::cout << \"Could not open the file to write documentation to!\" << std::endl;\n return;\n }\n\n docFile << documentation.c_str();\n docFile.close();\n std::cout << \"Documentation has been written to a readable-file.\" << std::endl;\n\n FileGDBAPI::Envelope extent;\n if ((result = table.GetExtent(extent)) != S_OK)\n {\n LogError(L\"Error loading the table extent!\", result);\n return;\n }\n\n std::cout << \"Extent: [\" << extent.xMin << \", \" << extent.yMin << \", \" << extent.zMin << \"] to [\" \n << extent.xMax << \", \" << extent.yMax << \", \" << extent.zMax << \"]\" << std::endl;\n\n int rowCount;\n if ((result = table.GetRowCount(rowCount)) != S_OK)\n {\n LogError(L\"Error loading the table row count!\", result);\n return;\n }\n\n std::cout << \"Rows: \" << rowCount << std::endl;\n\n FileGDBAPI::EnumRows allRows;\n std::cout << \"Searching ALL rows in the database...\" << std::endl;\n if ((result = table.Search(L\"*\", L\"\", extent, true, allRows)) != S_OK)\n {\n LogError(L\"Error searching for all rows!\", result);\n return;\n }\n\n std::cout << \"Counting returned rows...\" << std::endl;\n FileGDBAPI::Row row;\n int foundRowCount = 0;\n while (allRows.Next(row) == S_OK)\n {\n ++foundRowCount;\n if (foundRowCount % 1000 == 0)\n {\n std::cout << \" \" << foundRowCount << std::endl;\n }\n\n ProcessRow(row);\n }\n\n allRows.Close();\n std::cout << \"Counted \" << foundRowCount << \" returned rows (versus \" << rowCount << \" total rows)\" << std::endl;\n if (foundRowCount != rowCount)\n {\n std::cout << \"Warning: Didn't read all the data from the database!\" << std::endl;\n return;\n }\n}\n\n\/\/ Processes the provided Geodatabase.\nvoid ProcessGeodatabase(FileGDBAPI::Geodatabase& geodatabase)\n{\n \/\/ Types\n std::vector datasetTypes;\n \n std::wcout << L\"Reading dataset types...\" << std::endl;\n fgdbError result;\n if ((result = geodatabase.GetDatasetTypes(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset types!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetTypes.size() << \" dataset types.\" << std::endl;\n for (unsigned int i = 0; i < datasetTypes.size(); i++)\n {\n std::wcout << L\" \" << datasetTypes[i] << std::endl;\n }\n\n \/\/ Relationship types\n std::vector datasetRelationshipTypes;\n\n std::wcout << L\"Reading dataset relationship types...\" << std::endl;\n if ((result = geodatabase.GetDatasetRelationshipTypes(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset relationship types!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetRelationshipTypes.size() << \" dataset relationship types.\" << std::endl;\n for (unsigned int i = 0; i < datasetRelationshipTypes.size(); i++)\n {\n std::wcout << L\" \" << datasetRelationshipTypes[i] << std::endl;\n }\n\n \/\/ Domains\n std::vector datasetDomains;\n\n std::wcout << L\"Reading dataset domains...\" << std::endl;\n if ((result = geodatabase.GetDomains(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset domains!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetDomains.size() << \" dataset domains.\" << std::endl;\n for (unsigned int i = 0; i < datasetDomains.size(); i++)\n {\n std::wcout << L\" \" << datasetDomains[i] << std::endl;\n }\n \n std::vector childDatasets;\n\n std::wcout << L\"Reading child datasets...\" << std::endl;\n if ((result = geodatabase.GetChildDatasets(L\"\\\\\", L\"\", childDatasets)) != S_OK)\n {\n LogError(L\"Error loading the child datasets!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << childDatasets.size() << \" child datasets.\" << std::endl;\n for (unsigned int i = 0; i < childDatasets.size(); i++)\n {\n std::wcout << L\" \" << childDatasets[i] << std::endl;\n }\n\n std::wstring datasetType;\n std::vector childDatasetDefinitions;\n\n std::wcout << L\"Reading primary dataset type...\" << std::endl;\n if ((result = geodatabase.GetChildDatasetDefinitions(L\"\\\\CONTOUR005_LINE\", datasetType, childDatasetDefinitions)) != S_OK)\n {\n LogError(L\"Error loading the primary dataset definition info!\", result);\n return;\n }\n\n std::wcout << L\"The primary dataset is of type '\" << datasetType << \"'.\" << std::endl;\n for (unsigned int i = 0; i < childDatasetDefinitions.size(); i++)\n {\n std::cout << \" \" << childDatasetDefinitions[i] << std::endl;\n }\n\n \/\/ Open the primary table\n FileGDBAPI::Table table;\n std::wcout << \"Reading in the primary table...\" << std::endl;\n if ((result = geodatabase.OpenTable(L\"\\\\CONTOUR005_LINE\", table)) != S_OK)\n {\n LogError(L\"Error loading the table!\", result);\n return;\n }\n\n std::wcout << \"Primary table opened.\" << std::endl;\n\n ProcessTable(table);\n\n std::wcout << \"Closing the primary table...\" << std::endl;\n if ((result = geodatabase.CloseTable(table)) != S_OK)\n {\n LogError(L\"Error closing the table!\", result);\n return;\n }\n\n std::wcout << \"Primary table closed.\" << std::endl;\n}\n\nint main(int argc, const char* argv[])\n{\n \/\/ Honestly this should be a command-line argument but this is just a basic converter tool.\n std::wstring databasePath =\n L\"C:\\\\Users\\\\Gustave\\\\Desktop\\\\KingCounty_GDB_topo_contour005_complete - Copy\\\\KingCounty_GDB_topo_contour005_complete.gdb\";\n\n FileGDBAPI::Geodatabase geodatabase;\n\n fgdbError result;\n std::wcout << \"Opening the db...\" << std::endl;\n if ((result = FileGDBAPI::OpenGeodatabase(databasePath, geodatabase)) != S_OK)\n {\n LogError(L\"Could not open the Geodatabase!\", result);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n return -1;\n }\n\n std::wcout << \"DB opened.\" << std::endl;\n\n ProcessGeodatabase(geodatabase);\n\n std::wcout << \"Closing DB...\" << std::endl;\n if ((result = FileGDBAPI::CloseGeodatabase(geodatabase)) != S_OK)\n {\n LogError(L\"Could not close the Geodatabase!\", result);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n return -1;\n }\n\n std::wcout << \"DB closed.\" << std::endl;\n std::system(\"pause\");\n return 0;\n}\n\nExtracting basic information. There are many, many points to process...\/\/ GeometryTiler.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef _DEBUG\n #pragma comment(lib, \"lib\/FileGDBAPI.lib\")\n#else\n #pragma comment(lib, \"lib\/FileGDBAPID.lib\")\n#endif\n\n\/\/ Nicely logs the provided error message and error code.\nvoid LogError(std::wstring errorMessage, fgdbError errorCode)\n{\n std::wcout << errorMessage << std::endl;\n \n std::wstring errorText;\n FileGDBAPI::ErrorInfo::GetErrorDescription(errorCode, errorText);\n std::wcout << \"Error: \" << errorText << \"[\" << errorCode << \"]\" << std::endl;\n}\n\n\/\/ Processes an individual row.\nlong totalPoints = 0;\nvoid ProcessRow(FileGDBAPI::Row& row)\n{\n \/\/ TODO this is a good point to move into a class. \n fgdbError result;\n FileGDBAPI::ShapeBuffer shapeBuffer;\n if ((result = row.GetGeometry(shapeBuffer)) != S_OK)\n {\n LogError(L\"Error loading the shape buffer!\", result);\n return;\n }\n\n double elevation; \/\/ Can be negative!\n if ((result = row.GetDouble(L\"ELEVATION\", elevation)) != S_OK)\n {\n LogError(L\"Error loading the shape buffer!\", result);\n return;\n }\n\n\n \/\/ At this point we know (from our saved table.xml file) that this is a polyline, and (from the above), we know the elevation.\n long type = shapeBuffer.shapeBuffer[0];\n \n \/\/ See the extended_shape_buffer_format.PDF file detailing the polyline shape\n long numParts = shapeBuffer.shapeBuffer[sizeof(long) + 4*sizeof(double)];\n long numPoints = shapeBuffer.shapeBuffer[sizeof(long) + 4*sizeof(double) + sizeof(long)];\n \n \/\/ std::cout << type << \" \" << numParts << \" \" << numPoints << std::endl;\n \/*if ((result = shapeBuffer.GetNumPoints(numPoints)) != S_OK)\n {\n LogError(L\"Error loading the number of points in the shape!\", result);\n return;\n }*\/\n \n totalPoints += numPoints;\n}\n\n\/\/ Processes the provided Table.\nvoid ProcessTable(FileGDBAPI::Table& table)\n{\n std::string tableDefinition;\n\n fgdbError result;\n if ((result = table.GetDefinition(tableDefinition)) != S_OK)\n {\n LogError(L\"Error loading the table definition!\", result);\n return;\n }\n\n std::ofstream defFile(\"table.xml\");\n if (!defFile)\n {\n std::cout << \"Could not open the file to write the table definition to!\" << std::endl;\n return;\n }\n\n defFile << tableDefinition.c_str();\n defFile.close();\n std::cout << \"Table definition has been written to a readable file.\" << std::endl;\n\n std::string documentation;\n if ((result = table.GetDocumentation(documentation)) != S_OK)\n {\n LogError(L\"Error loading the table documentation!\", result);\n return;\n }\n\n std::ofstream docFile(\"documentation.xml\");\n if (!docFile)\n {\n std::cout << \"Could not open the file to write documentation to!\" << std::endl;\n return;\n }\n\n docFile << documentation.c_str();\n docFile.close();\n std::cout << \"Documentation has been written to a readable-file.\" << std::endl;\n\n FileGDBAPI::Envelope extent;\n if ((result = table.GetExtent(extent)) != S_OK)\n {\n LogError(L\"Error loading the table extent!\", result);\n return;\n }\n\n std::cout << \"Extent: [\" << extent.xMin << \", \" << extent.yMin << \", \" << extent.zMin << \"] to [\" \n << extent.xMax << \", \" << extent.yMax << \", \" << extent.zMax << \"]\" << std::endl;\n\n int rowCount;\n if ((result = table.GetRowCount(rowCount)) != S_OK)\n {\n LogError(L\"Error loading the table row count!\", result);\n return;\n }\n\n std::cout << \"Rows: \" << rowCount << std::endl;\n\n FileGDBAPI::EnumRows allRows;\n std::cout << \"Searching ALL rows in the database...\" << std::endl;\n if ((result = table.Search(L\"*\", L\"\", extent, true, allRows)) != S_OK)\n {\n LogError(L\"Error searching for all rows!\", result);\n return;\n }\n\n std::cout << \"Counting returned rows...\" << std::endl;\n FileGDBAPI::Row row;\n int foundRowCount = 0;\n while (allRows.Next(row) == S_OK)\n {\n ++foundRowCount;\n if (foundRowCount % 1000 == 0)\n {\n std::cout << \" \" << foundRowCount << std::endl;\n }\n\n ProcessRow(row);\n }\n\n allRows.Close();\n std::cout << \"Counted \" << foundRowCount << \" returned rows (versus \" << rowCount << \" total rows)\" << std::endl;\n if (foundRowCount != rowCount)\n {\n std::cout << \"Warning: Didn't read all the data from the database!\" << std::endl;\n return;\n }\n\n std::cout << \"Total of \" << totalPoints << \" total geometry points.\" << std::endl;\n}\n\n\/\/ Processes the provided Geodatabase.\nvoid ProcessGeodatabase(FileGDBAPI::Geodatabase& geodatabase)\n{\n \/\/ Types\n std::vector datasetTypes;\n \n std::wcout << L\"Reading dataset types...\" << std::endl;\n fgdbError result;\n if ((result = geodatabase.GetDatasetTypes(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset types!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetTypes.size() << \" dataset types.\" << std::endl;\n for (unsigned int i = 0; i < datasetTypes.size(); i++)\n {\n std::wcout << L\" \" << datasetTypes[i] << std::endl;\n }\n\n \/\/ Relationship types\n std::vector datasetRelationshipTypes;\n\n std::wcout << L\"Reading dataset relationship types...\" << std::endl;\n if ((result = geodatabase.GetDatasetRelationshipTypes(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset relationship types!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetRelationshipTypes.size() << \" dataset relationship types.\" << std::endl;\n for (unsigned int i = 0; i < datasetRelationshipTypes.size(); i++)\n {\n std::wcout << L\" \" << datasetRelationshipTypes[i] << std::endl;\n }\n\n \/\/ Domains\n std::vector datasetDomains;\n\n std::wcout << L\"Reading dataset domains...\" << std::endl;\n if ((result = geodatabase.GetDomains(datasetTypes)) != S_OK)\n {\n LogError(L\"Error loading the dataset domains!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << datasetDomains.size() << \" dataset domains.\" << std::endl;\n for (unsigned int i = 0; i < datasetDomains.size(); i++)\n {\n std::wcout << L\" \" << datasetDomains[i] << std::endl;\n }\n \n std::vector childDatasets;\n\n std::wcout << L\"Reading child datasets...\" << std::endl;\n if ((result = geodatabase.GetChildDatasets(L\"\\\\\", L\"\", childDatasets)) != S_OK)\n {\n LogError(L\"Error loading the child datasets!\", result);\n return;\n }\n\n std::wcout << L\"Read \" << childDatasets.size() << \" child datasets.\" << std::endl;\n for (unsigned int i = 0; i < childDatasets.size(); i++)\n {\n std::wcout << L\" \" << childDatasets[i] << std::endl;\n }\n\n std::wstring datasetType;\n std::vector childDatasetDefinitions;\n\n std::wcout << L\"Reading primary dataset type...\" << std::endl;\n if ((result = geodatabase.GetChildDatasetDefinitions(L\"\\\\CONTOUR005_LINE\", datasetType, childDatasetDefinitions)) != S_OK)\n {\n LogError(L\"Error loading the primary dataset definition info!\", result);\n return;\n }\n\n std::wcout << L\"The primary dataset is of type '\" << datasetType << \"'.\" << std::endl;\n for (unsigned int i = 0; i < childDatasetDefinitions.size(); i++)\n {\n std::cout << \" \" << childDatasetDefinitions[i] << std::endl;\n }\n\n \/\/ Open the primary table\n FileGDBAPI::Table table;\n std::wcout << \"Reading in the primary table...\" << std::endl;\n if ((result = geodatabase.OpenTable(L\"\\\\CONTOUR005_LINE\", table)) != S_OK)\n {\n LogError(L\"Error loading the table!\", result);\n return;\n }\n\n std::wcout << \"Primary table opened.\" << std::endl;\n\n ProcessTable(table);\n\n std::wcout << \"Closing the primary table...\" << std::endl;\n if ((result = geodatabase.CloseTable(table)) != S_OK)\n {\n LogError(L\"Error closing the table!\", result);\n return;\n }\n\n std::wcout << \"Primary table closed.\" << std::endl;\n}\n\nint main(int argc, const char* argv[])\n{\n \/\/ Honestly this should be a command-line argument but this is just a basic converter tool.\n std::wstring databasePath =\n L\"C:\\\\Users\\\\Gustave\\\\Desktop\\\\KingCounty_GDB_topo_contour005_complete - Copy\\\\KingCounty_GDB_topo_contour005_complete.gdb\";\n\n FileGDBAPI::Geodatabase geodatabase;\n\n fgdbError result;\n std::wcout << \"Opening the db...\" << std::endl;\n if ((result = FileGDBAPI::OpenGeodatabase(databasePath, geodatabase)) != S_OK)\n {\n LogError(L\"Could not open the Geodatabase!\", result);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n return -1;\n }\n\n std::wcout << \"DB opened.\" << std::endl;\n\n ProcessGeodatabase(geodatabase);\n\n std::wcout << \"Closing DB...\" << std::endl;\n if ((result = FileGDBAPI::CloseGeodatabase(geodatabase)) != S_OK)\n {\n LogError(L\"Could not close the Geodatabase!\", result);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n return -1;\n }\n\n std::wcout << \"DB closed.\" << std::endl;\n std::system(\"pause\");\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project *\n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: David Rohr *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTVZEROOnlineCalibComponent.cxx\n @author David Rohr \n @brief VZERO online calib component\n*\/\n\n#include \"TTree.h\"\n#include \"TMap.h\"\n#include \"TObjString.h\"\n#include \"TDatime.h\"\n#include \"TH1F.h\"\n\n#include \"AliLog.h\"\n#include \"AliRunInfo.h\"\n#include \"AliGRPObject.h\"\n#include \"AliGeomManager.h\"\n\n#include \"AliVZERORecoParam.h\"\n\n#include \"AliHLTErrorGuard.h\"\n#include \"AliHLTDataTypes.h\"\n#include \"AliHLTVZEROOnlineCalibComponent.h\"\n#include \"AliESDVZERO.h\"\n\n#include \"AliESDVZEROfriend.h\"\n\nusing namespace std;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTVZEROOnlineCalibComponent)\n\n\/*\n * ---------------------------------------------------------------------------------\n * Constructor \/ Destructor\n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nAliHLTVZEROOnlineCalibComponent::AliHLTVZEROOnlineCalibComponent() :\n AliHLTProcessor(),\n fRunInfo(NULL), \n fVZERORecoParam(NULL),\n fHistMult(\"vzero\", \"vzero\", 100, 0, 1000),\n fEventModulo(0)\n {\n \/\/ an example component which implements the ALICE HLT processor\n \/\/ interface and does some analysis on the input raw data\n \/\/\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n \/\/\n \/\/ NOTE: all helper classes should be instantiated in DoInit()\n}\n\n\/\/ #################################################################################\nAliHLTVZEROOnlineCalibComponent::~AliHLTVZEROOnlineCalibComponent() {\n \/\/ see header file for class documentation\n}\n\n\/*\n * ---------------------------------------------------------------------------------\n * Public functions to implement AliHLTComponent's interface.\n * These functions are required for the registration process\n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nconst Char_t* AliHLTVZEROOnlineCalibComponent::GetComponentID() { \n \/\/ see header file for class documentation\n return \"VZEROOnlineCalib\";\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetInputDataTypes( vector& list) {\n \/\/ see header file for class documentation\n list.push_back(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO);\n}\n\n\/\/ #################################################################################\nAliHLTComponentDataType AliHLTVZEROOnlineCalibComponent::GetOutputDataType() \n{\n \/\/ see header file for class documentation\n return kAliHLTDataTypeHistogram|kAliHLTDataOriginOut;\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetOutputDataSize( ULong_t& constBase, Double_t& inputMultiplier ) {\n \/\/ see header file for class documentation\n constBase = 3000;\n inputMultiplier = 1;\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetOCDBObjectDescription( TMap* const targetMap) {\n \/\/ see header file for class documentation\n\n if (!targetMap) return;\n targetMap->Add(new TObjString(\"GRP\/GRP\/Data\"),\n\t\t new TObjString(\"GRP object - run information\"));\n targetMap->Add(new TObjString(\"GRP\/CTP\/CTPtiming\"),\n\t\t new TObjString(\"GRP object - CTP information\"));\n targetMap->Add(new TObjString(\"GRP\/CTP\/TimeAlign\"),\n\t\t new TObjString(\"GRP object - CTP information\"));\n targetMap->Add(new TObjString(\"GRP\/Calib\/LHCClockPhase\"),\n\t\t new TObjString(\"GRP object - time calibration\"));\n\n targetMap->Add(new TObjString(\"VZERO\/Calib\/Data\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Calib\/TimeDelays\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Calib\/TimeSlewing\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Trigger\/Data\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n return;\n}\n\n\/\/ #################################################################################\nAliHLTComponent* AliHLTVZEROOnlineCalibComponent::Spawn() {\n \/\/ see header file for class documentation\n return new AliHLTVZEROOnlineCalibComponent;\n}\n\n\/*\n * ---------------------------------------------------------------------------------\n * Protected functions to implement AliHLTComponent's interface.\n * These functions provide initialization as well as the actual processing\n * capabilities of the component. \n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoInit( Int_t argc, const Char_t** argv ) {\n \/\/ see header file for class documentation\n \n Int_t iResult=0;\n\n \/\/ -- Load GeomManager\n if(AliGeomManager::GetGeometry()==NULL){\n AliGeomManager::LoadGeometry();\n }\n \n \/\/ -- Read the component arguments\n if (iResult>=0) {\n iResult=ConfigureFromArgumentString(argc, argv);\n }\n\n \/\/ -- Get AliRunInfo variables\n \/\/ -----------------------------\n TObject* pOCDBEntry=LoadAndExtractOCDBObject(\"GRP\/GRP\/Data\");\n AliGRPObject* pGRP=pOCDBEntry?dynamic_cast(pOCDBEntry):NULL;\n \n TString beamType = \"\";\n TString lhcState = \"\";\n TString runType = \"\";\n Float_t beamEnergy = 0.;\n UInt_t activeDetectors = 0;\n \n if (pGRP) {\n lhcState = pGRP->GetLHCState(); \t \t \n beamType = pGRP->GetBeamType(); \n runType = pGRP->GetRunType(); \n beamEnergy = pGRP->GetBeamEnergy();\n activeDetectors = pGRP->GetDetectorMask();\n }\n \n \/\/ -- Initialize members\n \/\/ -----------------------\n do {\n if (iResult<0) break;\n\n \/\/ AliGRPManager grpMan;\n \/\/ Bool_t status = grpMan.ReadGRPEntry(); \/\/ Read the corresponding OCDB entry\n \/\/ status = grpMan.SetMagField(); \/\/ Set global field instanton\n \/\/ AliRunInfo *runInfo = grpMan.GetRunInfo(); \/\/ Get instance of run info\n\n fRunInfo = new AliRunInfo(lhcState.Data(), beamType.Data(),\n\t\t\t beamEnergy, runType.Data(), activeDetectors);\n if (!fRunInfo) {\n iResult=-ENOMEM;\n break;\n }\n\n fVZERORecoParam = new AliVZERORecoParam;\n if (!fVZERORecoParam) {\n iResult=-ENOMEM;\n break;\n } \n\n \/\/ implement further initialization\n } while (0);\n\n if (iResult<0) {\n \/\/ implement cleanup\n\n if (fVZERORecoParam)\n delete fVZERORecoParam;\n fVZERORecoParam = NULL;\n\n if (fRunInfo)\n delete fRunInfo;\n fRunInfo = NULL;\n }\n\n return iResult;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::ScanConfigurationArgument(Int_t \/*argc*\/, const Char_t** argv) {\n Int_t ii =0;\n TString argument=argv[ii];\n\n if (argument.IsNull()) return 0;\n\n return 0;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoDeinit() {\n \/\/ see header file for class documentation\n\n if (fVZERORecoParam)\n delete fVZERORecoParam;\n fVZERORecoParam = NULL;\n \n if (fRunInfo)\n delete fRunInfo;\n fRunInfo = NULL;\n \n return 0;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoEvent(const AliHLTComponentEventData& \/*evtData*\/,\n\t\t\t\t\tAliHLTComponentTriggerData& \/*trigData*\/) {\n \/\/ see header file for class documentation\n Int_t iResult=0;\n\n \/\/ -- Only use data event\n if (!IsDataEvent()) \n return 0;\n\n \n \/\/Get input data, and proceed if we got a VZERO ESD object\n const AliESDVZERO* esdVZERO = dynamic_cast(GetFirstInputObject(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO, \"AliESDVZERO\"));\n if (esdVZERO)\n {\n \/\/Just some example, create histogram with VZero multiplicity.\n float vZEROMultiplicity = 0.f;\n for (int i = 0;i < 64;i++) vZEROMultiplicity += esdVZERO->GetMultiplicity(i);\n fHistMult.Fill(vZEROMultiplicity);\n \/\/vZEROTriggerChargeA = esdVZERO->GetTriggerChargeA();\n \/\/vZEROTriggerChargeC = esdVZERO->GetTriggerChargeC();\n }\n \n \/\/If the histogram is not empty, we send it out every 16th event (to collect some statistics).\n \/\/Depending on the pushback period set for the component, it might not be send out every time, but only after a certain amount of time. (order of 3 minutes)\n \/\/We check whether it was really sent out, and only if so, we reset the histogram.\n \/\/The ZMQ merging component that sits at the end of the chain will receive all histograms from all concurrent VZEROOnlineCalib components, and merge them to the final histogram.\n if ((++fEventModulo % 16 == 0) && fHistMult.GetEntries() && PushBack(&fHistMult, kAliHLTDataTypeHistogram|kAliHLTDataOriginHLT) > 0) fHistMult.Reset();\n \n return iResult;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::Reconfigure(const Char_t* cdbEntry, const Char_t* chainId) {\n \/\/ see header file for class documentation\n\n Int_t iResult=0;\n return iResult;\n}\n\nPlace member TH1 to top root directory\/\/ $Id$\n\/**************************************************************************\n * This file is property of and copyright by the ALICE HLT Project *\n * ALICE Experiment at CERN, All rights reserved. *\n * *\n * Primary Authors: David Rohr *\n * for The ALICE HLT Project. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/** @file AliHLTVZEROOnlineCalibComponent.cxx\n @author David Rohr \n @brief VZERO online calib component\n*\/\n\n#include \"TTree.h\"\n#include \"TMap.h\"\n#include \"TObjString.h\"\n#include \"TDatime.h\"\n#include \"TH1F.h\"\n\n#include \"AliLog.h\"\n#include \"AliRunInfo.h\"\n#include \"AliGRPObject.h\"\n#include \"AliGeomManager.h\"\n\n#include \"AliVZERORecoParam.h\"\n\n#include \"AliHLTErrorGuard.h\"\n#include \"AliHLTDataTypes.h\"\n#include \"AliHLTVZEROOnlineCalibComponent.h\"\n#include \"AliESDVZERO.h\"\n\n#include \"AliESDVZEROfriend.h\"\n\nusing namespace std;\n\n\/** ROOT macro for the implementation of ROOT specific class methods *\/\nClassImp(AliHLTVZEROOnlineCalibComponent)\n\n\/*\n * ---------------------------------------------------------------------------------\n * Constructor \/ Destructor\n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nAliHLTVZEROOnlineCalibComponent::AliHLTVZEROOnlineCalibComponent() :\n AliHLTProcessor(),\n fRunInfo(NULL), \n fVZERORecoParam(NULL),\n fHistMult(\"vzero\", \"vzero\", 100, 0, 1000),\n fEventModulo(0)\n {\n \/\/ an example component which implements the ALICE HLT processor\n \/\/ interface and does some analysis on the input raw data\n \/\/\n \/\/ see header file for class documentation\n \/\/ or\n \/\/ refer to README to build package\n \/\/ or\n \/\/ visit http:\/\/web.ift.uib.no\/~kjeks\/doc\/alice-hlt\n \/\/\n \/\/ NOTE: all helper classes should be instantiated in DoInit()\n fHistMult.SetDirectory(0);\n}\n\n\/\/ #################################################################################\nAliHLTVZEROOnlineCalibComponent::~AliHLTVZEROOnlineCalibComponent() {\n \/\/ see header file for class documentation\n}\n\n\/*\n * ---------------------------------------------------------------------------------\n * Public functions to implement AliHLTComponent's interface.\n * These functions are required for the registration process\n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nconst Char_t* AliHLTVZEROOnlineCalibComponent::GetComponentID() { \n \/\/ see header file for class documentation\n return \"VZEROOnlineCalib\";\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetInputDataTypes( vector& list) {\n \/\/ see header file for class documentation\n list.push_back(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO);\n}\n\n\/\/ #################################################################################\nAliHLTComponentDataType AliHLTVZEROOnlineCalibComponent::GetOutputDataType() \n{\n \/\/ see header file for class documentation\n return kAliHLTDataTypeHistogram|kAliHLTDataOriginOut;\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetOutputDataSize( ULong_t& constBase, Double_t& inputMultiplier ) {\n \/\/ see header file for class documentation\n constBase = 3000;\n inputMultiplier = 1;\n}\n\n\/\/ #################################################################################\nvoid AliHLTVZEROOnlineCalibComponent::GetOCDBObjectDescription( TMap* const targetMap) {\n \/\/ see header file for class documentation\n\n if (!targetMap) return;\n targetMap->Add(new TObjString(\"GRP\/GRP\/Data\"),\n\t\t new TObjString(\"GRP object - run information\"));\n targetMap->Add(new TObjString(\"GRP\/CTP\/CTPtiming\"),\n\t\t new TObjString(\"GRP object - CTP information\"));\n targetMap->Add(new TObjString(\"GRP\/CTP\/TimeAlign\"),\n\t\t new TObjString(\"GRP object - CTP information\"));\n targetMap->Add(new TObjString(\"GRP\/Calib\/LHCClockPhase\"),\n\t\t new TObjString(\"GRP object - time calibration\"));\n\n targetMap->Add(new TObjString(\"VZERO\/Calib\/Data\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Calib\/TimeDelays\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Calib\/TimeSlewing\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n targetMap->Add(new TObjString(\"VZERO\/Trigger\/Data\"),\n\t\t new TObjString(\"VZERO calibration object\"));\n return;\n}\n\n\/\/ #################################################################################\nAliHLTComponent* AliHLTVZEROOnlineCalibComponent::Spawn() {\n \/\/ see header file for class documentation\n return new AliHLTVZEROOnlineCalibComponent;\n}\n\n\/*\n * ---------------------------------------------------------------------------------\n * Protected functions to implement AliHLTComponent's interface.\n * These functions provide initialization as well as the actual processing\n * capabilities of the component. \n * ---------------------------------------------------------------------------------\n *\/\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoInit( Int_t argc, const Char_t** argv ) {\n \/\/ see header file for class documentation\n \n Int_t iResult=0;\n\n \/\/ -- Load GeomManager\n if(AliGeomManager::GetGeometry()==NULL){\n AliGeomManager::LoadGeometry();\n }\n \n \/\/ -- Read the component arguments\n if (iResult>=0) {\n iResult=ConfigureFromArgumentString(argc, argv);\n }\n\n \/\/ -- Get AliRunInfo variables\n \/\/ -----------------------------\n TObject* pOCDBEntry=LoadAndExtractOCDBObject(\"GRP\/GRP\/Data\");\n AliGRPObject* pGRP=pOCDBEntry?dynamic_cast(pOCDBEntry):NULL;\n \n TString beamType = \"\";\n TString lhcState = \"\";\n TString runType = \"\";\n Float_t beamEnergy = 0.;\n UInt_t activeDetectors = 0;\n \n if (pGRP) {\n lhcState = pGRP->GetLHCState(); \t \t \n beamType = pGRP->GetBeamType(); \n runType = pGRP->GetRunType(); \n beamEnergy = pGRP->GetBeamEnergy();\n activeDetectors = pGRP->GetDetectorMask();\n }\n \n \/\/ -- Initialize members\n \/\/ -----------------------\n do {\n if (iResult<0) break;\n\n \/\/ AliGRPManager grpMan;\n \/\/ Bool_t status = grpMan.ReadGRPEntry(); \/\/ Read the corresponding OCDB entry\n \/\/ status = grpMan.SetMagField(); \/\/ Set global field instanton\n \/\/ AliRunInfo *runInfo = grpMan.GetRunInfo(); \/\/ Get instance of run info\n\n fRunInfo = new AliRunInfo(lhcState.Data(), beamType.Data(),\n\t\t\t beamEnergy, runType.Data(), activeDetectors);\n if (!fRunInfo) {\n iResult=-ENOMEM;\n break;\n }\n\n fVZERORecoParam = new AliVZERORecoParam;\n if (!fVZERORecoParam) {\n iResult=-ENOMEM;\n break;\n } \n\n \/\/ implement further initialization\n } while (0);\n\n if (iResult<0) {\n \/\/ implement cleanup\n\n if (fVZERORecoParam)\n delete fVZERORecoParam;\n fVZERORecoParam = NULL;\n\n if (fRunInfo)\n delete fRunInfo;\n fRunInfo = NULL;\n }\n\n return iResult;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::ScanConfigurationArgument(Int_t \/*argc*\/, const Char_t** argv) {\n Int_t ii =0;\n TString argument=argv[ii];\n\n if (argument.IsNull()) return 0;\n\n return 0;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoDeinit() {\n \/\/ see header file for class documentation\n\n if (fVZERORecoParam)\n delete fVZERORecoParam;\n fVZERORecoParam = NULL;\n \n if (fRunInfo)\n delete fRunInfo;\n fRunInfo = NULL;\n \n return 0;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::DoEvent(const AliHLTComponentEventData& \/*evtData*\/,\n\t\t\t\t\tAliHLTComponentTriggerData& \/*trigData*\/) {\n \/\/ see header file for class documentation\n Int_t iResult=0;\n\n \/\/ -- Only use data event\n if (!IsDataEvent()) \n return 0;\n\n \n \/\/Get input data, and proceed if we got a VZERO ESD object\n const AliESDVZERO* esdVZERO = dynamic_cast(GetFirstInputObject(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO, \"AliESDVZERO\"));\n if (esdVZERO)\n {\n \/\/Just some example, create histogram with VZero multiplicity.\n float vZEROMultiplicity = 0.f;\n for (int i = 0;i < 64;i++) vZEROMultiplicity += esdVZERO->GetMultiplicity(i);\n fHistMult.Fill(vZEROMultiplicity);\n \/\/vZEROTriggerChargeA = esdVZERO->GetTriggerChargeA();\n \/\/vZEROTriggerChargeC = esdVZERO->GetTriggerChargeC();\n }\n \n \/\/If the histogram is not empty, we send it out every 16th event (to collect some statistics).\n \/\/Depending on the pushback period set for the component, it might not be send out every time, but only after a certain amount of time. (order of 3 minutes)\n \/\/We check whether it was really sent out, and only if so, we reset the histogram.\n \/\/The ZMQ merging component that sits at the end of the chain will receive all histograms from all concurrent VZEROOnlineCalib components, and merge them to the final histogram.\n if ((++fEventModulo % 16 == 0) && fHistMult.GetEntries() && PushBack(&fHistMult, kAliHLTDataTypeHistogram|kAliHLTDataOriginHLT) > 0) fHistMult.Reset();\n \n return iResult;\n}\n\n\/\/ #################################################################################\nInt_t AliHLTVZEROOnlineCalibComponent::Reconfigure(const Char_t* cdbEntry, const Char_t* chainId) {\n \/\/ see header file for class documentation\n\n Int_t iResult=0;\n return iResult;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_POSIX\n#include \n#include \n#include \n#include \n#if defined(__APPLE__) && defined(__MACH__)\n#include \n#endif\n#include \n#include \n#include \n#elif qPlatform_Windows\n#include \n#endif\n#include \"..\/Math\/Common.h\"\n\n#include \"Debugger.h\"\n\nusing namespace Stroika::Foundation;\n\n#ifndef __has_builtin\n#define __has_builtin(x) 0 \/\/ Compatibility with non-clang compilers.\n#endif\n\n#if qPlatform_Linux\nnamespace {\n \/\/ From https:\/\/stackoverflow.com\/questions\/3596781\/how-to-detect-if-the-current-process-is-being-run-by-gdb\n bool debuggerIsAttached_ ()\n {\n char buf[4096];\n const int status_fd = ::open (\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n const ssize_t num_read = ::read (status_fd, buf, sizeof (buf) - 1);\n ::close (status_fd);\n if (num_read <= 0)\n return false;\n buf[num_read] = '\\0';\n constexpr char tracerPidString[] = \"TracerPid:\";\n const auto tracer_pid_ptr = ::strstr (buf, tracerPidString);\n if (!tracer_pid_ptr)\n return false;\n for (const char* characterPtr = tracer_pid_ptr + sizeof (tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr) {\n if (::isspace (*characterPtr))\n continue;\n else\n return ::isdigit (*characterPtr) != 0 && *characterPtr != '0';\n }\n return false;\n }\n}\n#endif\n\n#if qPlatform_MacOS\nnamespace {\n \/\/ https:\/\/stackoverflow.com\/questions\/2200277\/detecting-debugger-on-mac-os-x\n\n \/\/ Returns true if the current process is being debugged (either\n \/\/ running under the debugger or has a debugger attached post facto).\n bool AmIBeingDebugged_ ()\n {\n \/\/ Initialize the flags so that, if sysctl fails for some bizarre\n \/\/ reason, we get a predictable result.\n kinfo_proc info{};\n \/\/ Initialize mib, which tells sysctl the info we want, in this case\n \/\/ we're looking for information about a specific process ID.\n int mib[4] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid ()};\n size_t size = sizeof (info);\n int junk = sysctl (mib, sizeof (mib) \/ sizeof (*mib), &info, &size, NULL, 0);\n Assert (junk == 0);\n return (info.kp_proc.p_flag & P_TRACED) != 0;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ************************ Debug::IsThisProcessBeingDebugged **********************\n ********************************************************************************\n *\/\noptional Debug::IsThisProcessBeingDebugged ()\n{\n#if qPlatform_Linux\n return debuggerIsAttached_ ();\n#endif\n#if qPlatform_MacOS\n return AmIBeingDebugged_ ();\n#endif\n#if qPlatform_POSIX\n#if 0\n \/\/ Not a good approach - see https:\/\/stackoverflow.com\/questions\/3596781\/how-to-detect-if-the-current-process-is-being-run-by-gdb\n return ptrace (PTRACE_TRACEME, 0, NULL, 0) == -1;\n#endif\n#endif\n#if qPlatform_Windows\n return ::IsDebuggerPresent ();\n#endif\n return nullopt;\n}\n\n\/*\n ********************************************************************************\n ************************ Debug::DropIntoDebuggerIfPresent **********************\n ********************************************************************************\n *\/\nvoid Debug::DropIntoDebuggerIfPresent ()\n{\n if (IsThisProcessBeingDebugged () == true) {\n#if __has_builtin(__builtin_trap) || defined(__GNUC__)\n __builtin_trap ();\n#elif qPlatform_POSIX\n raise (SIGTRAP);\n#elif qPlatform_Windows\n ::DebugBreak ();\n#else\n abort ();\n#endif\n }\n}\nminor code cleanups\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_POSIX\n#include \n#include \n#include \n#include \n#if defined(__APPLE__) && defined(__MACH__)\n#include \n#endif\n#include \n#include \n#include \n#elif qPlatform_Windows\n#include \n#endif\n#include \"..\/Math\/Common.h\"\n\n#include \"Debugger.h\"\n\nusing namespace Stroika::Foundation;\n\n#ifndef __has_builtin\n#define __has_builtin(x) 0 \/\/ Compatibility with non-clang compilers.\n#endif\n\n#if qPlatform_Linux\nnamespace {\n \/\/ From https:\/\/stackoverflow.com\/questions\/3596781\/how-to-detect-if-the-current-process-is-being-run-by-gdb\n bool DebuggerIsAttached_ ()\n {\n char buf[4096];\n const int status_fd = ::open (\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n const ssize_t num_read = ::read (status_fd, buf, sizeof (buf) - 1);\n ::close (status_fd);\n if (num_read <= 0)\n return false;\n buf[num_read] = '\\0';\n constexpr char tracerPidString[] = \"TracerPid:\";\n const auto tracer_pid_ptr = ::strstr (buf, tracerPidString);\n if (!tracer_pid_ptr)\n return false;\n for (const char* characterPtr = tracer_pid_ptr + sizeof (tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr) {\n if (::isspace (*characterPtr))\n continue;\n else\n return ::isdigit (*characterPtr) != 0 && *characterPtr != '0';\n }\n return false;\n }\n}\n#endif\n\n#if qPlatform_MacOS\nnamespace {\n \/\/ https:\/\/stackoverflow.com\/questions\/2200277\/detecting-debugger-on-mac-os-x\n\n \/\/ Returns true if the current process is being debugged (either\n \/\/ running under the debugger or has a debugger attached post facto).\n bool DebuggerIsAttached_ ()\n {\n \/\/ Initialize the flags so that, if sysctl fails for some bizarre\n \/\/ reason, we get a predictable result.\n kinfo_proc info{};\n \/\/ Initialize mib, which tells sysctl the info we want, in this case\n \/\/ we're looking for information about a specific process ID.\n int mib[4] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid ()};\n size_t size = sizeof (info);\n int junk = sysctl (mib, sizeof (mib) \/ sizeof (*mib), &info, &size, NULL, 0);\n Assert (junk == 0);\n return (info.kp_proc.p_flag & P_TRACED) != 0;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ************************ Debug::IsThisProcessBeingDebugged **********************\n ********************************************************************************\n *\/\noptional Debug::IsThisProcessBeingDebugged ()\n{\n#if qPlatform_Linux\n return DebuggerIsAttached_ ();\n#endif\n#if qPlatform_MacOS\n return DebuggerIsAttached_ ();\n#endif\n#if qPlatform_POSIX\n#if 0\n \/\/ Not a good approach - see https:\/\/stackoverflow.com\/questions\/3596781\/how-to-detect-if-the-current-process-is-being-run-by-gdb\n return ptrace (PTRACE_TRACEME, 0, NULL, 0) == -1;\n#endif\n#endif\n#if qPlatform_Windows\n return ::IsDebuggerPresent ();\n#endif\n return nullopt;\n}\n\n\/*\n ********************************************************************************\n ************************ Debug::DropIntoDebuggerIfPresent **********************\n ********************************************************************************\n *\/\nvoid Debug::DropIntoDebuggerIfPresent ()\n{\n if (IsThisProcessBeingDebugged () == true) {\n#if __has_builtin(__builtin_trap) || defined(__GNUC__)\n __builtin_trap ();\n#elif qPlatform_POSIX\n raise (SIGTRAP);\n#elif qPlatform_Windows\n ::DebugBreak ();\n#else\n abort ();\n#endif\n }\n}\n<|endoftext|>"} {"text":"\n#include \"tablemodelanovamodel.h\"\n\n#include \n#include \n\n#include \"utils.h\"\n#include \n\n#include \"options\/optionboolean.h\"\n\nusing namespace std;\n\nTableModelAnovaModel::TableModelAnovaModel(QObject *parent)\n\t: TableModel(parent)\n{\n\t_boundTo = NULL;\n\t_customModel = false;\n\n\t_terms.setSortParent(_variables);\n}\n\nQVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const\n{\n\tif (_boundTo == NULL || index.isValid() == false)\n\t\treturn QVariant();\n\n\tif (role == Qt::DisplayRole)\n\t{\n\t\tint colNo = index.column();\n\t\tint rowNo = index.row();\n\t\tOptions *row = _rows.at(rowNo);\n\n\t\tif (colNo == 0) {\n\n\t\t\tOptionTerms *termOption = static_cast(row->get(0));\n\t\t\tTerm t(termOption->value().front());\n\t\t\treturn t.asQString();\n\t\t}\n\t}\n\telse if (role == Qt::CheckStateRole)\n\t{\n\t\tint colNo = index.column();\n\t\tint rowNo = index.row();\n\t\tOptions *row = _rows.at(rowNo);\n\n\t\tif (colNo == 1)\n\t\t{\n\t\t\tOptionBoolean *booleanOption = static_cast(row->get(1));\n\t\t\treturn booleanOption->value() ? Qt::Checked : Qt::Unchecked;\n\t\t}\n\t}\n\n\treturn QVariant();\n}\n\nint TableModelAnovaModel::rowCount(const QModelIndex &) const\n{\n\tif (_boundTo == NULL)\n\t\treturn 0;\n\n\treturn _rows.size();\n}\n\nint TableModelAnovaModel::columnCount(const QModelIndex &) const\n{\n\tif (_boundTo == NULL)\n\t\treturn 0;\n\n\treturn _boundTo->rowTemplate()->size();\n}\n\nbool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n\tif (index.isValid() == false)\n\t\treturn false;\n\n\tif (index.column() == 1 && role == Qt::CheckStateRole)\n\t{\n\t\tOptions *row = _rows.at(index.row());\n\t\tOptionBoolean *booleanOption = static_cast(row->get(1));\n\t\tbooleanOption->setValue(value.toInt() == Qt::Checked);\n\n\t\t_boundTo->setValue(_rows);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nQStringList TableModelAnovaModel::mimeTypes() const\n{\n\tQStringList types;\n\n\ttypes << \"application\/vnd.list.term\";\n\n\treturn types;\n}\n\nvoid TableModelAnovaModel::setVariables(const Terms &variables)\n{\n\tbeginResetModel();\n\n\t_variables.set(variables);\n\n\tif (_customModel)\n\t{\n\t\tTerms terms = _terms;\n\t\tterms.discardWhatDoesntContainTheseComponents(_variables);\n\t\tif (terms.size() != _terms.size())\n\t\t\tsetTerms(terms);\n\t}\n\telse\n\t{\n\t\tTerms terms = _variables.crossCombinations();\n\t\tif (terms != _terms)\n\t\t\tsetTerms(terms);\n\t}\n\n\temit variablesAvailableChanged();\n\n\tendResetModel();\n}\n\nconst Terms &TableModelAnovaModel::variables() const\n{\n\treturn _variables;\n}\n\nvoid TableModelAnovaModel::setCustomModelMode(bool on)\n{\n\t_customModel = on;\n\n\tif (_customModel)\n\t\tclear();\n\telse\n\t\tsetTerms(_variables.crossCombinations());\n}\n\nvoid TableModelAnovaModel::bindTo(Option *option)\n{\n\t_boundTo = dynamic_cast(option);\n}\n\nvoid TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes)\n{\n\t\/\/ sort indices, and delete from end to beginning\n\n\tQModelIndexList sorted = indexes;\n\tqSort(sorted.begin(), sorted.end(), qGreater());\n\n\tint lastRowDeleted = -1;\n\n\tTerms terms = _terms;\n\n\tforeach (const QModelIndex &index, sorted)\n\t{\n\t\tint rowNo = index.row();\n\t\tif (rowNo != lastRowDeleted)\n\t\t\tterms.remove(index.row());\n\t\tlastRowDeleted = rowNo;\n\t}\n\n\tsetTerms(terms);\n}\n\nconst Terms &TableModelAnovaModel::terms() const\n{\n\treturn _terms;\n}\n\nbool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const\n{\n\tQ_UNUSED(action);\n\tQ_UNUSED(row);\n\tQ_UNUSED(column);\n\tQ_UNUSED(parent);\n\n\tif (mimeTypes().contains(\"application\/vnd.list.term\"))\n\t{\n\t\tQByteArray encodedData = data->data(\"application\/vnd.list.term\");\n\t\tQDataStream stream(&encodedData, QIODevice::ReadOnly);\n\n\t\tif (stream.atEnd())\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType)\n{\n\tif (action == Qt::IgnoreAction)\n\t\treturn true;\n\n\tif ( ! canDropMimeData(data, action, row, column, parent))\n\t\treturn false;\n\n\tif ( ! data->hasFormat(\"application\/vnd.list.term\"))\n\t\treturn false;\n\n\n\tQByteArray encodedData = data->data(\"application\/vnd.list.term\");\n\n\tTerms dropped;\n\tdropped.setSortParent(_variables);\n\tdropped.set(encodedData);\n\n\tTerms newTerms;\n\n\tswitch (assignType)\n\t{\n\tcase Cross:\n\t\tnewTerms = dropped.crossCombinations();\n\t\tbreak;\n\tcase Interaction:\n\t\tnewTerms = dropped.wayCombinations(dropped.size());\n\t\tbreak;\n\tcase MainEffects:\n\t\tnewTerms = dropped.wayCombinations(1);\n\t\tbreak;\n\tcase All2Way:\n\t\tnewTerms = dropped.wayCombinations(2);\n\t\tbreak;\n\tcase All3Way:\n\t\tnewTerms = dropped.wayCombinations(3);\n\t\tbreak;\n\tcase All4Way:\n\t\tnewTerms = dropped.wayCombinations(4);\n\t\tbreak;\n\tcase All5Way:\n\t\tnewTerms = dropped.wayCombinations(5);\n\t\tbreak;\n\tdefault:\n\t\t(void)newTerms;\n\t}\n\n\tassign(newTerms);\n\n\treturn true;\n}\n\nbool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)\n{\n\treturn dropMimeData(data, action, row, column, parent, Cross);\n}\n\nQMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const\n{\n\t\/* returns dummy data. when the user drags entries away from this listbox\n\t * it means that they're deleting entries, so there's no point populating\n\t * this data object properly\n\t *\/\n\n\tQ_UNUSED(indexes);\n\n\tQMimeData *mimeData = new QMimeData();\n\tQByteArray encodedData;\n\n\tQDataStream dataStream(&encodedData, QIODevice::WriteOnly);\n\n\tdataStream << 0;\n\n\tmimeData->setData(\"application\/vnd.list.term\", encodedData);\n\n\treturn mimeData;\n}\n\nQt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const\n{\n\tif (index.isValid())\n\t{\n\t\tif (index.column() == 0)\n\t\t\treturn Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;\n\t\telse\n\t\t\treturn Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;\n\t}\n\telse\n\t{\n\t\treturn Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;\n\t}\n}\n\nQVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\t\n\tif (role == Qt::DisplayRole && orientation == Qt::Horizontal)\n\t{\n\t\tif (section == 0)\n\t\t\treturn \"Model Terms\";\n\t\tif (section == 1)\n\t\t\treturn \"Is Nuisance\";\n\t}\n\n\treturn QVariant();\n}\n\nQt::DropActions TableModelAnovaModel::supportedDropActions() const\n{\n\treturn Qt::CopyAction;\n}\n\nQt::DropActions TableModelAnovaModel::supportedDragActions() const\n{\n\treturn Qt::MoveAction;\n}\n\nOptionVariables *TableModelAnovaModel::termOptionFromRow(Options *row)\n{\n\treturn static_cast(row->get(0));\n}\n\nvoid TableModelAnovaModel::setTerms(const Terms &terms)\n{\n\t_terms.set(terms);\n\n\tif (_boundTo == NULL)\n\t\treturn;\n\n\tbeginResetModel();\n\n\tBOOST_FOREACH(Options *row, _rows)\n\t\tdelete row;\n\n\t_rows.clear();\n\n\tBOOST_FOREACH(const Term &term, _terms.terms())\n\t{\n\t\t(void)_terms;\n\t\tOptions *row = static_cast(_boundTo->rowTemplate()->clone());\n\t\tOptionTerms *termCell = static_cast(row->get(0));\n\t\ttermCell->setValue(term.scomponents());\n\n\t\t_rows.push_back(row);\n\t}\n\n\t_boundTo->setValue(_rows);\n\n\tendResetModel();\n\n\temit termsChanged();\n}\n\nvoid TableModelAnovaModel::clear()\n{\n\tsetTerms(Terms());\n}\n\nvoid TableModelAnovaModel::assign(const Terms &terms)\n{\n\tTerms t = _terms;\n\tt.add(terms);\n\tsetTerms(t);\n}\nB ANOVA: Tweaks to the \"Is Nuisance\" column width\n#include \"tablemodelanovamodel.h\"\n\n#include \n#include \n\n#include \"utils.h\"\n#include \n\n#include \"options\/optionboolean.h\"\n\nusing namespace std;\n\nTableModelAnovaModel::TableModelAnovaModel(QObject *parent)\n\t: TableModel(parent)\n{\n\t_boundTo = NULL;\n\t_customModel = false;\n\n\t_terms.setSortParent(_variables);\n}\n\nQVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const\n{\n\tif (_boundTo == NULL || index.isValid() == false)\n\t\treturn QVariant();\n\n\tif (role == Qt::DisplayRole)\n\t{\n\t\tint colNo = index.column();\n\t\tint rowNo = index.row();\n\t\tOptions *row = _rows.at(rowNo);\n\n\t\tif (colNo == 0) {\n\n\t\t\tOptionTerms *termOption = static_cast(row->get(0));\n\t\t\tTerm t(termOption->value().front());\n\t\t\treturn t.asQString();\n\t\t}\n\t}\n\telse if (role == Qt::CheckStateRole)\n\t{\n\t\tint colNo = index.column();\n\t\tint rowNo = index.row();\n\t\tOptions *row = _rows.at(rowNo);\n\n\t\tif (colNo == 1)\n\t\t{\n\t\t\tOptionBoolean *booleanOption = static_cast(row->get(1));\n\t\t\treturn booleanOption->value() ? Qt::Checked : Qt::Unchecked;\n\t\t}\n\t}\n\n\treturn QVariant();\n}\n\nint TableModelAnovaModel::rowCount(const QModelIndex &) const\n{\n\tif (_boundTo == NULL)\n\t\treturn 0;\n\n\treturn _rows.size();\n}\n\nint TableModelAnovaModel::columnCount(const QModelIndex &) const\n{\n\tif (_boundTo == NULL)\n\t\treturn 0;\n\n\treturn _boundTo->rowTemplate()->size();\n}\n\nbool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n\tif (index.isValid() == false)\n\t\treturn false;\n\n\tif (index.column() == 1 && role == Qt::CheckStateRole)\n\t{\n\t\tOptions *row = _rows.at(index.row());\n\t\tOptionBoolean *booleanOption = static_cast(row->get(1));\n\t\tbooleanOption->setValue(value.toInt() == Qt::Checked);\n\n\t\t_boundTo->setValue(_rows);\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nQStringList TableModelAnovaModel::mimeTypes() const\n{\n\tQStringList types;\n\n\ttypes << \"application\/vnd.list.term\";\n\n\treturn types;\n}\n\nvoid TableModelAnovaModel::setVariables(const Terms &variables)\n{\n\tbeginResetModel();\n\n\t_variables.set(variables);\n\n\tif (_customModel)\n\t{\n\t\tTerms terms = _terms;\n\t\tterms.discardWhatDoesntContainTheseComponents(_variables);\n\t\tif (terms.size() != _terms.size())\n\t\t\tsetTerms(terms);\n\t}\n\telse\n\t{\n\t\tTerms terms = _variables.crossCombinations();\n\t\tif (terms != _terms)\n\t\t\tsetTerms(terms);\n\t}\n\n\temit variablesAvailableChanged();\n\n\tendResetModel();\n}\n\nconst Terms &TableModelAnovaModel::variables() const\n{\n\treturn _variables;\n}\n\nvoid TableModelAnovaModel::setCustomModelMode(bool on)\n{\n\t_customModel = on;\n\n\tif (_customModel)\n\t\tclear();\n\telse\n\t\tsetTerms(_variables.crossCombinations());\n}\n\nvoid TableModelAnovaModel::bindTo(Option *option)\n{\n\t_boundTo = dynamic_cast(option);\n}\n\nvoid TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes)\n{\n\t\/\/ sort indices, and delete from end to beginning\n\n\tQModelIndexList sorted = indexes;\n\tqSort(sorted.begin(), sorted.end(), qGreater());\n\n\tint lastRowDeleted = -1;\n\n\tTerms terms = _terms;\n\n\tforeach (const QModelIndex &index, sorted)\n\t{\n\t\tint rowNo = index.row();\n\t\tif (rowNo != lastRowDeleted)\n\t\t\tterms.remove(index.row());\n\t\tlastRowDeleted = rowNo;\n\t}\n\n\tsetTerms(terms);\n}\n\nconst Terms &TableModelAnovaModel::terms() const\n{\n\treturn _terms;\n}\n\nbool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const\n{\n\tQ_UNUSED(action);\n\tQ_UNUSED(row);\n\tQ_UNUSED(column);\n\tQ_UNUSED(parent);\n\n\tif (mimeTypes().contains(\"application\/vnd.list.term\"))\n\t{\n\t\tQByteArray encodedData = data->data(\"application\/vnd.list.term\");\n\t\tQDataStream stream(&encodedData, QIODevice::ReadOnly);\n\n\t\tif (stream.atEnd())\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType)\n{\n\tif (action == Qt::IgnoreAction)\n\t\treturn true;\n\n\tif ( ! canDropMimeData(data, action, row, column, parent))\n\t\treturn false;\n\n\tif ( ! data->hasFormat(\"application\/vnd.list.term\"))\n\t\treturn false;\n\n\n\tQByteArray encodedData = data->data(\"application\/vnd.list.term\");\n\n\tTerms dropped;\n\tdropped.setSortParent(_variables);\n\tdropped.set(encodedData);\n\n\tTerms newTerms;\n\n\tswitch (assignType)\n\t{\n\tcase Cross:\n\t\tnewTerms = dropped.crossCombinations();\n\t\tbreak;\n\tcase Interaction:\n\t\tnewTerms = dropped.wayCombinations(dropped.size());\n\t\tbreak;\n\tcase MainEffects:\n\t\tnewTerms = dropped.wayCombinations(1);\n\t\tbreak;\n\tcase All2Way:\n\t\tnewTerms = dropped.wayCombinations(2);\n\t\tbreak;\n\tcase All3Way:\n\t\tnewTerms = dropped.wayCombinations(3);\n\t\tbreak;\n\tcase All4Way:\n\t\tnewTerms = dropped.wayCombinations(4);\n\t\tbreak;\n\tcase All5Way:\n\t\tnewTerms = dropped.wayCombinations(5);\n\t\tbreak;\n\tdefault:\n\t\t(void)newTerms;\n\t}\n\n\tassign(newTerms);\n\n\treturn true;\n}\n\nbool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)\n{\n\treturn dropMimeData(data, action, row, column, parent, Cross);\n}\n\nQMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const\n{\n\t\/* returns dummy data. when the user drags entries away from this listbox\n\t * it means that they're deleting entries, so there's no point populating\n\t * this data object properly\n\t *\/\n\n\tQ_UNUSED(indexes);\n\n\tQMimeData *mimeData = new QMimeData();\n\tQByteArray encodedData;\n\n\tQDataStream dataStream(&encodedData, QIODevice::WriteOnly);\n\n\tdataStream << 0;\n\n\tmimeData->setData(\"application\/vnd.list.term\", encodedData);\n\n\treturn mimeData;\n}\n\nQt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const\n{\n\tif (index.isValid())\n\t{\n\t\tif (index.column() == 0)\n\t\t\treturn Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;\n\t\telse\n\t\t\treturn Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;\n\t}\n\telse\n\t{\n\t\treturn Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;\n\t}\n}\n\nQVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\t\n\tif (orientation == Qt::Horizontal)\n\t{\n\t\tif (role == Qt::DisplayRole)\n\t\t{\n\t\t\tif (section == 0)\n\t\t\t\treturn \"Model Terms\";\n\t\t\telse if (section == 1)\n\t\t\t\treturn \"Is Nuisance\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (section == 1 && role == Qt::SizeHintRole)\n\t\t\t\treturn QSize(50, -1);\n\t\t}\n\t}\n\n\treturn QVariant();\n}\n\nQt::DropActions TableModelAnovaModel::supportedDropActions() const\n{\n\treturn Qt::CopyAction;\n}\n\nQt::DropActions TableModelAnovaModel::supportedDragActions() const\n{\n\treturn Qt::MoveAction;\n}\n\nOptionVariables *TableModelAnovaModel::termOptionFromRow(Options *row)\n{\n\treturn static_cast(row->get(0));\n}\n\nvoid TableModelAnovaModel::setTerms(const Terms &terms)\n{\n\t_terms.set(terms);\n\n\tif (_boundTo == NULL)\n\t\treturn;\n\n\tbeginResetModel();\n\n\tBOOST_FOREACH(Options *row, _rows)\n\t\tdelete row;\n\n\t_rows.clear();\n\n\tBOOST_FOREACH(const Term &term, _terms.terms())\n\t{\n\t\t(void)_terms;\n\t\tOptions *row = static_cast(_boundTo->rowTemplate()->clone());\n\t\tOptionTerms *termCell = static_cast(row->get(0));\n\t\ttermCell->setValue(term.scomponents());\n\n\t\t_rows.push_back(row);\n\t}\n\n\t_boundTo->setValue(_rows);\n\n\tendResetModel();\n\n\temit termsChanged();\n}\n\nvoid TableModelAnovaModel::clear()\n{\n\tsetTerms(Terms());\n}\n\nvoid TableModelAnovaModel::assign(const Terms &terms)\n{\n\tTerms t = _terms;\n\tt.add(terms);\n\tsetTerms(t);\n}\n<|endoftext|>"} {"text":" \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\\file AddTaskEMCALPhotonIsolation.C\n \/\/\/\\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation\n \/\/\/\n \/\/\/ Version to be used in lego train for testing on pp@7TeV\n \/\/\/\n \/\/\/ \\author Lucile Ronflette , SUBATECH, Nantes\n \/\/\/ \\author Davide Francesco Lodato , Utrecht University\n \/\/\/ \\author Marco Marquard , University Frankfurt am Main\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(\n const char* periodstr = \"LHC11c\",\n const char* ntracks = \"EmcalTracks\",\n const char* nclusters = \"EmcCaloClusters\",\n const UInt_t pSel = AliVEvent::kEMC7,\n const TString dType = \"ESD\",\n const Bool_t\t bHisto = kTRUE,\n const Int_t\t iOutput\t \t = 0,\n const Bool_t\t bIsMC \t = kFALSE,\n const Bool_t bMCNormalization = kFALSE,\n const Bool_t bNLMCut = kFALSE,\n const Int_t NLMCut = 0,\n const Double_t minPtCutCluster = 0.3,\n const Double_t EtIso = 2.,\n const Int_t iIsoMethod = 1,\n const Int_t iEtIsoMethod = 0,\n const Int_t iUEMethod = 1,\n const Bool_t bUseofTPC = kFALSE,\n const Double_t TMdeta = 0.02,\n const Double_t TMdphi = 0.03,\n const Bool_t bTMClusterRejection = kTRUE,\n const Bool_t bTMClusterRejectionInCone = kTRUE,\n const Float_t iIsoConeRadius = 0.4,\n const Bool_t iSmearingSS = kFALSE,\n const Float_t iWidthSSsmear = 0.,\n const Float_t iMean_SSsmear = 0.,\n const Bool_t iExtraIsoCuts = kFALSE,\n const Bool_t i_pPb = kFALSE\n )\n{\n \n Printf(\"Preparing neutral cluster analysis\\n\");\n \n \/\/ #### Define manager and data container names\n AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();\n if (!manager) {\n ::Error(\"AddTaskEMCALPhotonIsolation\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \n printf(\"Creating container names for cluster analysis\\n\");\n TString myContName(\"\");\n if(bIsMC)\n myContName = Form(\"Analysis_Neutrals_MC\");\n else\n myContName = Form(\"Analysis_Neutrals\");\n \n myContName.Append(Form(\"_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s\",bTMClusterRejection? \"On\" :\"Off\", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? \"Yes\" : \"No\",iIsoConeRadius,bNLMCut ? \"On\": \"Off\",NLMCut, iSmearingSS ? \"On\":\"Off\",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?\"On\":\"Off\"));\n \n \/\/ #### Define analysis task\n AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation(\"Analysis\",bHisto);\n \n \/\/ #### Task preferences\n task->SetOutputFormat(iOutput);\n task->SetLCAnalysis(kFALSE);\n task->SetIsoConeRadius(iIsoConeRadius);\n task->SetEtIsoThreshold(EtIso); \/\/ after should be replace by EtIso\n task->SetCTMdeltaEta(TMdeta); \/\/ after should be replaced by TMdeta\n task->SetCTMdeltaPhi(TMdphi); \/\/ after should be replaced by TMdphi\n task->SetQA(kTRUE);\n task->SetIsoMethod(iIsoMethod);\n task->SetEtIsoMethod(iEtIsoMethod);\n task->SetUEMethod(iUEMethod);\n task->SetUSEofTPC(bUseofTPC);\n task->SetMC(bIsMC);\n task->SetM02Smearing(iSmearingSS);\n task->SetWidth4Smear(iWidthSSsmear);\n task->SetMean4Smear(iMean_SSsmear);\n task->SetExtraIsoCuts(iExtraIsoCuts);\n task->SetAnalysispPb(i_pPb);\n if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);\n \n task->SetNLMCut(bNLMCut,NLMCut);\n \n \n \n TString name(Form(\"PhotonIsolation_%s_%s\", ntracks, nclusters));\n cout<<\"name of the containers \"<AddTrackContainer(\"tracks\");\n if(!trackCont)\n Printf(\"Error with TPCOnly!!\");\n trackCont->SetName(\"tpconlyMatch\");\n trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);\n \/\/ clusters to be used in the analysis already filtered\n AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);\n \n \/\/ tracks to be used in the analysis (Hybrid tracks)\n AliTrackContainer * tracksForAnalysis = task->AddTrackContainer(\"tracks\");\n if(!tracksForAnalysis)\n Printf(\"Error with Hybrids!!\");\n tracksForAnalysis->SetName(\"filterTracksAna\");\n tracksForAnalysis->SetFilterHybridTracks(kTRUE);\n if(dType==\"ESD\"){\n tracksForAnalysis->SetTrackCutsPeriod(periodstr);\n tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);\n }\n \n Printf(\"Name of Tracks for matching: %s \\n Name for Tracks for Isolation: %s\",trackCont->GetName(),tracksForAnalysis->GetName());\n \n printf(\"Task for neutral cluster analysis created and configured, pass it to AnalysisManager\\n\");\n \/\/ #### Add analysis task\n manager->AddTask(task);\n \n \n AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form(\"%s:NeutralClusters\",AliAnalysisManager::GetCommonFileName()));\n AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer();\n manager->ConnectInput(task, 0, cinput);\n manager->ConnectOutput(task, 1, contHistos);\n \n \n \n return task;\n}\nfixing flag in AddTask for TrackCuts \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\\file AddTaskEMCALPhotonIsolation.C\n \/\/\/\\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation\n \/\/\/\n \/\/\/ Version to be used in lego train for testing on pp@7TeV\n \/\/\/\n \/\/\/ \\author Lucile Ronflette , SUBATECH, Nantes\n \/\/\/ \\author Davide Francesco Lodato , Utrecht University\n \/\/\/ \\author Marco Marquard , University Frankfurt am Main\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(\n const char* periodstr = \"LHC11c\",\n const char* ntracks = \"EmcalTracks\",\n const char* nclusters = \"EmcCaloClusters\",\n const UInt_t pSel = AliVEvent::kEMC7,\n const TString dType = \"ESD\",\n const Bool_t\t bHisto = kTRUE,\n const Int_t\t iOutput\t \t = 0,\n const Bool_t\t bIsMC \t = kFALSE,\n const Bool_t bMCNormalization = kFALSE,\n const Bool_t bNLMCut = kFALSE,\n const Int_t NLMCut = 0,\n const Double_t minPtCutCluster = 0.3,\n const Double_t EtIso = 2.,\n const Int_t iIsoMethod = 1,\n const Int_t iEtIsoMethod = 0,\n const Int_t iUEMethod = 1,\n const Bool_t bUseofTPC = kFALSE,\n const Double_t TMdeta = 0.02,\n const Double_t TMdphi = 0.03,\n const Bool_t bTMClusterRejection = kTRUE,\n const Bool_t bTMClusterRejectionInCone = kTRUE,\n const Float_t iIsoConeRadius = 0.4,\n const Bool_t iSmearingSS = kFALSE,\n const Float_t iWidthSSsmear = 0.,\n const Float_t iMean_SSsmear = 0.,\n const Bool_t iExtraIsoCuts = kFALSE,\n const Bool_t i_pPb = kFALSE\n )\n{\n \n Printf(\"Preparing neutral cluster analysis\\n\");\n \n \/\/ #### Define manager and data container names\n AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();\n if (!manager) {\n ::Error(\"AddTaskEMCALPhotonIsolation\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \n printf(\"Creating container names for cluster analysis\\n\");\n TString myContName(\"\");\n if(bIsMC)\n myContName = Form(\"Analysis_Neutrals_MC\");\n else\n myContName = Form(\"Analysis_Neutrals\");\n \n myContName.Append(Form(\"_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s\",bTMClusterRejection? \"On\" :\"Off\", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? \"Yes\" : \"No\",iIsoConeRadius,bNLMCut ? \"On\": \"Off\",NLMCut, iSmearingSS ? \"On\":\"Off\",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?\"On\":\"Off\"));\n \n \/\/ #### Define analysis task\n AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation(\"Analysis\",bHisto);\n \n \/\/ #### Task preferences\n task->SetOutputFormat(iOutput);\n task->SetLCAnalysis(kFALSE);\n task->SetIsoConeRadius(iIsoConeRadius);\n task->SetEtIsoThreshold(EtIso); \/\/ after should be replace by EtIso\n task->SetCTMdeltaEta(TMdeta); \/\/ after should be replaced by TMdeta\n task->SetCTMdeltaPhi(TMdphi); \/\/ after should be replaced by TMdphi\n task->SetQA(kTRUE);\n task->SetIsoMethod(iIsoMethod);\n task->SetEtIsoMethod(iEtIsoMethod);\n task->SetUEMethod(iUEMethod);\n task->SetUSEofTPC(bUseofTPC);\n task->SetMC(bIsMC);\n task->SetM02Smearing(iSmearingSS);\n task->SetWidth4Smear(iWidthSSsmear);\n task->SetMean4Smear(iMean_SSsmear);\n task->SetExtraIsoCuts(iExtraIsoCuts);\n task->SetAnalysispPb(i_pPb);\n if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);\n \n task->SetNLMCut(bNLMCut,NLMCut);\n \n \n \n TString name(Form(\"PhotonIsolation_%s_%s\", ntracks, nclusters));\n cout<<\"name of the containers \"<AddTrackContainer(\"tracks\");\n if(!trackCont)\n Printf(\"Error with TPCOnly!!\");\n trackCont->SetName(\"tpconlyMatch\");\n trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);\n \/\/ clusters to be used in the analysis already filtered\n AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);\n \n \/\/ tracks to be used in the analysis (Hybrid tracks)\n AliTrackContainer * tracksForAnalysis = task->AddTrackContainer(\"tracks\");\n if(!tracksForAnalysis)\n Printf(\"Error with Hybrids!!\");\n tracksForAnalysis->SetName(\"filterTracksAna\");\n tracksForAnalysis->SetFilterHybridTracks(kTRUE);\n if(!bIsMC){\n tracksForAnalysis->SetTrackCutsPeriod(periodstr);\n tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);\n }\n \n Printf(\"Name of Tracks for matching: %s \\n Name for Tracks for Isolation: %s\",trackCont->GetName(),tracksForAnalysis->GetName());\n \n printf(\"Task for neutral cluster analysis created and configured, pass it to AnalysisManager\\n\");\n \/\/ #### Add analysis task\n manager->AddTask(task);\n \n \n AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form(\"%s:NeutralClusters\",AliAnalysisManager::GetCommonFileName()));\n AliAnalysisDataContainer *cinput = manager->GetCommonInputContainer();\n manager->ConnectInput(task, 0, cinput);\n manager->ConnectOutput(task, 1, contHistos);\n \n \n \n return task;\n}\n<|endoftext|>"} {"text":"\/*!\r\n\t@file\r\n\t@author\t\tAlbert Semenov\r\n\t@date\t\t01\/2008\r\n\t@module\r\n*\/\r\n#include \"MyGUI_Prerequest.h\"\r\n#include \"MyGUI_ControllerFadeAlpha.h\"\r\n#include \"MyGUI_Gui.h\"\r\n#include \"MyGUI_InputManager.h\"\r\n#include \"MyGUI_WidgetManager.h\"\r\n#include \"MyGUI_Widget.h\"\r\n\r\nnamespace MyGUI\r\n{\r\n\r\n\tControllerFadeAlpha::ControllerFadeAlpha()\r\n\t{\r\n\t}\r\n\r\n\tControllerFadeAlpha::ControllerFadeAlpha(float _alpha, float _coef, bool _enabled) :\r\n\t\tmAlpha(_alpha), mCoef(_coef), mEnabled(_enabled)\r\n\t{\r\n\t\tMYGUI_DEBUG_ASSERT(mCoef > 0, \"coef must be > 0\");\r\n\t}\r\n\r\n\tconst std::string & ControllerFadeAlpha::getType()\r\n\t{\r\n\t\tstatic std::string type(\"FadeAlphaController\");\r\n\t\treturn type;\r\n\t}\r\n\r\n\tvoid ControllerFadeAlpha::prepareItem(WidgetPtr _widget)\r\n\t{\r\n\t\t\/\/ подготовка виджета\r\n\t\t_widget->setEnabledSilent(mEnabled);\r\n\r\n\t\tif ((ALPHA_MIN != mAlpha) && (false == _widget->isShow())) {\r\n\t\t\t_widget->setAlpha(ALPHA_MIN);\r\n\t\t\t_widget->show();\r\n\t\t}\r\n\r\n\t\t\/\/ отписываем его от ввода\r\n\t\tif (false == mEnabled) InputManager::getInstance()._unlinkWidget(_widget);\r\n\r\n\t\t\/\/ вызываем пользовательский делегат для подготовки\r\n\t\teventPreAction(_widget);\r\n\t}\r\n\r\n\t\/*void ControllerFadeAlpha::replaseItem(WidgetPtr _widget, ControllerItem * _item)\r\n\t{\r\n\t\tControllerFadeAlpha * item = static_cast(_item);\r\n\t\tmEnabled = item->getEnabled();\r\n\t\tmCoef = item->getCoef();\r\n\t\tmAlpha = item->getAlpha();\r\n\t}*\/\r\n\r\n\tbool ControllerFadeAlpha::addTime(WidgetPtr _widget, float _time)\r\n\t{\r\n\t\tfloat alpha = _widget->getAlpha();\r\n\r\n\t\t\/\/ проверяем нужно ли к чему еще стремиться\r\n\t\tif (mAlpha > alpha) {\r\n\t\t\talpha += _time * mCoef;\r\n\t\t\tif (mAlpha > alpha) {\r\n\t\t\t\t_widget->setAlpha(alpha);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t_widget->setAlpha(mAlpha);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (mAlpha < alpha) {\r\n\t\t\talpha -= _time * mCoef;\r\n\t\t\tif (mAlpha < alpha) {\r\n\t\t\t\t_widget->setAlpha(alpha);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t_widget->setAlpha(mAlpha);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ вызываем пользовательский делегат пост обработки\r\n\t\teventPostAction(_widget);\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n} \/\/ namespace MyGUI\r\nfix controller\/*!\r\n\t@file\r\n\t@author\t\tAlbert Semenov\r\n\t@date\t\t01\/2008\r\n\t@module\r\n*\/\r\n#include \"MyGUI_Prerequest.h\"\r\n#include \"MyGUI_ControllerFadeAlpha.h\"\r\n#include \"MyGUI_Gui.h\"\r\n#include \"MyGUI_InputManager.h\"\r\n#include \"MyGUI_WidgetManager.h\"\r\n#include \"MyGUI_Widget.h\"\r\n\r\nnamespace MyGUI\r\n{\r\n\r\n\tControllerFadeAlpha::ControllerFadeAlpha()\r\n\t{\r\n\t}\r\n\r\n\tControllerFadeAlpha::ControllerFadeAlpha(float _alpha, float _coef, bool _enabled) :\r\n\t\tmAlpha(_alpha), mCoef(_coef), mEnabled(_enabled)\r\n\t{\r\n\t\tMYGUI_DEBUG_ASSERT(mCoef > 0, \"coef must be > 0\");\r\n\t}\r\n\r\n\tconst std::string & ControllerFadeAlpha::getType()\r\n\t{\r\n\t\tstatic std::string type(\"FadeAlphaController\");\r\n\t\treturn type;\r\n\t}\r\n\r\n\tvoid ControllerFadeAlpha::prepareItem(WidgetPtr _widget)\r\n\t{\r\n\t\t\/\/ подготовка виджета, блокируем если только нужно\r\n\t\tif (!mEnabled) _widget->setEnabledSilent(mEnabled);\r\n\r\n\t\tif ((ALPHA_MIN != mAlpha) && (false == _widget->isShow())) {\r\n\t\t\t_widget->setAlpha(ALPHA_MIN);\r\n\t\t\t_widget->show();\r\n\t\t}\r\n\r\n\t\t\/\/ отписываем его от ввода\r\n\t\tif (false == mEnabled) InputManager::getInstance()._unlinkWidget(_widget);\r\n\r\n\t\t\/\/ вызываем пользовательский делегат для подготовки\r\n\t\teventPreAction(_widget);\r\n\t}\r\n\r\n\t\/*void ControllerFadeAlpha::replaseItem(WidgetPtr _widget, ControllerItem * _item)\r\n\t{\r\n\t\tControllerFadeAlpha * item = static_cast(_item);\r\n\t\tmEnabled = item->getEnabled();\r\n\t\tmCoef = item->getCoef();\r\n\t\tmAlpha = item->getAlpha();\r\n\t}*\/\r\n\r\n\tbool ControllerFadeAlpha::addTime(WidgetPtr _widget, float _time)\r\n\t{\r\n\t\tfloat alpha = _widget->getAlpha();\r\n\r\n\t\t\/\/ проверяем нужно ли к чему еще стремиться\r\n\t\tif (mAlpha > alpha) {\r\n\t\t\talpha += _time * mCoef;\r\n\t\t\tif (mAlpha > alpha) {\r\n\t\t\t\t_widget->setAlpha(alpha);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t_widget->setAlpha(mAlpha);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (mAlpha < alpha) {\r\n\t\t\talpha -= _time * mCoef;\r\n\t\t\tif (mAlpha < alpha) {\r\n\t\t\t\t_widget->setAlpha(alpha);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t_widget->setAlpha(mAlpha);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ вызываем пользовательский делегат пост обработки\r\n\t\teventPostAction(_widget);\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n} \/\/ namespace MyGUI\r\n<|endoftext|>"} {"text":"#include \"gillet_johnson.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ --------- TODO: no est contando com a capacidade de cada ponto de atendimento --------\nnamespace rotas\n{\n\tnamespace algoritmos\n\t{\t\n\n\t\tbool compara_diferencas(Cidade *a, Cidade *b) {\n\t\t\treturn a->diferenca > b->diferenca;\n\t\t}\n\t\t\n\t\tvector encontra_lista_designacao(vector &pontos_demanda, vector &pontos_atendimento) {\n\t\t\tvector lista_designacao = vector();\n\n\t\t\tif (pontos_atendimento.size() == 1) {\n\t\t\t\tlista_designacao.push_back(&(pontos_atendimento.front()));\n\t\t\t\treturn lista_designacao;\n\t\t\t}\n\n\t\t\tfor (unsigned int i = 0; i < pontos_demanda.size(); i++) {\n\t\t\t\tCidade *ponto_demanda = &pontos_demanda[i];\n\t\t\t\t\/\/Passo 1: Encontrar L1 e L2, as duas medianas mais prximas\n\t\t\t\t\/\/vector* Cidade::ordena_por_distancia(vector *destinos)\n\t\t\t\tvector *pontos_atendimento_ordenados = ponto_demanda->ordena_por_distancia(&pontos_atendimento);\n\t\t\t\t\/\/L1 -> cidades_ordenadas[0]\n\t\t\t\t\/\/L2 -> cidades_ordenadas[1]\n\n\t\t\t\t\/\/Passo 2: calcular a razo r = |L2| - |L1|\n\t\t\t\tdouble d1 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(0));\n\t\t\t\tdouble d2 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(1));\n\t\t\t\tponto_demanda->diferenca = d2 - d1;\n\n\t\t\t\t\/\/Passo 3: preencher a lista de designao\n\t\t\t\tlista_designacao.push_back(ponto_demanda);\n\t\t\t}\n\t\t\treturn lista_designacao;\n\t\t}\n\n\t\tvoid remove_cidade(vector &cidades, Cidade *to_remove) {\n\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\tif (cidades[i].get_id() == to_remove->get_id()) {\n\t\t\t\t\tcidades.erase(cidades.begin() + i);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid diminui_capacidade_pela_propria_demanda(vector &pontos_atendimento)\n\t\t{\n\t\t\tsize_t size_pontos_atendimento = pontos_atendimento.size();\n\t\t\tfor (unsigned int i = 0; i < size_pontos_atendimento; i++)\n\t\t\t{\n\t\t\t\tdouble capacidade_atual = pontos_atendimento[i].get_capacidade();\n\t\t\t\tdouble demanda_atual = pontos_atendimento[i].get_demanda();\n\t\t\t\tif (capacidade_atual > demanda_atual)\n\t\t\t\t{\n\t\t\t\t\tpontos_atendimento[i].set_capacidade(capacidade_atual - demanda_atual);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid GilletJohnson::encontra_medianas(vector & cidades) {\n\n\t\t\tvector pontos_atendimento = vector();\n\t\t\tvector pontos_demanda = vector();\n\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\tif (cidades[i].is_mediana()) {\n\t\t\t\t\tpontos_atendimento.push_back(cidades[i]);\n\t\t\t\t}\n\t\t\t\tpontos_demanda.push_back(cidades[i]);\n\t\t\t}\n\n\t\t\tdiminui_capacidade_pela_propria_demanda(pontos_atendimento);\n\n\t\t\tswitch (pontos_atendimento.size()) {\n\t\t\tcase 0:\n\t\t\t\t\/\/Se no encontrou nenhum ponto de atendimento, o algoritmo no faz sentido\n\t\t\t\t\/\/TODO disparar exceo\n\t\t\t\treturn;\n\t\t\tcase 1:\n\t\t\t\t\/\/Se encontrou um ponto de atendimento, ele atende a todos os pontos de demanda\n\t\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\t\tcidades[i].set_id_mediana(pontos_atendimento.front().get_id());\n\t\t\t\t}\n\t\t\t\treturn;\t\t\t\t\n\t\t\tdefault:\n\t\t\t\tbool flag_demanda_estourada;\n\t\t\t\tvector lista_designacao;\n\t\t\t\t\n\t\t\t\tdo {\n\t\t\t\t\tflag_demanda_estourada = false;\n\t\t\t\t\t\/\/ Passos 1-3: Encontrar a lista de designao\n\t\t\t\t\tlista_designacao = encontra_lista_designacao(pontos_demanda, pontos_atendimento);\n\n\t\t\t\t\t\/\/Passo 4: organizar a lista por ordem decrescente de d\n\t\t\t\t\tsort(lista_designacao.begin(), lista_designacao.end(), compara_diferencas);\n\n\t\t\t\t\t\/\/Passo 5: Designar os pontos de demanda ao ponto de atendimento mais prximo\n\t\t\t\t\tfor (unsigned i = 0; i < lista_designacao.size(); i++) {\n\t\t\t\t\t\tCidade* ponto_atendimento_mais_prox = lista_designacao[i]->encontra_mais_proxima(&pontos_atendimento);\n\t\t\t\t\t\tdouble capacidade = ponto_atendimento_mais_prox->get_capacidade();\n\t\t\t\t\t\tif (capacidade >= lista_designacao[i]->get_demanda()) {\n\t\t\t\t\t\t\tponto_atendimento_mais_prox->set_capacidade(capacidade - lista_designacao[i]->get_demanda());\n\t\t\t\t\t\t\tlista_designacao[i]->set_id_mediana(ponto_atendimento_mais_prox->get_id());\n\t\t\t\t\t\t\tcidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento_mais_prox->get_id());\n\n\t\t\t\t\t\t\t\/\/Tira a cidade atendida dos pontos de demanda\n\t\t\t\t\t\t\tremove_cidade(pontos_demanda, lista_designacao[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\/\/Ponto de atendimento no tem mais capacidade, atribuir ao prximo disponvel\n\t\t\t\t\t\t\tvector *pontos_atendimento_ordenados = lista_designacao[i]->ordena_por_distancia(&pontos_atendimento);\n\t\t\t\t\t\t\tfor (size_t j = 0; j < pontos_atendimento_ordenados->size(); j++) {\n\t\t\t\t\t\t\t\tCidade *ponto_atendimento = pontos_atendimento_ordenados->at(j);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif (lista_designacao[i]->get_demanda() >= ponto_atendimento->get_capacidade()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tponto_atendimento->set_capacidade(ponto_atendimento->get_capacidade() - lista_designacao[i]->get_demanda());\n\t\t\t\t\t\t\t\tlista_designacao[i]->set_id_mediana(ponto_atendimento->get_id());\n\t\t\t\t\t\t\t\tcidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento->get_id());\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\tflag_demanda_estourada = true;\n\t\t\t\t\t\t\t\/\/Tira a cidade atendida dos pontos de demanda\n\t\t\t\t\t\t\tremove_cidade(pontos_demanda, lista_designacao[i]);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} while (flag_demanda_estourada);\n\n\t\t\t\t\/*for (unsigned i = 0; i < lista_designacao.size(); i++) {\n\t\t\t\t\tCidade cidade = lista_designacao[i];\t\t\t\t\t\n\t\t\t\t\tcidades[cidade.get_id()].set_id_mediana(cidade.get_id_mediana());\n\t\t\t\t}*\/\n\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\t\t\t\n\t\t\t\n\t\t}\n\t} \/\/ algoritmos\n} \/\/ rotas\nCorrigido bug do gillet que tava adicionando sede duas vezes na rota#include \"gillet_johnson.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ --------- TODO: no est contando com a capacidade de cada ponto de atendimento --------\nnamespace rotas\n{\n\tnamespace algoritmos\n\t{\t\n\n\t\tbool compara_diferencas(Cidade *a, Cidade *b) {\n\t\t\treturn a->diferenca > b->diferenca;\n\t\t}\n\t\t\n\t\tvector encontra_lista_designacao(vector &pontos_demanda, vector &pontos_atendimento) {\n\t\t\tvector lista_designacao = vector();\n\n\t\t\tif (pontos_atendimento.size() == 1) {\n\t\t\t\tlista_designacao.push_back(&(pontos_atendimento.front()));\n\t\t\t\treturn lista_designacao;\n\t\t\t}\n\n\t\t\tfor (unsigned int i = 0; i < pontos_demanda.size(); i++) {\n\t\t\t\tCidade *ponto_demanda = &pontos_demanda[i];\n\t\t\t\t\/\/Passo 1: Encontrar L1 e L2, as duas medianas mais prximas\n\t\t\t\t\/\/vector* Cidade::ordena_por_distancia(vector *destinos)\n\t\t\t\tvector *pontos_atendimento_ordenados = ponto_demanda->ordena_por_distancia(&pontos_atendimento);\n\t\t\t\t\/\/L1 -> cidades_ordenadas[0]\n\t\t\t\t\/\/L2 -> cidades_ordenadas[1]\n\n\t\t\t\t\/\/Passo 2: calcular a razo r = |L2| - |L1|\n\t\t\t\tdouble d1 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(0));\n\t\t\t\tdouble d2 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(1));\n\t\t\t\tponto_demanda->diferenca = d2 - d1;\n\n\t\t\t\t\/\/Passo 3: preencher a lista de designao\n\t\t\t\tlista_designacao.push_back(ponto_demanda);\n\t\t\t}\n\t\t\treturn lista_designacao;\n\t\t}\n\n\t\tvoid remove_cidade(vector &cidades, Cidade *to_remove) {\n\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\tif (cidades[i].get_id() == to_remove->get_id()) {\n\t\t\t\t\tcidades.erase(cidades.begin() + i);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid diminui_capacidade_pela_propria_demanda(vector &pontos_atendimento)\n\t\t{\n\t\t\tsize_t size_pontos_atendimento = pontos_atendimento.size();\n\t\t\tfor (unsigned int i = 0; i < size_pontos_atendimento; i++)\n\t\t\t{\n\t\t\t\tdouble capacidade_atual = pontos_atendimento[i].get_capacidade();\n\t\t\t\tdouble demanda_atual = pontos_atendimento[i].get_demanda();\n\t\t\t\tif (capacidade_atual > demanda_atual)\n\t\t\t\t{\n\t\t\t\t\tpontos_atendimento[i].set_capacidade(capacidade_atual - demanda_atual);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid GilletJohnson::encontra_medianas(vector & cidades) {\n\n\t\t\tvector pontos_atendimento = vector();\n\t\t\tvector pontos_demanda = vector();\n\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\tif (cidades[i].is_mediana()) {\n\t\t\t\t\tpontos_atendimento.push_back(cidades[i]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpontos_demanda.push_back(cidades[i]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdiminui_capacidade_pela_propria_demanda(pontos_atendimento);\n\n\t\t\tswitch (pontos_atendimento.size()) {\n\t\t\tcase 0:\n\t\t\t\t\/\/Se no encontrou nenhum ponto de atendimento, o algoritmo no faz sentido\n\t\t\t\t\/\/TODO disparar exceo\n\t\t\t\treturn;\n\t\t\tcase 1:\n\t\t\t\t\/\/Se encontrou um ponto de atendimento, ele atende a todos os pontos de demanda\n\t\t\t\tfor (unsigned int i = 0; i < cidades.size(); i++) {\n\t\t\t\t\tcidades[i].set_id_mediana(pontos_atendimento.front().get_id());\n\t\t\t\t}\n\t\t\t\treturn;\t\t\t\t\n\t\t\tdefault:\n\t\t\t\tbool flag_demanda_estourada;\n\t\t\t\tvector lista_designacao;\n\t\t\t\t\n\t\t\t\tdo {\n\t\t\t\t\tflag_demanda_estourada = false;\n\t\t\t\t\t\/\/ Passos 1-3: Encontrar a lista de designao\n\t\t\t\t\tlista_designacao = encontra_lista_designacao(pontos_demanda, pontos_atendimento);\n\n\t\t\t\t\t\/\/Passo 4: organizar a lista por ordem decrescente de d\n\t\t\t\t\tsort(lista_designacao.begin(), lista_designacao.end(), compara_diferencas);\n\n\t\t\t\t\t\/\/Passo 5: Designar os pontos de demanda ao ponto de atendimento mais prximo\n\t\t\t\t\tfor (unsigned i = 0; i < lista_designacao.size(); i++) {\n\t\t\t\t\t\tCidade* ponto_atendimento_mais_prox = lista_designacao[i]->encontra_mais_proxima(&pontos_atendimento);\n\t\t\t\t\t\tdouble capacidade = ponto_atendimento_mais_prox->get_capacidade();\n\t\t\t\t\t\tif (capacidade >= lista_designacao[i]->get_demanda()) {\n\t\t\t\t\t\t\tponto_atendimento_mais_prox->set_capacidade(capacidade - lista_designacao[i]->get_demanda());\n\t\t\t\t\t\t\tlista_designacao[i]->set_id_mediana(ponto_atendimento_mais_prox->get_id());\n\t\t\t\t\t\t\tcidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento_mais_prox->get_id());\n\n\t\t\t\t\t\t\t\/\/Tira a cidade atendida dos pontos de demanda\n\t\t\t\t\t\t\tremove_cidade(pontos_demanda, lista_designacao[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\/\/Ponto de atendimento no tem mais capacidade, atribuir ao prximo disponvel\n\t\t\t\t\t\t\tvector *pontos_atendimento_ordenados = lista_designacao[i]->ordena_por_distancia(&pontos_atendimento);\n\t\t\t\t\t\t\tfor (size_t j = 0; j < pontos_atendimento_ordenados->size(); j++) {\n\t\t\t\t\t\t\t\tCidade *ponto_atendimento = pontos_atendimento_ordenados->at(j);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif (lista_designacao[i]->get_demanda() >= ponto_atendimento->get_capacidade()) {\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tponto_atendimento->set_capacidade(ponto_atendimento->get_capacidade() - lista_designacao[i]->get_demanda());\n\t\t\t\t\t\t\t\tlista_designacao[i]->set_id_mediana(ponto_atendimento->get_id());\n\t\t\t\t\t\t\t\tcidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento->get_id());\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\tflag_demanda_estourada = true;\n\t\t\t\t\t\t\t\/\/Tira a cidade atendida dos pontos de demanda\n\t\t\t\t\t\t\tremove_cidade(pontos_demanda, lista_designacao[i]);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} while (flag_demanda_estourada);\n\n\t\t\t\t\/*for (unsigned i = 0; i < lista_designacao.size(); i++) {\n\t\t\t\t\tCidade cidade = lista_designacao[i];\t\t\t\t\t\n\t\t\t\t\tcidades[cidade.get_id()].set_id_mediana(cidade.get_id_mediana());\n\t\t\t\t}*\/\n\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\t\t\t\n\t\t\t\n\t\t}\n\t} \/\/ algoritmos\n} \/\/ rotas\n<|endoftext|>"} {"text":"\/\/ Use cases in C++\n\/\/ See also file use-cases.md\n\/\/\n\/\/ Notice: This is pseudo code. It will not compile, much less do anything useful.\n\/\/\n\nusing Storage::DeviceGraph;\nusing Storage::Disk;\nusing Storage::Partition;\ntypedef std::vector DiskVector;\n\n\n#define EFI_BOOT_SIZE 64*MB\n#define SWAP_SIZE 2*GB\n#define ROOT_SIZE 20*GB\n#define HOME_MIN_SIZE 5*GB\n\n\nvoid bare_metal_pc() \/\/ this handles both modern and legacy bare metal PC\n{\n const DeviceGraph *probed = Storage::get_probed();\n\n if ( probed->have_disks() )\n {\n\tDeviceGraph *staging = Storage::get_staging();\n\tDisk *disk = staging->get_disks().front();\n\tPartitionTable * partition_table = nullptr;\n\n\tif ( Storage::get_arch()->is_efi_boot() )\n\t{\n\t \/\/ This implicitly deletes any existing partitions\n\t partition_table = disk->create_partition_table( Disk::GPT );\n\n\t Partition *efi_boot_part = partition_table->create_partition( EFI_BOOT_SIZE, ID_GPT_BOOT );\n\t Filesystem *efi_boot_fs = efi_boot_part->create_filesystem( VFAT );\n\t efi_boot_fs->set_mount_point( \"\/boot\/efi\" );\n\t}\n\telse\n\t{\n\t partition_table = disk->create_partition_table( Disk::MSDOS );\n\t}\n\n\tPartition *swap_part = partition_table->create_partition( SWAP_SIZE, ID_SWAP );\n\tFilesystem *swap_fs = swap_part->create_filesystem( SWAP );\n\tswap_fs->set_mount_point( \"swap\" );\n\n\n\tDiskSize root_size = ROOT_SIZE;\n\tDiskSize home_size = disk->free_size() - root_size;\n\n\tif ( home_size < MIN_HOME_SIZE ) \/\/ No space for separate \/home ?\n\t{\n\t home_size = 0;\n\t root_size = disk->free_size();\n\t}\n\n\tPartition *root_part = partition_table->create_partition( root_size, ID_LINUX );\n\tFilesystem *root_fs = root_part->create_filesystem( BTRFS );\n\troot_fs->set_mount_point( \"\/\" );\n\n\tif ( home_size > 0 )\n\t{\n\t Partition *home_part = partition_table->create_partition( home_size );\n\t Filesystem *home_fs = home_part->create_filesystem( XFS );\n\t home_fs->set_mount_point( \"\/home\" );\n\t}\n\n\ttry\n\t{\n \/\/ Apply all changes in staging: create and format partitions\n\t \/\/\n\t \/\/ GUI applications will want to install error callbacks and use\n\t \/\/ Storage::NoThrow\n\t Storage::commit( Storage::DoThrow );\n\t}\n\tcatch ( const Storage::Exception & exception )\n\t{\n\t ST_CAUGHT( exception );\n\n\t \/\/ Handle exception: Display errors to the user etc.\n\t \/\/ ...\n\t \/\/ ...\n\t}\n }\n\n \/\/ Intentionally NOT deleting staging or probed: They are owned by libstorage\n}\n\n\n\nvoid multi_boot_pc_with_windows()\n\/\/ Pre-condition: We know that there is one disk, and that this one disk has an\n\/\/ MS-DOS partition table and is completely occupied with one large Windows\n\/\/ partition. These are just shortcuts to illustrate the relevant points here\n\/\/ and to avoid getting bogged down in all kinds of fringe cases.\n{\n const DeviceGraph *probed = Storage::get_probed();\n\n if ( ! probed->have_disks() )\n\tST_THROW( StorageException( \"Preconditions not met: No hard disk\" ) );\n\n DeviceGraph *staging = Storage::get_staging();\n Disk *disk = staging->get_disks().front();\n MsDosPartitionTable * partition_table = disk->get_partition_table();\n\n if ( ! partition_table )\n\tST_THROW( StorageException( \"Preconditions not met: No MS-DOS partition table\" ) );\n\n std::vector partitions = disk->get_partitions();\n if ( partitions.size() != 1 )\n\tST_THROW( StorageException( \"Preconditions not met: One partition on disk expected\" ) );\n\n\n \/\/ Find windows partition and resize it\n\n Partition *win_part = partitions.front();\n FsType win_fs_type = win_part->get_type();\n if ( win_part->get_type() != NTFS && win_part->get_type() != VFAT )\n\tST_THROW( StorageException( \"Preconditions not met: Expected NTFS or VFAT partition\" ) );\n\n DiskSize win_size = win_part.get_size();\n DiskSize win_min_size = win_part.get_resize_info();\n DiskSize win_new_size = std::min( win_min_size * 1.2, win_size );\n\n win_part->resize( win_new_size );\n\n\n \/\/ Create Linux partitions\n\n Partition *swap_part = partition_table->create_partition( SWAP_SIZE, ID_SWAP ); \/\/ primary partition\n Filesystem *swap_fs = swap_part->create_filesystem( SWAP );\n swap_fs->set_mount_point( \"swap\" );\n\n Region free_space = partition_table->largest_free_region();\n Partition *extended_part = partition_table->create_partition( free_space, EXTENDED );\n DiskSize root_size = ROOT_SIZE;\n DiskSize home_size = extended_part->free_size() - root_size;\n\n if ( home_size < MIN_HOME_SIZE ) \/\/ No space for separate \/home ?\n {\n\thome_size = 0;\n\troot_size = disk->free_size();\n }\n\n Partition *root_part = extended_part->create_partition( root_size, ID_LINUX ); \/\/ logical partition\n Filesystem *root_fs = root_part->create_filesystem( BTRFS );\n root_fs->set_mount_point( \"\/\" );\n\n if ( home_size > 0 )\n {\n\tPartition *home_part = extended_part->create_partition( home_size ); \/\/ logical partition\n\tFilesystem *home_fs = home_part->create_filesystem( XFS );\n\thome_fs->set_mount_point( \"\/home\" );\n }\n\n try\n {\n\t\/\/ Apply all changes in staging: create and format partitions\n\t\/\/\n\t\/\/ GUI applications will want to install error callbacks and use\n\t\/\/ Storage::NoThrow\n\tStorage::commit( Storage::DoThrow );\n }\n catch ( const Storage::Exception & exception )\n {\n\tST_CAUGHT( exception );\n\n\t\/\/ Handle exception: Display errors to the user etc.\n\t\/\/ ...\n\t\/\/ ...\n }\n\n \/\/ Intentionally NOT deleting staging or probed: They are owned by libstorage\n}\nadded comment\/\/ Use cases in C++\n\/\/ See also file use-cases.md\n\/\/\n\/\/ This is how I (shundhammer@suse.de) would like to use it from an application\n\/\/ developer's point of view. Many aspects are already slightly changed to\n\/\/ match some technical aspects of Arvin's prototype of the new libstorage.\n\/\/\n\/\/ Notice: This is pseudo code. It will not compile, much less do anything useful.\n\/\/\n\nusing Storage::DeviceGraph;\nusing Storage::Disk;\nusing Storage::Partition;\ntypedef std::vector DiskVector;\n\n\n#define EFI_BOOT_SIZE 64*MB\n#define SWAP_SIZE 2*GB\n#define ROOT_SIZE 20*GB\n#define HOME_MIN_SIZE 5*GB\n\n\nvoid bare_metal_pc() \/\/ this handles both modern and legacy bare metal PC\n{\n const DeviceGraph *probed = Storage::get_probed();\n\n if ( probed->have_disks() )\n {\n\tDeviceGraph *staging = Storage::get_staging();\n\tDisk *disk = staging->get_disks().front();\n\tPartitionTable * partition_table = nullptr;\n\n\tif ( Storage::get_arch()->is_efi_boot() )\n\t{\n\t \/\/ This implicitly deletes any existing partitions\n\t partition_table = disk->create_partition_table( Disk::GPT );\n\n\t Partition *efi_boot_part = partition_table->create_partition( EFI_BOOT_SIZE, ID_GPT_BOOT );\n\t Filesystem *efi_boot_fs = efi_boot_part->create_filesystem( VFAT );\n\t efi_boot_fs->set_mount_point( \"\/boot\/efi\" );\n\t}\n\telse\n\t{\n\t partition_table = disk->create_partition_table( Disk::MSDOS );\n\t}\n\n\tPartition *swap_part = partition_table->create_partition( SWAP_SIZE, ID_SWAP );\n\tFilesystem *swap_fs = swap_part->create_filesystem( SWAP );\n\tswap_fs->set_mount_point( \"swap\" );\n\n\n\tDiskSize root_size = ROOT_SIZE;\n\tDiskSize home_size = disk->free_size() - root_size;\n\n\tif ( home_size < MIN_HOME_SIZE ) \/\/ No space for separate \/home ?\n\t{\n\t home_size = 0;\n\t root_size = disk->free_size();\n\t}\n\n\tPartition *root_part = partition_table->create_partition( root_size, ID_LINUX );\n\tFilesystem *root_fs = root_part->create_filesystem( BTRFS );\n\troot_fs->set_mount_point( \"\/\" );\n\n\tif ( home_size > 0 )\n\t{\n\t Partition *home_part = partition_table->create_partition( home_size );\n\t Filesystem *home_fs = home_part->create_filesystem( XFS );\n\t home_fs->set_mount_point( \"\/home\" );\n\t}\n\n\ttry\n\t{\n \/\/ Apply all changes in staging: create and format partitions\n\t \/\/\n\t \/\/ GUI applications will want to install error callbacks and use\n\t \/\/ Storage::NoThrow\n\t Storage::commit( Storage::DoThrow );\n\t}\n\tcatch ( const Storage::Exception & exception )\n\t{\n\t ST_CAUGHT( exception );\n\n\t \/\/ Handle exception: Display errors to the user etc.\n\t \/\/ ...\n\t \/\/ ...\n\t}\n }\n\n \/\/ Intentionally NOT deleting staging or probed: They are owned by libstorage\n}\n\n\n\nvoid multi_boot_pc_with_windows()\n\/\/ Pre-condition: We know that there is one disk, and that this one disk has an\n\/\/ MS-DOS partition table and is completely occupied with one large Windows\n\/\/ partition. These are just shortcuts to illustrate the relevant points here\n\/\/ and to avoid getting bogged down in all kinds of fringe cases.\n{\n const DeviceGraph *probed = Storage::get_probed();\n\n if ( ! probed->have_disks() )\n\tST_THROW( StorageException( \"Preconditions not met: No hard disk\" ) );\n\n DeviceGraph *staging = Storage::get_staging();\n Disk *disk = staging->get_disks().front();\n MsDosPartitionTable * partition_table = disk->get_partition_table();\n\n if ( ! partition_table )\n\tST_THROW( StorageException( \"Preconditions not met: No MS-DOS partition table\" ) );\n\n std::vector partitions = disk->get_partitions();\n if ( partitions.size() != 1 )\n\tST_THROW( StorageException( \"Preconditions not met: One partition on disk expected\" ) );\n\n\n \/\/ Find windows partition and resize it\n\n Partition *win_part = partitions.front();\n FsType win_fs_type = win_part->get_type();\n if ( win_part->get_type() != NTFS && win_part->get_type() != VFAT )\n\tST_THROW( StorageException( \"Preconditions not met: Expected NTFS or VFAT partition\" ) );\n\n DiskSize win_size = win_part.get_size();\n DiskSize win_min_size = win_part.get_resize_info();\n DiskSize win_new_size = std::min( win_min_size * 1.2, win_size );\n\n win_part->resize( win_new_size );\n\n\n \/\/ Create Linux partitions\n\n Partition *swap_part = partition_table->create_partition( SWAP_SIZE, ID_SWAP ); \/\/ primary partition\n Filesystem *swap_fs = swap_part->create_filesystem( SWAP );\n swap_fs->set_mount_point( \"swap\" );\n\n Region free_space = partition_table->largest_free_region();\n Partition *extended_part = partition_table->create_partition( free_space, EXTENDED );\n DiskSize root_size = ROOT_SIZE;\n DiskSize home_size = extended_part->free_size() - root_size;\n\n if ( home_size < MIN_HOME_SIZE ) \/\/ No space for separate \/home ?\n {\n\thome_size = 0;\n\troot_size = disk->free_size();\n }\n\n Partition *root_part = extended_part->create_partition( root_size, ID_LINUX ); \/\/ logical partition\n Filesystem *root_fs = root_part->create_filesystem( BTRFS );\n root_fs->set_mount_point( \"\/\" );\n\n if ( home_size > 0 )\n {\n\tPartition *home_part = extended_part->create_partition( home_size ); \/\/ logical partition\n\tFilesystem *home_fs = home_part->create_filesystem( XFS );\n\thome_fs->set_mount_point( \"\/home\" );\n }\n\n try\n {\n\t\/\/ Apply all changes in staging: create and format partitions\n\t\/\/\n\t\/\/ GUI applications will want to install error callbacks and use\n\t\/\/ Storage::NoThrow\n\tStorage::commit( Storage::DoThrow );\n }\n catch ( const Storage::Exception & exception )\n {\n\tST_CAUGHT( exception );\n\n\t\/\/ Handle exception: Display errors to the user etc.\n\t\/\/ ...\n\t\/\/ ...\n }\n\n \/\/ Intentionally NOT deleting staging or probed: They are owned by libstorage\n}\n<|endoftext|>"} {"text":"#include \"drawable.h\"\n\nusing namespace std;\n\nDrawable::Drawable() : m_idVAO(0), m_idVBO(0), m_shader(nullptr), m_model(1.0)\n{\n}\n\nDrawable::~Drawable()\n{\n glDeleteBuffers(1, &m_idVBO);\n glDeleteVertexArrays(1, &m_idVAO);\n}\n\nvoid Drawable::setShader(Shader* shader)\n{\n m_shader = shader;\n}\n\nvoid Drawable::setModel(glm::mat4 model)\n{\n m_model = model;\n}\n\nconst Shader* Drawable::getShader() const\n{\n return m_shader;\n}\n\nconst glm::mat4& Drawable::getModel() const\n{\n return m_model;\n}\n\nGLuint Drawable::getIdVAO() const\n{\n return m_idVAO;\n}\n\nGLuint Drawable::getIdVBO() const\n{\n return m_idVBO;\n}\n\nGLuint Drawable::getIdIBO() const\n{\n return m_idIBO;\n}\nint Drawable::getVerticesNumber() const\n{\n return m_verticesNumber;\n}\n\nint Drawable::getIndicesNumber() const\n{\n return m_indicesNumber;\n}\n\nvoid Drawable::rotate(glm::vec3 axis, float angle)\n{\n m_model = glm::rotate(m_model, angle, axis);\n}\n\nvoid Drawable::translate(glm::vec3 translation)\n{\n m_model = glm::translate(m_model, translation);\n}\n\nvoid Drawable::homothetie(glm::vec3 homoth)\n{\n m_model = glm::scale(m_model, homoth);\n}\n\nvoid Drawable::load(std::vector const &vertices, std::vector const &indices)\n{\n int sizeVertices = sizeof(glm::vec3) * vertices.size();\n int sizeIBO = sizeof(glm::uvec3) * indices.size();\n\n if (glIsVertexArray(m_idVAO) == GL_TRUE)\n glDeleteVertexArrays(1, &m_idVAO);\n\n glGenVertexArrays(1, &m_idVAO);\n glBindVertexArray(m_idVAO);\n\n if (glIsBuffer(m_idVBO) == GL_TRUE)\n glDeleteBuffers(1, &m_idVBO);\n\n glGenBuffers(1, &m_idVBO);\n glBindBuffer(GL_ARRAY_BUFFER, m_idVBO);\n glBufferData(GL_ARRAY_BUFFER, sizeVertices, &vertices[0], GL_STATIC_DRAW);\n glEnableVertexAttribArray(0);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n if (glIsBuffer(m_idIBO) == GL_TRUE)\n glDeleteBuffers(1, &m_idIBO);\n\n glGenBuffers(1, &m_idIBO);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_idIBO);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeIBO, &indices[0], GL_STATIC_DRAW);\n\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n\n m_indicesNumber = indices.size() * 3 ;\n m_verticesNumber = vertices.size() * 3 ;\n\n}\n\nvoid Drawable::update(const std::vector &data, int offset)\n{\n glBindBuffer(GL_ARRAY_BUFFER, m_idVBO);\n void* VBOAddress = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);\n if (VBOAddress == NULL)\n {\n std::cerr << \"Erreur au niveau de la récupération du VBO\" << std::endl;\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n return;\n }\n memcpy(GET_ADDRESS(VBOAddress, offset), &data[0], data.size() * sizeof(float));\n\n glUnmapBuffer(GL_ARRAY_BUFFER);\n VBOAddress = NULL;\n\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\nSEGFAULT FIXED \\!\\!\\!#include \"drawable.h\"\n\nusing namespace std;\n\nDrawable::Drawable() : m_idVAO(0), m_idVBO(0), m_idIBO(0), m_shader(nullptr), m_model(1.0)\n{\n}\n\nDrawable::~Drawable()\n{\n glDeleteBuffers(1, &m_idVBO);\n glDeleteVertexArrays(1, &m_idVAO);\n}\n\nvoid Drawable::setShader(Shader* shader)\n{\n m_shader = shader;\n}\n\nvoid Drawable::setModel(glm::mat4 model)\n{\n m_model = model;\n}\n\nconst Shader* Drawable::getShader() const\n{\n return m_shader;\n}\n\nconst glm::mat4& Drawable::getModel() const\n{\n return m_model;\n}\n\nGLuint Drawable::getIdVAO() const\n{\n return m_idVAO;\n}\n\nGLuint Drawable::getIdVBO() const\n{\n return m_idVBO;\n}\n\nGLuint Drawable::getIdIBO() const\n{\n return m_idIBO;\n}\nint Drawable::getVerticesNumber() const\n{\n return m_verticesNumber;\n}\n\nint Drawable::getIndicesNumber() const\n{\n return m_indicesNumber;\n}\n\nvoid Drawable::rotate(glm::vec3 axis, float angle)\n{\n m_model = glm::rotate(m_model, angle, axis);\n}\n\nvoid Drawable::translate(glm::vec3 translation)\n{\n m_model = glm::translate(m_model, translation);\n}\n\nvoid Drawable::homothetie(glm::vec3 homoth)\n{\n m_model = glm::scale(m_model, homoth);\n}\n\nvoid Drawable::load(std::vector const &vertices, std::vector const &indices)\n{\n int sizeVertices = sizeof(glm::vec3) * vertices.size();\n int sizeIBO = sizeof(glm::uvec3) * indices.size();\n\n if (glIsVertexArray(m_idVAO) == GL_TRUE)\n glDeleteVertexArrays(1, &m_idVAO);\n\n glGenVertexArrays(1, &m_idVAO);\n glBindVertexArray(m_idVAO);\n\n if (glIsBuffer(m_idVBO) == GL_TRUE)\n glDeleteBuffers(1, &m_idVBO);\n\n glGenBuffers(1, &m_idVBO);\n glBindBuffer(GL_ARRAY_BUFFER, m_idVBO);\n glBufferData(GL_ARRAY_BUFFER, sizeVertices, &vertices[0], GL_STATIC_DRAW);\n glEnableVertexAttribArray(0);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n if (glIsBuffer(m_idIBO) == GL_TRUE)\n glDeleteBuffers(1, &m_idIBO);\n\n glGenBuffers(1, &m_idIBO);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_idIBO);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeIBO, &indices[0], GL_STATIC_DRAW);\n\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\n\n m_indicesNumber = indices.size() * 3 ;\n m_verticesNumber = vertices.size() * 3 ;\n\n}\n\nvoid Drawable::update(const std::vector &data, int offset)\n{\n glBindBuffer(GL_ARRAY_BUFFER, m_idVBO);\n void* VBOAddress = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);\n if (VBOAddress == NULL)\n {\n std::cerr << \"Erreur au niveau de la récupération du VBO\" << std::endl;\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n return;\n }\n memcpy(GET_ADDRESS(VBOAddress, offset), &data[0], data.size() * sizeof(float));\n\n glUnmapBuffer(GL_ARRAY_BUFFER);\n VBOAddress = NULL;\n\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n<|endoftext|>"} {"text":"Update CmdLineInterface.hpp#ifndef CmdLineInterface_hpp\r\n#define CmdLineInterface_hpp\r\n\r\n#include \"AppConfig.hpp\"\r\n\r\nclass CmdLineInterface\r\n{\r\n private:\r\n \/\/void printUsage(std::string name);\r\n AppConfig config;\r\n public:\r\n CmdLineInterface(int argc, char *argv[]);\r\n AppConfig getConfig();\r\n};\r\n\r\n#endif \/* CmdLineInterface_hpp *\/\r\n<|endoftext|>"} {"text":"\/*\topendatacon\n *\n *\tCopyright (c) 2014:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\t\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\t\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/ \n\/*\n * DataConcentrator.cpp\n *\n * Created on: 15\/07\/2014\n * Author: Neil Stephens \n *\/\n\n#ifdef WIN32\n\n#else\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \"DataConcentrator.h\"\n#include \"Console.h\"\n\n#include \n#include \"logging_cmds.h\"\n#include \"NullPort.h\"\n\n#include \"..\/WebUI\/WebUI.h\"\n\nDataConcentrator::DataConcentrator(std::string FileName):\n\tConfigParser(FileName),\n\tDNP3Mgr(std::thread::hardware_concurrency()),\n\tLOG_LEVEL(opendnp3::levels::NORMAL),\n\tAdvConsoleLog(asiodnp3::ConsoleLogger::Instance(),LOG_LEVEL),\n\tFileLog(\"datacon_log\"),\n\tAdvFileLog(FileLog,LOG_LEVEL),\n\tIOS(std::thread::hardware_concurrency()),\n\tios_working(new asio::io_service::work(IOS)),\n UI(new WebUI(10443))\n{\n\t\/\/fire up some worker threads\n\tfor(size_t i=0; i < std::thread::hardware_concurrency(); ++i)\n\t\tstd::thread([&](){IOS.run();}).detach();\n\n\tAdvConsoleLog.AddIngoreAlways(\".*\"); \/\/silence all console messages by default\n\tDNP3Mgr.AddLogSubscriber(&AdvConsoleLog);\n\tDNP3Mgr.AddLogSubscriber(&AdvFileLog);\n\n\t\/\/Parse the configs and create all the ports and connections\n\tProcessFile();\n\n UI->AddResponder(\"\/DataPorts\", DataPorts);\n UI->AddResponder(\"\/DataConnectors\", DataConnectors);\n \n \/\/Initialise Data Ports\n\tfor(auto& port : DataPorts)\n\t{\n\t\tport.second->AddLogSubscriber(&AdvConsoleLog);\n\t\tport.second->AddLogSubscriber(&AdvFileLog);\n\t\tport.second->SetIOS(&IOS);\n\t\tport.second->SetLogLevel(LOG_LEVEL);\n }\n \n \/\/Initialise Data Connectors\n\tfor(auto& conn : DataConnectors)\n\t{\n\t\tconn.second->AddLogSubscriber(&AdvConsoleLog);\n\t\tconn.second->AddLogSubscriber(&AdvFileLog);\n\t\tconn.second->SetIOS(&IOS);\n\t\tconn.second->SetLogLevel(LOG_LEVEL);\n\t}\n}\nDataConcentrator::~DataConcentrator()\n{\n\t\/\/turn everything off\n\tthis->Shutdown();\n\tDNP3Mgr.Shutdown();\n\t\/\/tell the io service to let it's run functions return once there's no handlers left (letting our threads end)\n\tios_working.reset();\n\t\/\/help finish any work\n\tIOS.run();\n}\n\nvoid DataConcentrator::ProcessElements(const Json::Value& JSONRoot)\n{\n\tif(!JSONRoot[\"LogFileSizekB\"].isNull())\n\t\tFileLog.SetLogFileSizekB(JSONRoot[\"LogFileSizekB\"].asUInt());\n\n\tif(!JSONRoot[\"NumLogFiles\"].isNull())\n\t\tFileLog.SetNumLogFiles(JSONRoot[\"NumLogFiles\"].asUInt());\n\n\tif(!JSONRoot[\"LogName\"].isNull())\n\t\tFileLog.SetLogName(JSONRoot[\"LogName\"].asString());\n\n\tif(!JSONRoot[\"LOG_LEVEL\"].isNull())\n\t{\n\t\tstd::string value = JSONRoot[\"LOG_LEVEL\"].asString();\n\t\tif(value == \"ALL\")\n\t\t\tLOG_LEVEL = opendnp3::levels::ALL;\n\t\telse if(value == \"ALL_COMMS\")\n\t\t\tLOG_LEVEL = opendnp3::levels::ALL_COMMS;\n\t\telse if(value == \"NORMAL\")\n\t\t\tLOG_LEVEL = opendnp3::levels::NORMAL;\n\t\telse if(value == \"NOTHING\")\n\t\t\tLOG_LEVEL = opendnp3::levels::NOTHING;\n\t\telse\n\t\t\tstd::cout << \"Warning: invalid LOG_LEVEL setting: '\" << value << \"' : ignoring and using 'NORMAL' log level.\" << std::endl;\n\t\tAdvFileLog.SetLogLevel(LOG_LEVEL);\n\t\tAdvConsoleLog.SetLogLevel(LOG_LEVEL);\n\t}\n\n\tif(!JSONRoot[\"Ports\"].isNull())\n\t{\n\t\tconst Json::Value Ports = JSONRoot[\"Ports\"];\n\n\t\tfor(Json::Value::ArrayIndex n = 0; n < Ports.size(); ++n)\n\t\t{\n\t\t\tif(Ports[n][\"Type\"].isNull() || Ports[n][\"Name\"].isNull() || Ports[n][\"ConfFilename\"].isNull())\n\t\t\t{\n\t\t\t\tstd::cout<<\"Warning: invalid port config: need at least Type, Name, ConfFilename: \\n'\"<(new NullPort(Ports[n][\"Name\"].asString(), Ports[n][\"ConfFilename\"].asString(), Ports[n][\"ConfOverrides\"]));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Looks for a specific library (for libs that implement more than one class)\n\t\t\t\tstd::string libname;\n\t\t\t\tif(!Ports[n][\"Library\"].isNull())\n\t\t\t\t{\n\t\t\t\t\tlibname = GetLibFileName(Ports[n][\"Library\"].asString());\n\t\t\t\t}\n\t\t\t\t\/\/Otherwise use the naming convention libPort.so to find the default lib that implements a type of port\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tlibname = GetLibFileName(Ports[n][\"Type\"].asString());\n\t\t\t\t}\n\n\t\t\t\t\/\/try to load the lib\n\t\t\t\tauto* portlib = DYNLIBLOAD(libname.c_str());\n\n\t\t\t\tif(portlib == nullptr)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Warning: failed to load library '\"<Port(Name, Filename, Overrides)\n\t\t\t\t\/\/it should return a pointer to a heap allocated instance of a descendant of DataPort\n\t\t\t\tstd::string new_funcname = \"new_\"+Ports[n][\"Type\"].asString()+\"Port\";\n\t\t\t\tauto new_port_func = (DataPort*(*)(std::string, std::string, const Json::Value))DYNLIBGETSYM(portlib, new_funcname.c_str());\n\n\t\t\t\tif(new_port_func == nullptr)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Warning: failed to load symbol '\"<(new_port_func(Ports[n][\"Name\"].asString(), Ports[n][\"ConfFilename\"].asString(), Ports[n][\"ConfOverrides\"]));\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!JSONRoot[\"Connectors\"].isNull())\n\t{\n\t\tconst Json::Value Connectors = JSONRoot[\"Connectors\"];\n\n\t\tfor(Json::Value::ArrayIndex n = 0; n < Connectors.size(); ++n)\n\t\t{\n\t\t\tif(Connectors[n][\"Name\"].isNull() || Connectors[n][\"ConfFilename\"].isNull())\n\t\t\t{\n\t\t\t\tstd::cout<<\"Warning: invalid Connector config: need at least Name, ConfFilename: \\n'\"<(new DataConnector(Connectors[n][\"Name\"].asString(), Connectors[n][\"ConfFilename\"].asString(), Connectors[n][\"ConfOverrides\"]));\n\t\t}\n\t}\n}\nvoid DataConcentrator::BuildOrRebuild()\n{\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tName_n_Port.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);\n\t}\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tName_n_Conn.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);\n\t}\n}\nvoid DataConcentrator::Run()\n{\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tIOS.post([=]()\n\t\t{\n\t\t\tName_n_Conn.second->Enable();\n\t\t});\n\t}\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tIOS.post([=]()\n\t\t{\n\t\t\tName_n_Port.second->Enable();\n\t\t});\n\t}\n\n\tConsole console(\"odc> \");\n \n UI->start();\n\n\tstd::function bound_func;\n\n\t\/\/Version\n\tbound_func = [](std::stringstream& ss){std::cout<<\"Release 0.2\"<Enable() : Name_n_Conn.second->Disable();\n\t}\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tif(std::regex_match(Name_n_Port.first, reg))\n\t\t\tenable ? Name_n_Port.second->Enable() : Name_n_Port.second->Disable();\n\t}\n}\nvoid DataConcentrator::ListPorts(std::stringstream& args)\n{\n\tstd::string arg = \"\";\n\tstd::string mregex;\n\tstd::regex reg;\n\tif(!extract_delimited_string(args,mregex))\n\t{\n\t\tstd::cout<<\"Syntax error: Delimited regex expected, found \\\"...\"<stop();\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tName_n_Port.second->Disable();\n\t}\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tName_n_Conn.second->Disable();\n\t}\n}\nStart WebUI as soon as DataConcentrator is created\/*\topendatacon\n *\n *\tCopyright (c) 2014:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\t\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\t\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/ \n\/*\n * DataConcentrator.cpp\n *\n * Created on: 15\/07\/2014\n * Author: Neil Stephens \n *\/\n\n#ifdef WIN32\n\n#else\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \"DataConcentrator.h\"\n#include \"Console.h\"\n\n#include \n#include \"logging_cmds.h\"\n#include \"NullPort.h\"\n\n#include \"..\/WebUI\/WebUI.h\"\n\nDataConcentrator::DataConcentrator(std::string FileName):\n\tConfigParser(FileName),\n\tDNP3Mgr(std::thread::hardware_concurrency()),\n\tLOG_LEVEL(opendnp3::levels::NORMAL),\n\tAdvConsoleLog(asiodnp3::ConsoleLogger::Instance(),LOG_LEVEL),\n\tFileLog(\"datacon_log\"),\n\tAdvFileLog(FileLog,LOG_LEVEL),\n\tIOS(std::thread::hardware_concurrency()),\n\tios_working(new asio::io_service::work(IOS)),\n UI(new WebUI(10443))\n{\n UI->start();\n\n\t\/\/fire up some worker threads\n\tfor(size_t i=0; i < std::thread::hardware_concurrency(); ++i)\n\t\tstd::thread([&](){IOS.run();}).detach();\n\n\tAdvConsoleLog.AddIngoreAlways(\".*\"); \/\/silence all console messages by default\n\tDNP3Mgr.AddLogSubscriber(&AdvConsoleLog);\n\tDNP3Mgr.AddLogSubscriber(&AdvFileLog);\n\n\t\/\/Parse the configs and create all the ports and connections\n\tProcessFile();\n\n UI->AddResponder(\"\/DataPorts\", DataPorts);\n UI->AddResponder(\"\/DataConnectors\", DataConnectors);\n \n \/\/Initialise Data Ports\n\tfor(auto& port : DataPorts)\n\t{\n\t\tport.second->AddLogSubscriber(&AdvConsoleLog);\n\t\tport.second->AddLogSubscriber(&AdvFileLog);\n\t\tport.second->SetIOS(&IOS);\n\t\tport.second->SetLogLevel(LOG_LEVEL);\n }\n \n \/\/Initialise Data Connectors\n\tfor(auto& conn : DataConnectors)\n\t{\n\t\tconn.second->AddLogSubscriber(&AdvConsoleLog);\n\t\tconn.second->AddLogSubscriber(&AdvFileLog);\n\t\tconn.second->SetIOS(&IOS);\n\t\tconn.second->SetLogLevel(LOG_LEVEL);\n\t}\n}\nDataConcentrator::~DataConcentrator()\n{\n\t\/\/turn everything off\n\tthis->Shutdown();\n\tDNP3Mgr.Shutdown();\n\t\/\/tell the io service to let it's run functions return once there's no handlers left (letting our threads end)\n\tios_working.reset();\n\t\/\/help finish any work\n\tIOS.run();\n \n UI->stop();\n}\n\nvoid DataConcentrator::ProcessElements(const Json::Value& JSONRoot)\n{\n\tif(!JSONRoot[\"LogFileSizekB\"].isNull())\n\t\tFileLog.SetLogFileSizekB(JSONRoot[\"LogFileSizekB\"].asUInt());\n\n\tif(!JSONRoot[\"NumLogFiles\"].isNull())\n\t\tFileLog.SetNumLogFiles(JSONRoot[\"NumLogFiles\"].asUInt());\n\n\tif(!JSONRoot[\"LogName\"].isNull())\n\t\tFileLog.SetLogName(JSONRoot[\"LogName\"].asString());\n\n\tif(!JSONRoot[\"LOG_LEVEL\"].isNull())\n\t{\n\t\tstd::string value = JSONRoot[\"LOG_LEVEL\"].asString();\n\t\tif(value == \"ALL\")\n\t\t\tLOG_LEVEL = opendnp3::levels::ALL;\n\t\telse if(value == \"ALL_COMMS\")\n\t\t\tLOG_LEVEL = opendnp3::levels::ALL_COMMS;\n\t\telse if(value == \"NORMAL\")\n\t\t\tLOG_LEVEL = opendnp3::levels::NORMAL;\n\t\telse if(value == \"NOTHING\")\n\t\t\tLOG_LEVEL = opendnp3::levels::NOTHING;\n\t\telse\n\t\t\tstd::cout << \"Warning: invalid LOG_LEVEL setting: '\" << value << \"' : ignoring and using 'NORMAL' log level.\" << std::endl;\n\t\tAdvFileLog.SetLogLevel(LOG_LEVEL);\n\t\tAdvConsoleLog.SetLogLevel(LOG_LEVEL);\n\t}\n\n\tif(!JSONRoot[\"Ports\"].isNull())\n\t{\n\t\tconst Json::Value Ports = JSONRoot[\"Ports\"];\n\n\t\tfor(Json::Value::ArrayIndex n = 0; n < Ports.size(); ++n)\n\t\t{\n\t\t\tif(Ports[n][\"Type\"].isNull() || Ports[n][\"Name\"].isNull() || Ports[n][\"ConfFilename\"].isNull())\n\t\t\t{\n\t\t\t\tstd::cout<<\"Warning: invalid port config: need at least Type, Name, ConfFilename: \\n'\"<(new NullPort(Ports[n][\"Name\"].asString(), Ports[n][\"ConfFilename\"].asString(), Ports[n][\"ConfOverrides\"]));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Looks for a specific library (for libs that implement more than one class)\n\t\t\t\tstd::string libname;\n\t\t\t\tif(!Ports[n][\"Library\"].isNull())\n\t\t\t\t{\n\t\t\t\t\tlibname = GetLibFileName(Ports[n][\"Library\"].asString());\n\t\t\t\t}\n\t\t\t\t\/\/Otherwise use the naming convention libPort.so to find the default lib that implements a type of port\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tlibname = GetLibFileName(Ports[n][\"Type\"].asString());\n\t\t\t\t}\n\n\t\t\t\t\/\/try to load the lib\n\t\t\t\tauto* portlib = DYNLIBLOAD(libname.c_str());\n\n\t\t\t\tif(portlib == nullptr)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Warning: failed to load library '\"<Port(Name, Filename, Overrides)\n\t\t\t\t\/\/it should return a pointer to a heap allocated instance of a descendant of DataPort\n\t\t\t\tstd::string new_funcname = \"new_\"+Ports[n][\"Type\"].asString()+\"Port\";\n\t\t\t\tauto new_port_func = (DataPort*(*)(std::string, std::string, const Json::Value))DYNLIBGETSYM(portlib, new_funcname.c_str());\n\n\t\t\t\tif(new_port_func == nullptr)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Warning: failed to load symbol '\"<(new_port_func(Ports[n][\"Name\"].asString(), Ports[n][\"ConfFilename\"].asString(), Ports[n][\"ConfOverrides\"]));\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!JSONRoot[\"Connectors\"].isNull())\n\t{\n\t\tconst Json::Value Connectors = JSONRoot[\"Connectors\"];\n\n\t\tfor(Json::Value::ArrayIndex n = 0; n < Connectors.size(); ++n)\n\t\t{\n\t\t\tif(Connectors[n][\"Name\"].isNull() || Connectors[n][\"ConfFilename\"].isNull())\n\t\t\t{\n\t\t\t\tstd::cout<<\"Warning: invalid Connector config: need at least Name, ConfFilename: \\n'\"<(new DataConnector(Connectors[n][\"Name\"].asString(), Connectors[n][\"ConfFilename\"].asString(), Connectors[n][\"ConfOverrides\"]));\n\t\t}\n\t}\n}\nvoid DataConcentrator::BuildOrRebuild()\n{\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tName_n_Port.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);\n\t}\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tName_n_Conn.second->BuildOrRebuild(DNP3Mgr,LOG_LEVEL);\n\t}\n}\nvoid DataConcentrator::Run()\n{\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tIOS.post([=]()\n\t\t{\n\t\t\tName_n_Conn.second->Enable();\n\t\t});\n\t}\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tIOS.post([=]()\n\t\t{\n\t\t\tName_n_Port.second->Enable();\n\t\t});\n\t}\n\n\tConsole console(\"odc> \");\n \n\tstd::function bound_func;\n\n\t\/\/Version\n\tbound_func = [](std::stringstream& ss){std::cout<<\"Release 0.2\"<Enable() : Name_n_Conn.second->Disable();\n\t}\n\tfor(auto& Name_n_Port : DataPorts)\n\t{\n\t\tif(std::regex_match(Name_n_Port.first, reg))\n\t\t\tenable ? Name_n_Port.second->Enable() : Name_n_Port.second->Disable();\n\t}\n}\nvoid DataConcentrator::ListPorts(std::stringstream& args)\n{\n\tstd::string arg = \"\";\n\tstd::string mregex;\n\tstd::regex reg;\n\tif(!extract_delimited_string(args,mregex))\n\t{\n\t\tstd::cout<<\"Syntax error: Delimited regex expected, found \\\"...\"<Disable();\n\t}\n\tfor(auto& Name_n_Conn : DataConnectors)\n\t{\n\t\tName_n_Conn.second->Disable();\n\t}\n}\n<|endoftext|>"} {"text":"\n\n#include \"DiscoveryVisitor.hpp\"\n#include \"DataExtractor.hpp\"\n\n#include \"util.hpp\"\n#include \"Type.hpp\"\n\n\nnamespace autobind {\n\nstd::string prototypeSpelling(clang::FunctionDecl *decl)\n{\n\tstd::string result;\n\tbool first = true;\n\n\tresult += decl->getResultType().getAsString();\n\tresult += \" \";\n\tresult += decl->getQualifiedNameAsString();\n\n\tresult += \"(\";\n\n\tfor(auto param : PROP_RANGE(decl->param))\n\t{\n\t\tif(first) first = false;\n\t\telse result += \", \";\n\n\t\tresult += param->getType().getAsString();\n\t\tresult += \" \";\n\t\tresult += param->getNameAsString();\n\n\t}\n\tresult += \")\";\n\n\treturn result;\n}\n\n\nauto attributeStream(clang::Decl &x)\n{\n\treturn streams::stream(x.specific_attr_begin(),\n\t x.specific_attr_end());\n}\n\nbool isPyExport(clang::Decl *d)\n{\n\tusing namespace streams;\n\n\tauto pred = [](auto a) { return a->getAnnotation() == \"pyexport\"; };\n\treturn any(attributeStream(*d) | transformed(pred));\n}\n\n\nclass DiscoveryVisitor\n: public clang::RecursiveASTVisitor\n{\n\tDataExtractor _wrapperEmitter;\n\tbool _foundModule = false;\n\tstd::vector _matches;\n\tautobind::ModuleManager &_modmgr;\n\tstd::vector _modstack;\npublic:\n\n\texplicit DiscoveryVisitor(clang::ASTContext *context, autobind::ModuleManager &modmgr)\n\t: _wrapperEmitter(context)\n\t, _modmgr(modmgr)\n\t{\n\t\t\t\t\n\t}\n\n\n\tbool checkInModule(clang::Decl *d)\n\t{\n\t\tif(_modstack.empty())\n\t\t{\n\t\t\tauto &diags = d->getASTContext().getDiagnostics();\n\t\t\tunsigned id = diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n\t\t\t \"python exports must be preceded by module declaration\");\n\t\t\tdiags.Report(d->getLocation(), id);\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool VisitCXXRecordDecl(clang::CXXRecordDecl *decl)\n\t{\n\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\tif(!checkInModule(decl)) return false;\n\n\t\t\tauto name = decl->getQualifiedNameAsString();\n\t\t\tauto unqualName = rsplit(name, \"::\").second;\n\n\/\/ \t\t\tassert(!_modstack.empty());\n\t\t\tauto ty = std::make_unique(unqualName, name, \"\");\n\t\t\tusing namespace streams;\n\n\t\t\tbool foundConstructor = false;\n\n\t\t\tif(decl->hasTrivialCopyConstructor())\n\t\t\t{\n\t\t\t\tty->setCopyAvailable();\n\t\t\t}\n\t\t\t\n\t\t\tfor(auto field : stream(decl->decls_begin(), decl->decls_end()))\n\t\t\t{\n\/\/ \t\t\t\tif(llvm::dyn_cast_or_null(field)\n\/\/ \t\t\t \t\t|| llvm::dyn_cast_or_null(field)) \n\/\/ \t\t\t\t{\n\/\/ \t\t\t\t\tcontinue;\n\/\/ \t\t\t\t}\n\t\t\t\tif(auto constructor = llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\tif(!foundConstructor && !constructor->isCopyOrMoveConstructor())\n\t\t\t\t\t{\n\t\t\t\t\t\tfoundConstructor = true;\n\t\t\t\t\t\tauto cdata = _wrapperEmitter.function(constructor);\n\t\t\t\t\t\tcdata->setReturnType(\"void\"); \/\/ prevents attempting to convert result type\n\t\t\t\t\t\tty->setConstructor(std::move(cdata));\n\t\t\t\t\t\tstd::cerr << \"--> found constructor: \"<< constructor->getQualifiedNameAsString() << \"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if(constructor->isCopyConstructor())\n\t\t\t\t\t{\n\t\t\t\t\t\tty->setCopyAvailable();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\t\/\/ ignore\n\t\t\t\t}\n\t\t\t\telse if(auto method = llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\tif(!method->isOverloadedOperator() && method->getAccess() == clang::AS_public)\n\t\t\t\t\t{\n\/\/ \t\t\t\t\t\tstd::cerr << \"--> found method: \" << method->getQualifiedNameAsString() << \"\\n\";\n\t\t\t\t\t\tauto mdata = _wrapperEmitter.method(method);\n\t\t\t\t\t\tty->addMethod(std::move(mdata));\n\t\t\t\t\t}\n\/\/ \t\t\t\t\telse\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tstd::cerr << \"--> ignored method: \"<< method->getQualifiedNameAsString() << \"\\n\";\n\/\/ \t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t_modstack.back()->addExport(std::move(ty));\n\n\n\n\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool VisitNamespaceDecl(clang::NamespaceDecl *decl)\n\t{\n\t\tusing namespace streams;\n\n\t\tauto stream = attributeStream(*decl)\n\t\t\t| filtered([](auto a) { return a->getAnnotation().startswith(\"py:module:\"); });\n\n\n\t\tif(!stream.empty())\n\t\t{\n\t\t\tif(_foundModule)\n\t\t\t{\n\t\t\t\tauto &diags = decl->getASTContext().getDiagnostics();\n\t\t\t\tunsigned id = diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n\t\t\t\t \"redeclaration of module name\");\n\n\t\t\t\tdiags.Report(decl->getLocation(), id);\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto parts = stream.front()->getAnnotation().rsplit(':');\n\t\t\t_modstack.insert(_modstack.begin(), &_modmgr.module(parts.second));\n\t\t\t_foundModule = true;\n\n\t\t}\n\n\t\tauto docstringStream = attributeStream(*decl)\n\t\t\t| filtered([](auto a) { return a->getAnnotation().startswith(\"pydocstring:\"); });\n\n\t\tif(!docstringStream.empty())\n\t\t{\n\t\t\tauto ann = docstringStream.front()->getAnnotation();\n\t\t\tcheckInModule(decl);\n\t\t\t\n\t\t\t_modstack.back()->setDocstring(ann.split(':').second);\n\t\t}\n\n\n\t\treturn true;\n\t}\n\n\n\tbool TraverseNamespaceDecl(clang::NamespaceDecl *decl)\n\t{\n\n\t\tbool pushed = false;\n\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\t_modstack.push_back(&_modmgr.module(decl->getNameAsString()));\n\n\t\t\tif(auto comment = decl->getASTContext().getRawCommentForAnyRedecl(decl))\n\t\t\t{\n\t\t\t\tif(comment->isDocumentation())\n\t\t\t\t{\n\t\t\t\t\t_modstack.back()->setDocstring(comment->getRawText(decl->getASTContext().getSourceManager()));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tpushed = true;\n\t\t}\n\n\t\tbool result = clang::RecursiveASTVisitor::TraverseNamespaceDecl(decl);\n\n\n\t\tif(pushed)\n\t\t{\n\t\t\tassert(!_modstack.empty());\n\t\t\t_modstack.pop_back();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\/\/ \n\/\/ \tbool VisitMethodDecl(clang::CXXMethodDecl *decl)\n\/\/ \t{\n\/\/ \t\tif(isPyExport(decl->getParent()))\n\/\/ \t\t{\n\/\/ \t\t\tif(!checkInModule(decl)) return false;\n\/\/ \n\/\/ \t\t\t\/\/ check not a structor\n\/\/ \t\t\tif(llvm::dyn_cast_or_null(decl)\n\/\/ \t\t\t || llvm::dyn_cast_or_null(decl))\n\/\/ \t\t\t{\n\/\/ \t\t\t\treturn true;\n\/\/ \t\t\t}\n\/\/ \n\/\/ \n\/\/ \t\t}\n\/\/ \t}\n\/\/ \n\tbool VisitFunctionDecl(clang::FunctionDecl *decl)\n\t{\n\t\t\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\tif(!checkInModule(decl)) return false;\n\t\t\t_modstack.back()->addExport(_wrapperEmitter.function(decl));\n\t\t}\n\t\t\n\n\t\treturn true;\n\t}\n\n\tconst std::vector &matches() const\n\t{\n\t\treturn _matches;\n\t}\n};\n\nvoid discoverTranslationUnit(autobind::ModuleManager &mgr,\n clang::TranslationUnitDecl &tu)\n{\n\tDiscoveryVisitor dv(&tu.getASTContext(), mgr);\n\tdv.TraverseDecl(&tu);\n\n}\n} \/\/ autobindFix copy constructor detection logic.\n\n#include \"DiscoveryVisitor.hpp\"\n#include \"DataExtractor.hpp\"\n\n#include \"util.hpp\"\n#include \"Type.hpp\"\n\n\nnamespace autobind {\n\nstd::string prototypeSpelling(clang::FunctionDecl *decl)\n{\n\tstd::string result;\n\tbool first = true;\n\n\tresult += decl->getResultType().getAsString();\n\tresult += \" \";\n\tresult += decl->getQualifiedNameAsString();\n\n\tresult += \"(\";\n\n\tfor(auto param : PROP_RANGE(decl->param))\n\t{\n\t\tif(first) first = false;\n\t\telse result += \", \";\n\n\t\tresult += param->getType().getAsString();\n\t\tresult += \" \";\n\t\tresult += param->getNameAsString();\n\n\t}\n\tresult += \")\";\n\n\treturn result;\n}\n\n\nauto attributeStream(clang::Decl &x)\n{\n\treturn streams::stream(x.specific_attr_begin(),\n\t x.specific_attr_end());\n}\n\nbool isPyExport(clang::Decl *d)\n{\n\tusing namespace streams;\n\n\tauto pred = [](auto a) { return a->getAnnotation() == \"pyexport\"; };\n\treturn any(attributeStream(*d) | transformed(pred));\n}\n\n\nclass DiscoveryVisitor\n: public clang::RecursiveASTVisitor\n{\n\tDataExtractor _wrapperEmitter;\n\tbool _foundModule = false;\n\tstd::vector _matches;\n\tautobind::ModuleManager &_modmgr;\n\tstd::vector _modstack;\npublic:\n\n\texplicit DiscoveryVisitor(clang::ASTContext *context, autobind::ModuleManager &modmgr)\n\t: _wrapperEmitter(context)\n\t, _modmgr(modmgr)\n\t{\n\t\t\t\t\n\t}\n\n\n\tbool checkInModule(clang::Decl *d)\n\t{\n\t\tif(_modstack.empty())\n\t\t{\n\t\t\tauto &diags = d->getASTContext().getDiagnostics();\n\t\t\tunsigned id = diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n\t\t\t \"python exports must be preceded by module declaration\");\n\t\t\tdiags.Report(d->getLocation(), id);\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool VisitCXXRecordDecl(clang::CXXRecordDecl *decl)\n\t{\n\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\tif(!checkInModule(decl)) return false;\n\n\t\t\tauto name = decl->getQualifiedNameAsString();\n\t\t\tauto unqualName = rsplit(name, \"::\").second;\n\n\/\/ \t\t\tassert(!_modstack.empty());\n\t\t\tauto ty = std::make_unique(unqualName, name, \"\");\n\t\t\tusing namespace streams;\n\n\t\t\tbool foundConstructor = false;\n\n\t\t\tif(decl->hasTrivialCopyConstructor() || decl->hasNonTrivialCopyConstructor())\n\t\t\t{\n\t\t\t\tty->setCopyAvailable();\n\t\t\t}\n\t\t\t\n\t\t\tfor(auto field : stream(decl->decls_begin(), decl->decls_end()))\n\t\t\t{\n\/\/ \t\t\t\tif(llvm::dyn_cast_or_null(field)\n\/\/ \t\t\t \t\t|| llvm::dyn_cast_or_null(field)) \n\/\/ \t\t\t\t{\n\/\/ \t\t\t\t\tcontinue;\n\/\/ \t\t\t\t}\n\t\t\t\tif(auto constructor = llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\tif(!foundConstructor && !constructor->isCopyOrMoveConstructor())\n\t\t\t\t\t{\n\t\t\t\t\t\tfoundConstructor = true;\n\t\t\t\t\t\tauto cdata = _wrapperEmitter.function(constructor);\n\t\t\t\t\t\tcdata->setReturnType(\"void\"); \/\/ prevents attempting to convert result type\n\t\t\t\t\t\tty->setConstructor(std::move(cdata));\n\t\t\t\t\t\tstd::cerr << \"--> found constructor: \"<< constructor->getQualifiedNameAsString() << \"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if(constructor->isCopyConstructor())\n\t\t\t\t\t{\n\t\t\t\t\t\tty->setCopyAvailable();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\t\/\/ ignore\n\t\t\t\t}\n\t\t\t\telse if(auto method = llvm::dyn_cast_or_null(field))\n\t\t\t\t{\n\t\t\t\t\tif(!method->isOverloadedOperator() && method->getAccess() == clang::AS_public)\n\t\t\t\t\t{\n\/\/ \t\t\t\t\t\tstd::cerr << \"--> found method: \" << method->getQualifiedNameAsString() << \"\\n\";\n\t\t\t\t\t\tauto mdata = _wrapperEmitter.method(method);\n\t\t\t\t\t\tty->addMethod(std::move(mdata));\n\t\t\t\t\t}\n\/\/ \t\t\t\t\telse\n\/\/ \t\t\t\t\t{\n\/\/ \t\t\t\t\t\tstd::cerr << \"--> ignored method: \"<< method->getQualifiedNameAsString() << \"\\n\";\n\/\/ \t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t_modstack.back()->addExport(std::move(ty));\n\n\n\n\n\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool VisitNamespaceDecl(clang::NamespaceDecl *decl)\n\t{\n\t\tusing namespace streams;\n\n\t\tauto stream = attributeStream(*decl)\n\t\t\t| filtered([](auto a) { return a->getAnnotation().startswith(\"py:module:\"); });\n\n\n\t\tif(!stream.empty())\n\t\t{\n\t\t\tif(_foundModule)\n\t\t\t{\n\t\t\t\tauto &diags = decl->getASTContext().getDiagnostics();\n\t\t\t\tunsigned id = diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n\t\t\t\t \"redeclaration of module name\");\n\n\t\t\t\tdiags.Report(decl->getLocation(), id);\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto parts = stream.front()->getAnnotation().rsplit(':');\n\t\t\t_modstack.insert(_modstack.begin(), &_modmgr.module(parts.second));\n\t\t\t_foundModule = true;\n\n\t\t}\n\n\t\tauto docstringStream = attributeStream(*decl)\n\t\t\t| filtered([](auto a) { return a->getAnnotation().startswith(\"pydocstring:\"); });\n\n\t\tif(!docstringStream.empty())\n\t\t{\n\t\t\tauto ann = docstringStream.front()->getAnnotation();\n\t\t\tcheckInModule(decl);\n\t\t\t\n\t\t\t_modstack.back()->setDocstring(ann.split(':').second);\n\t\t}\n\n\n\t\treturn true;\n\t}\n\n\n\tbool TraverseNamespaceDecl(clang::NamespaceDecl *decl)\n\t{\n\n\t\tbool pushed = false;\n\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\t_modstack.push_back(&_modmgr.module(decl->getNameAsString()));\n\n\t\t\tif(auto comment = decl->getASTContext().getRawCommentForAnyRedecl(decl))\n\t\t\t{\n\t\t\t\tif(comment->isDocumentation())\n\t\t\t\t{\n\t\t\t\t\t_modstack.back()->setDocstring(comment->getRawText(decl->getASTContext().getSourceManager()));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tpushed = true;\n\t\t}\n\n\t\tbool result = clang::RecursiveASTVisitor::TraverseNamespaceDecl(decl);\n\n\n\t\tif(pushed)\n\t\t{\n\t\t\tassert(!_modstack.empty());\n\t\t\t_modstack.pop_back();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\n\/\/ \n\/\/ \tbool VisitMethodDecl(clang::CXXMethodDecl *decl)\n\/\/ \t{\n\/\/ \t\tif(isPyExport(decl->getParent()))\n\/\/ \t\t{\n\/\/ \t\t\tif(!checkInModule(decl)) return false;\n\/\/ \n\/\/ \t\t\t\/\/ check not a structor\n\/\/ \t\t\tif(llvm::dyn_cast_or_null(decl)\n\/\/ \t\t\t || llvm::dyn_cast_or_null(decl))\n\/\/ \t\t\t{\n\/\/ \t\t\t\treturn true;\n\/\/ \t\t\t}\n\/\/ \n\/\/ \n\/\/ \t\t}\n\/\/ \t}\n\/\/ \n\tbool VisitFunctionDecl(clang::FunctionDecl *decl)\n\t{\n\t\t\n\t\tif(isPyExport(decl))\n\t\t{\n\t\t\tif(!checkInModule(decl)) return false;\n\t\t\t_modstack.back()->addExport(_wrapperEmitter.function(decl));\n\t\t}\n\t\t\n\n\t\treturn true;\n\t}\n\n\tconst std::vector &matches() const\n\t{\n\t\treturn _matches;\n\t}\n};\n\nvoid discoverTranslationUnit(autobind::ModuleManager &mgr,\n clang::TranslationUnitDecl &tu)\n{\n\tDiscoveryVisitor dv(&tu.getASTContext(), mgr);\n\tdv.TraverseDecl(&tu);\n\n}\n} \/\/ autobind<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: querycontainerwindow.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2004-09-09 09:49:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#include \"querycontainerwindow.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNVIEW_HXX\n#include \"QueryDesignView.hxx\"\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _SFXSIDS_HRC\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_\n#include \n#endif\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::frame;\n\n \/\/=====================================================================\n \/\/= OQueryContainerWindow\n \/\/=====================================================================\n DBG_NAME(OQueryContainerWindow)\n OQueryContainerWindow::OQueryContainerWindow(Window* pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory)\n :ODataView(pParent,_pController, _rFactory)\n ,m_pBeamer(NULL)\n ,m_pViewSwitch(NULL)\n {\n DBG_CTOR(OQueryContainerWindow,NULL);\n m_pViewSwitch = new OQueryViewSwitch(this,_pController,_rFactory);\n\n m_pSplitter = new Splitter(this,WB_VSCROLL);\n m_pSplitter->Hide();\n m_pSplitter->SetSplitHdl( LINK( this, OQueryContainerWindow, SplitHdl ) );\n m_pSplitter->SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );\n }\n \/\/ -----------------------------------------------------------------------------\n OQueryContainerWindow::~OQueryContainerWindow()\n {\n DBG_DTOR(OQueryContainerWindow,NULL);\n {\n ::std::auto_ptr aTemp(m_pViewSwitch);\n m_pViewSwitch = NULL;\n }\n if ( m_pBeamer )\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pBeamer = NULL;\n if ( m_xBeamer.is() )\n {\n Reference< ::com::sun::star::util::XCloseable > xCloseable(m_xBeamer,UNO_QUERY);\n m_xBeamer = NULL;\n if(xCloseable.is())\n xCloseable->close(sal_False); \/\/ false - holds the owner ship of this frame\n \/\/ m_xBeamer->setComponent(NULL,NULL);\n }\n {\n ::std::auto_ptr aTemp(m_pSplitter);\n m_pSplitter = NULL;\n }\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool OQueryContainerWindow::switchView()\n {\n return m_pViewSwitch->switchView();\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::resizeAll( const Rectangle& _rPlayground )\n {\n Rectangle aPlayground( _rPlayground );\n\n if ( m_pBeamer && m_pBeamer->IsVisible() )\n {\n \/\/ calc pos and size of the splitter\n Point aSplitPos = m_pSplitter->GetPosPixel();\n Size aSplitSize = m_pSplitter->GetOutputSizePixel();\n aSplitSize.Width() = aPlayground.GetWidth();\n\n if ( aSplitPos.Y() <= aPlayground.Top() )\n aSplitPos.Y() = aPlayground.Top() + sal_Int32( aPlayground.GetHeight() * 0.2 );\n\n if ( aSplitPos.Y() + aSplitSize.Height() > aPlayground.GetHeight() )\n aSplitPos.Y() = aPlayground.GetHeight() - aSplitSize.Height();\n\n \/\/ set pos and size of the splitter\n m_pSplitter->SetPosSizePixel( aSplitPos, aSplitSize );\n m_pSplitter->SetDragRectPixel( aPlayground );\n\n \/\/ set pos and size of the beamer\n Size aBeamerSize( aPlayground.GetWidth(), aSplitPos.Y() );\n m_pBeamer->SetPosSizePixel( aPlayground.TopLeft(), aBeamerSize );\n\n \/\/ shrink the playground by the size which is occupied by the beamer\n aPlayground.Top() = aSplitPos.Y() + aSplitSize.Height();\n }\n\n ODataView::resizeAll( aPlayground );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::resizeDocumentView( Rectangle& _rPlayground )\n {\n m_pViewSwitch->SetPosSizePixel( _rPlayground.TopLeft(), Size( _rPlayground.GetWidth(), _rPlayground.GetHeight() ) );\n\n ODataView::resizeDocumentView( _rPlayground );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::GetFocus()\n {\n ODataView::GetFocus();\n if(m_pViewSwitch)\n m_pViewSwitch->GrabFocus();\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK( OQueryContainerWindow, SplitHdl, void*, p )\n {\n long nTest = m_pSplitter->GetPosPixel().Y();\n m_pSplitter->SetPosPixel( Point( m_pSplitter->GetPosPixel().X(),m_pSplitter->GetSplitPosPixel() ) );\n Resize();\n\n return 0L;\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::Construct()\n {\n m_pViewSwitch->Construct();\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::initialize(const Reference& _xFrame)\n {\n \/\/ append our frame\n Reference < XFramesSupplier > xSup(_xFrame,UNO_QUERY);\n Reference < XFrames > xFrames = xSup->getFrames();\n xFrames->append( m_xBeamer );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::disposingPreview()\n {\n if ( m_pBeamer )\n {\n \/\/ here I know that we will be destroyed from the frame\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pBeamer = NULL;\n m_xBeamer = NULL;\n m_pSplitter->Hide();\n Resize();\n }\n }\n \/\/ -----------------------------------------------------------------------------\n long OQueryContainerWindow::PreNotify( NotifyEvent& rNEvt )\n {\n BOOL bHandled = FALSE;\n switch (rNEvt.GetType())\n {\n case EVENT_GETFOCUS:\n if ( m_pViewSwitch )\n {\n OJoinController* pController = m_pViewSwitch->getDesignView()->getController();\n pController->InvalidateFeature(SID_CUT);\n pController->InvalidateFeature(SID_COPY);\n pController->InvalidateFeature(SID_PASTE);\n }\n }\n return bHandled ? 1L : ODataView::PreNotify(rNEvt);\n }\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::showPreview(const Reference& _xFrame)\n {\n if(!m_pBeamer)\n {\n m_pBeamer = new OBeamer(this);\n\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n\n m_xBeamer.set(m_pViewSwitch->getORB()->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.frame.Frame\")),UNO_QUERY);\n OSL_ENSURE(m_xBeamer.is(),\"No frame created!\");\n m_xBeamer->initialize( VCLUnoHelper::GetInterface ( m_pBeamer ) );\n m_xBeamer->setName(FRAME_NAME_QUERY_PREVIEW);\n\n \/\/ append our frame\n Reference < XFramesSupplier > xSup(_xFrame,UNO_QUERY);\n Reference < XFrames > xFrames = xSup->getFrames();\n xFrames->append( m_xBeamer );\n\n Size aSize = GetOutputSizePixel();\n Size aBeamer(aSize.Width(),sal_Int32(aSize.Height()*0.33));\n\n const long nFrameHeight = LogicToPixel( Size( 0, 3 ), MAP_APPFONT ).Height();\n Point aPos(0,aBeamer.Height()+nFrameHeight);\n\n m_pBeamer->SetPosSizePixel(Point(0,0),aBeamer);\n m_pBeamer->Show();\n\n m_pSplitter->SetPosSizePixel( Point(0,aBeamer.Height()), Size(aSize.Width(),nFrameHeight) );\n \/\/ a default pos for the splitter, so that the listbox is about 80 (logical) pixels wide\n m_pSplitter->SetSplitPosPixel( aBeamer.Height() );\n m_pViewSwitch->SetPosSizePixel(aPos,Size(aBeamer.Width(),aSize.Height() - aBeamer.Height()-nFrameHeight));\n\n m_pSplitter->Show();\n\n Resize();\n }\n }\n \/\/ -----------------------------------------------------------------------------\n\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n\nINTEGRATION: CWS ooo19126 (1.12.194); FILE MERGED 2005\/09\/05 17:35:39 rt 1.12.194.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: querycontainerwindow.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:33:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#include \"querycontainerwindow.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNVIEW_HXX\n#include \"QueryDesignView.hxx\"\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _SFXSIDS_HRC\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCLOSEABLE_HPP_\n#include \n#endif\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::frame;\n\n \/\/=====================================================================\n \/\/= OQueryContainerWindow\n \/\/=====================================================================\n DBG_NAME(OQueryContainerWindow)\n OQueryContainerWindow::OQueryContainerWindow(Window* pParent, OQueryController* _pController,const Reference< XMultiServiceFactory >& _rFactory)\n :ODataView(pParent,_pController, _rFactory)\n ,m_pBeamer(NULL)\n ,m_pViewSwitch(NULL)\n {\n DBG_CTOR(OQueryContainerWindow,NULL);\n m_pViewSwitch = new OQueryViewSwitch(this,_pController,_rFactory);\n\n m_pSplitter = new Splitter(this,WB_VSCROLL);\n m_pSplitter->Hide();\n m_pSplitter->SetSplitHdl( LINK( this, OQueryContainerWindow, SplitHdl ) );\n m_pSplitter->SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );\n }\n \/\/ -----------------------------------------------------------------------------\n OQueryContainerWindow::~OQueryContainerWindow()\n {\n DBG_DTOR(OQueryContainerWindow,NULL);\n {\n ::std::auto_ptr aTemp(m_pViewSwitch);\n m_pViewSwitch = NULL;\n }\n if ( m_pBeamer )\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pBeamer = NULL;\n if ( m_xBeamer.is() )\n {\n Reference< ::com::sun::star::util::XCloseable > xCloseable(m_xBeamer,UNO_QUERY);\n m_xBeamer = NULL;\n if(xCloseable.is())\n xCloseable->close(sal_False); \/\/ false - holds the owner ship of this frame\n \/\/ m_xBeamer->setComponent(NULL,NULL);\n }\n {\n ::std::auto_ptr aTemp(m_pSplitter);\n m_pSplitter = NULL;\n }\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool OQueryContainerWindow::switchView()\n {\n return m_pViewSwitch->switchView();\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::resizeAll( const Rectangle& _rPlayground )\n {\n Rectangle aPlayground( _rPlayground );\n\n if ( m_pBeamer && m_pBeamer->IsVisible() )\n {\n \/\/ calc pos and size of the splitter\n Point aSplitPos = m_pSplitter->GetPosPixel();\n Size aSplitSize = m_pSplitter->GetOutputSizePixel();\n aSplitSize.Width() = aPlayground.GetWidth();\n\n if ( aSplitPos.Y() <= aPlayground.Top() )\n aSplitPos.Y() = aPlayground.Top() + sal_Int32( aPlayground.GetHeight() * 0.2 );\n\n if ( aSplitPos.Y() + aSplitSize.Height() > aPlayground.GetHeight() )\n aSplitPos.Y() = aPlayground.GetHeight() - aSplitSize.Height();\n\n \/\/ set pos and size of the splitter\n m_pSplitter->SetPosSizePixel( aSplitPos, aSplitSize );\n m_pSplitter->SetDragRectPixel( aPlayground );\n\n \/\/ set pos and size of the beamer\n Size aBeamerSize( aPlayground.GetWidth(), aSplitPos.Y() );\n m_pBeamer->SetPosSizePixel( aPlayground.TopLeft(), aBeamerSize );\n\n \/\/ shrink the playground by the size which is occupied by the beamer\n aPlayground.Top() = aSplitPos.Y() + aSplitSize.Height();\n }\n\n ODataView::resizeAll( aPlayground );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::resizeDocumentView( Rectangle& _rPlayground )\n {\n m_pViewSwitch->SetPosSizePixel( _rPlayground.TopLeft(), Size( _rPlayground.GetWidth(), _rPlayground.GetHeight() ) );\n\n ODataView::resizeDocumentView( _rPlayground );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::GetFocus()\n {\n ODataView::GetFocus();\n if(m_pViewSwitch)\n m_pViewSwitch->GrabFocus();\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK( OQueryContainerWindow, SplitHdl, void*, p )\n {\n long nTest = m_pSplitter->GetPosPixel().Y();\n m_pSplitter->SetPosPixel( Point( m_pSplitter->GetPosPixel().X(),m_pSplitter->GetSplitPosPixel() ) );\n Resize();\n\n return 0L;\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::Construct()\n {\n m_pViewSwitch->Construct();\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::initialize(const Reference& _xFrame)\n {\n \/\/ append our frame\n Reference < XFramesSupplier > xSup(_xFrame,UNO_QUERY);\n Reference < XFrames > xFrames = xSup->getFrames();\n xFrames->append( m_xBeamer );\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::disposingPreview()\n {\n if ( m_pBeamer )\n {\n \/\/ here I know that we will be destroyed from the frame\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pBeamer = NULL;\n m_xBeamer = NULL;\n m_pSplitter->Hide();\n Resize();\n }\n }\n \/\/ -----------------------------------------------------------------------------\n long OQueryContainerWindow::PreNotify( NotifyEvent& rNEvt )\n {\n BOOL bHandled = FALSE;\n switch (rNEvt.GetType())\n {\n case EVENT_GETFOCUS:\n if ( m_pViewSwitch )\n {\n OJoinController* pController = m_pViewSwitch->getDesignView()->getController();\n pController->InvalidateFeature(SID_CUT);\n pController->InvalidateFeature(SID_COPY);\n pController->InvalidateFeature(SID_PASTE);\n }\n }\n return bHandled ? 1L : ODataView::PreNotify(rNEvt);\n }\n \/\/ -----------------------------------------------------------------------------\n void OQueryContainerWindow::showPreview(const Reference& _xFrame)\n {\n if(!m_pBeamer)\n {\n m_pBeamer = new OBeamer(this);\n\n ::dbaui::notifySystemWindow(this,m_pBeamer,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n\n m_xBeamer.set(m_pViewSwitch->getORB()->createInstance(::rtl::OUString::createFromAscii(\"com.sun.star.frame.Frame\")),UNO_QUERY);\n OSL_ENSURE(m_xBeamer.is(),\"No frame created!\");\n m_xBeamer->initialize( VCLUnoHelper::GetInterface ( m_pBeamer ) );\n m_xBeamer->setName(FRAME_NAME_QUERY_PREVIEW);\n\n \/\/ append our frame\n Reference < XFramesSupplier > xSup(_xFrame,UNO_QUERY);\n Reference < XFrames > xFrames = xSup->getFrames();\n xFrames->append( m_xBeamer );\n\n Size aSize = GetOutputSizePixel();\n Size aBeamer(aSize.Width(),sal_Int32(aSize.Height()*0.33));\n\n const long nFrameHeight = LogicToPixel( Size( 0, 3 ), MAP_APPFONT ).Height();\n Point aPos(0,aBeamer.Height()+nFrameHeight);\n\n m_pBeamer->SetPosSizePixel(Point(0,0),aBeamer);\n m_pBeamer->Show();\n\n m_pSplitter->SetPosSizePixel( Point(0,aBeamer.Height()), Size(aSize.Width(),nFrameHeight) );\n \/\/ a default pos for the splitter, so that the listbox is about 80 (logical) pixels wide\n m_pSplitter->SetSplitPosPixel( aBeamer.Height() );\n m_pViewSwitch->SetPosSizePixel(aPos,Size(aBeamer.Width(),aSize.Height() - aBeamer.Height()-nFrameHeight));\n\n m_pSplitter->Show();\n\n Resize();\n }\n }\n \/\/ -----------------------------------------------------------------------------\n\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\nclass CBlockMotd : public CModule {\npublic:\n\tMODCONSTRUCTOR(CBlockMotd) {\n\t}\n\n\tvirtual ~CBlockMotd() {\n\t}\n\n\tEModRet OnRaw(CString &sLine) override {\n\t\tconst CString sCmd = sLine.Token(1);\n\n\t\tif (sCmd == \"375\" \/* begin of MOTD *\/\n\t\t\t\t|| sCmd == \"372\" \/* MOTD *\/)\n\t\t\treturn HALT;\n\t\tif (sCmd == \"376\" \/* End of MOTD *\/) {\n\t\t\tsLine = sLine.Token(0) + \" 422 \" +\n\t\t\t\tsLine.Token(2) + \" :MOTD blocked by ZNC\";\n\t\t}\n\t\treturn CONTINUE;\n\t}\n};\n\ntemplate<> void TModInfo(CModInfo& Info) {\n\tInfo.AddType(CModInfo::NetworkModule);\n\tInfo.AddType(CModInfo::GlobalModule);\n\tInfo.SetWikiPage(\"block_motd\");\n}\n\nUSERMODULEDEFS(CBlockMotd, \"Block the MOTD from IRC so it's not sent to your client(s).\")\nblockmotd: Allow overriding via command\/*\n * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\nclass CBlockMotd : public CModule {\npublic:\n\tMODCONSTRUCTOR(CBlockMotd) {\n\t\tAddHelpCommand();\n\t\tAddCommand(\"GetMotd\", static_cast(&CBlockMotd::OverrideCommand), \"[]\", \"Override the block with this command. Can optionally specify which server to query.\");\n\t}\n\n\tvirtual ~CBlockMotd() {\n\t}\n\n\tvoid OverrideCommand(const CString& sLine) {\n\t\tm_bTemporaryAcceptMotd = true;\n\t\tconst CString sServer = sLine.Token(1);\n\n\t\tif (sServer.empty()) {\n\t\t\tPutIRC(\"motd\");\n\t\t} else {\n\t\t\tPutIRC(\"motd \" + sServer);\n\t\t}\n\t}\n\n\tEModRet OnRaw(CString &sLine) override {\n\t\tconst CString sCmd = sLine.Token(1);\n\n\t\tif ((sCmd == \"375\" \/* begin of MOTD *\/ || sCmd == \"372\" \/* MOTD *\/)\n\t\t\t&& !m_bTemporaryAcceptMotd)\n\t\t\treturn HALT;\n\t\t\n\t\tif (sCmd == \"376\" \/* End of MOTD *\/) {\n\t\t\tif (!m_bTemporaryAcceptMotd) {\n\t\t\t\tsLine = sLine.Token(0) + \" 422 \" +\n\t\t\t\t\tsLine.Token(2) + \" :MOTD blocked by ZNC\";\n\t\t\t}\n\t\t\tm_bTemporaryAcceptMotd = false;\n\t\t}\n\t\treturn CONTINUE;\n\t}\n\nprivate:\n\tbool m_bTemporaryAcceptMotd = false;\n};\n\ntemplate<> void TModInfo(CModInfo& Info) {\n\tInfo.AddType(CModInfo::NetworkModule);\n\tInfo.AddType(CModInfo::GlobalModule);\n\tInfo.SetWikiPage(\"block_motd\");\n}\n\nUSERMODULEDEFS(CBlockMotd, \"Block the MOTD from IRC so it's not sent to your client(s).\")\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2008-2012 J-P Nurmi \n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"menufactory.h\"\n#include \"messageview.h\"\n#include \"userlistview.h\"\n#include \"sessiontreeitem.h\"\n#include \"sessiontabwidget.h\"\n#include \"sessiontreewidget.h\"\n#include \"session.h\"\n#include \n\nMenuFactory::MenuFactory(QObject* parent) : QObject(parent)\n{\n}\n\nMenuFactory::~MenuFactory()\n{\n}\n\nclass UserViewMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n UserViewMenu(const QString& user, MessageView* view) :\n QMenu(view), user(user), view(view)\n {\n }\n\nprivate slots:\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(user);\n view->session()->sendCommand(command);\n }\n\n void onQueryTriggered()\n {\n QMetaObject::invokeMethod(view, \"queried\", Q_ARG(QString, user));\n }\n\nprivate:\n QString user;\n MessageView* view;\n};\n\nQMenu* MenuFactory::createUserViewMenu(const QString& user, MessageView* view)\n{\n UserViewMenu* menu = new UserViewMenu(user, view);\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Query\"), menu, SLOT(onQueryTriggered()));\n return menu;\n}\n\nclass TabViewMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n TabViewMenu(MessageView* view, SessionTabWidget* tab) :\n QMenu(tab), view(view), tab(tab)\n {\n }\n\nprivate slots:\n void onEditSession()\n {\n QMetaObject::invokeMethod(tab, \"editSession\", Q_ARG(Session*, view->session()));\n }\n\n void onNamesTriggered()\n {\n IrcCommand* command = IrcCommand::createNames(view->receiver());\n view->session()->sendCommand(command);\n }\n\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(view->receiver());\n view->session()->sendCommand(command);\n }\n\n void onCloseView()\n {\n tab->removeView(view->receiver());\n }\n\nprivate:\n MessageView* view;\n SessionTabWidget* tab;\n};\n\nQMenu* MenuFactory::createTabViewMenu(MessageView* view, SessionTabWidget* tab)\n{\n TabViewMenu* menu = new TabViewMenu(view, tab);\n if (view->viewType() == MessageView::ServerView) {\n if (view->session()->isActive())\n menu->addAction(tr(\"Disconnect\"), view->session(), SLOT(quit()));\n else\n menu->addAction(tr(\"Reconnect\"), view->session(), SLOT(reconnect()));\n menu->addAction(tr(\"Edit\"), menu, SLOT(onEditSession()))->setEnabled(!view->session()->isActive());\n }\n if (view->viewType() == MessageView::ChannelView) {\n menu->addAction(tr(\"Names\"), menu, SLOT(onNamesTriggered()));\n menu->addAction(tr(\"Part\"), menu, SLOT(onCloseView()));\n } else {\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Close\"), menu, SLOT(onCloseView()));\n }\n return menu;\n}\n\nclass UserListMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n UserListMenu(UserListView* listView) : QMenu(listView), listView(listView)\n {\n }\n\nprivate slots:\n void onWhoisTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createWhois(action->data().toString());\n listView->session()->sendCommand(command);\n }\n }\n\n void onQueryTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action)\n QMetaObject::invokeMethod(listView, \"queried\", Q_ARG(QString, action->data().toString()));\n }\n\n void onModeTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n QStringList params = action->data().toStringList();\n IrcCommand* command = IrcCommand::createMode(listView->channel(), params.at(1), params.at(0));\n listView->session()->sendCommand(command);\n }\n }\n\n void onKickTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createKick(listView->channel(), action->data().toString());\n listView->session()->sendCommand(command);\n }\n }\n\n void onBanTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createMode(listView->channel(), \"+b\", action->data().toString() + \"!*@*\");\n listView->session()->sendCommand(command);\n }\n }\n\nprivate:\n UserListView* listView;\n};\n\nQMenu* MenuFactory::createUserListMenu(const QString& user, UserListView* listView)\n{\n UserListMenu* menu = new UserListMenu(listView);\n\n QString mode = listView->session()->userPrefix(user);\n QString name = listView->session()->unprefixedUser(user);\n\n QAction* action = 0;\n action = menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n action->setData(name);\n\n action = menu->addAction(tr(\"Query\"), menu, SLOT(onQueryTriggered()));\n action->setData(name);\n\n menu->addSeparator();\n\n if (mode.contains(\"@\")) {\n action = menu->addAction(tr(\"Deop\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"-o\");\n } else {\n action = menu->addAction(tr(\"Op\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"+o\");\n }\n\n if (mode.contains(\"+\")) {\n action = menu->addAction(tr(\"Devoice\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"-v\");\n } else {\n action = menu->addAction(tr(\"Voice\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"+v\");\n }\n\n menu->addSeparator();\n\n action = menu->addAction(tr(\"Kick\"), menu, SLOT(onKickTriggered()));\n action->setData(name);\n\n action = menu->addAction(tr(\"Ban\"), menu, SLOT(onBanTriggered()));\n action->setData(name);\n\n return menu;\n}\n\nclass SessionTreeMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n SessionTreeMenu(SessionTreeItem* item, SessionTreeWidget* tree) :\n QMenu(tree), item(item), tree(tree)\n {\n }\n\nprivate slots:\n void onEditSession()\n {\n QMetaObject::invokeMethod(tree, \"editSession\", Q_ARG(Session*, item->session()));\n }\n\n void onNamesTriggered()\n {\n IrcCommand* command = IrcCommand::createNames(item->text(0));\n item->session()->sendCommand(command);\n }\n\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(item->text(0));\n item->session()->sendCommand(command);\n }\n\n void onCloseItem()\n {\n QMetaObject::invokeMethod(tree, \"closeItem\", Q_ARG(SessionTreeItem*, item));\n }\n\nprivate:\n SessionTreeItem* item;\n SessionTreeWidget* tree;\n};\n\nQMenu* MenuFactory::createSessionTreeMenu(SessionTreeItem* item, SessionTreeWidget* tree)\n{\n SessionTreeMenu* menu = new SessionTreeMenu(item, tree);\n if (!item->parent()) {\n if (item->session()->isActive())\n menu->addAction(tr(\"Disconnect\"), item->session(), SLOT(quit()));\n else\n menu->addAction(tr(\"Reconnect\"), item->session(), SLOT(reconnect()));\n menu->addAction(tr(\"Edit\"), menu, SLOT(onEditSession()))->setEnabled(!item->session()->isActive());\n }\n if (item->session()->isChannel(item->text(0))) {\n menu->addAction(tr(\"Names\"), menu, SLOT(onNamesTriggered()));\n menu->addAction(tr(\"Part\"), menu, SLOT(onCloseItem()));\n } else {\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Close\"), menu, SLOT(onCloseItem()));\n }\n return menu;\n}\n\n#include \"menufactory.moc\"\ndesktop: fix the \"Part\" item in the session tree menu\/*\n* Copyright (C) 2008-2012 J-P Nurmi \n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"menufactory.h\"\n#include \"messageview.h\"\n#include \"userlistview.h\"\n#include \"sessiontreeitem.h\"\n#include \"sessiontabwidget.h\"\n#include \"sessiontreewidget.h\"\n#include \"session.h\"\n#include \n\nMenuFactory::MenuFactory(QObject* parent) : QObject(parent)\n{\n}\n\nMenuFactory::~MenuFactory()\n{\n}\n\nclass UserViewMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n UserViewMenu(const QString& user, MessageView* view) :\n QMenu(view), user(user), view(view)\n {\n }\n\nprivate slots:\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(user);\n view->session()->sendCommand(command);\n }\n\n void onQueryTriggered()\n {\n QMetaObject::invokeMethod(view, \"queried\", Q_ARG(QString, user));\n }\n\nprivate:\n QString user;\n MessageView* view;\n};\n\nQMenu* MenuFactory::createUserViewMenu(const QString& user, MessageView* view)\n{\n UserViewMenu* menu = new UserViewMenu(user, view);\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Query\"), menu, SLOT(onQueryTriggered()));\n return menu;\n}\n\nclass TabViewMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n TabViewMenu(MessageView* view, SessionTabWidget* tab) :\n QMenu(tab), view(view), tab(tab)\n {\n }\n\nprivate slots:\n void onEditSession()\n {\n QMetaObject::invokeMethod(tab, \"editSession\", Q_ARG(Session*, view->session()));\n }\n\n void onNamesTriggered()\n {\n IrcCommand* command = IrcCommand::createNames(view->receiver());\n view->session()->sendCommand(command);\n }\n\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(view->receiver());\n view->session()->sendCommand(command);\n }\n\n void onCloseView()\n {\n tab->removeView(view->receiver());\n }\n\nprivate:\n MessageView* view;\n SessionTabWidget* tab;\n};\n\nQMenu* MenuFactory::createTabViewMenu(MessageView* view, SessionTabWidget* tab)\n{\n TabViewMenu* menu = new TabViewMenu(view, tab);\n if (view->viewType() == MessageView::ServerView) {\n if (view->session()->isActive())\n menu->addAction(tr(\"Disconnect\"), view->session(), SLOT(quit()));\n else\n menu->addAction(tr(\"Reconnect\"), view->session(), SLOT(reconnect()));\n menu->addAction(tr(\"Edit\"), menu, SLOT(onEditSession()))->setEnabled(!view->session()->isActive());\n }\n if (view->viewType() == MessageView::ChannelView) {\n menu->addAction(tr(\"Names\"), menu, SLOT(onNamesTriggered()));\n menu->addAction(tr(\"Part\"), menu, SLOT(onCloseView()));\n } else {\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Close\"), menu, SLOT(onCloseView()));\n }\n return menu;\n}\n\nclass UserListMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n UserListMenu(UserListView* listView) : QMenu(listView), listView(listView)\n {\n }\n\nprivate slots:\n void onWhoisTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createWhois(action->data().toString());\n listView->session()->sendCommand(command);\n }\n }\n\n void onQueryTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action)\n QMetaObject::invokeMethod(listView, \"queried\", Q_ARG(QString, action->data().toString()));\n }\n\n void onModeTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n QStringList params = action->data().toStringList();\n IrcCommand* command = IrcCommand::createMode(listView->channel(), params.at(1), params.at(0));\n listView->session()->sendCommand(command);\n }\n }\n\n void onKickTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createKick(listView->channel(), action->data().toString());\n listView->session()->sendCommand(command);\n }\n }\n\n void onBanTriggered()\n {\n QAction* action = qobject_cast(sender());\n if (action) {\n IrcCommand* command = IrcCommand::createMode(listView->channel(), \"+b\", action->data().toString() + \"!*@*\");\n listView->session()->sendCommand(command);\n }\n }\n\nprivate:\n UserListView* listView;\n};\n\nQMenu* MenuFactory::createUserListMenu(const QString& user, UserListView* listView)\n{\n UserListMenu* menu = new UserListMenu(listView);\n\n QString mode = listView->session()->userPrefix(user);\n QString name = listView->session()->unprefixedUser(user);\n\n QAction* action = 0;\n action = menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n action->setData(name);\n\n action = menu->addAction(tr(\"Query\"), menu, SLOT(onQueryTriggered()));\n action->setData(name);\n\n menu->addSeparator();\n\n if (mode.contains(\"@\")) {\n action = menu->addAction(tr(\"Deop\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"-o\");\n } else {\n action = menu->addAction(tr(\"Op\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"+o\");\n }\n\n if (mode.contains(\"+\")) {\n action = menu->addAction(tr(\"Devoice\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"-v\");\n } else {\n action = menu->addAction(tr(\"Voice\"), menu, SLOT(onModeTriggered()));\n action->setData(QStringList() << name << \"+v\");\n }\n\n menu->addSeparator();\n\n action = menu->addAction(tr(\"Kick\"), menu, SLOT(onKickTriggered()));\n action->setData(name);\n\n action = menu->addAction(tr(\"Ban\"), menu, SLOT(onBanTriggered()));\n action->setData(name);\n\n return menu;\n}\n\nclass SessionTreeMenu : public QMenu\n{\n Q_OBJECT\n\npublic:\n SessionTreeMenu(SessionTreeItem* item, SessionTreeWidget* tree) :\n QMenu(tree), item(item), tree(tree)\n {\n }\n\nprivate slots:\n void onEditSession()\n {\n QMetaObject::invokeMethod(tree, \"editSession\", Q_ARG(Session*, item->session()));\n }\n\n void onNamesTriggered()\n {\n IrcCommand* command = IrcCommand::createNames(item->text(0));\n item->session()->sendCommand(command);\n }\n\n void onWhoisTriggered()\n {\n IrcCommand* command = IrcCommand::createWhois(item->text(0));\n item->session()->sendCommand(command);\n }\n\n void onPartTriggered()\n {\n IrcCommand* command = IrcCommand::createPart(item->text(0));\n item->session()->sendCommand(command);\n }\n\n void onCloseTriggered()\n {\n QMetaObject::invokeMethod(tree, \"closeItem\", Q_ARG(SessionTreeItem*, item));\n }\n\nprivate:\n SessionTreeItem* item;\n SessionTreeWidget* tree;\n};\n\nQMenu* MenuFactory::createSessionTreeMenu(SessionTreeItem* item, SessionTreeWidget* tree)\n{\n SessionTreeMenu* menu = new SessionTreeMenu(item, tree);\n if (!item->parent()) {\n if (item->session()->isActive())\n menu->addAction(tr(\"Disconnect\"), item->session(), SLOT(quit()));\n else\n menu->addAction(tr(\"Reconnect\"), item->session(), SLOT(reconnect()));\n menu->addAction(tr(\"Edit\"), menu, SLOT(onEditSession()))->setEnabled(!item->session()->isActive());\n }\n if (item->session()->isChannel(item->text(0))) {\n menu->addAction(tr(\"Names\"), menu, SLOT(onNamesTriggered()));\n menu->addAction(tr(\"Part\"), menu, SLOT(onPartTriggered()));\n } else {\n menu->addAction(tr(\"Whois\"), menu, SLOT(onWhoisTriggered()));\n menu->addAction(tr(\"Close\"), menu, SLOT(onCloseTriggered()));\n }\n return menu;\n}\n\n#include \"menufactory.moc\"\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"Neural_Networks.h\"\n\nusing namespace std;\n\nvoid Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {\n\tifstream file(training_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(training_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = 0; h < number_training; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + training_set_labels + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_images, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 4; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char pixel;\n\n\t\t\tfor (int j = 0; j < 28 * 28; j++) {\n\t\t\t\tfile.read((char*)(&pixel), 1);\n\t\t\t\tinput[h][j] = pixel \/ 255.0;\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_images + \" not found\" << endl;\n\t}\n\n\tfile.open(test_set_labels, ifstream::binary);\n\n\tif (file.is_open()) {\n\t\tfor (int h = 0, value; h < 2; h++) {\n\t\t\tfile.read((char*)(&value), sizeof(int));\n\t\t}\n\t\tfor (int h = number_training; h < number_training + number_test; h++) {\n\t\t\tunsigned char label;\n\n\t\t\tfile.read((char*)(&label), 1);\n\n\t\t\tfor (int j = 0; j < 10; j++) {\n\t\t\t\toutput[h][j] = (j == label);\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\t}\n\telse {\n\t\tcerr << \"[Read_MNIST], \" + test_set_labels + \" not found\" << endl;\n\t}\n}\n\nint main() {\n\tint epochs = 20;\n\tint number_training = 60000;\n\tint number_test = 10000;\n\tint number_nodes[] = { 784, 10 };\n\n\tfloat **x_data = new float*[number_training + number_test];\n\tfloat **y_data = new float*[number_training + number_test];\n\tfloat **x_train = x_data;\n\tfloat **y_train = y_data;\n\tfloat **x_test = &x_data[number_training];\n\tfloat **y_test = &y_data[number_training];\n\n\tdouble learning_rate = 0.1;\n\n\tstring path;\n\n\tNeural_Networks NN = Neural_Networks();\n\n\tcout << \"path where MNIST handwritten digits dataset is : \";\n\tgetline(cin, path);\n\n\tfor (int h = 0; h < number_training + number_test; h++) {\n\t\tx_data[h] = new float[number_nodes[0]];\n\t\ty_data[h] = new float[number_nodes[1]];\n\t}\n\tRead_MNIST(path + \"train-images.idx3-ubyte\", path + \"train-labels.idx1-ubyte\", path + \"t10k-images.idx3-ubyte\", path + \"t10k-labels.idx1-ubyte\", number_training, number_test, x_data, y_data);\n\n\tsrand(0);\n\tNN.Add(number_nodes[0]);\n\tNN.Add(number_nodes[1]);\n\tNN.Connect(1, 0, 0.01);\n\tNN.Compile(learning_rate);\n\n\tfor (int e = 0, time = clock(); e < epochs; e++) {\n\t\tint score[2] = { 0, };\n\n\t\tfloat *output = new float[number_nodes[1]];\n\n\t\tdouble loss[2] = { NN.Fit(x_train, y_train, number_training), NN.Evaluate(x_test, y_test, number_test) };\n\n\t\tfor (int i = 0, argmax; i < number_training + number_test; i++) {\n\t\t\tdouble max = 0;\n\n\t\t\tNN.Predict(x_data[i], output);\n\n\t\t\tfor (int j = 0; j < number_nodes[1]; j++) {\n\t\t\t\tif (j == 0 || max < output[j]) {\n\t\t\t\t\tmax = output[argmax = j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tscore[(i < number_training) ? (0) : (1)] += (int)y_data[i][argmax];\n\t\t}\n\t\tprintf(\"loss: %.4f \/ %.4f\taccuracy: %.4f \/ %.4f\tstep %d %.2f sec\\n\", loss[0], loss[1], 1.0 * score[0] \/ number_training, 1.0 * score[1] \/ number_test, e + 1, (double)(clock() - time) \/ CLOCKS_PER_SEC);\n\t\t\n\t\tdelete[] output;\n\t}\n\n\tfor (int i = 0; i < number_training + number_test; i++) {\n\t\tdelete[] x_data[i];\n\t\tdelete[] y_data[i];\n\t}\n\tdelete[] x_data;\n\tdelete[] y_data;\n}Delete main.cpp<|endoftext|>"} {"text":"#include \"bots\/constant\/bot.h\"\n\n#include \n#include \n\n#include \"game\/physics_params.h\"\n#include \"gflags\/gflags.h\"\n\nusing game::Position;\nusing game::CarTracker;\nusing game::Race;\nusing game::Command;\nusing game::Switch;\nusing game::PhysicsParams;\n\nDEFINE_double(constant_throttle, 0.5, \"Throttle to use in constant bot\");\nDECLARE_bool(always_switch);\n\n\nnamespace bots {\nnamespace constant {\n\nBot::Bot() {\n srand(time(0));\n}\n\nBot::~Bot() {\n}\n\ngame::Command Bot::ComputeMove(const Position& position, int game_tick) {\n if (FLAGS_always_switch) {\n int r = rand() % 100;\n if (r == 0) return Command(game::Switch::kSwitchLeft);\n if (r == 1) return Command(game::Switch::kSwitchRight);\n }\n return Command(FLAGS_constant_throttle);\n}\n\ngame::Command Bot::GetMove(\n const std::map& positions, int game_tick) {\n const auto& my_position = positions.find(color_)->second;\n car_tracker_->Record(my_position);\n\n Command command = ComputeMove(my_position, game_tick);\n\n car_tracker_->RecordCommand(command);\n return Command(command);\n}\n\nvoid Bot::GameStarted() {\n car_tracker_->Reset();\n}\n\nvoid Bot::YourCar(const std::string& color) {\n color_ = color;\n}\n\nvoid Bot::NewRace(const Race& race) {\n race_ = race;\n car_tracker_.reset(new CarTracker(&race_, PhysicsParams::Load()));\n}\n\nvoid Bot::CarCrashed(const std::string& color) {\n crash_ = true;\n car_tracker_->RecordCarCrash();\n}\n\nvoid Bot::OnTurbo(const game::Turbo& turbo) {\n turbo_ = true;\n car_tracker_->RecordTurboAvailable(turbo);\n}\n\n} \/\/ namespace bots\n} \/\/ namespace constant\nAdd constant seed to slowbots#include \"bots\/constant\/bot.h\"\n\n#include \n#include \n\n#include \"game\/physics_params.h\"\n#include \"gflags\/gflags.h\"\n\nusing game::Position;\nusing game::CarTracker;\nusing game::Race;\nusing game::Command;\nusing game::Switch;\nusing game::PhysicsParams;\n\nDEFINE_double(constant_throttle, 0.5, \"Throttle to use in constant bot\");\nDECLARE_bool(always_switch);\n\n\nnamespace bots {\nnamespace constant {\n\nBot::Bot() {\n srand(7353521);\n}\n\nBot::~Bot() {\n}\n\ngame::Command Bot::ComputeMove(const Position& position, int game_tick) {\n if (FLAGS_always_switch) {\n int r = rand() % 100;\n if (r == 0) return Command(game::Switch::kSwitchLeft);\n if (r == 1) return Command(game::Switch::kSwitchRight);\n }\n return Command(FLAGS_constant_throttle);\n}\n\ngame::Command Bot::GetMove(\n const std::map& positions, int game_tick) {\n const auto& my_position = positions.find(color_)->second;\n car_tracker_->Record(my_position);\n\n Command command = ComputeMove(my_position, game_tick);\n\n car_tracker_->RecordCommand(command);\n return Command(command);\n}\n\nvoid Bot::GameStarted() {\n car_tracker_->Reset();\n}\n\nvoid Bot::YourCar(const std::string& color) {\n color_ = color;\n}\n\nvoid Bot::NewRace(const Race& race) {\n race_ = race;\n car_tracker_.reset(new CarTracker(&race_, PhysicsParams::Load()));\n}\n\nvoid Bot::CarCrashed(const std::string& color) {\n crash_ = true;\n car_tracker_->RecordCarCrash();\n}\n\nvoid Bot::OnTurbo(const game::Turbo& turbo) {\n turbo_ = true;\n car_tracker_->RecordTurboAvailable(turbo);\n}\n\n} \/\/ namespace bots\n} \/\/ namespace constant\n<|endoftext|>"} {"text":"\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include \n#include \n#include \n#include \n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( xmlnode &node, int level = 0 )\n{\n xmlstring name = node.getName();\n xmlnodetype type = node.getType();\n xmlstring c_data;\n\n for(int i=0;ifirst << \": \" << j->second << endl;\n }\n\n xmlnodelist& nlist = node.getChildren();\n\n xmlnodelist::const_iterator iter, stop;\n iter = nlist.begin();\n stop = nlist.end();\n\n while (iter != stop)\n {\n xmlnodeptr node = *iter;\n\n dump_node ( *node, level+1 );\n\n ++iter;\n }\n};\n\nvoid process_xml( std::string filename )\n{\n cout << \"processing [\" << filename << \"] ...\" << endl;\n\n xmlcontextptr context( new xmlcontext );\n xmldocument node( context );\n ifstream istr( filename.c_str() );\n\n \/\/ Verify that file opened\n if(!istr)\n {\n std::cerr << \"Bad file: \" << filename << std::endl;\n return;\n }\n\n try\n {\n clock_t tstart = ::clock();\n\n node.load( istr, context );\n\n clock_t tstop = ::clock();\n cout << \" needed \" <<\n (tstop-tstart)\/static_cast(CLOCKS_PER_SEC)\n << \" seconds.\" << endl;\n\n dump_node( node );\n\n ofstream ostr( \"parsetest.xml\" );\n node.save( ostr );\n ostr.close();\n\n }\n catch (xmlerror e)\n {\n xmllocation where( context->get_location() );\n xmlstring errmsg;\n e.get_strerror(errmsg);\n\n \/\/ print out where the error occured\n cout << filename << \":\" << where.get_line() << \" \";\n cout << \"at position \" << where.get_pos();\n cout << \": error: \" << errmsg.c_str();\n cout << endl;\n\n \/\/ print out line where the error occured\n ifstream errfile( filename.c_str() );\n if(!errfile)\n {\n std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n }\n\n int linenr = where.get_line();\n char linebuffer[1024];\n for(int i=0; i=80)\n pos %= 80;\n\n std::string err_line( linebuffer + (where.get_pos()-pos) );\n if (err_line.length()>=79)\n err_line.erase(79);\n cout << err_line << std::flush;\n cout << err_line.c_str() << std::endl;\n cout << linebuffer << std::endl;\n for(int j=2;jupdated to recent cppdom API changes\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include \n#include \n#include \n#include \n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( XMLNode &node, int level = 0 )\n{\n XMLString name = node.getName();\n XMLNodeType type = node.getType();\n XMLString c_data;\n\n for(int i=0;ifirst << \": \" << j->second << endl;\n }\n\n XMLNodeList& nlist = node.getChildren();\n\n XMLNodeList::const_iterator iter, stop;\n iter = nlist.begin();\n stop = nlist.end();\n\n while (iter != stop)\n {\n XMLNodePtr node = *iter;\n\n dump_node ( *node, level+1 );\n\n ++iter;\n }\n};\n\nvoid process_xml( std::string filename )\n{\n cout << \"processing [\" << filename << \"] ...\" << endl;\n\n XMLContextPtr context( new XMLContext );\n XMLDocument node( context );\n ifstream istr( filename.c_str() );\n\n \/\/ Verify that file opened\n if(!istr)\n {\n std::cerr << \"Bad file: \" << filename << std::endl;\n return;\n }\n\n try\n {\n clock_t tstart = ::clock();\n\n node.load( istr, context );\n\n clock_t tstop = ::clock();\n cout << \" needed \" <<\n (tstop-tstart)\/static_cast(CLOCKS_PER_SEC)\n << \" seconds.\" << endl;\n\n dump_node( node );\n\n ofstream ostr( \"parsetest.xml\" );\n node.save( ostr );\n ostr.close();\n\n }\n catch (xmlerror e)\n {\n XMLLocation where( context->get_location() );\n XMLString errmsg;\n e.getStrError(errmsg);\n\n \/\/ print out where the error occured\n cout << filename << \":\" << where.getLine() << \" \";\n cout << \"at position \" << where.getPos();\n cout << \": error: \" << errmsg.c_str();\n cout << endl;\n\n \/\/ print out line where the error occured\n ifstream errfile( filename.c_str() );\n if(!errfile)\n {\n std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n }\n\n int linenr = where.get_line();\n char linebuffer[1024];\n for(int i=0; i=80)\n pos %= 80;\n\n std::string err_line( linebuffer + (where.get_pos()-pos) );\n if (err_line.length()>=79)\n err_line.erase(79);\n cout << err_line << std::flush;\n cout << err_line.c_str() << std::endl;\n cout << linebuffer << std::endl;\n for(int j=2;j"} {"text":"#include \"ImageImporter2D.hpp\"\n#include \n#include \"DataTypes.hpp\"\n#include \"DeviceManager.hpp\"\n#include \"Exception.hpp\"\nusing namespace fast;\n\nvoid ImageImporter2D::execute() {\n \/\/ TODO check that all parameters needed are present\n\n \/\/ Load image from disk using Qt\n QImage image;\n std::cout << \"Trying to load image...\" << std::endl;\n if(!image.load(mFilename.c_str())) {\n throw FileNotFoundException(mFilename);\n }\n std::cout << \"Loaded image with size \" << image.width() << \" \" << image.height() << std::endl;\n\n \/\/ Convert image to make sure color tables are not used\n QImage convertedImage = image.convertToFormat(QImage::Format_RGB32);\n\n \/\/ Get pixel data\n const unsigned char * pixelData = convertedImage.constBits();\n \/\/ The pixel data array should contain one uchar value for the\n \/\/ R, G, B, A components for each pixel\n\n \/\/ TODO: do some conversion to requested output format, also color vs. no color\n float * convertedPixelData = new float[image.width()*image.height()];\n for(int i = 0; i < image.width()*image.height(); i++) {\n \/\/ Converted to grayscale\n convertedPixelData[i] = (1.0f\/255.0f)*(float)(pixelData[i*4]+pixelData[i*4+1]+pixelData[i*4+2])\/3.0f;\n }\n\n \/\/ Transfer to texture(if OpenCL) or copy raw pixel data (if host)\n if(mDevice->isHost()) {\n mOutput2.lock()->createImage(image.width(), image.height(), convertedPixelData);\n } else {\n OpenCLDevice::pointer device = boost::static_pointer_cast(mDevice);\n cl::Image2D* clImage = new cl::Image2D(\n device->getContext(),\n CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n cl::ImageFormat(CL_R, CL_FLOAT),\n image.width(), image.height(),\n 0,\n convertedPixelData\n );\n delete[] convertedPixelData;\n mOutput2.lock()->createImage(clImage, device);\n }\n}\n\nImageImporter2D::ImageImporter2D() {\n mOutput = Image2D::New();\n mOutput2 = mOutput;\n mDevice = DeviceManager::getInstance().getDefaultComputationDevice();\n}\n\nImage2D::pointer ImageImporter2D::getOutput() {\n if(mOutput.isValid()) {\n mOutput->addParent(mPtr.lock());\n\n Image2D::pointer newSmartPtr;\n newSmartPtr.swap(mOutput);\n\n return newSmartPtr;\n } else {\n return mOutput2.lock();\n }\n}\n\nvoid ImageImporter2D::setFilename(std::string filename) {\n mFilename = filename;\n mIsModified = true;\n}\n\nvoid ImageImporter2D::setDevice(ExecutionDevice::pointer device) {\n mDevice = device;\n mIsModified = true;\n}\nAdded a filename check to the ImageImporter2D#include \"ImageImporter2D.hpp\"\n#include \n#include \"DataTypes.hpp\"\n#include \"DeviceManager.hpp\"\n#include \"Exception.hpp\"\nusing namespace fast;\n\nvoid ImageImporter2D::execute() {\n if(mFilename == \"\")\n throw Exception(\"No filename was supplied to the ImageImporter2D\");\n\n \/\/ Load image from disk using Qt\n QImage image;\n std::cout << \"Trying to load image...\" << std::endl;\n if(!image.load(mFilename.c_str())) {\n throw FileNotFoundException(mFilename);\n }\n std::cout << \"Loaded image with size \" << image.width() << \" \" << image.height() << std::endl;\n\n \/\/ Convert image to make sure color tables are not used\n QImage convertedImage = image.convertToFormat(QImage::Format_RGB32);\n\n \/\/ Get pixel data\n const unsigned char * pixelData = convertedImage.constBits();\n \/\/ The pixel data array should contain one uchar value for the\n \/\/ R, G, B, A components for each pixel\n\n \/\/ TODO: do some conversion to requested output format, also color vs. no color\n float * convertedPixelData = new float[image.width()*image.height()];\n for(int i = 0; i < image.width()*image.height(); i++) {\n \/\/ Converted to grayscale\n convertedPixelData[i] = (1.0f\/255.0f)*(float)(pixelData[i*4]+pixelData[i*4+1]+pixelData[i*4+2])\/3.0f;\n }\n\n \/\/ Transfer to texture(if OpenCL) or copy raw pixel data (if host)\n if(mDevice->isHost()) {\n mOutput2.lock()->createImage(image.width(), image.height(), convertedPixelData);\n } else {\n OpenCLDevice::pointer device = boost::static_pointer_cast(mDevice);\n cl::Image2D* clImage = new cl::Image2D(\n device->getContext(),\n CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,\n cl::ImageFormat(CL_R, CL_FLOAT),\n image.width(), image.height(),\n 0,\n convertedPixelData\n );\n delete[] convertedPixelData;\n mOutput2.lock()->createImage(clImage, device);\n }\n}\n\nImageImporter2D::ImageImporter2D() {\n mOutput = Image2D::New();\n mOutput2 = mOutput;\n mDevice = DeviceManager::getInstance().getDefaultComputationDevice();\n}\n\nImage2D::pointer ImageImporter2D::getOutput() {\n if(mOutput.isValid()) {\n mOutput->addParent(mPtr.lock());\n\n Image2D::pointer newSmartPtr;\n newSmartPtr.swap(mOutput);\n\n return newSmartPtr;\n } else {\n return mOutput2.lock();\n }\n}\n\nvoid ImageImporter2D::setFilename(std::string filename) {\n mFilename = filename;\n mIsModified = true;\n}\n\nvoid ImageImporter2D::setDevice(ExecutionDevice::pointer device) {\n mDevice = device;\n mIsModified = true;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2014, J.D. Koftinoff Software, Ltd.\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n#pragma once\n\n#include \"JDKSAvdeccWorld.hpp\"\n#include \"JDKSAvdeccNetIO.hpp\"\n#include \"JDKSAvdeccFrame.hpp\"\n#include \"JDKSAvdeccHandler.hpp\"\n#include \"JDKSAvdeccControlValueHolder.hpp\"\n#include \"JDKSAvdeccHelpers.hpp\"\n\nnamespace JDKSAvdecc {\n\ntemplate \nclass ControlReceiver : public Handler {\npublic:\n \/\/\/ Construct the ControlReceiver object\n ControlReceiver(NetIO &net,\n jdksavdecc_eui64 const &entity_id,\n uint16_t descriptor_index_offset=0 )\n : m_net( net )\n , m_entity_id( entity_id )\n , m_descriptor_index_offset( descriptor_index_offset )\n , m_num_descriptors(0)\n , m_last_sequence_id(0xffff) {}\n\n \/\/\/ Register the ControlValueHolder to relate to the next descriptor_index in line\n void AddDescriptor(ControlValueHolder *v ) {\n m_values[ m_num_descriptors++ ] = v;\n }\n\n virtual bool ReceivedGetControlCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n \/\/ yes, get the descriptor index\n uint16_t descriptor_index = jdksavdecc_aem_command_set_control_get_descriptor_index(pdu.GetBuf(),pdu.GetPos());\n \/\/ is it a descriptor index that we care about?\n if( (descriptor_index>=m_descriptor_index_offset)\n && (descriptor_index < (m_descriptor_index_offset+m_num_descriptors)) ) {\n \/\/ yes, it is in range, extract the data value\n\n \/\/ TODO Add GetValue method in ControlValueHolder.\n\/\/ m_values[descriptor_index-m_descriptor_index_offset]->SetValue(\n\/\/ &buf[pos+JDKSAVDECC_AEM_COMMAND_SET_CONTROL_COMMAND_OFFSET_VALUES] );\n \/\/ TODO: Set control_data_length appropriately.\n\n r=true;\n }\n return r;\n }\n\n virtual bool ReceivedSetControlCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n \/\/ yes, get the descriptor index\n uint16_t descriptor_index = jdksavdecc_aem_command_set_control_get_descriptor_index(pdu.GetBuf(),pdu.GetPos());\n \/\/ is it a descriptor index that we care about?\n if( (descriptor_index>=m_descriptor_index_offset)\n && (descriptor_index < (m_descriptor_index_offset+m_num_descriptors)) ) {\n \/\/ yes, it is in range, extract the data value\n\n m_values[descriptor_index-m_descriptor_index_offset]->SetValue(\n pdu.GetBuf() + pdu.GetPos() +JDKSAVDECC_AEM_COMMAND_SET_CONTROL_COMMAND_OFFSET_VALUES\n );\n\n r=true;\n }\n return r;\n }\n\n virtual bool ReceivedReadDescriptorCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n return r;\n\n }\n\n \/\/\/ Handle incoming PDU\n virtual bool ReceivedPDU( jdksavdecc_timestamp_in_milliseconds time_in_millis, uint8_t *buf, uint16_t len ) {\n bool r=false;\n \/\/ we already know the message is AVTP ethertype and is either directly\n \/\/ targetting my MAC address or is a multicast message\n\n FrameBase pdu(time_in_millis,buf,len);\n\n \/\/ Try see if it is an AEM message\n jdksavdecc_aecpdu_aem aem;\n if( ParseAEM(&aem,pdu)) {\n \/\/ Yes, Is it a command for me?\n if( IsAEMForTarget(aem,m_entity_id)) {\n \/\/ Yes. Is the sequence_id ok?\n if( aem.aecpdu_header.sequence_id != m_last_sequence_id )\n {\n \/\/ Yes, it is different.\n m_last_sequence_id = aem.aecpdu_header.sequence_id;\n if( aem.command_type == JDKSAVDECC_AEM_COMMAND_GET_CONTROL ) {\n \/\/ Handle GET_CONTROL commands\n r=ReceivedGetControlCommand( aem, pdu );\n } else if( aem.command_type == JDKSAVDECC_AEM_COMMAND_SET_CONTROL ) {\n \/\/ Handle SET_CONTROL commands\n r=ReceivedSetControlCommand( aem, pdu );\n } else if( aem.command_type == JDKSAVDECC_AEM_COMMAND_READ_DESCRIPTOR ) {\n \/\/ Handle READ_DESCRIPTOR commands\n r=ReceivedReadDescriptorCommand( aem, pdu );\n }\n }\n }\n }\n if( r ) {\n \/\/ TODO: change message type to AEM_RESPONSE and send it back to sender\n }\n return r;\n }\n\n \/\/\/ Get the enitity ID that we are handling\n jdksavdecc_eui64 const &GetEntityID() const { return m_entity_id; }\n\nprotected:\n NetIO &m_net;\n jdksavdecc_eui64 const &m_entity_id;\n uint16_t m_descriptor_index_offset;\n uint16_t m_num_descriptors;\n ControlValueHolder *m_values[MaxDescriptors];\n uint16_t m_last_sequence_id;\n};\n\n}\nClean up warnings\/*\n Copyright (c) 2014, J.D. Koftinoff Software, Ltd.\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n 3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n#pragma once\n\n#include \"JDKSAvdeccWorld.hpp\"\n#include \"JDKSAvdeccNetIO.hpp\"\n#include \"JDKSAvdeccFrame.hpp\"\n#include \"JDKSAvdeccHandler.hpp\"\n#include \"JDKSAvdeccControlValueHolder.hpp\"\n#include \"JDKSAvdeccHelpers.hpp\"\n\nnamespace JDKSAvdecc {\n\ntemplate \nclass ControlReceiver : public Handler {\npublic:\n \/\/\/ Construct the ControlReceiver object\n ControlReceiver(NetIO &net,\n jdksavdecc_eui64 const &entity_id,\n uint16_t descriptor_index_offset=0 )\n : m_net( net )\n , m_entity_id( entity_id )\n , m_descriptor_index_offset( descriptor_index_offset )\n , m_num_descriptors(0)\n , m_last_sequence_id(0xffff) {}\n\n \/\/\/ Register the ControlValueHolder to relate to the next descriptor_index in line\n void AddDescriptor(ControlValueHolder *v ) {\n m_values[ m_num_descriptors++ ] = v;\n }\n\n virtual bool ReceivedGetControlCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n \/\/ yes, get the descriptor index\n uint16_t descriptor_index = jdksavdecc_aem_command_set_control_get_descriptor_index(pdu.GetBuf(),pdu.GetPos());\n (void)aem;\n \/\/ is it a descriptor index that we care about?\n if( (descriptor_index>=m_descriptor_index_offset)\n && (descriptor_index < (m_descriptor_index_offset+m_num_descriptors)) ) {\n \/\/ yes, it is in range, extract the data value\n\n \/\/ TODO Add GetValue method in ControlValueHolder.\n\/\/ m_values[descriptor_index-m_descriptor_index_offset]->SetValue(\n\/\/ &buf[pos+JDKSAVDECC_AEM_COMMAND_SET_CONTROL_COMMAND_OFFSET_VALUES] );\n \/\/ TODO: Set control_data_length appropriately.\n\n r=true;\n }\n return r;\n }\n\n virtual bool ReceivedSetControlCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n \/\/ yes, get the descriptor index\n uint16_t descriptor_index = jdksavdecc_aem_command_set_control_get_descriptor_index(pdu.GetBuf(),pdu.GetPos());\n (void)aem;\n \/\/ is it a descriptor index that we care about?\n if( (descriptor_index>=m_descriptor_index_offset)\n && (descriptor_index < (m_descriptor_index_offset+m_num_descriptors)) ) {\n \/\/ yes, it is in range, extract the data value\n\n m_values[descriptor_index-m_descriptor_index_offset]->SetValue(\n pdu.GetBuf() + pdu.GetPos() +JDKSAVDECC_AEM_COMMAND_SET_CONTROL_COMMAND_OFFSET_VALUES\n );\n\n r=true;\n }\n return r;\n }\n\n virtual bool ReceivedReadDescriptorCommand(\n jdksavdecc_aecpdu_aem const &aem,\n FrameBase &pdu ) {\n bool r=false;\n (void)aem;\n (void)pdu;\n return r;\n }\n\n \/\/\/ Handle incoming PDU\n virtual bool ReceivedPDU( jdksavdecc_timestamp_in_milliseconds time_in_millis, uint8_t *buf, uint16_t len ) {\n bool r=false;\n \/\/ we already know the message is AVTP ethertype and is either directly\n \/\/ targetting my MAC address or is a multicast message\n\n FrameBase pdu(time_in_millis,buf,len);\n\n \/\/ Try see if it is an AEM message\n jdksavdecc_aecpdu_aem aem;\n if( ParseAEM(&aem,pdu)) {\n \/\/ Yes, Is it a command for me?\n if( IsAEMForTarget(aem,m_entity_id)) {\n \/\/ Yes. Is the sequence_id ok?\n if( aem.aecpdu_header.sequence_id != m_last_sequence_id )\n {\n \/\/ Yes, it is different.\n m_last_sequence_id = aem.aecpdu_header.sequence_id;\n if( aem.command_type == JDKSAVDECC_AEM_COMMAND_GET_CONTROL ) {\n \/\/ Handle GET_CONTROL commands\n r=ReceivedGetControlCommand( aem, pdu );\n } else if( aem.command_type == JDKSAVDECC_AEM_COMMAND_SET_CONTROL ) {\n \/\/ Handle SET_CONTROL commands\n r=ReceivedSetControlCommand( aem, pdu );\n } else if( aem.command_type == JDKSAVDECC_AEM_COMMAND_READ_DESCRIPTOR ) {\n \/\/ Handle READ_DESCRIPTOR commands\n r=ReceivedReadDescriptorCommand( aem, pdu );\n }\n }\n }\n }\n if( r ) {\n \/\/ TODO: change message type to AEM_RESPONSE and send it back to sender\n }\n return r;\n }\n\n \/\/\/ Get the enitity ID that we are handling\n jdksavdecc_eui64 const &GetEntityID() const { return m_entity_id; }\n\nprotected:\n NetIO &m_net;\n jdksavdecc_eui64 const &m_entity_id;\n uint16_t m_descriptor_index_offset;\n uint16_t m_num_descriptors;\n ControlValueHolder *m_values[MaxDescriptors];\n uint16_t m_last_sequence_id;\n};\n\n}\n<|endoftext|>"} {"text":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetTaskIOTest\n#include \n#include \"..\/JPetCmdParser\/JPetCmdParser.h\"\n#include \"..\/JPetTaskIO\/JPetTaskIO.h\"\n\n\/\/#include \"TaskA.h\"\n\/\/#include \"TaskB.h\"\n\/\/#include \"TaskC1.h\"\n\/\/#include \"TaskC2.h\"\n\/\/#include \"TaskC3.h\"\n\/\/#include \"TaskD.h\"\n\/\/#include \"TaskE.h\"\n\n\/\/ methods\n\/\/virtual void init(const JPetTaskInterface::Options& opts);\n\/\/virtual void exec();\n\/\/virtual void terminate();\n\/\/virtual ~JPetTaskIO();\n\/\/virtual void addSubTask(JPetTaskInterface* subtask);\n\/\/void manageProgressBar(long long done, long long end);\n\/\/float setProgressBar(int currentEventNumber, int numberOfEvents);\n\n\/\/\/protected:\n\/\/virtual void createInputObjects(const char* inputFilename);\n\/\/virtual void createOutputObjects(const char* outputFilename);\n\/\/void setUserLimits(const JPetOptions& opts, long long& firstEvent, long long& lastEvent) const;\n\n\n\n\/\/using Options = std::map;\n\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\nchar* convertStringToCharP(const std::string& s)\n{\n char* pc = new char[s.size() + 1];\n std::strcpy(pc, s.c_str());\n return pc;\n}\n\nstd::vector createArgs(const std::string& commandLine) \n{\n std::istringstream iss(commandLine);\n std::vector args {std::istream_iterator{iss},\n std::istream_iterator{}\n };\n std::vector args_char;\n std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);\n return args_char;\n}\n\n\n\nBOOST_AUTO_TEST_CASE(progressBarTest)\n{\n JPetTaskIO taskIO;\n BOOST_REQUIRE_EQUAL(taskIO.setProgressBar(5, 100), 5);\n taskIO.manageProgressBar(5, 100);\n}\n\/\/ToDo: remake this tests without calling private methods\n\/*\nBOOST_AUTO_TEST_CASE( setUserLimits)\n{\n auto commandLine = \".\/main.x -t root -f unitTestData\/JPetTaskIOTest\/cosm_barrel.hld.root -i 26 -r 1000 1001\";\n auto args_char = createArgs(commandLine);\n auto argc = args_char.size();\n auto argv = args_char.data();\n\n JPetCmdParser parser;\n auto options = parser.parseAndGenerateOptions(argc, const_cast(argv));\n auto first = 0ll;\n auto last = 0ll;\n auto opt = options.front().getOptions();\n JPetOptions optObject(opt);\n JPetTaskIO task;\n task.setUserLimits(optObject,10000, first,last); \n BOOST_REQUIRE_EQUAL(first, 1000);\n BOOST_REQUIRE_EQUAL(last, 1001);\n}\n\nBOOST_AUTO_TEST_CASE( setUserLimits2 )\n{\n auto commandLine = \".\/main.x -t root -f unitTestData\/JPetTaskIOTest\/cosm_barrel.hld.root -i 26 -r 1000 1001\";\n auto args_char = createArgs(commandLine);\n auto argc = args_char.size();\n auto argv = args_char.data();\n\n JPetCmdParser parser;\n auto options = parser.parseAndGenerateOptions(argc, const_cast(argv));\n auto first = 0ll;\n auto last = 0ll;\n auto opt = options.front().getOptions();\n JPetOptions optObject(opt);\n JPetTaskIO task;\n task.setUserLimits(optObject,1, first,last); \n BOOST_REQUIRE_EQUAL(first, 0);\n BOOST_REQUIRE_EQUAL(last, 0);\n}\n\nBOOST_AUTO_TEST_CASE( my_testA )\n{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.hld.root\"},\n \/\/{\"inputFileType\", \"hld\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.tslot.raw.out.root\"},\n \/\/{\"outputFileType\", \"tslot.raw\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/\/\/JPetParamManager myParamManager;\n \/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskA();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testB )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.tslot.raw.root\"},\n \/\/{\"inputFileType\", \"tslot.raw\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.tslot.cal.out.root\"},\n \/\/{\"outputFileType\", \"tslot.cal\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskB();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC1 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.tslot.cal.root\"},\n \/\/{\"inputFileType\", \"tslot.cal\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.raw.sig.out.root\"},\n \/\/{\"outputFileType\", \"raw.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskC1();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC2 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.raw.sig.root\"},\n \/\/{\"inputFileType\", \"raw.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.reco.sig.out.root\"},\n \/\/{\"outputFileType\", \"reco.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskC2();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC3 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.reco.sig.root\"},\n \/\/{\"inputFileType\", \"reco.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.sig.out.root\"},\n \/\/{\"outputFileType\", \"phys.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskC3();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_test1 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.phys.sig.root\"},\n \/\/{\"inputFileType\", \"phys.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.hit.out.root\"},\n \/\/{\"outputFileType\", \"phys.hit\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskD();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\/\/BOOST_AUTO_TEST_CASE( my_test2 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.phys.hit.root\"},\n \/\/{\"inputFileType\", \"phys.hit\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.eve.out.root\"},\n \/\/{\"outputFileType\", \"phys.eve\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetParamManager myParamManager;\n \/\/auto myTask = new TaskE();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n}\n*\/\nBOOST_AUTO_TEST_SUITE_END()\nJPetTaskIO\/JPetTaskIOTest.cpp unnecessary comments removed#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetTaskIOTest\n#include \n#include \"..\/JPetCmdParser\/JPetCmdParser.h\"\n#include \"..\/JPetTaskIO\/JPetTaskIO.h\"\n\nBOOST_AUTO_TEST_SUITE(FirstSuite)\n\n\nchar* convertStringToCharP(const std::string& s)\n{\n char* pc = new char[s.size() + 1];\n std::strcpy(pc, s.c_str());\n return pc;\n}\n\nstd::vector createArgs(const std::string& commandLine) \n{\n std::istringstream iss(commandLine);\n std::vector args {std::istream_iterator{iss},\n std::istream_iterator{}\n };\n std::vector args_char;\n std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);\n return args_char;\n}\n\n\n\nBOOST_AUTO_TEST_CASE(progressBarTest)\n{\n JPetTaskIO taskIO;\n BOOST_REQUIRE_EQUAL(taskIO.setProgressBar(5, 100), 5);\n taskIO.manageProgressBar(5, 100);\n}\n\/\/ToDo: remake this tests without calling private methods\n\/*\nBOOST_AUTO_TEST_CASE( setUserLimits)\n{\n auto commandLine = \".\/main.x -t root -f unitTestData\/JPetTaskIOTest\/cosm_barrel.hld.root -i 26 -r 1000 1001\";\n auto args_char = createArgs(commandLine);\n auto argc = args_char.size();\n auto argv = args_char.data();\n\n JPetCmdParser parser;\n auto options = parser.parseAndGenerateOptions(argc, const_cast(argv));\n auto first = 0ll;\n auto last = 0ll;\n auto opt = options.front().getOptions();\n JPetOptions optObject(opt);\n JPetTaskIO task;\n task.setUserLimits(optObject,10000, first,last); \n BOOST_REQUIRE_EQUAL(first, 1000);\n BOOST_REQUIRE_EQUAL(last, 1001);\n}\n\nBOOST_AUTO_TEST_CASE( setUserLimits2 )\n{\n auto commandLine = \".\/main.x -t root -f unitTestData\/JPetTaskIOTest\/cosm_barrel.hld.root -i 26 -r 1000 1001\";\n auto args_char = createArgs(commandLine);\n auto argc = args_char.size();\n auto argv = args_char.data();\n\n JPetCmdParser parser;\n auto options = parser.parseAndGenerateOptions(argc, const_cast(argv));\n auto first = 0ll;\n auto last = 0ll;\n auto opt = options.front().getOptions();\n JPetOptions optObject(opt);\n JPetTaskIO task;\n task.setUserLimits(optObject,1, first,last); \n BOOST_REQUIRE_EQUAL(first, 0);\n BOOST_REQUIRE_EQUAL(last, 0);\n}\n\nBOOST_AUTO_TEST_CASE( my_testA )\n{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.hld.root\"},\n \/\/{\"inputFileType\", \"hld\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.tslot.raw.out.root\"},\n \/\/{\"outputFileType\", \"tslot.raw\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/\/\/JPetParamManager myParamManager;\n \/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskA();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testB )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.tslot.raw.root\"},\n \/\/{\"inputFileType\", \"tslot.raw\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.tslot.cal.out.root\"},\n \/\/{\"outputFileType\", \"tslot.cal\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskB();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC1 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.tslot.cal.root\"},\n \/\/{\"inputFileType\", \"tslot.cal\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.raw.sig.out.root\"},\n \/\/{\"outputFileType\", \"raw.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetTaskIO task;\n \/\/task.setParamManager(&myParamManager);\n \/\/auto myTask = new TaskC1();\n \/\/myTask->setParamManager(&myParamManager);\n \/\/task.addSubTask(myTask); \n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC2 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.raw.sig.root\"},\n \/\/{\"inputFileType\", \"raw.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.reco.sig.out.root\"},\n \/\/{\"outputFileType\", \"reco.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskC2();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_testC3 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.reco.sig.root\"},\n \/\/{\"inputFileType\", \"reco.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.sig.out.root\"},\n \/\/{\"outputFileType\", \"phys.sig\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskC3();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\n\/\/BOOST_AUTO_TEST_CASE( my_test1 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.phys.sig.root\"},\n \/\/{\"inputFileType\", \"phys.sig\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.hit.out.root\"},\n \/\/{\"outputFileType\", \"phys.hit\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/JPetParamManager myParamManager;\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/auto myTask = new TaskD();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n\/\/}\n\/\/BOOST_AUTO_TEST_CASE( my_test2 )\n\/\/{\n \/\/Options options = {\n \/\/{\"inputFile\", \"data_files\/cosm_barrel.phys.hit.root\"},\n \/\/{\"inputFileType\", \"phys.hit\"},\n \/\/{\"outputFile\", \"data_files\/cosm_barrel.phys.eve.out.root\"},\n \/\/{\"outputFileType\", \"phys.eve\"},\n \/\/{\"firstEvent\", \"1\"},\n \/\/{\"lastEvent\", \"10\"},\n \/\/{\"progressBar\", \"false\"}\n \/\/};\n \/\/\/\/JPetParamManager myParamManager(\"..\/DBConfig\/configDB.cfg.koza\");\n \/\/\/\/myParamManager.getParametersFromDatabase(26);\n \/\/JPetParamManager myParamManager;\n \/\/auto myTask = new TaskE();\n \/\/JPetTaskIO task;\n \/\/task.addSubTask(myTask); \n \/\/task.setParamManager(&myParamManager);\n \/\/task.init(options);\n \/\/task.exec();\n \/\/task.terminate();\n\n \/\/BOOST_REQUIRE(1 == 0);\n}\n*\/\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \"..\/test_math.hpp\"\n#include \"nnlib\/math\/math.hpp\"\n#include \"nnlib\/math\/random.hpp\"\nusing namespace nnlib;\nusing namespace nnlib::math;\nusing T = NN_REAL_T;\n\nNNTestClassImpl(Math)\n{\n NNTestMethod(min)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(min(x), -6, 1e-12);\n }\n }\n\n NNTestMethod(max)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(max(x), 9, 1e-12);\n }\n }\n\n NNTestMethod(sum)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(sum(x), 29.14159, 1e-12);\n }\n }\n\n NNTestMethod(mean)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(mean(x), 3.64269875, 1e-12);\n }\n }\n\n NNTestMethod(variance)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(variance(x), 20.964444282761, 1e-12);\n }\n\n NNTestParams(const Tensor &, bool)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(variance(x, true), 23.959364894584, 1e-12);\n }\n }\n\n NNTestMethod(normalize)\n {\n NNTestParams(Tensor &, T, T)\n {\n Tensor x({ -2, 0, 8, 3 });\n normalize(x, -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 1.5, 1e-12);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n Tensor x = normalize(Tensor({ -2, 0, 8, 3 }), -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 1.5, 1e-12);\n }\n }\n\n NNTestMethod(clip)\n {\n NNTestParams(Tensor &, T, T)\n {\n Tensor x({ -2, 0, 8, 3 });\n clip(x, -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 3, 1e-12);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n Tensor x = clip(Tensor({ -2, 0, 8, 3 }), -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 3, 1e-12);\n }\n }\n\n NNTestMethod(square)\n {\n NNTestParams(Tensor &)\n {\n Tensor x({ -2, 0, 1, 6 });\n square(x);\n NNTestAlmostEquals(x(0), 4, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 1, 1e-12);\n NNTestAlmostEquals(x(3), 36, 1e-12);\n }\n\n NNTestParams(Tensor &&)\n {\n Tensor x = square(Tensor({ -2, 0, 1, 6 }));\n NNTestAlmostEquals(x(0), 4, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 1, 1e-12);\n NNTestAlmostEquals(x(3), 36, 1e-12);\n }\n }\n\n NNTestMethod(rand)\n {\n NNTestParams(Tensor &, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n rand(x, -1, 1);\n NNTestAlmostEquals(mean(x), 0, 0.5);\n NNTestAlmostEquals(variance(x), 0.3333, 0.5);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = rand(Tensor(1000), -1, 1);\n NNTestAlmostEquals(mean(x), 0, 0.5);\n NNTestAlmostEquals(variance(x), 0.3333, 0.5);\n }\n }\n\n NNTestMethod(randn)\n {\n NNTestParams(Tensor &, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n randn(x, -1, 3.14);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestAlmostEquals(variance(x), 9.8596, 0.5);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = randn(Tensor(1000), -1, 3.14);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestAlmostEquals(variance(x), 9.8596, 0.5);\n }\n\n NNTestParams(Tensor &, T, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n randn(x, -1, 3.14, 3);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestGreaterThanOrEquals(min(x), -4);\n NNTestLessThanOrEquals(max(x), 2);\n }\n\n NNTestParams(Tensor &&, T, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = randn(Tensor(1000), -1, 3.14, 3);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestGreaterThanOrEquals(min(x), -4);\n NNTestLessThanOrEquals(max(x), 2);\n }\n }\n\n NNTestMethod(bernoulli)\n {\n NNTestParams(Tensor &, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n bernoulli(x, 0.25);\n size_t n = 0;\n forEach([&](T x)\n {\n if(x > 0.5)\n ++n;\n }, x);\n NNTestAlmostEquals(n, 0.25 * x.size(), 50);\n }\n\n NNTestParams(Tensor &&, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = bernoulli(Tensor(1000), 0.25);\n size_t n = 0;\n forEach([&](T x)\n {\n if(x > 0.5)\n ++n;\n }, x);\n NNTestAlmostEquals(n, 0.25 * x.size(), 50);\n }\n }\n\n NNTestMethod(sum)\n {\n NNTestParams(const Tensor &, Tensor &, size_t)\n {\n Tensor x = Tensor({ 1, 2, 3, 4, 5, 6 }).resize(2, 3);\n Tensor y = Tensor({ 5, 7, 9 });\n Tensor z(3);\n sum(x, z, 0);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n y = Tensor({ 6, 15 });\n z.resize(2);\n sum(x, z, 1);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n }\n\n NNTestParams(const Tensor &, Tensor &&, size_t)\n {\n Tensor x = Tensor({ 1, 2, 3, 4, 5, 6 }).resize(2, 3);\n Tensor y = Tensor({ 5, 7, 9 });\n Tensor z = sum(x, Tensor(3), 0);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n }\n }\n\n NNTestMethod(pointwiseProduct)\n {\n NNTestParams(const Tensor &, const Tensor &, Tensor &)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = Tensor({ 4, 5, 6 });\n Tensor z(3);\n pointwiseProduct(x, y, z);\n NNTestAlmostEquals(z(0), 4, 1e-12);\n NNTestAlmostEquals(z(1), 10, 1e-12);\n NNTestAlmostEquals(z(2), 18, 1e-12);\n }\n\n NNTestParams(const Tensor &, const Tensor &, Tensor &&)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = Tensor({ 4, 5, 6 });\n Tensor z = pointwiseProduct(x, y, Tensor(3));\n NNTestAlmostEquals(z(0), 4, 1e-12);\n NNTestAlmostEquals(z(1), 10, 1e-12);\n NNTestAlmostEquals(z(2), 18, 1e-12);\n }\n }\n}\nAdded missing math unit test.#include \"..\/test_math.hpp\"\n#include \"nnlib\/math\/math.hpp\"\n#include \"nnlib\/math\/random.hpp\"\nusing namespace nnlib;\nusing namespace nnlib::math;\nusing T = NN_REAL_T;\n\nNNTestClassImpl(Math)\n{\n NNTestMethod(min)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(min(x), -6, 1e-12);\n }\n }\n\n NNTestMethod(max)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(max(x), 9, 1e-12);\n }\n }\n\n NNTestMethod(sum)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(sum(x), 29.14159, 1e-12);\n }\n }\n\n NNTestMethod(mean)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(mean(x), 3.64269875, 1e-12);\n }\n }\n\n NNTestMethod(variance)\n {\n NNTestParams(const Tensor &)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(variance(x), 20.964444282761, 1e-12);\n }\n\n NNTestParams(const Tensor &, bool)\n {\n Tensor x({ 8, -6, 7, 5, 3, 0, 9, 3.14159 });\n NNTestAlmostEquals(variance(x, true), 23.959364894584, 1e-12);\n }\n }\n\n NNTestMethod(normalize)\n {\n NNTestParams(Tensor &, T, T)\n {\n Tensor x({ -2, 0, 8, 3 });\n normalize(x, -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 1.5, 1e-12);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n Tensor x = normalize(Tensor({ -2, 0, 8, 3 }), -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 1.5, 1e-12);\n }\n }\n\n NNTestMethod(clip)\n {\n NNTestParams(Tensor &, T, T)\n {\n Tensor x({ -2, 0, 8, 3 });\n clip(x, -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 3, 1e-12);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n Tensor x = clip(Tensor({ -2, 0, 8, 3 }), -1, 4);\n NNTestAlmostEquals(x(0), -1, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 4, 1e-12);\n NNTestAlmostEquals(x(3), 3, 1e-12);\n }\n }\n\n NNTestMethod(square)\n {\n NNTestParams(Tensor &)\n {\n Tensor x({ -2, 0, 1, 6 });\n square(x);\n NNTestAlmostEquals(x(0), 4, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 1, 1e-12);\n NNTestAlmostEquals(x(3), 36, 1e-12);\n }\n\n NNTestParams(Tensor &&)\n {\n Tensor x = square(Tensor({ -2, 0, 1, 6 }));\n NNTestAlmostEquals(x(0), 4, 1e-12);\n NNTestAlmostEquals(x(1), 0, 1e-12);\n NNTestAlmostEquals(x(2), 1, 1e-12);\n NNTestAlmostEquals(x(3), 36, 1e-12);\n }\n }\n\n NNTestMethod(rand)\n {\n NNTestParams(Tensor &, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n rand(x, -1, 1);\n NNTestAlmostEquals(mean(x), 0, 0.5);\n NNTestAlmostEquals(variance(x), 0.3333, 0.5);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = rand(Tensor(1000), -1, 1);\n NNTestAlmostEquals(mean(x), 0, 0.5);\n NNTestAlmostEquals(variance(x), 0.3333, 0.5);\n }\n }\n\n NNTestMethod(randn)\n {\n NNTestParams(Tensor &, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n randn(x, -1, 3.14);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestAlmostEquals(variance(x), 9.8596, 0.5);\n }\n\n NNTestParams(Tensor &&, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = randn(Tensor(1000), -1, 3.14);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestAlmostEquals(variance(x), 9.8596, 0.5);\n }\n\n NNTestParams(Tensor &, T, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n randn(x, -1, 3.14, 3);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestGreaterThanOrEquals(min(x), -4);\n NNTestLessThanOrEquals(max(x), 2);\n }\n\n NNTestParams(Tensor &&, T, T, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = randn(Tensor(1000), -1, 3.14, 3);\n NNTestAlmostEquals(mean(x), -1, 0.5);\n NNTestGreaterThanOrEquals(min(x), -4);\n NNTestLessThanOrEquals(max(x), 2);\n }\n }\n\n NNTestMethod(bernoulli)\n {\n NNTestParams(Tensor &, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x(1000);\n bernoulli(x, 0.25);\n size_t n = 0;\n forEach([&](T x)\n {\n if(x > 0.5)\n ++n;\n }, x);\n NNTestAlmostEquals(n, 0.25 * x.size(), 50);\n }\n\n NNTestParams(Tensor &&, T)\n {\n RandomEngine::sharedEngine().seed(0);\n Tensor x = bernoulli(Tensor(1000), 0.25);\n size_t n = 0;\n forEach([&](T x)\n {\n if(x > 0.5)\n ++n;\n }, x);\n NNTestAlmostEquals(n, 0.25 * x.size(), 50);\n }\n }\n\n NNTestMethod(sum)\n {\n NNTestParams(const Tensor &, Tensor &, size_t)\n {\n Tensor x = Tensor({ 1, 2, 3, 4, 5, 6 }).resize(2, 3);\n Tensor y = Tensor({ 5, 7, 9 });\n Tensor z(3);\n sum(x, z, 0);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n y = Tensor({ 6, 15 });\n z.resize(2);\n sum(x, z, 1);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n }\n\n NNTestParams(const Tensor &, Tensor &&, size_t)\n {\n Tensor x = Tensor({ 1, 2, 3, 4, 5, 6 }).resize(2, 3);\n Tensor y = Tensor({ 5, 7, 9 });\n Tensor z = sum(x, Tensor(3), 0);\n forEach([&](T y, T z)\n {\n NNTestAlmostEquals(y, z, 1e-12);\n }, y, z);\n }\n }\n\n NNTestMethod(pointwiseProduct)\n {\n NNTestParams(const Tensor &, Tensor &)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = Tensor({ 4, 5, 6 });\n pointwiseProduct(x, y);\n NNTestAlmostEquals(y(0), 4, 1e-12);\n NNTestAlmostEquals(y(1), 10, 1e-12);\n NNTestAlmostEquals(y(2), 18, 1e-12);\n }\n\n NNTestParams(const Tensor &, Tensor &&)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = pointwiseProduct(x, Tensor({ 4, 5, 6 }));\n NNTestAlmostEquals(y(0), 4, 1e-12);\n NNTestAlmostEquals(y(1), 10, 1e-12);\n NNTestAlmostEquals(y(2), 18, 1e-12);\n }\n\n NNTestParams(const Tensor &, const Tensor &, Tensor &)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = Tensor({ 4, 5, 6 });\n Tensor z(3);\n pointwiseProduct(x, y, z);\n NNTestAlmostEquals(z(0), 4, 1e-12);\n NNTestAlmostEquals(z(1), 10, 1e-12);\n NNTestAlmostEquals(z(2), 18, 1e-12);\n }\n\n NNTestParams(const Tensor &, const Tensor &, Tensor &&)\n {\n Tensor x = Tensor({ 1, 2, 3 });\n Tensor y = Tensor({ 4, 5, 6 });\n Tensor z = pointwiseProduct(x, y, Tensor(3));\n NNTestAlmostEquals(z(0), 4, 1e-12);\n NNTestAlmostEquals(z(1), 10, 1e-12);\n NNTestAlmostEquals(z(2), 18, 1e-12);\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"Halide.h\"\n\nusing namespace Halide;\nusing namespace Halide::Internal;\n\nclass ValidateInterleavedPipeline: public IRMutator {\nprotected:\n\/\/\n\/\/ This is roughly the structure that we are trying to validate in this custom pass:\n\/\/\n\/\/ parallel (result$2.s0.y$2.__block_id_y, 0, result$2.extent.1) {\n\/\/ parallel (result$2.s0.x$2.__block_id_x, 0, result$2.extent.0) {\n\/\/ ...\n\/\/ parallel (.__thread_id_x, 0, 1) {\n\/\/ for (result$2.s0.c$2, 0, 4) {\n\/\/ image_store(\"result$2\",\n\/\/ result$2.buffer,\n\/\/ (result$2.s0.x$2.__block_id_x + result$2.min.0),\n\/\/ (result$2.s0.y$2.__block_id_y + result$2.min.1),\n\/\/ result$2.s0.c$2,\n\/\/ image_load(\"input\",\n\/\/ input.buffer,\n\/\/ ((result$2.s0.x$2.__block_id_x + result$2.min.0) - input.min.0),\n\/\/ input.extent.0,\n\/\/ ((result$2.s0.y$2.__block_id_y + result$2.min.1) - input.min.1),\n\/\/ input.extent.1,\n\/\/ result$2.s0.c$2,\n\/\/ 4))\n\/\/ }\n\/\/ }\n\/\/ ...\n\/\/ }\n\/\/ }\n\/\/\n using IRMutator::visit;\n\n virtual void visit(const Call *call) {\n if (in_pipeline && call->is_intrinsic(Call::image_store)) {\n assert(for_nest_level == 4);\n\n std::map matches;\n\n assert(expr_match(\n StringImm::make(\"result\"),\n call->args[0],\n matches));\n assert(expr_match(\n Variable::make(Handle(1), \"result.buffer\"),\n call->args[1],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.x.__block_id_x\") + Variable::make(Int(32), \"result.min.0\"),\n call->args[2],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.y.__block_id_y\") + Variable::make(Int(32), \"result.min.1\"),\n call->args[3],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.c\"),\n call->args[4],\n matches));\n assert(expr_match(\n Call::make(\n UInt(8),\n Call::image_load,\n {\n StringImm::make(\"input\"),\n Variable::make(Handle(1), \"input.buffer\"),\n (Variable::make(Int(32), \"result.s0.x.__block_id_x\") +\n Variable::make(Int(32), \"result.min.0\")) -\n Variable::make(Int(32), \"input.min.0\"),\n Variable::make(Int(32), \"input.extent.0\"),\n (Variable::make(Int(32), \"result.s0.y.__block_id_y\") +\n Variable::make(Int(32), \"result.min.1\")) -\n Variable::make(Int(32), \"input.min.1\"),\n Variable::make(Int(32), \"input.extent.1\"),\n Variable::make(Int(32), \"result.s0.c\"),\n channels\n },\n Call::CallType::PureIntrinsic),\n call->args[5],\n matches));\n }\n IRMutator::visit(call);\n }\n\n void visit(const For *op) {\n if (in_pipeline) {\n assert(for_nest_level >= 0); \/\/ For-loop should show up in Pipeline.\n for_nest_level++;\n if (for_nest_level <= 3) {\n assert(op->for_type == ForType::Parallel);\n }\n assert(op->device_api == DeviceAPI::Renderscript);\n }\n IRMutator::visit(op);\n }\n\n void visit(const ProducerConsumer *op) {\n assert(!in_pipeline); \/\/ There should be only one pipeline in the test.\n for_nest_level = 0;\n in_pipeline = true;\n\n assert(op->produce.defined());\n assert(!op->update.defined());\n assert(op->consume.defined());\n\n IRMutator::visit(op);\n stmt = Stmt();\n }\n\n int for_nest_level = -1;\n bool in_pipeline = false;\n int channels;\n\npublic:\n ValidateInterleavedPipeline(int _channels) : channels(_channels) {}\n};\n\nclass ValidateInterleavedVectorizedPipeline: public ValidateInterleavedPipeline {\n using IRMutator::visit;\n using ValidateInterleavedPipeline::visit;\n\n virtual void visit(const Call *call) {\n if (in_pipeline && call->is_intrinsic(Call::image_store)) {\n assert(for_nest_level == 3); \/\/ Should be three nested for-loops before we get to the first call.\n\n std::map matches;\n\n assert(expr_match(\n Broadcast::make(StringImm::make(\"result\"), channels),\n call->args[0],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Handle(1), \"result.buffer\"), channels),\n call->args[1],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Int(32), \"result.s0.x.__block_id_x\") + Variable::make(Int(32), \"result.min.0\"), channels),\n call->args[2],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Int(32), \"result.s0.y.__block_id_y\") + Variable::make(Int(32), \"result.min.1\"), channels),\n call->args[3],\n matches));\n assert(expr_match(\n Ramp::make(0, 1, channels), call->args[4], matches));\n assert(expr_match(\n Call::make(\n UInt(8, channels),\n Call::image_load,\n {\n Broadcast::make(StringImm::make(\"input\"), channels),\n Broadcast::make(Variable::make(Handle(1), \"input.buffer\"), channels),\n Broadcast::make(\n Add::make(\n Variable::make(Int(32), \"result.s0.x.__block_id_x\"),\n Variable::make(Int(32), \"result.min.0\")) -\n Variable::make(Int(32), \"input.min.0\"),\n channels),\n Broadcast::make(Variable::make(Int(32), \"input.extent.0\"), channels),\n Broadcast::make(\n Add::make(\n Variable::make(Int(32), \"result.s0.y.__block_id_y\"),\n Variable::make(Int(32), \"result.min.1\")) -\n Variable::make(Int(32), \"input.min.1\"),\n channels),\n Broadcast::make(Variable::make(Int(32), \"input.extent.1\"), channels),\n Ramp::make(0, 1, channels),\n Broadcast::make(channels, channels)\n },\n Call::CallType::PureIntrinsic),\n call->args[5],\n matches));\n }\n IRMutator::visit(call);\n }\npublic:\n ValidateInterleavedVectorizedPipeline(int _channels) : ValidateInterleavedPipeline(_channels) {}\n};\n\nImage make_interleaved_image(uint8_t *host, int W, int H, int channels) {\n buffer_t buf = { 0 };\n buf.host = host;\n buf.extent[0] = W;\n buf.stride[0] = channels;\n buf.extent[1] = H;\n buf.stride[1] = buf.stride[0] * buf.extent[0];\n buf.extent[2] = channels;\n buf.stride[2] = 1;\n buf.elem_size = 1;\n return Image(&buf);\n}\n\nvoid copy_interleaved(bool vectorized = false, int channels = 4) {\n ImageParam input8(UInt(8), 3, \"input\");\n input8.set_stride(0, channels)\n .set_stride(1, Halide::Expr())\n .set_stride(2, 1)\n .set_bounds(2, 0, channels); \/\/ expecting interleaved image\n uint8_t *in_buf = new uint8_t[128 * 128 * channels];\n Image in = make_interleaved_image(in_buf, 128, 128, channels);\n input8.set(in);\n\n Var x, y, c;\n Func result(\"result\");\n result(x, y, c) = input8(x, y, c);\n result.output_buffer()\n .set_stride(0, channels)\n .set_stride(1, Halide::Expr())\n .set_stride(2, 1)\n .set_bounds(2, 0, channels); \/\/ expecting interleaved image\n\n result.bound(c, 0, channels);\n result.shader(x, y, c, DeviceAPI::Renderscript);\n if (vectorized) result.vectorize(c);\n\n result.add_custom_lowering_pass(\n vectorized?\n new ValidateInterleavedVectorizedPipeline(channels):\n new ValidateInterleavedPipeline(channels));\n\n result.compile_jit();\n\n delete[] in_buf;\n}\n\nint main(int argc, char **argv) {\n copy_interleaved(true, 4);\n copy_interleaved(false, 4);\n copy_interleaved(true, 3);\n copy_interleaved(false, 3);\n\n std::cout << \"Done!\" << std::endl;\n return 0;\n}\nFix renderscript test#include \"Halide.h\"\n\nusing namespace Halide;\nusing namespace Halide::Internal;\n\nclass ValidateInterleavedPipeline: public IRMutator {\nprotected:\n\/\/\n\/\/ This is roughly the structure that we are trying to validate in this custom pass:\n\/\/\n\/\/ parallel (result$2.s0.y$2.__block_id_y, 0, result$2.extent.1) {\n\/\/ parallel (result$2.s0.x$2.__block_id_x, 0, result$2.extent.0) {\n\/\/ ...\n\/\/ parallel (.__thread_id_x, 0, 1) {\n\/\/ for (result$2.s0.c$2, 0, 4) {\n\/\/ image_store(\"result$2\",\n\/\/ result$2.buffer,\n\/\/ (result$2.s0.x$2.__block_id_x + result$2.min.0),\n\/\/ (result$2.s0.y$2.__block_id_y + result$2.min.1),\n\/\/ result$2.s0.c$2,\n\/\/ image_load(\"input\",\n\/\/ input.buffer,\n\/\/ ((result$2.s0.x$2.__block_id_x + result$2.min.0) - input.min.0),\n\/\/ input.extent.0,\n\/\/ ((result$2.s0.y$2.__block_id_y + result$2.min.1) - input.min.1),\n\/\/ input.extent.1,\n\/\/ result$2.s0.c$2,\n\/\/ 4))\n\/\/ }\n\/\/ }\n\/\/ ...\n\/\/ }\n\/\/ }\n\/\/\n using IRMutator::visit;\n\n virtual void visit(const Call *call) {\n if (in_pipeline && call->is_intrinsic(Call::image_store)) {\n assert(for_nest_level == 4);\n\n std::map matches;\n\n assert(expr_match(\n StringImm::make(\"result\"),\n call->args[0],\n matches));\n assert(expr_match(\n Variable::make(Handle(1), \"result.buffer\"),\n call->args[1],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.x.__block_id_x\") + Variable::make(Int(32), \"result.min.0\"),\n call->args[2],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.y.__block_id_y\") + Variable::make(Int(32), \"result.min.1\"),\n call->args[3],\n matches));\n assert(expr_match(\n Variable::make(Int(32), \"result.s0.c\"),\n call->args[4],\n matches));\n assert(expr_match(\n Call::make(\n UInt(8),\n Call::image_load,\n {\n StringImm::make(\"input\"),\n Variable::make(Handle(1), \"input.buffer\"),\n (Variable::make(Int(32), \"result.s0.x.__block_id_x\") +\n Variable::make(Int(32), \"result.min.0\")) -\n Variable::make(Int(32), \"input.min.0\"),\n Variable::make(Int(32), \"input.extent.0\"),\n (Variable::make(Int(32), \"result.s0.y.__block_id_y\") +\n Variable::make(Int(32), \"result.min.1\")) -\n Variable::make(Int(32), \"input.min.1\"),\n Variable::make(Int(32), \"input.extent.1\"),\n Variable::make(Int(32), \"result.s0.c\"),\n channels\n },\n Call::CallType::PureIntrinsic),\n call->args[5],\n matches));\n }\n IRMutator::visit(call);\n }\n\n void visit(const For *op) {\n if (in_pipeline) {\n assert(for_nest_level >= 0); \/\/ For-loop should show up in Pipeline.\n for_nest_level++;\n if (for_nest_level <= 3) {\n assert(op->for_type == ForType::Parallel);\n assert(op->device_api == DeviceAPI::Renderscript);\n }\n }\n IRMutator::visit(op);\n }\n\n void visit(const ProducerConsumer *op) {\n assert(!in_pipeline); \/\/ There should be only one pipeline in the test.\n for_nest_level = 0;\n in_pipeline = true;\n\n assert(op->produce.defined());\n assert(!op->update.defined());\n assert(op->consume.defined());\n\n IRMutator::visit(op);\n stmt = Stmt();\n }\n\n int for_nest_level = -1;\n bool in_pipeline = false;\n int channels;\n\npublic:\n ValidateInterleavedPipeline(int _channels) : channels(_channels) {}\n};\n\nclass ValidateInterleavedVectorizedPipeline: public ValidateInterleavedPipeline {\n using IRMutator::visit;\n using ValidateInterleavedPipeline::visit;\n\n virtual void visit(const Call *call) {\n if (in_pipeline && call->is_intrinsic(Call::image_store)) {\n assert(for_nest_level == 3); \/\/ Should be three nested for-loops before we get to the first call.\n\n std::map matches;\n\n assert(expr_match(\n Broadcast::make(StringImm::make(\"result\"), channels),\n call->args[0],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Handle(1), \"result.buffer\"), channels),\n call->args[1],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Int(32), \"result.s0.x.__block_id_x\") + Variable::make(Int(32), \"result.min.0\"), channels),\n call->args[2],\n matches));\n assert(expr_match(\n Broadcast::make(Variable::make(Int(32), \"result.s0.y.__block_id_y\") + Variable::make(Int(32), \"result.min.1\"), channels),\n call->args[3],\n matches));\n assert(expr_match(\n Ramp::make(0, 1, channels), call->args[4], matches));\n assert(expr_match(\n Call::make(\n UInt(8, channels),\n Call::image_load,\n {\n Broadcast::make(StringImm::make(\"input\"), channels),\n Broadcast::make(Variable::make(Handle(1), \"input.buffer\"), channels),\n Broadcast::make(\n Add::make(\n Variable::make(Int(32), \"result.s0.x.__block_id_x\"),\n Variable::make(Int(32), \"result.min.0\")) -\n Variable::make(Int(32), \"input.min.0\"),\n channels),\n Broadcast::make(Variable::make(Int(32), \"input.extent.0\"), channels),\n Broadcast::make(\n Add::make(\n Variable::make(Int(32), \"result.s0.y.__block_id_y\"),\n Variable::make(Int(32), \"result.min.1\")) -\n Variable::make(Int(32), \"input.min.1\"),\n channels),\n Broadcast::make(Variable::make(Int(32), \"input.extent.1\"), channels),\n Ramp::make(0, 1, channels),\n Broadcast::make(channels, channels)\n },\n Call::CallType::PureIntrinsic),\n call->args[5],\n matches));\n }\n IRMutator::visit(call);\n }\npublic:\n ValidateInterleavedVectorizedPipeline(int _channels) : ValidateInterleavedPipeline(_channels) {}\n};\n\nImage make_interleaved_image(uint8_t *host, int W, int H, int channels) {\n buffer_t buf = { 0 };\n buf.host = host;\n buf.extent[0] = W;\n buf.stride[0] = channels;\n buf.extent[1] = H;\n buf.stride[1] = buf.stride[0] * buf.extent[0];\n buf.extent[2] = channels;\n buf.stride[2] = 1;\n buf.elem_size = 1;\n return Image(&buf);\n}\n\nvoid copy_interleaved(bool vectorized = false, int channels = 4) {\n ImageParam input8(UInt(8), 3, \"input\");\n input8.set_stride(0, channels)\n .set_stride(1, Halide::Expr())\n .set_stride(2, 1)\n .set_bounds(2, 0, channels); \/\/ expecting interleaved image\n uint8_t *in_buf = new uint8_t[128 * 128 * channels];\n Image in = make_interleaved_image(in_buf, 128, 128, channels);\n input8.set(in);\n\n Var x, y, c;\n Func result(\"result\");\n result(x, y, c) = input8(x, y, c);\n result.output_buffer()\n .set_stride(0, channels)\n .set_stride(1, Halide::Expr())\n .set_stride(2, 1)\n .set_bounds(2, 0, channels); \/\/ expecting interleaved image\n\n result.bound(c, 0, channels);\n result.shader(x, y, c, DeviceAPI::Renderscript);\n if (vectorized) result.vectorize(c);\n\n result.add_custom_lowering_pass(\n vectorized?\n new ValidateInterleavedVectorizedPipeline(channels):\n new ValidateInterleavedPipeline(channels));\n\n result.compile_jit();\n\n delete[] in_buf;\n}\n\nint main(int argc, char **argv) {\n copy_interleaved(true, 4);\n copy_interleaved(false, 4);\n copy_interleaved(true, 3);\n copy_interleaved(false, 3);\n\n std::cout << \"Done!\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"oddlib\/stream.hpp\"\n#include \n#include \"logger.hpp\"\n#include \"resourcemapper.hpp\"\n\nusing namespace ::testing;\n\nclass MockFileSystem : public IFileSystem\n{\npublic:\n virtual std::unique_ptr Open(const char* fileName) override\n {\n \/\/ Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call\n return std::unique_ptr(OpenProxy(fileName));\n }\n\n MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));\n MOCK_METHOD1(EnumerateFiles, std::vector(const char* ));\n MOCK_METHOD1(Exists, bool(const char*));\n};\n\nTEST(ResourceLocator, ResourceLoaderOpen)\n{\n MockFileSystem fs;\n\n ResourceLoader loader(fs);\n\n loader.Add(\"C:\\\\dataset_location1\", 1, \"AePc\");\n loader.Add(\"C:\\\\dataset_location2\", 2, \"AePc\");\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location1\\\\SLIGZ.BND\")))\n .WillRepeatedly(Return(nullptr));\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location2\\\\SLIGZ.BND\")))\n .Times(1)\n .WillOnce(Return(new Oddlib::Stream(StringToVector(\"test\"))));\n\n auto stream = loader.Open(\"SLIGZ.BND\");\n ASSERT_NE(nullptr, stream);\n\n const auto str = stream->LoadAllToString();\n ASSERT_EQ(str, \"test\");\n}\n\nTEST(ResourceLocator, Cache)\n{\n ResourceCache cache;\n\n const size_t resNameHash = StringHash(\"foo\");\n ASSERT_EQ(nullptr, cache.Find(resNameHash));\n {\n Resource res1(resNameHash, cache, nullptr);\n\n std::shared_ptr cached = cache.Find(resNameHash);\n ASSERT_NE(nullptr, cached);\n ASSERT_EQ(cached.get(), res1.Ptr());\n }\n ASSERT_EQ(nullptr, cache.Find(resNameHash));\n}\n\nTEST(ResourceLocator, ParseResourceMap)\n{\n const std::string resourceMapsJson = R\"({\"anims\":[{\"blend_mode\":1,\"name\":\"SLIGZ.BND_417_1\"},{\"blend_mode\":1,\"name\":\"SLIGZ.BND_417_2\"}],\"file\":\"SLIGZ.BND\",\"id\":417})\";\n\n MockFileSystem fs;\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"resource_maps.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));\n\n ResourceMapper mapper(fs, \"resource_maps.json\");\n \n const ResourceMapper::AnimMapping* r0 = mapper.Find(\"I don't exist\");\n ASSERT_EQ(nullptr, r0);\n\n const ResourceMapper::AnimMapping* r1 = mapper.Find(\"SLIGZ.BND_417_1\");\n ASSERT_NE(nullptr, r1);\n ASSERT_EQ(\"SLIGZ.BND\", r1->mFile);\n ASSERT_EQ(417u, r1->mId);\n ASSERT_EQ(1u, r1->mBlendingMode);\n\n const ResourceMapper::AnimMapping* r2 = mapper.Find(\"SLIGZ.BND_417_2\");\n ASSERT_NE(nullptr, r2);\n ASSERT_EQ(\"SLIGZ.BND\", r2->mFile);\n ASSERT_EQ(417u, r2->mId);\n ASSERT_EQ(1u, r2->mBlendingMode);\n\n}\n\nTEST(ResourceLocator, ParseGameDefinition)\n{\n\n const std::string gameDefJson = R\"(\n {\n \"Name\" : \"Oddworld Abe's Exoddus PC\",\n \"Description\" : \"The original PC version of Oddworld Abe's Exoddus\",\n \"Author\" : \"Oddworld Inhabitants\",\n \"InitialLevel\" : \"st_path1\",\n \"DatasetName\" : \"AePc\",\n \"RequiredDatasets\" : []\n }\n )\";\n\n MockFileSystem fs;\n EXPECT_CALL(fs, OpenProxy(StrEq(\"test_game_definition.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(gameDefJson))));\n\n GameDefinition gd(fs, \"test_game_definition.json\");\n ASSERT_EQ(gd.Name(), \"Oddworld Abe's Exoddus PC\");\n ASSERT_EQ(gd.Description(), \"The original PC version of Oddworld Abe's Exoddus\");\n ASSERT_EQ(gd.Author(), \"Oddworld Inhabitants\");\n ASSERT_EQ(gd.InitialLevel(), \"st_path1\");\n ASSERT_EQ(gd.DataSet(), \"AePc\");\n}\n\nTEST(ResourceLocator, GameDefinitionDiscovery)\n{\n \/\/ TODO - enumerating GD's\n}\n\nTEST(ResourceLocator, LocateAnimation)\n{\n GameDefinition aePc;\n\n MockFileSystem fs;\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location1\\\\SLIGZ.BND\")))\n .WillRepeatedly(Return(nullptr));\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location2\\\\SLIGZ.BND\")))\n .Times(1)\n .WillOnce(Return(new Oddlib::Stream(StringToVector(\"test\")))); \/\/ For SLIGZ.BND_417_1, 2nd call should be cached\n\n ResourceMapper mapper;\n mapper.AddAnimMapping(\"SLIGZ.BND_417_1\", { \"SLIGZ.BND\", 417, 1 });\n mapper.AddAnimMapping(\"SLIGZ.BND_417_2\", { \"SLIGZ.BND\", 417, 1 });\n\n ResourceLocator locator(fs, aePc, std::move(mapper));\n\n locator.AddDataPath(\"C:\\\\dataset_location2\", 2, \"AoPc\");\n locator.AddDataPath(\"C:\\\\dataset_location1\", 1, \"AePc\");\n \n Resource resMapped1 = locator.Locate(\"SLIGZ.BND_417_1\");\n resMapped1.Reload();\n\n Resource resMapped2 = locator.Locate(\"SLIGZ.BND_417_1\");\n resMapped2.Reload();\n\n \/\/ Can explicitly set the dataset to obtain it from a known location\n Resource resDirect = locator.Locate(\"SLIGZ.BND_417_1\", \"AePc\");\n resDirect.Reload();\n}\n\nTEST(ResourceLocator, LocateAnimationMod)\n{\n \/\/ TODO: Like LocateAnimation but with mod override with and without original data\n}\n\nTEST(ResourceLocator, LocateFmv)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateSound)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateMusic)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateCamera)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocatePath)\n{\n \/\/ TODO\n}\n\nclass DataPathIdentities\n{\npublic:\n DataPathIdentities(IFileSystem& fs, const char* dataSetsIdsFileName)\n {\n auto stream = fs.Open(dataSetsIdsFileName);\n Parse(stream->LoadAllToString());\n }\n\n void AddIdentity(const std::string& dataSetName, const std::vector& idenfyingFiles)\n {\n mDataPathIds[dataSetName] = idenfyingFiles;\n }\n\n std::string Identify(IFileSystem& fs, const std::string& path) const\n {\n for (const auto& dataPathId : mDataPathIds)\n {\n bool foundAll = true;\n for (const auto& identifyingFile : dataPathId.second)\n {\n if (!fs.Exists((path + \"\\\\\" + identifyingFile).c_str()))\n {\n foundAll = false;\n break;\n }\n }\n if (foundAll)\n {\n return dataPathId.first;\n }\n }\n return \"\";\n }\n\nprivate:\n std::map> mDataPathIds;\n\n void Parse(const std::string& json)\n {\n jsonxx::Object root;\n root.parse(json);\n if (root.has(\"data_set_ids\"))\n {\n jsonxx::Object dataSetIds = root.get(\"data_set_ids\");\n for (const auto& v : dataSetIds.kv_map())\n {\n jsonxx::Object dataSetId = dataSetIds.get(v.first);\n jsonxx::Array identifyingFiles = dataSetId.get(\"files\");\n std::vector files;\n files.reserve(identifyingFiles.size());\n for (const auto& f : identifyingFiles.values())\n {\n files.emplace_back(f->get());\n }\n mDataPathIds[v.first] = files;\n }\n }\n }\n};\n\n\nclass DataPaths\n{\npublic:\n DataPaths(IFileSystem& fs, const char* dataSetsIdsFileName, const char* dataPathFileName)\n : mIds(fs, dataSetsIdsFileName)\n {\n auto stream = fs.Open(dataPathFileName);\n std::vector paths = Parse(stream->LoadAllToString());\n for (const auto& path : paths)\n {\n \/\/ TODO: Store the path and its identity\n std::string id = mIds.Identify(fs, path);\n auto it = mPaths.find(id);\n if (it == std::end(mPaths))\n {\n mPaths[id] = std::vector < std::string > {path};\n }\n else\n {\n it->second.push_back(path);\n }\n }\n }\n\n const std::vector& PathsFor(const std::string& id)\n {\n auto it = mPaths.find(id);\n if (it == std::end(mPaths))\n {\n return mNotFoundResult;\n }\n else\n {\n return it->second;\n }\n }\n\n std::vector MissingDataSets(const std::vector& requiredSets)\n {\n std::vector ret;\n for (const auto& dataset : requiredSets)\n {\n if (!PathsFor(dataset).empty())\n {\n break;\n }\n ret.emplace_back(dataset);\n }\n return ret;\n }\n\nprivate:\n std::map> mPaths;\n\n std::vector Parse(const std::string& json)\n {\n std::vector paths;\n jsonxx::Object root;\n root.parse(json);\n if (root.has(\"paths\"))\n {\n jsonxx::Array pathsArray = root.get(\"paths\");\n for (const auto& path : pathsArray.values())\n {\n paths.emplace_back(path->get());\n }\n }\n return paths;\n }\n\n \/\/ To match to what a game def wants (AePcCd1, AoDemoPsx etc)\n \/\/ we use SLUS codes for PSX or if it contains ABEWIN.EXE etc then its AoPc.\n DataPathIdentities mIds;\n std::vector mNotFoundResult;\n};\n\n\nTEST(ResourceLocator, Construct)\n{\n\n MockFileSystem fs;\n\n const std::string resourceMapsJson = R\"(\n {\n \"data_set_ids\" :\n {\n \"AoPc\": { \"files\": [ \"AbeWin.exe\" ] },\n \"AePc\": { \"files\": [ \"Exoddus.exe\" ] }\n }\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"datasetids.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));\n\n const std::string dataSetsJson = R\"(\n {\n \"paths\": [\n \"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\",\n \"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\"\n ]\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"datasets.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(dataSetsJson))));\n\n EXPECT_CALL(fs, Exists(StrEq(\"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\\\\Exoddus.exe\")))\n .WillOnce(Return(true));\n\n EXPECT_CALL(fs, Exists(StrEq(\"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\\\AbeWin.exe\")))\n .WillOnce(Return(false));\n EXPECT_CALL(fs, Exists(StrEq(\"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\\\Exoddus.exe\")))\n .WillOnce(Return(false));\n\n EXPECT_CALL(fs, EnumerateFiles(StrEq(\"${game_files}\\\\GameDefinitions\")))\n .WillOnce(Return(std::vector { \"AbesExoddusPc.json\" }));\n\n EXPECT_CALL(fs, EnumerateFiles(StrEq(\"${user_home}\\\\Alive\\\\Mods\")))\n .WillOnce(Return(std::vector { }));\n\n\n const std::string aePcGameDefJson = R\"(\n {\n \"Name\" : \"Oddworld Abe's Exoddus PC\",\n \"Description\" : \"The original PC version of Oddworld Abe's Exoddus\",\n \"Author\" : \"Oddworld Inhabitants\",\n \"InitialLevel\" : \"st_path1\",\n \"DatasetName\" : \"AePc\",\n \"RequiredDatasets\" : [ \"Foo1\", \"Foo2\" ]\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"${game_files}\\\\GameDefinitions\\\\AbesExoddusPc.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(aePcGameDefJson))));\n\n\n \/\/ Data paths are saved user paths to game data\n \/\/ load the list of data paths (if any) and discover what they are\n DataPaths dataPaths(fs, \"datasetids.json\", \"datasets.json\");\n\n auto aoPaths = dataPaths.PathsFor(\"AoPc\");\n ASSERT_EQ(aoPaths.size(), 0u);\n\n\n auto aePaths = dataPaths.PathsFor(\"AePc\");\n ASSERT_EQ(aePaths.size(), 1u);\n ASSERT_EQ(aePaths[0], \"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\");\n\n \n std::vector gds;\n \n\n \/\/ load the enumerated \"built-in\" game defs\n const auto builtInGds = fs.EnumerateFiles(\"${game_files}\\\\GameDefinitions\");\n for (const auto& file : builtInGds)\n {\n gds.emplace_back(GameDefinition(fs, (std::string(\"${game_files}\\\\GameDefinitions\") + \"\\\\\" + file).c_str()));\n }\n\n \/\/ load the enumerated \"mod\" game defs\n const auto modGs = fs.EnumerateFiles(\"${user_home}\\\\Alive\\\\Mods\");\n for (const auto& file : modGs)\n {\n gds.emplace_back(GameDefinition(fs, (std::string(\"${user_home}\\\\Alive\\\\Mods\") + \"\\\\\" + file).c_str()));\n }\n\n\n ResourceMapper mapper;\n\n \/\/ Get the user selected game def\n GameDefinition& selected = gds[0];\n\n \/\/ ask for any missing data sets\n auto requiredSets = selected.RequiredDataSets();\n requiredSets.emplace_back(\"AePc\"); \/\/ add in self to check its found\n const auto missing = dataPaths.MissingDataSets(requiredSets);\n const std::vector expected{ \"Foo1\", \"Foo2\" };\n ASSERT_EQ(expected, missing);\n\n \/\/ TODO: Pass in data paths here instead of calling AddDataPath?\n \/\/ create the resource mapper loading the resource maps from the json db\n ResourceLocator resourceLocator(fs, selected, std::move(mapper));\n \n \/\/ TODO: Should be a DataPath instance (?)\n \/\/locator.AddDataPath(dataPaths);\n\n \/\/ TODO: Allow changing at any point, don't set in ctor?\n \/\/resourceLocator.SetGameDefinition(&selected);\n \n \/\/ Now we can obtain resources\n Resource resMapped1 = resourceLocator.Locate(\"SLIGZ.BND_417_1\");\n resMapped1.Reload();\n\n}\nAdd GameDef paths to ResourceLocator#include \n#include \n#include \"oddlib\/stream.hpp\"\n#include \n#include \"logger.hpp\"\n#include \"resourcemapper.hpp\"\n\nusing namespace ::testing;\n\nclass MockFileSystem : public IFileSystem\n{\npublic:\n virtual std::unique_ptr Open(const char* fileName) override\n {\n \/\/ Can't mock unique_ptr return, so mock raw one which the unique_ptr one will call\n return std::unique_ptr(OpenProxy(fileName));\n }\n\n MOCK_METHOD1(OpenProxy, Oddlib::IStream*(const char*));\n MOCK_METHOD1(EnumerateFiles, std::vector(const char* ));\n MOCK_METHOD1(Exists, bool(const char*));\n};\n\nTEST(ResourceLocator, ResourceLoaderOpen)\n{\n MockFileSystem fs;\n\n ResourceLoader loader(fs);\n\n loader.Add(\"C:\\\\dataset_location1\", 1, \"AePc\");\n loader.Add(\"C:\\\\dataset_location2\", 2, \"AePc\");\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location1\\\\SLIGZ.BND\")))\n .WillRepeatedly(Return(nullptr));\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location2\\\\SLIGZ.BND\")))\n .Times(1)\n .WillOnce(Return(new Oddlib::Stream(StringToVector(\"test\"))));\n\n auto stream = loader.Open(\"SLIGZ.BND\");\n ASSERT_NE(nullptr, stream);\n\n const auto str = stream->LoadAllToString();\n ASSERT_EQ(str, \"test\");\n}\n\nTEST(ResourceLocator, Cache)\n{\n ResourceCache cache;\n\n const size_t resNameHash = StringHash(\"foo\");\n ASSERT_EQ(nullptr, cache.Find(resNameHash));\n {\n Resource res1(resNameHash, cache, nullptr);\n\n std::shared_ptr cached = cache.Find(resNameHash);\n ASSERT_NE(nullptr, cached);\n ASSERT_EQ(cached.get(), res1.Ptr());\n }\n ASSERT_EQ(nullptr, cache.Find(resNameHash));\n}\n\nTEST(ResourceLocator, ParseResourceMap)\n{\n const std::string resourceMapsJson = R\"({\"anims\":[{\"blend_mode\":1,\"name\":\"SLIGZ.BND_417_1\"},{\"blend_mode\":1,\"name\":\"SLIGZ.BND_417_2\"}],\"file\":\"SLIGZ.BND\",\"id\":417})\";\n\n MockFileSystem fs;\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"resource_maps.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));\n\n ResourceMapper mapper(fs, \"resource_maps.json\");\n \n const ResourceMapper::AnimMapping* r0 = mapper.Find(\"I don't exist\");\n ASSERT_EQ(nullptr, r0);\n\n const ResourceMapper::AnimMapping* r1 = mapper.Find(\"SLIGZ.BND_417_1\");\n ASSERT_NE(nullptr, r1);\n ASSERT_EQ(\"SLIGZ.BND\", r1->mFile);\n ASSERT_EQ(417u, r1->mId);\n ASSERT_EQ(1u, r1->mBlendingMode);\n\n const ResourceMapper::AnimMapping* r2 = mapper.Find(\"SLIGZ.BND_417_2\");\n ASSERT_NE(nullptr, r2);\n ASSERT_EQ(\"SLIGZ.BND\", r2->mFile);\n ASSERT_EQ(417u, r2->mId);\n ASSERT_EQ(1u, r2->mBlendingMode);\n\n}\n\nTEST(ResourceLocator, ParseGameDefinition)\n{\n\n const std::string gameDefJson = R\"(\n {\n \"Name\" : \"Oddworld Abe's Exoddus PC\",\n \"Description\" : \"The original PC version of Oddworld Abe's Exoddus\",\n \"Author\" : \"Oddworld Inhabitants\",\n \"InitialLevel\" : \"st_path1\",\n \"DatasetName\" : \"AePc\",\n \"RequiredDatasets\" : []\n }\n )\";\n\n MockFileSystem fs;\n EXPECT_CALL(fs, OpenProxy(StrEq(\"test_game_definition.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(gameDefJson))));\n\n GameDefinition gd(fs, \"test_game_definition.json\");\n ASSERT_EQ(gd.Name(), \"Oddworld Abe's Exoddus PC\");\n ASSERT_EQ(gd.Description(), \"The original PC version of Oddworld Abe's Exoddus\");\n ASSERT_EQ(gd.Author(), \"Oddworld Inhabitants\");\n ASSERT_EQ(gd.InitialLevel(), \"st_path1\");\n ASSERT_EQ(gd.DataSet(), \"AePc\");\n}\n\nTEST(ResourceLocator, GameDefinitionDiscovery)\n{\n \/\/ TODO - enumerating GD's\n}\n\nTEST(ResourceLocator, LocateAnimation)\n{\n GameDefinition aePc;\n\n MockFileSystem fs;\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location1\\\\SLIGZ.BND\")))\n .WillRepeatedly(Return(nullptr));\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"C:\\\\dataset_location2\\\\SLIGZ.BND\")))\n .Times(1)\n .WillOnce(Return(new Oddlib::Stream(StringToVector(\"test\")))); \/\/ For SLIGZ.BND_417_1, 2nd call should be cached\n\n ResourceMapper mapper;\n mapper.AddAnimMapping(\"SLIGZ.BND_417_1\", { \"SLIGZ.BND\", 417, 1 });\n mapper.AddAnimMapping(\"SLIGZ.BND_417_2\", { \"SLIGZ.BND\", 417, 1 });\n\n ResourceLocator locator(fs, aePc, std::move(mapper));\n\n locator.AddDataPath(\"C:\\\\dataset_location2\", 2, \"AoPc\");\n locator.AddDataPath(\"C:\\\\dataset_location1\", 1, \"AePc\");\n \n Resource resMapped1 = locator.Locate(\"SLIGZ.BND_417_1\");\n resMapped1.Reload();\n\n Resource resMapped2 = locator.Locate(\"SLIGZ.BND_417_1\");\n resMapped2.Reload();\n\n \/\/ Can explicitly set the dataset to obtain it from a known location\n Resource resDirect = locator.Locate(\"SLIGZ.BND_417_1\", \"AePc\");\n resDirect.Reload();\n}\n\nTEST(ResourceLocator, LocateAnimationMod)\n{\n \/\/ TODO: Like LocateAnimation but with mod override with and without original data\n}\n\nTEST(ResourceLocator, LocateFmv)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateSound)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateMusic)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocateCamera)\n{\n \/\/ TODO\n}\n\nTEST(ResourceLocator, LocatePath)\n{\n \/\/ TODO\n}\n\nclass DataPathIdentities\n{\npublic:\n DataPathIdentities(IFileSystem& fs, const char* dataSetsIdsFileName)\n {\n auto stream = fs.Open(dataSetsIdsFileName);\n Parse(stream->LoadAllToString());\n }\n\n void AddIdentity(const std::string& dataSetName, const std::vector& idenfyingFiles)\n {\n mDataPathIds[dataSetName] = idenfyingFiles;\n }\n\n std::string Identify(IFileSystem& fs, const std::string& path) const\n {\n for (const auto& dataPathId : mDataPathIds)\n {\n bool foundAll = true;\n for (const auto& identifyingFile : dataPathId.second)\n {\n if (!fs.Exists((path + \"\\\\\" + identifyingFile).c_str()))\n {\n foundAll = false;\n break;\n }\n }\n if (foundAll)\n {\n return dataPathId.first;\n }\n }\n return \"\";\n }\n\nprivate:\n std::map> mDataPathIds;\n\n void Parse(const std::string& json)\n {\n jsonxx::Object root;\n root.parse(json);\n if (root.has(\"data_set_ids\"))\n {\n jsonxx::Object dataSetIds = root.get(\"data_set_ids\");\n for (const auto& v : dataSetIds.kv_map())\n {\n jsonxx::Object dataSetId = dataSetIds.get(v.first);\n jsonxx::Array identifyingFiles = dataSetId.get(\"files\");\n std::vector files;\n files.reserve(identifyingFiles.size());\n for (const auto& f : identifyingFiles.values())\n {\n files.emplace_back(f->get());\n }\n mDataPathIds[v.first] = files;\n }\n }\n }\n};\n\n\nclass DataPaths\n{\npublic:\n DataPaths(IFileSystem& fs, const char* dataSetsIdsFileName, const char* dataPathFileName)\n : mIds(fs, dataSetsIdsFileName)\n {\n auto stream = fs.Open(dataPathFileName);\n std::vector paths = Parse(stream->LoadAllToString());\n for (const auto& path : paths)\n {\n \/\/ TODO: Store the path and its identity\n std::string id = mIds.Identify(fs, path);\n auto it = mPaths.find(id);\n if (it == std::end(mPaths))\n {\n mPaths[id] = std::vector < std::string > {path};\n }\n else\n {\n it->second.push_back(path);\n }\n }\n }\n\n const std::vector& PathsFor(const std::string& id)\n {\n auto it = mPaths.find(id);\n if (it == std::end(mPaths))\n {\n return mNotFoundResult;\n }\n else\n {\n return it->second;\n }\n }\n\n std::vector MissingDataSets(const std::vector& requiredSets)\n {\n std::vector ret;\n for (const auto& dataset : requiredSets)\n {\n if (!PathsFor(dataset).empty())\n {\n break;\n }\n ret.emplace_back(dataset);\n }\n return ret;\n }\n\nprivate:\n std::map> mPaths;\n\n std::vector Parse(const std::string& json)\n {\n std::vector paths;\n jsonxx::Object root;\n root.parse(json);\n if (root.has(\"paths\"))\n {\n jsonxx::Array pathsArray = root.get(\"paths\");\n for (const auto& path : pathsArray.values())\n {\n paths.emplace_back(path->get());\n }\n }\n return paths;\n }\n\n \/\/ To match to what a game def wants (AePcCd1, AoDemoPsx etc)\n \/\/ we use SLUS codes for PSX or if it contains ABEWIN.EXE etc then its AoPc.\n DataPathIdentities mIds;\n std::vector mNotFoundResult;\n};\n\n\nTEST(ResourceLocator, Construct)\n{\n\n MockFileSystem fs;\n\n const std::string resourceMapsJson = R\"(\n {\n \"data_set_ids\" :\n {\n \"AoPc\": { \"files\": [ \"AbeWin.exe\" ] },\n \"AePc\": { \"files\": [ \"Exoddus.exe\" ] }\n }\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"datasetids.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(resourceMapsJson))));\n\n const std::string dataSetsJson = R\"(\n {\n \"paths\": [\n \"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\",\n \"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\"\n ]\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"datasets.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(dataSetsJson))));\n\n EXPECT_CALL(fs, Exists(StrEq(\"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\\\\Exoddus.exe\")))\n .WillOnce(Return(true));\n\n EXPECT_CALL(fs, Exists(StrEq(\"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\\\AbeWin.exe\")))\n .WillOnce(Return(false));\n EXPECT_CALL(fs, Exists(StrEq(\"C:\\\\data\\\\Oddworld - Abe's Exoddus (E) (Disc 1) [SLES-01480].bin\\\\Exoddus.exe\")))\n .WillOnce(Return(false));\n\n EXPECT_CALL(fs, EnumerateFiles(StrEq(\"${game_files}\\\\GameDefinitions\")))\n .WillOnce(Return(std::vector { \"AbesExoddusPc.json\" }));\n\n EXPECT_CALL(fs, EnumerateFiles(StrEq(\"${user_home}\\\\Alive\\\\Mods\")))\n .WillOnce(Return(std::vector { }));\n\n\n const std::string aePcGameDefJson = R\"(\n {\n \"Name\" : \"Oddworld Abe's Exoddus PC\",\n \"Description\" : \"The original PC version of Oddworld Abe's Exoddus\",\n \"Author\" : \"Oddworld Inhabitants\",\n \"InitialLevel\" : \"st_path1\",\n \"DatasetName\" : \"AePc\",\n \"RequiredDatasets\" : [ \"Foo1\", \"Foo2\" ]\n }\n )\";\n\n EXPECT_CALL(fs, OpenProxy(StrEq(\"${game_files}\\\\GameDefinitions\\\\AbesExoddusPc.json\")))\n .WillRepeatedly(Return(new Oddlib::Stream(StringToVector(aePcGameDefJson))));\n\n\n \/\/ Data paths are saved user paths to game data\n \/\/ load the list of data paths (if any) and discover what they are\n DataPaths dataPaths(fs, \"datasetids.json\", \"datasets.json\");\n\n auto aoPaths = dataPaths.PathsFor(\"AoPc\");\n ASSERT_EQ(aoPaths.size(), 0u);\n\n\n auto aePaths = dataPaths.PathsFor(\"AePc\");\n ASSERT_EQ(aePaths.size(), 1u);\n ASSERT_EQ(aePaths[0], \"F:\\\\Program Files\\\\SteamGames\\\\SteamApps\\\\common\\\\Oddworld Abes Exoddus\");\n\n \n std::vector gds;\n \n\n \/\/ load the enumerated \"built-in\" game defs\n const auto builtInGds = fs.EnumerateFiles(\"${game_files}\\\\GameDefinitions\");\n for (const auto& file : builtInGds)\n {\n gds.emplace_back(GameDefinition(fs, (std::string(\"${game_files}\\\\GameDefinitions\") + \"\\\\\" + file).c_str()));\n }\n\n \/\/ load the enumerated \"mod\" game defs\n const auto modGs = fs.EnumerateFiles(\"${user_home}\\\\Alive\\\\Mods\");\n for (const auto& file : modGs)\n {\n gds.emplace_back(GameDefinition(fs, (std::string(\"${user_home}\\\\Alive\\\\Mods\") + \"\\\\\" + file).c_str()));\n }\n\n \/\/ Get the user selected game def\n GameDefinition& selected = gds[0];\n\n \/\/ ask for any missing data sets\n auto requiredSets = selected.RequiredDataSets();\n requiredSets.emplace_back(\"AePc\"); \/\/ add in self to check its found\n const auto missing = dataPaths.MissingDataSets(requiredSets);\n const std::vector expected{ \"Foo1\", \"Foo2\" };\n ASSERT_EQ(expected, missing);\n\n \/\/ create the resource mapper loading the resource maps from the json db\n ResourceMapper mapper;\n mapper.AddAnimMapping(\"SLIGZ.BND_417_1\", { \"SLIGZ.BND\", 417, 1 });\n\n ResourceLocator resourceLocator(fs, selected, std::move(mapper));\n \n \/\/ TODO: Handle extra mod dependant data sets\n\n for (const auto& requiredSet : selected.RequiredDataSets())\n {\n const auto& paths = dataPaths.PathsFor(requiredSet);\n for (const auto& path : paths)\n {\n \/\/ TODO: Priority\n resourceLocator.AddDataPath(path.c_str(), 0, requiredSet);\n }\n }\n\n \/\/ Now we can obtain resources\n Resource resMapped1 = resourceLocator.Locate(\"SLIGZ.BND_417_1\");\n resMapped1.Reload();\n\n}\n<|endoftext|>"} {"text":"\/*\n * SessionExecuteChunkOperation.hpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n#ifndef SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP\n#define SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"NotebookOutput.hpp\"\n#include \"NotebookExec.hpp\"\n#include \"SessionRmdNotebook.hpp\"\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\n\nnamespace {\n\ncore::shell_utils::ShellCommand shellCommandForEngine(\n const std::string& engine,\n const std::map& options)\n{\n using namespace core;\n using namespace core::string_utils;\n using namespace core::shell_utils;\n \n \/\/ determine engine path -- respect chunk option 'engine.path' if supplied\n std::string enginePath = engine;\n if (options.count(\"engine.path\"))\n {\n std::string path = options.at(\"engine.path\");\n enginePath = module_context::resolveAliasedPath(path).absolutePath();\n }\n \n ShellCommand command(enginePath);\n \n \/\/ pass along 'engine.opts' if supplied\n if (options.count(\"engine.opts\"))\n command << EscapeFilesOnly << options.at(\"engine.opts\") << EscapeAll;\n \n return command;\n}\n\nstd::string scriptPathForShellCommand(\n const core::FilePath& scriptPath,\n const std::string& engine,\n const std::map& chunkOptions)\n{\n using namespace core;\n\n auto defaultPath = [&]() {\n return string_utils::utf8ToSystem(scriptPath.absolutePathNative());\n };\n\n#ifndef _WIN32\n return defaultPath();\n#else\n if (engine == \"bash\")\n {\n std::string bashPath = \"bash.exe\";\n if (chunkOptions.count(\"engine.path\"))\n {\n FilePath resolvedPath =\n module_context::resolveAliasedPath(chunkOptions.at(\"engine.path\"));\n bashPath = resolvedPath.absolutePathNative();\n }\n\n system::ProcessOptions options;\n options.workingDir = scriptPath.parent();\n\n system::ProcessResult result;\n Error error = system::runCommand(\n bashPath + \" --norc --noprofile -c pwd\",\n options,\n &result);\n if (error)\n {\n LOG_ERROR(error);\n return defaultPath();\n }\n\n std::string path =\n string_utils::trimWhitespace(result.stdOut) +\n \"\/\" +\n scriptPath.filename();\n return string_utils::utf8ToSystem(path);\n }\n else\n {\n return defaultPath();\n }\n#endif\n}\n\n} \/\/ end anonymous namespace\n\nclass ExecuteChunkOperation : boost::noncopyable,\n public boost::enable_shared_from_this\n{\n typedef core::shell_utils::ShellCommand ShellCommand;\n typedef core::system::ProcessCallbacks ProcessCallbacks;\n typedef core::system::ProcessOperations ProcessOperations;\n \npublic:\n static boost::shared_ptr create(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const ShellCommand& command,\n const core::FilePath& scriptPath)\n {\n boost::shared_ptr pProcess =\n boost::shared_ptr(new ExecuteChunkOperation(\n docId,\n chunkId,\n nbCtxId,\n command,\n scriptPath));\n pProcess->registerProcess();\n return pProcess;\n }\n \nprivate:\n \n ExecuteChunkOperation(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const ShellCommand& command,\n const core::FilePath& scriptPath)\n : terminationRequested_(false),\n docId_(docId),\n chunkId_(chunkId),\n nbCtxId_(nbCtxId),\n command_(command),\n scriptPath_(scriptPath)\n {\n using namespace core;\n Error error = Success();\n \n \/\/ ensure regular directory\n FilePath outputPath = chunkOutputPath(\n docId_,\n chunkId_,\n ContextExact);\n \n error = outputPath.removeIfExists();\n if (error)\n LOG_ERROR(error);\n \n error = outputPath.ensureDirectory();\n if (error)\n LOG_ERROR(error);\n \n \/\/ clean old chunk output\n error = cleanChunkOutput(docId_, chunkId_, nbCtxId_, true);\n if (error)\n LOG_ERROR(error);\n }\n \npublic:\n \n ProcessCallbacks processCallbacks()\n {\n ProcessCallbacks callbacks;\n \n callbacks.onStarted = boost::bind(\n &ExecuteChunkOperation::onStarted,\n shared_from_this());\n \n callbacks.onContinue = boost::bind(\n &ExecuteChunkOperation::onContinue,\n shared_from_this());\n \n callbacks.onStdout = boost::bind(\n &ExecuteChunkOperation::onStdout,\n shared_from_this(),\n _2);\n \n callbacks.onStderr = boost::bind(\n &ExecuteChunkOperation::onStderr,\n shared_from_this(),\n _2);\n \n callbacks.onExit = boost::bind(\n &ExecuteChunkOperation::onExit,\n shared_from_this(),\n _1);\n \n return callbacks;\n }\n \nprivate:\n \n enum OutputType { OUTPUT_STDOUT, OUTPUT_STDERR };\n \n void onStarted()\n {\n }\n \n bool onContinue()\n {\n return !terminationRequested_;\n }\n \n void onExit(int exitStatus)\n {\n events().onChunkExecCompleted(docId_, chunkId_, notebookCtxId());\n deregisterProcess();\n scriptPath_.removeIfExists();\n }\n \n void onStdout(const std::string& output)\n {\n onText(output, OUTPUT_STDOUT);\n }\n \n void onStderr(const std::string& output)\n {\n onText(output, OUTPUT_STDERR);\n }\n \n void onText(const std::string& output, OutputType outputType)\n {\n using namespace core;\n \n \/\/ get path to cache file\n FilePath target = chunkOutputFile(docId_, chunkId_, nbCtxId_,\n ChunkOutputText);\n \n \/\/ append console data (for notebook cache)\n notebook::appendConsoleOutput(\n outputType == OUTPUT_STDOUT ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n target);\n \n \/\/ write to temporary file (for streaming output)\n FilePath tempFile = module_context::tempFile(\"chunk-output-\", \"txt\");\n RemoveOnExitScope scope(tempFile, ERROR_LOCATION);\n notebook::appendConsoleOutput(\n outputType == OUTPUT_STDOUT ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n tempFile);\n \n \/\/ emit client event\n enqueueChunkOutput(\n docId_,\n chunkId_,\n nbCtxId_,\n 0, \/\/ no ordinals needed for alternate engines\n ChunkOutputText,\n tempFile);\n }\n \npublic:\n \n void terminate() { terminationRequested_ = true; }\n bool terminationRequested() const { return terminationRequested_; }\n const std::string& chunkId() const { return chunkId_; }\n \nprivate:\n bool terminationRequested_;\n std::string docId_;\n std::string chunkId_;\n std::string nbCtxId_;\n ShellCommand command_;\n core::FilePath scriptPath_;\n \nprivate:\n \n typedef std::map<\n std::string,\n boost::shared_ptr\n > ProcessRegistry;\n \n static ProcessRegistry& registry()\n {\n static ProcessRegistry instance;\n return instance;\n }\n \n void registerProcess()\n {\n registry()[docId_ + \"-\" + chunkId_] = shared_from_this();\n }\n \n void deregisterProcess()\n {\n registry().erase(docId_ + \"-\" + chunkId_);\n }\n \npublic:\n static boost::shared_ptr getProcess(\n const std::string& docId,\n const std::string& chunkId)\n {\n return registry()[docId + \"-\" + chunkId];\n }\n};\n\ncore::Error runChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& engine,\n const std::string& code,\n const std::map& chunkOptions)\n{\n using namespace core;\n typedef core::shell_utils::ShellCommand ShellCommand;\n \n \/\/ write code to temporary file\n FilePath scriptPath = module_context::tempFile(\"chunk-code-\", \"txt\");\n Error error = core::writeStringToFile(scriptPath, code);\n if (error)\n {\n LOG_ERROR(error);\n return error;\n }\n\n \/\/ get command\n ShellCommand command = notebook::shellCommandForEngine(engine, chunkOptions);\n\n \/\/ augment with script path\n std::string shellScriptPath = scriptPathForShellCommand(\n scriptPath,\n engine,\n chunkOptions);\n\n command << shellScriptPath;\n\n \/\/ create process\n boost::shared_ptr operation =\n ExecuteChunkOperation::create(docId, chunkId, nbCtxId, command, \n scriptPath);\n\n \/\/ write input code to cache\n FilePath cacheFilePath = notebook::chunkOutputFile(\n docId,\n chunkId,\n nbCtxId,\n ChunkOutputText);\n \n error = notebook::appendConsoleOutput(\n kChunkConsoleInput,\n code,\n cacheFilePath);\n \n if (error)\n LOG_ERROR(error);\n \n \/\/ generate process options\n core::system::ProcessOptions options;\n options.terminateChildren = true;\n \n core::system::Options env;\n core::system::environment(&env);\n \n \/\/ if we're using python in a virtual environment, then\n \/\/ set the VIRTUAL_ENV + PATH environment variables appropriately\n if (engine == \"python\")\n {\n \/\/ determine engine path -- respect chunk option 'engine.path' if supplied\n FilePath enginePath;\n if (chunkOptions.count(\"engine.path\"))\n {\n enginePath = module_context::resolveAliasedPath(chunkOptions.at(\"engine.path\"));\n }\n else\n {\n core::system::realPath(engine, &enginePath);\n }\n \n \/\/ if we discovered the engine path, then look for an 'activate' script\n \/\/ in the same directory -- if it exists, this is a virtual env\n if (enginePath.exists())\n {\n FilePath activatePath = enginePath.parent().childPath(\"activate\");\n if (activatePath.exists())\n {\n FilePath binPath = enginePath.parent();\n FilePath venvPath = binPath.parent();\n core::system::setenv(&env, \"VIRTUAL_ENV\", venvPath.absolutePath());\n core::system::addToPath(&env, binPath.absolutePath(), true);\n }\n }\n }\n \n options.environment = env;\n \n \/\/ run it\n error = module_context::processSupervisor().runCommand(\n command,\n options,\n operation->processCallbacks());\n \n if (error)\n LOG_ERROR(error);\n \n return Success();\n}\n\nvoid interruptChunk(const std::string& docId,\n const std::string& chunkId)\n{\n boost::shared_ptr pOperation =\n ExecuteChunkOperation::getProcess(docId, chunkId);\n \n if (pOperation)\n pOperation->terminate();\n}\n\n} \/\/ end namespace notebook\n} \/\/ end namespace rmarkdown\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n\n#endif \/* SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP *\/\ndon't set terminateChildren on win32 for chunks\/*\n * SessionExecuteChunkOperation.hpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n#ifndef SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP\n#define SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"NotebookOutput.hpp\"\n#include \"NotebookExec.hpp\"\n#include \"SessionRmdNotebook.hpp\"\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\n\nnamespace {\n\ncore::shell_utils::ShellCommand shellCommandForEngine(\n const std::string& engine,\n const std::map& options)\n{\n using namespace core;\n using namespace core::string_utils;\n using namespace core::shell_utils;\n \n \/\/ determine engine path -- respect chunk option 'engine.path' if supplied\n std::string enginePath = engine;\n if (options.count(\"engine.path\"))\n {\n std::string path = options.at(\"engine.path\");\n enginePath = module_context::resolveAliasedPath(path).absolutePath();\n }\n \n ShellCommand command(enginePath);\n \n \/\/ pass along 'engine.opts' if supplied\n if (options.count(\"engine.opts\"))\n command << EscapeFilesOnly << options.at(\"engine.opts\") << EscapeAll;\n \n return command;\n}\n\nstd::string scriptPathForShellCommand(\n const core::FilePath& scriptPath,\n const std::string& engine,\n const std::map& chunkOptions)\n{\n using namespace core;\n\n auto defaultPath = [&]() {\n return string_utils::utf8ToSystem(scriptPath.absolutePathNative());\n };\n\n#ifndef _WIN32\n return defaultPath();\n#else\n if (engine == \"bash\")\n {\n std::string bashPath = \"bash.exe\";\n if (chunkOptions.count(\"engine.path\"))\n {\n FilePath resolvedPath =\n module_context::resolveAliasedPath(chunkOptions.at(\"engine.path\"));\n bashPath = resolvedPath.absolutePathNative();\n }\n\n system::ProcessOptions options;\n options.workingDir = scriptPath.parent();\n\n system::ProcessResult result;\n Error error = system::runCommand(\n bashPath + \" --norc --noprofile -c pwd\",\n options,\n &result);\n if (error)\n {\n LOG_ERROR(error);\n return defaultPath();\n }\n\n std::string path =\n string_utils::trimWhitespace(result.stdOut) +\n \"\/\" +\n scriptPath.filename();\n return string_utils::utf8ToSystem(path);\n }\n else\n {\n return defaultPath();\n }\n#endif\n}\n\n} \/\/ end anonymous namespace\n\nclass ExecuteChunkOperation : boost::noncopyable,\n public boost::enable_shared_from_this\n{\n typedef core::shell_utils::ShellCommand ShellCommand;\n typedef core::system::ProcessCallbacks ProcessCallbacks;\n typedef core::system::ProcessOperations ProcessOperations;\n \npublic:\n static boost::shared_ptr create(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const ShellCommand& command,\n const core::FilePath& scriptPath)\n {\n boost::shared_ptr pProcess =\n boost::shared_ptr(new ExecuteChunkOperation(\n docId,\n chunkId,\n nbCtxId,\n command,\n scriptPath));\n pProcess->registerProcess();\n return pProcess;\n }\n \nprivate:\n \n ExecuteChunkOperation(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const ShellCommand& command,\n const core::FilePath& scriptPath)\n : terminationRequested_(false),\n docId_(docId),\n chunkId_(chunkId),\n nbCtxId_(nbCtxId),\n command_(command),\n scriptPath_(scriptPath)\n {\n using namespace core;\n Error error = Success();\n \n \/\/ ensure regular directory\n FilePath outputPath = chunkOutputPath(\n docId_,\n chunkId_,\n ContextExact);\n \n error = outputPath.removeIfExists();\n if (error)\n LOG_ERROR(error);\n \n error = outputPath.ensureDirectory();\n if (error)\n LOG_ERROR(error);\n \n \/\/ clean old chunk output\n error = cleanChunkOutput(docId_, chunkId_, nbCtxId_, true);\n if (error)\n LOG_ERROR(error);\n }\n \npublic:\n \n ProcessCallbacks processCallbacks()\n {\n ProcessCallbacks callbacks;\n \n callbacks.onStarted = boost::bind(\n &ExecuteChunkOperation::onStarted,\n shared_from_this());\n \n callbacks.onContinue = boost::bind(\n &ExecuteChunkOperation::onContinue,\n shared_from_this());\n \n callbacks.onStdout = boost::bind(\n &ExecuteChunkOperation::onStdout,\n shared_from_this(),\n _2);\n \n callbacks.onStderr = boost::bind(\n &ExecuteChunkOperation::onStderr,\n shared_from_this(),\n _2);\n \n callbacks.onExit = boost::bind(\n &ExecuteChunkOperation::onExit,\n shared_from_this(),\n _1);\n \n return callbacks;\n }\n \nprivate:\n \n enum OutputType { OUTPUT_STDOUT, OUTPUT_STDERR };\n \n void onStarted()\n {\n }\n \n bool onContinue()\n {\n return !terminationRequested_;\n }\n \n void onExit(int exitStatus)\n {\n events().onChunkExecCompleted(docId_, chunkId_, notebookCtxId());\n deregisterProcess();\n scriptPath_.removeIfExists();\n }\n \n void onStdout(const std::string& output)\n {\n onText(output, OUTPUT_STDOUT);\n }\n \n void onStderr(const std::string& output)\n {\n onText(output, OUTPUT_STDERR);\n }\n \n void onText(const std::string& output, OutputType outputType)\n {\n using namespace core;\n \n \/\/ get path to cache file\n FilePath target = chunkOutputFile(docId_, chunkId_, nbCtxId_,\n ChunkOutputText);\n \n \/\/ append console data (for notebook cache)\n notebook::appendConsoleOutput(\n outputType == OUTPUT_STDOUT ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n target);\n \n \/\/ write to temporary file (for streaming output)\n FilePath tempFile = module_context::tempFile(\"chunk-output-\", \"txt\");\n RemoveOnExitScope scope(tempFile, ERROR_LOCATION);\n notebook::appendConsoleOutput(\n outputType == OUTPUT_STDOUT ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n tempFile);\n \n \/\/ emit client event\n enqueueChunkOutput(\n docId_,\n chunkId_,\n nbCtxId_,\n 0, \/\/ no ordinals needed for alternate engines\n ChunkOutputText,\n tempFile);\n }\n \npublic:\n \n void terminate() { terminationRequested_ = true; }\n bool terminationRequested() const { return terminationRequested_; }\n const std::string& chunkId() const { return chunkId_; }\n \nprivate:\n bool terminationRequested_;\n std::string docId_;\n std::string chunkId_;\n std::string nbCtxId_;\n ShellCommand command_;\n core::FilePath scriptPath_;\n \nprivate:\n \n typedef std::map<\n std::string,\n boost::shared_ptr\n > ProcessRegistry;\n \n static ProcessRegistry& registry()\n {\n static ProcessRegistry instance;\n return instance;\n }\n \n void registerProcess()\n {\n registry()[docId_ + \"-\" + chunkId_] = shared_from_this();\n }\n \n void deregisterProcess()\n {\n registry().erase(docId_ + \"-\" + chunkId_);\n }\n \npublic:\n static boost::shared_ptr getProcess(\n const std::string& docId,\n const std::string& chunkId)\n {\n return registry()[docId + \"-\" + chunkId];\n }\n};\n\ncore::Error runChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& engine,\n const std::string& code,\n const std::map& chunkOptions)\n{\n using namespace core;\n typedef core::shell_utils::ShellCommand ShellCommand;\n \n \/\/ write code to temporary file\n FilePath scriptPath = module_context::tempFile(\"chunk-code-\", \"txt\");\n Error error = core::writeStringToFile(scriptPath, code);\n if (error)\n {\n LOG_ERROR(error);\n return error;\n }\n\n \/\/ get command\n ShellCommand command = notebook::shellCommandForEngine(engine, chunkOptions);\n\n \/\/ augment with script path\n std::string shellScriptPath = scriptPathForShellCommand(\n scriptPath,\n engine,\n chunkOptions);\n\n command << shellScriptPath;\n\n \/\/ create process\n boost::shared_ptr operation =\n ExecuteChunkOperation::create(docId, chunkId, nbCtxId, command, \n scriptPath);\n\n \/\/ write input code to cache\n FilePath cacheFilePath = notebook::chunkOutputFile(\n docId,\n chunkId,\n nbCtxId,\n ChunkOutputText);\n \n error = notebook::appendConsoleOutput(\n kChunkConsoleInput,\n code,\n cacheFilePath);\n \n if (error)\n LOG_ERROR(error);\n \n \/\/ generate process options\n core::system::ProcessOptions options;\n\n \/\/ don't set terminateChildren on win32 as that flag\n \/\/ will force the process to generate a new console window\n#ifndef _WIN32\n options.terminateChildren = true;\n#endif\n\n core::system::Options env;\n core::system::environment(&env);\n \n \/\/ if we're using python in a virtual environment, then\n \/\/ set the VIRTUAL_ENV + PATH environment variables appropriately\n if (engine == \"python\")\n {\n \/\/ determine engine path -- respect chunk option 'engine.path' if supplied\n FilePath enginePath;\n if (chunkOptions.count(\"engine.path\"))\n {\n enginePath = module_context::resolveAliasedPath(chunkOptions.at(\"engine.path\"));\n }\n else\n {\n core::system::realPath(engine, &enginePath);\n }\n \n \/\/ if we discovered the engine path, then look for an 'activate' script\n \/\/ in the same directory -- if it exists, this is a virtual env\n if (enginePath.exists())\n {\n FilePath activatePath = enginePath.parent().childPath(\"activate\");\n if (activatePath.exists())\n {\n FilePath binPath = enginePath.parent();\n FilePath venvPath = binPath.parent();\n core::system::setenv(&env, \"VIRTUAL_ENV\", venvPath.absolutePath());\n core::system::addToPath(&env, binPath.absolutePath(), true);\n }\n }\n }\n \n options.environment = env;\n \n \/\/ run it\n error = module_context::processSupervisor().runCommand(\n command,\n options,\n operation->processCallbacks());\n \n if (error)\n LOG_ERROR(error);\n \n return Success();\n}\n\nvoid interruptChunk(const std::string& docId,\n const std::string& chunkId)\n{\n boost::shared_ptr pOperation =\n ExecuteChunkOperation::getProcess(docId, chunkId);\n \n if (pOperation)\n pOperation->terminate();\n}\n\n} \/\/ end namespace notebook\n} \/\/ end namespace rmarkdown\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n\n#endif \/* SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP *\/\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/dimm\/rcd_load_ddr4.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file rcd_load_ddr4.C\n\/\/\/ @brief Run and manage the DDR4 rcd loading\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_MCS;\nusing fapi2::TARGET_TYPE_DIMM;\n\nusing fapi2::FAPI2_RC_SUCCESS;\n\nnamespace mss\n{\n\n\/\/\/\n\/\/\/ @brief Perform the rcd_load_ddr4 operations - TARGET_TYPE_DIMM specialization\n\/\/\/ @param[in] i_target, a fapi2::Target\n\/\/\/ @param[in,out] a vector of CCS instructions we should add to\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\nfapi2::ReturnCode rcd_load_ddr4( const fapi2::Target& i_target,\n std::vector< ccs::instruction_t >& io_inst)\n{\n FAPI_INF(\"rcd_load_ddr4 %s\", mss::c_str(i_target));\n\n \/\/ Per DDR4RCD02, tSTAB is us. We want this in cycles for the CCS.\n const uint64_t tSTAB = mss::us_to_cycles(i_target, mss::tstab());\n constexpr uint8_t FS0 = 0; \/\/ Function space 0\n\n \/\/ RCD 4-bit data - integral represents rc#\n static const std::vector< cw_data > l_rcd_4bit_data =\n {\n { FS0, 0, eff_dimm_ddr4_rc00, mss::tmrd() },\n { FS0, 1, eff_dimm_ddr4_rc01, mss::tmrd() },\n { FS0, 2, eff_dimm_ddr4_rc02, tSTAB },\n { FS0, 3, eff_dimm_ddr4_rc03, mss::tmrd_l() },\n { FS0, 4, eff_dimm_ddr4_rc04, mss::tmrd_l() },\n { FS0, 5, eff_dimm_ddr4_rc05, mss::tmrd_l() },\n \/\/ Note: the tMRC1 timing as it is larger for saftey's sake\n \/\/ The concern is that if geardown mode is ever required in the future, we would need the longer timing\n { FS0, 6, eff_dimm_ddr4_rc06_07, mss::tmrc1() },\n { FS0, 8, eff_dimm_ddr4_rc08, mss::tmrd() },\n { FS0, 9, eff_dimm_ddr4_rc09, mss::tmrd() },\n { FS0, 10, eff_dimm_ddr4_rc0a, tSTAB },\n { FS0, 11, eff_dimm_ddr4_rc0b, mss::tmrd_l() },\n { FS0, 12, eff_dimm_ddr4_rc0c, mss::tmrd() },\n { FS0, 13, eff_dimm_ddr4_rc0d, mss::tmrd_l2() },\n { FS0, 14, eff_dimm_ddr4_rc0e, mss::tmrd() },\n { FS0, 15, eff_dimm_ddr4_rc0f, mss::tmrd_l2() },\n };\n\n \/\/ RCD 8-bit data - integral represents rc#\n static const std::vector< cw_data > l_rcd_8bit_data =\n {\n { FS0, 1, eff_dimm_ddr4_rc_1x, mss::tmrd() },\n { FS0, 2, eff_dimm_ddr4_rc_2x, mss::tmrd() },\n { FS0, 3, eff_dimm_ddr4_rc_3x, tSTAB },\n { FS0, 4, eff_dimm_ddr4_rc_4x, mss::tmrd() },\n { FS0, 5, eff_dimm_ddr4_rc_5x, mss::tmrd() },\n { FS0, 6, eff_dimm_ddr4_rc_6x, mss::tmrd() },\n { FS0, 7, eff_dimm_ddr4_rc_7x, mss::tmrd_l() },\n { FS0, 8, eff_dimm_ddr4_rc_8x, mss::tmrd() },\n { FS0, 9, eff_dimm_ddr4_rc_9x, mss::tmrd() },\n { FS0, 10, eff_dimm_ddr4_rc_ax, mss::tmrd() },\n { FS0, 11, eff_dimm_ddr4_rc_bx, mss::tmrd_l() },\n };\n\n \/\/ Load 4-bit data\n FAPI_TRY( control_word_engine(i_target, l_rcd_4bit_data, io_inst), \"%s failed to load 4-bit control words\",\n mss::c_str(i_target));\n\n \/\/ Load 8-bit data\n FAPI_TRY( control_word_engine(i_target, l_rcd_8bit_data, io_inst), \"%s failed to load 8-bit control words\",\n mss::c_str(i_target));\n\n \/\/ DD2 hardware has an issue with properly resetting the DRAM\n \/\/ The below workaround toggles RC06 again to ensure the DRAM is reset properly\n FAPI_TRY( mss::workarounds::rcw_reset_dram(i_target, io_inst), \"%s failed to add reset workaround functionality\",\n mss::c_str(i_target));\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ namespace\nL3 draminit and mss_lib\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/dimm\/rcd_load_ddr4.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file rcd_load_ddr4.C\n\/\/\/ @brief Run and manage the DDR4 rcd loading\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_MCS;\nusing fapi2::TARGET_TYPE_DIMM;\n\nusing fapi2::FAPI2_RC_SUCCESS;\n\nnamespace mss\n{\n\n\/\/\/\n\/\/\/ @brief Perform the rcd_load_ddr4 operations - TARGET_TYPE_DIMM specialization\n\/\/\/ @param[in] i_target, a fapi2::Target\n\/\/\/ @param[in,out] io_inst a vector of CCS instructions we should add to\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\nfapi2::ReturnCode rcd_load_ddr4( const fapi2::Target& i_target,\n std::vector< ccs::instruction_t >& io_inst)\n{\n FAPI_INF(\"rcd_load_ddr4 %s\", mss::c_str(i_target));\n\n \/\/ Per DDR4RCD02, tSTAB is us. We want this in cycles for the CCS.\n const uint64_t tSTAB = mss::us_to_cycles(i_target, mss::tstab());\n constexpr uint8_t FS0 = 0; \/\/ Function space 0\n\n \/\/ RCD 4-bit data - integral represents rc#\n static const std::vector< cw_data > l_rcd_4bit_data =\n {\n { FS0, 0, eff_dimm_ddr4_rc00, mss::tmrd() },\n { FS0, 1, eff_dimm_ddr4_rc01, mss::tmrd() },\n { FS0, 2, eff_dimm_ddr4_rc02, tSTAB },\n { FS0, 3, eff_dimm_ddr4_rc03, mss::tmrd_l() },\n { FS0, 4, eff_dimm_ddr4_rc04, mss::tmrd_l() },\n { FS0, 5, eff_dimm_ddr4_rc05, mss::tmrd_l() },\n \/\/ Note: the tMRC1 timing as it is larger for saftey's sake\n \/\/ The concern is that if geardown mode is ever required in the future, we would need the longer timing\n { FS0, 6, eff_dimm_ddr4_rc06_07, mss::tmrc1() },\n { FS0, 8, eff_dimm_ddr4_rc08, mss::tmrd() },\n { FS0, 9, eff_dimm_ddr4_rc09, mss::tmrd() },\n { FS0, 10, eff_dimm_ddr4_rc0a, tSTAB },\n { FS0, 11, eff_dimm_ddr4_rc0b, mss::tmrd_l() },\n { FS0, 12, eff_dimm_ddr4_rc0c, mss::tmrd() },\n { FS0, 13, eff_dimm_ddr4_rc0d, mss::tmrd_l2() },\n { FS0, 14, eff_dimm_ddr4_rc0e, mss::tmrd() },\n { FS0, 15, eff_dimm_ddr4_rc0f, mss::tmrd_l2() },\n };\n\n \/\/ RCD 8-bit data - integral represents rc#\n static const std::vector< cw_data > l_rcd_8bit_data =\n {\n { FS0, 1, eff_dimm_ddr4_rc_1x, mss::tmrd() },\n { FS0, 2, eff_dimm_ddr4_rc_2x, mss::tmrd() },\n { FS0, 3, eff_dimm_ddr4_rc_3x, tSTAB },\n { FS0, 4, eff_dimm_ddr4_rc_4x, mss::tmrd() },\n { FS0, 5, eff_dimm_ddr4_rc_5x, mss::tmrd() },\n { FS0, 6, eff_dimm_ddr4_rc_6x, mss::tmrd() },\n { FS0, 7, eff_dimm_ddr4_rc_7x, mss::tmrd_l() },\n { FS0, 8, eff_dimm_ddr4_rc_8x, mss::tmrd() },\n { FS0, 9, eff_dimm_ddr4_rc_9x, mss::tmrd() },\n { FS0, 10, eff_dimm_ddr4_rc_ax, mss::tmrd() },\n { FS0, 11, eff_dimm_ddr4_rc_bx, mss::tmrd_l() },\n };\n\n \/\/ Load 4-bit data\n FAPI_TRY( control_word_engine(i_target, l_rcd_4bit_data, io_inst), \"%s failed to load 4-bit control words\",\n mss::c_str(i_target));\n\n \/\/ Load 8-bit data\n FAPI_TRY( control_word_engine(i_target, l_rcd_8bit_data, io_inst), \"%s failed to load 8-bit control words\",\n mss::c_str(i_target));\n\n \/\/ DD2 hardware has an issue with properly resetting the DRAM\n \/\/ The below workaround toggles RC06 again to ensure the DRAM is reset properly\n FAPI_TRY( mss::workarounds::rcw_reset_dram(i_target, io_inst), \"%s failed to add reset workaround functionality\",\n mss::c_str(i_target));\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n * 2013 Oleksandr Novychenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"mongodb_datasource.hpp\"\n#include \"mongodb_featureset.hpp\"\n#include \"connection_manager.hpp\"\n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n\n\/\/ stl\n#include \n#include \n#include \n#include \n#include \n\nDATASOURCE_PLUGIN(mongodb_datasource)\n\nusing boost::shared_ptr;\nusing mapnik::attribute_descriptor;\n\nmongodb_datasource::mongodb_datasource(parameters const& params)\n : datasource(params),\n desc_(*params.get(\"type\"), \"utf-8\"),\n type_(datasource::Vector),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"collection\"),\n params.get(\"user\"),\n params.get(\"password\")),\n persist_connection_(*params.get(\"persist_connection\", true)),\n extent_initialized_(false) {\n boost::optional ext = params.get(\"extent\");\n if (ext && !ext->empty())\n extent_initialized_ = extent_.from_string(*ext);\n\n boost::optional initial_size = params.get(\"initial_size\", 1);\n boost::optional max_size = params.get(\"max_size\", 10);\n\n ConnectionManager::instance().registerPool(creator_, *initial_size, *max_size);\n}\n\nmongodb_datasource::~mongodb_datasource() {\n if (!persist_connection_) {\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n if (conn)\n conn->close();\n }\n }\n}\n\nconst char *mongodb_datasource::name() {\n return \"mongodb\";\n}\n\nmapnik::datasource::datasource_t mongodb_datasource::type() const {\n return type_;\n}\n\nlayer_descriptor mongodb_datasource::get_descriptor() const {\n return desc_;\n}\n\nstd::string mongodb_datasource::json_bbox(const box2d &env) const {\n std::ostringstream lookup;\n\n lookup << \"{ loc: { \\\"$geoWithin\\\": { \\\"$box\\\": [ [ \"\n << std::setprecision(16)\n << env.minx() << \", \" << env.miny() << \" ], [ \"\n << env.maxx() << \", \" << env.maxy() << \" ] ] } } }\";\n\n return lookup.str();\n}\n\nfeatureset_ptr mongodb_datasource::features(const query &q) const {\n const box2d &box = q.get_bbox();\n\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return featureset_ptr();\n\n if (conn && conn->isOK()) {\n mapnik::context_ptr ctx = boost::make_shared();\n\n boost::shared_ptr rs(conn->query(json_bbox(box)));\n return boost::make_shared(rs, ctx, desc_.get_encoding());\n }\n }\n\n return featureset_ptr();\n}\n\nfeatureset_ptr mongodb_datasource::features_at_point(const coord2d &pt, double tol) const {\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return featureset_ptr();\n\n if (conn->isOK()) {\n mapnik::context_ptr ctx = boost::make_shared();\n\n box2d box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol);\n boost::shared_ptr rs(conn->query(json_bbox(box)));\n return boost::make_shared(rs, ctx, desc_.get_encoding());\n }\n }\n\n return featureset_ptr();\n}\n\nbox2d mongodb_datasource::envelope() const {\n if (extent_initialized_)\n return extent_;\n else {\n \/\/ a dumb way :-\/\n extent_.init(-180.0, -90.0, 180.0, 90.0);\n extent_initialized_ = true;\n }\n\n \/\/ shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n \/\/ if (pool) {\n \/\/ shared_ptr conn = pool->borrowObject();\n\n \/\/ if (!conn)\n \/\/ return extent_;\n\n \/\/ if (conn->isOK()) {\n \/\/ \/\/ query\n \/\/ }\n \/\/ }\n\n return extent_;\n}\n\nboost::optional mongodb_datasource::get_geometry_type() const {\n boost::optional result;\n\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return result;\n\n if (conn->isOK()) {\n result.reset(mapnik::datasource::Collection);\n return result;\n }\n }\n\n return result;\n}\nimplemented geometry-type determination\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n * 2013 Oleksandr Novychenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"mongodb_datasource.hpp\"\n#include \"mongodb_featureset.hpp\"\n#include \"connection_manager.hpp\"\n\n\/\/ mapnik\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n\n\/\/ stl\n#include \n#include \n#include \n#include \n#include \n\nDATASOURCE_PLUGIN(mongodb_datasource)\n\nusing boost::shared_ptr;\nusing mapnik::attribute_descriptor;\n\nmongodb_datasource::mongodb_datasource(parameters const& params)\n : datasource(params),\n desc_(*params.get(\"type\"), \"utf-8\"),\n type_(datasource::Vector),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"collection\"),\n params.get(\"user\"),\n params.get(\"password\")),\n persist_connection_(*params.get(\"persist_connection\", true)),\n extent_initialized_(false) {\n boost::optional ext = params.get(\"extent\");\n if (ext && !ext->empty())\n extent_initialized_ = extent_.from_string(*ext);\n\n boost::optional initial_size = params.get(\"initial_size\", 1);\n boost::optional max_size = params.get(\"max_size\", 10);\n\n ConnectionManager::instance().registerPool(creator_, *initial_size, *max_size);\n}\n\nmongodb_datasource::~mongodb_datasource() {\n if (!persist_connection_) {\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n if (conn)\n conn->close();\n }\n }\n}\n\nconst char *mongodb_datasource::name() {\n return \"mongodb\";\n}\n\nmapnik::datasource::datasource_t mongodb_datasource::type() const {\n return type_;\n}\n\nlayer_descriptor mongodb_datasource::get_descriptor() const {\n return desc_;\n}\n\nstd::string mongodb_datasource::json_bbox(const box2d &env) const {\n std::ostringstream lookup;\n\n lookup << \"{ loc: { \\\"$geoWithin\\\": { \\\"$box\\\": [ [ \"\n << std::setprecision(16)\n << env.minx() << \", \" << env.miny() << \" ], [ \"\n << env.maxx() << \", \" << env.maxy() << \" ] ] } } }\";\n\n return lookup.str();\n}\n\nfeatureset_ptr mongodb_datasource::features(const query &q) const {\n const box2d &box = q.get_bbox();\n\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return featureset_ptr();\n\n if (conn && conn->isOK()) {\n mapnik::context_ptr ctx = boost::make_shared();\n\n boost::shared_ptr rs(conn->query(json_bbox(box)));\n return boost::make_shared(rs, ctx, desc_.get_encoding());\n }\n }\n\n return featureset_ptr();\n}\n\nfeatureset_ptr mongodb_datasource::features_at_point(const coord2d &pt, double tol) const {\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return featureset_ptr();\n\n if (conn->isOK()) {\n mapnik::context_ptr ctx = boost::make_shared();\n\n box2d box(pt.x - tol, pt.y - tol, pt.x + tol, pt.y + tol);\n boost::shared_ptr rs(conn->query(json_bbox(box)));\n return boost::make_shared(rs, ctx, desc_.get_encoding());\n }\n }\n\n return featureset_ptr();\n}\n\nbox2d mongodb_datasource::envelope() const {\n if (extent_initialized_)\n return extent_;\n else {\n \/\/ a dumb way :-\/\n extent_.init(-180.0, -90.0, 180.0, 90.0);\n extent_initialized_ = true;\n }\n\n \/\/ shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n \/\/ if (pool) {\n \/\/ shared_ptr conn = pool->borrowObject();\n\n \/\/ if (!conn)\n \/\/ return extent_;\n\n \/\/ if (conn->isOK()) {\n \/\/ \/\/ query\n \/\/ }\n \/\/ }\n\n return extent_;\n}\n\nboost::optional mongodb_datasource::get_geometry_type() const {\n boost::optional result;\n\n shared_ptr< Pool > pool = ConnectionManager::instance().getPool(creator_.id());\n if (pool) {\n shared_ptr conn = pool->borrowObject();\n\n if (!conn)\n return result;\n\n if (conn->isOK()) {\n boost::shared_ptr rs(conn->query(\"{ loc: { \\\"$exists\\\": true } }\", 1));\n try {\n if (rs->more()) {\n mongo::BSONObj bson = rs->next();\n std::string type = bson[\"loc\"][\"type\"].String();\n\n if (type == \"Point\")\n result.reset(mapnik::datasource::Point);\n else if (type == \"LineString\")\n result.reset(mapnik::datasource::LineString);\n else if (type == \"Polygon\")\n result.reset(mapnik::datasource::Polygon);\n }\n } catch(mongo::DBException &de) {\n std::string err_msg = \"Mongodb Plugin: \";\n err_msg += de.toString();\n err_msg += \"\\n\";\n throw mapnik::datasource_exception(err_msg);\n }\n }\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"RConfigure.h\" \/\/ R__USE_IMT\n#include \"ROOT\/RDataSource.hxx\"\n#include \"ROOT\/RDF\/RCustomColumnBase.hxx\"\n#include \"ROOT\/RDF\/RLoopManager.hxx\"\n#include \"RtypesCore.h\"\n#include \"TBranch.h\"\n#include \"TBranchElement.h\"\n#include \"TClass.h\"\n#include \"TClassEdit.h\"\n#include \"TClassRef.h\"\n#include \"TInterpreter.h\"\n#include \"TLeaf.h\"\n#include \"TROOT.h\" \/\/ IsImplicitMTEnabled, GetThreadPoolSize\n#include \"TTree.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace ROOT::Detail::RDF;\nusing namespace ROOT::RDF;\n\nnamespace ROOT {\nnamespace Internal {\nnamespace RDF {\n\n\/\/\/ Return the type_info associated to a name. If the association fails, an\n\/\/\/ exception is thrown.\n\/\/\/ References and pointers are not supported since those cannot be stored in\n\/\/\/ columns.\nconst std::type_info &TypeName2TypeID(const std::string &name)\n{\n if (auto c = TClass::GetClass(name.c_str())) {\n return *c->GetTypeInfo();\n } else if (name == \"char\" || name == \"Char_t\")\n return typeid(char);\n else if (name == \"unsigned char\" || name == \"UChar_t\")\n return typeid(unsigned char);\n else if (name == \"int\" || name == \"Int_t\")\n return typeid(int);\n else if (name == \"unsigned int\" || name == \"UInt_t\")\n return typeid(unsigned int);\n else if (name == \"short\" || name == \"Short_t\")\n return typeid(short);\n else if (name == \"unsigned short\" || name == \"UShort_t\")\n return typeid(unsigned short);\n else if (name == \"long\" || name == \"Long_t\")\n return typeid(long);\n else if (name == \"unsigned long\" || name == \"ULong_t\")\n return typeid(unsigned long);\n else if (name == \"double\" || name == \"Double_t\")\n return typeid(double);\n else if (name == \"float\" || name == \"Float_t\")\n return typeid(float);\n else if (name == \"long long\" || name == \"long long int\" || name == \"Long64_t\")\n return typeid(Long64_t);\n else if (name == \"unsigned long long\" || name == \"unsigned long long int\" || name == \"ULong64_t\")\n return typeid(ULong64_t);\n else if (name == \"bool\" || name == \"Bool_t\")\n return typeid(bool);\n else {\n std::string msg(\"Cannot extract type_info of type \");\n msg += name.c_str();\n msg += \".\";\n throw std::runtime_error(msg);\n }\n}\n\n\/\/\/ Returns the name of a type starting from its type_info\n\/\/\/ An empty string is returned in case of failure\n\/\/\/ References and pointers are not supported since those cannot be stored in\n\/\/\/ columns.\nstd::string TypeID2TypeName(const std::type_info &id)\n{\n if (auto c = TClass::GetClass(id)) {\n return c->GetName();\n } else if (id == typeid(char))\n return \"char\";\n else if (id == typeid(unsigned char))\n return \"unsigned char\";\n else if (id == typeid(int))\n return \"int\";\n else if (id == typeid(unsigned int))\n return \"unsigned int\";\n else if (id == typeid(short))\n return \"short\";\n else if (id == typeid(unsigned short))\n return \"unsigned short\";\n else if (id == typeid(long))\n return \"long\";\n else if (id == typeid(unsigned long))\n return \"unsigned long\";\n else if (id == typeid(double))\n return \"double\";\n else if (id == typeid(float))\n return \"float\";\n else if (id == typeid(Long64_t))\n return \"Long64_t\";\n else if (id == typeid(ULong64_t))\n return \"ULong64_t\";\n else if (id == typeid(bool))\n return \"bool\";\n else\n return \"\";\n}\n\nstd::string ComposeRVecTypeName(const std::string &valueType)\n{\n return \"ROOT::VecOps::RVec<\" + valueType + \">\";\n}\n\nstd::string GetLeafTypeName(TLeaf *leaf, const std::string &colName)\n{\n std::string colType = leaf->GetTypeName();\n if (colType.empty())\n throw std::runtime_error(\"Could not deduce type of leaf \" + colName);\n if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() == 1) {\n \/\/ this is a variable-sized array\n colType = ComposeRVecTypeName(colType);\n } else if (leaf->GetLeafCount() == nullptr && leaf->GetLenStatic() > 1) {\n \/\/ this is a fixed-sized array (we do not differentiate between variable- and fixed-sized arrays)\n colType = ComposeRVecTypeName(colType);\n } else if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() > 1) {\n \/\/ we do not know how to deal with this branch\n throw std::runtime_error(\"TTree leaf \" + colName +\n \" has both a leaf count and a static length. This is not supported.\");\n }\n\n return colType;\n}\n\n\/\/\/ Return the typename of object colName stored in t, if any. Return an empty string if colName is not in t.\n\/\/\/ Supported cases:\n\/\/\/ - leaves corresponding to single values, variable- and fixed-length arrays, with following syntax:\n\/\/\/ - \"leafname\", as long as TTree::GetLeaf resolves it\n\/\/\/ - \"b1.b2...leafname\", as long as TTree::GetLeaf(\"b1.b2....\", \"leafname\") resolves it\n\/\/\/ - TBranchElements, as long as TTree::GetBranch resolves their names\nstd::string GetBranchOrLeafTypeName(TTree &t, const std::string &colName)\n{\n \/\/ look for TLeaf either with GetLeaf(colName) or with GetLeaf(branchName, leafName) (splitting on last dot)\n auto leaf = t.GetLeaf(colName.c_str());\n if (!leaf) {\n const auto dotPos = colName.find_last_of('.');\n const auto hasDot = dotPos != std::string::npos;\n if (hasDot) {\n const auto branchName = colName.substr(0, dotPos);\n const auto leafName = colName.substr(dotPos + 1);\n leaf = t.GetLeaf(branchName.c_str(), leafName.c_str());\n }\n }\n if (leaf)\n return GetLeafTypeName(leaf, colName);\n\n \/\/ we could not find a leaf named colName, so we look for a TBranchElement\n auto branch = t.GetBranch(colName.c_str());\n if (branch) {\n static const TClassRef tbranchelement(\"TBranchElement\");\n if (branch->InheritsFrom(tbranchelement)) {\n auto be = static_cast(branch);\n if (auto currentClass = be->GetCurrentClass())\n return currentClass->GetName();\n else {\n \/\/ Here we have a special case for getting right the type of data members\n \/\/ of classes sorted in TClonesArrays: ROOT-9674\n auto mother = be->GetMother();\n if (mother && mother->InheritsFrom(tbranchelement)) {\n auto beMom = static_cast(mother);\n auto beMomClass = beMom->GetClass();\n if (beMomClass && 0 == std::strcmp(\"TClonesArray\", beMomClass->GetName()))\n return be->GetTypeName();\n }\n return be->GetClassName();\n }\n }\n }\n\n \/\/ colName is not a leaf nor a TBranchElement\n return std::string();\n}\n\n\/\/\/ Return a string containing the type of the given branch. Works both with real TTree branches and with temporary\n\/\/\/ column created by Define. Throws if type name deduction fails.\n\/\/\/ Note that for fixed- or variable-sized c-style arrays the returned type name will be RVec.\n\/\/\/ vector2rvec specifies whether typename 'std::vector' should be converted to 'RVec' or returned as is\n\/\/\/ customColID is only used if isCustomColumn is true, and must correspond to the custom column's unique identifier\n\/\/\/ returned by its `GetID()` method.\nstd::string ColumnName2ColumnTypeName(const std::string &colName, TTree *tree, RDataSource *ds,\n RCustomColumnBase *customColumn, bool vector2rvec)\n{\n std::string colType;\n\n if (ds && ds->HasColumn(colName))\n colType = ds->GetTypeName(colName);\n\n if (colType.empty() && tree) {\n colType = GetBranchOrLeafTypeName(*tree, colName);\n if (vector2rvec && TClassEdit::IsSTLCont(colType) == ROOT::ESTLType::kSTLvector) {\n std::vector split;\n int dummy;\n TClassEdit::GetSplit(colType.c_str(), split, dummy);\n auto &valueType = split[1];\n colType = ComposeRVecTypeName(valueType);\n }\n }\n\n if (colType.empty() && customColumn) {\n colType = customColumn->GetTypeName();\n }\n\n if (colType.empty())\n throw std::runtime_error(\"Column \\\"\" + colName +\n \"\\\" is not in a dataset and is not a custom column been defined.\");\n\n return colType;\n}\n\n\/\/\/ Convert type name (e.g. \"Float_t\") to ROOT type code (e.g. 'F') -- see TBranch documentation.\n\/\/\/ Return a space ' ' in case no match was found.\nchar TypeName2ROOTTypeName(const std::string &b)\n{\n if (b == \"Char_t\" || b == \"char\")\n return 'B';\n if (b == \"UChar_t\" || b == \"unsigned char\")\n return 'b';\n if (b == \"Short_t\" || b == \"short\" || b == \"short int\")\n return 'S';\n if (b == \"UShort_t\" || b == \"unsigned short\" || b == \"unsigned short int\")\n return 's';\n if (b == \"Int_t\" || b == \"int\")\n return 'I';\n if (b == \"UInt_t\" || b == \"unsigned\" || b == \"unsigned int\")\n return 'i';\n if (b == \"Float_t\" || b == \"float\")\n return 'F';\n if (b == \"Double_t\" || b == \"double\")\n return 'D';\n if (b == \"Long64_t\" || b == \"long\" || b == \"long int\")\n return 'L';\n if (b == \"ULong64_t\" || b == \"unsigned long\" || b == \"unsigned long int\")\n return 'l';\n if (b == \"Bool_t\" || b == \"bool\")\n return 'O';\n return ' ';\n}\n\nunsigned int GetNSlots()\n{\n unsigned int nSlots = 1;\n#ifdef R__USE_IMT\n if (ROOT::IsImplicitMTEnabled())\n nSlots = ROOT::GetThreadPoolSize();\n#endif \/\/ R__USE_IMT\n return nSlots;\n}\n\n\/\/\/ Replace occurrences of '.' with '_' in each string passed as argument.\n\/\/\/ An Info message is printed when this happens. Dots at the end of the string are not replaced.\n\/\/\/ An exception is thrown in case the resulting set of strings would contain duplicates.\nstd::vector ReplaceDotWithUnderscore(const std::vector &columnNames)\n{\n auto newColNames = columnNames;\n for (auto &col : newColNames) {\n const auto dotPos = col.find('.');\n if (dotPos != std::string::npos && dotPos != col.size() - 1 && dotPos != 0u) {\n auto oldName = col;\n std::replace(col.begin(), col.end(), '.', '_');\n if (std::find(columnNames.begin(), columnNames.end(), col) != columnNames.end())\n throw std::runtime_error(\"Column \" + oldName + \" would be written as \" + col +\n \" but this column already exists. Please use Alias to select a new name for \" +\n oldName);\n Info(\"Snapshot\", \"Column %s will be saved as %s\", oldName.c_str(), col.c_str());\n }\n }\n\n return newColNames;\n}\n\nvoid InterpreterDeclare(const std::string &code)\n{\n if (!gInterpreter->Declare(code.c_str())) {\n const auto msg =\n \"\\nRDataFrame: An error occurred during just-in-time compilation. The lines above might indicate the cause of \"\n \"the crash\\n All RDF objects that have not run an event loop yet should be considered in an invalid state.\\n\";\n throw std::runtime_error(msg);\n }\n}\n\nLong64_t InterpreterCalc(const std::string &code, const std::string &context)\n{\n TInterpreter::EErrorCode errorCode(TInterpreter::kNoError);\n auto res = gInterpreter->Calc(code.c_str(), &errorCode);\n if (errorCode != TInterpreter::EErrorCode::kNoError) {\n std::string msg = \"\\nAn error occurred during just-in-time compilation\";\n if (!context.empty())\n msg += \" in \" + context;\n msg += \". The lines above might indicate the cause of the crash\\nAll RDF objects that have not run their event \"\n \"loop yet should be considered in an invalid state.\\n\";\n throw std::runtime_error(msg);\n }\n return res;\n}\n\n} \/\/ end NS RDF\n} \/\/ end NS Internal\n} \/\/ end NS ROOT\n[DF] Fix type inference of TClonesArrays branches\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"RConfigure.h\" \/\/ R__USE_IMT\n#include \"ROOT\/RDataSource.hxx\"\n#include \"ROOT\/RDF\/RCustomColumnBase.hxx\"\n#include \"ROOT\/RDF\/RLoopManager.hxx\"\n#include \"RtypesCore.h\"\n#include \"TBranch.h\"\n#include \"TBranchElement.h\"\n#include \"TClass.h\"\n#include \"TClassEdit.h\"\n#include \"TClassRef.h\"\n#include \"TInterpreter.h\"\n#include \"TLeaf.h\"\n#include \"TROOT.h\" \/\/ IsImplicitMTEnabled, GetThreadPoolSize\n#include \"TTree.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace ROOT::Detail::RDF;\nusing namespace ROOT::RDF;\n\nnamespace ROOT {\nnamespace Internal {\nnamespace RDF {\n\n\/\/\/ Return the type_info associated to a name. If the association fails, an\n\/\/\/ exception is thrown.\n\/\/\/ References and pointers are not supported since those cannot be stored in\n\/\/\/ columns.\nconst std::type_info &TypeName2TypeID(const std::string &name)\n{\n if (auto c = TClass::GetClass(name.c_str())) {\n return *c->GetTypeInfo();\n } else if (name == \"char\" || name == \"Char_t\")\n return typeid(char);\n else if (name == \"unsigned char\" || name == \"UChar_t\")\n return typeid(unsigned char);\n else if (name == \"int\" || name == \"Int_t\")\n return typeid(int);\n else if (name == \"unsigned int\" || name == \"UInt_t\")\n return typeid(unsigned int);\n else if (name == \"short\" || name == \"Short_t\")\n return typeid(short);\n else if (name == \"unsigned short\" || name == \"UShort_t\")\n return typeid(unsigned short);\n else if (name == \"long\" || name == \"Long_t\")\n return typeid(long);\n else if (name == \"unsigned long\" || name == \"ULong_t\")\n return typeid(unsigned long);\n else if (name == \"double\" || name == \"Double_t\")\n return typeid(double);\n else if (name == \"float\" || name == \"Float_t\")\n return typeid(float);\n else if (name == \"long long\" || name == \"long long int\" || name == \"Long64_t\")\n return typeid(Long64_t);\n else if (name == \"unsigned long long\" || name == \"unsigned long long int\" || name == \"ULong64_t\")\n return typeid(ULong64_t);\n else if (name == \"bool\" || name == \"Bool_t\")\n return typeid(bool);\n else {\n std::string msg(\"Cannot extract type_info of type \");\n msg += name.c_str();\n msg += \".\";\n throw std::runtime_error(msg);\n }\n}\n\n\/\/\/ Returns the name of a type starting from its type_info\n\/\/\/ An empty string is returned in case of failure\n\/\/\/ References and pointers are not supported since those cannot be stored in\n\/\/\/ columns.\nstd::string TypeID2TypeName(const std::type_info &id)\n{\n if (auto c = TClass::GetClass(id)) {\n return c->GetName();\n } else if (id == typeid(char))\n return \"char\";\n else if (id == typeid(unsigned char))\n return \"unsigned char\";\n else if (id == typeid(int))\n return \"int\";\n else if (id == typeid(unsigned int))\n return \"unsigned int\";\n else if (id == typeid(short))\n return \"short\";\n else if (id == typeid(unsigned short))\n return \"unsigned short\";\n else if (id == typeid(long))\n return \"long\";\n else if (id == typeid(unsigned long))\n return \"unsigned long\";\n else if (id == typeid(double))\n return \"double\";\n else if (id == typeid(float))\n return \"float\";\n else if (id == typeid(Long64_t))\n return \"Long64_t\";\n else if (id == typeid(ULong64_t))\n return \"ULong64_t\";\n else if (id == typeid(bool))\n return \"bool\";\n else\n return \"\";\n}\n\nstd::string ComposeRVecTypeName(const std::string &valueType)\n{\n return \"ROOT::VecOps::RVec<\" + valueType + \">\";\n}\n\nstd::string GetLeafTypeName(TLeaf *leaf, const std::string &colName)\n{\n std::string colType = leaf->GetTypeName();\n if (colType.empty())\n throw std::runtime_error(\"Could not deduce type of leaf \" + colName);\n if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() == 1) {\n \/\/ this is a variable-sized array\n colType = ComposeRVecTypeName(colType);\n } else if (leaf->GetLeafCount() == nullptr && leaf->GetLenStatic() > 1) {\n \/\/ this is a fixed-sized array (we do not differentiate between variable- and fixed-sized arrays)\n colType = ComposeRVecTypeName(colType);\n } else if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() > 1) {\n \/\/ we do not know how to deal with this branch\n throw std::runtime_error(\"TTree leaf \" + colName +\n \" has both a leaf count and a static length. This is not supported.\");\n }\n\n return colType;\n}\n\n\/\/\/ Return the typename of object colName stored in t, if any. Return an empty string if colName is not in t.\n\/\/\/ Supported cases:\n\/\/\/ - leaves corresponding to single values, variable- and fixed-length arrays, with following syntax:\n\/\/\/ - \"leafname\", as long as TTree::GetLeaf resolves it\n\/\/\/ - \"b1.b2...leafname\", as long as TTree::GetLeaf(\"b1.b2....\", \"leafname\") resolves it\n\/\/\/ - TBranchElements, as long as TTree::GetBranch resolves their names\nstd::string GetBranchOrLeafTypeName(TTree &t, const std::string &colName)\n{\n \/\/ look for TLeaf either with GetLeaf(colName) or with GetLeaf(branchName, leafName) (splitting on last dot)\n auto leaf = t.GetLeaf(colName.c_str());\n if (!leaf) {\n const auto dotPos = colName.find_last_of('.');\n const auto hasDot = dotPos != std::string::npos;\n if (hasDot) {\n const auto branchName = colName.substr(0, dotPos);\n const auto leafName = colName.substr(dotPos + 1);\n leaf = t.GetLeaf(branchName.c_str(), leafName.c_str());\n }\n }\n if (leaf)\n return GetLeafTypeName(leaf, colName);\n\n \/\/ we could not find a leaf named colName, so we look for a TBranchElement\n auto branch = t.GetBranch(colName.c_str());\n if (branch) {\n static const TClassRef tbranchelement(\"TBranchElement\");\n if (branch->InheritsFrom(tbranchelement)) {\n auto be = static_cast(branch);\n if (auto currentClass = be->GetCurrentClass())\n return currentClass->GetName();\n else {\n \/\/ Here we have a special case for getting right the type of data members\n \/\/ of classes sorted in TClonesArrays: ROOT-9674\n auto mother = be->GetMother();\n if (mother && mother->InheritsFrom(tbranchelement) && mother != be) {\n auto beMom = static_cast(mother);\n auto beMomClass = beMom->GetClass();\n if (beMomClass && 0 == std::strcmp(\"TClonesArray\", beMomClass->GetName()))\n return be->GetTypeName();\n }\n return be->GetClassName();\n }\n }\n }\n\n \/\/ colName is not a leaf nor a TBranchElement\n return std::string();\n}\n\n\/\/\/ Return a string containing the type of the given branch. Works both with real TTree branches and with temporary\n\/\/\/ column created by Define. Throws if type name deduction fails.\n\/\/\/ Note that for fixed- or variable-sized c-style arrays the returned type name will be RVec.\n\/\/\/ vector2rvec specifies whether typename 'std::vector' should be converted to 'RVec' or returned as is\n\/\/\/ customColID is only used if isCustomColumn is true, and must correspond to the custom column's unique identifier\n\/\/\/ returned by its `GetID()` method.\nstd::string ColumnName2ColumnTypeName(const std::string &colName, TTree *tree, RDataSource *ds,\n RCustomColumnBase *customColumn, bool vector2rvec)\n{\n std::string colType;\n\n if (ds && ds->HasColumn(colName))\n colType = ds->GetTypeName(colName);\n\n if (colType.empty() && tree) {\n colType = GetBranchOrLeafTypeName(*tree, colName);\n if (vector2rvec && TClassEdit::IsSTLCont(colType) == ROOT::ESTLType::kSTLvector) {\n std::vector split;\n int dummy;\n TClassEdit::GetSplit(colType.c_str(), split, dummy);\n auto &valueType = split[1];\n colType = ComposeRVecTypeName(valueType);\n }\n }\n\n if (colType.empty() && customColumn) {\n colType = customColumn->GetTypeName();\n }\n\n if (colType.empty())\n throw std::runtime_error(\"Column \\\"\" + colName +\n \"\\\" is not in a dataset and is not a custom column been defined.\");\n\n return colType;\n}\n\n\/\/\/ Convert type name (e.g. \"Float_t\") to ROOT type code (e.g. 'F') -- see TBranch documentation.\n\/\/\/ Return a space ' ' in case no match was found.\nchar TypeName2ROOTTypeName(const std::string &b)\n{\n if (b == \"Char_t\" || b == \"char\")\n return 'B';\n if (b == \"UChar_t\" || b == \"unsigned char\")\n return 'b';\n if (b == \"Short_t\" || b == \"short\" || b == \"short int\")\n return 'S';\n if (b == \"UShort_t\" || b == \"unsigned short\" || b == \"unsigned short int\")\n return 's';\n if (b == \"Int_t\" || b == \"int\")\n return 'I';\n if (b == \"UInt_t\" || b == \"unsigned\" || b == \"unsigned int\")\n return 'i';\n if (b == \"Float_t\" || b == \"float\")\n return 'F';\n if (b == \"Double_t\" || b == \"double\")\n return 'D';\n if (b == \"Long64_t\" || b == \"long\" || b == \"long int\")\n return 'L';\n if (b == \"ULong64_t\" || b == \"unsigned long\" || b == \"unsigned long int\")\n return 'l';\n if (b == \"Bool_t\" || b == \"bool\")\n return 'O';\n return ' ';\n}\n\nunsigned int GetNSlots()\n{\n unsigned int nSlots = 1;\n#ifdef R__USE_IMT\n if (ROOT::IsImplicitMTEnabled())\n nSlots = ROOT::GetThreadPoolSize();\n#endif \/\/ R__USE_IMT\n return nSlots;\n}\n\n\/\/\/ Replace occurrences of '.' with '_' in each string passed as argument.\n\/\/\/ An Info message is printed when this happens. Dots at the end of the string are not replaced.\n\/\/\/ An exception is thrown in case the resulting set of strings would contain duplicates.\nstd::vector ReplaceDotWithUnderscore(const std::vector &columnNames)\n{\n auto newColNames = columnNames;\n for (auto &col : newColNames) {\n const auto dotPos = col.find('.');\n if (dotPos != std::string::npos && dotPos != col.size() - 1 && dotPos != 0u) {\n auto oldName = col;\n std::replace(col.begin(), col.end(), '.', '_');\n if (std::find(columnNames.begin(), columnNames.end(), col) != columnNames.end())\n throw std::runtime_error(\"Column \" + oldName + \" would be written as \" + col +\n \" but this column already exists. Please use Alias to select a new name for \" +\n oldName);\n Info(\"Snapshot\", \"Column %s will be saved as %s\", oldName.c_str(), col.c_str());\n }\n }\n\n return newColNames;\n}\n\nvoid InterpreterDeclare(const std::string &code)\n{\n if (!gInterpreter->Declare(code.c_str())) {\n const auto msg =\n \"\\nRDataFrame: An error occurred during just-in-time compilation. The lines above might indicate the cause of \"\n \"the crash\\n All RDF objects that have not run an event loop yet should be considered in an invalid state.\\n\";\n throw std::runtime_error(msg);\n }\n}\n\nLong64_t InterpreterCalc(const std::string &code, const std::string &context)\n{\n TInterpreter::EErrorCode errorCode(TInterpreter::kNoError);\n auto res = gInterpreter->Calc(code.c_str(), &errorCode);\n if (errorCode != TInterpreter::EErrorCode::kNoError) {\n std::string msg = \"\\nAn error occurred during just-in-time compilation\";\n if (!context.empty())\n msg += \" in \" + context;\n msg += \". The lines above might indicate the cause of the crash\\nAll RDF objects that have not run their event \"\n \"loop yet should be considered in an invalid state.\\n\";\n throw std::runtime_error(msg);\n }\n return res;\n}\n\n} \/\/ end NS RDF\n} \/\/ end NS Internal\n} \/\/ end NS ROOT\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2017 Shivansh Rai\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\/\/\n\/\/ $FreeBSD$\n\n#include \n#include \n#include \n#include \n#include \"read_annotations.h\"\n\nvoid\nannotations::read_annotations(std::string utility,\n std::unordered_set& annot)\n{\n std::string line;\n \/\/ TODO do this for all the annotation files\n std::ifstream annot_fstream;\n annot_fstream.open(\"annotations\/\" + utility + \"_test.annot\");\n\n while (getline(annot_fstream, line)) {\n \/\/ Add a unique identifier for no_arguments testcase\n if (line.compare(2, 4, \"flag\")) {\n annot.insert('*');\n continue;\n }\n annot.insert(line[0]);\n }\n\n annot_fstream.close();\n}\nFix condition for annotating \"no_arguments\" testcase\/\/\n\/\/ Copyright 2017 Shivansh Rai\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\/\/\n\/\/ $FreeBSD$\n\n#include \n#include \n#include \n#include \n#include \"read_annotations.h\"\n\nvoid\nannotations::read_annotations(std::string utility,\n std::unordered_set& annot)\n{\n std::string line;\n \/\/ TODO do this for all the annotation files\n std::ifstream annot_fstream;\n annot_fstream.open(\"annotations\/\" + utility + \"_test.annot\");\n\n while (getline(annot_fstream, line)) {\n \/\/ Add a unique identifier for no_arguments testcase\n if (!line.compare(0, 12, \"no_arguments\"))\n annot.insert('*');\n \/\/ Add flag value for supported argument testcases\n \/\/ Doing so we ignore the \"invalid_usage\" testcase\n \/\/ as it is guaranteed to always succeed.\n else if (!line.compare(2, 4, \"flag\"))\n annot.insert(line[0]);\n }\n\n annot_fstream.close();\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/** @file\n* Tests for the Gauss-Seidel implementation of the MLCP solver.\n*\/\n\n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \n\n#include \n#include \n#include \n#include \"MlcpTestData.h\"\n#include \"ReadText.h\"\n\nusing SurgSim::Math::isValid;\nusing SurgSim::Math::MlcpGaussSeidelSolver;\n\n\nstatic std::shared_ptr loadTestData(const std::string& fileName)\n{\n\tstd::shared_ptr data = std::make_shared();\n\tif (! readMlcpTestDataAsText(\"MlcpTestData\/\" + fileName, data.get()))\n\t{\n\t\tdata.reset();\n\t}\n\treturn data;\n}\n\nstatic inline std::string getTestFileName(const std::string& prefix, int index, const std::string& suffix)\n{\n\tstd::ostringstream stream;\n\tstream << prefix << std::setfill('0') << std::setw(3) << index << suffix;\n\treturn stream.str();\n}\n\n\nTEST(MlcpGaussSeidelSolverTests, CanConstruct)\n{\n\t\/\/ASSERT_NO_THROW({\n\tMlcpGaussSeidelSolver mlcpSolver(1.0, 1.0, 100);\n}\n\n\nstatic void solveAndCompareResult(const std::string& fileName, bool compare = false,\n\t\t\t\t\t\t double gsSolverPrecision = 1e-9, double gsContactTolerance = 1e-9, int gsMaxIterations = 100)\n{\n\tSCOPED_TRACE(\"while running test \" + fileName);\n\tprintf(\"-- TEST %s --\\n\", fileName.c_str());\n\n\tconst std::shared_ptr data = loadTestData(fileName);\n\tASSERT_TRUE(data) << \"Failed to load \" << fileName;\n\n\t\/\/ NB: need to make the solver calls const-correct.\n\tEigen::MatrixXd A = data->problem.A;\n\tEigen::VectorXd b = data->problem.b;\n\tEigen::VectorXd mu = data->problem.mu;\n\tstd::vector constraintTypes = data->problem.constraintTypes;\n\n\tconst int size = data->getSize();\n\tSurgSim::Math::MlcpSolution solution;\n\tsolution.x.resize(size);\n\n\t\/\/################################\n\t\/\/ Gauss-Seidel solver\n\tMlcpGaussSeidelSolver mlcpSolver(gsSolverPrecision, gsContactTolerance,\n\t\t\t\t\t\t\t\t\t gsMaxIterations);\n\n\tprintf(\" ### Gauss Seidel solver:\\n\");\n\tsolution.x.setZero();\n\n\t\/\/ XXX set ratio to 1\n\tbool res = mlcpSolver.solve(data->problem, &solution);\n\n\tprintf(\"\\tsolver did %d iterations convergence=%d Signorini=%d\\n\",\n\t\t solution.numIterations, solution.validConvergence ? 1 : 0, solution.validSignorini ? 1 : 0);\n\n\tASSERT_EQ(size, solution.x.rows());\n\tASSERT_EQ(size, data->expectedLambda.rows());\n\tif (size > 0)\n\t{\n\t\tASSERT_TRUE(isValid(solution.x)) << solution.x;\n\t}\n\n\t\/\/ TODO(advornik): Because this is a mixed LCP problem *with friction*, we can't just easily check that\n\t\/\/ all x are positive (the frictional entries may not be), or that all Ax+b are positive(ditto).\n\t\/\/ We need to either (a) make the test aware of the meaning of the constraint types, or (b) get rid\n\t\/\/ of the constraint types and flag the frictional DOFs more directly.\n\t\/\/\n\t\/\/ For now, we check if the MLCP is really a pure LCP (only unilaterals without friction), and we\n\t\/\/ perform some simple checks that apply to that case and that case only.\n\tbool isSimpleLcp = true;\n\tfor (auto it = constraintTypes.cbegin(); it != constraintTypes.cend(); ++it)\n\t{\n\t\tif ((*it) != SurgSim::Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT)\n\t\t{\n\t\t\tisSimpleLcp = false;\n\t\t}\n\t}\n\n\tif (isSimpleLcp && (size > 0))\n\t{\n\t\tEXPECT_GE(solution.x.minCoeff(), 0.0) << \"x contains negative coefficients:\" << std::endl << solution.x;\n\n\t\tEigen::VectorXd c = A * solution.x + b;\n\t\tEXPECT_GE(c.minCoeff(), -gsSolverPrecision) << \"Ax+b contains negative coefficients:\" << std::endl << c;\n\n\t\t\/\/ Orthogonality test should be taking into account the scaling factor\n\t\tdouble maxAbsForce = abs(solution.x.maxCoeff());\n\t\tif (abs(solution.x.minCoeff()) > maxAbsForce)\n\t\t{\n\t\t\tmaxAbsForce = abs(solution.x.minCoeff());\n\t\t}\n\t\tconst double epsilon = 1e-9 * maxAbsForce;\n\t\tEXPECT_NEAR(0.0, c.dot(solution.x), epsilon) << \"Ax+b is not orthogonal to x!\" << std::endl <<\n\t\t\t\"x:\" << std::endl << solution.x << std::endl << \"Ax+b:\" << std::endl << c;\n\t}\n\n\tif (compare)\n\t{\n\t\tEXPECT_TRUE(solution.x.isApprox(data->expectedLambda)) << \"lambda:\" << std::endl << solution.x << std::endl <<\n\t\t\t\"expected:\" << std::endl << data->expectedLambda;\n\t}\n\n\/\/\tdouble convergenceCriteria=0.0;\n\/\/\tbool validSignorini=false;\n\/\/\tint nbContactToSkip=0;\n\/\/\tint currentAtomicIndex = calculateConvergenceCriteria(lambda, nbContactToSkip, convergenceCriteria,\n\/\/\t\tvalidSignorini, 1.0);\n\/\/\tprintf(\"\\tStatus method final [convergence criteria=%g, Signorini=%d]\\n\",convergenceCriteria,validSignorini?1:0);\n\tprintf(\"############\\n\");\n}\n\nTEST(MlcpGaussSeidelSolverTests, SolveOriginal)\n{\n\tconst double gsSolverPrecision = 1e-4;\n\tconst double gsContactTolerance = 2e-4;\n\tint gsMaxIterations = 30;\n\tsolveAndCompareResult(\"mlcpOriginalTest.txt\", false, gsSolverPrecision, gsContactTolerance, gsMaxIterations);\n}\n\nTEST(MlcpGaussSeidelSolverTests, CompareResultOriginal)\n{\n\tconst double gsSolverPrecision = 1e-4;\n\tconst double gsContactTolerance = 2e-4;\n\tint gsMaxIterations = 30;\n\tsolveAndCompareResult(\"mlcpOriginalTest.txt\", true, gsSolverPrecision, gsContactTolerance, gsMaxIterations);\n}\n\nTEST(MlcpGaussSeidelSolverTests, solveSequence)\n{\n\tfor (int i = 0; i <= 9; ++i)\n\t{\n\t\tsolveAndCompareResult(getTestFileName(\"mlcpTest\", i, \".txt\"), false);\n\t}\n}\n\nTEST(MlcpGaussSeidelSolverTests, CompareResultsSequence)\n{\n\tfor (int i = 0; i <= 9; ++i)\n\t{\n\t\tsolveAndCompareResult(getTestFileName(\"mlcpTest\", i, \".txt\"), true);\n\t}\n}\n\n\nstatic void solveRepeatedly(const MlcpTestData& data,\n\t\t\t\t\t\t\t\/*XXX const *\/ MlcpGaussSeidelSolver* mlcpSolver,\n\t\t\t\t\t\t\tconst int repetitions)\n{\n\t\/\/ NB: need to make the solver calls const-correct.\n\tSurgSim::Math::MlcpProblem problem;\n\tSurgSim::Math::MlcpSolution solution;\n\tstd::vector constraintTypes;\n\n\tconst int size = data.getSize();\n\tsolution.x.resize(size);\n\n\tfor (int i = repetitions; i > 0; --i)\n\t{\n\t\tproblem = data.problem;\n\n\t\tif (mlcpSolver)\n\t\t{\n\t\t\tsolution.x.setZero();\n\t\t\tbool res = mlcpSolver->solve(problem, &solution);\n\t\t}\n\t}\n}\n\nstatic double measureExecutionTimeUsec(const std::string& fileName,\n\t\t\t\t\t\t\t\t\t double gsSolverPrecision = 1e-8, double gsContactTolerance = 1e-8,\n\t\t\t\t\t\t\t\t\t int gsMaxIterations = 20)\n{\n\tSCOPED_TRACE(\"while running test \" + fileName);\n\tprintf(\"-- TEST %s --\\n\", fileName.c_str());\n\n\tconst std::shared_ptr data = loadTestData(fileName);\n\tEXPECT_TRUE(data) << \"Failed to load \" << fileName;\n\n\tMlcpGaussSeidelSolver mlcpSolver(gsSolverPrecision, gsContactTolerance, gsMaxIterations);\n\n\ttypedef boost::chrono::high_resolution_clock clock;\n\tclock::time_point calibrationStart = clock::now();\n\n\tconst int calibrationRepetitions = 1000;\n\tsolveRepeatedly(*data, &mlcpSolver, calibrationRepetitions);\n\n\tboost::chrono::duration calibrationTime = clock::now() - calibrationStart;\n\tdouble desiredTestTimeSec = 1.0;\n\tdouble desiredRepetitions = desiredTestTimeSec * calibrationRepetitions \/ calibrationTime.count();\n\tconst int repetitions = std::max(10, std::min(1000000, static_cast(desiredRepetitions)));\n\n\tclock::time_point time0 = clock::now();\n\n\t\/\/ Do not actually solve the problem; just copy the input data.\n\tsolveRepeatedly(*data, nullptr, repetitions);\n\n\tclock::time_point time1 = clock::now();\n\n\t\/\/ Actually solve the problem.\n\tsolveRepeatedly(*data, &mlcpSolver, repetitions);\n\n\tclock::time_point time2 = clock::now();\n\n\tboost::chrono::duration elapsedSolveTime = time2 - time1;\n\t\/\/std::cout << \"Elapsed: \" << (elapsedSolveTime.count() * 1000.) << \" ms\" << std::endl;\n\tboost::chrono::duration elapsedBaseline = time1 - time0;\n\t\/\/std::cout << \"Baseline: \" << (elapsedBaseline.count() * 1000.) << \" ms\" << std::endl;\n\tdouble solveTimeUsec = (elapsedSolveTime - elapsedBaseline).count() * 1e6 \/ repetitions;\n\tdouble copyTimeUsec = elapsedBaseline.count() * 1e6 \/ repetitions;\n\tstd::cout << \"Average solution time: \" << solveTimeUsec << \" microseconds (over \" <<\n\t\trepetitions << \" loops)\" << std::endl;\n\treturn solveTimeUsec;\n}\n\nTEST(MlcpGaussSeidelSolverTests, MeasureExecutionTimeOriginal)\n{\n\tconst double gsSolverPrecision = 1e-4;\n\tconst double gsContactTolerance = 2e-5;\n\tint gsMaxIterations = 30;\n\tdouble solveTimeUsec = measureExecutionTimeUsec(\"mlcpOriginalTest.txt\", gsSolverPrecision, gsContactTolerance,\n\t\t\t\t\t\t\t\t\t\t\t\t\tgsMaxIterations);\n\n\t\/\/ When refactoring the MLCP code, it can be very useful to compare the execution time before and after making\n\t\/\/ changes. But you can't usefully compare execution times on different machines, or with different build\n\t\/\/ settings, so you'll need to manually uncomment the following line and adjust the time accordingly.\n\/\/\tEXPECT_LE(solveTimeUsec, 14.0);\n}\nGet rid of the split between solve\/compare tests in MLCPGauss-SeidelSolverTests.\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/** @file\n* Tests for the Gauss-Seidel implementation of the MLCP solver.\n*\/\n\n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n#include \n\n#include \n#include \n#include \n#include \"MlcpTestData.h\"\n#include \"ReadText.h\"\n\nusing SurgSim::Math::isValid;\nusing SurgSim::Math::MlcpGaussSeidelSolver;\n\n\nstatic std::shared_ptr loadTestData(const std::string& fileName)\n{\n\tstd::shared_ptr data = std::make_shared();\n\tif (! readMlcpTestDataAsText(\"MlcpTestData\/\" + fileName, data.get()))\n\t{\n\t\tdata.reset();\n\t}\n\treturn data;\n}\n\nstatic inline std::string getTestFileName(const std::string& prefix, int index, const std::string& suffix)\n{\n\tstd::ostringstream stream;\n\tstream << prefix << std::setfill('0') << std::setw(3) << index << suffix;\n\treturn stream.str();\n}\n\n\nTEST(MlcpGaussSeidelSolverTests, CanConstruct)\n{\n\t\/\/ASSERT_NO_THROW({\n\tMlcpGaussSeidelSolver mlcpSolver(1.0, 1.0, 100);\n}\n\n\nstatic void solveAndCompareResult(const std::string& fileName,\n\t\t\t\t\t\t double gsSolverPrecision = 1e-9, double gsContactTolerance = 1e-9, int gsMaxIterations = 100)\n{\n\tSCOPED_TRACE(\"while running test \" + fileName);\n\tprintf(\"-- TEST %s --\\n\", fileName.c_str());\n\n\tconst std::shared_ptr data = loadTestData(fileName);\n\tASSERT_TRUE(data) << \"Failed to load \" << fileName;\n\n\t\/\/ NB: need to make the solver calls const-correct.\n\tEigen::MatrixXd A = data->problem.A;\n\tEigen::VectorXd b = data->problem.b;\n\tEigen::VectorXd mu = data->problem.mu;\n\tstd::vector constraintTypes = data->problem.constraintTypes;\n\n\tconst int size = data->getSize();\n\tSurgSim::Math::MlcpSolution solution;\n\tsolution.x.resize(size);\n\n\t\/\/################################\n\t\/\/ Gauss-Seidel solver\n\tMlcpGaussSeidelSolver mlcpSolver(gsSolverPrecision, gsContactTolerance,\n\t\t\t\t\t\t\t\t\t gsMaxIterations);\n\n\tprintf(\" ### Gauss Seidel solver:\\n\");\n\tsolution.x.setZero();\n\n\t\/\/ XXX set ratio to 1\n\tbool res = mlcpSolver.solve(data->problem, &solution);\n\n\tprintf(\"\\tsolver did %d iterations convergence=%d Signorini=%d\\n\",\n\t\t solution.numIterations, solution.validConvergence ? 1 : 0, solution.validSignorini ? 1 : 0);\n\n\tASSERT_EQ(size, solution.x.rows());\n\tASSERT_EQ(size, data->expectedLambda.rows());\n\tif (size > 0)\n\t{\n\t\tASSERT_TRUE(isValid(solution.x)) << solution.x;\n\t}\n\n\t\/\/ TODO(advornik): Because this is a mixed LCP problem *with friction*, we can't just easily check that\n\t\/\/ all x are positive (the frictional entries may not be), or that all Ax+b are positive(ditto).\n\t\/\/ We need to either (a) make the test aware of the meaning of the constraint types, or (b) get rid\n\t\/\/ of the constraint types and flag the frictional DOFs more directly.\n\t\/\/\n\t\/\/ For now, we check if the MLCP is really a pure LCP (only unilaterals without friction), and we\n\t\/\/ perform some simple checks that apply to that case and that case only.\n\tbool isSimpleLcp = true;\n\tfor (auto it = constraintTypes.cbegin(); it != constraintTypes.cend(); ++it)\n\t{\n\t\tif ((*it) != SurgSim::Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT)\n\t\t{\n\t\t\tisSimpleLcp = false;\n\t\t}\n\t}\n\n\tif (isSimpleLcp && (size > 0))\n\t{\n\t\tEXPECT_GE(solution.x.minCoeff(), 0.0) << \"x contains negative coefficients:\" << std::endl << solution.x;\n\n\t\tEigen::VectorXd c = A * solution.x + b;\n\t\tEXPECT_GE(c.minCoeff(), -gsSolverPrecision) << \"Ax+b contains negative coefficients:\" << std::endl << c;\n\n\t\t\/\/ Orthogonality test should be taking into account the scaling factor\n\t\tdouble maxAbsForce = abs(solution.x.maxCoeff());\n\t\tif (abs(solution.x.minCoeff()) > maxAbsForce)\n\t\t{\n\t\t\tmaxAbsForce = abs(solution.x.minCoeff());\n\t\t}\n\t\tconst double epsilon = 1e-9 * maxAbsForce;\n\t\tEXPECT_NEAR(0.0, c.dot(solution.x), epsilon) << \"Ax+b is not orthogonal to x!\" << std::endl <<\n\t\t\t\"x:\" << std::endl << solution.x << std::endl << \"Ax+b:\" << std::endl << c;\n\t}\n\n\tEXPECT_TRUE(solution.x.isApprox(data->expectedLambda)) << \"lambda:\" << std::endl << solution.x << std::endl <<\n\t\t\"expected:\" << std::endl << data->expectedLambda;\n\n\/\/\tdouble convergenceCriteria=0.0;\n\/\/\tbool validSignorini=false;\n\/\/\tint nbContactToSkip=0;\n\/\/\tint currentAtomicIndex = calculateConvergenceCriteria(lambda, nbContactToSkip, convergenceCriteria,\n\/\/\t\tvalidSignorini, 1.0);\n\/\/\tprintf(\"\\tStatus method final [convergence criteria=%g, Signorini=%d]\\n\",convergenceCriteria,validSignorini?1:0);\n\tprintf(\"############\\n\");\n}\n\nTEST(MlcpGaussSeidelSolverTests, SolveOriginal)\n{\n\tconst double gsSolverPrecision = 1e-4;\n\tconst double gsContactTolerance = 2e-4;\n\tint gsMaxIterations = 30;\n\tsolveAndCompareResult(\"mlcpOriginalTest.txt\", gsSolverPrecision, gsContactTolerance, gsMaxIterations);\n}\n\nTEST(MlcpGaussSeidelSolverTests, SolveSequence)\n{\n\tfor (int i = 0; i <= 9; ++i)\n\t{\n\t\tsolveAndCompareResult(getTestFileName(\"mlcpTest\", i, \".txt\"));\n\t}\n}\n\nstatic void solveRepeatedly(const MlcpTestData& data,\n\t\t\t\t\t\t\t\/*XXX const *\/ MlcpGaussSeidelSolver* mlcpSolver,\n\t\t\t\t\t\t\tconst int repetitions)\n{\n\t\/\/ NB: need to make the solver calls const-correct.\n\tSurgSim::Math::MlcpProblem problem;\n\tSurgSim::Math::MlcpSolution solution;\n\tstd::vector constraintTypes;\n\n\tconst int size = data.getSize();\n\tsolution.x.resize(size);\n\n\tfor (int i = repetitions; i > 0; --i)\n\t{\n\t\tproblem = data.problem;\n\n\t\tif (mlcpSolver)\n\t\t{\n\t\t\tsolution.x.setZero();\n\t\t\tbool res = mlcpSolver->solve(problem, &solution);\n\t\t}\n\t}\n}\n\nstatic double measureExecutionTimeUsec(const std::string& fileName,\n\t\t\t\t\t\t\t\t\t double gsSolverPrecision = 1e-8, double gsContactTolerance = 1e-8,\n\t\t\t\t\t\t\t\t\t int gsMaxIterations = 20)\n{\n\tSCOPED_TRACE(\"while running test \" + fileName);\n\tprintf(\"-- TEST %s --\\n\", fileName.c_str());\n\n\tconst std::shared_ptr data = loadTestData(fileName);\n\tEXPECT_TRUE(data) << \"Failed to load \" << fileName;\n\n\tMlcpGaussSeidelSolver mlcpSolver(gsSolverPrecision, gsContactTolerance, gsMaxIterations);\n\n\ttypedef boost::chrono::high_resolution_clock clock;\n\tclock::time_point calibrationStart = clock::now();\n\n\tconst int calibrationRepetitions = 1000;\n\tsolveRepeatedly(*data, &mlcpSolver, calibrationRepetitions);\n\n\tboost::chrono::duration calibrationTime = clock::now() - calibrationStart;\n\tdouble desiredTestTimeSec = 1.0;\n\tdouble desiredRepetitions = desiredTestTimeSec * calibrationRepetitions \/ calibrationTime.count();\n\tconst int repetitions = std::max(10, std::min(1000000, static_cast(desiredRepetitions)));\n\n\tclock::time_point time0 = clock::now();\n\n\t\/\/ Do not actually solve the problem; just copy the input data.\n\tsolveRepeatedly(*data, nullptr, repetitions);\n\n\tclock::time_point time1 = clock::now();\n\n\t\/\/ Actually solve the problem.\n\tsolveRepeatedly(*data, &mlcpSolver, repetitions);\n\n\tclock::time_point time2 = clock::now();\n\n\tboost::chrono::duration elapsedSolveTime = time2 - time1;\n\t\/\/std::cout << \"Elapsed: \" << (elapsedSolveTime.count() * 1000.) << \" ms\" << std::endl;\n\tboost::chrono::duration elapsedBaseline = time1 - time0;\n\t\/\/std::cout << \"Baseline: \" << (elapsedBaseline.count() * 1000.) << \" ms\" << std::endl;\n\tdouble solveTimeUsec = (elapsedSolveTime - elapsedBaseline).count() * 1e6 \/ repetitions;\n\tdouble copyTimeUsec = elapsedBaseline.count() * 1e6 \/ repetitions;\n\tstd::cout << \"Average solution time: \" << solveTimeUsec << \" microseconds (over \" <<\n\t\trepetitions << \" loops)\" << std::endl;\n\treturn solveTimeUsec;\n}\n\nTEST(MlcpGaussSeidelSolverTests, MeasureExecutionTimeOriginal)\n{\n\tconst double gsSolverPrecision = 1e-4;\n\tconst double gsContactTolerance = 2e-5;\n\tint gsMaxIterations = 30;\n\tdouble solveTimeUsec = measureExecutionTimeUsec(\"mlcpOriginalTest.txt\", gsSolverPrecision, gsContactTolerance,\n\t\t\t\t\t\t\t\t\t\t\t\t\tgsMaxIterations);\n\n\t\/\/ When refactoring the MLCP code, it can be very useful to compare the execution time before and after making\n\t\/\/ changes. But you can't usefully compare execution times on different machines, or with different build\n\t\/\/ settings, so you'll need to manually uncomment the following line and adjust the time accordingly.\n\/\/\tEXPECT_LE(solveTimeUsec, 14.0);\n}\n<|endoftext|>"} {"text":"\/**\n * Zillians MMO\n * Copyright (C) 2007-2011 Zillians.com, Inc.\n * For more information see http:\/\/www.zillians.com\n *\n * Zillians MMO is the library and runtime for massive multiplayer online game\n * development in utility computing model, which runs as a service for every\n * developer to build their virtual world running on our GPU-assisted machines.\n *\n * This is a close source library intended to be used solely within Zillians.com\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"language\/stage\/generator\/LLVMGeneratorStage.h\"\n#include \"language\/stage\/generator\/detail\/LLVMForeach.h\"\n#include \"language\/context\/ParserContext.h\"\n#include \"language\/context\/GeneratorContext.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace zillians { namespace language { namespace stage {\n\nLLVMGeneratorStage::LLVMGeneratorStage()\n{ }\n\nLLVMGeneratorStage::~LLVMGeneratorStage()\n{ }\n\nconst char* LLVMGeneratorStage::name()\n{\n\treturn \"llvm_generator\";\n}\n\nvoid LLVMGeneratorStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc)\n{\n option_desc.add_options()\n (\"llvm-module-name\", po::value(),\t\"llvm module name\");\n}\n\nbool LLVMGeneratorStage::parseOptions(po::variables_map& vm)\n{\n\tif(vm.count(\"llvm-module-name\") == 0)\n\t{\n\t\tllvm_module_name = \"default_module\";\n\t}\n\telse if(vm.count(\"llvm-module-name\") == 1)\n\t{\n\t\tllvm_module_name = vm[\"llvm-module-name\"].as();\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool LLVMGeneratorStage::execute()\n{\n\tllvm::Module* module = new llvm::Module(llvm_module_name, llvm::getGlobalContext());\n\t\/\/ TODO make a visitor to walk through the entire tree and generate instructions accordingly\n\tgetGeneratorContext().modules.push_back(module);\n\treturn true;\n}\n\n} } }\ninitialize GeneratorContext\/**\n * Zillians MMO\n * Copyright (C) 2007-2011 Zillians.com, Inc.\n * For more information see http:\/\/www.zillians.com\n *\n * Zillians MMO is the library and runtime for massive multiplayer online game\n * development in utility computing model, which runs as a service for every\n * developer to build their virtual world running on our GPU-assisted machines.\n *\n * This is a close source library intended to be used solely within Zillians.com\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\n * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"language\/stage\/generator\/LLVMGeneratorStage.h\"\n#include \"language\/stage\/generator\/detail\/LLVMForeach.h\"\n#include \"language\/context\/ParserContext.h\"\n#include \"language\/context\/GeneratorContext.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace zillians { namespace language { namespace stage {\n\nLLVMGeneratorStage::LLVMGeneratorStage()\n{ }\n\nLLVMGeneratorStage::~LLVMGeneratorStage()\n{ }\n\nconst char* LLVMGeneratorStage::name()\n{\n\treturn \"llvm_generator\";\n}\n\nvoid LLVMGeneratorStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc)\n{\n option_desc.add_options()\n (\"llvm-module-name\", po::value(),\t\"llvm module name\");\n}\n\nbool LLVMGeneratorStage::parseOptions(po::variables_map& vm)\n{\n\tif(vm.count(\"llvm-module-name\") == 0)\n\t{\n\t\tllvm_module_name = \"default_module\";\n\t}\n\telse if(vm.count(\"llvm-module-name\") == 1)\n\t{\n\t\tllvm_module_name = vm[\"llvm-module-name\"].as();\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool LLVMGeneratorStage::execute()\n{\n\tsetGeneratorContext(new GeneratorContext());\n\n\tllvm::Module* module = new llvm::Module(llvm_module_name, llvm::getGlobalContext());\n\t\/\/ TODO make a visitor to walk through the entire tree and generate instructions accordingly\n\tgetGeneratorContext().modules.push_back(module);\n\treturn true;\n}\n\n} } }\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file TaskC.cpp\n *\/\n\n#include \n#include \n#include \n#include \"TaskC.h\"\n#include \n\nusing namespace std;\n\n\nTaskC::TaskC(const char* name, const char* description): JPetTask(name, description) {}\nTaskC::~TaskC() {}\n\nvoid TaskC::init(const JPetTaskInterface::Options& opts)\n{\n}\n\n\nvoid TaskC::exec()\n{\n \/\/getting the data from event in propriate format\n if (auto currSignal = dynamic_cast(getEvent())) {\n getStatistics().getCounter(\"No. initial signals\")++;\n if (fSignals.empty()) {\n fSignals.push_back(*currSignal);\n } else {\n if (fSignals[0].getTimeWindowIndex() == currSignal->getTimeWindowIndex()) {\n fSignals.push_back(*currSignal);\n } else {\n\n vector hits = createHits(fSignals);\n hits = JPetAnalysisTools::getHitsOrderedByTime(hits);\n \/\/ uncomment this in order to fill histograms\n \/\/ of time differences for subsequent hist\n studyTimeWindow(hits);\n saveHits(hits);\n\n fSignals.clear();\n fSignals.push_back(*currSignal);\n }\n }\n }\n}\n\nvector TaskC::createHits(const vector& signals)\n{\n vector hits;\n for (auto i = signals.begin(); i != signals.end(); ++i) {\n for (auto j = i; ++j != signals.end();) {\n if (i->getPM().getScin() == j->getPM().getScin()) {\n \/\/ found 2 signals from the same scintillator\n \/\/ wrap the RawSignal objects into RecoSignal and PhysSignal\n \/\/ for now this is just wrapping opne object into another\n \/\/ in the future analyses it will involve more logic like\n \/\/ reconstructing the signal's shape, charge, amplitude etc.\n JPetRecoSignal recoSignalA;\n JPetRecoSignal recoSignalB;\n JPetPhysSignal physSignalA;\n JPetPhysSignal physSignalB;\n \/\/ assign sides A and B properly\n if (\n (i->getPM().getSide() == JPetPM::SideA)\n && (j->getPM().getSide() == JPetPM::SideB)\n ) {\n recoSignalA.setRawSignal(*i);\n recoSignalB.setRawSignal(*j);\n } else if (\n (j->getPM().getSide() == JPetPM::SideA)\n && (i->getPM().getSide() == JPetPM::SideB)\n ) {\n recoSignalA.setRawSignal(*j);\n recoSignalB.setRawSignal(*i);\n } else {\n \/\/ if two hits on the same side, ignore\n WARNING(\"TWO hits on the same scintillator side we ignore it\");\n continue;\n }\n\n if ( recoSignalA.getRawSignal().getNumberOfPoints(JPetSigCh::Leading) < 4 ) continue;\n if ( recoSignalB.getRawSignal().getNumberOfPoints(JPetSigCh::Leading) < 4 ) continue;\n\n bool thresholds_ok = true;\n for (int i = 1; i <= 4; ++i) {\n if ( recoSignalA.getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).count(i) < 1 ) {\n thresholds_ok = false;\n }\n if ( recoSignalB.getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).count(i) < 1 ) {\n thresholds_ok = false;\n }\n }\n if (thresholds_ok == false) {\n continue;\n }\n\n physSignalA.setRecoSignal(recoSignalA);\n physSignalB.setRecoSignal(recoSignalB);\n auto leading_points_a = physSignalA.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n auto leading_points_b = physSignalB.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n \/\/skip signals with no information on 1st threshold\n if (leading_points_a.count(1) == 0) continue;\n if (leading_points_b.count(1) == 0) continue;\n\n physSignalA.setTime(leading_points_a.at(1));\n physSignalB.setTime(leading_points_b.at(1));\n\n\n JPetHit hit;\n hit.setSignalA(physSignalA);\n hit.setSignalB(physSignalB);\n hit.setScintillator(i->getPM().getScin());\n hit.setBarrelSlot(i->getPM().getScin().getBarrelSlot());\n\n physSignalA.setTime(physSignalA.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(1));\n physSignalB.setTime(physSignalB.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(1));\n\n hit.setTime( 0.5 * ( hit.getSignalA().getTime() + hit.getSignalB().getTime()) );\n hits.push_back(hit);\n getStatistics().getCounter(\"No. found hits\")++;\n }\n }\n }\n return hits;\n}\n\nvoid TaskC::terminate()\n{\n \/\/\tsaveHits(createHits(fSignals)); \/\/if there is something left\n INFO( Form(\"From %d initial signals %d hits were paired.\",\n static_cast(getStatistics().getCounter(\"No. initial signals\")),\n static_cast(getStatistics().getCounter(\"No. found hits\")) )\n );\n}\n\n\nvoid TaskC::studyTimeWindow(const vector& hits)\n{\n \/\/ make sure the hits are really sorted\n \/\/ assert(hits.at(i-1).getTime() <= hits.at(i).getTime());\n\n \/\/ double dt = hits.at(i).getTime() - hits.at(i-1).getTime();\n\n \/\/ getStatistics().getHisto1D(\"timeSepSmall\").Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n \/\/ getStatistics().getHisto1D(\"timeSepLarge\").Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n\n for(int k=1;k<=4;++k){\n\n double t2 = 0.5*(hits.at(i).getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k) + hits.at(i).getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k));\n\n double t1 = 0.5*(hits.at(i-1).getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k) + hits.at(i-1).getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k));\n \n\n double dt = t2 - t1;\n\n getStatistics().getHisto1D(Form(\"timeSepSmall_thr_%d\", k)).Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n getStatistics().getHisto1D(Form(\"timeSepLarge_thr_%d\", k)).Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n \n }\n \n }\n\n getStatistics().getHisto1D(\"timeSepSmall\").Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n getStatistics().getHisto1D(\"timeSepLarge\").Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n}\n\nvoid TaskC::saveHits(const vector& hits)\n{\n assert(fWriter);\n for (auto hit : hits) {\n \/\/ here one can impose any conditions on hits that should be\n \/\/ saved or skipped\n \/\/ for now, all hits are written to the output file\n \/\/ without checking anything\n fWriter->write(hit);\n }\n}\nUse hit sorting from framework library\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file TaskC.cpp\n *\/\n\n#include \n#include \n#include \n#include \"TaskC.h\"\n#include \n\nusing namespace std;\n\n\nTaskC::TaskC(const char* name, const char* description): JPetTask(name, description) {}\nTaskC::~TaskC() {}\n\nvoid TaskC::init(const JPetTaskInterface::Options& opts)\n{\n}\n\n\nvoid TaskC::exec()\n{\n \/\/getting the data from event in propriate format\n if (auto currSignal = dynamic_cast(getEvent())) {\n getStatistics().getCounter(\"No. initial signals\")++;\n if (fSignals.empty()) {\n fSignals.push_back(*currSignal);\n } else {\n if (fSignals[0].getTimeWindowIndex() == currSignal->getTimeWindowIndex()) {\n fSignals.push_back(*currSignal);\n } else {\n\n vector hits = createHits(fSignals);\n hits = JPetAnalysisTools::getHitsOrderedByTime(hits);\n \/\/ uncomment this in order to fill histograms\n \/\/ of time differences for subsequent hist\n studyTimeWindow(hits);\n saveHits(hits);\n\n fSignals.clear();\n fSignals.push_back(*currSignal);\n }\n }\n }\n}\n\nvoid TaskC::exec()\n{\n \/\/getting the data from event in propriate format\n if (auto currSignal = dynamic_cast(getEvent())) {\n getStatistics().getCounter(\"No. initial signals\")++;\n if (fSignals.empty()) {\n fSignals.push_back(*currSignal);\n } else {\n if (fSignals[0].getTimeWindowIndex() == currSignal->getTimeWindowIndex()) {\n fSignals.push_back(*currSignal);\n } else {\n\n vector hits = createHits(fSignals);\n hits = JPetAnalysisTools::getHitsOrderedByTime(hits);\n \/\/ uncomment this in order to fill histograms\n \/\/ of time differences for subsequent hist\n studyTimeWindow(hits);\n\n saveHits(hits);\n\n fSignals.clear();\n fSignals.push_back(*currSignal);\n }\n }\n }\n}\nvector TaskC::createHits(const vector& signals)\n{\n vector hits;\n for (auto i = signals.begin(); i != signals.end(); ++i) {\n for (auto j = i; ++j != signals.end();) {\n if (i->getPM().getScin() == j->getPM().getScin()) {\n \/\/ found 2 signals from the same scintillator\n \/\/ wrap the RawSignal objects into RecoSignal and PhysSignal\n \/\/ for now this is just wrapping opne object into another\n \/\/ in the future analyses it will involve more logic like\n \/\/ reconstructing the signal's shape, charge, amplitude etc.\n JPetRecoSignal recoSignalA;\n JPetRecoSignal recoSignalB;\n JPetPhysSignal physSignalA;\n JPetPhysSignal physSignalB;\n \/\/ assign sides A and B properly\n if (\n (i->getPM().getSide() == JPetPM::SideA)\n && (j->getPM().getSide() == JPetPM::SideB)\n ) {\n recoSignalA.setRawSignal(*i);\n recoSignalB.setRawSignal(*j);\n } else if (\n (j->getPM().getSide() == JPetPM::SideA)\n && (i->getPM().getSide() == JPetPM::SideB)\n ) {\n recoSignalA.setRawSignal(*j);\n recoSignalB.setRawSignal(*i);\n } else {\n \/\/ if two hits on the same side, ignore\n WARNING(\"TWO hits on the same scintillator side we ignore it\");\n continue;\n }\n\n if ( recoSignalA.getRawSignal().getNumberOfPoints(JPetSigCh::Leading) < 4 ) continue;\n if ( recoSignalB.getRawSignal().getNumberOfPoints(JPetSigCh::Leading) < 4 ) continue;\n\n bool thresholds_ok = true;\n for (int i = 1; i <= 4; ++i) {\n if ( recoSignalA.getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).count(i) < 1 ) {\n thresholds_ok = false;\n }\n if ( recoSignalB.getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).count(i) < 1 ) {\n thresholds_ok = false;\n }\n }\n if (thresholds_ok == false) {\n continue;\n }\n\n physSignalA.setRecoSignal(recoSignalA);\n physSignalB.setRecoSignal(recoSignalB);\n auto leading_points_a = physSignalA.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n auto leading_points_b = physSignalB.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading);\n\n \/\/skip signals with no information on 1st threshold\n \/\/ if(leading_points_a.count(1) == 0) continue;\n \/\/ if(leading_points_b.count(1) == 0) continue;\n\n physSignalA.setTime(leading_points_a.at(1));\n physSignalB.setTime(leading_points_b.at(1));\n\n\n JPetHit hit;\n hit.setSignalA(physSignalA);\n hit.setSignalB(physSignalB);\n hit.setScintillator(i->getPM().getScin());\n hit.setBarrelSlot(i->getPM().getScin().getBarrelSlot());\n\n physSignalA.setTime(physSignalA.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(1));\n physSignalB.setTime(physSignalB.getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(1));\n\n hit.setTime( 0.5 * ( hit.getSignalA().getTime() + hit.getSignalB().getTime()) );\n\n hits.push_back(hit);\n getStatistics().getCounter(\"No. found hits\")++;\n }\n }\n }\n return hits;\n}\n\nvoid TaskC::terminate()\n{\n \/\/\tsaveHits(createHits(fSignals)); \/\/if there is something left\n INFO( Form(\"From %d initial signals %d hits were paired.\",\n static_cast(getStatistics().getCounter(\"No. initial signals\")),\n static_cast(getStatistics().getCounter(\"No. found hits\")) )\n );\n}\n\n\n\nvoid TaskC::studyTimeWindow(const vector& hits)\n{\n\n \/\/ plot time differences for subsequent hits at each threshold separately\n for (int i = 1; i < hits.size(); ++i) {\n >>> >>> > Use hit sorting from framework library\n for (int k = 1; k <= 4; ++k) {\n double t2 = 0.5 * (hits.at(i).getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k) + hits.at(i).getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k));\n double t1 = 0.5 * (hits.at(i - 1).getSignalA().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k) + hits.at(i - 1).getSignalB().getRecoSignal().getRawSignal().getTimesVsThresholdNumber(JPetSigCh::Leading).at(k));\n double dt = t2 - t1;\n getStatistics().getHisto1D(Form(\"timeSepSmall_thr_%d\", k)).Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n getStatistics().getHisto1D(Form(\"timeSepLarge_thr_%d\", k)).Fill(dt \/ 1000.); \/\/ we fill the histo in [ns]\n }\n }\n}\n\nvoid TaskC::saveHits(const vector& hits)\n{\n assert(fWriter);\n for (auto hit : hits) {\n \/\/ here one can impose any conditions on hits that should be\n \/\/ saved or skipped\n \/\/ for now, all hits are written to the output file\n \/\/ without checking anything\n fWriter->write(hit);\n }\n}\n<|endoftext|>"} {"text":"\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"thread_per_process_schedule.h\"\n\n#include \n#include \n\n#include \n#include \n\nnamespace vistk\n{\n\nstatic void run_process(process_t process);\n\nclass thread_per_process_schedule::priv\n{\n public:\n priv();\n ~priv();\n\n boost::thread_group process_threads;\n};\n\nthread_per_process_schedule\n::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)\n : schedule(config, pipe)\n{\n}\n\nthread_per_process_schedule\n::~thread_per_process_schedule()\n{\n}\n\nvoid\nthread_per_process_schedule\n::start()\n{\n BOOST_FOREACH (process::name_t const& name, pipeline()->process_names())\n {\n process_t process = pipeline()->process_by_name(name);\n\n d->process_threads.create_thread(boost::bind(run_process, process));\n }\n}\n\nvoid\nthread_per_process_schedule\n::stop()\n{\n \/\/\/ \\todo Shut the schedule down.\n}\n\nthread_per_process_schedule::priv\n::priv()\n{\n}\n\nthread_per_process_schedule::priv\n::~priv()\n{\n}\n\nvoid\nrun_process(process_t process)\n{\n name_thread(process->name());\n\n \/\/\/ \\todo Run the process until it is complete.\n}\n\n}\nInitialize the private pointer\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"thread_per_process_schedule.h\"\n\n#include \n#include \n\n#include \n#include \n\nnamespace vistk\n{\n\nstatic void run_process(process_t process);\n\nclass thread_per_process_schedule::priv\n{\n public:\n priv();\n ~priv();\n\n boost::thread_group process_threads;\n};\n\nthread_per_process_schedule\n::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)\n : schedule(config, pipe)\n{\n d = boost::shared_ptr(new priv);\n}\n\nthread_per_process_schedule\n::~thread_per_process_schedule()\n{\n}\n\nvoid\nthread_per_process_schedule\n::start()\n{\n BOOST_FOREACH (process::name_t const& name, pipeline()->process_names())\n {\n process_t process = pipeline()->process_by_name(name);\n\n d->process_threads.create_thread(boost::bind(run_process, process));\n }\n}\n\nvoid\nthread_per_process_schedule\n::stop()\n{\n \/\/\/ \\todo Shut the schedule down.\n}\n\nthread_per_process_schedule::priv\n::priv()\n{\n}\n\nthread_per_process_schedule::priv\n::~priv()\n{\n}\n\nvoid\nrun_process(process_t process)\n{\n name_thread(process->name());\n\n \/\/\/ \\todo Run the process until it is complete.\n}\n\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n *\n * Copyright (C) 2014 Dominik Haumann \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"katetabbutton.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nQColor KateTabButton::s_predefinedColors[] = { Qt::red, Qt::yellow, Qt::green, Qt::cyan, Qt::blue, Qt::magenta };\nconst int KateTabButton::s_colorCount = 6;\nint KateTabButton::s_currentColor = 0;\n\n\nKateTabButton::KateTabButton(const QString &docurl, const QString &caption,\n int button_id, QWidget *parent)\n : QPushButton(parent)\n{\n setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));\n setCheckable(true);\n setFocusPolicy(Qt::NoFocus);\n setMinimumWidth(1);\n setFlat(true);\n\/\/ setAutoFillBackground(true);\n\n m_buttonId = button_id;\n m_modified = false;\n\n setIcon(QIcon());\n setText(caption);\n setURL(docurl);\n\n connect(this, SIGNAL(clicked()), this, SLOT(buttonClicked()));\n}\n\nKateTabButton::~KateTabButton()\n{\n}\n\nvoid KateTabButton::setURL(const QString &docurl)\n{\n m_url = docurl;\n if (!m_url.isEmpty()) {\n setToolTip(m_url);\n } else {\n setToolTip(text());\n }\n}\n\nQString KateTabButton::url() const\n{\n return m_url;\n}\n\nvoid KateTabButton::buttonClicked()\n{\n \/\/ once down, stay down until another tab is activated\n if (isChecked()) {\n emit activated(this);\n } else {\n setChecked(true);\n }\n}\n\nvoid KateTabButton::setActivated(bool active)\n{\n if (isChecked() == active) {\n return;\n }\n setChecked(active);\n update();\n}\n\nbool KateTabButton::isActivated() const\n{\n return isChecked();\n}\n\nvoid KateTabButton::paintEvent(QPaintEvent *ev)\n{\n Q_UNUSED(ev)\n\n QPalette pal = QApplication::palette();\n\n QPainter p(this);\n if (underMouse()) {\n QColor c = pal.color(QPalette::Background);\n p.fillRect(rect(), c.lighter(110));\n }\n\n \/\/ draw text\n style()->drawItemText(&p, rect(), Qt::AlignHCenter, pal, true, text());\n\n if (m_highlightColor.isValid()) {\n p.fillRect(QRect(0, height() - 3, width(), 10), m_highlightColor);\n }\n\n if (isActivated()) {\n p.fillRect(QRect(0, height() - 3, width(), 10), QColor(0, 0, 255, 128));\n }\n}\n\nvoid KateTabButton::contextMenuEvent(QContextMenuEvent *ev)\n{\n QPixmap colorIcon(22, 22);\n QMenu menu(\/*text(),*\/ this);\n QMenu *colorMenu = menu.addMenu(i18n(\"&Highlight Tab\"));\n QAction *aNone = colorMenu->addAction(i18n(\"&None\"));\n colorMenu->addSeparator();\n colorIcon.fill(Qt::red);\n QAction *aRed = colorMenu->addAction(colorIcon, i18n(\"&Red\"));\n colorIcon.fill(Qt::yellow);\n QAction *aYellow = colorMenu->addAction(colorIcon, i18n(\"&Yellow\"));\n colorIcon.fill(Qt::green);\n QAction *aGreen = colorMenu->addAction(colorIcon, i18n(\"&Green\"));\n colorIcon.fill(Qt::cyan);\n QAction *aCyan = colorMenu->addAction(colorIcon, i18n(\"&Cyan\"));\n colorIcon.fill(Qt::blue);\n QAction *aBlue = colorMenu->addAction(colorIcon, i18n(\"&Blue\"));\n colorIcon.fill(Qt::magenta);\n QAction *aMagenta = colorMenu->addAction(colorIcon, i18n(\"&Magenta\"));\n colorMenu->addSeparator();\n QAction *aCustomColor = colorMenu->addAction(\n QIcon::fromTheme(QStringLiteral(\"colors\")), i18n(\"C&ustom Color...\"));\n menu.addSeparator();\n\n QAction *aCloseTab = menu.addAction(i18n(\"&Close Tab\"));\n QAction *aCloseOtherTabs = menu.addAction(i18n(\"Close &Other Tabs\"));\n QAction *aCloseAllTabs = menu.addAction(i18n(\"Close &All Tabs\"));\n\n QAction *choice = menu.exec(ev->globalPos());\n\n \/\/ process the result\n if (choice == aNone) {\n if (m_highlightColor.isValid()) {\n setHighlightColor(QColor());\n emit highlightChanged(this);\n }\n } else if (choice == aRed) {\n setHighlightColor(Qt::red);\n emit highlightChanged(this);\n } else if (choice == aYellow) {\n setHighlightColor(Qt::yellow);\n emit highlightChanged(this);\n } else if (choice == aGreen) {\n setHighlightColor(Qt::green);\n emit highlightChanged(this);\n } else if (choice == aCyan) {\n setHighlightColor(Qt::cyan);\n emit highlightChanged(this);\n } else if (choice == aBlue) {\n setHighlightColor(Qt::blue);\n emit highlightChanged(this);\n } else if (choice == aMagenta) {\n setHighlightColor(Qt::magenta);\n emit highlightChanged(this);\n } else if (choice == aCustomColor) {\n QColor newColor = QColorDialog::getColor(m_highlightColor, this);\n if (newColor.isValid()) {\n setHighlightColor(newColor);\n emit highlightChanged(this);\n }\n } else if (choice == aCloseTab) {\n emit closeRequest(this);\n } else if (choice == aCloseOtherTabs) {\n emit closeOtherTabsRequest(this);\n } else if (choice == aCloseAllTabs) {\n emit closeAllTabsRequest();\n }\n}\n\nvoid KateTabButton::mousePressEvent(QMouseEvent *ev)\n{\n if (ev->button() == Qt::MidButton) {\n if (ev->modifiers() & Qt::ControlModifier) {\n \/\/ clear tab highlight\n setHighlightColor(QColor());\n } else {\n setHighlightColor(s_predefinedColors[s_currentColor]);\n if (++s_currentColor >= s_colorCount) {\n s_currentColor = 0;\n }\n }\n ev->accept();\n } else {\n QPushButton::mousePressEvent(ev);\n }\n}\n\nvoid KateTabButton::setButtonID(int button_id)\n{\n m_buttonId = button_id;\n}\n\nint KateTabButton::buttonID() const\n{\n return m_buttonId;\n}\n\nvoid KateTabButton::setHighlightColor(const QColor &color)\n{\n if (color.isValid()) {\n m_highlightColor = color;\n update();\n } else if (m_highlightColor.isValid()) {\n m_highlightColor = QColor();\n update();\n }\n}\n\nQColor KateTabButton::highlightColor() const\n{\n return m_highlightColor;\n}\n\nvoid KateTabButton::setModified(bool modified)\n{\n m_modified = modified;\n update();\n}\n\nbool KateTabButton::isModified() const\n{\n return m_modified;\n}\n\n\/\/ kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; eol unix;\ncenter vertically too\/* This file is part of the KDE project\n *\n * Copyright (C) 2014 Dominik Haumann \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"katetabbutton.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nQColor KateTabButton::s_predefinedColors[] = { Qt::red, Qt::yellow, Qt::green, Qt::cyan, Qt::blue, Qt::magenta };\nconst int KateTabButton::s_colorCount = 6;\nint KateTabButton::s_currentColor = 0;\n\n\nKateTabButton::KateTabButton(const QString &docurl, const QString &caption,\n int button_id, QWidget *parent)\n : QPushButton(parent)\n{\n setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));\n setCheckable(true);\n setFocusPolicy(Qt::NoFocus);\n setMinimumWidth(1);\n setFlat(true);\n\/\/ setAutoFillBackground(true);\n\n m_buttonId = button_id;\n m_modified = false;\n\n setIcon(QIcon());\n setText(caption);\n setURL(docurl);\n\n connect(this, SIGNAL(clicked()), this, SLOT(buttonClicked()));\n}\n\nKateTabButton::~KateTabButton()\n{\n}\n\nvoid KateTabButton::setURL(const QString &docurl)\n{\n m_url = docurl;\n if (!m_url.isEmpty()) {\n setToolTip(m_url);\n } else {\n setToolTip(text());\n }\n}\n\nQString KateTabButton::url() const\n{\n return m_url;\n}\n\nvoid KateTabButton::buttonClicked()\n{\n \/\/ once down, stay down until another tab is activated\n if (isChecked()) {\n emit activated(this);\n } else {\n setChecked(true);\n }\n}\n\nvoid KateTabButton::setActivated(bool active)\n{\n if (isChecked() == active) {\n return;\n }\n setChecked(active);\n update();\n}\n\nbool KateTabButton::isActivated() const\n{\n return isChecked();\n}\n\nvoid KateTabButton::paintEvent(QPaintEvent *ev)\n{\n Q_UNUSED(ev)\n\n QPalette pal = QApplication::palette();\n\n QPainter p(this);\n if (underMouse()) {\n QColor c = pal.color(QPalette::Background);\n p.fillRect(rect(), c.lighter(110));\n }\n\n \/\/ draw text\n style()->drawItemText(&p, rect(), Qt::AlignHCenter | Qt::AlignVCenter, pal, true, text());\n\n if (m_highlightColor.isValid()) {\n p.fillRect(QRect(0, height() - 3, width(), 10), m_highlightColor);\n }\n\n if (isActivated()) {\n p.fillRect(QRect(0, height() - 3, width(), 10), QColor(0, 0, 255, 128));\n }\n}\n\nvoid KateTabButton::contextMenuEvent(QContextMenuEvent *ev)\n{\n QPixmap colorIcon(22, 22);\n QMenu menu(\/*text(),*\/ this);\n QMenu *colorMenu = menu.addMenu(i18n(\"&Highlight Tab\"));\n QAction *aNone = colorMenu->addAction(i18n(\"&None\"));\n colorMenu->addSeparator();\n colorIcon.fill(Qt::red);\n QAction *aRed = colorMenu->addAction(colorIcon, i18n(\"&Red\"));\n colorIcon.fill(Qt::yellow);\n QAction *aYellow = colorMenu->addAction(colorIcon, i18n(\"&Yellow\"));\n colorIcon.fill(Qt::green);\n QAction *aGreen = colorMenu->addAction(colorIcon, i18n(\"&Green\"));\n colorIcon.fill(Qt::cyan);\n QAction *aCyan = colorMenu->addAction(colorIcon, i18n(\"&Cyan\"));\n colorIcon.fill(Qt::blue);\n QAction *aBlue = colorMenu->addAction(colorIcon, i18n(\"&Blue\"));\n colorIcon.fill(Qt::magenta);\n QAction *aMagenta = colorMenu->addAction(colorIcon, i18n(\"&Magenta\"));\n colorMenu->addSeparator();\n QAction *aCustomColor = colorMenu->addAction(\n QIcon::fromTheme(QStringLiteral(\"colors\")), i18n(\"C&ustom Color...\"));\n menu.addSeparator();\n\n QAction *aCloseTab = menu.addAction(i18n(\"&Close Tab\"));\n QAction *aCloseOtherTabs = menu.addAction(i18n(\"Close &Other Tabs\"));\n QAction *aCloseAllTabs = menu.addAction(i18n(\"Close &All Tabs\"));\n\n QAction *choice = menu.exec(ev->globalPos());\n\n \/\/ process the result\n if (choice == aNone) {\n if (m_highlightColor.isValid()) {\n setHighlightColor(QColor());\n emit highlightChanged(this);\n }\n } else if (choice == aRed) {\n setHighlightColor(Qt::red);\n emit highlightChanged(this);\n } else if (choice == aYellow) {\n setHighlightColor(Qt::yellow);\n emit highlightChanged(this);\n } else if (choice == aGreen) {\n setHighlightColor(Qt::green);\n emit highlightChanged(this);\n } else if (choice == aCyan) {\n setHighlightColor(Qt::cyan);\n emit highlightChanged(this);\n } else if (choice == aBlue) {\n setHighlightColor(Qt::blue);\n emit highlightChanged(this);\n } else if (choice == aMagenta) {\n setHighlightColor(Qt::magenta);\n emit highlightChanged(this);\n } else if (choice == aCustomColor) {\n QColor newColor = QColorDialog::getColor(m_highlightColor, this);\n if (newColor.isValid()) {\n setHighlightColor(newColor);\n emit highlightChanged(this);\n }\n } else if (choice == aCloseTab) {\n emit closeRequest(this);\n } else if (choice == aCloseOtherTabs) {\n emit closeOtherTabsRequest(this);\n } else if (choice == aCloseAllTabs) {\n emit closeAllTabsRequest();\n }\n}\n\nvoid KateTabButton::mousePressEvent(QMouseEvent *ev)\n{\n if (ev->button() == Qt::MidButton) {\n if (ev->modifiers() & Qt::ControlModifier) {\n \/\/ clear tab highlight\n setHighlightColor(QColor());\n } else {\n setHighlightColor(s_predefinedColors[s_currentColor]);\n if (++s_currentColor >= s_colorCount) {\n s_currentColor = 0;\n }\n }\n ev->accept();\n } else {\n QPushButton::mousePressEvent(ev);\n }\n}\n\nvoid KateTabButton::setButtonID(int button_id)\n{\n m_buttonId = button_id;\n}\n\nint KateTabButton::buttonID() const\n{\n return m_buttonId;\n}\n\nvoid KateTabButton::setHighlightColor(const QColor &color)\n{\n if (color.isValid()) {\n m_highlightColor = color;\n update();\n } else if (m_highlightColor.isValid()) {\n m_highlightColor = QColor();\n update();\n }\n}\n\nQColor KateTabButton::highlightColor() const\n{\n return m_highlightColor;\n}\n\nvoid KateTabButton::setModified(bool modified)\n{\n m_modified = modified;\n update();\n}\n\nbool KateTabButton::isModified() const\n{\n return m_modified;\n}\n\n\/\/ kate: space-indent on; indent-width 4; tab-width 4; replace-tabs on; eol unix;\n<|endoftext|>"} {"text":"\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 gatecat \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"chains.h\"\n#include \n#include \n#include \"cells.h\"\n#include \"chain_utils.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"place_common.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nclass ChainConstrainer\n{\n private:\n int feedio_lcs = 0;\n Context *ctx;\n \/\/ Split a carry chain into multiple legal chains\n std::vector split_carry_chain(CellChain &carryc)\n {\n bool start_of_chain = true;\n std::vector chains;\n std::vector tile;\n const int max_length = (ctx->chip_info->height - 2) * 8 - 2;\n auto curr_cell = carryc.cells.begin();\n while (curr_cell != carryc.cells.end()) {\n CellInfo *cell = *curr_cell;\n if (ctx->debug)\n log_info(\" processing cell %s\\n\", ctx->nameOf(cell));\n if (tile.size() >= 8) {\n tile.clear();\n }\n if (start_of_chain) {\n tile.clear();\n chains.emplace_back();\n start_of_chain = false;\n if (cell->ports.at(id_CIN).net) {\n \/\/ CIN is not constant and not part of a chain. Must feed in from fabric\n CellInfo *feedin = make_carry_feed_in(cell, cell->ports.at(id_CIN));\n chains.back().cells.push_back(feedin);\n tile.push_back(feedin);\n ++feedio_lcs;\n }\n }\n tile.push_back(cell);\n chains.back().cells.push_back(cell);\n bool split_chain = (!ctx->logic_cells_compatible(tile.data(), tile.size())) ||\n (int(chains.back().cells.size()) > max_length);\n if (split_chain) {\n CellInfo *passout = make_carry_pass_out((*(curr_cell - 1))->ports.at(id_COUT));\n tile.pop_back();\n chains.back().cells.back() = passout;\n start_of_chain = true;\n } else {\n NetInfo *carry_net = cell->ports.at(id_COUT).net;\n bool at_end = (curr_cell == carryc.cells.end() - 1);\n if (carry_net != nullptr && (carry_net->users.entries() > 1 || at_end)) {\n if (carry_net->users.entries() > 2 ||\n (net_only_drives(ctx, carry_net, is_lc, id_I3, false) !=\n net_only_drives(ctx, carry_net, is_lc, id_CIN, false)) ||\n (at_end && !net_only_drives(ctx, carry_net, is_lc, id_I3, true))) {\n if (ctx->debug)\n log_info(\" inserting feed-%s\\n\", at_end ? \"out\" : \"out-in\");\n CellInfo *passout;\n if (!at_end) {\n \/\/ See if we need to split chain anyway\n tile.push_back(*(curr_cell + 1));\n bool split_chain_next = (!ctx->logic_cells_compatible(tile.data(), tile.size())) ||\n (int(chains.back().cells.size()) > max_length);\n tile.pop_back();\n if (split_chain_next)\n start_of_chain = true;\n passout = make_carry_pass_out(cell->ports.at(id_COUT),\n split_chain_next ? nullptr : *(curr_cell + 1));\n } else {\n passout = make_carry_pass_out(cell->ports.at(id_COUT), nullptr);\n }\n\n chains.back().cells.push_back(passout);\n tile.push_back(passout);\n ++feedio_lcs;\n }\n }\n ++curr_cell;\n }\n }\n return chains;\n }\n\n \/\/ Insert a logic cell to legalise a COUT->fabric connection\n CellInfo *make_carry_pass_out(PortInfo &cout_port, CellInfo *cin_cell = nullptr)\n {\n NPNR_ASSERT(cout_port.net != nullptr);\n std::unique_ptr lc = create_ice_cell(ctx, id_ICESTORM_LC);\n lc->params[id_LUT_INIT] = Property(65280, 16); \/\/ 0xff00: O = I3\n lc->params[id_CARRY_ENABLE] = Property::State::S1;\n lc->ports.at(id_O).net = cout_port.net;\n NetInfo *co_i3_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$I3\"));\n co_i3_net->driver = cout_port.net->driver;\n lc->connectPort(id_I3, co_i3_net);\n PortRef o_r;\n o_r.port = id_O;\n o_r.cell = lc.get();\n cout_port.net->driver = o_r;\n cout_port.net = co_i3_net;\n\n \/\/ If COUT also connects to a CIN; preserve the carry chain\n if (cin_cell) {\n NetInfo *co_cin_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$COUT\"));\n\n \/\/ Connect I1 to 1 to preserve carry chain\n NetInfo *vcc = ctx->nets.at(ctx->id(\"$PACKER_VCC_NET\")).get();\n lc->connectPort(id_I1, vcc);\n\n \/\/ Connect co_cin_net to the COUT of the LC\n lc->connectPort(id_COUT, co_cin_net);\n\n \/\/ Find the user corresponding to the next CIN\n int replaced_ports = 0;\n if (ctx->debug)\n log_info(\"cell: %s\\n\", cin_cell->name.c_str(ctx));\n for (auto port : {id_CIN, id_I3}) {\n NetInfo *out_net = lc->ports.at(id_O).net;\n auto &cin_p = cin_cell->ports.at(port);\n if (cin_p.net == out_net) {\n cin_cell->disconnectPort(port);\n cin_cell->connectPort(port, co_cin_net);\n ++replaced_ports;\n }\n }\n NPNR_ASSERT(replaced_ports > 0);\n }\n\n IdString name = lc->name;\n ctx->assignCellInfo(lc.get());\n ctx->cells[lc->name] = std::move(lc);\n return ctx->cells[name].get();\n }\n\n \/\/ Insert a logic cell to legalise a CIN->fabric connection\n CellInfo *make_carry_feed_in(CellInfo *cin_cell, PortInfo &cin_port)\n {\n NPNR_ASSERT(cin_port.net != nullptr);\n std::unique_ptr lc = create_ice_cell(ctx, id_ICESTORM_LC);\n lc->params[id_CARRY_ENABLE] = Property::State::S1;\n lc->params[id_CIN_CONST] = Property::State::S1;\n lc->params[id_CIN_SET] = Property::State::S1;\n\n lc->connectPort(id_I1, cin_port.net);\n cin_port.net->users.remove(cin_port.user_idx);\n\n NetInfo *out_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$O\"));\n\n lc->connectPort(id_COUT, out_net);\n\n cin_port.net = nullptr;\n cin_cell->connectPort(cin_port.name, out_net);\n\n IdString name = lc->name;\n ctx->assignCellInfo(lc.get());\n ctx->cells[lc->name] = std::move(lc);\n return ctx->cells[name].get();\n }\n\n void process_carries()\n {\n std::vector carry_chains = find_chains(\n ctx, [](const Context *ctx, const CellInfo *cell) { return is_lc(ctx, cell); },\n [](const Context *ctx, const\n\n CellInfo *cell) {\n CellInfo *carry_prev = net_driven_by(ctx, cell->ports.at(id_CIN).net, is_lc, id_COUT);\n if (carry_prev != nullptr)\n return carry_prev;\n CellInfo *i3_prev = net_driven_by(ctx, cell->ports.at(id_I3).net, is_lc, id_COUT);\n if (i3_prev != nullptr)\n return i3_prev;\n return (CellInfo *)nullptr;\n },\n [](const Context *ctx, const CellInfo *cell) {\n CellInfo *carry_next = net_only_drives(ctx, cell->ports.at(id_COUT).net, is_lc, id_CIN, false);\n if (carry_next != nullptr)\n return carry_next;\n CellInfo *i3_next = net_only_drives(ctx, cell->ports.at(id_COUT).net, is_lc, id_I3, false);\n if (i3_next != nullptr)\n return i3_next;\n return (CellInfo *)nullptr;\n });\n pool chained;\n for (auto &base_chain : carry_chains) {\n for (auto c : base_chain.cells)\n chained.insert(c->name);\n }\n \/\/ Any cells not in chains, but with carry enabled, must also be put in a single-carry chain\n \/\/ for correct processing\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (chained.find(cell.first) == chained.end() && is_lc(ctx, ci) &&\n bool_or_default(ci->params, id_CARRY_ENABLE)) {\n CellChain sChain;\n sChain.cells.push_back(ci);\n chained.insert(cell.first);\n carry_chains.push_back(sChain);\n }\n }\n std::vector all_chains;\n \/\/ Chain splitting\n for (auto &base_chain : carry_chains) {\n if (ctx->verbose) {\n log_info(\"Found carry chain: \\n\");\n for (auto entry : base_chain.cells)\n log_info(\" %s\\n\", entry->name.c_str(ctx));\n log_info(\"\\n\");\n }\n std::vector split_chains = split_carry_chain(base_chain);\n for (auto &chain : split_chains) {\n all_chains.push_back(chain);\n }\n }\n \/\/ Actual chain placement\n for (auto &chain : all_chains) {\n if (ctx->verbose)\n log_info(\"Placing carry chain starting at '%s'\\n\", chain.cells.front()->name.c_str(ctx));\n\n \/\/ Place carry chain\n chain.cells.at(0)->constr_abs_z = true;\n chain.cells.at(0)->constr_z = 0;\n chain.cells.at(0)->cluster = chain.cells.at(0)->name;\n\n for (int i = 1; i < int(chain.cells.size()); i++) {\n chain.cells.at(i)->constr_x = 0;\n chain.cells.at(i)->constr_y = (i \/ 8);\n chain.cells.at(i)->constr_z = i % 8;\n chain.cells.at(i)->constr_abs_z = true;\n chain.cells.at(i)->cluster = chain.cells.at(0)->name;\n chain.cells.at(0)->constr_children.push_back(chain.cells.at(i));\n }\n }\n log_info(\" %4d LCs used to legalise carry chains.\\n\", feedio_lcs);\n }\n\n public:\n ChainConstrainer(Context *ctx) : ctx(ctx){};\n void constrain_chains() { process_carries(); }\n};\n\nvoid constrain_chains(Context *ctx)\n{\n log_info(\"Constraining chains...\\n\");\n ChainConstrainer(ctx).constrain_chains();\n}\n\nNEXTPNR_NAMESPACE_END\nice40: Avoid chain finder from mixing up chains by only allowing I3 chaining at end\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 gatecat \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"chains.h\"\n#include \n#include \n#include \"cells.h\"\n#include \"chain_utils.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n#include \"place_common.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nclass ChainConstrainer\n{\n private:\n int feedio_lcs = 0;\n Context *ctx;\n \/\/ Split a carry chain into multiple legal chains\n std::vector split_carry_chain(CellChain &carryc)\n {\n bool start_of_chain = true;\n std::vector chains;\n std::vector tile;\n const int max_length = (ctx->chip_info->height - 2) * 8 - 2;\n auto curr_cell = carryc.cells.begin();\n while (curr_cell != carryc.cells.end()) {\n CellInfo *cell = *curr_cell;\n if (ctx->debug)\n log_info(\" processing cell %s\\n\", ctx->nameOf(cell));\n if (tile.size() >= 8) {\n tile.clear();\n }\n if (start_of_chain) {\n tile.clear();\n chains.emplace_back();\n start_of_chain = false;\n if (cell->ports.at(id_CIN).net) {\n \/\/ CIN is not constant and not part of a chain. Must feed in from fabric\n CellInfo *feedin = make_carry_feed_in(cell, cell->ports.at(id_CIN));\n chains.back().cells.push_back(feedin);\n tile.push_back(feedin);\n ++feedio_lcs;\n }\n }\n tile.push_back(cell);\n chains.back().cells.push_back(cell);\n bool split_chain = (!ctx->logic_cells_compatible(tile.data(), tile.size())) ||\n (int(chains.back().cells.size()) > max_length);\n if (split_chain) {\n CellInfo *passout = make_carry_pass_out((*(curr_cell - 1))->ports.at(id_COUT));\n tile.pop_back();\n chains.back().cells.back() = passout;\n start_of_chain = true;\n } else {\n NetInfo *carry_net = cell->ports.at(id_COUT).net;\n bool at_end = (curr_cell == carryc.cells.end() - 1);\n if (carry_net != nullptr && (carry_net->users.entries() > 1 || at_end)) {\n if (carry_net->users.entries() > 2 ||\n (net_only_drives(ctx, carry_net, is_lc, id_I3, false) !=\n net_only_drives(ctx, carry_net, is_lc, id_CIN, false)) ||\n (at_end && !net_only_drives(ctx, carry_net, is_lc, id_I3, true))) {\n if (ctx->debug)\n log_info(\" inserting feed-%s\\n\", at_end ? \"out\" : \"out-in\");\n CellInfo *passout;\n if (!at_end) {\n \/\/ See if we need to split chain anyway\n tile.push_back(*(curr_cell + 1));\n bool split_chain_next = (!ctx->logic_cells_compatible(tile.data(), tile.size())) ||\n (int(chains.back().cells.size()) > max_length);\n tile.pop_back();\n if (split_chain_next)\n start_of_chain = true;\n passout = make_carry_pass_out(cell->ports.at(id_COUT),\n split_chain_next ? nullptr : *(curr_cell + 1));\n } else {\n passout = make_carry_pass_out(cell->ports.at(id_COUT), nullptr);\n }\n\n chains.back().cells.push_back(passout);\n tile.push_back(passout);\n ++feedio_lcs;\n }\n }\n ++curr_cell;\n }\n }\n return chains;\n }\n\n \/\/ Insert a logic cell to legalise a COUT->fabric connection\n CellInfo *make_carry_pass_out(PortInfo &cout_port, CellInfo *cin_cell = nullptr)\n {\n NPNR_ASSERT(cout_port.net != nullptr);\n std::unique_ptr lc = create_ice_cell(ctx, id_ICESTORM_LC);\n lc->params[id_LUT_INIT] = Property(65280, 16); \/\/ 0xff00: O = I3\n lc->params[id_CARRY_ENABLE] = Property::State::S1;\n lc->ports.at(id_O).net = cout_port.net;\n NetInfo *co_i3_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$I3\"));\n co_i3_net->driver = cout_port.net->driver;\n lc->connectPort(id_I3, co_i3_net);\n PortRef o_r;\n o_r.port = id_O;\n o_r.cell = lc.get();\n cout_port.net->driver = o_r;\n cout_port.net = co_i3_net;\n\n \/\/ If COUT also connects to a CIN; preserve the carry chain\n if (cin_cell) {\n NetInfo *co_cin_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$COUT\"));\n\n \/\/ Connect I1 to 1 to preserve carry chain\n NetInfo *vcc = ctx->nets.at(ctx->id(\"$PACKER_VCC_NET\")).get();\n lc->connectPort(id_I1, vcc);\n\n \/\/ Connect co_cin_net to the COUT of the LC\n lc->connectPort(id_COUT, co_cin_net);\n\n \/\/ Find the user corresponding to the next CIN\n int replaced_ports = 0;\n if (ctx->debug)\n log_info(\"cell: %s\\n\", cin_cell->name.c_str(ctx));\n for (auto port : {id_CIN, id_I3}) {\n NetInfo *out_net = lc->ports.at(id_O).net;\n auto &cin_p = cin_cell->ports.at(port);\n if (cin_p.net == out_net) {\n cin_cell->disconnectPort(port);\n cin_cell->connectPort(port, co_cin_net);\n ++replaced_ports;\n }\n }\n NPNR_ASSERT(replaced_ports > 0);\n }\n\n IdString name = lc->name;\n ctx->assignCellInfo(lc.get());\n ctx->cells[lc->name] = std::move(lc);\n return ctx->cells[name].get();\n }\n\n \/\/ Insert a logic cell to legalise a CIN->fabric connection\n CellInfo *make_carry_feed_in(CellInfo *cin_cell, PortInfo &cin_port)\n {\n NPNR_ASSERT(cin_port.net != nullptr);\n std::unique_ptr lc = create_ice_cell(ctx, id_ICESTORM_LC);\n lc->params[id_CARRY_ENABLE] = Property::State::S1;\n lc->params[id_CIN_CONST] = Property::State::S1;\n lc->params[id_CIN_SET] = Property::State::S1;\n\n lc->connectPort(id_I1, cin_port.net);\n cin_port.net->users.remove(cin_port.user_idx);\n\n NetInfo *out_net = ctx->createNet(ctx->id(lc->name.str(ctx) + \"$O\"));\n\n lc->connectPort(id_COUT, out_net);\n\n cin_port.net = nullptr;\n cin_cell->connectPort(cin_port.name, out_net);\n\n IdString name = lc->name;\n ctx->assignCellInfo(lc.get());\n ctx->cells[lc->name] = std::move(lc);\n return ctx->cells[name].get();\n }\n\n void process_carries()\n {\n \/\/ Find carry roots\n std::vector carry_chains;\n pool processed;\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (is_lc(ctx, ci) && bool_or_default(ci->params, id_CARRY_ENABLE)) {\n \/\/ possibly a non-root if CIN or I3 driven by another cout\n NetInfo *cin = ci->getPort(id_CIN);\n if (cin && cin->driver.cell && is_lc(ctx, cin->driver.cell) && cin->driver.port == id_COUT) {\n continue;\n }\n carry_chains.emplace_back();\n auto &cc = carry_chains.back();\n CellInfo *cursor = ci;\n while (cursor) {\n cc.cells.push_back(cursor);\n processed.insert(cursor->name);\n NetInfo *cout = cursor->getPort(id_COUT);\n if (!cout)\n break;\n cursor = nullptr;\n \/\/ look for CIN connectivity\n for (auto &usr : cout->users) {\n if (is_lc(ctx, usr.cell) && usr.port == id_CIN && !processed.count(usr.cell->name)) {\n cursor = usr.cell;\n break;\n }\n }\n \/\/ look for I3 connectivity - only to a top cell with no further chaining\n if (cursor)\n continue;\n for (auto &usr : cout->users) {\n if (is_lc(ctx, usr.cell) && usr.port == id_I3 && !processed.count(usr.cell->name) &&\n !usr.cell->getPort(id_COUT)) {\n cursor = usr.cell;\n break;\n }\n }\n }\n }\n }\n \/\/ anything left behind....\n for (auto &cell : ctx->cells) {\n CellInfo *ci = cell.second.get();\n if (is_lc(ctx, ci) && bool_or_default(ci->params, id_CARRY_ENABLE) && !processed.count(ci->name)) {\n carry_chains.emplace_back();\n carry_chains.back().cells.push_back(ci);\n processed.insert(ci->name);\n }\n }\n std::vector all_chains;\n \/\/ Chain splitting\n for (auto &base_chain : carry_chains) {\n if (ctx->verbose) {\n log_info(\"Found carry chain: \\n\");\n for (auto entry : base_chain.cells)\n log_info(\" %s\\n\", entry->name.c_str(ctx));\n log_info(\"\\n\");\n }\n std::vector split_chains = split_carry_chain(base_chain);\n for (auto &chain : split_chains) {\n all_chains.push_back(chain);\n }\n }\n \/\/ Actual chain placement\n for (auto &chain : all_chains) {\n if (ctx->verbose)\n log_info(\"Placing carry chain starting at '%s'\\n\", chain.cells.front()->name.c_str(ctx));\n\n \/\/ Place carry chain\n chain.cells.at(0)->constr_abs_z = true;\n chain.cells.at(0)->constr_z = 0;\n chain.cells.at(0)->cluster = chain.cells.at(0)->name;\n\n for (int i = 1; i < int(chain.cells.size()); i++) {\n chain.cells.at(i)->constr_x = 0;\n chain.cells.at(i)->constr_y = (i \/ 8);\n chain.cells.at(i)->constr_z = i % 8;\n chain.cells.at(i)->constr_abs_z = true;\n chain.cells.at(i)->cluster = chain.cells.at(0)->name;\n chain.cells.at(0)->constr_children.push_back(chain.cells.at(i));\n }\n }\n log_info(\" %4d LCs used to legalise carry chains.\\n\", feedio_lcs);\n }\n\n public:\n ChainConstrainer(Context *ctx) : ctx(ctx){};\n void constrain_chains() { process_carries(); }\n};\n\nvoid constrain_chains(Context *ctx)\n{\n log_info(\"Constraining chains...\\n\");\n ChainConstrainer(ctx).constrain_chains();\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"#ifndef CPPJIEBA_KEYWORD_EXTRACTOR_H\n#define CPPJIEBA_KEYWORD_EXTRACTOR_H\n\n#include \"MixSegment.hpp\"\n#include \n#include \n\n#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))\n\nnamespace CppJieba\n{\n using namespace Limonp;\n\n \/*utf8*\/\n class KeywordExtractor: public InitOnOff\n {\n private:\n MixSegment _segment;\n private:\n unordered_map _idfMap;\n double _idfAverage;\n\n unordered_set _stopWords;\n public:\n KeywordExtractor(){_setInitFlag(false);};\n explicit KeywordExtractor(const string& dictPath, const string& hmmFilePath, const string& idfPath, const string& stopWordPath)\n {\n _setInitFlag(init(dictPath, hmmFilePath, idfPath, stopWordPath));\n };\n ~KeywordExtractor(){};\n\n public:\n bool init(const string& dictPath, const string& hmmFilePath, const string& idfPath, const string& stopWordPath)\n {\n _loadIdfDict(idfPath);\n _loadStopWordDict(stopWordPath);\n return _setInitFlag(_segment.init(dictPath, hmmFilePath));\n };\n public:\n\n bool extract(const string& str, vector& keywords, size_t topN) const\n {\n assert(_getInitFlag());\n vector > topWords;\n if(!extract(str, topWords, topN))\n {\n return false;\n }\n for(size_t i = 0; i < topWords.size(); i++)\n {\n keywords.push_back(topWords[i].first);\n }\n return true;\n }\n\n bool extract(const string& str, vector >& keywords, size_t topN) const\n {\n vector words;\n if(!_segment.cut(str, words))\n {\n LogError(\"segment cut(%s) failed.\", str.c_str());\n return false;\n }\n\n \/\/ filtering single word.\n for(vector::iterator iter = words.begin(); iter != words.end(); )\n {\n if(_isSingleWord(*iter))\n {\n iter = words.erase(iter);\n }\n else\n {\n iter++;\n }\n }\n\n map wordmap;\n for(size_t i = 0; i < words.size(); i ++)\n {\n wordmap[ words[i] ] += 1.0;\n }\n\n for(map::iterator itr = wordmap.begin(); itr != wordmap.end(); )\n {\n if(_stopWords.end() != _stopWords.find(itr->first))\n {\n wordmap.erase(itr++);\n continue;\n }\n\n unordered_map::const_iterator cit = _idfMap.find(itr->first);\n if(cit != _idfMap.end())\n {\n itr->second *= cit->second;\n }\n else\n {\n itr->second *= _idfAverage;\n }\n itr ++;\n }\n\n keywords.clear();\n std::copy(wordmap.begin(), wordmap.end(), std::inserter(keywords, keywords.begin()));\n topN = MIN(topN, keywords.size());\n partial_sort(keywords.begin(), keywords.begin() + topN, keywords.end(), _cmp);\n keywords.resize(topN);\n return true;\n }\n private:\n void _loadIdfDict(const string& idfPath)\n {\n ifstream ifs(idfPath.c_str());\n if(!ifs)\n {\n LogError(\"open %s failed.\", idfPath.c_str());\n assert(false);\n }\n string line ;\n vector buf;\n double idf = 0.0;\n double idfSum = 0.0;\n size_t lineno = 0;\n for(;getline(ifs, line); lineno++)\n {\n buf.clear();\n if(line.empty())\n {\n LogError(\"line[%d] empty. skipped.\", lineno);\n continue;\n }\n if(!split(line, buf, \" \") || buf.size() != 2)\n {\n LogError(\"line %d [%s] illegal. skipped.\", lineno, line.c_str());\n continue;\n }\n idf = atof(buf[1].c_str());\n _idfMap[buf[0]] = idf;\n idfSum += idf;\n\n } \n\n assert(lineno);\n _idfAverage = idfSum \/ lineno;\n assert(_idfAverage > 0.0);\n }\n void _loadStopWordDict(const string& filePath)\n {\n ifstream ifs(filePath.c_str());\n if(!ifs)\n {\n LogError(\"open %s failed.\", filePath.c_str());\n assert(false);\n }\n string line ;\n while(getline(ifs, line))\n {\n _stopWords.insert(line);\n }\n assert(_stopWords.size());\n }\n private:\n bool _isSingleWord(const string& str) const\n {\n Unicode unicode;\n TransCode::decode(str, unicode);\n if(unicode.size() == 1)\n return true;\n return false;\n }\n\n private:\n static bool _cmp(const pair& lhs, const pair& rhs)\n {\n return lhs.second > rhs.second;\n }\n \n };\n}\n\n#endif\n\n\nmake keywordextractor faster#ifndef CPPJIEBA_KEYWORD_EXTRACTOR_H\n#define CPPJIEBA_KEYWORD_EXTRACTOR_H\n\n#include \"MixSegment.hpp\"\n#include \n#include \n\n#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))\n\nnamespace CppJieba\n{\n using namespace Limonp;\n\n \/*utf8*\/\n class KeywordExtractor: public InitOnOff\n {\n private:\n MixSegment _segment;\n private:\n unordered_map _idfMap;\n double _idfAverage;\n\n unordered_set _stopWords;\n public:\n KeywordExtractor(){_setInitFlag(false);};\n explicit KeywordExtractor(const string& dictPath, const string& hmmFilePath, const string& idfPath, const string& stopWordPath)\n {\n _setInitFlag(init(dictPath, hmmFilePath, idfPath, stopWordPath));\n };\n ~KeywordExtractor(){};\n\n public:\n bool init(const string& dictPath, const string& hmmFilePath, const string& idfPath, const string& stopWordPath)\n {\n _loadIdfDict(idfPath);\n _loadStopWordDict(stopWordPath);\n return _setInitFlag(_segment.init(dictPath, hmmFilePath));\n };\n public:\n\n bool extract(const string& str, vector& keywords, size_t topN) const\n {\n assert(_getInitFlag());\n vector > topWords;\n if(!extract(str, topWords, topN))\n {\n return false;\n }\n for(size_t i = 0; i < topWords.size(); i++)\n {\n keywords.push_back(topWords[i].first);\n }\n return true;\n }\n\n bool extract(const string& str, vector >& keywords, size_t topN) const\n {\n vector words;\n if(!_segment.cut(str, words))\n {\n LogError(\"segment cut(%s) failed.\", str.c_str());\n return false;\n }\n\n map wordmap;\n for(vector::iterator iter = words.begin(); iter != words.end(); iter++)\n {\n if(_isSingleWord(*iter))\n {\n continue;\n }\n wordmap[*iter] += 1.0;\n }\n\n for(map::iterator itr = wordmap.begin(); itr != wordmap.end(); )\n {\n if(_stopWords.end() != _stopWords.find(itr->first))\n {\n wordmap.erase(itr++);\n continue;\n }\n\n unordered_map::const_iterator cit = _idfMap.find(itr->first);\n if(cit != _idfMap.end())\n {\n itr->second *= cit->second;\n }\n else\n {\n itr->second *= _idfAverage;\n }\n itr ++;\n }\n\n keywords.clear();\n std::copy(wordmap.begin(), wordmap.end(), std::inserter(keywords, keywords.begin()));\n topN = MIN(topN, keywords.size());\n partial_sort(keywords.begin(), keywords.begin() + topN, keywords.end(), _cmp);\n keywords.resize(topN);\n return true;\n }\n private:\n void _loadIdfDict(const string& idfPath)\n {\n ifstream ifs(idfPath.c_str());\n if(!ifs)\n {\n LogError(\"open %s failed.\", idfPath.c_str());\n assert(false);\n }\n string line ;\n vector buf;\n double idf = 0.0;\n double idfSum = 0.0;\n size_t lineno = 0;\n for(;getline(ifs, line); lineno++)\n {\n buf.clear();\n if(line.empty())\n {\n LogError(\"line[%d] empty. skipped.\", lineno);\n continue;\n }\n if(!split(line, buf, \" \") || buf.size() != 2)\n {\n LogError(\"line %d [%s] illegal. skipped.\", lineno, line.c_str());\n continue;\n }\n idf = atof(buf[1].c_str());\n _idfMap[buf[0]] = idf;\n idfSum += idf;\n\n } \n\n assert(lineno);\n _idfAverage = idfSum \/ lineno;\n assert(_idfAverage > 0.0);\n }\n void _loadStopWordDict(const string& filePath)\n {\n ifstream ifs(filePath.c_str());\n if(!ifs)\n {\n LogError(\"open %s failed.\", filePath.c_str());\n assert(false);\n }\n string line ;\n while(getline(ifs, line))\n {\n _stopWords.insert(line);\n }\n assert(_stopWords.size());\n }\n private:\n bool _isSingleWord(const string& str) const\n {\n Unicode unicode;\n TransCode::decode(str, unicode);\n if(unicode.size() == 1)\n return true;\n return false;\n }\n\n private:\n static bool _cmp(const pair& lhs, const pair& rhs)\n {\n return lhs.second > rhs.second;\n }\n \n };\n}\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2016-2018 The Bitcoin Unlimited developers\n\n#include \"connmgr.h\"\n#include \"expedited.h\"\n\nstd::unique_ptr connmgr(new CConnMgr);\n\n\/**\n * Find a node in a vector. Just calls std::find. Split out for cleanliness and also because std:find won't be\n * enough if we switch to vectors of noderefs. Requires any lock for vector traversal to be held.\n *\/\nstatic std::vector::iterator FindNode(std::vector &vNodes, CNode *pNode)\n{\n return std::find(vNodes.begin(), vNodes.end(), pNode);\n}\n\n\/**\n * Add a node to a vector, and take a reference. This function does NOT prevent adding duplicates.\n * Requires any lock for vector traversal to be held.\n * @param[in] vNodes The vector of nodes.\n * @param[in] pNode The node to add.\n *\/\nstatic void AddNode(std::vector &vNodes, CNode *pNode)\n{\n pNode->AddRef();\n vNodes.push_back(pNode);\n}\n\n\/**\n * If a node is present in a vector, remove it and drop a reference.\n * Requires any lock for vector traversal to be held.\n * @param[in] vNodes The vector of nodes.\n * @param[in] pNode The node to remove.\n * @return True if the node was originally present, false if not.\n *\/\nstatic bool RemoveNode(std::vector &vNodes, CNode *pNode)\n{\n auto Node = FindNode(vNodes, pNode);\n\n if (Node != vNodes.end())\n {\n pNode->Release();\n vNodes.erase(Node);\n return true;\n }\n\n return false;\n}\n\nCConnMgr::CConnMgr() : nExpeditedBlocksMax(32), nExpeditedTxsMax(32), next(0)\n{\n vSendExpeditedBlocks.reserve(256);\n vSendExpeditedTxs.reserve(256);\n vExpeditedUpstream.reserve(256);\n}\n\nNodeId CConnMgr::NextNodeId()\n{\n \/\/ Pre-increment; do not use zero\n return ++next;\n}\n\n\/**\n * Given a node ID, return a node reference to the node.\n *\/\nCNodeRef CConnMgr::FindNodeFromId(NodeId id)\n{\n LOCK(cs_vNodes);\n\n for (CNode *pNode : vNodes)\n {\n if (pNode->GetId() == id)\n return CNodeRef(pNode);\n }\n\n return CNodeRef();\n}\n\nvoid CConnMgr::EnableExpeditedSends(CNode *pNode, bool fBlocks, bool fTxs, bool fForceIfFull)\n{\n LOCK(cs_expedited);\n\n if (fBlocks && FindNode(vSendExpeditedBlocks, pNode) == vSendExpeditedBlocks.end())\n {\n if (fForceIfFull || vSendExpeditedBlocks.size() < nExpeditedBlocksMax)\n {\n AddNode(vSendExpeditedBlocks, pNode);\n LOG(THIN, \"Enabled expedited blocks to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n }\n else\n {\n LOG(THIN, \"Cannot enable expedited blocks to peer %s, I am full (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n }\n }\n\n if (fTxs && FindNode(vSendExpeditedTxs, pNode) == vSendExpeditedTxs.end())\n {\n if (fForceIfFull || vSendExpeditedTxs.size() < nExpeditedTxsMax)\n {\n AddNode(vSendExpeditedTxs, pNode);\n LOG(THIN, \"Enabled expedited txs to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n }\n else\n {\n LOG(THIN, \"Cannot enable expedited txs to peer %s, I am full (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n }\n }\n}\n\nvoid CConnMgr::DisableExpeditedSends(CNode *pNode, bool fBlocks, bool fTxs)\n{\n LOCK(cs_expedited);\n\n if (fBlocks && RemoveNode(vSendExpeditedBlocks, pNode))\n LOG(THIN, \"Disabled expedited blocks to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n\n if (fTxs && RemoveNode(vSendExpeditedTxs, pNode))\n LOG(THIN, \"Disabled expedited txs to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n}\n\nvoid CConnMgr::HandleCommandLine()\n{\n nExpeditedBlocksMax = GetArg(\"-maxexpeditedblockrecipients\", nExpeditedBlocksMax);\n nExpeditedTxsMax = GetArg(\"-maxexpeditedtxrecipients\", nExpeditedTxsMax);\n}\n\n\/\/ Called after a node is removed from the node list.\nvoid CConnMgr::RemovedNode(CNode *pNode)\n{\n LOCK(cs_expedited);\n\n RemoveNode(vSendExpeditedBlocks, pNode);\n RemoveNode(vSendExpeditedTxs, pNode);\n RemoveNode(vExpeditedUpstream, pNode);\n}\n\nvoid CConnMgr::ExpeditedNodeCounts(uint32_t &nBlocks, uint32_t &nTxs, uint32_t &nUpstream)\n{\n LOCK(cs_expedited);\n\n nBlocks = vSendExpeditedBlocks.size();\n nTxs = vSendExpeditedTxs.size();\n nUpstream = vExpeditedUpstream.size();\n}\n\nVNodeRefs CConnMgr::ExpeditedBlockNodes()\n{\n LOCK(cs_expedited);\n\n VNodeRefs vRefs;\n\n BOOST_FOREACH (CNode *pNode, vExpeditedUpstream)\n vRefs.push_back(CNodeRef(pNode));\n\n return vRefs;\n}\n\nbool CConnMgr::PushExpeditedRequest(CNode *pNode, uint64_t flags)\n{\n if (!IsThinBlocksEnabled())\n return error(\"Thinblocks is not enabled so cannot request expedited blocks from peer %s\", pNode->GetLogName());\n\n if (!pNode->ThinBlockCapable())\n return error(\"Remote peer has not enabled Thinblocks so you cannot request expedited blocks from %s\",\n pNode->GetLogName());\n\n if (flags & EXPEDITED_BLOCKS)\n {\n LOCK(cs_expedited);\n\n \/\/ Add or remove this node as an upstream node\n if (flags & EXPEDITED_STOP)\n {\n RemoveNode(vExpeditedUpstream, pNode);\n LOGA(\"Requesting a stop of expedited blocks from peer %s\\n\", pNode->GetLogName());\n }\n else\n {\n if (FindNode(vExpeditedUpstream, pNode) == vExpeditedUpstream.end())\n AddNode(vExpeditedUpstream, pNode);\n LOGA(\"Requesting expedited blocks from peer %s\\n\", pNode->GetLogName());\n }\n }\n\n \/\/ Push even if its a repeat to allow the operator to use the CLI or GUI to force another message.\n pNode->PushMessage(NetMsgType::XPEDITEDREQUEST, flags);\n\n return true;\n}\n\nbool CConnMgr::IsExpeditedUpstream(CNode *pNode)\n{\n LOCK(cs_expedited);\n\n return FindNode(vExpeditedUpstream, pNode) != vExpeditedUpstream.end();\n}\nFix variables shadowing in connmgr.cpp\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2016-2018 The Bitcoin Unlimited developers\n\n#include \"connmgr.h\"\n#include \"expedited.h\"\n\nstd::unique_ptr connmgr(new CConnMgr);\n\n\/**\n * Find a node in a vector. Just calls std::find. Split out for cleanliness and also because std:find won't be\n * enough if we switch to vectors of noderefs. Requires any lock for vector traversal to be held.\n *\/\nstatic std::vector::iterator FindNode(std::vector &_vNodes, CNode *pNode)\n{\n return std::find(_vNodes.begin(), _vNodes.end(), pNode);\n}\n\n\/**\n * Add a node to a vector, and take a reference. This function does NOT prevent adding duplicates.\n * Requires any lock for vector traversal to be held.\n * @param[in] vNodes The vector of nodes.\n * @param[in] pNode The node to add.\n *\/\nstatic void AddNode(std::vector &_vNodes, CNode *pNode)\n{\n pNode->AddRef();\n _vNodes.push_back(pNode);\n}\n\n\/**\n * If a node is present in a vector, remove it and drop a reference.\n * Requires any lock for vector traversal to be held.\n * @param[in] vNodes The vector of nodes.\n * @param[in] pNode The node to remove.\n * @return True if the node was originally present, false if not.\n *\/\nstatic bool RemoveNode(std::vector &_vNodes, CNode *pNode)\n{\n auto Node = FindNode(_vNodes, pNode);\n\n if (Node != _vNodes.end())\n {\n pNode->Release();\n _vNodes.erase(Node);\n return true;\n }\n\n return false;\n}\n\nCConnMgr::CConnMgr() : nExpeditedBlocksMax(32), nExpeditedTxsMax(32), next(0)\n{\n vSendExpeditedBlocks.reserve(256);\n vSendExpeditedTxs.reserve(256);\n vExpeditedUpstream.reserve(256);\n}\n\nNodeId CConnMgr::NextNodeId()\n{\n \/\/ Pre-increment; do not use zero\n return ++next;\n}\n\n\/**\n * Given a node ID, return a node reference to the node.\n *\/\nCNodeRef CConnMgr::FindNodeFromId(NodeId id)\n{\n LOCK(cs_vNodes);\n\n for (CNode *pNode : vNodes)\n {\n if (pNode->GetId() == id)\n return CNodeRef(pNode);\n }\n\n return CNodeRef();\n}\n\nvoid CConnMgr::EnableExpeditedSends(CNode *pNode, bool fBlocks, bool fTxs, bool fForceIfFull)\n{\n LOCK(cs_expedited);\n\n if (fBlocks && FindNode(vSendExpeditedBlocks, pNode) == vSendExpeditedBlocks.end())\n {\n if (fForceIfFull || vSendExpeditedBlocks.size() < nExpeditedBlocksMax)\n {\n AddNode(vSendExpeditedBlocks, pNode);\n LOG(THIN, \"Enabled expedited blocks to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n }\n else\n {\n LOG(THIN, \"Cannot enable expedited blocks to peer %s, I am full (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n }\n }\n\n if (fTxs && FindNode(vSendExpeditedTxs, pNode) == vSendExpeditedTxs.end())\n {\n if (fForceIfFull || vSendExpeditedTxs.size() < nExpeditedTxsMax)\n {\n AddNode(vSendExpeditedTxs, pNode);\n LOG(THIN, \"Enabled expedited txs to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n }\n else\n {\n LOG(THIN, \"Cannot enable expedited txs to peer %s, I am full (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n }\n }\n}\n\nvoid CConnMgr::DisableExpeditedSends(CNode *pNode, bool fBlocks, bool fTxs)\n{\n LOCK(cs_expedited);\n\n if (fBlocks && RemoveNode(vSendExpeditedBlocks, pNode))\n LOG(THIN, \"Disabled expedited blocks to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedBlocks.size());\n\n if (fTxs && RemoveNode(vSendExpeditedTxs, pNode))\n LOG(THIN, \"Disabled expedited txs to peer %s (%u peers total)\\n\", pNode->GetLogName(),\n vSendExpeditedTxs.size());\n}\n\nvoid CConnMgr::HandleCommandLine()\n{\n nExpeditedBlocksMax = GetArg(\"-maxexpeditedblockrecipients\", nExpeditedBlocksMax);\n nExpeditedTxsMax = GetArg(\"-maxexpeditedtxrecipients\", nExpeditedTxsMax);\n}\n\n\/\/ Called after a node is removed from the node list.\nvoid CConnMgr::RemovedNode(CNode *pNode)\n{\n LOCK(cs_expedited);\n\n RemoveNode(vSendExpeditedBlocks, pNode);\n RemoveNode(vSendExpeditedTxs, pNode);\n RemoveNode(vExpeditedUpstream, pNode);\n}\n\nvoid CConnMgr::ExpeditedNodeCounts(uint32_t &nBlocks, uint32_t &nTxs, uint32_t &nUpstream)\n{\n LOCK(cs_expedited);\n\n nBlocks = vSendExpeditedBlocks.size();\n nTxs = vSendExpeditedTxs.size();\n nUpstream = vExpeditedUpstream.size();\n}\n\nVNodeRefs CConnMgr::ExpeditedBlockNodes()\n{\n LOCK(cs_expedited);\n\n VNodeRefs vRefs;\n\n BOOST_FOREACH (CNode *pNode, vExpeditedUpstream)\n vRefs.push_back(CNodeRef(pNode));\n\n return vRefs;\n}\n\nbool CConnMgr::PushExpeditedRequest(CNode *pNode, uint64_t flags)\n{\n if (!IsThinBlocksEnabled())\n return error(\"Thinblocks is not enabled so cannot request expedited blocks from peer %s\", pNode->GetLogName());\n\n if (!pNode->ThinBlockCapable())\n return error(\"Remote peer has not enabled Thinblocks so you cannot request expedited blocks from %s\",\n pNode->GetLogName());\n\n if (flags & EXPEDITED_BLOCKS)\n {\n LOCK(cs_expedited);\n\n \/\/ Add or remove this node as an upstream node\n if (flags & EXPEDITED_STOP)\n {\n RemoveNode(vExpeditedUpstream, pNode);\n LOGA(\"Requesting a stop of expedited blocks from peer %s\\n\", pNode->GetLogName());\n }\n else\n {\n if (FindNode(vExpeditedUpstream, pNode) == vExpeditedUpstream.end())\n AddNode(vExpeditedUpstream, pNode);\n LOGA(\"Requesting expedited blocks from peer %s\\n\", pNode->GetLogName());\n }\n }\n\n \/\/ Push even if its a repeat to allow the operator to use the CLI or GUI to force another message.\n pNode->PushMessage(NetMsgType::XPEDITEDREQUEST, flags);\n\n return true;\n}\n\nbool CConnMgr::IsExpeditedUpstream(CNode *pNode)\n{\n LOCK(cs_expedited);\n\n return FindNode(vExpeditedUpstream, pNode) != vExpeditedUpstream.end();\n}\n<|endoftext|>"} {"text":"Init allocated SkBitmap pixels<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/audio_send_stream.h\"\n\n#include \n\n#include \"rtc_base\/string_encode.h\"\n#include \"rtc_base\/strings\/audio_format_to_string.h\"\n#include \"rtc_base\/strings\/string_builder.h\"\n\nnamespace webrtc {\n\nAudioSendStream::Stats::Stats() = default;\nAudioSendStream::Stats::~Stats() = default;\n\nAudioSendStream::Config::Config(Transport* send_transport)\n : send_transport(send_transport) {}\n\nAudioSendStream::Config::~Config() = default;\n\nstd::string AudioSendStream::Config::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{rtp: \" << rtp.ToString();\n ss << \", rtcp_report_interval_ms: \" << rtcp_report_interval_ms;\n ss << \", send_transport: \" << (send_transport ? \"(Transport)\" : \"null\");\n ss << \", min_bitrate_bps: \" << min_bitrate_bps;\n ss << \", max_bitrate_bps: \" << max_bitrate_bps;\n ss << \", send_codec_spec: \"\n << (send_codec_spec ? send_codec_spec->ToString() : \"\");\n ss << '}';\n return ss.str();\n}\n\nAudioSendStream::Config::Rtp::Rtp() = default;\n\nAudioSendStream::Config::Rtp::~Rtp() = default;\n\nstd::string AudioSendStream::Config::Rtp::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{ssrc: \" << ssrc;\n ss << \", extmap-allow-mixed: \" << (extmap_allow_mixed ? \"true\" : \"false\");\n ss << \", extensions: [\";\n for (size_t i = 0; i < extensions.size(); ++i) {\n ss << extensions[i].ToString();\n if (i != extensions.size() - 1) {\n ss << \", \";\n }\n }\n ss << ']';\n ss << \", c_name: \" << c_name;\n ss << '}';\n return ss.str();\n}\n\nAudioSendStream::Config::SendCodecSpec::SendCodecSpec(\n int payload_type,\n const SdpAudioFormat& format)\n : payload_type(payload_type), format(format) {}\nAudioSendStream::Config::SendCodecSpec::~SendCodecSpec() = default;\n\nstd::string AudioSendStream::Config::SendCodecSpec::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{nack_enabled: \" << (nack_enabled ? \"true\" : \"false\");\n ss << \", transport_cc_enabled: \" << (transport_cc_enabled ? \"true\" : \"false\");\n ss << \", cng_payload_type: \"\n << (cng_payload_type ? rtc::ToString(*cng_payload_type) : \"\");\n ss << \", red_payload_type: \"\n << (red_payload_type ? rtc::ToString(*red_payload_type) : \"\");\n ss << \", payload_type: \" << payload_type;\n ss << \", format: \" << rtc::ToString(format);\n ss << '}';\n return ss.str();\n}\n\nbool AudioSendStream::Config::SendCodecSpec::operator==(\n const AudioSendStream::Config::SendCodecSpec& rhs) const {\n if (nack_enabled == rhs.nack_enabled &&\n transport_cc_enabled == rhs.transport_cc_enabled &&\n cng_payload_type == rhs.cng_payload_type &&\n payload_type == rhs.payload_type && format == rhs.format &&\n target_bitrate_bps == rhs.target_bitrate_bps) {\n return true;\n }\n return false;\n}\n} \/\/ namespace webrtc\nred: fix SendCodecSpec == operator\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/audio_send_stream.h\"\n\n#include \n\n#include \"rtc_base\/string_encode.h\"\n#include \"rtc_base\/strings\/audio_format_to_string.h\"\n#include \"rtc_base\/strings\/string_builder.h\"\n\nnamespace webrtc {\n\nAudioSendStream::Stats::Stats() = default;\nAudioSendStream::Stats::~Stats() = default;\n\nAudioSendStream::Config::Config(Transport* send_transport)\n : send_transport(send_transport) {}\n\nAudioSendStream::Config::~Config() = default;\n\nstd::string AudioSendStream::Config::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{rtp: \" << rtp.ToString();\n ss << \", rtcp_report_interval_ms: \" << rtcp_report_interval_ms;\n ss << \", send_transport: \" << (send_transport ? \"(Transport)\" : \"null\");\n ss << \", min_bitrate_bps: \" << min_bitrate_bps;\n ss << \", max_bitrate_bps: \" << max_bitrate_bps;\n ss << \", send_codec_spec: \"\n << (send_codec_spec ? send_codec_spec->ToString() : \"\");\n ss << '}';\n return ss.str();\n}\n\nAudioSendStream::Config::Rtp::Rtp() = default;\n\nAudioSendStream::Config::Rtp::~Rtp() = default;\n\nstd::string AudioSendStream::Config::Rtp::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{ssrc: \" << ssrc;\n ss << \", extmap-allow-mixed: \" << (extmap_allow_mixed ? \"true\" : \"false\");\n ss << \", extensions: [\";\n for (size_t i = 0; i < extensions.size(); ++i) {\n ss << extensions[i].ToString();\n if (i != extensions.size() - 1) {\n ss << \", \";\n }\n }\n ss << ']';\n ss << \", c_name: \" << c_name;\n ss << '}';\n return ss.str();\n}\n\nAudioSendStream::Config::SendCodecSpec::SendCodecSpec(\n int payload_type,\n const SdpAudioFormat& format)\n : payload_type(payload_type), format(format) {}\nAudioSendStream::Config::SendCodecSpec::~SendCodecSpec() = default;\n\nstd::string AudioSendStream::Config::SendCodecSpec::ToString() const {\n char buf[1024];\n rtc::SimpleStringBuilder ss(buf);\n ss << \"{nack_enabled: \" << (nack_enabled ? \"true\" : \"false\");\n ss << \", transport_cc_enabled: \" << (transport_cc_enabled ? \"true\" : \"false\");\n ss << \", cng_payload_type: \"\n << (cng_payload_type ? rtc::ToString(*cng_payload_type) : \"\");\n ss << \", red_payload_type: \"\n << (red_payload_type ? rtc::ToString(*red_payload_type) : \"\");\n ss << \", payload_type: \" << payload_type;\n ss << \", format: \" << rtc::ToString(format);\n ss << '}';\n return ss.str();\n}\n\nbool AudioSendStream::Config::SendCodecSpec::operator==(\n const AudioSendStream::Config::SendCodecSpec& rhs) const {\n if (nack_enabled == rhs.nack_enabled &&\n transport_cc_enabled == rhs.transport_cc_enabled &&\n cng_payload_type == rhs.cng_payload_type &&\n red_payload_type == rhs.red_payload_type &&\n payload_type == rhs.payload_type && format == rhs.format &&\n target_bitrate_bps == rhs.target_bitrate_bps) {\n return true;\n }\n return false;\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n\n#include \n\n#include \"sr300.h\"\n#include \"ds5.h\"\n#include \"backend.h\"\n#include \"context.h\"\n#include \"recorder.h\"\n\n#define constexpr_support 1\n\n#ifdef _MSC_VER\n#if (_MSC_VER <= 1800) \/\/ constexpr is not supported in MSVC2013\n#pragma error( \"Librealsense requires MSVC2015 or later to build\" )\n#undef constexpr_support\n#define constexpr_support 0\n#endif\n#endif\n\n#if (constexpr_support == 1)\ntemplate struct seq{};\ntemplate\nstruct gen_seq : gen_seq{};\ntemplate\nstruct gen_seq<0, Is...> : seq{};\n\ntemplate\nconstexpr std::array concat(char const (&a1)[N1], char const (&a2)[N2], seq, seq){\n return {{ a1[I1]..., a2[I2]... }};\n}\n\ntemplate\nconstexpr std::array concat(char const (&a1)[N1], char const (&a2)[N2]){\n return concat(a1, a2, gen_seq{}, gen_seq{});\n}\n\nconstexpr auto rs_api_version = concat(\"VERSION: \",RS_API_VERSION_STR);\n\n#endif\n\nnamespace rsimpl\n{\n context::context(backend_type type, \n const char* filename, \n const char* section, \n rs_recording_mode mode)\n {\n switch(type)\n {\n case backend_type::standard:\n _backend = uvc::create_backend();\n break;\n case backend_type::record:\n _backend = std::make_shared(uvc::create_backend(), filename, section, mode);\n break;\n case backend_type::playback: \n _backend = std::make_shared(filename, section);\n break;\n default: throw invalid_value_exception(to_string() << \"Undefined backend type \" << static_cast(type));\n }\n }\n\n std::vector> context::query_devices() const\n {\n std::vector> list;\n\n auto uvc_devices = _backend->query_uvc_devices();\n auto usb_devices = _backend->query_usb_devices();\n auto hid_devices = _backend->query_hid_devices();\n\n auto sr300_devices = sr300_info::pick_sr300_devices(_backend, uvc_devices, usb_devices);\n std::copy(begin(sr300_devices), end(sr300_devices), std::back_inserter(list));\n\n auto ds5_devices = ds5_info::pick_ds5_devices(_backend, uvc_devices, usb_devices, hid_devices);\n std::copy(begin(ds5_devices), end(ds5_devices), std::back_inserter(list));\n\n auto recovery_devices = recovery_info::pick_recovery_devices(_backend, usb_devices);\n std::copy(begin(recovery_devices), end(recovery_devices), std::back_inserter(list));\n\n return list;\n }\n}\nFix MSVC error that will be raised for MSVC2013 or earlier\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015 Intel Corporation. All Rights Reserved.\n#ifdef _MSC_VER\n#if (_MSC_VER <= 1800) \/\/ constexpr is not supported in MSVC2013\n#error( \"Librealsense requires MSVC2015 or later to build. Compilation will be aborted\" )\n#endif\n#endif\n\n#include \n\n#include \"sr300.h\"\n#include \"ds5.h\"\n#include \"backend.h\"\n#include \"context.h\"\n#include \"recorder.h\"\n\n\ntemplate struct seq{};\ntemplate\nstruct gen_seq : gen_seq{};\ntemplate\nstruct gen_seq<0, Is...> : seq{};\n\ntemplate\nconstexpr std::array concat(char const (&a1)[N1], char const (&a2)[N2], seq, seq){\n return {{ a1[I1]..., a2[I2]... }};\n}\n\ntemplate\nconstexpr std::array concat(char const (&a1)[N1], char const (&a2)[N2]){\n return concat(a1, a2, gen_seq{}, gen_seq{});\n}\n\n\/\/ The string is used to retrieve the version embedded into .so file on Linux\nconstexpr auto rs_api_version = concat(\"VERSION: \",RS_API_VERSION_STR);\n\nnamespace rsimpl\n{\n context::context(backend_type type, \n const char* filename, \n const char* section, \n rs_recording_mode mode)\n {\n switch(type)\n {\n case backend_type::standard:\n _backend = uvc::create_backend();\n break;\n case backend_type::record:\n _backend = std::make_shared(uvc::create_backend(), filename, section, mode);\n break;\n case backend_type::playback: \n _backend = std::make_shared(filename, section);\n break;\n default: throw invalid_value_exception(to_string() << \"Undefined backend type \" << static_cast(type));\n }\n }\n\n std::vector> context::query_devices() const\n {\n std::vector> list;\n\n auto uvc_devices = _backend->query_uvc_devices();\n auto usb_devices = _backend->query_usb_devices();\n auto hid_devices = _backend->query_hid_devices();\n\n auto sr300_devices = sr300_info::pick_sr300_devices(_backend, uvc_devices, usb_devices);\n std::copy(begin(sr300_devices), end(sr300_devices), std::back_inserter(list));\n\n auto ds5_devices = ds5_info::pick_ds5_devices(_backend, uvc_devices, usb_devices, hid_devices);\n std::copy(begin(ds5_devices), end(ds5_devices), std::back_inserter(list));\n\n auto recovery_devices = recovery_info::pick_recovery_devices(_backend, usb_devices);\n std::copy(begin(recovery_devices), end(recovery_devices), std::back_inserter(list));\n\n return list;\n }\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2015 Guy Sherman, Shermann Innovations Limited\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n\/\/ C++ Standard Headers\n#include \n#include \n\n\/\/ C Standard Headers\n#include \n\n\/\/ Boost Headers\n\n\/\/ 3rd Party Headers\n\n\n\/\/ GTK Headers\n\n#include \n#include \"OcpMessageReader.hxx\"\n#include \"Ocp1Header.hxx\"\n#include \"Ocp1Response.hxx\"\n#include \"Ocp1EventData.hxx\"\n\nnamespace oca\n{\n\tOcpMessageReader::OcpMessageReader()\n\t{\n\n\t}\n\n\tOcpMessageReader::~OcpMessageReader()\n\t{\n\n\t}\n\n\n\tconst net::Ocp1Header OcpMessageReader::HeaderFromBuffer(boost::asio::const_buffer& buffer)\n\t{\n\t\tnet::Ocp1Header header;\n\n\t\tHeaderFromBuffer(buffer, header);\n\n\t\treturn header;\n\t}\n\n\tvoid OcpMessageReader::HeaderFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header& header)\n\t{\n\t\t\/\/ Cast the buffer to the type we want, and dereference the pointer\n\t\t\/\/ so that we can read the data.\n\t\theader.protocolVersion = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\t\/\/ Create a new buffer offset from the previous one so that we can\n\t\t\/\/ do the same as above but for the next field\n\t\tboost::asio::const_buffer ms = buffer+sizeof(uint16_t);\n\t\theader.messageSize = ntohl(*(boost::asio::buffer_cast(ms)));\n\n\t\tboost::asio::const_buffer mt = ms+sizeof(uint32_t);\n\t\theader.messageType = (net::OcaMessageType) *(boost::asio::buffer_cast(mt));\n\n\t\tboost::asio::const_buffer mc = mt+sizeof(uint8_t);\n\t\theader.messageCount = ntohs(*(boost::asio::buffer_cast(mc)));\n\t}\n\n\tvoid OcpMessageReader::ParametersFromBuffer(boost::asio::const_buffer& buffer, size_t remainingCommandBytes, net::Ocp1Parameters& parameters)\n\t{\n\t\tparameters.parameterCount = *(boost::asio::buffer_cast(buffer));\n\n\t\tsize_t parameterBufferBytes = (remainingCommandBytes - sizeof(uint8_t));\n\t\tboost::asio::const_buffer paramBuffer = buffer+sizeof(uint8_t);\n\t\t\/\/const uint8_t* params = boost::asio::buffer_cast(paramBuffer);\n\n\t\tbufferToUint8Vector(paramBuffer, parameterBufferBytes, parameters.parameters);\n\n\t\t\/\/ assert (parameters.parameters.size() == 0);\n\t\t\/\/ \/\/ We ask the vector to grow in one hit, so we can memcpy straight after into it\n\t\t\/\/ \/\/ We reserve then resize, rather than just resizing, so that we only get one\n\t\t\/\/ \/\/ allocation, rather than log(n) allocations;\n\t\t\/\/ \/\/ We resize so that the size() value is up to date, and so that the\n\t\t\/\/ \/\/ memory gets initialized to 0.\n\t\t\/\/ parameters.parameters.reserve(parameterBufferBytes);\n\t\t\/\/ parameters.parameters.resize(parameterBufferBytes, 0);\n\t\t\/\/ \/\/ TODO: security issue: we trust that the buffer actually has the right number of bytes #security\n\t\t\/\/ memcpy(¶meters.parameters[0], params, parameterBufferBytes);\n\n\t}\n\n\tvoid OcpMessageReader::bufferToUint8Vector(boost::asio::const_buffer& buffer, size_t numBytes, std::vector& vec)\n\t{\n\t\tassert (vec.size() == 0);\n\n\t\tconst OcaUint8* bytes = boost::asio::buffer_cast(buffer);\n\n\t\t\/\/ We ask the vector to grow in one hit, so we can memcpy straight after into it\n\t\t\/\/ We reserve then resize, rather than just resizing, so that we only get one\n\t\t\/\/ allocation, rather than log(n) allocations;\n\t\t\/\/ We resize so that the size() value is up to date, and so that the\n\t\t\/\/ memory gets initialized to 0.\n\t\tvec.reserve(numBytes);\n\t\tvec.resize(numBytes, 0);\n\t\t\/\/ TODO: security issue: we trust that the buffer actually has the right number of bytes #security\n\t\tmemcpy(&vec[0], bytes, numBytes);\n\t}\n\n\tvoid OcpMessageReader::MethodIdFromBuffer(boost::asio::const_buffer& buffer, OcaMethodId& methodId)\n\t{\n\t\tmethodId.treeLevel = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer mi = buffer + sizeof(OcaUint16);\n\t\tmethodId.methodIndex = ntohs(*(boost::asio::buffer_cast(mi)));\n\t}\n\n\tvoid OcpMessageReader::CommandFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Command& cmd)\n\t{\n\t\tcmd.commandSize = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer handleBuf = buffer + sizeof(OcaUint32);\n\t\tcmd.handle = ntohl(*(boost::asio::buffer_cast(handleBuf)));\n\n\t\tboost::asio::const_buffer targetONoBuffer = handleBuf + sizeof(OcaUint32);\n\t\tcmd.targetONo = ntohl(*(boost::asio::buffer_cast(targetONoBuffer)));\n\n\t\tboost::asio::const_buffer methodIdBuffer = targetONoBuffer + sizeof(OcaONo);\n\t\tMethodIdFromBuffer(methodIdBuffer, cmd.methodId);\n\n\t\tsize_t remainingBytes = cmd.commandSize - (2*sizeof(OcaUint32) + sizeof(OcaONo) + sizeof(OcaMethodId));\n\t\tboost::asio::const_buffer parametersBuffer = methodIdBuffer + sizeof(OcaMethodId);\n\n\t\tParametersFromBuffer(parametersBuffer, remainingBytes, cmd.parameters);\n\t}\n\n\tvoid OcpMessageReader::CommandListFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header header, std::vector& commands)\n\t{\n\t\tboost::asio::const_buffer message = buffer;\n\n\t\tfor (uint16_t i = 0; i < header.messageCount; ++i )\n\t\t{\n\t\t\tnet::Ocp1Command cmd;\n\t\t\tCommandFromBuffer(message, cmd);\n\t\t\tcommands.push_back(cmd);\n\t\t\tmessage = message + cmd.commandSize;\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::ResponseListFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header header, std::vector& responses)\n\t{\n\t\tboost::asio::const_buffer message = buffer;\n\t\tfor (uint16_t i = 0; i < header.messageCount; ++i)\n\t\t{\n\t\t\tnet::Ocp1Response resp;\n\t\t\tResponseFromBuffer(message, resp);\n\t\t\tresponses.push_back(resp);\n\t\t\tmessage = message + resp.responseSize;\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::ResponseFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Response& resp)\n\t{\n\t\tresp.responseSize = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer handleBuf = buffer + sizeof(OcaUint32);\n\t\tresp.handle = ntohl(*(boost::asio::buffer_cast(handleBuf)));\n\n\t\tboost::asio::const_buffer statusCodeBuf = handleBuf + sizeof(OcaUint32);\n\t\tresp.statusCode = *(boost::asio::buffer_cast(statusCodeBuf));\n\n\t\tboost::asio::const_buffer paramsBuf = statusCodeBuf + sizeof(OcaStatus);\n\t\tsize_t remainingBytes = resp.responseSize - (2*sizeof(OcaUint32) + sizeof(OcaStatus));\n\t\tParametersFromBuffer(paramsBuf, remainingBytes, resp.parameters);\n\t}\n\n\tvoid OcpMessageReader::EventIdFromBuffer(boost::asio::const_buffer& buffer, OcaEventId& eventId)\n\t{\n\t\teventId.treeLevel = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer indexBuf = buffer + sizeof(OcaUint16);\n\t\teventId.eventIndex = ntohs(*(boost::asio::buffer_cast(indexBuf)));\n\t}\n\n\tvoid OcpMessageReader::EventFromBuffer(boost::asio::const_buffer& buffer, OcaEvent& event)\n\t{\n\t\tevent.emitterONo = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer idBuffer = buffer + sizeof(OcaONo);\n\t\tEventIdFromBuffer(idBuffer, event.eventId);\n\t}\n\n\tvoid OcpMessageReader::EventDataFromBuffer(boost::asio::const_buffer& buffer, size_t remainingBytes, oca::net::Ocp1EventData& data)\n\t{\n\t\tEventFromBuffer(buffer, data.event);\n\n\t\tboost::asio::const_buffer paramsBuffer = buffer + sizeof(OcaEvent);\n\t\tsize_t parameterBytes = remainingBytes - sizeof(OcaEvent);\n\t\tbufferToUint8Vector(paramsBuffer, parameterBytes, data.eventParameters);\n\n\t}\n\n\tvoid OcpMessageReader::SyncValueReceived(uint8_t* bufferData,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred,\n\t\tboost::function getHeader )\n\t{\n\t\tif (error.value() != boost::system::errc::success)\n\t\t{\n\t\t\t\/\/ TODO: consider an exception here\n\t\t\treturn;\n\t\t}\n\n\n\t\tif (bytesTransferred != 1)\n\t\t{\n\t\t\t\/\/ TODO: consider an exception here\n\t\t\treturn;\n\t\t}\n\n\n\t\t\/\/ TODO: logging\n\n\n\t\tif (bufferData != 0)\n\t\t{\n\t\t\tif (bufferData[0] == 0x3B)\n\t\t\t{\n\t\t\t\tgetHeader();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::Ocp1HeaderReceived(uint8_t* bufferData,\n\t\tuint64_t connectionIdentifier,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred,\n\t\tboost::function getData)\n\t{\n\t\tboost::asio::const_buffer headerBuffer(bufferData, bytesTransferred);\n\n\n\n\t\t\/\/ By convetion we should be removing the per connection header object once we're done\n\t\t\/\/ so if this assert throws we've either forgotten, or we've got a concurrency\n\t\t\/\/ issue.\n\t\tConnectionStateMap::iterator it = perConnectionState.find(connectionIdentifier);\n\t\tassert(it == perConnectionState.end());\n\n\n\n\n\t\toca::net::Ocp1Header header = HeaderFromBuffer(headerBuffer);\n\n\t\tperConnectionState.insert(ConnectionStateMap::value_type(connectionIdentifier, header));\n\n\t\t\/\/ The messageSize property includes the header, but we've\n\t\t\/\/ already got it so we ask for fewer bytes.\n\t\tgetData(header.messageSize - OCP1_HEADER_SIZE);\n\n\t}\n\n\tvoid OcpMessageReader::Ocp1DataReceived(uint8_t* bufferData,\n\t\tuint64_t connectionIdentifier,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred)\n\t{\n\t\t\/\/ Don't really have anything to do here yet...\n\n\n\n\t\t\/\/ ...but before we go, lets clean up\n\t\tConnectionStateMap::iterator it = perConnectionState.find(connectionIdentifier);\n\t\tif (it != perConnectionState.end())\n\t\t{\n\t\t\tperConnectionState.erase(it);\n\t\t}\n\t\treturn;\n\t}\n\n}\n* Cleand up some code that had been commented out.\/*\n Copyright (C) 2015 Guy Sherman, Shermann Innovations Limited\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n\/\/ C++ Standard Headers\n#include \n#include \n\n\/\/ C Standard Headers\n#include \n\n\/\/ Boost Headers\n\n\/\/ 3rd Party Headers\n\n\n\/\/ GTK Headers\n\n#include \n#include \"OcpMessageReader.hxx\"\n#include \"Ocp1Header.hxx\"\n#include \"Ocp1Response.hxx\"\n#include \"Ocp1EventData.hxx\"\n\nnamespace oca\n{\n\tOcpMessageReader::OcpMessageReader()\n\t{\n\n\t}\n\n\tOcpMessageReader::~OcpMessageReader()\n\t{\n\n\t}\n\n\n\tconst net::Ocp1Header OcpMessageReader::HeaderFromBuffer(boost::asio::const_buffer& buffer)\n\t{\n\t\tnet::Ocp1Header header;\n\n\t\tHeaderFromBuffer(buffer, header);\n\n\t\treturn header;\n\t}\n\n\tvoid OcpMessageReader::HeaderFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header& header)\n\t{\n\t\t\/\/ Cast the buffer to the type we want, and dereference the pointer\n\t\t\/\/ so that we can read the data.\n\t\theader.protocolVersion = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\t\/\/ Create a new buffer offset from the previous one so that we can\n\t\t\/\/ do the same as above but for the next field\n\t\tboost::asio::const_buffer ms = buffer+sizeof(uint16_t);\n\t\theader.messageSize = ntohl(*(boost::asio::buffer_cast(ms)));\n\n\t\tboost::asio::const_buffer mt = ms+sizeof(uint32_t);\n\t\theader.messageType = (net::OcaMessageType) *(boost::asio::buffer_cast(mt));\n\n\t\tboost::asio::const_buffer mc = mt+sizeof(uint8_t);\n\t\theader.messageCount = ntohs(*(boost::asio::buffer_cast(mc)));\n\t}\n\n\tvoid OcpMessageReader::ParametersFromBuffer(boost::asio::const_buffer& buffer, size_t remainingCommandBytes, net::Ocp1Parameters& parameters)\n\t{\n\t\tparameters.parameterCount = *(boost::asio::buffer_cast(buffer));\n\n\t\tsize_t parameterBufferBytes = (remainingCommandBytes - sizeof(uint8_t));\n\t\tboost::asio::const_buffer paramBuffer = buffer+sizeof(uint8_t);\n\t\t\/\/const uint8_t* params = boost::asio::buffer_cast(paramBuffer);\n\n\t\tbufferToUint8Vector(paramBuffer, parameterBufferBytes, parameters.parameters);\n\n\t}\n\n\tvoid OcpMessageReader::bufferToUint8Vector(boost::asio::const_buffer& buffer, size_t numBytes, std::vector& vec)\n\t{\n\t\tassert (vec.size() == 0);\n\n\t\tconst OcaUint8* bytes = boost::asio::buffer_cast(buffer);\n\n\t\t\/\/ We ask the vector to grow in one hit, so we can memcpy straight after into it\n\t\t\/\/ We reserve then resize, rather than just resizing, so that we only get one\n\t\t\/\/ allocation, rather than log(n) allocations;\n\t\t\/\/ We resize so that the size() value is up to date, and so that the\n\t\t\/\/ memory gets initialized to 0.\n\t\tvec.reserve(numBytes);\n\t\tvec.resize(numBytes, 0);\n\t\t\/\/ TODO: security issue: we trust that the buffer actually has the right number of bytes #security\n\t\tmemcpy(&vec[0], bytes, numBytes);\n\t}\n\n\tvoid OcpMessageReader::MethodIdFromBuffer(boost::asio::const_buffer& buffer, OcaMethodId& methodId)\n\t{\n\t\tmethodId.treeLevel = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer mi = buffer + sizeof(OcaUint16);\n\t\tmethodId.methodIndex = ntohs(*(boost::asio::buffer_cast(mi)));\n\t}\n\n\tvoid OcpMessageReader::CommandFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Command& cmd)\n\t{\n\t\tcmd.commandSize = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer handleBuf = buffer + sizeof(OcaUint32);\n\t\tcmd.handle = ntohl(*(boost::asio::buffer_cast(handleBuf)));\n\n\t\tboost::asio::const_buffer targetONoBuffer = handleBuf + sizeof(OcaUint32);\n\t\tcmd.targetONo = ntohl(*(boost::asio::buffer_cast(targetONoBuffer)));\n\n\t\tboost::asio::const_buffer methodIdBuffer = targetONoBuffer + sizeof(OcaONo);\n\t\tMethodIdFromBuffer(methodIdBuffer, cmd.methodId);\n\n\t\tsize_t remainingBytes = cmd.commandSize - (2*sizeof(OcaUint32) + sizeof(OcaONo) + sizeof(OcaMethodId));\n\t\tboost::asio::const_buffer parametersBuffer = methodIdBuffer + sizeof(OcaMethodId);\n\n\t\tParametersFromBuffer(parametersBuffer, remainingBytes, cmd.parameters);\n\t}\n\n\tvoid OcpMessageReader::CommandListFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header header, std::vector& commands)\n\t{\n\t\tboost::asio::const_buffer message = buffer;\n\n\t\tfor (uint16_t i = 0; i < header.messageCount; ++i )\n\t\t{\n\t\t\tnet::Ocp1Command cmd;\n\t\t\tCommandFromBuffer(message, cmd);\n\t\t\tcommands.push_back(cmd);\n\t\t\tmessage = message + cmd.commandSize;\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::ResponseListFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Header header, std::vector& responses)\n\t{\n\t\tboost::asio::const_buffer message = buffer;\n\t\tfor (uint16_t i = 0; i < header.messageCount; ++i)\n\t\t{\n\t\t\tnet::Ocp1Response resp;\n\t\t\tResponseFromBuffer(message, resp);\n\t\t\tresponses.push_back(resp);\n\t\t\tmessage = message + resp.responseSize;\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::ResponseFromBuffer(boost::asio::const_buffer& buffer, net::Ocp1Response& resp)\n\t{\n\t\tresp.responseSize = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer handleBuf = buffer + sizeof(OcaUint32);\n\t\tresp.handle = ntohl(*(boost::asio::buffer_cast(handleBuf)));\n\n\t\tboost::asio::const_buffer statusCodeBuf = handleBuf + sizeof(OcaUint32);\n\t\tresp.statusCode = *(boost::asio::buffer_cast(statusCodeBuf));\n\n\t\tboost::asio::const_buffer paramsBuf = statusCodeBuf + sizeof(OcaStatus);\n\t\tsize_t remainingBytes = resp.responseSize - (2*sizeof(OcaUint32) + sizeof(OcaStatus));\n\t\tParametersFromBuffer(paramsBuf, remainingBytes, resp.parameters);\n\t}\n\n\tvoid OcpMessageReader::EventIdFromBuffer(boost::asio::const_buffer& buffer, OcaEventId& eventId)\n\t{\n\t\teventId.treeLevel = ntohs(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer indexBuf = buffer + sizeof(OcaUint16);\n\t\teventId.eventIndex = ntohs(*(boost::asio::buffer_cast(indexBuf)));\n\t}\n\n\tvoid OcpMessageReader::EventFromBuffer(boost::asio::const_buffer& buffer, OcaEvent& event)\n\t{\n\t\tevent.emitterONo = ntohl(*(boost::asio::buffer_cast(buffer)));\n\n\t\tboost::asio::const_buffer idBuffer = buffer + sizeof(OcaONo);\n\t\tEventIdFromBuffer(idBuffer, event.eventId);\n\t}\n\n\tvoid OcpMessageReader::EventDataFromBuffer(boost::asio::const_buffer& buffer, size_t remainingBytes, oca::net::Ocp1EventData& data)\n\t{\n\t\tEventFromBuffer(buffer, data.event);\n\n\t\tboost::asio::const_buffer paramsBuffer = buffer + sizeof(OcaEvent);\n\t\tsize_t parameterBytes = remainingBytes - sizeof(OcaEvent);\n\t\tbufferToUint8Vector(paramsBuffer, parameterBytes, data.eventParameters);\n\n\t}\n\n\tvoid OcpMessageReader::SyncValueReceived(uint8_t* bufferData,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred,\n\t\tboost::function getHeader )\n\t{\n\t\tif (error.value() != boost::system::errc::success)\n\t\t{\n\t\t\t\/\/ TODO: consider an exception here\n\t\t\treturn;\n\t\t}\n\n\n\t\tif (bytesTransferred != 1)\n\t\t{\n\t\t\t\/\/ TODO: consider an exception here\n\t\t\treturn;\n\t\t}\n\n\n\t\t\/\/ TODO: logging\n\n\n\t\tif (bufferData != 0)\n\t\t{\n\t\t\tif (bufferData[0] == 0x3B)\n\t\t\t{\n\t\t\t\tgetHeader();\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid OcpMessageReader::Ocp1HeaderReceived(uint8_t* bufferData,\n\t\tuint64_t connectionIdentifier,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred,\n\t\tboost::function getData)\n\t{\n\t\tboost::asio::const_buffer headerBuffer(bufferData, bytesTransferred);\n\n\n\n\t\t\/\/ By convetion we should be removing the per connection header object once we're done\n\t\t\/\/ so if this assert throws we've either forgotten, or we've got a concurrency\n\t\t\/\/ issue.\n\t\tConnectionStateMap::iterator it = perConnectionState.find(connectionIdentifier);\n\t\tassert(it == perConnectionState.end());\n\n\n\n\n\t\toca::net::Ocp1Header header = HeaderFromBuffer(headerBuffer);\n\n\t\tperConnectionState.insert(ConnectionStateMap::value_type(connectionIdentifier, header));\n\n\t\t\/\/ The messageSize property includes the header, but we've\n\t\t\/\/ already got it so we ask for fewer bytes.\n\t\tgetData(header.messageSize - OCP1_HEADER_SIZE);\n\n\t}\n\n\tvoid OcpMessageReader::Ocp1DataReceived(uint8_t* bufferData,\n\t\tuint64_t connectionIdentifier,\n\t\tconst boost::system::error_code& error,\n\t\tsize_t bytesTransferred)\n\t{\n\t\t\/\/ Don't really have anything to do here yet...\n\n\n\n\t\t\/\/ ...but before we go, lets clean up\n\t\tConnectionStateMap::iterator it = perConnectionState.find(connectionIdentifier);\n\t\tif (it != perConnectionState.end())\n\t\t{\n\t\t\tperConnectionState.erase(it);\n\t\t}\n\t\treturn;\n\t}\n\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"publish\/settings.h\"\n\n#include \n#include \n#include \n\n#include \"options.h\"\n#include \"publish\/except.h\"\n#include \"publish\/repository.h\"\n#include \"sanitizer.h\"\n#include \"util\/posix.h\"\n#include \"util\/string.h\"\n\nnamespace publish {\n\nvoid SettingsSpoolArea::UseSystemTempDir() {\n if (getenv(\"TMPDIR\") != NULL)\n tmp_dir_ = getenv(\"TMPDIR\");\n else\n tmp_dir_ = \"\/tmp\";\n}\n\nvoid SettingsSpoolArea::SetSpoolArea(const std::string &path) {\n workspace_ = path;\n tmp_dir_ = workspace_() + \"\/tmp\";\n}\n\nvoid SettingsSpoolArea::SetUnionMount(const std::string &path) {\n union_mnt_ = path;\n}\n\nvoid SettingsSpoolArea::SetRepairMode(const EUnionMountRepairMode val) {\n repair_mode_ = val;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nvoid SettingsTransaction::SetUnionFsType(const std::string &union_fs) {\n if (union_fs == \"aufs\") {\n union_fs_ = kUnionFsAufs;\n } else if ((union_fs == \"overlay\") || (union_fs == \"overlayfs\")) {\n union_fs_ = kUnionFsOverlay;\n } else if (union_fs == \"tarball\") {\n union_fs_ = kUnionFsTarball;\n } else {\n throw EPublish(\"unsupported union file system: \" + union_fs);\n }\n}\n\nvoid SettingsTransaction::DetectUnionFsType() {\n \/\/ TODO(jblomer): shall we switch the order?\n if (DirectoryExists(\"\/sys\/fs\/aufs\")) {\n union_fs_ = kUnionFsAufs;\n return;\n }\n \/\/ TODO(jblomer): modprobe aufs, try again\n if (DirectoryExists(\"\/sys\/module\/overlay\")) {\n union_fs_ = kUnionFsOverlay;\n return;\n }\n \/\/ TODO(jblomer): modprobe overlay, try again\n throw EPublish(\"neither AUFS nor OverlayFS detected on the system\");\n}\n\nbool SettingsTransaction::ValidateUnionFs() {\n \/\/ TODO(jblomer)\n return true;\n}\n\nvoid SettingsTransaction::SetTimeout(unsigned seconds) {\n timeout_s_ = seconds;\n}\n\nvoid SettingsTransaction::SetLeasePath(const std::string &path) {\n lease_path_ = path;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\nstd::string SettingsStorage::GetLocator() const {\n return std::string(upload::SpoolerDefinition::kDriverNames[type_]) +\n \",\" + tmp_dir_() +\n \",\" + endpoint_();\n}\n\nvoid SettingsStorage::MakeS3(\n const std::string &s3_config,\n const std::string &tmp_dir)\n{\n type_ = upload::SpoolerDefinition::S3;\n tmp_dir_ = tmp_dir;\n endpoint_ = \"cvmfs\/\" + fqrn_() + \"@\" + s3_config;\n}\n\nvoid SettingsStorage::MakeLocal(const std::string &path) {\n type_ = upload::SpoolerDefinition::Local;\n endpoint_ = path;\n tmp_dir_ = path + \"\/data\/txn\";\n}\n\nvoid SettingsStorage::MakeGateway(\n const std::string &host,\n unsigned int port,\n const std::string &tmp_dir)\n{\n type_ = upload::SpoolerDefinition::Gateway;\n endpoint_ = \"http:\/\/\" + host + \":\" + StringifyInt(port) + \"\/api\/v1\";\n tmp_dir_ = tmp_dir_;\n}\n\nvoid SettingsStorage::SetLocator(const std::string &locator) {\n std::vector tokens = SplitString(locator, ',');\n if (tokens.size() != 3) {\n throw EPublish(\"malformed storage locator, expected format is \"\n \",,\");\n }\n if (tokens[0] == \"local\") {\n type_ = upload::SpoolerDefinition::Local;\n } else if (tokens[0] == \"S3\") {\n type_ = upload::SpoolerDefinition::S3;\n } else if (tokens[0] == \"gw\") {\n type_ = upload::SpoolerDefinition::Gateway;\n } else {\n throw EPublish(\"unsupported storage type: \" + tokens[0]);\n }\n tmp_dir_ = tokens[1];\n endpoint_ = tokens[2];\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nvoid SettingsKeychain::SetKeychainDir(const std::string &keychain_dir) {\n keychain_dir_ = keychain_dir;\n master_private_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".masterkey\";\n master_public_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".pub\";\n private_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".key\";\n certificate_path_ = keychain_dir + \"\/\" + fqrn_() + \".crt\";\n gw_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".gw\";\n}\n\n\nbool SettingsKeychain::HasDanglingMasterKeys() const {\n return (FileExists(master_private_key_path_) &&\n !FileExists(master_public_key_path_)) ||\n (!FileExists(master_private_key_path_) &&\n FileExists(master_public_key_path_));\n}\n\n\nbool SettingsKeychain::HasMasterKeys() const {\n return FileExists(master_private_key_path_) &&\n FileExists(master_public_key_path_);\n}\n\n\nbool SettingsKeychain::HasDanglingRepositoryKeys() const {\n return (FileExists(private_key_path_) &&\n !FileExists(certificate_path_)) ||\n (!FileExists(private_key_path_) &&\n FileExists(certificate_path_));\n}\n\n\nbool SettingsKeychain::HasRepositoryKeys() const {\n return FileExists(private_key_path_) &&\n FileExists(certificate_path_);\n}\n\nbool SettingsKeychain::HasGatewayKey() const {\n return FileExists(gw_key_path_);\n}\n\n\/\/------------------------------------------------------------------------------\n\n\nSettingsRepository::SettingsRepository(\n const SettingsPublisher &settings_publisher)\n : fqrn_(settings_publisher.fqrn())\n , url_(settings_publisher.url())\n , tmp_dir_(settings_publisher.transaction().spool_area().tmp_dir())\n , keychain_(settings_publisher.fqrn())\n{\n keychain_.SetKeychainDir(settings_publisher.keychain().keychain_dir());\n}\n\n\nvoid SettingsRepository::SetUrl(const std::string &url) {\n \/\/ TODO(jblomer): sanitiation, check availability\n url_ = url;\n}\n\n\nvoid SettingsRepository::SetTmpDir(const std::string &tmp_dir) {\n tmp_dir_ = tmp_dir;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nconst unsigned SettingsPublisher::kDefaultWhitelistValidity = 30;\n\n\nSettingsPublisher::SettingsPublisher(\n const SettingsRepository &settings_repository)\n : fqrn_(settings_repository.fqrn())\n , url_(settings_repository.url())\n , owner_uid_(0)\n , owner_gid_(0)\n , whitelist_validity_days_(kDefaultWhitelistValidity)\n , is_silent_(false)\n , is_managed_(false)\n , storage_(fqrn_)\n , transaction_(fqrn_)\n , keychain_(fqrn_)\n{\n keychain_.SetKeychainDir(settings_repository.keychain().keychain_dir());\n}\n\n\nvoid SettingsPublisher::SetUrl(const std::string &url) {\n \/\/ TODO(jblomer): sanitiation, check availability\n url_ = url;\n}\n\n\nvoid SettingsPublisher::SetOwner(const std::string &user_name) {\n bool retval = GetUidOf(user_name, owner_uid_.GetPtr(), owner_gid_.GetPtr());\n if (!retval) {\n throw EPublish(\"unknown user name for repository owner\");\n }\n}\n\nvoid SettingsPublisher::SetOwner(uid_t uid, gid_t gid) {\n owner_uid_ = uid;\n owner_gid_ = gid;\n}\n\nvoid SettingsPublisher::SetIsSilent(bool value) {\n is_silent_ = value;\n}\n\nvoid SettingsPublisher::SetIsManaged(bool value) {\n is_managed_ = value;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSettingsBuilder::~SettingsBuilder() {\n delete options_mgr_;\n}\n\n\nstd::string SettingsBuilder::GetSingleAlias() {\n std::vector repositories = FindDirectories(config_path_);\n if (repositories.empty())\n throw EPublish(\"no repositories available in \" + config_path_);\n if (repositories.size() > 1)\n throw EPublish(\"multiple repositories available in \" + config_path_);\n return GetFileName(repositories[0]);\n}\n\n\nSettingsRepository SettingsBuilder::CreateSettingsRepository(\n const std::string &ident)\n{\n if (HasPrefix(ident, \"http:\/\/\", true \/* ignore case *\/) ||\n HasPrefix(ident, \"https:\/\/\", true \/* ignore case *\/) ||\n HasPrefix(ident, \"file:\/\/\", true \/* ignore case *\/))\n {\n std::string fqrn = Repository::GetFqrnFromUrl(ident);\n sanitizer::RepositorySanitizer sanitizer;\n if (!sanitizer.IsValid(fqrn)) {\n throw EPublish(\"malformed repository name: \" + fqrn);\n }\n SettingsRepository settings(fqrn);\n settings.SetUrl(ident);\n return settings;\n }\n\n std::string alias = ident.empty() ? GetSingleAlias() : ident;\n std::string repo_path = config_path_ + \"\/\" + alias;\n std::string server_path = repo_path + \"\/server.conf\";\n std::string replica_path = repo_path + \"\/replica.conf\";\n std::string fqrn = alias;\n\n delete options_mgr_;\n options_mgr_ = new BashOptionsManager();\n std::string arg;\n options_mgr_->set_taint_environment(false);\n options_mgr_->ParsePath(server_path, false \/* external *\/);\n options_mgr_->ParsePath(replica_path, false \/* external *\/);\n if (options_mgr_->GetValue(\"CVMFS_REPOSITORY_NAME\", &arg))\n fqrn = arg;\n SettingsRepository settings(fqrn);\n\n if (options_mgr_->GetValue(\"CVMFS_PUBLIC_KEY\", &arg))\n settings.GetKeychain()->SetKeychainDir(arg);\n if (options_mgr_->GetValue(\"CVMFS_STRATUM0\", &arg))\n settings.SetUrl(arg);\n \/\/ For a replica, the stratum 1 url is the \"local\" location, hence it takes\n \/\/ precedence over the stratum 0 url\n if (options_mgr_->GetValue(\"CVMFS_STRATUM1\", &arg))\n settings.SetUrl(arg);\n if (options_mgr_->GetValue(\"CVMFS_SPOOL_DIR\", &arg))\n settings.SetTmpDir(arg + \"\/tmp\");\n\n return settings;\n}\n\n\nSettingsPublisher SettingsBuilder::CreateSettingsPublisher(\n const std::string &ident, bool needs_managed)\n{\n SettingsRepository settings_repository = CreateSettingsRepository(ident);\n if (needs_managed && !IsManagedRepository())\n throw EPublish(\"remote repositories are not supported in this context\");\n\n if (options_mgr_->GetValueOrDie(\"CVMFS_REPOSITORY_TYPE\") != \"stratum0\")\n throw EPublish(\"Not a stratum 0 repository\");\n\n SettingsPublisher settings_publisher(settings_repository);\n settings_publisher.SetIsManaged(IsManagedRepository());\n settings_publisher.SetOwner(options_mgr_->GetValueOrDie(\"CVMFS_USER\"));\n settings_publisher.GetStorage()->SetLocator(\n options_mgr_->GetValueOrDie(\"CVMFS_UPSTREAM_STORAGE\"));\n\n std::string arg;\n if (options_mgr_->GetValue(\"CVMFS_AUTO_REPAIR_MOUNTPOINT\", &arg)) {\n if (!options_mgr_->IsOn(arg)) {\n settings_publisher.GetTransaction()->GetSpoolArea()->SetRepairMode(\n kUnionMountRepairNever);\n }\n }\n\n \/\/ TODO(jblomer): process other parameters\n\n return settings_publisher;\n}\n\n} \/\/ namespace publish\nManage case when we don't find the server.conf configuratio file.\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"publish\/settings.h\"\n\n#include \n#include \n#include \n\n#include \"options.h\"\n#include \"publish\/except.h\"\n#include \"publish\/repository.h\"\n#include \"sanitizer.h\"\n#include \"util\/posix.h\"\n#include \"util\/string.h\"\n\nnamespace publish {\n\nvoid SettingsSpoolArea::UseSystemTempDir() {\n if (getenv(\"TMPDIR\") != NULL)\n tmp_dir_ = getenv(\"TMPDIR\");\n else\n tmp_dir_ = \"\/tmp\";\n}\n\nvoid SettingsSpoolArea::SetSpoolArea(const std::string &path) {\n workspace_ = path;\n tmp_dir_ = workspace_() + \"\/tmp\";\n}\n\nvoid SettingsSpoolArea::SetUnionMount(const std::string &path) {\n union_mnt_ = path;\n}\n\nvoid SettingsSpoolArea::SetRepairMode(const EUnionMountRepairMode val) {\n repair_mode_ = val;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nvoid SettingsTransaction::SetUnionFsType(const std::string &union_fs) {\n if (union_fs == \"aufs\") {\n union_fs_ = kUnionFsAufs;\n } else if ((union_fs == \"overlay\") || (union_fs == \"overlayfs\")) {\n union_fs_ = kUnionFsOverlay;\n } else if (union_fs == \"tarball\") {\n union_fs_ = kUnionFsTarball;\n } else {\n throw EPublish(\"unsupported union file system: \" + union_fs);\n }\n}\n\nvoid SettingsTransaction::DetectUnionFsType() {\n \/\/ TODO(jblomer): shall we switch the order?\n if (DirectoryExists(\"\/sys\/fs\/aufs\")) {\n union_fs_ = kUnionFsAufs;\n return;\n }\n \/\/ TODO(jblomer): modprobe aufs, try again\n if (DirectoryExists(\"\/sys\/module\/overlay\")) {\n union_fs_ = kUnionFsOverlay;\n return;\n }\n \/\/ TODO(jblomer): modprobe overlay, try again\n throw EPublish(\"neither AUFS nor OverlayFS detected on the system\");\n}\n\nbool SettingsTransaction::ValidateUnionFs() {\n \/\/ TODO(jblomer)\n return true;\n}\n\nvoid SettingsTransaction::SetTimeout(unsigned seconds) {\n timeout_s_ = seconds;\n}\n\nvoid SettingsTransaction::SetLeasePath(const std::string &path) {\n lease_path_ = path;\n}\n\n\/\/------------------------------------------------------------------------------\n\n\nstd::string SettingsStorage::GetLocator() const {\n return std::string(upload::SpoolerDefinition::kDriverNames[type_]) +\n \",\" + tmp_dir_() +\n \",\" + endpoint_();\n}\n\nvoid SettingsStorage::MakeS3(\n const std::string &s3_config,\n const std::string &tmp_dir)\n{\n type_ = upload::SpoolerDefinition::S3;\n tmp_dir_ = tmp_dir;\n endpoint_ = \"cvmfs\/\" + fqrn_() + \"@\" + s3_config;\n}\n\nvoid SettingsStorage::MakeLocal(const std::string &path) {\n type_ = upload::SpoolerDefinition::Local;\n endpoint_ = path;\n tmp_dir_ = path + \"\/data\/txn\";\n}\n\nvoid SettingsStorage::MakeGateway(\n const std::string &host,\n unsigned int port,\n const std::string &tmp_dir)\n{\n type_ = upload::SpoolerDefinition::Gateway;\n endpoint_ = \"http:\/\/\" + host + \":\" + StringifyInt(port) + \"\/api\/v1\";\n tmp_dir_ = tmp_dir_;\n}\n\nvoid SettingsStorage::SetLocator(const std::string &locator) {\n std::vector tokens = SplitString(locator, ',');\n if (tokens.size() != 3) {\n throw EPublish(\"malformed storage locator, expected format is \"\n \",,\");\n }\n if (tokens[0] == \"local\") {\n type_ = upload::SpoolerDefinition::Local;\n } else if (tokens[0] == \"S3\") {\n type_ = upload::SpoolerDefinition::S3;\n } else if (tokens[0] == \"gw\") {\n type_ = upload::SpoolerDefinition::Gateway;\n } else {\n throw EPublish(\"unsupported storage type: \" + tokens[0]);\n }\n tmp_dir_ = tokens[1];\n endpoint_ = tokens[2];\n}\n\n\n\/\/------------------------------------------------------------------------------\n\nvoid SettingsKeychain::SetKeychainDir(const std::string &keychain_dir) {\n keychain_dir_ = keychain_dir;\n master_private_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".masterkey\";\n master_public_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".pub\";\n private_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".key\";\n certificate_path_ = keychain_dir + \"\/\" + fqrn_() + \".crt\";\n gw_key_path_ = keychain_dir + \"\/\" + fqrn_() + \".gw\";\n}\n\n\nbool SettingsKeychain::HasDanglingMasterKeys() const {\n return (FileExists(master_private_key_path_) &&\n !FileExists(master_public_key_path_)) ||\n (!FileExists(master_private_key_path_) &&\n FileExists(master_public_key_path_));\n}\n\n\nbool SettingsKeychain::HasMasterKeys() const {\n return FileExists(master_private_key_path_) &&\n FileExists(master_public_key_path_);\n}\n\n\nbool SettingsKeychain::HasDanglingRepositoryKeys() const {\n return (FileExists(private_key_path_) &&\n !FileExists(certificate_path_)) ||\n (!FileExists(private_key_path_) &&\n FileExists(certificate_path_));\n}\n\n\nbool SettingsKeychain::HasRepositoryKeys() const {\n return FileExists(private_key_path_) &&\n FileExists(certificate_path_);\n}\n\nbool SettingsKeychain::HasGatewayKey() const {\n return FileExists(gw_key_path_);\n}\n\n\/\/------------------------------------------------------------------------------\n\n\nSettingsRepository::SettingsRepository(\n const SettingsPublisher &settings_publisher)\n : fqrn_(settings_publisher.fqrn())\n , url_(settings_publisher.url())\n , tmp_dir_(settings_publisher.transaction().spool_area().tmp_dir())\n , keychain_(settings_publisher.fqrn())\n{\n keychain_.SetKeychainDir(settings_publisher.keychain().keychain_dir());\n}\n\n\nvoid SettingsRepository::SetUrl(const std::string &url) {\n \/\/ TODO(jblomer): sanitiation, check availability\n url_ = url;\n}\n\n\nvoid SettingsRepository::SetTmpDir(const std::string &tmp_dir) {\n tmp_dir_ = tmp_dir;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nconst unsigned SettingsPublisher::kDefaultWhitelistValidity = 30;\n\n\nSettingsPublisher::SettingsPublisher(\n const SettingsRepository &settings_repository)\n : fqrn_(settings_repository.fqrn())\n , url_(settings_repository.url())\n , owner_uid_(0)\n , owner_gid_(0)\n , whitelist_validity_days_(kDefaultWhitelistValidity)\n , is_silent_(false)\n , is_managed_(false)\n , storage_(fqrn_)\n , transaction_(fqrn_)\n , keychain_(fqrn_)\n{\n keychain_.SetKeychainDir(settings_repository.keychain().keychain_dir());\n}\n\n\nvoid SettingsPublisher::SetUrl(const std::string &url) {\n \/\/ TODO(jblomer): sanitiation, check availability\n url_ = url;\n}\n\n\nvoid SettingsPublisher::SetOwner(const std::string &user_name) {\n bool retval = GetUidOf(user_name, owner_uid_.GetPtr(), owner_gid_.GetPtr());\n if (!retval) {\n throw EPublish(\"unknown user name for repository owner\");\n }\n}\n\nvoid SettingsPublisher::SetOwner(uid_t uid, gid_t gid) {\n owner_uid_ = uid;\n owner_gid_ = gid;\n}\n\nvoid SettingsPublisher::SetIsSilent(bool value) {\n is_silent_ = value;\n}\n\nvoid SettingsPublisher::SetIsManaged(bool value) {\n is_managed_ = value;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSettingsBuilder::~SettingsBuilder() {\n delete options_mgr_;\n}\n\n\nstd::string SettingsBuilder::GetSingleAlias() {\n std::vector repositories = FindDirectories(config_path_);\n if (repositories.empty())\n throw EPublish(\"no repositories available in \" + config_path_);\n if (repositories.size() > 1)\n throw EPublish(\"multiple repositories available in \" + config_path_);\n return GetFileName(repositories[0]);\n}\n\n\nSettingsRepository SettingsBuilder::CreateSettingsRepository(\n const std::string &ident)\n{\n if (HasPrefix(ident, \"http:\/\/\", true \/* ignore case *\/) ||\n HasPrefix(ident, \"https:\/\/\", true \/* ignore case *\/) ||\n HasPrefix(ident, \"file:\/\/\", true \/* ignore case *\/))\n {\n std::string fqrn = Repository::GetFqrnFromUrl(ident);\n sanitizer::RepositorySanitizer sanitizer;\n if (!sanitizer.IsValid(fqrn)) {\n throw EPublish(\"malformed repository name: \" + fqrn);\n }\n SettingsRepository settings(fqrn);\n settings.SetUrl(ident);\n return settings;\n }\n\n std::string alias = ident.empty() ? GetSingleAlias() : ident;\n std::string repo_path = config_path_ + \"\/\" + alias;\n std::string server_path = repo_path + \"\/server.conf\";\n std::string replica_path = repo_path + \"\/replica.conf\";\n std::string fqrn = alias;\n\n delete options_mgr_;\n options_mgr_ = new BashOptionsManager();\n std::string arg;\n options_mgr_->set_taint_environment(false);\n options_mgr_->ParsePath(server_path, false \/* external *\/);\n options_mgr_->ParsePath(replica_path, false \/* external *\/);\n if (options_mgr_->GetValue(\"CVMFS_REPOSITORY_NAME\", &arg))\n fqrn = arg;\n SettingsRepository settings(fqrn);\n\n if (options_mgr_->GetValue(\"CVMFS_PUBLIC_KEY\", &arg))\n settings.GetKeychain()->SetKeychainDir(arg);\n if (options_mgr_->GetValue(\"CVMFS_STRATUM0\", &arg))\n settings.SetUrl(arg);\n \/\/ For a replica, the stratum 1 url is the \"local\" location, hence it takes\n \/\/ precedence over the stratum 0 url\n if (options_mgr_->GetValue(\"CVMFS_STRATUM1\", &arg))\n settings.SetUrl(arg);\n if (options_mgr_->GetValue(\"CVMFS_SPOOL_DIR\", &arg))\n settings.SetTmpDir(arg + \"\/tmp\");\n\n return settings;\n}\n\n\nSettingsPublisher SettingsBuilder::CreateSettingsPublisher(\n const std::string &ident, bool needs_managed)\n{\n \/\/ we are creating a publisher, it need to have the `server.conf` file\n \/\/ present, otherwise something is wrong and we should exit early\n const std::string alias(ident.empty() ? GetSingleAlias() : ident);\n const std::string server_path = config_path_ + \"\/\" + alias + \"\/server.conf\";\n\n if (FileExists(server_path) == false)\n throw EPublish(\n \"Unable to find the configuration file `server.conf` for the cvmfs \"\n \"publisher\");\n\n SettingsRepository settings_repository = CreateSettingsRepository(alias);\n if (needs_managed && !IsManagedRepository())\n throw EPublish(\"remote repositories are not supported in this context\");\n\n if (options_mgr_->GetValueOrDie(\"CVMFS_REPOSITORY_TYPE\") != \"stratum0\")\n throw EPublish(\"Not a stratum 0 repository\");\n\n SettingsPublisher settings_publisher(settings_repository);\n settings_publisher.SetIsManaged(IsManagedRepository());\n settings_publisher.SetOwner(options_mgr_->GetValueOrDie(\"CVMFS_USER\"));\n settings_publisher.GetStorage()->SetLocator(\n options_mgr_->GetValueOrDie(\"CVMFS_UPSTREAM_STORAGE\"));\n\n std::string arg;\n if (options_mgr_->GetValue(\"CVMFS_AUTO_REPAIR_MOUNTPOINT\", &arg)) {\n if (!options_mgr_->IsOn(arg)) {\n settings_publisher.GetTransaction()->GetSpoolArea()->SetRepairMode(\n kUnionMountRepairNever);\n }\n }\n\n \/\/ TODO(jblomer): process other parameters\n\n return settings_publisher;\n}\n\n} \/\/ namespace publish\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (C) 2016 Felix Rohrbach \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"syncjob.h\"\n\n#include \n\nusing namespace QMatrixClient;\n\nstatic size_t jobId = 0;\n\nSyncJob::SyncJob(const ConnectionData* connection, const QString& since,\n const QString& filter, int timeout, const QString& presence)\n : BaseJob(connection, HttpVerb::Get, QString(\"SyncJob-%1\").arg(++jobId),\n \"_matrix\/client\/r0\/sync\")\n{\n setLoggingCategory(SYNCJOB);\n QUrlQuery query;\n if( !filter.isEmpty() )\n query.addQueryItem(\"filter\", filter);\n if( !presence.isEmpty() )\n query.addQueryItem(\"set_presence\", presence);\n if( timeout >= 0 )\n query.addQueryItem(\"timeout\", QString::number(timeout));\n if( !since.isEmpty() )\n query.addQueryItem(\"since\", since);\n setRequestQuery(query);\n\n setMaxRetries(std::numeric_limits::max());\n}\n\nQString SyncData::nextBatch() const\n{\n return nextBatch_;\n}\n\nSyncDataList&& SyncData::takeRoomData()\n{\n return std::move(roomData);\n}\n\nBaseJob::Status SyncJob::parseJson(const QJsonDocument& data)\n{\n return d.parseJson(data);\n}\n\nBaseJob::Status SyncData::parseJson(const QJsonDocument &data) {\n QElapsedTimer et; et.start();\n QJsonObject json = data.object();\n nextBatch_ = json.value(\"next_batch\").toString();\n \/\/ TODO: presence\n \/\/ TODO: account_data\n QJsonObject rooms = json.value(\"rooms\").toObject();\n\n const struct { QString jsonKey; JoinState enumVal; } roomStates[]\n {\n { \"join\", JoinState::Join },\n { \"invite\", JoinState::Invite },\n { \"leave\", JoinState::Leave }\n };\n for (auto roomState: roomStates)\n {\n const QJsonObject rs = rooms.value(roomState.jsonKey).toObject();\n \/\/ We have a Qt container on the right and an STL one on the left\n roomData.reserve(static_cast(rs.size()));\n for( auto rkey: rs.keys() )\n roomData.emplace_back(rkey, roomState.enumVal, rs[rkey].toObject());\n }\n qCDebug(PROFILER) << \"*** SyncData::parseJson():\" << et.elapsed() << \"ms\";\n return BaseJob::Success;\n}\n\nSyncRoomData::SyncRoomData(const QString& roomId_, JoinState joinState_,\n const QJsonObject& room_)\n : roomId(roomId_)\n , joinState(joinState_)\n , state(\"state\")\n , timeline(\"timeline\")\n , ephemeral(\"ephemeral\")\n , accountData(\"account_data\")\n , inviteState(\"invite_state\")\n{\n switch (joinState) {\n case JoinState::Invite:\n inviteState.fromJson(room_);\n break;\n case JoinState::Join:\n state.fromJson(room_);\n timeline.fromJson(room_);\n ephemeral.fromJson(room_);\n accountData.fromJson(room_);\n break;\n case JoinState::Leave:\n state.fromJson(room_);\n timeline.fromJson(room_);\n break;\n default:\n qCWarning(SYNCJOB) << \"SyncRoomData: Unknown JoinState value, ignoring:\" << int(joinState);\n }\n\n QJsonObject timeline = room_.value(\"timeline\").toObject();\n timelineLimited = timeline.value(\"limited\").toBool();\n timelinePrevBatch = timeline.value(\"prev_batch\").toString();\n\n QJsonObject unread = room_.value(\"unread_notifications\").toObject();\n highlightCount = unread.value(\"highlight_count\").toInt();\n notificationCount = unread.value(\"notification_count\").toInt();\n qCDebug(SYNCJOB) << \"Highlights: \" << highlightCount << \" Notifications:\" << notificationCount;\n}\nMinor optimisations in sync data parsing\/******************************************************************************\n * Copyright (C) 2016 Felix Rohrbach \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"syncjob.h\"\n\n#include \n\nusing namespace QMatrixClient;\n\nstatic size_t jobId = 0;\n\nSyncJob::SyncJob(const ConnectionData* connection, const QString& since,\n const QString& filter, int timeout, const QString& presence)\n : BaseJob(connection, HttpVerb::Get, QString(\"SyncJob-%1\").arg(++jobId),\n \"_matrix\/client\/r0\/sync\")\n{\n setLoggingCategory(SYNCJOB);\n QUrlQuery query;\n if( !filter.isEmpty() )\n query.addQueryItem(\"filter\", filter);\n if( !presence.isEmpty() )\n query.addQueryItem(\"set_presence\", presence);\n if( timeout >= 0 )\n query.addQueryItem(\"timeout\", QString::number(timeout));\n if( !since.isEmpty() )\n query.addQueryItem(\"since\", since);\n setRequestQuery(query);\n\n setMaxRetries(std::numeric_limits::max());\n}\n\nQString SyncData::nextBatch() const\n{\n return nextBatch_;\n}\n\nSyncDataList&& SyncData::takeRoomData()\n{\n return std::move(roomData);\n}\n\nBaseJob::Status SyncJob::parseJson(const QJsonDocument& data)\n{\n return d.parseJson(data);\n}\n\nBaseJob::Status SyncData::parseJson(const QJsonDocument &data)\n{\n QElapsedTimer et; et.start();\n\n QJsonObject json = data.object();\n nextBatch_ = json.value(\"next_batch\").toString();\n \/\/ TODO: presence\n \/\/ TODO: account_data\n QJsonObject rooms = json.value(\"rooms\").toObject();\n\n static const struct { QString jsonKey; JoinState enumVal; } roomStates[]\n {\n { \"join\", JoinState::Join },\n { \"invite\", JoinState::Invite },\n { \"leave\", JoinState::Leave }\n };\n for (const auto& roomState: roomStates)\n {\n const QJsonObject rs = rooms.value(roomState.jsonKey).toObject();\n \/\/ We have a Qt container on the right and an STL one on the left\n roomData.reserve(static_cast(rs.size()));\n for(auto roomIt = rs.begin(); roomIt != rs.end(); ++roomIt)\n roomData.emplace_back(roomIt.key(), roomState.enumVal,\n roomIt.value().toObject());\n }\n qCDebug(PROFILER) << \"*** SyncData::parseJson():\" << et.elapsed() << \"ms\";\n return BaseJob::Success;\n}\n\nSyncRoomData::SyncRoomData(const QString& roomId_, JoinState joinState_,\n const QJsonObject& room_)\n : roomId(roomId_)\n , joinState(joinState_)\n , state(\"state\")\n , timeline(\"timeline\")\n , ephemeral(\"ephemeral\")\n , accountData(\"account_data\")\n , inviteState(\"invite_state\")\n{\n switch (joinState) {\n case JoinState::Invite:\n inviteState.fromJson(room_);\n break;\n case JoinState::Join:\n state.fromJson(room_);\n timeline.fromJson(room_);\n ephemeral.fromJson(room_);\n accountData.fromJson(room_);\n break;\n case JoinState::Leave:\n state.fromJson(room_);\n timeline.fromJson(room_);\n break;\n default:\n qCWarning(SYNCJOB) << \"SyncRoomData: Unknown JoinState value, ignoring:\" << int(joinState);\n }\n\n QJsonObject timeline = room_.value(\"timeline\").toObject();\n timelineLimited = timeline.value(\"limited\").toBool();\n timelinePrevBatch = timeline.value(\"prev_batch\").toString();\n\n QJsonObject unread = room_.value(\"unread_notifications\").toObject();\n highlightCount = unread.value(\"highlight_count\").toInt();\n notificationCount = unread.value(\"notification_count\").toInt();\n qCDebug(SYNCJOB) << \"Highlights: \" << highlightCount << \" Notifications:\" << notificationCount;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"filelib.h\"\n#include \"decoder.h\"\n#include \"ff_register.h\"\n#include \"verbose.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n register_feature_functions();\n Decoder decoder(argc, argv);\n\n const string input = decoder.GetConf()[\"input\"].as();\n const bool show_feature_dictionary = decoder.GetConf().count(\"show_feature_dictionary\");\n if (!SILENT) cerr << \"Reading input from \" << ((input == \"-\") ? \"STDIN\" : input.c_str()) << endl;\n ReadFile in_read(input);\n istream *in = in_read.stream();\n assert(*in);\n\n string buf;\n#ifdef CP_TIME\n clock_t time_cp(0);\/\/, end_cp;\n#endif\n while(*in) {\n getline(*in, buf);\n if (buf.empty()) continue;\n decoder.Decode(buf);\n }\n#ifdef CP_TIME\n cerr << \"Time required for Cube Pruning execution: \"\n << CpTime::Get()\n << \" seconds.\" << \"\\n\\n\";\n#endif\n if (show_feature_dictionary) {\n int num = FD::NumFeats();\n for (int i = 1; i < num; ++i) {\n cout << FD::Convert(i) << endl;\n }\n }\n return 0;\n}\n\nAdd memory size logging#include \n\n#include \"filelib.h\"\n#include \"decoder.h\"\n#include \"ff_register.h\"\n#include \"verbose.h\"\n#include \"util\/usage.hh\"\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n register_feature_functions();\n Decoder decoder(argc, argv);\n\n const string input = decoder.GetConf()[\"input\"].as();\n const bool show_feature_dictionary = decoder.GetConf().count(\"show_feature_dictionary\");\n if (!SILENT) cerr << \"Reading input from \" << ((input == \"-\") ? \"STDIN\" : input.c_str()) << endl;\n ReadFile in_read(input);\n istream *in = in_read.stream();\n assert(*in);\n\n string buf;\n#ifdef CP_TIME\n clock_t time_cp(0);\/\/, end_cp;\n#endif\n while(*in) {\n getline(*in, buf);\n if (buf.empty()) continue;\n decoder.Decode(buf);\n }\n#ifdef CP_TIME\n cerr << \"Time required for Cube Pruning execution: \"\n << CpTime::Get()\n << \" seconds.\" << \"\\n\\n\";\n#endif\n if (show_feature_dictionary) {\n int num = FD::NumFeats();\n for (int i = 1; i < num; ++i) {\n cout << FD::Convert(i) << endl;\n }\n }\n util::PrintUsage(std::cerr);\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string-join.hh\"\n#include \"acmacs-base\/string-split.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/read-file.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/factory-export.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\" && path.stem().extension() == \".acd1\")\n return true;\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::virus::name_t;\n using Passage = acmacs::virus::Passage;\n using Reassortant = acmacs::virus::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_string_t;\n using SerumEntry = std::tuple;\n using TableEntry = std::tuple;\n using Entry = std::tuple;\n using Entries = std::vector;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple;\n using PerSerumIdRootEntry = std::tuple>;\n using PerSerumIdRootEntries = std::vector;\n\n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n\n \/\/ returns number of files processed\n size_t scan_directory(std::string dirname)\n {\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n auto chart = acmacs::chart::import_from_file(pathname);\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n ++charts_processed;\n }\n }\n sort();\n scan();\n return charts_processed;\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get(*std::get<0>(per_root_.front())) == acmacs::virus::type_subtype_t{\"A(H3N2)\"};\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << fmt::format(\"{} {}\\n\", std::get(*std::get<0>(per_root_entry)), std::get<1>(per_root_entry) - std::get<0>(per_root_entry));\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << fmt::format(\" {} {} [{}]\", std::get(*std::get<0>(per_serum_id_entry)), tabs.size(), make_name(std::get<0>(per_serum_id_entry)));\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get(*std::get<0>(sids.front())) != std::get(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(),\n [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n std::cout << \" --fix \";\n const auto sid1 = std::get(*std::get<0>(*ep)), sid2 = std::get(*std::get<0>(*sid));\n if ((std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid)) && sid2.size() < sid1.size())\n std::cout << *sid2 << '^' << *sid1;\n else\n std::cout << *sid1 << '^' << *sid2;\n std::cout << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get(serum), std::get(serum), std::get(serum), std::get(serum),\n std::get(table), std::get(table), std::get(table), std::get(table),\n std::get(table), std::get(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get(*entry_ptr) != std::get(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get(*entry_ptr) != std::get(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get(serum);\n if (std::get(table) == acmacs::chart::Lab{\"MELB\"}) {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R' || serum_id[0] == 'A') && serum_id[5] == '-' && serum_id->back() == 'D')\n return SerumIdRoot(serum_id->substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr) { return acmacs::string::join(\" \", std::get(*ptr), std::get(*ptr), acmacs::string::join(\" \", std::get(*ptr))); }\n\n static inline std::vector tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector tables(static_cast(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector fields;\n if (assay)\n fields.push_back(*std::get(entry));\n if (rbc)\n fields.push_back(*std::get(entry));\n fields.push_back(*std::get(entry));\n return acmacs::string::join(\":\", fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n}; \/\/ class SerumIds\n\n\/\/ ======================================================================\n\nclass FixSerumIds\n{\n public:\n FixSerumIds(std::string_view program_name) : program_name_(program_name) {}\n void add_fix(std::string_view fix_entry)\n {\n const auto fields = acmacs::string::split(fix_entry, \"^\");\n data_.emplace_back(fields[0], fields[1]);\n }\n\n \/\/ returns number of files updated\n size_t fix_charts_in_directory(std::string dirname)\n {\n size_t fixed_charts = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(pathname));\n if (fix_in_chart(chart)) {\n acmacs::file::backup(pathname.native(), acmacs::file::backup_move::yes);\n acmacs::chart::export_factory(chart, make_export_filename(pathname), program_name_, report_time::no);\n ++fixed_charts;\n }\n }\n }\n return fixed_charts;\n }\n\n private:\n std::string_view program_name_;\n std::vector> data_;\n\n bool fix_in_chart(acmacs::chart::ChartModify& chart)\n {\n auto sera = chart.sera_modify();\n bool modified = false;\n for (size_t serum_no = 0; serum_no < sera->size(); ++ serum_no) {\n auto& serum = sera->at(serum_no);\n const auto sid = serum.serum_id();\n for (const auto& fix : data_) {\n if (sid == acmacs::chart::SerumId{fix.first}) {\n std::cout << fmt::format(\"{} FIX {} {} {} {} --> {}\\n\", chart.info()->make_name(), serum.name(), serum.reassortant(), acmacs::string::join(\" \", serum.annotations()), serum.serum_id(), fix.second);\n serum.serum_id(acmacs::chart::SerumId{fix.second});\n modified = true;\n break;\n }\n }\n }\n return modified;\n }\n\n std::string make_export_filename(const fs::path& pathname) const\n {\n if (pathname.extension() == \".ace\")\n return pathname;\n if (pathname.extension() == \".bz2\" && pathname.stem().extension() == \".acd1\")\n return pathname.stem().stem() += \".ace\";\n throw std::runtime_error(\"cannot figure out export filename for: \" + pathname.string());\n }\n\n}; \/\/ class FixSerumIds\n\n\/\/ ======================================================================\n\nusing namespace acmacs::argv;\n\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n option fix{*this, \"fix\"};\n \/\/ argument period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n \/\/ argument start{*this, arg_name{\"start-date\"}, mandatory};\n \/\/ argument end{*this, arg_name{\"end-date\"}, mandatory};\n \/\/ argument output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n std::vector> fix_data;\n if (opt.fix.has_value()) {\n FixSerumIds fix_serum_ids(opt.program_name());\n for (const auto& fix_entry : opt.fix.get())\n fix_serum_ids.add_fix(fix_entry);\n const auto charts_modified = fix_serum_ids.fix_charts_in_directory(\".\");\n std::cerr << \"INFO: charts modified: \" << charts_modified << '\\n';\n }\n else {\n SerumIds serum_ids;\n const auto charts_processed = serum_ids.scan_directory(\".\");\n std::cout << charts_processed << \" charts processed\\n\";\n serum_ids.print(false);\n }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nacmacs::string::join interface improvement#include \n#include \n#include \n#include \n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string-join.hh\"\n#include \"acmacs-base\/string-split.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/read-file.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/factory-export.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\" && path.stem().extension() == \".acd1\")\n return true;\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::virus::name_t;\n using Passage = acmacs::virus::Passage;\n using Reassortant = acmacs::virus::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_string_t;\n using SerumEntry = std::tuple;\n using TableEntry = std::tuple;\n using Entry = std::tuple;\n using Entries = std::vector;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple;\n using PerSerumIdRootEntry = std::tuple>;\n using PerSerumIdRootEntries = std::vector;\n\n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n\n \/\/ returns number of files processed\n size_t scan_directory(std::string dirname)\n {\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n auto chart = acmacs::chart::import_from_file(pathname);\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n ++charts_processed;\n }\n }\n sort();\n scan();\n return charts_processed;\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get(*std::get<0>(per_root_.front())) == acmacs::virus::type_subtype_t{\"A(H3N2)\"};\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << fmt::format(\"{} {}\\n\", std::get(*std::get<0>(per_root_entry)), std::get<1>(per_root_entry) - std::get<0>(per_root_entry));\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << fmt::format(\" {} {} [{}]\", std::get(*std::get<0>(per_serum_id_entry)), tabs.size(), make_name(std::get<0>(per_serum_id_entry)));\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get(*std::get<0>(sids.front())) != std::get(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(),\n [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n std::cout << \" --fix \";\n const auto sid1 = std::get(*std::get<0>(*ep)), sid2 = std::get(*std::get<0>(*sid));\n if ((std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid)) && sid2.size() < sid1.size())\n std::cout << *sid2 << '^' << *sid1;\n else\n std::cout << *sid1 << '^' << *sid2;\n std::cout << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get(serum), std::get(serum), std::get(serum), std::get(serum),\n std::get(table), std::get(table), std::get(table), std::get(table),\n std::get(table), std::get(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get(*entry_ptr) != std::get(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get(*entry_ptr) != std::get(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get(serum);\n if (std::get(table) == acmacs::chart::Lab{\"MELB\"}) {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R' || serum_id[0] == 'A') && serum_id[5] == '-' && serum_id->back() == 'D')\n return SerumIdRoot(serum_id->substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr) { return acmacs::string::join(acmacs::string::join_space, std::get(*ptr), std::get(*ptr), acmacs::string::join(acmacs::string::join_space, std::get(*ptr))); }\n\n static inline std::vector tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector tables(static_cast(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector fields;\n if (assay)\n fields.push_back(*std::get(entry));\n if (rbc)\n fields.push_back(*std::get(entry));\n fields.push_back(*std::get(entry));\n return acmacs::string::join(acmacs::string::join_colon, fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n}; \/\/ class SerumIds\n\n\/\/ ======================================================================\n\nclass FixSerumIds\n{\n public:\n FixSerumIds(std::string_view program_name) : program_name_(program_name) {}\n void add_fix(std::string_view fix_entry)\n {\n const auto fields = acmacs::string::split(fix_entry, \"^\");\n data_.emplace_back(fields[0], fields[1]);\n }\n\n \/\/ returns number of files updated\n size_t fix_charts_in_directory(std::string dirname)\n {\n size_t fixed_charts = 0;\n for (auto& entry : fs::directory_iterator(dirname)) {\n if (const auto pathname = entry.path(); entry.is_regular_file() && is_acmacs_file(pathname)) {\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(pathname));\n if (fix_in_chart(chart)) {\n acmacs::file::backup(pathname.native(), acmacs::file::backup_move::yes);\n acmacs::chart::export_factory(chart, make_export_filename(pathname), program_name_, report_time::no);\n ++fixed_charts;\n }\n }\n }\n return fixed_charts;\n }\n\n private:\n std::string_view program_name_;\n std::vector> data_;\n\n bool fix_in_chart(acmacs::chart::ChartModify& chart)\n {\n auto sera = chart.sera_modify();\n bool modified = false;\n for (size_t serum_no = 0; serum_no < sera->size(); ++ serum_no) {\n auto& serum = sera->at(serum_no);\n const auto sid = serum.serum_id();\n for (const auto& fix : data_) {\n if (sid == acmacs::chart::SerumId{fix.first}) {\n std::cout << fmt::format(\"{} FIX {} {} {} {} --> {}\\n\", chart.info()->make_name(), serum.name(), serum.reassortant(), acmacs::string::join(acmacs::string::join_space, serum.annotations()), serum.serum_id(), fix.second);\n serum.serum_id(acmacs::chart::SerumId{fix.second});\n modified = true;\n break;\n }\n }\n }\n return modified;\n }\n\n std::string make_export_filename(const fs::path& pathname) const\n {\n if (pathname.extension() == \".ace\")\n return pathname;\n if (pathname.extension() == \".bz2\" && pathname.stem().extension() == \".acd1\")\n return pathname.stem().stem() += \".ace\";\n throw std::runtime_error(\"cannot figure out export filename for: \" + pathname.string());\n }\n\n}; \/\/ class FixSerumIds\n\n\/\/ ======================================================================\n\nusing namespace acmacs::argv;\n\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n option fix{*this, \"fix\"};\n \/\/ argument period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n \/\/ argument start{*this, arg_name{\"start-date\"}, mandatory};\n \/\/ argument end{*this, arg_name{\"end-date\"}, mandatory};\n \/\/ argument output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n std::vector> fix_data;\n if (opt.fix.has_value()) {\n FixSerumIds fix_serum_ids(opt.program_name());\n for (const auto& fix_entry : opt.fix.get())\n fix_serum_ids.add_fix(fix_entry);\n const auto charts_modified = fix_serum_ids.fix_charts_in_directory(\".\");\n std::cerr << \"INFO: charts modified: \" << charts_modified << '\\n';\n }\n else {\n SerumIds serum_ids;\n const auto charts_processed = serum_ids.scan_directory(\".\");\n std::cout << charts_processed << \" charts processed\\n\";\n serum_ids.print(false);\n }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass TestQuad : public parsernode::Parser {\npublic:\n virtual bool takeoff() { return true; } \/\/ Take off the quadcopter\n virtual bool land() { return true; } \/\/ Land the quadcopter\n virtual bool disarm() { return true; } \/\/ Disarm the quadcopter\n virtual bool flowControl(bool) {\n return true;\n } \/\/ Enable or disable control of quadcopter\n virtual bool calibrateimubias() {\n return true;\n } \/\/ Calibrate imu of the quadcopter based on sample data\n\n \/\/ Command the euler angles of the quad and the thrust. the msg format is\n \/\/ (x,y,z,w) -> (roll, pitch, yaw, thrust). The thrust value will be adjusted\n \/\/ based on whethere there is thrust bias or not.\n virtual bool cmdrpythrust(geometry_msgs::Quaternion &rpytmsg,\n bool sendyaw = false) {\n return true;\n }\n virtual bool cmdvelguided(geometry_msgs::Vector3 &vel_cmd, double &yaw_ang) {\n return true;\n }\n virtual bool cmdwaypoint(geometry_msgs::Vector3 &desired_pos,\n double desired_yaw = 0) {\n quad_data.localpos = desired_pos;\n quad_data.rpydata.z = desired_yaw;\n return true;\n }\n virtual void grip(int state) {}\n virtual void reset_attitude(double roll, double pitch, double yaw) {}\n virtual void setmode(std::string mode) {}\n\n \/\/ PluginLib initialization function\n virtual void initialize(ros::NodeHandle &nh_) {}\n virtual void getquaddata(parsernode::common::quaddata &d1) { d1 = quad_data; }\n virtual ~TestQuad() {}\n virtual void\n setaltitude(double altitude_){}; \/\/ Set the altitude value in the data\n virtual void setlogdir(string logdir){}; \/\/ Set whether to log data or not\n virtual void controllog(bool logswitch) {}\n\nprivate:\n parsernode::common::quaddata quad_data;\n};\n\n\/\/\/ \\brief Test BuiltInPositionController\nTEST(PositionControllerDroneConnectorTests, Constructor) {\n TestQuad drone_hardware;\n\n BuiltInPositionController position_controller;\n\n ASSERT_NO_THROW(new PositionControllerDroneConnector(drone_hardware,\n position_controller));\n}\n\nTEST(PositionControllerDroneConnectorTests, SetGoal) {\n TestQuad drone_hardware;\n\n \/\/ Create controller and connector\n BuiltInPositionController position_controller;\n PositionControllerDroneConnector pos_controller_connector(drone_hardware, position_controller);\n\n \/\/ Test set goal\n PositionYaw goal(10, 10, 10, 0.1);\n pos_controller_connector.setGoal(goal);\n PositionYaw goal_get = pos_controller_connector.getGoal();\n ASSERT_EQ(goal_get.x, goal.x);\n ASSERT_EQ(goal_get.y, goal.y);\n ASSERT_EQ(goal_get.z, goal.z);\n pos_controller_connector.run();\n\n parsernode::common::quaddata sensor_data;\n drone_hardware.getquaddata(sensor_data);\n\n ASSERT_EQ(sensor_data.localpos.x, goal.x);\n ASSERT_EQ(sensor_data.localpos.y, goal.y);\n ASSERT_EQ(sensor_data.localpos.z, goal.z);\n ASSERT_EQ(sensor_data.rpydata.z, goal.yaw);\n}\n\/\/\/\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nWrite out variable name in test#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass TestQuad : public parsernode::Parser {\npublic:\n virtual bool takeoff() { return true; } \/\/ Take off the quadcopter\n virtual bool land() { return true; } \/\/ Land the quadcopter\n virtual bool disarm() { return true; } \/\/ Disarm the quadcopter\n virtual bool flowControl(bool) {\n return true;\n } \/\/ Enable or disable control of quadcopter\n virtual bool calibrateimubias() {\n return true;\n } \/\/ Calibrate imu of the quadcopter based on sample data\n\n \/\/ Command the euler angles of the quad and the thrust. the msg format is\n \/\/ (x,y,z,w) -> (roll, pitch, yaw, thrust). The thrust value will be adjusted\n \/\/ based on whethere there is thrust bias or not.\n virtual bool cmdrpythrust(geometry_msgs::Quaternion &rpytmsg,\n bool sendyaw = false) {\n return true;\n }\n virtual bool cmdvelguided(geometry_msgs::Vector3 &vel_cmd, double &yaw_ang) {\n return true;\n }\n virtual bool cmdwaypoint(geometry_msgs::Vector3 &desired_pos,\n double desired_yaw = 0) {\n quad_data.localpos = desired_pos;\n quad_data.rpydata.z = desired_yaw;\n return true;\n }\n virtual void grip(int state) {}\n virtual void reset_attitude(double roll, double pitch, double yaw) {}\n virtual void setmode(std::string mode) {}\n\n \/\/ PluginLib initialization function\n virtual void initialize(ros::NodeHandle &nh_) {}\n virtual void getquaddata(parsernode::common::quaddata &d1) { d1 = quad_data; }\n virtual ~TestQuad() {}\n virtual void\n setaltitude(double altitude_){}; \/\/ Set the altitude value in the data\n virtual void setlogdir(string logdir){}; \/\/ Set whether to log data or not\n virtual void controllog(bool logswitch) {}\n\nprivate:\n parsernode::common::quaddata quad_data;\n};\n\n\/\/\/ \\brief Test BuiltInPositionController\nTEST(PositionControllerDroneConnectorTests, Constructor) {\n TestQuad drone_hardware;\n\n BuiltInPositionController position_controller;\n\n ASSERT_NO_THROW(new PositionControllerDroneConnector(drone_hardware,\n position_controller));\n}\n\nTEST(PositionControllerDroneConnectorTests, SetGoal) {\n TestQuad drone_hardware;\n\n \/\/ Create controller and connector\n BuiltInPositionController position_controller;\n PositionControllerDroneConnector position_controller_connector(\n drone_hardware, position_controller);\n\n \/\/ Test set goal\n PositionYaw goal(10, 10, 10, 0.1);\n position_controller_connector.setGoal(goal);\n PositionYaw goal_get = position_controller_connector.getGoal();\n ASSERT_EQ(goal_get.x, goal.x);\n ASSERT_EQ(goal_get.y, goal.y);\n ASSERT_EQ(goal_get.z, goal.z);\n position_controller_connector.run();\n\n parsernode::common::quaddata sensor_data;\n drone_hardware.getquaddata(sensor_data);\n\n ASSERT_EQ(sensor_data.localpos.x, goal.x);\n ASSERT_EQ(sensor_data.localpos.y, goal.y);\n ASSERT_EQ(sensor_data.localpos.z, goal.z);\n ASSERT_EQ(sensor_data.rpydata.z, goal.yaw);\n}\n\/\/\/\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"RapidIPSmearGauss.h\"\n\n#include \"TMath.h\"\n#include \"TRandom.h\"\n\nstd::pair RapidIPSmearGauss::smearIP(double ip, double pt) {\n\n\tconst double sigma_ = gRandom->Gaus(0.,intercept_ + slope_\/pt);\n\tconst double smear_ = ip+sigma_;\n\treturn std::pair(smear_,std::fabs(sigma_));\n\n}\n\navoid negative IPs#include \"RapidIPSmearGauss.h\"\n\n#include \"TMath.h\"\n#include \"TRandom.h\"\n\nstd::pair RapidIPSmearGauss::smearIP(double ip, double pt) {\n\n\tconst double sigma_ = gRandom->Gaus(0.,intercept_ + slope_\/pt);\n\tconst double smear_ = ip+sigma_;\n\treturn std::pair(std::fabs(smear_),std::fabs(sigma_));\n\n}\n\n<|endoftext|>"} {"text":"\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"text_classification_feature_extractor.hpp\"\n\n#include \n#include \n#include \n\nnamespace resembla {\n\nTextClassificationFeatureExtractor::TextClassificationFeatureExtractor(\n const std::string& mecab_options, const std::string& dict_path, const std::string& model_path):\n tagger(MeCab::createTagger(mecab_options.c_str())),\n model(svm_load_model(model_path.c_str()))\n{\n std::ifstream ifs(dict_path);\n if(ifs.fail()){\n throw std::runtime_error(\"input file is not available: \" + dict_path);\n }\n\n while(ifs.good()){\n std::string line;\n std::getline(ifs, line);\n if(ifs.eof()){\n break;\n }\n\n auto i = line.find(column_delimiter<>());\n if(i != std::string::npos){\n dictionary[line.substr(0, i)] = std::stoi(line.substr(i + 1));\n }\n }\n}\n\nFeature::text_type TextClassificationFeatureExtractor::operator()(const string_type& text) const\n{\n auto nodes = toNodes(text);\n double s;\n {\n std::lock_guard lock(mutex_model);\n s = svm_predict(model, &nodes[0]);\n }\n std::stringstream ss;\n ss << s;\n return ss.str();\n}\n\nstd::vector TextClassificationFeatureExtractor::toNodes(const string_type& text) const\n{\n const auto text_string = cast_string(text);\n BoW bow;\n {\n std::lock_guard lock(mutex_tagger);\n for(const MeCab::Node* node = tagger->parseToNode(text_string.c_str()); node; node = node->next){\n \/\/ skip BOS\/EOS nodes\n if(node->stat == MECAB_BOS_NODE || node->stat == MECAB_EOS_NODE){\n continue;\n }\n\n auto i = dictionary.find(std::string(node->surface, node->surface + node->length));\n if(i != dictionary.end()){\n auto j = bow.find(i->second);\n if(j == bow.end()){\n bow[i->second] = 1;\n }\n else{\n ++j->second;\n }\n }\n }\n }\n\n std::vector nodes(bow.size() + 1);\n size_t i = 0;\n for(const auto j: bow){\n nodes[j.first].index = j.first;\n nodes[j.first].value = static_cast(j.second);\n ++i;\n }\n nodes[i].index = -1; \/\/ end of features\n return nodes;\n}\n\n}\nuse common utility\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"text_classification_feature_extractor.hpp\"\n\n#include \n#include \n\nnamespace resembla {\n\nTextClassificationFeatureExtractor::TextClassificationFeatureExtractor(\n const std::string& mecab_options, const std::string& dict_path, const std::string& model_path):\n tagger(MeCab::createTagger(mecab_options.c_str())),\n model(svm_load_model(model_path.c_str()))\n{\n std::ifstream ifs(dict_path);\n if(ifs.fail()){\n throw std::runtime_error(\"input file is not available: \" + dict_path);\n }\n\n while(ifs.good()){\n std::string line;\n std::getline(ifs, line);\n if(ifs.eof()){\n break;\n }\n\n auto i = line.find(column_delimiter<>());\n if(i != std::string::npos){\n dictionary[line.substr(0, i)] = std::stoi(line.substr(i + 1));\n }\n }\n}\n\nFeature::text_type TextClassificationFeatureExtractor::operator()(const string_type& text) const\n{\n auto nodes = toNodes(text);\n double s;\n {\n std::lock_guard lock(mutex_model);\n s = svm_predict(model, &nodes[0]);\n }\n return Feature::toText(s);\n}\n\nstd::vector TextClassificationFeatureExtractor::toNodes(const string_type& text) const\n{\n const auto text_string = cast_string(text);\n BoW bow;\n {\n std::lock_guard lock(mutex_tagger);\n for(const MeCab::Node* node = tagger->parseToNode(text_string.c_str()); node; node = node->next){\n \/\/ skip BOS\/EOS nodes\n if(node->stat == MECAB_BOS_NODE || node->stat == MECAB_EOS_NODE){\n continue;\n }\n\n auto i = dictionary.find(std::string(node->surface, node->surface + node->length));\n if(i != dictionary.end()){\n auto j = bow.find(i->second);\n if(j == bow.end()){\n bow[i->second] = 1;\n }\n else{\n ++j->second;\n }\n }\n }\n }\n\n std::vector nodes(bow.size() + 1);\n size_t i = 0;\n for(const auto j: bow){\n nodes[j.first].index = j.first;\n nodes[j.first].value = static_cast(j.second);\n ++i;\n }\n nodes[i].index = -1; \/\/ end of features\n return nodes;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_register_coalesce.cpp\n *\n * Implements register coalescing: Checks if the two registers involved in a\n * raw move don't interfere, in which case they can both be stored in the same\n * place and the MOV removed.\n *\n * To do this, all uses of the source of the MOV in the shader are replaced\n * with the destination of the MOV. For example:\n *\n * add vgrf3:F, vgrf1:F, vgrf2:F\n * mov vgrf4:F, vgrf3:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\n * becomes\n *\n * add vgrf4:F, vgrf1:F, vgrf2:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_fs_live_variables.h\"\n\nstatic bool\nis_nop_mov(const fs_inst *inst)\n{\n if (inst->opcode == BRW_OPCODE_MOV) {\n return inst->dst.equals(inst->src[0]);\n }\n\n return false;\n}\n\nstatic bool\nis_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)\n{\n if (inst->opcode != BRW_OPCODE_MOV ||\n inst->is_partial_write() ||\n inst->saturate ||\n inst->src[0].file != GRF ||\n inst->src[0].negate ||\n inst->src[0].abs ||\n !inst->src[0].is_contiguous() ||\n inst->dst.file != GRF ||\n inst->dst.type != inst->src[0].type) {\n return false;\n }\n\n if (virtual_grf_sizes[inst->src[0].reg] >\n virtual_grf_sizes[inst->dst.reg])\n return false;\n\n return true;\n}\n\nstatic bool\ncan_coalesce_vars(brw::fs_live_variables *live_intervals,\n const exec_list *instructions, const fs_inst *inst, int ip,\n int var_to, int var_from)\n{\n if (!live_intervals->vars_interfere(var_from, var_to))\n return true;\n\n \/* We know that the live ranges of A (var_from) and B (var_to)\n * interfere because of the ->vars_interfere() call above. If the end\n * of B's live range is after the end of A's range, then we know two\n * things:\n * - the start of B's live range must be in A's live range (since we\n * already know the two ranges interfere, this is the only remaining\n * possibility)\n * - the interference isn't of the form we're looking for (where B is\n * entirely inside A)\n *\/\n if (live_intervals->end[var_to] > live_intervals->end[var_from])\n return false;\n\n assert(ip >= live_intervals->start[var_to]);\n\n fs_inst *scan_inst;\n for (scan_inst = (fs_inst *)inst->next;\n !scan_inst->is_tail_sentinel() && ip <= live_intervals->end[var_to];\n scan_inst = (fs_inst *)scan_inst->next, ip++) {\n if (scan_inst->opcode == BRW_OPCODE_WHILE)\n return false;\n\n if (scan_inst->dst.equals(inst->dst) ||\n scan_inst->dst.equals(inst->src[0]))\n return false;\n }\n\n return true;\n}\n\nbool\nfs_visitor::register_coalesce()\n{\n bool progress = false;\n\n calculate_live_intervals();\n\n int src_size = 0;\n int channels_remaining = 0;\n int reg_from = -1, reg_to = -1;\n int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];\n fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];\n int var_to[MAX_SAMPLER_MESSAGE_SIZE];\n int var_from[MAX_SAMPLER_MESSAGE_SIZE];\n int ip = -1;\n\n foreach_list(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n ip++;\n\n if (!is_coalesce_candidate(inst, virtual_grf_sizes))\n continue;\n\n if (is_nop_mov(inst)) {\n inst->opcode = BRW_OPCODE_NOP;\n progress = true;\n continue;\n }\n\n if (reg_from != inst->src[0].reg) {\n reg_from = inst->src[0].reg;\n\n src_size = virtual_grf_sizes[inst->src[0].reg];\n assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);\n\n channels_remaining = src_size;\n memset(mov, 0, sizeof(mov));\n\n reg_to = inst->dst.reg;\n }\n\n if (reg_to != inst->dst.reg)\n continue;\n\n const int offset = inst->src[0].reg_offset;\n reg_to_offset[offset] = inst->dst.reg_offset;\n mov[offset] = inst;\n channels_remaining--;\n\n if (channels_remaining)\n continue;\n\n bool can_coalesce = true;\n for (int i = 0; i < src_size; i++) {\n var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];\n var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;\n\n if (!can_coalesce_vars(live_intervals, &instructions, inst, ip,\n var_to[i], var_from[i])) {\n can_coalesce = false;\n reg_from = -1;\n break;\n }\n }\n\n if (!can_coalesce)\n continue;\n\n progress = true;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n mov[i]->opcode = BRW_OPCODE_NOP;\n mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;\n mov[i]->dst = reg_undef;\n mov[i]->src[0] = reg_undef;\n mov[i]->src[1] = reg_undef;\n mov[i]->src[2] = reg_undef;\n }\n }\n\n foreach_list(node, &this->instructions) {\n fs_inst *scan_inst = (fs_inst *)node;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n if (scan_inst->dst.file == GRF &&\n scan_inst->dst.reg == reg_from &&\n scan_inst->dst.reg_offset == i) {\n scan_inst->dst.reg = reg_to;\n scan_inst->dst.reg_offset = reg_to_offset[i];\n }\n for (int j = 0; j < 3; j++) {\n if (scan_inst->src[j].file == GRF &&\n scan_inst->src[j].reg == reg_from &&\n scan_inst->src[j].reg_offset == i) {\n scan_inst->src[j].reg = reg_to;\n scan_inst->src[j].reg_offset = reg_to_offset[i];\n }\n }\n }\n }\n }\n\n for (int i = 0; i < src_size; i++) {\n live_intervals->start[var_to[i]] =\n MIN2(live_intervals->start[var_to[i]],\n live_intervals->start[var_from[i]]);\n live_intervals->end[var_to[i]] =\n MAX2(live_intervals->end[var_to[i]],\n live_intervals->end[var_from[i]]);\n }\n reg_from = -1;\n }\n\n if (progress) {\n foreach_list_safe(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n\n if (inst->opcode == BRW_OPCODE_NOP) {\n inst->remove();\n }\n }\n\n invalidate_live_intervals();\n }\n\n return progress;\n}\ni965\/fs: Reduce restrictions on interference in register coalescing.\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_register_coalesce.cpp\n *\n * Implements register coalescing: Checks if the two registers involved in a\n * raw move don't interfere, in which case they can both be stored in the same\n * place and the MOV removed.\n *\n * To do this, all uses of the source of the MOV in the shader are replaced\n * with the destination of the MOV. For example:\n *\n * add vgrf3:F, vgrf1:F, vgrf2:F\n * mov vgrf4:F, vgrf3:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\n * becomes\n *\n * add vgrf4:F, vgrf1:F, vgrf2:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_fs_live_variables.h\"\n\nstatic bool\nis_nop_mov(const fs_inst *inst)\n{\n if (inst->opcode == BRW_OPCODE_MOV) {\n return inst->dst.equals(inst->src[0]);\n }\n\n return false;\n}\n\nstatic bool\nis_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)\n{\n if (inst->opcode != BRW_OPCODE_MOV ||\n inst->is_partial_write() ||\n inst->saturate ||\n inst->src[0].file != GRF ||\n inst->src[0].negate ||\n inst->src[0].abs ||\n !inst->src[0].is_contiguous() ||\n inst->dst.file != GRF ||\n inst->dst.type != inst->src[0].type) {\n return false;\n }\n\n if (virtual_grf_sizes[inst->src[0].reg] >\n virtual_grf_sizes[inst->dst.reg])\n return false;\n\n return true;\n}\n\nstatic bool\ncan_coalesce_vars(brw::fs_live_variables *live_intervals,\n const exec_list *instructions, const fs_inst *inst, int ip,\n int var_to, int var_from)\n{\n if (!live_intervals->vars_interfere(var_from, var_to))\n return true;\n\n assert(ip >= live_intervals->start[var_to]);\n\n fs_inst *scan_inst;\n for (scan_inst = (fs_inst *)inst->next;\n !scan_inst->is_tail_sentinel() && ip <= live_intervals->end[var_to];\n scan_inst = (fs_inst *)scan_inst->next, ip++) {\n if (scan_inst->opcode == BRW_OPCODE_WHILE)\n return false;\n\n if (scan_inst->dst.equals(inst->dst) ||\n scan_inst->dst.equals(inst->src[0]))\n return false;\n }\n\n return true;\n}\n\nbool\nfs_visitor::register_coalesce()\n{\n bool progress = false;\n\n calculate_live_intervals();\n\n int src_size = 0;\n int channels_remaining = 0;\n int reg_from = -1, reg_to = -1;\n int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];\n fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];\n int var_to[MAX_SAMPLER_MESSAGE_SIZE];\n int var_from[MAX_SAMPLER_MESSAGE_SIZE];\n int ip = -1;\n\n foreach_list(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n ip++;\n\n if (!is_coalesce_candidate(inst, virtual_grf_sizes))\n continue;\n\n if (is_nop_mov(inst)) {\n inst->opcode = BRW_OPCODE_NOP;\n progress = true;\n continue;\n }\n\n if (reg_from != inst->src[0].reg) {\n reg_from = inst->src[0].reg;\n\n src_size = virtual_grf_sizes[inst->src[0].reg];\n assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);\n\n channels_remaining = src_size;\n memset(mov, 0, sizeof(mov));\n\n reg_to = inst->dst.reg;\n }\n\n if (reg_to != inst->dst.reg)\n continue;\n\n const int offset = inst->src[0].reg_offset;\n reg_to_offset[offset] = inst->dst.reg_offset;\n mov[offset] = inst;\n channels_remaining--;\n\n if (channels_remaining)\n continue;\n\n bool can_coalesce = true;\n for (int i = 0; i < src_size; i++) {\n var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];\n var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;\n\n if (!can_coalesce_vars(live_intervals, &instructions, inst, ip,\n var_to[i], var_from[i])) {\n can_coalesce = false;\n reg_from = -1;\n break;\n }\n }\n\n if (!can_coalesce)\n continue;\n\n progress = true;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n mov[i]->opcode = BRW_OPCODE_NOP;\n mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;\n mov[i]->dst = reg_undef;\n mov[i]->src[0] = reg_undef;\n mov[i]->src[1] = reg_undef;\n mov[i]->src[2] = reg_undef;\n }\n }\n\n foreach_list(node, &this->instructions) {\n fs_inst *scan_inst = (fs_inst *)node;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n if (scan_inst->dst.file == GRF &&\n scan_inst->dst.reg == reg_from &&\n scan_inst->dst.reg_offset == i) {\n scan_inst->dst.reg = reg_to;\n scan_inst->dst.reg_offset = reg_to_offset[i];\n }\n for (int j = 0; j < 3; j++) {\n if (scan_inst->src[j].file == GRF &&\n scan_inst->src[j].reg == reg_from &&\n scan_inst->src[j].reg_offset == i) {\n scan_inst->src[j].reg = reg_to;\n scan_inst->src[j].reg_offset = reg_to_offset[i];\n }\n }\n }\n }\n }\n\n for (int i = 0; i < src_size; i++) {\n live_intervals->start[var_to[i]] =\n MIN2(live_intervals->start[var_to[i]],\n live_intervals->start[var_from[i]]);\n live_intervals->end[var_to[i]] =\n MAX2(live_intervals->end[var_to[i]],\n live_intervals->end[var_from[i]]);\n }\n reg_from = -1;\n }\n\n if (progress) {\n foreach_list_safe(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n\n if (inst->opcode == BRW_OPCODE_NOP) {\n inst->remove();\n }\n }\n\n invalidate_live_intervals();\n }\n\n return progress;\n}\n<|endoftext|>"} {"text":"#include \"SemanticAnalyzer.h\"\n#include \"Symbol.h\"\n#include \"PrintFunction.h\"\n\nSemanticAnalyzer::SemanticAnalyzer() {\n this->currentStructure = NULL;\n this->lastStatement = NULL;\n this->symbolTable.newScope();\n}\n\nSemanticAnalyzer::~SemanticAnalyzer() {\n}\n\nvoid SemanticAnalyzer::analyzeRelationalOperationCasting(BinaryOperation* binaryop) {\n}\n\nvoid SemanticAnalyzer::newScope() {\n this->analyzeScopeCreation();\n this->symbolTable.setCurrentStructure(this->currentStructure);\n this->symbolTable.setLastStatement(this->lastStatement);\n this->currentStructure = NULL;\n this->symbolTable.newScope();\n}\n\nvoid SemanticAnalyzer::returnScope() {\n this->symbolTable.returnScope();\n this->lastStatement = this->symbolTable.getLastStatement();\n}\n\nvoid SemanticAnalyzer::setScope(float indentation) {\n int indINT = (int) indentation;\n\n if(indINT != indentation) {\n ERROR_LOGGER->log(ErrorLogger::SYNTAX, \"INDENTATION 2 SPACES ERROR\"); \/\/ TODO\n return;\n }\n\n if(indINT - this->getCurrentIndentation() > 1)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"INDENTATION ERROR\"); \/\/ TODO\n else if(indINT > this->getCurrentIndentation()) {\n this->newScope();\n } else {\n int ind = this->getCurrentIndentation();\n while(indINT < ind) {\n this->returnScope();\n ind--;\n }\n }\n}\n\nvoid SemanticAnalyzer::pushLineScope(TreeNode* line) {\n this->symbolTable.pushLineScope(line);\n}\n\nCodeBlock* SemanticAnalyzer::getCurrentBody() {\n return this->symbolTable.getCurrentCodeBlock();\n}\n\nint SemanticAnalyzer::getCurrentIndentation() {\n return this->symbolTable.getCurrentIndentation();\n}\n\nvoid SemanticAnalyzer::setUnknownTypes(Data::Type type, CodeBlock* codeBlock) {\n this->symbolTable.setUnknownTypes(type);\n\n for(int i = 0; i < codeBlock->numberOfLines(); i++){\n codeBlock->getLine(i)->setType(type);\n }\n}\n\nvoid SemanticAnalyzer::analyzeProgram() {\n \/\/ Verifica a existência da função toc()\n Symbol tocFunction = this->symbolTable.getSymbol(\"toc\");\n\n\n if(tocFunction.getType() != Symbol::FUNCTION\n || tocFunction.getDataType() != Data::VOID)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Main function toc() not found.\");\n}\n\nvoid SemanticAnalyzer::analyzeScopeCreation() {\n if(this->currentStructure == NULL)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"INDENTATION ERROR\"); \/\/ TODO\n}\n\nvoid SemanticAnalyzer::analyzeCasting(BinaryOperation* binaryOp) {\n TreeNode* left = binaryOp->left;\n TreeNode* right = binaryOp->right;\n std::string text = \"\";\n\n if (left->dataType() != right->dataType()) {\n if(right->dataType() == Data::STR) {\n\n switch (left->dataType()) {\n case Data::BOO:\n if (((String*)right)->isBoolean() || this->symbolTable.getSymbol(((Variable*)right)->getId()).getData()->dataType()) {\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n } else {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"String value is not false or true.\");\n }\n break;\n case Data::FLT:\n case Data::INT:\n if (((String*)right)->isNumber() || this->symbolTable.getSymbol(((Variable*)right)->getId()).getData()->dataType()) {\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n } else {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"String value is not a number.\");\n }\n break;\n default:\n break;\n }\n\n }else{\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n }\n }\n}\n\nvoid SemanticAnalyzer::analyzeLoop(std::string id) {\n if(this->symbolTable.getSymbol(id, true).getData()->classType() != TreeNode::ARRAY)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Expecting an array type \" + id + \".\");\n}\n\nvoid SemanticAnalyzer::analyzeArray(std::string id, int size, TreeNode* attribuition){\n BinaryOperation* node = (BinaryOperation*)attribuition;\n int c = 0;\n if(attribuition->classType() != TreeNode::BINARY_OPERATION && size > 1)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Illegal array assignment.\");\n else if(attribuition->classType() == TreeNode::BINARY_OPERATION){\n while(node->right->classType() == TreeNode::BINARY_OPERATION){\n c ++;\n if(node->right->classType() != TreeNode::BINARY_OPERATION)\n break;\n node = (BinaryOperation*)(node->right);\n }\n c = c + 2;\n if(c > size)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Number of elements in assignment differs from array length.\");\n }\n}\n\nvoid SemanticAnalyzer::analyzeAssignArray(std::string id, TreeNode* size){\n Integer* i = (Integer*) size;\n TreeNode* t = this->symbolTable.getSymbol(id, true).getData();\n if (t->classType() == TreeNode::ARRAY)\n std::cout << \"a\" << std::endl;\n \/\/ TreeNode* s = array->getSize();\n \/\/ if(i->getValue() > s->getValue())\n\n}\n\nbool SemanticAnalyzer::checkIdentifier(std::string id) const {\n if(this->symbolTable.existsSymbol(id, false)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Identifier \" + id + \" already used for declaration.\");\n return false;\n }\n\n return true;\n}\n\nTreeNode* SemanticAnalyzer::cast(Data::Type type, TreeNode* node) const {\n if(type != node->dataType())\n return new TypeCasting(type, node);\n\n return node;\n}\n\nTreeNode* SemanticAnalyzer::declareVariable(std::string id, Data::Type dataType, int size) {\n if(this->lastStatement->classType() == TreeNode::OBJECT && this->currentStructure != NULL){\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Declaration expected encapsulation.\");\n std::cout << this->lastStatement->classType() << std::endl;\n }\n if(this->checkIdentifier(id)) {\n if(size > 0) {\n Array* array = new Array(id, dataType, new Integer(size));\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n return array;\n } else {\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false)); \/\/ Adds variable to symbol table\n Variable* v = new Variable(id, dataType);\n VariableDeclaration* vD = new VariableDeclaration(dataType, v);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n\n return vD;\n }\n }\n\n \/\/ return a random variable if id is in use\n return new VariableDeclaration(dataType, new Variable(id, dataType));\n}\n\nTreeNode* SemanticAnalyzer::declareBinaryOperation(TreeNode* left, BinaryOperation::Type op, TreeNode* right) {\n \/\/ TODO\n}\n\nTreeNode* SemanticAnalyzer::declareObject(std::string id, CodeBlock* param, CodeBlock* body){\n if(this->checkIdentifier(id)) {\n Object* obj = new Object(id,param,NULL);\n this->symbolTable.addSymbol(id, Symbol(Data::OBJ, Symbol::OBJECT, true, obj));\n this->currentStructure = obj;\n return obj;\n }\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareAttribute(std::string id, Data::Type type, int encapsulation, int size) {\n if(this->lastStatement->classType() != TreeNode::OBJECT)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Encapsulation out of object body\");\n\n Object* obj = (Object*) this->lastStatement;\n\n if(size > 0){\n Array* a = new Array(id, type, new Integer(size));\n a->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, true, a));\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return a;\n }else{\n VariableDeclaration* vd = new VariableDeclaration(type, new Variable(id, type));\n vd->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, true, vd));\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return vd;\n }\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareAssignAttribute(std::string id, Data::Type type, int encapsulation, TreeNode* value, int size) {\n if(this->lastStatement->classType() != TreeNode::OBJECT)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Encapsulation out of object body\");\n\n if(this->checkIdentifier(id)) {\n if(size > 0) {\n Array* array = new Array(id, type, new Integer(size));\n array->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n this->symbolTable.setInitializedSymbol(id, array);\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return array;\n }\n\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, false)); \/\/ Adds variable to symbol table\n this->symbolTable.setInitializedSymbol(id, value);\n Variable* v = new Variable(id, type);\n VariableDeclaration* vD = new VariableDeclaration(type, v);\n vD->setEncapsulation(encapsulation);\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n return vD;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareMethod(std::string id, CodeBlock* params, CodeBlock* body, Data::Type returnType, int encapsulation) {\n if(this->lastStatement->classType() != TreeNode::OBJECT){\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Encapsulation method out of object body\");\n std::cout << \"method\" + this->lastStatement->classType() << std::endl;\n }\n\n Function* function;\n if(this->checkIdentifier(id)) {\n function = new Function(id, params, body, NULL);\n function->setType(returnType);\n function->setEncapsulation(encapsulation);\n\n this->symbolTable.addSymbol(id, Symbol(returnType, Symbol::FUNCTION, true, function));\n this->currentStructure = function;\n return function;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareFunction(std::string id, CodeBlock* params, CodeBlock* body, Data::Type returnType) {\n if(this->checkIdentifier(id)) {\n TreeNode* function;\n\n if(!id.compare(\"toc\")) { \/\/ Se é a função toc, cria a mesma\n function = new TocFunction(body);\n } else { \/\/ Outra função qualquer\n function = new Function(id, params, body, NULL);\n function->setType(returnType);\n }\n\n this->symbolTable.addSymbol(id, Symbol(returnType, Symbol::FUNCTION, true, function));\n this->currentStructure = function;\n this->lastStatement = function;\n return function;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareFunctionReturn(TreeNode* ret) {\n Function* f = (Function*) this->symbolTable.getParentStructure();\n if(f->classType() != TreeNode::FUNCTION){\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Return value for function \" + f->getId() + \"is different from expected;\" );\n }\n\n f->setReturn(ret);\n return NULL; \/\/ TODO\n}\n\nTreeNode* SemanticAnalyzer::declareCondition(TreeNode* expression, CodeBlock* body) {\n Conditional* cond = new Conditional(expression, body, NULL);\n this->currentStructure = cond;\n this->lastStatement = cond;\n return cond;\n}\n\nTreeNode* SemanticAnalyzer::declareElseCondition(CodeBlock* body) {\n std::string elseError = \"Else without a if.\";\n\n if(this->lastStatement->classType() != TreeNode::CONDITIONAL)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, elseError);\n\n Conditional* cond = (Conditional*) this->lastStatement;\n\n if(cond->hasElse())\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, elseError);\n\n cond->setElse(true);\n this->currentStructure = this->lastStatement;\n return this->currentStructure;\n}\n\nTreeNode* SemanticAnalyzer::declareLoop(TreeNode* init, TreeNode* test, TreeNode* attribuition) {\n Loop* loop;\n\n if(test == NULL) {\n Variable* v = (Variable*) attribuition;\n std::string id = v->getId();\n Array* array = (Array*)this->symbolTable.getSymbol(id, true).getData();\n loop = new Loop(init, test, array);\n }else{\n loop = new Loop(init, test, attribuition);\n }\n\n this->currentStructure = loop;\n return loop;\n}\n\nTreeNode* SemanticAnalyzer::declarePrint(TreeNode* param) {\n TreeNode* paramPrint = param;\n\n if(param->dataType() != Data::STR)\n paramPrint = new TypeCasting(Data::STR, paramPrint);\n\n return new PrintFunction(paramPrint);\n}\n\nTreeNode* SemanticAnalyzer::assignVariable(std::string id, TreeNode* value, TreeNode* index) {\n if(!this->symbolTable.existsSymbol(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Undeclared variable \" + id + \".\");\n return new Variable(id, Data::UNKNOWN); \/\/Creates variable node anyway\n } else if (index != NULL) {\n this->symbolTable.setInitializedSymbol(id);\n Array* a = (Array*)this->symbolTable.getSymbol(id).getData();\n return new Array(id, this->symbolTable.getSymbol(id).getDataType(), index, value);\n } else {\n this->symbolTable.setInitializedSymbol(id, value);\n Variable* v = new Variable(id, this->symbolTable.getSymbol(id, true).getDataType());\n v->setSymbolTable(this->symbolTable);\n return v;\n }\n}\n\nTreeNode* SemanticAnalyzer::declareAssignVariable(std::string id, Data::Type dataType, TreeNode* value, int size) {\n<<<<<<< HEAD\n if(this->lastStructure != NULL && this->lastStructure->classType() == TreeNode::OBJECT){\n=======\n if(this->lastStatement->classType() == TreeNode::OBJECT){\n>>>>>>> 948d2b3b3fe2119923a70b3982c5e6b70b6369a9\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Declaration expected encapsulation.\");\n }\n\n if(this->checkIdentifier(id)) {\n \/\/ sempre que size é maior do que zero, trata-se de uma declaração de array\n if(size > 0) {\n Array* array = new Array(id, dataType, new Integer(size), value);\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n this->symbolTable.setInitializedSymbol(id, array);\n return array;\n }\n\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, value)); \/\/ Adds variable to symbol table\n this->symbolTable.setInitializedSymbol(id, value);\n\n Variable* v = new Variable(id, dataType);\n VariableDeclaration* vD = new VariableDeclaration(dataType, v);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n return vD;\n }\n\n \/\/ return a random variable case id is in use\n return new VariableDeclaration(dataType, new Variable(id, dataType));\n}\n\nTreeNode* SemanticAnalyzer::useVariable(std::string id, TreeNode* index) {\n if(!this->symbolTable.existsSymbol(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Undeclared variable \" + id + \".\");\n return new Variable(id, Data::UNKNOWN); \/\/Creates variable node anyway\n } else if(!this->symbolTable.isSymbolInitialized(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Variable \" + id + \" used but not initialized.\");\n }\n\n TreeNode* t = this->symbolTable.getSymbol(id, true).getData();\n if (index != NULL and t->classType() == TreeNode::ARRAY) {\n Array* array = (Array*)t;\n if (array != NULL and array->getSize()->classType() == TreeNode::INTEGER) {\n if(((Integer*)index)->getValue() > ((Integer*)(array->getSize()))->getValue() || ((Integer*)index)->getValue() < 0)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Index out of bounds \" + id + \".\");\n }\n return new Array(id, this->symbolTable.getSymbol(id,true).getDataType(), index);\n }\n Variable* v = new Variable(id, this->symbolTable.getSymbol(id,true).getDataType());\n v->setSymbolTable(this->symbolTable);\n return v;\n}\narquivos organizados#include \"SemanticAnalyzer.h\"\n#include \"Symbol.h\"\n#include \"PrintFunction.h\"\n\nSemanticAnalyzer::SemanticAnalyzer() {\n this->currentStructure = NULL;\n this->lastStatement = NULL;\n this->symbolTable.newScope();\n}\n\nSemanticAnalyzer::~SemanticAnalyzer() {\n}\n\nvoid SemanticAnalyzer::analyzeRelationalOperationCasting(BinaryOperation* binaryop) {\n}\n\nvoid SemanticAnalyzer::newScope() {\n this->analyzeScopeCreation();\n this->symbolTable.setCurrentStructure(this->currentStructure);\n this->symbolTable.setLastStatement(this->lastStatement);\n this->currentStructure = NULL;\n this->symbolTable.newScope();\n}\n\nvoid SemanticAnalyzer::returnScope() {\n this->symbolTable.returnScope();\n this->lastStatement = this->symbolTable.getLastStatement();\n}\n\nvoid SemanticAnalyzer::setScope(float indentation) {\n int indINT = (int) indentation;\n\n if(indINT != indentation) {\n ERROR_LOGGER->log(ErrorLogger::SYNTAX, \"INDENTATION 2 SPACES ERROR\"); \/\/ TODO\n return;\n }\n\n if(indINT - this->getCurrentIndentation() > 1)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"INDENTATION ERROR\"); \/\/ TODO\n else if(indINT > this->getCurrentIndentation()) {\n this->newScope();\n } else {\n int ind = this->getCurrentIndentation();\n while(indINT < ind) {\n this->returnScope();\n ind--;\n }\n }\n}\n\nvoid SemanticAnalyzer::pushLineScope(TreeNode* line) {\n this->symbolTable.pushLineScope(line);\n}\n\nCodeBlock* SemanticAnalyzer::getCurrentBody() {\n return this->symbolTable.getCurrentCodeBlock();\n}\n\nint SemanticAnalyzer::getCurrentIndentation() {\n return this->symbolTable.getCurrentIndentation();\n}\n\nvoid SemanticAnalyzer::setUnknownTypes(Data::Type type, CodeBlock* codeBlock) {\n this->symbolTable.setUnknownTypes(type);\n\n for(int i = 0; i < codeBlock->numberOfLines(); i++){\n codeBlock->getLine(i)->setType(type);\n }\n}\n\nvoid SemanticAnalyzer::analyzeProgram() {\n \/\/ Verifica a existência da função toc()\n Symbol tocFunction = this->symbolTable.getSymbol(\"toc\");\n\n\n if(tocFunction.getType() != Symbol::FUNCTION\n || tocFunction.getDataType() != Data::VOID)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Main function toc() not found.\");\n}\n\nvoid SemanticAnalyzer::analyzeScopeCreation() {\n if(this->currentStructure == NULL)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"INDENTATION ERROR\"); \/\/ TODO\n}\n\nvoid SemanticAnalyzer::analyzeCasting(BinaryOperation* binaryOp) {\n TreeNode* left = binaryOp->left;\n TreeNode* right = binaryOp->right;\n std::string text = \"\";\n\n if (left->dataType() != right->dataType()) {\n if(right->dataType() == Data::STR) {\n\n switch (left->dataType()) {\n case Data::BOO:\n if (((String*)right)->isBoolean() || this->symbolTable.getSymbol(((Variable*)right)->getId()).getData()->dataType()) {\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n } else {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"String value is not false or true.\");\n }\n break;\n case Data::FLT:\n case Data::INT:\n if (((String*)right)->isNumber() || this->symbolTable.getSymbol(((Variable*)right)->getId()).getData()->dataType()) {\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n } else {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"String value is not a number.\");\n }\n break;\n default:\n break;\n }\n\n }else{\n binaryOp->right = new TypeCasting(left->dataType(), right);\n right = binaryOp->right;\n }\n }\n}\n\nvoid SemanticAnalyzer::analyzeLoop(std::string id) {\n if(this->symbolTable.getSymbol(id, true).getData()->classType() != TreeNode::ARRAY)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Expecting an array type \" + id + \".\");\n}\n\nvoid SemanticAnalyzer::analyzeArray(std::string id, int size, TreeNode* attribuition){\n BinaryOperation* node = (BinaryOperation*)attribuition;\n int c = 0;\n if(attribuition->classType() != TreeNode::BINARY_OPERATION && size > 1)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Illegal array assignment.\");\n else if(attribuition->classType() == TreeNode::BINARY_OPERATION){\n while(node->right->classType() == TreeNode::BINARY_OPERATION){\n c ++;\n if(node->right->classType() != TreeNode::BINARY_OPERATION)\n break;\n node = (BinaryOperation*)(node->right);\n }\n c = c + 2;\n if(c > size)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Number of elements in assignment differs from array length.\");\n }\n}\n\nvoid SemanticAnalyzer::analyzeAssignArray(std::string id, TreeNode* size){\n Integer* i = (Integer*) size;\n TreeNode* t = this->symbolTable.getSymbol(id, true).getData();\n if (t->classType() == TreeNode::ARRAY)\n std::cout << \"a\" << std::endl;\n \/\/ TreeNode* s = array->getSize();\n \/\/ if(i->getValue() > s->getValue())\n\n}\n\nbool SemanticAnalyzer::checkIdentifier(std::string id) const {\n if(this->symbolTable.existsSymbol(id, false)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Identifier \" + id + \" already used for declaration.\");\n return false;\n }\n\n return true;\n}\n\nTreeNode* SemanticAnalyzer::cast(Data::Type type, TreeNode* node) const {\n if(type != node->dataType())\n return new TypeCasting(type, node);\n\n return node;\n}\n\nTreeNode* SemanticAnalyzer::declareVariable(std::string id, Data::Type dataType, int size) {\n if(this->checkIdentifier(id)) {\n if(size > 0) {\n Array* array = new Array(id, dataType, new Integer(size));\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n return array;\n } else {\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false)); \/\/ Adds variable to symbol table\n Variable* v = new Variable(id, dataType);\n VariableDeclaration* vD = new VariableDeclaration(dataType, v);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n\n return vD;\n }\n }\n\n \/\/ return a random variable if id is in use\n return new VariableDeclaration(dataType, new Variable(id, dataType));\n}\n\nTreeNode* SemanticAnalyzer::declareBinaryOperation(TreeNode* left, BinaryOperation::Type op, TreeNode* right) {\n \/\/ TODO\n}\n\nTreeNode* SemanticAnalyzer::declareObject(std::string id, CodeBlock* param, CodeBlock* body){\n if(this->checkIdentifier(id)) {\n Object* obj = new Object(id,param,NULL);\n this->symbolTable.addSymbol(id, Symbol(Data::OBJ, Symbol::OBJECT, true, obj));\n this->currentStructure = obj;\n return obj;\n }\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareAttribute(std::string id, Data::Type type, int encapsulation, int size) {\n Object* obj = (Object*) this->lastStatement;\n\n if(size > 0){\n Array* a = new Array(id, type, new Integer(size));\n a->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, true, a));\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return a;\n }else{\n VariableDeclaration* vd = new VariableDeclaration(type, new Variable(id, type));\n vd->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, true, vd));\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return vd;\n }\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareAssignAttribute(std::string id, Data::Type type, int encapsulation, TreeNode* value, int size) {\n if(this->checkIdentifier(id)) {\n if(size > 0) {\n Array* array = new Array(id, type, new Integer(size));\n array->setEncapsulation(encapsulation);\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n this->symbolTable.setInitializedSymbol(id, array);\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n return array;\n }\n\n this->symbolTable.addSymbol(id, Symbol(type, Symbol::VARIABLE, false)); \/\/ Adds variable to symbol table\n this->symbolTable.setInitializedSymbol(id, value);\n Variable* v = new Variable(id, type);\n VariableDeclaration* vD = new VariableDeclaration(type, v);\n vD->setEncapsulation(encapsulation);\n if(encapsulation == 1)\n this->symbolTable.getSymbol(id).setEncapsulation(true);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n return vD;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareMethod(std::string id, CodeBlock* params, CodeBlock* body, Data::Type returnType, int encapsulation) {\n Function* function;\n if(this->checkIdentifier(id)) {\n function = new Function(id, params, body, NULL);\n function->setType(returnType);\n function->setEncapsulation(encapsulation);\n\n this->symbolTable.addSymbol(id, Symbol(returnType, Symbol::FUNCTION, true, function));\n this->currentStructure = function;\n return function;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareFunction(std::string id, CodeBlock* params, CodeBlock* body, Data::Type returnType) {\n if(this->checkIdentifier(id)) {\n TreeNode* function;\n\n if(!id.compare(\"toc\")) { \/\/ Se é a função toc, cria a mesma\n function = new TocFunction(body);\n } else { \/\/ Outra função qualquer\n function = new Function(id, params, body, NULL);\n function->setType(returnType);\n }\n\n this->symbolTable.addSymbol(id, Symbol(returnType, Symbol::FUNCTION, true, function));\n this->currentStructure = function;\n this->lastStatement = function;\n return function;\n }\n\n return NULL;\n}\n\nTreeNode* SemanticAnalyzer::declareFunctionReturn(TreeNode* ret) {\n Function* f = (Function*) this->symbolTable.getParentStructure();\n if(f->classType() != TreeNode::FUNCTION){\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Return value for function \" + f->getId() + \"is different from expected;\" );\n }\n\n f->setReturn(ret);\n return NULL; \/\/ TODO\n}\n\nTreeNode* SemanticAnalyzer::declareCondition(TreeNode* expression, CodeBlock* body) {\n Conditional* cond = new Conditional(expression, body, NULL);\n this->currentStructure = cond;\n this->lastStatement = cond;\n return cond;\n}\n\nTreeNode* SemanticAnalyzer::declareElseCondition(CodeBlock* body) {\n std::string elseError = \"Else without a if.\";\n\n if(this->lastStatement->classType() != TreeNode::CONDITIONAL)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, elseError);\n\n Conditional* cond = (Conditional*) this->lastStatement;\n\n if(cond->hasElse())\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, elseError);\n\n cond->setElse(true);\n this->currentStructure = this->lastStatement;\n return this->currentStructure;\n}\n\nTreeNode* SemanticAnalyzer::declareLoop(TreeNode* init, TreeNode* test, TreeNode* attribuition) {\n Loop* loop;\n\n if(test == NULL) {\n Variable* v = (Variable*) attribuition;\n std::string id = v->getId();\n Array* array = (Array*)this->symbolTable.getSymbol(id, true).getData();\n loop = new Loop(init, test, array);\n }else{\n loop = new Loop(init, test, attribuition);\n }\n\n this->currentStructure = loop;\n return loop;\n}\n\nTreeNode* SemanticAnalyzer::declarePrint(TreeNode* param) {\n TreeNode* paramPrint = param;\n\n if(param->dataType() != Data::STR)\n paramPrint = new TypeCasting(Data::STR, paramPrint);\n\n return new PrintFunction(paramPrint);\n}\n\nTreeNode* SemanticAnalyzer::assignVariable(std::string id, TreeNode* value, TreeNode* index) {\n if(!this->symbolTable.existsSymbol(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Undeclared variable \" + id + \".\");\n return new Variable(id, Data::UNKNOWN); \/\/Creates variable node anyway\n } else if (index != NULL) {\n this->symbolTable.setInitializedSymbol(id);\n Array* a = (Array*)this->symbolTable.getSymbol(id).getData();\n return new Array(id, this->symbolTable.getSymbol(id).getDataType(), index, value);\n } else {\n this->symbolTable.setInitializedSymbol(id, value);\n Variable* v = new Variable(id, this->symbolTable.getSymbol(id, true).getDataType());\n v->setSymbolTable(this->symbolTable);\n return v;\n }\n}\n\nTreeNode* SemanticAnalyzer::declareAssignVariable(std::string id, Data::Type dataType, TreeNode* value, int size) {\n if(this->checkIdentifier(id)) {\n \/\/ sempre que size é maior do que zero, trata-se de uma declaração de array\n if(size > 0) {\n Array* array = new Array(id, dataType, new Integer(size), value);\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, array)); \/\/ Adds variable to symbol table and save array size\n this->symbolTable.setInitializedSymbol(id, array);\n return array;\n }\n\n this->symbolTable.addSymbol(id, Symbol(dataType, Symbol::VARIABLE, false, value)); \/\/ Adds variable to symbol table\n this->symbolTable.setInitializedSymbol(id, value);\n\n Variable* v = new Variable(id, dataType);\n VariableDeclaration* vD = new VariableDeclaration(dataType, v);\n v->setSymbolTable(this->symbolTable);\n vD->setSymbolTable(this->symbolTable);\n return vD;\n }\n\n \/\/ return a random variable case id is in use\n return new VariableDeclaration(dataType, new Variable(id, dataType));\n}\n\nTreeNode* SemanticAnalyzer::useVariable(std::string id, TreeNode* index) {\n if(!this->symbolTable.existsSymbol(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Undeclared variable \" + id + \".\");\n return new Variable(id, Data::UNKNOWN); \/\/Creates variable node anyway\n } else if(!this->symbolTable.isSymbolInitialized(id, true)) {\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Variable \" + id + \" used but not initialized.\");\n }\n\n TreeNode* t = this->symbolTable.getSymbol(id, true).getData();\n if (index != NULL and t->classType() == TreeNode::ARRAY) {\n Array* array = (Array*)t;\n if (array != NULL and array->getSize()->classType() == TreeNode::INTEGER) {\n if(((Integer*)index)->getValue() > ((Integer*)(array->getSize()))->getValue() || ((Integer*)index)->getValue() < 0)\n ERROR_LOGGER->log(ErrorLogger::SEMANTIC, \"Index out of bounds \" + id + \".\");\n }\n return new Array(id, this->symbolTable.getSymbol(id,true).getDataType(), index);\n }\n Variable* v = new Variable(id, this->symbolTable.getSymbol(id,true).getDataType());\n v->setSymbolTable(this->symbolTable);\n return v;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2015 In Cheol, Kang\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"eznetpp.h\"\n#include \"net\/tcp\/tcp_acceptor.h\"\n#include \"net\/tcp\/tcp_socket.h\"\n#include \"sys\/io_manager.h\"\n\neznetpp::sys::io_manager g_io_mgr(4, true);\n\nvoid sig_handler(int signum) {\n g_io_mgr.stop();\n}\n\nclass tcp_echosvr_session : public eznetpp::event::tcp_socket_event_handler\n{\n public:\n tcp_echosvr_session(eznetpp::net::tcp::tcp_socket* sock)\n {\n _socket = sock;\n }\n virtual ~tcp_echosvr_session() = default;\n\n public:\n \/\/ override\n void on_recv(const std::string& msg, int len)\n {\n \/\/printf(\"received %d bytes\\n\", len);\n ++recv_num;\n \/\/if (recv_num % 1000 == 0)\n \/\/ printf(\"[%d] received %d\\n\", _socket->descriptor(), recv_num);\n\n _socket->send_bytes(msg);\n }\n\n void on_send(unsigned int len)\n {\n \/\/printf(\"sent %d bytes\\n\", len);\n ++send_num;\n \/\/if (send_num % 1000 == 0)\n \/\/ printf(\"[%d] sent %d\\n\", _socket->descriptor(), send_num);\n }\n\n void on_close(int err_no)\n {\n printf(\"closed the session(%d)\\n\", err_no);\n }\n\n void on_connect(int err_no)\n {\n \/\/ do not need\n };\n\n private:\n eznetpp::net::tcp::tcp_socket* _socket;\n unsigned int recv_num = 0;\n unsigned int send_num = 0;\n};\n\nclass tcp_echo_server : public eznetpp::event::tcp_acceptor_event_handler\n{\n public:\n tcp_echo_server(eznetpp::sys::io_manager* io_mgr)\n {\n _io_mgr = io_mgr;\n }\n virtual ~tcp_echo_server() = default;\n\n int open(int port, int backlog)\n {\n int ret = _acceptor.open(port, backlog);\n\n if (ret)\n {\n printf(\"%s\\n\", eznetpp::errcode::errno_to_str(ret).c_str());\n return -1;\n }\n\n _io_mgr->register_socket_event_handler(&_acceptor, this);\n\n return 0;\n }\n\n \/\/ override\n void on_accept(eznetpp::net::tcp::tcp_socket* sock, int err_no)\n {\n printf(\"on_accept\\n\");\n _io_mgr->register_socket_event_handler(sock, new tcp_echosvr_session(sock));\n }\n\n void on_close(int err_no)\n {\n printf(\"closed the acceptor(%d)\\n\", err_no);\n }\n\n private:\n eznetpp::sys::io_manager* _io_mgr = nullptr;\n eznetpp::net::tcp::tcp_acceptor _acceptor;\n};\n\nint main(void)\n{\n signal(SIGINT, sig_handler);\n\n g_io_mgr.init();\n\n tcp_echo_server server(&g_io_mgr);\n server.open(56789, 5);\n\n g_io_mgr.loop();\n\n return 0;\n}\n* update\/* Copyright (c) 2015 In Cheol, Kang\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"eznetpp.h\"\n#include \"net\/tcp\/tcp_acceptor.h\"\n#include \"net\/tcp\/tcp_socket.h\"\n#include \"sys\/io_manager.h\"\n\neznetpp::sys::io_manager g_io_mgr(false);\n\nvoid sig_handler(int signum) {\n g_io_mgr.stop();\n}\n\nclass tcp_echosvr_session : public eznetpp::event::tcp_socket_event_handler\n{\n public:\n tcp_echosvr_session(eznetpp::net::tcp::tcp_socket* sock)\n {\n _socket = sock;\n }\n virtual ~tcp_echosvr_session() = default;\n\n public:\n \/\/ override\n void on_recv(const std::string& msg, int len)\n {\n \/\/printf(\"received %d bytes\\n\", len);\n ++recv_num;\n \/\/if (recv_num % 1000 == 0)\n \/\/ printf(\"[%d] received %d\\n\", _socket->descriptor(), recv_num);\n\n _socket->send_bytes(msg);\n }\n\n void on_send(unsigned int len)\n {\n \/\/printf(\"sent %d bytes\\n\", len);\n ++send_num;\n \/\/if (send_num % 1000 == 0)\n \/\/ printf(\"[%d] sent %d\\n\", _socket->descriptor(), send_num);\n }\n\n void on_close(int err_no)\n {\n printf(\"closed the session(%d)\\n\", err_no);\n }\n\n void on_connect(int err_no)\n {\n \/\/ do not need\n };\n\n private:\n eznetpp::net::tcp::tcp_socket* _socket;\n unsigned int recv_num = 0;\n unsigned int send_num = 0;\n};\n\nclass tcp_echo_server : public eznetpp::event::tcp_acceptor_event_handler\n{\n public:\n tcp_echo_server(eznetpp::sys::io_manager* io_mgr)\n {\n _io_mgr = io_mgr;\n }\n virtual ~tcp_echo_server() = default;\n\n int open(int port, int backlog)\n {\n int ret = _acceptor.open(port, backlog);\n\n if (ret)\n {\n printf(\"%s\\n\", eznetpp::errcode::errno_to_str(ret).c_str());\n return -1;\n }\n\n _io_mgr->register_socket_event_handler(&_acceptor, this);\n\n return 0;\n }\n\n \/\/ override\n void on_accept(eznetpp::net::tcp::tcp_socket* sock, int err_no)\n {\n printf(\"on_accept\\n\");\n _io_mgr->register_socket_event_handler(sock, new tcp_echosvr_session(sock));\n }\n\n void on_close(int err_no)\n {\n printf(\"closed the acceptor(%d)\\n\", err_no);\n }\n\n private:\n eznetpp::sys::io_manager* _io_mgr = nullptr;\n eznetpp::net::tcp::tcp_acceptor _acceptor;\n};\n\nint main(void)\n{\n signal(SIGINT, sig_handler);\n\n g_io_mgr.init();\n\n tcp_echo_server server(&g_io_mgr);\n server.open(56789, 5);\n\n g_io_mgr.loop();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef SNR_HPP\n#define SNR_HPP\n\nnamespace PulsarSearch {\n\ntemplate< typename T > using snrFunc = void (*)(const AstroData::Observation< T > &, const float *, float *);\n\n\/\/ Sequential SNR\ntemplate< typename T > void snrFoldedTS(const AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs);\n\/\/ OpenCL SNR\ntemplate< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation);\n\/\/ SIMD SNR\nstd::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi = false);\n\n\n\/\/ Implementations\ntemplate< typename T > void snrFoldedTS(AstroData::Observation< T > & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs) {\n\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\tfor ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n\t\t\tT max = 0;\n\t\t\tfloat average = 0.0f;\n\t\t\tfloat rms = 0.0f;\n\n\t\t\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\t\t\tT value = foldedTS[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm];\n\n\t\t\t\taverage += value;\n\t\t\t\trms += (value * value);\n\n\t\t\t\tif ( value > max ) {\n\t\t\t\t\tmax = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\taverage \/= observation.getNrBins();\n\t\t\trms = std::sqrt(rms \/ observation.getNrBins());\n\n\t\t\tsnrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) \/ rms;\n\t\t}\n\t}\n}\n\ntemplate< typename T > std::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation< T > & observation) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n std::string nrPaddedDMs_s = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs());\n std::string nrBinsInverse_s = isa::utils::toString< float >(1.0f \/ observation.getNrBins());\n\n *code = \"__kernel void snr(__global const \" + dataType + \" * const restrict foldedData, __global \" + dataType + \" * const restrict snrs) {\\n\"\n \"<%DEF_DM%>\"\n \"<%DEF_PERIOD%>\"\n + dataType + \" globalItem = 0;\\n\"\n + dataType + \" average = 0;\\n\"\n + dataType + \" rms = 0;\\n\"\n + dataType + \" max = 0;\\n\"\n \"\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\";\n std::string defDMsTemplate = \"const unsigned int dm<%DM_NUM%> = (get_group_id(0) * \" + isa::utils::toString< unsigned int >(nrDMsPerBlock * nrDMsPerThread) + \") + get_local_id(0) + <%DM_NUM%>;\\n\";\n std::string defPeriodsTemplate = \"const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * \" + isa::utils::toString< unsigned int >(nrPeriodsPerBlock * nrPeriodsPerThread) + \") + get_local_id(1) + <%PERIOD_NUM%>;\\n\";\n std::string computeTemplate = \"average = 0;\\n\"\n \"rms = 0;\\n\"\n \"max = 0;\\n\"\n \"for ( unsigned int bin = 0; bin < \" + isa::utils::toString< unsigned int >(observation.getNrBins()) + \"; bin++ ) {\\n\"\n \"globalItem = foldedData[(bin * \" + isa::utils::toString< unsigned int >(observation.getNrPeriods()) + \" * \" + nrPaddedDMs_s + \") + (period<%PERIOD_NUM%> * \" + nrPaddedDMs_s + \") + dm<%DM_NUM%>];\\n\"\n \"average += globalItem;\\n\"\n \"rms += (globalItem * globalItem);\\n\"\n \"max = fmax(max, globalItem);\\n\"\n \"}\\n\"\n \"average *= \" + nrBinsInverse_s + \"f;\\n\"\n \"rms *= \" + nrBinsInverse_s + \"f;\\n\"\n \"snrs[(period<%PERIOD_NUM%> * \" + nrPaddedDMs_s + \") + dm<%DM_NUM%>] = (max - average) \/ native_sqrt(rms);\\n\";\n \/\/ End kernel's template\n\n std::string * defDM_s = new std::string();\n std::string * defPeriod_s = new std::string();\n std::string * compute_s = new std::string();\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(&defDMsTemplate, \"<%DM_NUM%>\", dm_s);\n defDM_s->append(*temp_s);\n delete temp_s;\n }\n for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {\n std::string period_s = isa::utils::toString< unsigned int >(period);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(&defPeriodsTemplate, \"<%PERIOD_NUM%>\", period_s);\n defPeriod_s->append(*temp_s);\n delete temp_s;\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n\n temp_s = isa::utils::replace(&computeTemplate, \"<%PERIOD_NUM%>\", period_s);\n temp_s = isa::utils::replace(temp_s, \"<%DM_NUM%>\", dm_s, true);\n compute_s->append(*temp_s);\n delete temp_s;\n }\n }\n\n code = isa::utils::replace(code, \"<%DEF_DM%>\", *defDM_s, true);\n code = isa::utils::replace(code, \"<%DEF_PERIOD%>\", *defPeriod_s, true);\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n\n return code;\n}\n\nstd::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi) {\n std::string * code = new std::string();\n std::string * computeTemplate = new std::string();\n\n \/\/ Begin kernel's template\n if ( !phi ) {\n *code = \"namespace PulsarSearch {\\n\"\n \"template< typename T > void snrAVX\" + isa::utils::toString(nrDMsPerThread) + \"x\" + isa::utils::toString(nrPeriodsPerThread) + \"(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\\n\"\n \"{\\n\"\n \"__m256 max = _mm256_setzero_ps();\\n\"\n \"__m256 average = _mm256_setzero_ps();\\n\"\n \"__m256 rms = _mm256_setzero_ps();\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int period = 0; period < observation.getNrPeriods(); period += \" + isa::utils::toString(nrPeriodsPerThread) + \") {\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += \" + isa::utils::toString(nrPeriodsPerThread) + \" * 8) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\";\n *computeTemplate = \"max = _mm256_setzero_ps();\\n\"\n \"average = _mm256_setzero_ps();\\n\"\n \"rms = _mm256_setzero_ps();\\n\"\n \"\\n\"\n \"for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\\n\"\n \"__m256 value = _mm256_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\\n\"\n \"\\n\"\n \"average = _mm256_add_ps(average, value);\\n\"\n \"rms = _mm256_add_ps(rms, _mm256_mul_ps(value, value));\\n\"\n \"max = _mm256_max_ps(max, value);\\n\"\n \"}\\n\"\n \"average = _mm256_div_ps(average, _mm256_set1_ps(observation.getNrBins()));\\n\"\n \"rms = _mm256_sqrt_ps(_mm256_div_ps(rms, _mm256_set1_ps(observation.getNrBins())));\\n\"\n \"_mm256_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm256_div_ps(_mm256_sub_ps(max, average), rms));\\n\";\n } else {\n *code = \"namespace PulsarSearch {\\n\"\n \"template< typename T > void snrPhi\" + isa::utils::toString(nrDMsPerThread) + \"x\" + isa::utils::toString(nrPeriodsPerThread) + \"(const AstroData::Observation< T > & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\\n\"\n \"{\\n\"\n \"__m512 max = _mm512_setzero_ps();\\n\"\n \"__m512 average = _mm512_setzero_ps();\\n\"\n \"__m512 rms = _mm512_setzero_ps();\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int period = 0; period < observation.getNrPeriods(); period += \" + isa::utils::toString(nrPeriodsPerThread) + \") {\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += \" + isa::utils::toString(nrPeriodsPerThread) + \" * 16) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\";\n *computeTemplate = \"max = _mm512_setzero_ps();\\n\"\n \"average = _mm512_setzero_ps();\\n\"\n \"rms = _mm512_setzero_ps();\\n\"\n \"\\n\"\n \"for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\\n\"\n \"__m512 value = _mm512_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\\n\"\n \"\\n\"\n \"average = _mm512_add_ps(average, value);\\n\"\n \"rms = _mm512_add_ps(rms, _mm512_mul_ps(value, value));\\n\"\n \"max = _mm512_max_ps(max, value);\\n\"\n \"}\\n\"\n \"average = _mm512_div_ps(average, _mm512_set1_ps(observation.getNrBins()));\\n\"\n \"rms = _mm512_sqrt_ps(_mm512_div_ps(rms, _mm512_set1_ps(observation.getNrBins())));\\n\"\n \"_mm512_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm512_div_ps(_mm512_sub_ps(max, average), rms));\\n\";\n }\n \/\/ End kernel's template\n\n std::string * compute_s = new std::string();\n\n for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {\n std::string period_s = isa::utils::toString< unsigned int >(period);\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(computeTemplate, \"<%PERIOD_NUM%>\", period_s);\n temp_s = isa::utils::replace(temp_s, \"<%DM_NUM%>\", dm_s, true);\n compute_s->append(*temp_s);\n delete temp_s;\n }\n }\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n delete compute_s;\n\n delete computeTemplate;\n return code;\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ SNR_HPP\n\nUsing the new observation. No need for templates.\/\/ Copyright 2014 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef SNR_HPP\n#define SNR_HPP\n\nnamespace PulsarSearch {\n\ntemplate< typename T > using snrFunc = void (*)(const AstroData::Observation &, const float *, float *);\n\n\/\/ Sequential SNR\ntemplate< typename T > void snrFoldedTS(const AstroData::Observation & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs);\n\/\/ OpenCL SNR\nstd::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation & observation);\n\/\/ SIMD SNR\nstd::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi = false);\n\n\n\/\/ Implementations\ntemplate< typename T > void snrFoldedTS(AstroData::Observation & observation, const std::vector< T > & foldedTS, std::vector< T > & snrs) {\n\tfor ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n\t\tfor ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n\t\t\tT max = 0;\n\t\t\tfloat average = 0.0f;\n\t\t\tfloat rms = 0.0f;\n\n\t\t\tfor ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n\t\t\t\tT value = foldedTS[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm];\n\n\t\t\t\taverage += value;\n\t\t\t\trms += (value * value);\n\n\t\t\t\tif ( value > max ) {\n\t\t\t\t\tmax = value;\n\t\t\t\t}\n\t\t\t}\n\t\t\taverage \/= observation.getNrBins();\n\t\t\trms = std::sqrt(rms \/ observation.getNrBins());\n\n\t\t\tsnrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) \/ rms;\n\t\t}\n\t}\n}\n\nstd::string * getSNROpenCL(const unsigned int nrDMsPerBlock, const unsigned int nrPeriodsPerBlock, const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, std::string & dataType, const AstroData::Observation & observation) {\n std::string * code = new std::string();\n\n \/\/ Begin kernel's template\n std::string nrPaddedDMs_s = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs());\n std::string nrBinsInverse_s = isa::utils::toString< float >(1.0f \/ observation.getNrBins());\n\n *code = \"__kernel void snr(__global const \" + dataType + \" * const restrict foldedData, __global \" + dataType + \" * const restrict snrs) {\\n\"\n \"<%DEF_DM%>\"\n \"<%DEF_PERIOD%>\"\n + dataType + \" globalItem = 0;\\n\"\n + dataType + \" average = 0;\\n\"\n + dataType + \" rms = 0;\\n\"\n + dataType + \" max = 0;\\n\"\n \"\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\";\n std::string defDMsTemplate = \"const unsigned int dm<%DM_NUM%> = (get_group_id(0) * \" + isa::utils::toString< unsigned int >(nrDMsPerBlock * nrDMsPerThread) + \") + get_local_id(0) + <%DM_NUM%>;\\n\";\n std::string defPeriodsTemplate = \"const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * \" + isa::utils::toString< unsigned int >(nrPeriodsPerBlock * nrPeriodsPerThread) + \") + get_local_id(1) + <%PERIOD_NUM%>;\\n\";\n std::string computeTemplate = \"average = 0;\\n\"\n \"rms = 0;\\n\"\n \"max = 0;\\n\"\n \"for ( unsigned int bin = 0; bin < \" + isa::utils::toString< unsigned int >(observation.getNrBins()) + \"; bin++ ) {\\n\"\n \"globalItem = foldedData[(bin * \" + isa::utils::toString< unsigned int >(observation.getNrPeriods()) + \" * \" + nrPaddedDMs_s + \") + (period<%PERIOD_NUM%> * \" + nrPaddedDMs_s + \") + dm<%DM_NUM%>];\\n\"\n \"average += globalItem;\\n\"\n \"rms += (globalItem * globalItem);\\n\"\n \"max = fmax(max, globalItem);\\n\"\n \"}\\n\"\n \"average *= \" + nrBinsInverse_s + \"f;\\n\"\n \"rms *= \" + nrBinsInverse_s + \"f;\\n\"\n \"snrs[(period<%PERIOD_NUM%> * \" + nrPaddedDMs_s + \") + dm<%DM_NUM%>] = (max - average) \/ native_sqrt(rms);\\n\";\n \/\/ End kernel's template\n\n std::string * defDM_s = new std::string();\n std::string * defPeriod_s = new std::string();\n std::string * compute_s = new std::string();\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(&defDMsTemplate, \"<%DM_NUM%>\", dm_s);\n defDM_s->append(*temp_s);\n delete temp_s;\n }\n for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {\n std::string period_s = isa::utils::toString< unsigned int >(period);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(&defPeriodsTemplate, \"<%PERIOD_NUM%>\", period_s);\n defPeriod_s->append(*temp_s);\n delete temp_s;\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n\n temp_s = isa::utils::replace(&computeTemplate, \"<%PERIOD_NUM%>\", period_s);\n temp_s = isa::utils::replace(temp_s, \"<%DM_NUM%>\", dm_s, true);\n compute_s->append(*temp_s);\n delete temp_s;\n }\n }\n\n code = isa::utils::replace(code, \"<%DEF_DM%>\", *defDM_s, true);\n code = isa::utils::replace(code, \"<%DEF_PERIOD%>\", *defPeriod_s, true);\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n\n return code;\n}\n\nstd::string * getSNRSIMD(const unsigned int nrDMsPerThread, const unsigned int nrPeriodsPerThread, bool phi) {\n std::string * code = new std::string();\n std::string * computeTemplate = new std::string();\n\n \/\/ Begin kernel's template\n if ( !phi ) {\n *code = \"namespace PulsarSearch {\\n\"\n \"template< typename T > void snrAVX\" + isa::utils::toString(nrDMsPerThread) + \"x\" + isa::utils::toString(nrPeriodsPerThread) + \"(const AstroData::Observation & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\\n\"\n \"{\\n\"\n \"__m256 max = _mm256_setzero_ps();\\n\"\n \"__m256 average = _mm256_setzero_ps();\\n\"\n \"__m256 rms = _mm256_setzero_ps();\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int period = 0; period < observation.getNrPeriods(); period += \" + isa::utils::toString(nrPeriodsPerThread) + \") {\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += \" + isa::utils::toString(nrPeriodsPerThread) + \" * 8) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\";\n *computeTemplate = \"max = _mm256_setzero_ps();\\n\"\n \"average = _mm256_setzero_ps();\\n\"\n \"rms = _mm256_setzero_ps();\\n\"\n \"\\n\"\n \"for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\\n\"\n \"__m256 value = _mm256_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\\n\"\n \"\\n\"\n \"average = _mm256_add_ps(average, value);\\n\"\n \"rms = _mm256_add_ps(rms, _mm256_mul_ps(value, value));\\n\"\n \"max = _mm256_max_ps(max, value);\\n\"\n \"}\\n\"\n \"average = _mm256_div_ps(average, _mm256_set1_ps(observation.getNrBins()));\\n\"\n \"rms = _mm256_sqrt_ps(_mm256_div_ps(rms, _mm256_set1_ps(observation.getNrBins())));\\n\"\n \"_mm256_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm256_div_ps(_mm256_sub_ps(max, average), rms));\\n\";\n } else {\n *code = \"namespace PulsarSearch {\\n\"\n \"template< typename T > void snrPhi\" + isa::utils::toString(nrDMsPerThread) + \"x\" + isa::utils::toString(nrPeriodsPerThread) + \"(const AstroData::Observation & observation, const float * const __restrict__ foldedData, float * const __restrict__ snrs) {\\n\"\n \"{\\n\"\n \"__m512 max = _mm512_setzero_ps();\\n\"\n \"__m512 average = _mm512_setzero_ps();\\n\"\n \"__m512 rms = _mm512_setzero_ps();\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int period = 0; period < observation.getNrPeriods(); period += \" + isa::utils::toString(nrPeriodsPerThread) + \") {\\n\"\n \"#pragma omp parallel for schedule(static)\\n\"\n \"for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm += \" + isa::utils::toString(nrPeriodsPerThread) + \" * 16) {\\n\"\n \"<%COMPUTE%>\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\"\n \"}\\n\";\n *computeTemplate = \"max = _mm512_setzero_ps();\\n\"\n \"average = _mm512_setzero_ps();\\n\"\n \"rms = _mm512_setzero_ps();\\n\"\n \"\\n\"\n \"for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\\n\"\n \"__m512 value = _mm512_load_ps(&(foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + ((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]));\\n\"\n \"\\n\"\n \"average = _mm512_add_ps(average, value);\\n\"\n \"rms = _mm512_add_ps(rms, _mm512_mul_ps(value, value));\\n\"\n \"max = _mm512_max_ps(max, value);\\n\"\n \"}\\n\"\n \"average = _mm512_div_ps(average, _mm512_set1_ps(observation.getNrBins()));\\n\"\n \"rms = _mm512_sqrt_ps(_mm512_div_ps(rms, _mm512_set1_ps(observation.getNrBins())));\\n\"\n \"_mm512_store_ps(&(snrs[((period + <%PERIOD_NUM%>) * observation.getNrPaddedDMs()) + dm + <%DM_NUM%>]),_mm512_div_ps(_mm512_sub_ps(max, average), rms));\\n\";\n }\n \/\/ End kernel's template\n\n std::string * compute_s = new std::string();\n\n for ( unsigned int period = 0; period < nrPeriodsPerThread; period++ ) {\n std::string period_s = isa::utils::toString< unsigned int >(period);\n\n for ( unsigned int dm = 0; dm < nrDMsPerThread; dm++ ) {\n std::string dm_s = isa::utils::toString< unsigned int >(dm);\n std::string * temp_s = 0;\n\n temp_s = isa::utils::replace(computeTemplate, \"<%PERIOD_NUM%>\", period_s);\n temp_s = isa::utils::replace(temp_s, \"<%DM_NUM%>\", dm_s, true);\n compute_s->append(*temp_s);\n delete temp_s;\n }\n }\n code = isa::utils::replace(code, \"<%COMPUTE%>\", *compute_s, true);\n delete compute_s;\n\n delete computeTemplate;\n return code;\n}\n\n} \/\/ PulsarSearch\n\n#endif \/\/ SNR_HPP\n\n<|endoftext|>"} {"text":"\/*\r\n * System_stateIdle.cpp\r\n *\r\n * Created on: Jun 19, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n\/\/ this\r\n#include \"System.hpp\"\r\n\r\n\/\/ local\r\n#include \"Defines.hpp\"\r\n\r\nusing namespace concurrency;\r\n\r\nvoid System::changeToIdle() {\r\n FileSystem::init(localAddress.ip);\r\n requestSystemState();\r\n httpThread = Thread([this]() {\r\n while (state == newState) {\r\n httpServer();\r\n Thread::sleep(MS_SLEEP);\r\n }\r\n });\r\n httpThread.start();\r\n}\r\n\r\nvoid System::stateIdle() {\r\n listen();\r\n speak();\r\n detectFailure();\r\n executeProtocol();\r\n}\r\nFixing bug\/*\r\n * System_stateIdle.cpp\r\n *\r\n * Created on: Jun 19, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n\/\/ this\r\n#include \"System.hpp\"\r\n\r\n\/\/ local\r\n#include \"Defines.hpp\"\r\n#include \"FileSystem.hpp\"\r\n\r\nusing namespace concurrency;\r\n\r\nvoid System::changeToIdle() {\r\n FileSystem::init(localAddress.ip);\r\n requestSystemState();\r\n httpThread = Thread([this]() {\r\n while (state == newState) {\r\n httpServer();\r\n Thread::sleep(MS_SLEEP);\r\n }\r\n });\r\n httpThread.start();\r\n}\r\n\r\nvoid System::stateIdle() {\r\n listen();\r\n speak();\r\n detectFailure();\r\n executeProtocol();\r\n}\r\n<|endoftext|>"} {"text":"\/*=============================================================================\n\tCopyright (c) 2012-2014 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ subroutines for EZD global minimization\n\/\/ Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du.\n\/\/ \"A new algorithm for the automation of phase diagram calculation.\" Computational Materials Science 35.1 (2006): 61-74.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ezd_minimization.hpp\"\n#include \"libgibbs\/include\/compositionset.hpp\"\n#include \"libgibbs\/include\/constraint.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/halton.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ndsimplex.hpp\"\n#include \"libgibbs\/include\/utils\/cholesky.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::vector> AdaptiveSearchND (\n CompositionSet const &phase,\n evalconditions const& conditions,\n const SimplexCollection &search_region,\n const std::size_t depth );\n\nnamespace Optimizer\n{\n\n\/\/ TODO: Should this be a member function of GibbsOpt?\n\/\/ The function calling LocateMinima definitely should be at least (needs access to all CompositionSets)\n\/\/ LocateMinima finds all of the minima for a given phase's Gibbs energy\n\/\/ In addition to allowing us to choose a better starting point, this will allow for automatic miscibility gap detection\nvoid LocateMinima (\n CompositionSet const &phase,\n sublattice_set const &sublset,\n evalconditions const& conditions,\n const std::size_t depth \/\/ depth tracking for recursion\n)\n {\n constexpr const std::size_t subdivisions_per_axis = 5; \/\/ TODO: make this user-configurable\n using namespace boost::numeric::ublas;\n\n \/\/ EZD Global Minimization (Emelianenko et al., 2006)\n \/\/ First: FIND CONCAVITY REGIONS\n std::vector> points, minima;\n std::vector start_simplices;\n std::vector positive_definite_regions;\n std::vector components_in_sublattice;\n\n \/\/ Get the first sublattice for this phase\n boost::multi_index::index::type::iterator ic0,ic1;\n int sublindex = 0;\n ic0 = boost::multi_index::get ( sublset ).lower_bound ( boost::make_tuple ( phase.name(), sublindex ) );\n ic1 = boost::multi_index::get ( sublset ).upper_bound ( boost::make_tuple ( phase.name(), sublindex ) );;\n\n \/\/ (1) Sample some points on the domain using NDSimplex\n \/\/ Because the grid is uniform, we can assume that each point is the center of an N-simplex\n\n \/\/ Determine number of components in each sublattice\n while ( ic0 != ic1 )\n {\n const std::size_t number_of_species = std::distance ( ic0,ic1 );\n if ( number_of_species > 0 )\n {\n NDSimplex base ( number_of_species-1 ); \/\/ construct the unit (q-1)-simplex\n components_in_sublattice.emplace_back ( base.simplex_subdivide ( subdivisions_per_axis ) );\n }\n \/\/ Next sublattice\n ++sublindex;\n ic0 = boost::multi_index::get ( sublset ).lower_bound ( boost::make_tuple ( phase.name(), sublindex ) );\n ic1 = boost::multi_index::get ( sublset ).end();\n }\n\n \/\/ Take all combinations of generated points in each sublattice\n start_simplices = lattice_complex ( components_in_sublattice );\n\n\n for ( SimplexCollection& simpcol : start_simplices )\n {\n std::cout << \"(\";\n std::vector pt;\n for ( NDSimplex& simp : simpcol )\n {\n std::vector sub_pt = simp.centroid_with_dependent_component();\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n for ( auto i = pt.begin(); i != pt.end(); ++i )\n {\n std::cout << *i;\n if ( std::distance ( i,pt.end() ) > 1 ) std::cout << \",\";\n }\n std::cout << \")\" << std::endl;\n points.emplace_back ( std::move ( pt ) );\n }\n\n \/\/ (2) Calculate the Lagrangian Hessian for all sampled points\n for ( SimplexCollection& simpcol : start_simplices )\n {\n std::vector pt;\n for ( NDSimplex& simp : simpcol )\n {\n \/\/ Generate the current point from all the simplices in each sublattice\n std::vector sub_pt = simp.centroid_with_dependent_component();\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n if ( pt.size() == 0 ) continue; \/\/ skip empty (invalid) points\n symmetric_matrix Hessian ( zero_matrix ( pt.size(),pt.size() ) );\n try\n {\n Hessian = phase.evaluate_objective_hessian_matrix ( conditions, phase.get_variable_map(), pt );\n }\n catch ( boost::exception &e )\n {\n std::cout << boost::diagnostic_information ( e );\n throw;\n }\n catch ( std::exception &e )\n {\n std::cout << e.what();\n throw;\n }\n \/\/std::cout << \"Hessian: \" << Hessian << std::endl;\n \/\/ NOTE: For this calculation we consider only the linear constraints for an isolated phase (e.g., site fraction balances)\n \/\/ (3) Save all points for which the Lagrangian Hessian is positive definite in the null space of the constraint gradient matrix\n \/\/ NOTE: This is the projected Hessian method (Nocedal and Wright, 2006, ch. 12.4, p.349)\n \/\/ But how do I choose the Lagrange multipliers for all the constraints? Can I calculate them?\n \/\/ The answer is that, because the constraints are linear, there is no constraint contribution to the Hessian.\n \/\/ That means that the Hessian of the Lagrangian is just the Hessian of the objective function.\n const std::size_t Zcolumns = pt.size() - phase.get_constraints().size();\n \/\/ Z is the constraint null space matrix = phase.get_constraint_null_space_matrix()\n \/\/ (a) Set Hproj = transpose(Z)*(L'')*Z\n matrix Hproj ( pt.size(), Zcolumns );\n Hproj = prod ( trans ( phase.get_constraint_null_space_matrix() ),\n matrix ( prod ( Hessian,phase.get_constraint_null_space_matrix() ) ) );\n \/\/std::cout << \"Hproj: \" << Hproj << std::endl;\n \/\/ (b) Verify that all diagonal elements of Hproj are strictly positive; if not, remove this point from consideration\n \/\/ NOTE: This is a necessary but not sufficient condition that a matrix be positive definite, and it's easy to check\n \/\/ Reference: Carlen and Carvalho, 2007, p. 148, Eq. 5.12\n \/\/ TODO: Currently not bothering to do this; should perform a test to figure out if there would be a performance increase\n \/\/ (c) Attempt a Cholesky factorization of Hproj; will only succeed if matrix is positive definite\n const bool is_positive_definite = cholesky_factorize ( Hproj );\n \/\/ (d) If it succeeds, save this point; else, discard it\n if ( is_positive_definite )\n {\n positive_definite_regions.push_back ( simpcol );\n for ( double i : pt ) std::cout << i << \",\";\n std::cout << \":\" << std::endl;\n }\n }\n\n \/\/ positive_definite_regions is now filled\n \/\/ Perform recursive search for minima on each of the identified regions\n for ( const SimplexCollection &simpcol : positive_definite_regions )\n {\n \/\/ We start at a recursive depth of 2 because we treat LocateMinima as depth == 1\n \/\/ This allows our notation for depth to be consistent with Emelianenko et al.\n std::vector> region_minima = AdaptiveSearchND ( phase, conditions, simpcol, 2 );\n \/\/ Append this region's minima to the list of minima\n \/\/ minima.size() > 1 means there is a miscilibility gap\n minima.reserve ( minima.size() +region_minima.size() );\n minima.insert ( minima.end(), std::make_move_iterator ( region_minima.begin() ), std::make_move_iterator ( region_minima.end() ) );\n }\n }\n\n\/\/ namespace Optimizer\n}\n\n\/\/ Recursive function for searching composition space for minima\n\/\/ Input: Simplex that bounds a positive definite search region (SimplexCollection is used for multiple sublattices)\n\/\/ Input: Recursion depth\n\/\/ Output: Vector of minimum points\nstd::vector> AdaptiveSearchND (\n CompositionSet const &phase,\n evalconditions const& conditions,\n const SimplexCollection &search_region,\n const std::size_t depth )\n {\n BOOST_ASSERT ( depth > 0 );\n constexpr const double gradient_magnitude_threshold = 1e8;\n constexpr const std::size_t subdivisions_per_axis = 2;\n constexpr const std::size_t max_depth = 5;\n std::vector> minima;\n std::vector pt;\n\n \/\/ (1) Calculate the objective gradient (L') for the centroid of the active simplex\n for ( const NDSimplex& simp : search_region )\n {\n \/\/ Generate the current point (pt) from all the simplices in each sublattice\n std::vector sub_pt = simp.centroid_with_dependent_component();\n \/\/std::cout << \"[\";\n \/\/for (double i : sub_pt) std::cout << i << \",\";\n \/\/std::cout << \"]\" << std::endl;\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n \/\/double obj = phase.evaluate_objective ( conditions, phase.get_variable_map(), &pt[0] );\n \/\/std::cout << obj << std::endl;\n std::vector gradient = phase.evaluate_internal_objective_gradient ( conditions, &pt[0] );\n double mag = 0;\n for ( auto i = gradient.begin(); i != gradient.end(); ++i )\n {\n \/\/std::cout << \"gradient[\" << std::distance(gradient.begin(),i) << \"] = \" << *i << std::endl;\n mag += pow ( *i,2 );\n }\n \/\/ (2) If that magnitude is less than some defined epsilon, return z as a minimum\n \/\/ Else simplex_subdivide() the active region and send to next depth (return minima from that)\n if (mag < gradient_magnitude_threshold) {\n std::cout << \"new minpoint \";\n for ( auto i = pt.begin(); i != pt.end(); ++i )\n {\n std::cout << *i;\n if ( std::distance ( i,pt.end() ) > 1 ) std::cout << \",\";\n }\n std::cout << \" gradient sq: \" << mag << std::endl;\n for ( auto i = gradient.begin(); i != gradient.end(); ++i )\n {\n std::cout << \"gradient[\" << std::distance(gradient.begin(),i) << \"] = \" << *i << std::endl;\n }\n minima.push_back(pt);\n }\n else {\n if (depth == max_depth) return minima; \/\/ we've hit max depth, return what we have (nothing)\n std::vector simplex_combinations, new_simplices;\n \/\/ simplex_subdivide() the simplices in all the active sublattices\n for (const NDSimplex &simp : search_region) {\n simplex_combinations.emplace_back(simp.simplex_subdivide(subdivisions_per_axis));\n }\n \/\/ lattice_complex() the result to generate all the combinations in the sublattices\n new_simplices = lattice_complex(simplex_combinations);\n \/\/ send each new SimplexCollection to the next depth\n for (const SimplexCollection &sc : new_simplices) {\n std::vector> recursive_minima = AdaptiveSearchND(phase, conditions, sc, depth+1);\n \/\/ Add the found minima to the list of known minima\n minima.reserve(minima.size()+recursive_minima.size());\n minima.insert ( minima.end(), std::make_move_iterator ( recursive_minima.begin() ), std::make_move_iterator ( recursive_minima.end() ) );\n }\n }\n return minima;\n }\n\/\/ kate: indent-mode cstyle; indent-width 4; replace-tabs on; \nUnstable commit devising a projected gradient calculation\/*=============================================================================\n\tCopyright (c) 2012-2014 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ subroutines for EZD global minimization\n\/\/ Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du.\n\/\/ \"A new algorithm for the automation of phase diagram calculation.\" Computational Materials Science 35.1 (2006): 61-74.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ezd_minimization.hpp\"\n#include \"libgibbs\/include\/compositionset.hpp\"\n#include \"libgibbs\/include\/constraint.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/halton.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ndsimplex.hpp\"\n#include \"libgibbs\/include\/utils\/cholesky.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstd::vector> AdaptiveSearchND (\n CompositionSet const &phase,\n evalconditions const& conditions,\n const SimplexCollection &search_region,\n const std::size_t depth );\n\nnamespace Optimizer\n{\n\n\/\/ TODO: Should this be a member function of GibbsOpt?\n\/\/ The function calling LocateMinima definitely should be at least (needs access to all CompositionSets)\n\/\/ LocateMinima finds all of the minima for a given phase's Gibbs energy\n\/\/ In addition to allowing us to choose a better starting point, this will allow for automatic miscibility gap detection\nvoid LocateMinima (\n CompositionSet const &phase,\n sublattice_set const &sublset,\n evalconditions const& conditions,\n const std::size_t depth \/\/ depth tracking for recursion\n)\n {\n constexpr const std::size_t subdivisions_per_axis = 5; \/\/ TODO: make this user-configurable\n using namespace boost::numeric::ublas;\n\n \/\/ EZD Global Minimization (Emelianenko et al., 2006)\n \/\/ First: FIND CONCAVITY REGIONS\n std::vector> points, minima;\n std::vector start_simplices;\n std::vector positive_definite_regions;\n std::vector components_in_sublattice;\n\n \/\/ Get the first sublattice for this phase\n boost::multi_index::index::type::iterator ic0,ic1;\n int sublindex = 0;\n ic0 = boost::multi_index::get ( sublset ).lower_bound ( boost::make_tuple ( phase.name(), sublindex ) );\n ic1 = boost::multi_index::get ( sublset ).upper_bound ( boost::make_tuple ( phase.name(), sublindex ) );;\n\n \/\/ (1) Sample some points on the domain using NDSimplex\n \/\/ Because the grid is uniform, we can assume that each point is the center of an N-simplex\n\n \/\/ Determine number of components in each sublattice\n while ( ic0 != ic1 )\n {\n const std::size_t number_of_species = std::distance ( ic0,ic1 );\n if ( number_of_species > 0 )\n {\n NDSimplex base ( number_of_species-1 ); \/\/ construct the unit (q-1)-simplex\n components_in_sublattice.emplace_back ( base.simplex_subdivide ( subdivisions_per_axis ) );\n }\n \/\/ Next sublattice\n ++sublindex;\n ic0 = boost::multi_index::get ( sublset ).lower_bound ( boost::make_tuple ( phase.name(), sublindex ) );\n ic1 = boost::multi_index::get ( sublset ).end();\n }\n\n \/\/ Take all combinations of generated points in each sublattice\n start_simplices = lattice_complex ( components_in_sublattice );\n\n\n for ( SimplexCollection& simpcol : start_simplices )\n {\n std::cout << \"(\";\n std::vector pt;\n for ( NDSimplex& simp : simpcol )\n {\n std::vector sub_pt = simp.centroid_with_dependent_component();\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n for ( auto i = pt.begin(); i != pt.end(); ++i )\n {\n std::cout << *i;\n if ( std::distance ( i,pt.end() ) > 1 ) std::cout << \",\";\n }\n std::cout << \")\" << std::endl;\n points.emplace_back ( std::move ( pt ) );\n }\n\n \/\/ (2) Calculate the Lagrangian Hessian for all sampled points\n for ( SimplexCollection& simpcol : start_simplices )\n {\n std::vector pt;\n for ( NDSimplex& simp : simpcol )\n {\n \/\/ Generate the current point from all the simplices in each sublattice\n std::vector sub_pt = simp.centroid_with_dependent_component();\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n if ( pt.size() == 0 ) continue; \/\/ skip empty (invalid) points\n symmetric_matrix Hessian ( zero_matrix ( pt.size(),pt.size() ) );\n try\n {\n Hessian = phase.evaluate_objective_hessian_matrix ( conditions, phase.get_variable_map(), pt );\n }\n catch ( boost::exception &e )\n {\n std::cout << boost::diagnostic_information ( e );\n throw;\n }\n catch ( std::exception &e )\n {\n std::cout << e.what();\n throw;\n }\n \/\/std::cout << \"Hessian: \" << Hessian << std::endl;\n \/\/ NOTE: For this calculation we consider only the linear constraints for an isolated phase (e.g., site fraction balances)\n \/\/ (3) Save all points for which the Lagrangian Hessian is positive definite in the null space of the constraint gradient matrix\n \/\/ NOTE: This is the projected Hessian method (Nocedal and Wright, 2006, ch. 12.4, p.349)\n \/\/ But how do I choose the Lagrange multipliers for all the constraints? Can I calculate them?\n \/\/ The answer is that, because the constraints are linear, there is no constraint contribution to the Hessian.\n \/\/ That means that the Hessian of the Lagrangian is just the Hessian of the objective function.\n const std::size_t Zcolumns = pt.size() - phase.get_constraints().size();\n \/\/ Z is the constraint null space matrix = phase.get_constraint_null_space_matrix()\n \/\/ (a) Set Hproj = transpose(Z)*(L'')*Z\n matrix Hproj ( pt.size(), Zcolumns );\n Hproj = prod ( trans ( phase.get_constraint_null_space_matrix() ),\n matrix ( prod ( Hessian,phase.get_constraint_null_space_matrix() ) ) );\n \/\/std::cout << \"Hproj: \" << Hproj << std::endl;\n \/\/ (b) Verify that all diagonal elements of Hproj are strictly positive; if not, remove this point from consideration\n \/\/ NOTE: This is a necessary but not sufficient condition that a matrix be positive definite, and it's easy to check\n \/\/ Reference: Carlen and Carvalho, 2007, p. 148, Eq. 5.12\n \/\/ TODO: Currently not bothering to do this; should perform a test to figure out if there would be a performance increase\n \/\/ (c) Attempt a Cholesky factorization of Hproj; will only succeed if matrix is positive definite\n const bool is_positive_definite = cholesky_factorize ( Hproj );\n \/\/ (d) If it succeeds, save this point; else, discard it\n if ( is_positive_definite )\n {\n positive_definite_regions.push_back ( simpcol );\n for ( double i : pt ) std::cout << i << \",\";\n std::cout << \":\" << std::endl;\n }\n }\n\n \/\/ positive_definite_regions is now filled\n \/\/ Perform recursive search for minima on each of the identified regions\n for ( const SimplexCollection &simpcol : positive_definite_regions )\n {\n \/\/ We start at a recursive depth of 2 because we treat LocateMinima as depth == 1\n \/\/ This allows our notation for depth to be consistent with Emelianenko et al.\n std::vector> region_minima = AdaptiveSearchND ( phase, conditions, simpcol, 2 );\n \/\/ Append this region's minima to the list of minima\n \/\/ minima.size() > 1 means there is a miscilibility gap\n minima.reserve ( minima.size() +region_minima.size() );\n minima.insert ( minima.end(), std::make_move_iterator ( region_minima.begin() ), std::make_move_iterator ( region_minima.end() ) );\n }\n }\n\n\/\/ namespace Optimizer\n}\n\n\/\/ Recursive function for searching composition space for minima\n\/\/ Input: Simplex that bounds a positive definite search region (SimplexCollection is used for multiple sublattices)\n\/\/ Input: Recursion depth\n\/\/ Output: Vector of minimum points\nstd::vector> AdaptiveSearchND (\n CompositionSet const &phase,\n evalconditions const& conditions,\n const SimplexCollection &search_region,\n const std::size_t depth )\n {\n using namespace boost::numeric::ublas;\n BOOST_ASSERT ( depth > 0 );\n constexpr const double gradient_magnitude_threshold = 1e3;\n constexpr const std::size_t subdivisions_per_axis = 5;\n constexpr const std::size_t max_depth = 5;\n std::vector> minima;\n std::vector pt;\n\n \/\/ (1) Calculate the objective gradient (L') for the centroid of the active simplex\n for ( const NDSimplex& simp : search_region )\n {\n \/\/ Generate the current point (pt) from all the simplices in each sublattice\n std::vector sub_pt = simp.centroid_with_dependent_component();\n \/\/std::cout << \"[\";\n \/\/for (double i : sub_pt) std::cout << i << \",\";\n \/\/std::cout << \"]\" << std::endl;\n pt.insert ( pt.end(),std::make_move_iterator ( sub_pt.begin() ),std::make_move_iterator ( sub_pt.end() ) );\n }\n \/\/double obj = phase.evaluate_objective ( conditions, phase.get_variable_map(), &pt[0] );\n \/\/std::cout << obj << std::endl;\n std::vector raw_gradient = phase.evaluate_internal_objective_gradient ( conditions, &pt[0] );\n \/\/ Project the raw gradient into the null space of constraints\n \/\/ This will leave only the gradient in the feasible directions\n boost::numeric::ublas::vector projected_gradient(raw_gradient.size());\n std::move(raw_gradient.begin(), raw_gradient.end(), projected_gradient.begin());\n projected_gradient = projected_gradient - prod ( phase.get_constraint_null_space_matrix(), projected_gradient );\n double mag = 0;\n for ( auto i = projected_gradient.begin(); i != projected_gradient.end(); ++i )\n {\n mag += pow ( *i,2 );\n }\n for ( auto i = projected_gradient.begin(); i != projected_gradient.end(); ++i )\n {\n std::cout << \"gradient[\" << std::distance(projected_gradient.begin(),i) << \"] = \" << *i << std::endl;\n }\n \/\/ (2) If that magnitude is less than some defined epsilon, return z as a minimum\n \/\/ Else simplex_subdivide() the active region and send to next depth (return minima from that)\n if (mag < gradient_magnitude_threshold) {\n std::cout << \"new minpoint \";\n for ( auto i = pt.begin(); i != pt.end(); ++i )\n {\n std::cout << *i;\n if ( std::distance ( i,pt.end() ) > 1 ) std::cout << \",\";\n }\n std::cout << \" gradient sq: \" << mag << std::endl;\n for ( auto i = projected_gradient.begin(); i != projected_gradient.end(); ++i )\n {\n std::cout << \"gradient[\" << std::distance(projected_gradient.begin(),i) << \"] = \" << *i << std::endl;\n }\n minima.push_back(pt);\n }\n else {\n if (depth == max_depth) return minima; \/\/ we've hit max depth, return what we have (nothing)\n std::vector simplex_combinations, new_simplices;\n \/\/ simplex_subdivide() the simplices in all the active sublattices\n for (const NDSimplex &simp : search_region) {\n simplex_combinations.emplace_back(simp.simplex_subdivide(subdivisions_per_axis));\n }\n \/\/ lattice_complex() the result to generate all the combinations in the sublattices\n new_simplices = lattice_complex(simplex_combinations);\n \/\/ send each new SimplexCollection to the next depth\n for (const SimplexCollection &sc : new_simplices) {\n std::vector> recursive_minima = AdaptiveSearchND(phase, conditions, sc, depth+1);\n \/\/ Add the found minima to the list of known minima\n minima.reserve(minima.size()+recursive_minima.size());\n minima.insert ( minima.end(), std::make_move_iterator ( recursive_minima.begin() ), std::make_move_iterator ( recursive_minima.end() ) );\n }\n }\n return minima;\n }\n\/\/ kate: indent-mode cstyle; indent-width 4; replace-tabs on; \n<|endoftext|>"} {"text":"\/\/ Include this #define to use SystemTraceControlGuid in Evntrace.h.\n#define INITGUID\n\n#include \n\n#include \n#include \n#include \n\nstatic void err(char *s) {\n \/\/ Retrieve the system error message for the last-error code\n LPVOID lpMsgBuf;\n auto e = GetLastError();\n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPTSTR)&lpMsgBuf, 0, NULL);\n\n \/\/ Display the error message and exit the process\n printf(\"%s failed with error %d: %s\\n\", s, e, lpMsgBuf);\n ExitProcess(e);\n}\n\nstatic void WINAPI EventRecordCallback(EVENT_RECORD *EventRecord) {\n EVENT_HEADER &Header = EventRecord->EventHeader;\n\n UCHAR ProcessorNumber = EventRecord->BufferContext.ProcessorNumber;\n ULONG ThreadID = Header.ThreadId;\n\n \/\/ Process event here.\n}\n\nstatic TRACEHANDLE ConsumerHandle;\n\nstatic DWORD WINAPI processThread(LPVOID Parameter) {\n ProcessTrace(&ConsumerHandle, 1, 0, 0);\n return (0);\n}\n\nint main(int argc, char **argv) {\n TRACEHANDLE SessionHandle = 0;\n\n auto BufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(KERNEL_LOGGER_NAME);\n EVENT_TRACE_PROPERTIES *properties =\n (EVENT_TRACE_PROPERTIES *)malloc(BufferSize);\n\n ZeroMemory(properties, BufferSize);\n properties->Wnode.BufferSize = BufferSize;\n properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;\n properties->Wnode.ClientContext = 3;\n properties->Wnode.Guid = SystemTraceControlGuid;\n properties->EnableFlags = EVENT_TRACE_FLAG_NETWORK_TCPIP;\n properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;\n properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);\n strcpy((char *)properties + properties->LoggerNameOffset, KERNEL_LOGGER_NAME);\n\n ControlTrace(0, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);\n\n auto status =\n StartTrace((PTRACEHANDLE)&SessionHandle, KERNEL_LOGGER_NAME, properties);\n if (ERROR_SUCCESS != status)\n err(\"StartTrace\");\n\n EVENT_TRACE_LOGFILE LogFile = {0};\n LogFile.LoggerName = KERNEL_LOGGER_NAME;\n LogFile.ProcessTraceMode =\n (PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD |\n PROCESS_TRACE_MODE_RAW_TIMESTAMP);\n LogFile.EventRecordCallback = EventRecordCallback;\n ConsumerHandle = OpenTrace(&LogFile);\n DWORD ThreadID;\n HANDLE ThreadHandle = CreateThread(0, 0, processThread, 0, 0, &ThreadID);\n CloseHandle(ThreadHandle);\n\n wprintf(L\"Press any key to end trace session \");\n getchar();\n\n ControlTrace(0, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);\n return 0;\n}\nrefactor\/\/ Include this #define to use SystemTraceControlGuid in Evntrace.h.\n#define INITGUID\n\n#include \n\n#include \n#include \n#include \n\nstatic void err(char *s) {\n \/\/ Retrieve the system error message for the last-error code\n LPVOID msg;\n auto e = GetLastError();\n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPTSTR)&msg, 0, NULL);\n\n \/\/ Display the error message and exit the process\n printf(\"%s failed with error %d: %s\\n\", s, e, msg);\n ExitProcess(e);\n}\n\nstatic void WINAPI EventRecordCallback(EVENT_RECORD *EventRecord) {\n EVENT_HEADER &Header = EventRecord->EventHeader;\n\n UCHAR ProcessorNumber = EventRecord->BufferContext.ProcessorNumber;\n ULONG ThreadID = Header.ThreadId;\n\n \/\/ Process event here.\n}\n\nstatic TRACEHANDLE trace;\n\nstatic DWORD WINAPI processThread(LPVOID Parameter) {\n ProcessTrace(&trace, 1, 0, 0);\n return (0);\n}\n\nint main(int argc, char **argv) {\n auto BufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(KERNEL_LOGGER_NAME);\n auto properties = (EVENT_TRACE_PROPERTIES *)malloc(BufferSize);\n\n ZeroMemory(properties, BufferSize);\n properties->Wnode.BufferSize = BufferSize;\n properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;\n properties->Wnode.ClientContext = 3;\n properties->Wnode.Guid = SystemTraceControlGuid;\n properties->EnableFlags = EVENT_TRACE_FLAG_NETWORK_TCPIP;\n properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;\n properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);\n strcpy((char *)properties + properties->LoggerNameOffset, KERNEL_LOGGER_NAME);\n\n ControlTrace(0, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);\n\n auto status =\n StartTrace((PTRACEHANDLE)&trace, KERNEL_LOGGER_NAME, properties);\n if (ERROR_SUCCESS != status)\n err(\"StartTrace\");\n\n EVENT_TRACE_LOGFILE LogFile = {0};\n LogFile.LoggerName = KERNEL_LOGGER_NAME;\n LogFile.ProcessTraceMode =\n (PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD |\n PROCESS_TRACE_MODE_RAW_TIMESTAMP);\n LogFile.EventRecordCallback = EventRecordCallback;\n trace = OpenTrace(&LogFile);\n CreateThread(0, 0, processThread, 0, 0, 0);\n\n wprintf(L\"Press any key to end trace session \");\n getchar();\n\n ControlTrace(0, KERNEL_LOGGER_NAME, properties, EVENT_TRACE_CONTROL_STOP);\n return 0;\n}\n<|endoftext|>"} {"text":"\/********************************************************************\n * AUTHORS: Vijay Ganesh, Trevor Hansen, Mate Soos\n *\n * BEGIN DATE: November, 2005\n *\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n********************************************************************\/\n\n#include \"main_common.h\"\n#include \"extlib-abc\/cnf_short.h\"\n\nextern int smtparse(void*);\nextern int smt2parse();\nextern int cvcparse(void*);\nextern int cvclex_destroy(void);\nextern int smtlex_destroy(void);\nextern int smt2lex_destroy(void);\nextern void errorHandler(const char* error_msg);\n\n\/\/ Amount of memory to ask for at beginning of main.\nextern const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE;\nextern FILE* cvcin;\nextern FILE* smtin;\nextern FILE* smt2in;\n\n#ifdef EXT_HASH_MAP\nusing namespace __gnu_cxx;\n#endif\nusing namespace BEEV;\nusing std::auto_ptr;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nvoid errorHandler(const char* error_msg)\n{\n cerr << prog << \": Error: \" << error_msg << endl;\n exit(-1);\n}\n\n\/\/ Amount of memory to ask for at beginning of main.\nconst intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000;\n\nMain::Main() : onePrintBack(false)\n{\n bm = NULL;\n toClose = NULL;\n cvcin = NULL;\n smtin = NULL;\n smt2in = NULL;\n\n \/\/ Register the error handler\n vc_error_hdlr = errorHandler;\n\n#if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(_MSC_VER)\n \/\/ Grab some memory from the OS upfront to reduce system time when\n \/\/ individual hash tables are being allocated\n if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void*)-1))\n {\n FatalError(\"Initial allocation of memory failed.\");\n }\n#endif\n\n bm = new STPMgr();\n ParserBM = bm;\n}\n\nMain::~Main()\n{\n delete bm;\n}\n\nvoid Main::parse_file(ASTVec* AssertsQuery)\n{\n TypeChecker nfTypeCheckSimp(*bm->defaultNodeFactory, *bm);\n TypeChecker nfTypeCheckDefault(*bm->hashingNodeFactory, *bm);\n\n Cpp_interface piTypeCheckSimp(*bm, &nfTypeCheckSimp);\n Cpp_interface piTypeCheckDefault(*bm, &nfTypeCheckDefault);\n\n \/\/ If you are converting formats, you probably don't want it simplifying (at\n \/\/ least I dont).\n if (onePrintBack)\n {\n parserInterface = &piTypeCheckDefault;\n }\n else\n {\n parserInterface = &piTypeCheckSimp;\n }\n\n parserInterface->startup();\n\n if (onePrintBack)\n {\n if (bm->UserFlags.smtlib2_parser_flag)\n {\n cerr << \"Printback from SMTLIB2 inputs isn't currently working.\" << endl;\n cerr << \"Please try again later\" << endl;\n cerr << \"It works prior to revision 1354\" << endl;\n exit(1);\n }\n }\n\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n smtparse((void*)AssertsQuery);\n smtlex_destroy();\n }\n else if (bm->UserFlags.smtlib2_parser_flag)\n {\n smt2parse();\n smt2lex_destroy();\n }\n else\n {\n cvcparse((void*)AssertsQuery);\n cvclex_destroy();\n }\n parserInterface = NULL;\n if (toClose != NULL)\n {\n fclose(toClose);\n }\n}\n\nvoid Main::print_back(ASTNode& query, ASTNode& asserts)\n{\n ASTNode original_input =\n bm->CreateNode(AND, bm->CreateNode(NOT, query), asserts);\n\n if (bm->UserFlags.print_STPinput_back_flag)\n {\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n bm->UserFlags.print_STPinput_back_SMTLIB2_flag = true;\n }\n else\n {\n bm->UserFlags.print_STPinput_back_CVC_flag = true;\n }\n }\n\n if (bm->UserFlags.print_STPinput_back_CVC_flag)\n {\n \/\/ needs just the query. Reads the asserts out of the data structure.\n print_STPInput_Back(original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_SMTLIB1_flag)\n {\n printer::SMTLIB1_PrintBack(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_SMTLIB2_flag)\n {\n printer::SMTLIB2_PrintBack(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_C_flag)\n {\n printer::C_Print(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_GDL_flag)\n {\n printer::GDL_Print(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_dot_flag)\n {\n printer::Dot_Print(cout, original_input);\n }\n}\n\nvoid Main::read_file()\n{\n bool error = false;\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n smtin = fopen(infile.c_str(), \"r\");\n toClose = smtin;\n if (smtin == NULL)\n {\n error = true;\n }\n }\n else if (bm->UserFlags.smtlib2_parser_flag)\n {\n smt2in = fopen(infile.c_str(), \"r\");\n toClose = smt2in;\n if (smt2in == NULL)\n {\n error = true;\n }\n }\n\n else\n {\n cvcin = fopen(infile.c_str(), \"r\");\n toClose = cvcin;\n if (cvcin == NULL)\n {\n error = true;\n }\n }\n\n if (error)\n {\n std::string errorMsg(\"Cannot open \");\n errorMsg += infile;\n FatalError(errorMsg.c_str());\n }\n}\n\nint Main::create_and_parse_options(int argc, char** argv)\n{\n return 0;\n}\n\nvoid Main::check_infile_type()\n{\n if (infile.size() >= 5)\n {\n if (!infile.compare(infile.length() - 4, 4, \".smt\"))\n {\n bm->UserFlags.division_by_zero_returns_one_flag = true;\n bm->UserFlags.smtlib1_parser_flag = true;\n }\n if (!infile.compare(infile.length() - 5, 5, \".smt2\"))\n {\n bm->UserFlags.division_by_zero_returns_one_flag = true;\n bm->UserFlags.smtlib2_parser_flag = true;\n }\n }\n}\n\nint Main::main(int argc, char** argv)\n{\n auto_ptr simplifyingNF(\n new SimplifyingNodeFactory(*bm->hashingNodeFactory, *bm));\n bm->defaultNodeFactory = simplifyingNF.get();\n\n auto_ptr simp(new Simplifier(bm));\n auto_ptr arrayTransformer(new ArrayTransformer(bm, simp.get()));\n auto_ptr tosat(new ToSAT(bm));\n\n auto_ptr Ctr_Example(\n new AbsRefine_CounterExample(bm, simp.get(), arrayTransformer.get()));\n\n int ret = create_and_parse_options(argc, argv);\n if (ret != 0)\n {\n return ret;\n }\n\n GlobalSTP = new STP(bm, simp.get(), arrayTransformer.get(), tosat.get(),\n Ctr_Example.get());\n\n \/\/ If we're not reading the file from stdin.\n if (!infile.empty())\n read_file();\n\n \/\/ want to print the output always from the commandline.\n bm->UserFlags.print_output_flag = true;\n ASTVec* AssertsQuery = new ASTVec;\n\n bm->GetRunTimes()->start(RunTimes::Parsing);\n parse_file(AssertsQuery);\n bm->GetRunTimes()->stop(RunTimes::Parsing);\n\n \/* The SMTLIB2 has a command language. The parser calls all the functions,\n * so when we get to here the parser has already called \"exit\". i.e. if the\n * language is smt2 then all the work has already been done, and all we need\n * to do is cleanup...\n * *\/\n if (!bm->UserFlags.smtlib2_parser_flag)\n {\n if (AssertsQuery->empty())\n FatalError(\"Input is Empty. Please enter some asserts and query\\n\");\n\n if (AssertsQuery->size() != 2)\n FatalError(\"Input must contain a query\\n\");\n\n ASTNode asserts = (*AssertsQuery)[0];\n ASTNode query = (*AssertsQuery)[1];\n\n if (onePrintBack)\n {\n print_back(query, asserts);\n return 0;\n }\n\n SOLVER_RETURN_TYPE ret = GlobalSTP->TopLevelSTP(asserts, query);\n if (bm->UserFlags.quick_statistics_flag)\n {\n bm->GetRunTimes()->print();\n }\n (GlobalSTP->tosat)->PrintOutput(ret);\n\n asserts = ASTNode();\n query = ASTNode();\n }\n\n \/\/ Without cleanup\n if (bm->UserFlags.isSet(\"fast-exit\", \"1\"))\n exit(0);\n\n \/\/Cleanup\n AssertsQuery->clear();\n delete AssertsQuery;\n _empty_ASTVec.clear();\n delete GlobalSTP;\n Cnf_ClearMemory();\n\n return 0;\n}Removing useless brackets\/********************************************************************\n * AUTHORS: Vijay Ganesh, Trevor Hansen, Mate Soos\n *\n * BEGIN DATE: November, 2005\n *\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n********************************************************************\/\n\n#include \"main_common.h\"\n#include \"extlib-abc\/cnf_short.h\"\n\nextern int smtparse(void*);\nextern int smt2parse();\nextern int cvcparse(void*);\nextern int cvclex_destroy(void);\nextern int smtlex_destroy(void);\nextern int smt2lex_destroy(void);\nextern void errorHandler(const char* error_msg);\n\n\/\/ Amount of memory to ask for at beginning of main.\nextern const intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE;\nextern FILE* cvcin;\nextern FILE* smtin;\nextern FILE* smt2in;\n\n#ifdef EXT_HASH_MAP\nusing namespace __gnu_cxx;\n#endif\nusing namespace BEEV;\nusing std::auto_ptr;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nvoid errorHandler(const char* error_msg)\n{\n cerr << prog << \": Error: \" << error_msg << endl;\n exit(-1);\n}\n\n\/\/ Amount of memory to ask for at beginning of main.\nconst intptr_t INITIAL_MEMORY_PREALLOCATION_SIZE = 4000000;\n\nMain::Main() : onePrintBack(false)\n{\n bm = NULL;\n toClose = NULL;\n cvcin = NULL;\n smtin = NULL;\n smt2in = NULL;\n\n \/\/ Register the error handler\n vc_error_hdlr = errorHandler;\n\n#if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(_MSC_VER)\n \/\/ Grab some memory from the OS upfront to reduce system time when\n \/\/ individual hash tables are being allocated\n if (sbrk(INITIAL_MEMORY_PREALLOCATION_SIZE) == ((void*)-1))\n {\n FatalError(\"Initial allocation of memory failed.\");\n }\n#endif\n\n bm = new STPMgr();\n ParserBM = bm;\n}\n\nMain::~Main()\n{\n delete bm;\n}\n\nvoid Main::parse_file(ASTVec* AssertsQuery)\n{\n TypeChecker nfTypeCheckSimp(*bm->defaultNodeFactory, *bm);\n TypeChecker nfTypeCheckDefault(*bm->hashingNodeFactory, *bm);\n\n Cpp_interface piTypeCheckSimp(*bm, &nfTypeCheckSimp);\n Cpp_interface piTypeCheckDefault(*bm, &nfTypeCheckDefault);\n\n \/\/ If you are converting formats, you probably don't want it simplifying (at\n \/\/ least I dont).\n if (onePrintBack)\n {\n parserInterface = &piTypeCheckDefault;\n }\n else\n {\n parserInterface = &piTypeCheckSimp;\n }\n\n parserInterface->startup();\n\n if (onePrintBack)\n {\n if (bm->UserFlags.smtlib2_parser_flag)\n {\n cerr << \"Printback from SMTLIB2 inputs isn't currently working.\" << endl;\n cerr << \"Please try again later\" << endl;\n cerr << \"It works prior to revision 1354\" << endl;\n exit(1);\n }\n }\n\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n smtparse((void*)AssertsQuery);\n smtlex_destroy();\n }\n else if (bm->UserFlags.smtlib2_parser_flag)\n {\n smt2parse();\n smt2lex_destroy();\n }\n else\n {\n cvcparse((void*)AssertsQuery);\n cvclex_destroy();\n }\n parserInterface = NULL;\n if (toClose != NULL)\n {\n fclose(toClose);\n }\n}\n\nvoid Main::print_back(ASTNode& query, ASTNode& asserts)\n{\n ASTNode original_input =\n bm->CreateNode(AND, bm->CreateNode(NOT, query), asserts);\n\n if (bm->UserFlags.print_STPinput_back_flag)\n {\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n bm->UserFlags.print_STPinput_back_SMTLIB2_flag = true;\n }\n else\n {\n bm->UserFlags.print_STPinput_back_CVC_flag = true;\n }\n }\n\n if (bm->UserFlags.print_STPinput_back_CVC_flag)\n {\n \/\/ needs just the query. Reads the asserts out of the data structure.\n print_STPInput_Back(original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_SMTLIB1_flag)\n {\n printer::SMTLIB1_PrintBack(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_SMTLIB2_flag)\n {\n printer::SMTLIB2_PrintBack(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_C_flag)\n {\n printer::C_Print(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_GDL_flag)\n {\n printer::GDL_Print(cout, original_input);\n }\n\n if (bm->UserFlags.print_STPinput_back_dot_flag)\n {\n printer::Dot_Print(cout, original_input);\n }\n}\n\nvoid Main::read_file()\n{\n bool error = false;\n if (bm->UserFlags.smtlib1_parser_flag)\n {\n smtin = fopen(infile.c_str(), \"r\");\n toClose = smtin;\n if (smtin == NULL)\n {\n error = true;\n }\n }\n else if (bm->UserFlags.smtlib2_parser_flag)\n {\n smt2in = fopen(infile.c_str(), \"r\");\n toClose = smt2in;\n if (smt2in == NULL)\n {\n error = true;\n }\n }\n\n else\n {\n cvcin = fopen(infile.c_str(), \"r\");\n toClose = cvcin;\n if (cvcin == NULL)\n {\n error = true;\n }\n }\n\n if (error)\n {\n std::string errorMsg(\"Cannot open \");\n errorMsg += infile;\n FatalError(errorMsg.c_str());\n }\n}\n\nint Main::create_and_parse_options(int argc, char** argv)\n{\n return 0;\n}\n\nvoid Main::check_infile_type()\n{\n if (infile.size() >= 5)\n {\n if (!infile.compare(infile.length() - 4, 4, \".smt\"))\n {\n bm->UserFlags.division_by_zero_returns_one_flag = true;\n bm->UserFlags.smtlib1_parser_flag = true;\n }\n if (!infile.compare(infile.length() - 5, 5, \".smt2\"))\n {\n bm->UserFlags.division_by_zero_returns_one_flag = true;\n bm->UserFlags.smtlib2_parser_flag = true;\n }\n }\n}\n\nint Main::main(int argc, char** argv)\n{\n auto_ptr simplifyingNF(\n new SimplifyingNodeFactory(*bm->hashingNodeFactory, *bm));\n bm->defaultNodeFactory = simplifyingNF.get();\n\n auto_ptr simp(new Simplifier(bm));\n auto_ptr arrayTransformer(new ArrayTransformer(bm, simp.get()));\n auto_ptr tosat(new ToSAT(bm));\n\n auto_ptr Ctr_Example(\n new AbsRefine_CounterExample(bm, simp.get(), arrayTransformer.get()));\n\n int ret = create_and_parse_options(argc, argv);\n if (ret != 0)\n {\n return ret;\n }\n\n GlobalSTP = new STP(bm, simp.get(), arrayTransformer.get(), tosat.get(),\n Ctr_Example.get());\n\n \/\/ If we're not reading the file from stdin.\n if (!infile.empty())\n read_file();\n\n \/\/ want to print the output always from the commandline.\n bm->UserFlags.print_output_flag = true;\n ASTVec* AssertsQuery = new ASTVec;\n\n bm->GetRunTimes()->start(RunTimes::Parsing);\n parse_file(AssertsQuery);\n bm->GetRunTimes()->stop(RunTimes::Parsing);\n\n \/* The SMTLIB2 has a command language. The parser calls all the functions,\n * so when we get to here the parser has already called \"exit\". i.e. if the\n * language is smt2 then all the work has already been done, and all we need\n * to do is cleanup...\n * *\/\n if (!bm->UserFlags.smtlib2_parser_flag)\n {\n if (AssertsQuery->empty())\n FatalError(\"Input is Empty. Please enter some asserts and query\\n\");\n\n if (AssertsQuery->size() != 2)\n FatalError(\"Input must contain a query\\n\");\n\n ASTNode asserts = (*AssertsQuery)[0];\n ASTNode query = (*AssertsQuery)[1];\n\n if (onePrintBack)\n {\n print_back(query, asserts);\n return 0;\n }\n\n SOLVER_RETURN_TYPE ret = GlobalSTP->TopLevelSTP(asserts, query);\n if (bm->UserFlags.quick_statistics_flag)\n {\n bm->GetRunTimes()->print();\n }\n GlobalSTP->tosat->PrintOutput(ret);\n\n asserts = ASTNode();\n query = ASTNode();\n }\n\n \/\/ Without cleanup\n if (bm->UserFlags.isSet(\"fast-exit\", \"1\"))\n exit(0);\n\n \/\/Cleanup\n AssertsQuery->clear();\n delete AssertsQuery;\n _empty_ASTVec.clear();\n delete GlobalSTP;\n Cnf_ClearMemory();\n\n return 0;\n}<|endoftext|>"} {"text":"\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \n#include \n\n#define debugPrintLn(...) { if (debugStream) debugStream->println(__VA_ARGS__); }\n#define debugPrint(...) { if (debugStream) debugStream->print(__VA_ARGS__); }\n\nvoid TheThingsNetwork::init(Stream& modemStream, Stream& debugStream) {\n this->modemStream = &modemStream;\n this->debugStream = &debugStream;\n}\n\nString TheThingsNetwork::readLine(int waitTime) {\n unsigned long start = millis();\n while (millis() < start + waitTime) {\n String line = modemStream->readStringUntil('\\n');\n if (line.length() > 0) {\n return line.substring(0, line.length() - 1);\n }\n }\n return \"\";\n}\n\nbool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {\n String line = readLine(waitTime);\n if (line == \"\") {\n debugPrintLn(F(\"Wait for OK time-out expired\"));\n return false;\n }\n\n if (line != okMessage) {\n debugPrint(F(\"Response is not OK: \"));\n debugPrintLn(line);\n return false;\n }\n\n return true;\n}\n\nString TheThingsNetwork::readValue(String cmd) {\n modemStream->println(cmd);\n return readLine();\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, int waitTime) {\n debugPrint(F(\"Sending: \"));\n debugPrintLn(cmd);\n\n modemStream->println(cmd);\n\n return waitForOK(waitTime);\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {\n int l = value.length();\n byte buf[l];\n value.getBytes(buf, l);\n\n return sendCommand(cmd, buf, l, waitTime);\n}\n\nchar btohexa_high(unsigned char b) {\n b >>= 4;\n return (b > 0x9u) ? b + 'A' - 10 : b + '0';\n}\n\nchar btohexa_low(unsigned char b) {\n b &= 0x0F;\n return (b > 0x9u) ? b + 'A' - 10 : b + '0';\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {\n debugPrint(F(\"Sending: \"));\n debugPrint(cmd);\n debugPrint(F(\" with \"));\n debugPrint(length);\n debugPrintLn(F(\" bytes\"));\n\n modemStream->print(cmd + \" \");\n\n for (int i = 0; i < length; i++) {\n modemStream->print(btohexa_high(buf[i]));\n modemStream->print(btohexa_low(buf[i]));\n }\n modemStream->println();\n\n return waitForOK(waitTime);\n}\n\nvoid TheThingsNetwork::reset(bool adr, int sf, int fsb) {\n #if !ADR_SUPPORTED\n adr = false;\n #endif\n\n modemStream->println(F(\"sys reset\"));\n String version = readLine(3000);\n if (version == \"\") {\n debugPrintLn(F(\"Invalid version\"));\n return;\n }\n\n model = version.substring(0, version.indexOf(' '));\n debugPrint(F(\"Version is \"));\n debugPrint(version);\n debugPrint(F(\", model is \"));\n debugPrintLn(model);\n\n String str = \"\";\n str.concat(F(\"mac set adr \"));\n if(adr){\n str.concat(F(\"on\"));\n } else {\n str.concat(F(\"off\"));\n }\n sendCommand(str);\n\n int dr = -1;\n if (model == F(\"RN2483\")) {\n str = \"\";\n str.concat(F(\"mac set pwridx \"));\n str.concat(PWRIDX_868);\n sendCommand(str);\n\n switch (sf) {\n case 7:\n dr = 5;\n break;\n case 8:\n dr = 4;\n break;\n case 9:\n dr = 3;\n break;\n case 10:\n dr = 2;\n break;\n case 11:\n dr = 1;\n break;\n case 12:\n dr = 0;\n break;\n default:\n debugPrintLn(F(\"Invalid SF\"))\n break;\n }\n }\n else if (model == F(\"RN2903\")) {\n str = \"\";\n str.concat(F(\"mac set pwridx \"));\n str.concat(PWRIDX_915);\n sendCommand(str);\n enableFsbChannels(fsb);\n\n switch (sf) {\n case 7:\n dr = 3;\n break;\n case 8:\n dr = 2;\n break;\n case 9:\n dr = 1;\n break;\n case 10:\n dr = 0;\n break;\n default:\n debugPrintLn(F(\"Invalid SF\"))\n break;\n }\n }\n\n if (dr > -1){\n str = \"\";\n str.concat(F(\"mac set dr \"));\n str.concat(dr);\n sendCommand(str);\n }\n}\n\nbool TheThingsNetwork::enableFsbChannels(int fsb) {\n int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;\n int chHigh = fsb > 0 ? chLow + 7 : 71;\n int ch500 = fsb + 63;\n\n for (int i = 0; i < 72; i++){\n String str = \"\";\n str.concat(F(\"mac set ch status \"));\n str.concat(i);\n if (i == ch500 || chLow <= i && i <= chHigh){\n str.concat(F(\" on\"));\n }\n else{\n str.concat(F(\" off\"));\n }\n sendCommand(str);\n }\n return true;\n}\n\nbool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16], bool reset) {\n \n if (reset == true)\n TheThingsNetwork::reset();\n sendCommand(F(\"mac set devaddr\"), devAddr, 4);\n sendCommand(F(\"mac set nwkskey\"), nwkSKey, 16);\n sendCommand(F(\"mac set appskey\"), appSKey, 16);\n sendCommand(F(\"mac join abp\"));\n\n String response = readLine();\n if (response != F(\"accepted\")) {\n debugPrint(F(\"Personalize not accepted: \"));\n debugPrintLn(response);\n return false;\n }\n\n debugPrint(F(\"Personalize accepted. Status: \"));\n debugPrintLn(readValue(F(\"mac get status\")));\n return true;\n}\n\nbool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16]) {\n String devEui = readValue(F(\"sys get hweui\"));\n sendCommand(F(\"mac set appeui\"), appEui, 8);\n String str = \"\";\n str.concat(F(\"mac set deveui \"));\n str.concat(devEui);\n sendCommand(str);\n sendCommand(F(\"mac set appkey\"), appKey, 16);\n if (!sendCommand(F(\"mac join otaa\"))) {\n debugPrintLn(F(\"Send join command failed\"));\n return false;\n }\n\n String response = readLine(10000);\n if (response != F(\"accepted\")) {\n debugPrint(F(\"Join not accepted: \"));\n debugPrintLn(response);\n return false;\n }\n\n debugPrint(F(\"Join accepted. Status: \"));\n debugPrintLn(readValue(F(\"mac get status\")));\n return true;\n}\n\nint TheThingsNetwork::sendBytes(const byte* buffer, int length, int port, bool confirm) {\n String str = \"\";\n str.concat(F(\"mac tx \"));\n str.concat(confirm ? F(\"cnf \") : F(\"uncnf \"));\n str.concat(port);\n if (!sendCommand(str, buffer, length)) {\n debugPrintLn(F(\"Send command failed\"));\n return 0;\n }\n\n String response = readLine(10000);\n if (response == \"\") {\n debugPrintLn(F(\"Time-out\"));\n return 0;\n }\n if (response == F(\"mac_tx_ok\")) {\n debugPrintLn(F(\"Successful transmission\"));\n return 0;\n }\n if (response.startsWith(F(\"mac_rx\"))) {\n int portEnds = response.indexOf(\" \", 7);\n this->downlinkPort = response.substring(7, portEnds).toInt();\n String data = response.substring(portEnds + 1);\n int downlinkLength = data.length() \/ 2;\n for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)\n this->downlink[i] = HEX_PAIR_TO_BYTE(data[d], data[d+1]);\n debugPrint(F(\"Successful transmission. Received \"));\n debugPrint(downlinkLength);\n debugPrintLn(F(\" bytes\"));\n return downlinkLength;\n }\n\n debugPrint(F(\"Unexpected response: \"));\n debugPrintLn(response);\n}\n\nint TheThingsNetwork::sendString(String message, int port, bool confirm) {\n int l = message.length();\n byte buf[l + 1];\n message.getBytes(buf, l + 1);\n\n return sendBytes(buf, l, port, confirm);\n}\n\nvoid TheThingsNetwork::showStatus() {\n debugPrint(F(\"EUI: \"));\n debugPrintLn(readValue(F(\"sys get hweui\")));\n debugPrint(F(\"Battery: \"));\n debugPrint(readValue(F(\"sys get vdd\")));\n debugPrint(F(\"AppEUI: \"));\n debugPrintLn(readValue(F(\"mac get appeui\")));\n debugPrint(F(\"DevEUI: \"));\n debugPrintLn(readValue(F(\"mac get deveui\")));\n debugPrint(F(\"DevAddr: \"));\n debugPrintLn(readValue(F(\"mac get devaddr\")));\n\n if (this->model == F(\"RN2483\")) {\n debugPrint(F(\"Band: \"));\n debugPrintLn(readValue(F(\"mac get band\")));\n }\n\n debugPrint(F(\"Data Rate: \"));\n debugPrintLn(readValue(F(\"mac get dr\")));\n debugPrint(F(\"RX Delay 1: \"));\n debugPrintLn(readValue(F(\"mac get rxdelay1\")));\n debugPrint(F(\"RX Delay 2: \"));\n debugPrintLn(readValue(F(\"mac get rxdelay2\")));\n}\nfixed reset = true\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \n#include \n\n#define debugPrintLn(...) { if (debugStream) debugStream->println(__VA_ARGS__); }\n#define debugPrint(...) { if (debugStream) debugStream->print(__VA_ARGS__); }\n\nvoid TheThingsNetwork::init(Stream& modemStream, Stream& debugStream) {\n this->modemStream = &modemStream;\n this->debugStream = &debugStream;\n}\n\nString TheThingsNetwork::readLine(int waitTime) {\n unsigned long start = millis();\n while (millis() < start + waitTime) {\n String line = modemStream->readStringUntil('\\n');\n if (line.length() > 0) {\n return line.substring(0, line.length() - 1);\n }\n }\n return \"\";\n}\n\nbool TheThingsNetwork::waitForOK(int waitTime, String okMessage) {\n String line = readLine(waitTime);\n if (line == \"\") {\n debugPrintLn(F(\"Wait for OK time-out expired\"));\n return false;\n }\n\n if (line != okMessage) {\n debugPrint(F(\"Response is not OK: \"));\n debugPrintLn(line);\n return false;\n }\n\n return true;\n}\n\nString TheThingsNetwork::readValue(String cmd) {\n modemStream->println(cmd);\n return readLine();\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, int waitTime) {\n debugPrint(F(\"Sending: \"));\n debugPrintLn(cmd);\n\n modemStream->println(cmd);\n\n return waitForOK(waitTime);\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, String value, int waitTime) {\n int l = value.length();\n byte buf[l];\n value.getBytes(buf, l);\n\n return sendCommand(cmd, buf, l, waitTime);\n}\n\nchar btohexa_high(unsigned char b) {\n b >>= 4;\n return (b > 0x9u) ? b + 'A' - 10 : b + '0';\n}\n\nchar btohexa_low(unsigned char b) {\n b &= 0x0F;\n return (b > 0x9u) ? b + 'A' - 10 : b + '0';\n}\n\nbool TheThingsNetwork::sendCommand(String cmd, const byte *buf, int length, int waitTime) {\n debugPrint(F(\"Sending: \"));\n debugPrint(cmd);\n debugPrint(F(\" with \"));\n debugPrint(length);\n debugPrintLn(F(\" bytes\"));\n\n modemStream->print(cmd + \" \");\n\n for (int i = 0; i < length; i++) {\n modemStream->print(btohexa_high(buf[i]));\n modemStream->print(btohexa_low(buf[i]));\n }\n modemStream->println();\n\n return waitForOK(waitTime);\n}\n\nvoid TheThingsNetwork::reset(bool adr, int sf, int fsb) {\n #if !ADR_SUPPORTED\n adr = false;\n #endif\n\n modemStream->println(F(\"sys reset\"));\n String version = readLine(3000);\n if (version == \"\") {\n debugPrintLn(F(\"Invalid version\"));\n return;\n }\n\n model = version.substring(0, version.indexOf(' '));\n debugPrint(F(\"Version is \"));\n debugPrint(version);\n debugPrint(F(\", model is \"));\n debugPrintLn(model);\n\n String str = \"\";\n str.concat(F(\"mac set adr \"));\n if(adr){\n str.concat(F(\"on\"));\n } else {\n str.concat(F(\"off\"));\n }\n sendCommand(str);\n\n int dr = -1;\n if (model == F(\"RN2483\")) {\n str = \"\";\n str.concat(F(\"mac set pwridx \"));\n str.concat(PWRIDX_868);\n sendCommand(str);\n\n switch (sf) {\n case 7:\n dr = 5;\n break;\n case 8:\n dr = 4;\n break;\n case 9:\n dr = 3;\n break;\n case 10:\n dr = 2;\n break;\n case 11:\n dr = 1;\n break;\n case 12:\n dr = 0;\n break;\n default:\n debugPrintLn(F(\"Invalid SF\"))\n break;\n }\n }\n else if (model == F(\"RN2903\")) {\n str = \"\";\n str.concat(F(\"mac set pwridx \"));\n str.concat(PWRIDX_915);\n sendCommand(str);\n enableFsbChannels(fsb);\n\n switch (sf) {\n case 7:\n dr = 3;\n break;\n case 8:\n dr = 2;\n break;\n case 9:\n dr = 1;\n break;\n case 10:\n dr = 0;\n break;\n default:\n debugPrintLn(F(\"Invalid SF\"))\n break;\n }\n }\n\n if (dr > -1){\n str = \"\";\n str.concat(F(\"mac set dr \"));\n str.concat(dr);\n sendCommand(str);\n }\n}\n\nbool TheThingsNetwork::enableFsbChannels(int fsb) {\n int chLow = fsb > 0 ? (fsb - 1) * 8 : 0;\n int chHigh = fsb > 0 ? chLow + 7 : 71;\n int ch500 = fsb + 63;\n\n for (int i = 0; i < 72; i++){\n String str = \"\";\n str.concat(F(\"mac set ch status \"));\n str.concat(i);\n if (i == ch500 || chLow <= i && i <= chHigh){\n str.concat(F(\" on\"));\n }\n else{\n str.concat(F(\" off\"));\n }\n sendCommand(str);\n }\n return true;\n}\n\nbool TheThingsNetwork::personalize(const byte devAddr[4], const byte nwkSKey[16], const byte appSKey[16], bool reset) {\n \n if (reset) {\n TheThingsNetwork::reset();\n }\n sendCommand(F(\"mac set devaddr\"), devAddr, 4);\n sendCommand(F(\"mac set nwkskey\"), nwkSKey, 16);\n sendCommand(F(\"mac set appskey\"), appSKey, 16);\n sendCommand(F(\"mac join abp\"));\n\n String response = readLine();\n if (response != F(\"accepted\")) {\n debugPrint(F(\"Personalize not accepted: \"));\n debugPrintLn(response);\n return false;\n }\n\n debugPrint(F(\"Personalize accepted. Status: \"));\n debugPrintLn(readValue(F(\"mac get status\")));\n return true;\n}\n\nbool TheThingsNetwork::join(const byte appEui[8], const byte appKey[16]) {\n String devEui = readValue(F(\"sys get hweui\"));\n sendCommand(F(\"mac set appeui\"), appEui, 8);\n String str = \"\";\n str.concat(F(\"mac set deveui \"));\n str.concat(devEui);\n sendCommand(str);\n sendCommand(F(\"mac set appkey\"), appKey, 16);\n if (!sendCommand(F(\"mac join otaa\"))) {\n debugPrintLn(F(\"Send join command failed\"));\n return false;\n }\n\n String response = readLine(10000);\n if (response != F(\"accepted\")) {\n debugPrint(F(\"Join not accepted: \"));\n debugPrintLn(response);\n return false;\n }\n\n debugPrint(F(\"Join accepted. Status: \"));\n debugPrintLn(readValue(F(\"mac get status\")));\n return true;\n}\n\nint TheThingsNetwork::sendBytes(const byte* buffer, int length, int port, bool confirm) {\n String str = \"\";\n str.concat(F(\"mac tx \"));\n str.concat(confirm ? F(\"cnf \") : F(\"uncnf \"));\n str.concat(port);\n if (!sendCommand(str, buffer, length)) {\n debugPrintLn(F(\"Send command failed\"));\n return 0;\n }\n\n String response = readLine(10000);\n if (response == \"\") {\n debugPrintLn(F(\"Time-out\"));\n return 0;\n }\n if (response == F(\"mac_tx_ok\")) {\n debugPrintLn(F(\"Successful transmission\"));\n return 0;\n }\n if (response.startsWith(F(\"mac_rx\"))) {\n int portEnds = response.indexOf(\" \", 7);\n this->downlinkPort = response.substring(7, portEnds).toInt();\n String data = response.substring(portEnds + 1);\n int downlinkLength = data.length() \/ 2;\n for (int i = 0, d = 0; i < downlinkLength; i++, d += 2)\n this->downlink[i] = HEX_PAIR_TO_BYTE(data[d], data[d+1]);\n debugPrint(F(\"Successful transmission. Received \"));\n debugPrint(downlinkLength);\n debugPrintLn(F(\" bytes\"));\n return downlinkLength;\n }\n\n debugPrint(F(\"Unexpected response: \"));\n debugPrintLn(response);\n}\n\nint TheThingsNetwork::sendString(String message, int port, bool confirm) {\n int l = message.length();\n byte buf[l + 1];\n message.getBytes(buf, l + 1);\n\n return sendBytes(buf, l, port, confirm);\n}\n\nvoid TheThingsNetwork::showStatus() {\n debugPrint(F(\"EUI: \"));\n debugPrintLn(readValue(F(\"sys get hweui\")));\n debugPrint(F(\"Battery: \"));\n debugPrint(readValue(F(\"sys get vdd\")));\n debugPrint(F(\"AppEUI: \"));\n debugPrintLn(readValue(F(\"mac get appeui\")));\n debugPrint(F(\"DevEUI: \"));\n debugPrintLn(readValue(F(\"mac get deveui\")));\n debugPrint(F(\"DevAddr: \"));\n debugPrintLn(readValue(F(\"mac get devaddr\")));\n\n if (this->model == F(\"RN2483\")) {\n debugPrint(F(\"Band: \"));\n debugPrintLn(readValue(F(\"mac get band\")));\n }\n\n debugPrint(F(\"Data Rate: \"));\n debugPrintLn(readValue(F(\"mac get dr\")));\n debugPrint(F(\"RX Delay 1: \"));\n debugPrintLn(readValue(F(\"mac get rxdelay1\")));\n debugPrint(F(\"RX Delay 2: \"));\n debugPrintLn(readValue(F(\"mac get rxdelay2\")));\n}\n<|endoftext|>"} {"text":"#include \"ParallelHash.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/Interface\/ThreadPool.h\"\r\n#include \"ClientHash.h\"\r\n#include \r\n#include \"database.h\"\r\n#include \"..\/stringtools.h\"\r\n\r\n\/\/#define HASH_CBT_CHECK\r\n\r\nnamespace\r\n{\r\n\tconst size_t max_modify_file_buffer_size = 2 * 1024 * 1024;\n\tconst int64 file_buffer_commit_interval = 120 * 1000;\r\n\tconst int64 link_file_min_size = 2048;\r\n}\r\n\r\nParallelHash::ParallelHash(SQueueRef* phash_queue, int sha_version)\r\n\t: do_quit(false), phash_queue(phash_queue), phash_queue_pos(0),\r\n\tstdout_buf_size(0), stdout_buf_pos(0), mutex(Server->createMutex()),\r\n\tlast_file_buffer_commit_time(0), sha_version(sha_version), eof(false)\r\n{\r\n\tstdout_buf.resize(4090);\r\n\tticket = Server->getThreadPool()->execute(this, \"phash\");\r\n}\r\n\r\nbool ParallelHash::getExitCode(int & exit_code)\r\n{\r\n\tServer->getThreadPool()->waitFor(ticket);\r\n\texit_code = 0;\r\n\treturn true;\r\n}\r\n\r\nvoid ParallelHash::forceExit()\r\n{\r\n\tdo_quit = true;\r\n\t\/\/Server->getThreadPool()->waitFor(ticket);\r\n}\r\n\r\nbool ParallelHash::readStdoutIntoBuffer(char * buf, size_t buf_avail, size_t & read_bytes)\r\n{\r\n\twhile(!do_quit)\r\n\t{\r\n\t\tIScopedLock lock(mutex.get());\r\n\t\tif (stdout_buf_size > stdout_buf_pos)\r\n\t\t{\r\n\t\t\tread_bytes = (std::min)(stdout_buf_size - stdout_buf_pos, buf_avail);\r\n\t\t\tmemcpy(buf, &stdout_buf[stdout_buf_pos], read_bytes);\r\n\t\t\tstdout_buf_pos += read_bytes;\r\n\r\n\t\t\tif (stdout_buf_pos == stdout_buf_size)\r\n\t\t\t{\r\n\t\t\t\tstdout_buf_pos = 0;\r\n\t\t\t\tstdout_buf_size = 0;\r\n\r\n\t\t\t\tif (eof)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (stdout_buf_pos == stdout_buf_size\r\n\t\t\t\t&& eof)\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tlock.relock(NULL);\r\n\t\t\tServer->wait(1000);\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid ParallelHash::finishStdout()\r\n{\r\n}\r\n\r\nbool ParallelHash::readStderrIntoBuffer(char * buf, size_t buf_avail, size_t & read_bytes)\r\n{\r\n\twhile (!do_quit\r\n\t\t&& !eof)\r\n\t{\r\n\t\tServer->wait(1000);\r\n\t}\r\n\t\r\n\treturn false;\r\n}\r\n\r\nvoid ParallelHash::operator()()\r\n{\r\n\tClientDAO clientdao(Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT));\r\n\r\n\tint mode = MODE_READ_SEQUENTIAL;\r\n#ifdef _WIN32\r\n\tmode = MODE_READ_DEVICE;\r\n#endif\r\n\tstd::auto_ptr phashf(Server->openFile(phash_queue->phash_queue->getFilename(), mode));\r\n\r\n\twhile (!do_quit\r\n\t\t&& phashf.get()!=NULL)\r\n\t{\r\n\t\tbool had_msg = false;\r\n\t\tif (phashf->Size() >= phash_queue_pos + static_cast(sizeof(_u32)))\r\n\t\t{\r\n\t\t\t_u32 msg_size;\r\n\t\t\tif (phashf->Read(phash_queue_pos, reinterpret_cast(&msg_size), sizeof(msg_size))\r\n\t\t\t\t== sizeof(msg_size))\r\n\t\t\t{\r\n\t\t\t\tif (phashf->Size() >= phash_queue_pos + static_cast(sizeof(_u32)) + msg_size)\r\n\t\t\t\t{\r\n\t\t\t\t\thad_msg = true;\r\n\r\n\t\t\t\t\tstd::string msg = phashf->Read(phash_queue_pos + sizeof(_u32), msg_size);\r\n\t\t\t\t\tCRData data(msg.data(), msg.size());\r\n\t\t\t\t\tphash_queue_pos += sizeof(_u32) + msg_size;\r\n\r\n\t\t\t\t\thashFile(data, clientdao);\r\n\r\n\t\t\t\t\tif (eof)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!had_msg)\r\n\t\t{\r\n\t\t\tServer->wait(1000);\r\n\t\t\tCWData data;\r\n\t\t\tdata.addUShort(1);\r\n\t\t\tdata.addChar(0);\r\n\t\t\taddToStdoutBuf(data.getDataPtr(), data.getDataSize());\r\n\t\t}\r\n\t}\r\n\r\n\tcommitModifyFileBuffer(clientdao);\r\n\r\n\tif (phash_queue->deref())\r\n\t{\r\n\t\tdelete phash_queue;\r\n\t\tphash_queue = NULL;\r\n\t}\r\n}\r\n\r\nbool ParallelHash::hashFile(CRData & data, ClientDAO& clientdao)\r\n{\r\n\tchar id;\r\n\tif (!data.getChar(&id))\r\n\t\treturn false;\r\n\r\n\tif (id == ID_SET_CURR_DIRS)\r\n\t{\r\n\t\tcurr_files.clear();\r\n\r\n\t\tif (!data.getStr2(&curr_dir)\r\n\t\t\t|| !data.getInt(&curr_tgroup)\r\n\t\t\t|| !data.getStr2(&curr_snapshot_dir))\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_FINISH_CURR_DIR)\r\n\t{\r\n\t\tint64 target_generation;\r\n\t\tif (!data.getVarInt(&target_generation))\r\n\t\t{\r\n\t\t\tcurr_files.clear();\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n#ifndef _WIN32\n\t\tstd::string path_lower = curr_dir + os_file_sep();\n#else\n\t\tstd::string path_lower = strlower(curr_dir + os_file_sep());\n#endif\r\n\r\n\t\tstd::vector files;\r\n\t\tint64 generation = -1;\r\n\t\tif (clientdao.getFiles(path_lower, curr_tgroup, files, generation))\r\n\t\t{\r\n\t\t\tif (generation != target_generation)\r\n\t\t\t{\r\n\t\t\t\tcurr_files.clear();\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tstd::sort(curr_files.begin(), curr_files.end());\r\n\r\n\t\t\tbool added_hash = false;\r\n\t\t\tfor (size_t i = 0; i < files.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tif (files[i].hash.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::vector::iterator it =\r\n\t\t\t\t\t\tstd::lower_bound(curr_files.begin(), curr_files.end(), files[i]);\r\n\t\t\t\t\tif (it != curr_files.end()\r\n\t\t\t\t\t\t&& it->name == files[i].name)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfiles[i].hash = it->hash;\r\n\t\t\t\t\t\tadded_hash = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (added_hash)\r\n\t\t\t{\r\n\t\t\t\taddModifyFileBuffer(clientdao, path_lower, curr_tgroup, files, target_generation);\r\n\t\t\t}\r\n\r\n\t\t\tcurr_files.clear();\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tcurr_files.clear();\r\n\t\treturn false;\r\n\t}\r\n\telse if (id == ID_INIT_HASH)\r\n\t{\r\n\t\tclient_hash.reset(new ClientHash(NULL, false, 0, NULL, 0));\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_CBT_DATA)\r\n\t{\r\n\t\tIFile* index_hdat_file;\r\n\t\tint64 index_hdat_fs_block_size;\r\n\t\tsize_t* snapshot_sequence_id;\r\n\t\tint64 snapshot_sequence_id_reference;\r\n\t\tif (!data.getVoidPtr(reinterpret_cast(&index_hdat_file))\r\n\t\t\t|| !data.getVarInt(&index_hdat_fs_block_size)\r\n\t\t\t|| !data.getVoidPtr(reinterpret_cast(&snapshot_sequence_id))\r\n\t\t\t|| !data.getVarInt(&snapshot_sequence_id_reference))\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tclient_hash.reset(new ClientHash(index_hdat_file, true, index_hdat_fs_block_size,\r\n\t\t\tsnapshot_sequence_id, static_cast(snapshot_sequence_id_reference)));\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_PHASH_FINISH)\r\n\t{\r\n\t\teof = true;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tif (id != ID_HASH_FILE)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tint64 file_id;\r\n\tif (!data.getVarInt(&file_id))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::string fn;\r\n\tif (!data.getStr2(&fn))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::string full_path = curr_snapshot_dir + os_file_sep() + fn;\r\n\r\n\tstd::auto_ptr f(Server->openFile(os_file_prefix(fn), MODE_READ_SEQUENTIAL_BACKUP));\r\n\r\n\tSFileAndHash fandhash;\r\n\tif (f.get() != NULL && f->Size() < link_file_min_size)\r\n\t{\r\n\t\tf.reset();\r\n\t}\r\n\telse if (sha_version == 256)\n\t{\n\t\tf.reset();\n\n\t\tHashSha256 hash_256;\n\t\tif (!client_hash->getShaBinary(full_path, hash_256, false))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (0) \" + full_path + \". \" + os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = hash_256.finalize();\n\t\t}\n\t}\n\telse if (sha_version == 528)\n\t{\n\t\tf.reset();\n\n\t\tTreeHash treehash(client_hash->hasCbtFile() ? client_hash.get() : NULL);\n\t\tif (!client_hash->getShaBinary(full_path, treehash, client_hash->hasCbtFile()))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (1) \" + full_path+\". \"+os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = treehash.finalize();\n\t\t}\n\n#ifdef HASH_CBT_CHECK\n\t\tTreeHash treehash2(client_hash->hasCbtFile() ? client_hash.get() : NULL);\n\t\tclient_hash->getShaBinary(full_path, treehash2, false);\n\t\t\n\t\tstd::string other_hash = treehash2.finalize();\n\t\tif (other_hash != fandhash.hash)\n\t\t{\n\t\t\tServer->Log(\"Treehash compare without CBT failed at file \\\"\" + full_path \n\t\t\t\t+ \"\\\". Real hash: \"+ base64_encode_dash(other_hash), LL_ERROR);\n\t\t}\n#endif\n\t}\n\telse\n\t{\n\t\tf.reset();\n\n\t\tHashSha512 hash_512;\n\t\tif (!client_hash->getShaBinary(full_path, hash_512, false))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (2) \" + full_path + \". \" + os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = hash_512.finalize();\n\t\t}\n\t}\r\n\r\n\tCWData wdata;\r\n\twdata.addUShort(0);\r\n\twdata.addChar(1);\r\n\twdata.addVarInt(file_id);\r\n\twdata.addString2(fandhash.hash);\r\n\tfandhash.name = fn;\r\n\t*reinterpret_cast<_u16*>(wdata.getDataPtr()) = little_endian(static_cast<_u16>(wdata.getDataSize() - sizeof(_u16)));\r\n\tcurr_files.push_back(fandhash);\r\n\r\n\tServer->Log(\"Parallel hash \\\"\" + full_path + \"\\\" id=\" + convert(file_id) + \" hash=\" + base64_encode_dash(fandhash.hash), LL_DEBUG);\r\n\r\n\taddToStdoutBuf(wdata.getDataPtr(), wdata.getDataSize());\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid ParallelHash::addToStdoutBuf(const char * ptr, size_t size)\r\n{\r\n\tIScopedLock lock(mutex.get());\r\n\r\n\twhile (stdout_buf_size + size > 32 * 1024)\r\n\t{\r\n\t\tlock.relock(NULL);\r\n\t\tServer->wait(1000);\r\n\t\tlock.relock(mutex.get());\r\n\t}\r\n\r\n\tif (stdout_buf_size + size > stdout_buf.size())\r\n\t{\r\n\t\tstdout_buf.resize(stdout_buf_size + size);\r\n\t}\r\n\r\n\tmemcpy(&stdout_buf[stdout_buf_size], ptr, size);\r\n\tstdout_buf_size += size;\r\n}\r\n\r\nsize_t ParallelHash::calcBufferSize(const std::string &path, const std::vector &data)\n{\n\tsize_t add_size = path.size() + sizeof(std::string) + sizeof(int) + sizeof(int64);\n\tfor (size_t i = 0; i);\n\n\treturn add_size;\n}\r\n\r\nvoid ParallelHash::addModifyFileBuffer(ClientDAO& clientdao, const std::string & path, int tgroup,\r\n\tconst std::vector& files, int64 target_generation)\r\n{\r\n\tmodify_file_buffer_size += calcBufferSize(path, files);\n\n\tmodify_file_buffer.push_back(SBufferItem(path, tgroup, files, target_generation));\n\n\tif (last_file_buffer_commit_time == 0)\n\t{\n\t\tlast_file_buffer_commit_time = Server->getTimeMS();\n\t}\n\n\tif (modify_file_buffer_size>max_modify_file_buffer_size\n\t\t|| Server->getTimeMS() - last_file_buffer_commit_time>file_buffer_commit_interval)\n\t{\n\t\tcommitModifyFileBuffer(clientdao);\n\t}\r\n}\r\n\r\nvoid ParallelHash::commitModifyFileBuffer(ClientDAO& clientdao)\r\n{\r\n\tDBScopedWriteTransaction trans(clientdao.getDatabase());\n\tfor (size_t i = 0; igetTimeMS();\r\n}\r\nFix phash skipping of small files#include \"ParallelHash.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/Interface\/ThreadPool.h\"\r\n#include \"ClientHash.h\"\r\n#include \r\n#include \"database.h\"\r\n#include \"..\/stringtools.h\"\r\n\r\n\/\/#define HASH_CBT_CHECK\r\n\r\nnamespace\r\n{\r\n\tconst size_t max_modify_file_buffer_size = 2 * 1024 * 1024;\n\tconst int64 file_buffer_commit_interval = 120 * 1000;\r\n\tconst int64 link_file_min_size = 2048;\r\n}\r\n\r\nParallelHash::ParallelHash(SQueueRef* phash_queue, int sha_version)\r\n\t: do_quit(false), phash_queue(phash_queue), phash_queue_pos(0),\r\n\tstdout_buf_size(0), stdout_buf_pos(0), mutex(Server->createMutex()),\r\n\tlast_file_buffer_commit_time(0), sha_version(sha_version), eof(false)\r\n{\r\n\tstdout_buf.resize(4090);\r\n\tticket = Server->getThreadPool()->execute(this, \"phash\");\r\n}\r\n\r\nbool ParallelHash::getExitCode(int & exit_code)\r\n{\r\n\tServer->getThreadPool()->waitFor(ticket);\r\n\texit_code = 0;\r\n\treturn true;\r\n}\r\n\r\nvoid ParallelHash::forceExit()\r\n{\r\n\tdo_quit = true;\r\n\t\/\/Server->getThreadPool()->waitFor(ticket);\r\n}\r\n\r\nbool ParallelHash::readStdoutIntoBuffer(char * buf, size_t buf_avail, size_t & read_bytes)\r\n{\r\n\twhile(!do_quit)\r\n\t{\r\n\t\tIScopedLock lock(mutex.get());\r\n\t\tif (stdout_buf_size > stdout_buf_pos)\r\n\t\t{\r\n\t\t\tread_bytes = (std::min)(stdout_buf_size - stdout_buf_pos, buf_avail);\r\n\t\t\tmemcpy(buf, &stdout_buf[stdout_buf_pos], read_bytes);\r\n\t\t\tstdout_buf_pos += read_bytes;\r\n\r\n\t\t\tif (stdout_buf_pos == stdout_buf_size)\r\n\t\t\t{\r\n\t\t\t\tstdout_buf_pos = 0;\r\n\t\t\t\tstdout_buf_size = 0;\r\n\r\n\t\t\t\tif (eof)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (stdout_buf_pos == stdout_buf_size\r\n\t\t\t\t&& eof)\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tlock.relock(NULL);\r\n\t\t\tServer->wait(1000);\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid ParallelHash::finishStdout()\r\n{\r\n}\r\n\r\nbool ParallelHash::readStderrIntoBuffer(char * buf, size_t buf_avail, size_t & read_bytes)\r\n{\r\n\twhile (!do_quit\r\n\t\t&& !eof)\r\n\t{\r\n\t\tServer->wait(1000);\r\n\t}\r\n\t\r\n\treturn false;\r\n}\r\n\r\nvoid ParallelHash::operator()()\r\n{\r\n\tClientDAO clientdao(Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT));\r\n\r\n\tint mode = MODE_READ_SEQUENTIAL;\r\n#ifdef _WIN32\r\n\tmode = MODE_READ_DEVICE;\r\n#endif\r\n\tstd::auto_ptr phashf(Server->openFile(phash_queue->phash_queue->getFilename(), mode));\r\n\r\n\twhile (!do_quit\r\n\t\t&& phashf.get()!=NULL)\r\n\t{\r\n\t\tbool had_msg = false;\r\n\t\tif (phashf->Size() >= phash_queue_pos + static_cast(sizeof(_u32)))\r\n\t\t{\r\n\t\t\t_u32 msg_size;\r\n\t\t\tif (phashf->Read(phash_queue_pos, reinterpret_cast(&msg_size), sizeof(msg_size))\r\n\t\t\t\t== sizeof(msg_size))\r\n\t\t\t{\r\n\t\t\t\tif (phashf->Size() >= phash_queue_pos + static_cast(sizeof(_u32)) + msg_size)\r\n\t\t\t\t{\r\n\t\t\t\t\thad_msg = true;\r\n\r\n\t\t\t\t\tstd::string msg = phashf->Read(phash_queue_pos + sizeof(_u32), msg_size);\r\n\t\t\t\t\tCRData data(msg.data(), msg.size());\r\n\t\t\t\t\tphash_queue_pos += sizeof(_u32) + msg_size;\r\n\r\n\t\t\t\t\thashFile(data, clientdao);\r\n\r\n\t\t\t\t\tif (eof)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!had_msg)\r\n\t\t{\r\n\t\t\tServer->wait(1000);\r\n\t\t\tCWData data;\r\n\t\t\tdata.addUShort(1);\r\n\t\t\tdata.addChar(0);\r\n\t\t\taddToStdoutBuf(data.getDataPtr(), data.getDataSize());\r\n\t\t}\r\n\t}\r\n\r\n\tcommitModifyFileBuffer(clientdao);\r\n\r\n\tif (phash_queue->deref())\r\n\t{\r\n\t\tdelete phash_queue;\r\n\t\tphash_queue = NULL;\r\n\t}\r\n}\r\n\r\nbool ParallelHash::hashFile(CRData & data, ClientDAO& clientdao)\r\n{\r\n\tchar id;\r\n\tif (!data.getChar(&id))\r\n\t\treturn false;\r\n\r\n\tif (id == ID_SET_CURR_DIRS)\r\n\t{\r\n\t\tcurr_files.clear();\r\n\r\n\t\tif (!data.getStr2(&curr_dir)\r\n\t\t\t|| !data.getInt(&curr_tgroup)\r\n\t\t\t|| !data.getStr2(&curr_snapshot_dir))\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_FINISH_CURR_DIR)\r\n\t{\r\n\t\tint64 target_generation;\r\n\t\tif (!data.getVarInt(&target_generation))\r\n\t\t{\r\n\t\t\tcurr_files.clear();\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n#ifndef _WIN32\n\t\tstd::string path_lower = curr_dir + os_file_sep();\n#else\n\t\tstd::string path_lower = strlower(curr_dir + os_file_sep());\n#endif\r\n\r\n\t\tstd::vector files;\r\n\t\tint64 generation = -1;\r\n\t\tif (clientdao.getFiles(path_lower, curr_tgroup, files, generation))\r\n\t\t{\r\n\t\t\tif (generation != target_generation)\r\n\t\t\t{\r\n\t\t\t\tcurr_files.clear();\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tstd::sort(curr_files.begin(), curr_files.end());\r\n\r\n\t\t\tbool added_hash = false;\r\n\t\t\tfor (size_t i = 0; i < files.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tif (files[i].hash.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::vector::iterator it =\r\n\t\t\t\t\t\tstd::lower_bound(curr_files.begin(), curr_files.end(), files[i]);\r\n\t\t\t\t\tif (it != curr_files.end()\r\n\t\t\t\t\t\t&& it->name == files[i].name)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfiles[i].hash = it->hash;\r\n\t\t\t\t\t\tadded_hash = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (added_hash)\r\n\t\t\t{\r\n\t\t\t\taddModifyFileBuffer(clientdao, path_lower, curr_tgroup, files, target_generation);\r\n\t\t\t}\r\n\r\n\t\t\tcurr_files.clear();\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tcurr_files.clear();\r\n\t\treturn false;\r\n\t}\r\n\telse if (id == ID_INIT_HASH)\r\n\t{\r\n\t\tclient_hash.reset(new ClientHash(NULL, false, 0, NULL, 0));\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_CBT_DATA)\r\n\t{\r\n\t\tIFile* index_hdat_file;\r\n\t\tint64 index_hdat_fs_block_size;\r\n\t\tsize_t* snapshot_sequence_id;\r\n\t\tint64 snapshot_sequence_id_reference;\r\n\t\tif (!data.getVoidPtr(reinterpret_cast(&index_hdat_file))\r\n\t\t\t|| !data.getVarInt(&index_hdat_fs_block_size)\r\n\t\t\t|| !data.getVoidPtr(reinterpret_cast(&snapshot_sequence_id))\r\n\t\t\t|| !data.getVarInt(&snapshot_sequence_id_reference))\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tclient_hash.reset(new ClientHash(index_hdat_file, true, index_hdat_fs_block_size,\r\n\t\t\tsnapshot_sequence_id, static_cast(snapshot_sequence_id_reference)));\r\n\t\treturn true;\r\n\t}\r\n\telse if (id == ID_PHASH_FINISH)\r\n\t{\r\n\t\teof = true;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tif (id != ID_HASH_FILE)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tint64 file_id;\r\n\tif (!data.getVarInt(&file_id))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::string fn;\r\n\tif (!data.getStr2(&fn))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tstd::string full_path = curr_snapshot_dir + os_file_sep() + fn;\r\n\r\n\tstd::auto_ptr f(Server->openFile(os_file_prefix(full_path), MODE_READ_SEQUENTIAL_BACKUP));\r\n\r\n\tSFileAndHash fandhash;\r\n\tif (f.get() != NULL && f->Size() < link_file_min_size)\r\n\t{\r\n\t\tf.reset();\r\n\t}\r\n\telse if (sha_version == 256)\n\t{\n\t\tf.reset();\n\n\t\tHashSha256 hash_256;\n\t\tif (!client_hash->getShaBinary(full_path, hash_256, false))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (0) \" + full_path + \". \" + os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = hash_256.finalize();\n\t\t}\n\t}\n\telse if (sha_version == 528)\n\t{\n\t\tf.reset();\n\n\t\tTreeHash treehash(client_hash->hasCbtFile() ? client_hash.get() : NULL);\n\t\tif (!client_hash->getShaBinary(full_path, treehash, client_hash->hasCbtFile()))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (1) \" + full_path+\". \"+os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = treehash.finalize();\n\t\t}\n\n#ifdef HASH_CBT_CHECK\n\t\tTreeHash treehash2(client_hash->hasCbtFile() ? client_hash.get() : NULL);\n\t\tclient_hash->getShaBinary(full_path, treehash2, false);\n\t\t\n\t\tstd::string other_hash = treehash2.finalize();\n\t\tif (other_hash != fandhash.hash)\n\t\t{\n\t\t\tServer->Log(\"Treehash compare without CBT failed at file \\\"\" + full_path \n\t\t\t\t+ \"\\\". Real hash: \"+ base64_encode_dash(other_hash), LL_ERROR);\n\t\t}\n#endif\n\t}\n\telse\n\t{\n\t\tf.reset();\n\n\t\tHashSha512 hash_512;\n\t\tif (!client_hash->getShaBinary(full_path, hash_512, false))\n\t\t{\n\t\t\tServer->Log(\"Error hashing file (2) \" + full_path + \". \" + os_last_error_str(), LL_DEBUG);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfandhash.hash = hash_512.finalize();\n\t\t}\n\t}\r\n\r\n\tCWData wdata;\r\n\twdata.addUShort(0);\r\n\twdata.addChar(1);\r\n\twdata.addVarInt(file_id);\r\n\twdata.addString2(fandhash.hash);\r\n\tfandhash.name = fn;\r\n\t*reinterpret_cast<_u16*>(wdata.getDataPtr()) = little_endian(static_cast<_u16>(wdata.getDataSize() - sizeof(_u16)));\r\n\tcurr_files.push_back(fandhash);\r\n\r\n\tServer->Log(\"Parallel hash \\\"\" + full_path + \"\\\" id=\" + convert(file_id) + \" hash=\" + base64_encode_dash(fandhash.hash), LL_DEBUG);\r\n\r\n\taddToStdoutBuf(wdata.getDataPtr(), wdata.getDataSize());\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid ParallelHash::addToStdoutBuf(const char * ptr, size_t size)\r\n{\r\n\tIScopedLock lock(mutex.get());\r\n\r\n\twhile (stdout_buf_size + size > 32 * 1024)\r\n\t{\r\n\t\tlock.relock(NULL);\r\n\t\tServer->wait(1000);\r\n\t\tlock.relock(mutex.get());\r\n\t}\r\n\r\n\tif (stdout_buf_size + size > stdout_buf.size())\r\n\t{\r\n\t\tstdout_buf.resize(stdout_buf_size + size);\r\n\t}\r\n\r\n\tmemcpy(&stdout_buf[stdout_buf_size], ptr, size);\r\n\tstdout_buf_size += size;\r\n}\r\n\r\nsize_t ParallelHash::calcBufferSize(const std::string &path, const std::vector &data)\n{\n\tsize_t add_size = path.size() + sizeof(std::string) + sizeof(int) + sizeof(int64);\n\tfor (size_t i = 0; i);\n\n\treturn add_size;\n}\r\n\r\nvoid ParallelHash::addModifyFileBuffer(ClientDAO& clientdao, const std::string & path, int tgroup,\r\n\tconst std::vector& files, int64 target_generation)\r\n{\r\n\tmodify_file_buffer_size += calcBufferSize(path, files);\n\n\tmodify_file_buffer.push_back(SBufferItem(path, tgroup, files, target_generation));\n\n\tif (last_file_buffer_commit_time == 0)\n\t{\n\t\tlast_file_buffer_commit_time = Server->getTimeMS();\n\t}\n\n\tif (modify_file_buffer_size>max_modify_file_buffer_size\n\t\t|| Server->getTimeMS() - last_file_buffer_commit_time>file_buffer_commit_interval)\n\t{\n\t\tcommitModifyFileBuffer(clientdao);\n\t}\r\n}\r\n\r\nvoid ParallelHash::commitModifyFileBuffer(ClientDAO& clientdao)\r\n{\r\n\tDBScopedWriteTransaction trans(clientdao.getDatabase());\n\tfor (size_t i = 0; igetTimeMS();\r\n}\r\n<|endoftext|>"} {"text":"#include \"dreal\/optimization\/nlopt_optimizer.h\"\n\n#include \n#include \n\n#include \"dreal\/util\/exception.h\"\n\nnamespace dreal {\n\nusing std::make_pair;\nusing std::make_unique;\nusing std::move;\nusing std::ostream;\nusing std::ostringstream;\nusing std::pair;\nusing std::unique_ptr;\nusing std::vector;\n\nnamespace {\n\/\/\/ A function passed to nlopt (type = nlopt_func). Given a vector @p\n\/\/\/ x, returns the evaluation of @p f_data at @p x and updates @p grad\n\/\/\/ which is the gradient of the function @p f_data with respect to @p\n\/\/\/ x.\n\/\/\/\n\/\/\/ @see\n\/\/\/ http:\/\/nlopt.readthedocs.io\/en\/latest\/NLopt_Reference\/#objective-function.\n\/\/ double NloptOptimizerEvaluate(unsigned n, const double* x, double* grad,\n\/\/ void* f_data);\ndouble NloptOptimizerEvaluate(const unsigned n, const double* x, double* grad,\n void* const f_data) {\n assert(f_data);\n auto& expression{*static_cast(f_data)};\n const Box& box{expression.box()};\n assert(n == static_cast(box.size()));\n \/\/ Set up an environment.\n Environment& env{expression.mutable_environment()};\n for (size_t i = 0; i < n; ++i) {\n const Variable& v{box.variable(i)};\n env[v] = x[i];\n }\n \/\/ Set up gradients.\n if (grad) {\n for (int i = 0; i < box.size(); ++i) {\n const Variable& v{box.variable(i)};\n grad[i] = expression.Differentiate(v).Evaluate(env);\n }\n }\n \/\/ Return evaluation.\n return expression.Evaluate(env);\n}\n} \/\/ namespace\n\n\/\/ ----------------\n\/\/ CachedExpression\n\/\/ ----------------\nCachedExpression::CachedExpression(Expression e, const Box& box)\n : expression_{move(e)}, box_{&box} {\n assert(box_);\n}\n\nconst Box& CachedExpression::box() const {\n assert(box_);\n return *box_;\n}\n\nEnvironment& CachedExpression::mutable_environment() { return environment_; }\n\nconst Environment& CachedExpression::environment() const {\n return environment_;\n}\n\ndouble CachedExpression::Evaluate(const Environment& env) const {\n return expression_.Evaluate(env);\n}\n\nconst Expression& CachedExpression::Differentiate(const Variable& x) {\n auto it = gradient_.find(x);\n if (it == gradient_.end()) {\n \/\/ Not found.\n return gradient_.emplace_hint(it, x, expression_.Differentiate(x))->second;\n } else {\n return it->second;\n }\n}\n\nostream& operator<<(ostream& os, const CachedExpression& expression) {\n return os << expression.expression_;\n}\n\n\/\/ --------------\n\/\/ NloptOptimizer\n\/\/ --------------\nNloptOptimizer::NloptOptimizer(const nlopt_algorithm algorithm, Box bound,\n const double delta)\n : box_{move(bound)}, delta_{delta} {\n assert(delta_ > 0.0);\n opt_ = nlopt_create(algorithm, box_.size());\n\n \/\/ Set tolerance.\n nlopt_set_ftol_rel(opt_, delta_);\n\n \/\/ Set bounds.\n const auto lower_bounds = make_unique(box_.size());\n const auto upper_bounds = make_unique(box_.size());\n for (int i = 0; i < box_.size(); ++i) {\n lower_bounds[i] = box_[i].lb();\n upper_bounds[i] = box_[i].ub();\n }\n const nlopt_result nlopt_result_lb{\n nlopt_set_lower_bounds(opt_, lower_bounds.get())};\n assert(nlopt_result_lb == NLOPT_SUCCESS);\n const nlopt_result nlopt_result_ub{\n nlopt_set_upper_bounds(opt_, upper_bounds.get())};\n assert(nlopt_result_ub == NLOPT_SUCCESS);\n}\n\nNloptOptimizer::~NloptOptimizer() { nlopt_destroy(opt_); }\n\nvoid NloptOptimizer::SetMinObjective(const Expression& objective) {\n objective_ = CachedExpression{objective, box_};\n const nlopt_result result{nlopt_set_min_objective(\n opt_, NloptOptimizerEvaluate, static_cast(&objective_))};\n assert(result == NLOPT_SUCCESS);\n}\n\nvoid NloptOptimizer::AddConstraint(const Formula& formula) {\n if (is_conjunction(formula)) {\n for (const Formula& f : get_operands(formula)) {\n AddConstraint(f);\n }\n return;\n }\n if (is_relational(formula)) {\n return AddRelationalConstraint(formula);\n }\n if (is_negation(formula)) {\n const Formula& negated_formula{get_operand(formula)};\n if (is_relational(negated_formula)) {\n return AddRelationalConstraint(nnfizer_.Convert(negated_formula));\n }\n }\n ostringstream oss;\n oss << \"NloptOptimizer::AddConstraint: \"\n << \"Unsupported formula: \" << formula;\n throw DREAL_RUNTIME_ERROR(oss.str());\n}\n\nvoid NloptOptimizer::AddRelationalConstraint(const Formula& formula) {\n bool equality{false};\n if (is_greater_than(formula) || is_greater_than_or_equal_to(formula)) {\n \/\/ f := e₁ > e₂ –> e₂ - e₁ < 0.\n auto cached_expression = make_unique(\n get_rhs_expression(formula) - get_lhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n } else if (is_less_than(formula) || is_less_than_or_equal_to(formula)) {\n \/\/ f := e₁ < e₂ –> e₁ - e₂ < 0.\n auto cached_expression = make_unique(\n get_lhs_expression(formula) - get_rhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n } else if (is_equal_to(formula)) {\n \/\/ f := e₁ == e₂ -> e₁ - e₂ == 0\n auto cached_expression = make_unique(\n get_lhs_expression(formula) - get_rhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n equality = true;\n } else {\n ostringstream oss;\n oss << \"NloptOptimizer::AddRelationalConstraint: \"\n << \"Unsupported formula: \" << formula;\n throw DREAL_RUNTIME_ERROR(oss.str());\n }\n\n if (equality) {\n nlopt_add_equality_constraint(opt_, NloptOptimizerEvaluate,\n static_cast(constraints_.back().get()),\n delta_);\n } else {\n nlopt_add_inequality_constraint(\n opt_, NloptOptimizerEvaluate,\n static_cast(constraints_.back().get()), delta_);\n }\n}\n\nvoid NloptOptimizer::AddConstraints(const vector& formulas) {\n for (const Formula& formula : formulas) {\n AddConstraint(formula);\n }\n}\n\nnlopt_result NloptOptimizer::Optimize(vector* const x,\n double* const opt_f) {\n return nlopt_optimize(opt_, x->data(), opt_f);\n}\n\n} \/\/ namespace dreal\nfix(dreal\/optimization\/nlopt_optimizer.cc): gcc-4.9 issue#include \"dreal\/optimization\/nlopt_optimizer.h\"\n\n#include \n#include \n\n#include \"dreal\/util\/exception.h\"\n\nnamespace dreal {\n\nusing std::make_pair;\nusing std::make_unique;\nusing std::move;\nusing std::ostream;\nusing std::ostringstream;\nusing std::pair;\nusing std::unique_ptr;\nusing std::vector;\n\nnamespace {\n\/\/\/ A function passed to nlopt (type = nlopt_func). Given a vector @p\n\/\/\/ x, returns the evaluation of @p f_data at @p x and updates @p grad\n\/\/\/ which is the gradient of the function @p f_data with respect to @p\n\/\/\/ x.\n\/\/\/\n\/\/\/ @see\n\/\/\/ http:\/\/nlopt.readthedocs.io\/en\/latest\/NLopt_Reference\/#objective-function.\n\/\/ double NloptOptimizerEvaluate(unsigned n, const double* x, double* grad,\n\/\/ void* f_data);\ndouble NloptOptimizerEvaluate(const unsigned n, const double* x, double* grad,\n void* const f_data) {\n assert(f_data);\n auto& expression = *static_cast(f_data);\n const Box& box{expression.box()};\n assert(n == static_cast(box.size()));\n \/\/ Set up an environment.\n Environment& env{expression.mutable_environment()};\n for (size_t i = 0; i < n; ++i) {\n const Variable& v{box.variable(i)};\n env[v] = x[i];\n }\n \/\/ Set up gradients.\n if (grad) {\n for (int i = 0; i < box.size(); ++i) {\n const Variable& v{box.variable(i)};\n grad[i] = expression.Differentiate(v).Evaluate(env);\n }\n }\n \/\/ Return evaluation.\n return expression.Evaluate(env);\n}\n} \/\/ namespace\n\n\/\/ ----------------\n\/\/ CachedExpression\n\/\/ ----------------\nCachedExpression::CachedExpression(Expression e, const Box& box)\n : expression_{move(e)}, box_{&box} {\n assert(box_);\n}\n\nconst Box& CachedExpression::box() const {\n assert(box_);\n return *box_;\n}\n\nEnvironment& CachedExpression::mutable_environment() { return environment_; }\n\nconst Environment& CachedExpression::environment() const {\n return environment_;\n}\n\ndouble CachedExpression::Evaluate(const Environment& env) const {\n return expression_.Evaluate(env);\n}\n\nconst Expression& CachedExpression::Differentiate(const Variable& x) {\n auto it = gradient_.find(x);\n if (it == gradient_.end()) {\n \/\/ Not found.\n return gradient_.emplace_hint(it, x, expression_.Differentiate(x))->second;\n } else {\n return it->second;\n }\n}\n\nostream& operator<<(ostream& os, const CachedExpression& expression) {\n return os << expression.expression_;\n}\n\n\/\/ --------------\n\/\/ NloptOptimizer\n\/\/ --------------\nNloptOptimizer::NloptOptimizer(const nlopt_algorithm algorithm, Box bound,\n const double delta)\n : box_{move(bound)}, delta_{delta} {\n assert(delta_ > 0.0);\n opt_ = nlopt_create(algorithm, box_.size());\n\n \/\/ Set tolerance.\n nlopt_set_ftol_rel(opt_, delta_);\n\n \/\/ Set bounds.\n const auto lower_bounds = make_unique(box_.size());\n const auto upper_bounds = make_unique(box_.size());\n for (int i = 0; i < box_.size(); ++i) {\n lower_bounds[i] = box_[i].lb();\n upper_bounds[i] = box_[i].ub();\n }\n const nlopt_result nlopt_result_lb{\n nlopt_set_lower_bounds(opt_, lower_bounds.get())};\n assert(nlopt_result_lb == NLOPT_SUCCESS);\n const nlopt_result nlopt_result_ub{\n nlopt_set_upper_bounds(opt_, upper_bounds.get())};\n assert(nlopt_result_ub == NLOPT_SUCCESS);\n}\n\nNloptOptimizer::~NloptOptimizer() { nlopt_destroy(opt_); }\n\nvoid NloptOptimizer::SetMinObjective(const Expression& objective) {\n objective_ = CachedExpression{objective, box_};\n const nlopt_result result{nlopt_set_min_objective(\n opt_, NloptOptimizerEvaluate, static_cast(&objective_))};\n assert(result == NLOPT_SUCCESS);\n}\n\nvoid NloptOptimizer::AddConstraint(const Formula& formula) {\n if (is_conjunction(formula)) {\n for (const Formula& f : get_operands(formula)) {\n AddConstraint(f);\n }\n return;\n }\n if (is_relational(formula)) {\n return AddRelationalConstraint(formula);\n }\n if (is_negation(formula)) {\n const Formula& negated_formula{get_operand(formula)};\n if (is_relational(negated_formula)) {\n return AddRelationalConstraint(nnfizer_.Convert(negated_formula));\n }\n }\n ostringstream oss;\n oss << \"NloptOptimizer::AddConstraint: \"\n << \"Unsupported formula: \" << formula;\n throw DREAL_RUNTIME_ERROR(oss.str());\n}\n\nvoid NloptOptimizer::AddRelationalConstraint(const Formula& formula) {\n bool equality{false};\n if (is_greater_than(formula) || is_greater_than_or_equal_to(formula)) {\n \/\/ f := e₁ > e₂ –> e₂ - e₁ < 0.\n auto cached_expression = make_unique(\n get_rhs_expression(formula) - get_lhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n } else if (is_less_than(formula) || is_less_than_or_equal_to(formula)) {\n \/\/ f := e₁ < e₂ –> e₁ - e₂ < 0.\n auto cached_expression = make_unique(\n get_lhs_expression(formula) - get_rhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n } else if (is_equal_to(formula)) {\n \/\/ f := e₁ == e₂ -> e₁ - e₂ == 0\n auto cached_expression = make_unique(\n get_lhs_expression(formula) - get_rhs_expression(formula), box_);\n constraints_.push_back(move(cached_expression));\n equality = true;\n } else {\n ostringstream oss;\n oss << \"NloptOptimizer::AddRelationalConstraint: \"\n << \"Unsupported formula: \" << formula;\n throw DREAL_RUNTIME_ERROR(oss.str());\n }\n\n if (equality) {\n nlopt_add_equality_constraint(opt_, NloptOptimizerEvaluate,\n static_cast(constraints_.back().get()),\n delta_);\n } else {\n nlopt_add_inequality_constraint(\n opt_, NloptOptimizerEvaluate,\n static_cast(constraints_.back().get()), delta_);\n }\n}\n\nvoid NloptOptimizer::AddConstraints(const vector& formulas) {\n for (const Formula& formula : formulas) {\n AddConstraint(formula);\n }\n}\n\nnlopt_result NloptOptimizer::Optimize(vector* const x,\n double* const opt_f) {\n return nlopt_optimize(opt_, x->data(), opt_f);\n}\n\n} \/\/ namespace dreal\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#include \n\n#include \n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Helper functions\n\/\/\n\n\/\/ nested for loop over matrices --------------------------\n\ntemplate \nvoid for_each_mat2_e(Func f)\n{\n for (int i = 0; i < 2; ++i)\n {\n for (int j = 0; j < 2; ++j)\n {\n f(i, j);\n }\n }\n}\n\ntemplate \nvoid for_each_mat3_e(Func f)\n{\n for (int i = 0; i < 3; ++i)\n {\n for (int j = 0; j < 3; ++j)\n {\n f(i, j);\n }\n }\n}\n\ntemplate \nvoid for_each_mat4_e(Func f)\n{\n for (int i = 0; i < 4; ++i)\n {\n for (int j = 0; j < 4; ++j)\n {\n f(i, j);\n }\n }\n}\n\n\n\/\/ get rows and columns -----------------------------------\n\ntemplate \nvector get_row(matrix const& m, int i)\n{\n assert( i >= 0 && i < 4 );\n\n vector result;\n\n for (size_t d = 0; d < Dim; ++d)\n {\n result[d] = m(i, d);\n }\n\n return result;\n}\n\ntemplate \nvector get_col(matrix const& m, int j)\n{\n assert( j >= 0 && j < 4 );\n\n return m(j);\n}\n\n\nTEST(Matrix, Inverse)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n mat2 I = mat2::identity();\n\n \/\/ make some non-singular matrix\n mat2 A(1, 2, 3, 4);\n mat2 B = inverse(A);\n mat2 C = A * B;\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n mat3 I = mat3::identity();\n\n \/\/ make some non-singular matrix\n mat3 A = mat3::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat3 B = inverse(A);\n mat3 C = A * B;\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n mat4 I = mat4::identity();\n\n \/\/ make some non-singular matrix\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = inverse(A);\n mat4 C = A * B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n}\n\nTEST(Matrix, Mult)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n \/\/ make some matrices\n mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat2 B = mat2::identity(); B(0, 0) = 11.0f; B(1, 0) = 6.28f; B(1, 1) = 3.0f;\n mat2 C = A * B;\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n \/\/ make some matrices\n mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat3 B = mat3::identity(); B(0, 1) = 11.0f; B(2, 1) = 6.28f; B(2, 2) = 3.0f;\n mat3 C = A * B;\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some matrices\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = mat4::translation(vec3(3, 4, 5));\n mat4 C = A * B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n\n }\n}\n\nTEST(Matrix, Add)\n{\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some matrices\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = mat4::translation(vec3(3, 4, 5));\n mat4 C = A + B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), A(i, j) + B(i, j));\n }\n );\n\n }\n}\n\nTEST(Matrix, Transpose)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat2 B = transpose(A);\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat3 B = transpose(A);\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = transpose(A);\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n}\nRefactoring\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#include \n\n#include \n\nusing namespace visionaray;\n\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ Helper functions\n\/\/\n\n\/\/ nested for loop over matrices --------------------------\n\ntemplate \nvoid for_each_mat2_e(Func f)\n{\n for (int i = 0; i < 2; ++i)\n {\n for (int j = 0; j < 2; ++j)\n {\n f(i, j);\n }\n }\n}\n\ntemplate \nvoid for_each_mat3_e(Func f)\n{\n for (int i = 0; i < 3; ++i)\n {\n for (int j = 0; j < 3; ++j)\n {\n f(i, j);\n }\n }\n}\n\ntemplate \nvoid for_each_mat4_e(Func f)\n{\n for (int i = 0; i < 4; ++i)\n {\n for (int j = 0; j < 4; ++j)\n {\n f(i, j);\n }\n }\n}\n\n\n\/\/ get rows and columns -----------------------------------\n\ntemplate \nvector get_row(matrix const& m, int i)\n{\n assert( i >= 0 && i < 4 );\n\n vector result;\n\n for (size_t d = 0; d < Dim; ++d)\n {\n result[d] = m(i, d);\n }\n\n return result;\n}\n\ntemplate \nvector get_col(matrix const& m, int j)\n{\n assert( j >= 0 && j < 4 );\n\n return m(j);\n}\n\n\nTEST(Matrix, Inverse)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n mat2 I = mat2::identity();\n\n \/\/ make some non-singular matrix\n mat2 A(1, 2, 3, 4);\n mat2 B = inverse(A);\n mat2 C = A * B;\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n mat3 I = mat3::identity();\n\n \/\/ make some non-singular matrix\n mat3 A = mat3::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat3 B = inverse(A);\n mat3 C = A * B;\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n mat4 I = mat4::identity();\n\n \/\/ make some non-singular matrix\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = inverse(A);\n mat4 C = A * B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), I(i, j));\n }\n );\n\n }\n}\n\nTEST(Matrix, Mul)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n \/\/ make some matrices\n mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat2 B = mat2::identity(); B(0, 0) = 11.0f; B(1, 0) = 6.28f; B(1, 1) = 3.0f;\n mat2 C = A * B;\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n \/\/ make some matrices\n mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat3 B = mat3::identity(); B(0, 1) = 11.0f; B(2, 1) = 6.28f; B(2, 2) = 3.0f;\n mat3 C = A * B;\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some matrices\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = mat4::translation(vec3(3, 4, 5));\n mat4 C = A * B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n float d = dot(get_row(A, i), get_col(B, j));\n EXPECT_FLOAT_EQ(C(i, j), d);\n }\n );\n\n }\n}\n\nTEST(Matrix, Add)\n{\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some matrices\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = mat4::translation(vec3(3, 4, 5));\n mat4 C = A + B;\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(C(i, j), A(i, j) + B(i, j));\n }\n );\n\n }\n}\n\nTEST(Matrix, Transpose)\n{\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat2\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat2 A = mat2::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat2 B = transpose(A);\n\n for_each_mat2_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat3\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat3 A = mat3::identity(); A(0, 0) = 2.0f; A(1, 0) = 3.14f; A(1, 1) = 3.0f;\n mat3 B = transpose(A);\n\n for_each_mat3_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n\n\n \/\/-------------------------------------------------------------------------\n \/\/ mat4\n \/\/\n\n {\n\n \/\/ make some non-singular matrix\n mat4 A = mat4::rotation(vec3(1, 0, 0), constants::pi() \/ 4);\n mat4 B = transpose(A);\n\n for_each_mat4_e(\n [&](int i, int j)\n {\n EXPECT_FLOAT_EQ(A(i, j), B(j, i));\n }\n );\n\n }\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of the Groupware\/KOrganizer integration.\n\n Requires the Qt and KDE widget libraries, available at no cost at\n http:\/\/www.trolltech.com and http:\/\/www.kde.org respectively\n\n Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB\n \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston,\n MA 02111-1307, USA.\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"kogroupware.h\"\n#include \"freebusymanager.h\"\n#include \"calendarview.h\"\n#include \"mailscheduler.h\"\n#include \"koprefs.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nFreeBusyManager *KOGroupware::mFreeBusyManager = 0;\n\nKOGroupware *KOGroupware::mInstance = 0;\n\nKOGroupware *KOGroupware::create( CalendarView *view,\n KCal::Calendar *calendar )\n{\n if( !mInstance )\n mInstance = new KOGroupware( view, calendar );\n return mInstance;\n}\n\nKOGroupware *KOGroupware::instance()\n{\n \/\/ Doesn't create, that is the task of create()\n Q_ASSERT( mInstance );\n return mInstance;\n}\n\n\nKOGroupware::KOGroupware( CalendarView* view, KCal::Calendar* calendar )\n : QObject( 0, \"kmgroupware_instance\" )\n{\n mView = view;\n mCalendar = calendar;\n\n \/\/ Set up the dir watch of the three incoming dirs\n KDirWatch* watcher = KDirWatch::self();\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.accepted\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.tentative\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.cancel\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.reply\/\" ) );\n connect( watcher, SIGNAL( dirty( const QString& ) ),\n this, SLOT( incomingDirChanged( const QString& ) ) );\n \/\/ Now set the ball rolling\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.accepted\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.tentative\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.cancel\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.reply\/\" ) );\n}\n\nFreeBusyManager *KOGroupware::freeBusyManager()\n{\n if ( !mFreeBusyManager ) {\n mFreeBusyManager = new FreeBusyManager( this, \"freebusymanager\" );\n mFreeBusyManager->setCalendar( mCalendar );\n connect( mCalendar, SIGNAL( calendarChanged() ),\n mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );\n }\n\n return mFreeBusyManager;\n}\n\nvoid KOGroupware::incomingDirChanged( const QString& path )\n{\n const QString incomingDirName = locateLocal( \"data\",\"korganizer\/\" )\n + \"income.\";\n if ( !path.startsWith( incomingDirName ) ) {\n kdDebug(5850) << \"incomingDirChanged: Wrong dir \" << path << endl;\n return;\n }\n QString action = path.mid( incomingDirName.length() );\n while ( action.length() > 0 && action[ action.length()-1 ] == '\/' )\n \/\/ Strip slashes at the end\n action.truncate( action.length()-1 );\n\n \/\/ Handle accepted invitations\n QDir dir( path );\n QStringList files = dir.entryList( QDir::Files );\n if ( files.count() == 0 )\n \/\/ No more files here\n return;\n\n \/\/ Read the file and remove it\n QFile f( path + \"\/\" + files[0] );\n if (!f.open(IO_ReadOnly)) {\n kdError(5850) << \"Can't open file '\" << files[0] << \"'\" << endl;\n return;\n }\n QTextStream t(&f);\n t.setEncoding( QTextStream::UnicodeUTF8 );\n QString receiver = KPIM::getEmailAddr( t.readLine() );\n QString iCal = t.read();\n\n ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );\n if ( !message ) {\n QString errorMessage;\n if (mFormat.exception())\n errorMessage = \"\\nError message: \" + mFormat.exception()->message();\n kdDebug(5850) << \"MailScheduler::retrieveTransactions() Error parsing\"\n << errorMessage << endl;\n f.close();\n return;\n } else\n f.remove();\n\n KCal::Scheduler::Method method =\n static_cast( message->method() );\n KCal::ScheduleMessage::Status status = message->status();\n KCal::Incidence* incidence =\n dynamic_cast( message->event() );\n KCal::MailScheduler scheduler( mCalendar );\n if ( action.startsWith( \"accepted\" ) ) {\n \/\/ Find myself and set to answered and accepted\n KCal::Attendee::List attendees = incidence->attendees();\n KCal::Attendee::List::ConstIterator it;\n for ( it = attendees.begin(); it != attendees.end(); ++it ) {\n if( (*it)->email() == receiver ) {\n (*it)->setStatus( KCal::Attendee::Accepted );\n (*it)->setRSVP(false);\n break;\n }\n }\n scheduler.acceptTransaction( incidence, method, status );\n } else if ( action.startsWith( \"tentative\" ) ) {\n \/\/ Find myself and set to answered and tentative\n KCal::Attendee::List attendees = incidence->attendees();\n KCal::Attendee::List::ConstIterator it;\n for ( it = attendees.begin(); it != attendees.end(); ++it ) {\n if( (*it)->email() == receiver ) {\n (*it)->setStatus( KCal::Attendee::Tentative );\n (*it)->setRSVP(false);\n break;\n }\n }\n scheduler.acceptTransaction( incidence, method, status );\n } else if ( action.startsWith( \"cancel\" ) )\n \/\/ TODO: Could this be done like the others?\n mCalendar->deleteIncidence( incidence );\n else if ( action.startsWith( \"reply\" ) )\n scheduler.acceptTransaction( incidence, method, status );\n else\n kdError(5850) << \"Unknown incoming action \" << action << endl;\n mView->updateView();\n}\n\n\/* This function sends mails if necessary, and makes sure the user really\n * want to change his calendar.\n *\n * Return true means accept the changes\n * Return false means revert the changes\n *\/\nbool KOGroupware::sendICalMessage( QWidget* parent,\n KCal::Scheduler::Method method,\n Incidence* incidence, bool isDeleting,\n bool statusChanged )\n{\n \/\/ If there are no attendees, don't bother\n if( incidence->attendees().isEmpty() )\n return true;\n\n bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );\n int rc = 0;\n \/*\n * There are two scenarios:\n * o \"we\" are the organizer, where \"we\" means any of the identities or mail\n * addresses known to Kontact\/PIM. If there are attendees, we need to mail\n * them all, even if one or more of them are also \"us\". Otherwise there\n * would be no way to invite a resource or our boss, other identities we\n * also manage.\n * o \"we: are not the organizer, which means we changed the completion status\n * of a todo, or we changed our attendee status from, say, tentative to\n * accepted. In both cases we only mail the organizer. All other changes\n * bring us out of sync with the organizer, so we won't mail, if the user\n * insists on applying them.\n *\/\n\n if ( isOrganizer ) {\n \/* We are the organizer. If there is more than one attendee, or if there is\n * only one, and it's not the same as the organizer, ask the user to send \n * mail. *\/\n if ( incidence->attendees().count() > 1 \n || incidence->attendees().first()->email() != incidence->organizer().email() ) {\n QString type;\n if( incidence->type() == \"Event\") type = i18n(\"event\");\n else if( incidence->type() == \"Todo\" ) type = i18n(\"task\");\n else if( incidence->type() == \"Journal\" ) type = i18n(\"journal entry\");\n else type = incidence->type();\n QString txt = i18n( \"This %1 includes other people. \"\n \"Should email be sent out to the attendees?\" )\n .arg( type );\n rc = KMessageBox::questionYesNoCancel( parent, txt,\n i18n(\"Group scheduling email\") );\n } else {\n return true;\n }\n } else if( incidence->type() == \"Todo\" ) {\n if( method == Scheduler::Request )\n \/\/ This is an update to be sent to the organizer\n method = Scheduler::Reply;\n\n \/\/ Ask if the user wants to tell the organizer about the current status\n QString txt = i18n( \"Do you want to send a status update to the \"\n \"organizer of this task?\");\n rc = KMessageBox::questionYesNo( parent, txt );\n } else if( incidence->type() == \"Event\" ) {\n QString txt;\n if ( statusChanged && method == Scheduler::Request ) {\n txt = i18n( \"Your status as an attendee of this event \"\n \"changed. Do you want to send a status update to the \"\n \"organizer of this event?\" );\n method = Scheduler::Reply;\n rc = KMessageBox::questionYesNo( parent, txt );\n } else {\n if( isDeleting )\n txt = i18n( \"You are not the organizer of this event. \"\n \"Deleting it will bring your calendar out of sync \"\n \"with the organizers calendar. Do you really want \"\n \"to delete it?\" );\n else\n txt = i18n( \"You are not the organizer of this event. \"\n \"Editing it will bring your calendar out of sync \"\n \"with the organizers calendar. Do you really want \"\n \"to edit it?\" );\n rc = KMessageBox::questionYesNo( parent, txt );\n return ( rc == KMessageBox::Yes );\n }\n } else {\n kdWarning(5850) << \"Groupware messages for Journals are not implemented yet!\" << endl;\n return true;\n }\n if( rc == KMessageBox::Yes ) {\n \/\/ We will be sending out a message here. Now make sure there is\n \/\/ some summary\n if( incidence->summary().isEmpty() )\n incidence->setSummary( i18n(\"\") );\n\n \/\/ Send the mail\n KCal::MailScheduler scheduler( mCalendar );\n scheduler.performTransaction( incidence, method );\n\n return true;\n } else if( rc == KMessageBox::No )\n return true;\n else\n return false;\n}\n\n\n#include \"kogroupware.moc\"\nDon't when processing a mail in one of the incoming dirs fails, remove the offending mail, otherwise it will block all following mails. Show an error dialog with a Details button which contains the parse error, if there was one.\/*\n This file is part of the Groupware\/KOrganizer integration.\n\n Requires the Qt and KDE widget libraries, available at no cost at\n http:\/\/www.trolltech.com and http:\/\/www.kde.org respectively\n\n Copyright (c) 2002-2004 Klarälvdalens Datakonsult AB\n \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston,\n MA 02111-1307, USA.\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"kogroupware.h\"\n#include \"freebusymanager.h\"\n#include \"calendarview.h\"\n#include \"mailscheduler.h\"\n#include \"koprefs.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nFreeBusyManager *KOGroupware::mFreeBusyManager = 0;\n\nKOGroupware *KOGroupware::mInstance = 0;\n\nKOGroupware *KOGroupware::create( CalendarView *view,\n KCal::Calendar *calendar )\n{\n if( !mInstance )\n mInstance = new KOGroupware( view, calendar );\n return mInstance;\n}\n\nKOGroupware *KOGroupware::instance()\n{\n \/\/ Doesn't create, that is the task of create()\n Q_ASSERT( mInstance );\n return mInstance;\n}\n\n\nKOGroupware::KOGroupware( CalendarView* view, KCal::Calendar* calendar )\n : QObject( 0, \"kmgroupware_instance\" )\n{\n mView = view;\n mCalendar = calendar;\n\n \/\/ Set up the dir watch of the three incoming dirs\n KDirWatch* watcher = KDirWatch::self();\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.accepted\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.tentative\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.cancel\/\" ) );\n watcher->addDir( locateLocal( \"data\", \"korganizer\/income.reply\/\" ) );\n connect( watcher, SIGNAL( dirty( const QString& ) ),\n this, SLOT( incomingDirChanged( const QString& ) ) );\n \/\/ Now set the ball rolling\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.accepted\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.tentative\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.cancel\/\" ) );\n incomingDirChanged( locateLocal( \"data\", \"korganizer\/income.reply\/\" ) );\n}\n\nFreeBusyManager *KOGroupware::freeBusyManager()\n{\n if ( !mFreeBusyManager ) {\n mFreeBusyManager = new FreeBusyManager( this, \"freebusymanager\" );\n mFreeBusyManager->setCalendar( mCalendar );\n connect( mCalendar, SIGNAL( calendarChanged() ),\n mFreeBusyManager, SLOT( slotPerhapsUploadFB() ) );\n }\n\n return mFreeBusyManager;\n}\n\nvoid KOGroupware::incomingDirChanged( const QString& path )\n{\n const QString incomingDirName = locateLocal( \"data\",\"korganizer\/\" )\n + \"income.\";\n if ( !path.startsWith( incomingDirName ) ) {\n kdDebug(5850) << \"incomingDirChanged: Wrong dir \" << path << endl;\n return;\n }\n QString action = path.mid( incomingDirName.length() );\n while ( action.length() > 0 && action[ action.length()-1 ] == '\/' )\n \/\/ Strip slashes at the end\n action.truncate( action.length()-1 );\n\n \/\/ Handle accepted invitations\n QDir dir( path );\n QStringList files = dir.entryList( QDir::Files );\n if ( files.count() == 0 )\n \/\/ No more files here\n return;\n\n \/\/ Read the file and remove it\n QFile f( path + \"\/\" + files[0] );\n if (!f.open(IO_ReadOnly)) {\n kdError(5850) << \"Can't open file '\" << files[0] << \"'\" << endl;\n return;\n }\n QTextStream t(&f);\n t.setEncoding( QTextStream::UnicodeUTF8 );\n QString receiver = KPIM::getEmailAddr( t.readLine() );\n QString iCal = t.read();\n\n f.remove();\n\n ScheduleMessage *message = mFormat.parseScheduleMessage( mCalendar, iCal );\n if ( !message ) {\n QString errorMessage;\n if (mFormat.exception())\n errorMessage = \"\\nError message: \" + mFormat.exception()->message();\n kdDebug(5850) << \"MailScheduler::retrieveTransactions() Error parsing\"\n << errorMessage << endl;\n KMessageBox::detailedError( mView, \n i18n(\"Error while processing an invitation or update.\"),\n errorMessage );\n return;\n }\n\n KCal::Scheduler::Method method =\n static_cast( message->method() );\n KCal::ScheduleMessage::Status status = message->status();\n KCal::Incidence* incidence =\n dynamic_cast( message->event() );\n KCal::MailScheduler scheduler( mCalendar );\n if ( action.startsWith( \"accepted\" ) ) {\n \/\/ Find myself and set to answered and accepted\n KCal::Attendee::List attendees = incidence->attendees();\n KCal::Attendee::List::ConstIterator it;\n for ( it = attendees.begin(); it != attendees.end(); ++it ) {\n if( (*it)->email() == receiver ) {\n (*it)->setStatus( KCal::Attendee::Accepted );\n (*it)->setRSVP(false);\n break;\n }\n }\n scheduler.acceptTransaction( incidence, method, status );\n } else if ( action.startsWith( \"tentative\" ) ) {\n \/\/ Find myself and set to answered and tentative\n KCal::Attendee::List attendees = incidence->attendees();\n KCal::Attendee::List::ConstIterator it;\n for ( it = attendees.begin(); it != attendees.end(); ++it ) {\n if( (*it)->email() == receiver ) {\n (*it)->setStatus( KCal::Attendee::Tentative );\n (*it)->setRSVP(false);\n break;\n }\n }\n scheduler.acceptTransaction( incidence, method, status );\n } else if ( action.startsWith( \"cancel\" ) )\n \/\/ TODO: Could this be done like the others?\n mCalendar->deleteIncidence( incidence );\n else if ( action.startsWith( \"reply\" ) )\n scheduler.acceptTransaction( incidence, method, status );\n else\n kdError(5850) << \"Unknown incoming action \" << action << endl;\n mView->updateView();\n}\n\n\/* This function sends mails if necessary, and makes sure the user really\n * want to change his calendar.\n *\n * Return true means accept the changes\n * Return false means revert the changes\n *\/\nbool KOGroupware::sendICalMessage( QWidget* parent,\n KCal::Scheduler::Method method,\n Incidence* incidence, bool isDeleting,\n bool statusChanged )\n{\n \/\/ If there are no attendees, don't bother\n if( incidence->attendees().isEmpty() )\n return true;\n\n bool isOrganizer = KOPrefs::instance()->thatIsMe( incidence->organizer().email() );\n int rc = 0;\n \/*\n * There are two scenarios:\n * o \"we\" are the organizer, where \"we\" means any of the identities or mail\n * addresses known to Kontact\/PIM. If there are attendees, we need to mail\n * them all, even if one or more of them are also \"us\". Otherwise there\n * would be no way to invite a resource or our boss, other identities we\n * also manage.\n * o \"we: are not the organizer, which means we changed the completion status\n * of a todo, or we changed our attendee status from, say, tentative to\n * accepted. In both cases we only mail the organizer. All other changes\n * bring us out of sync with the organizer, so we won't mail, if the user\n * insists on applying them.\n *\/\n\n if ( isOrganizer ) {\n \/* We are the organizer. If there is more than one attendee, or if there is\n * only one, and it's not the same as the organizer, ask the user to send \n * mail. *\/\n if ( incidence->attendees().count() > 1 \n || incidence->attendees().first()->email() != incidence->organizer().email() ) {\n QString type;\n if( incidence->type() == \"Event\") type = i18n(\"event\");\n else if( incidence->type() == \"Todo\" ) type = i18n(\"task\");\n else if( incidence->type() == \"Journal\" ) type = i18n(\"journal entry\");\n else type = incidence->type();\n QString txt = i18n( \"This %1 includes other people. \"\n \"Should email be sent out to the attendees?\" )\n .arg( type );\n rc = KMessageBox::questionYesNoCancel( parent, txt,\n i18n(\"Group scheduling email\") );\n } else {\n return true;\n }\n } else if( incidence->type() == \"Todo\" ) {\n if( method == Scheduler::Request )\n \/\/ This is an update to be sent to the organizer\n method = Scheduler::Reply;\n\n \/\/ Ask if the user wants to tell the organizer about the current status\n QString txt = i18n( \"Do you want to send a status update to the \"\n \"organizer of this task?\");\n rc = KMessageBox::questionYesNo( parent, txt );\n } else if( incidence->type() == \"Event\" ) {\n QString txt;\n if ( statusChanged && method == Scheduler::Request ) {\n txt = i18n( \"Your status as an attendee of this event \"\n \"changed. Do you want to send a status update to the \"\n \"organizer of this event?\" );\n method = Scheduler::Reply;\n rc = KMessageBox::questionYesNo( parent, txt );\n } else {\n if( isDeleting )\n txt = i18n( \"You are not the organizer of this event. \"\n \"Deleting it will bring your calendar out of sync \"\n \"with the organizers calendar. Do you really want \"\n \"to delete it?\" );\n else\n txt = i18n( \"You are not the organizer of this event. \"\n \"Editing it will bring your calendar out of sync \"\n \"with the organizers calendar. Do you really want \"\n \"to edit it?\" );\n rc = KMessageBox::questionYesNo( parent, txt );\n return ( rc == KMessageBox::Yes );\n }\n } else {\n kdWarning(5850) << \"Groupware messages for Journals are not implemented yet!\" << endl;\n return true;\n }\n if( rc == KMessageBox::Yes ) {\n \/\/ We will be sending out a message here. Now make sure there is\n \/\/ some summary\n if( incidence->summary().isEmpty() )\n incidence->setSummary( i18n(\"\") );\n\n \/\/ Send the mail\n KCal::MailScheduler scheduler( mCalendar );\n scheduler.performTransaction( incidence, method );\n\n return true;\n } else if( rc == KMessageBox::No )\n return true;\n else\n return false;\n}\n\n\n#include \"kogroupware.moc\"\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \n\n#include \"base\/not_null.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"integrators\/ordinary_differential_equations.hpp\"\n#include \"ksp_plugin\/burn.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"ksp_plugin\/manœuvre.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"physics\/discrete_trajectory.hpp\"\n#include \"physics\/ephemeris.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"serialization\/ksp_plugin.pb.h\"\n\nnamespace principia {\n\nusing base::not_null;\nusing geometry::Instant;\nusing integrators::AdaptiveStepSizeIntegrator;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::Ephemeris;\nusing quantities::Length;\nusing quantities::Mass;\nusing quantities::Speed;\n\nnamespace ksp_plugin {\n\n\/\/ A stack of |Burn|s that manages a chain of trajectories obtained by executing\n\/\/ the corresponding |NavigationManœuvre|s.\nclass FlightPlan {\n public:\n \/\/ Creates a |FlightPlan| with no burns starting at |initial_time| with\n \/\/ |initial_degrees_of_freedom| and with the given |initial_mass|. The\n \/\/ trajectories are computed using the given |integrator| in the given\n \/\/ |ephemeris|.\n FlightPlan(Mass const& initial_mass,\n Instant const& initial_time,\n DegreesOfFreedom const& initial_degrees_of_freedom,\n Instant const& final_time,\n not_null*> const ephemeris,\n Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters);\n\n virtual Instant initial_time() const;\n virtual Instant final_time() const;\n\n virtual int number_of_manœuvres() const;\n \/\/ |index| must be in [0, number_of_manœuvres()[.\n virtual NavigationManœuvre const& GetManœuvre(int const index) const;\n\n \/\/ The following two functions return false and have no effect if the given\n \/\/ |burn| would start before |initial_time_| or before the end of the previous\n \/\/ burn, or end after |final_time_|, or if the integration of the coasting\n \/\/ phase times out or is singular before the burn.\n virtual bool Append(Burn burn);\n\n \/\/ Forgets the flight plan at least before |time|. The actual cutoff time\n \/\/ will be in a coast trajectory and maybe after |time|. |on_empty| is run\n \/\/ if the flight plan would become empty (it is not modified before running\n \/\/ |on_empty|).\n virtual void ForgetBefore(Instant const& time,\n std::function const& on_empty);\n\n\n \/\/ |size()| must be greater than 0.\n virtual void RemoveLast();\n \/\/ |size()| must be greater than 0.\n virtual bool ReplaceLast(Burn burn);\n\n \/\/ Returns false and has no effect if |final_time| is before the end of the\n \/\/ last manœuvre or before |initial_time_|.\n virtual bool SetFinalTime(Instant const& final_time);\n\n virtual Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters() const;\n\n \/\/ Sets the parameters used to compute the trajectories. The trajectories are\n \/\/ recomputed. Returns false (and doesn't change this object) if the\n \/\/ parameters would make it impossible to recompute the trajectories.\n virtual bool SetAdaptiveStepParameters(\n Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters);\n\n \/\/ Returns the number of trajectory segments in this object.\n virtual int number_of_segments() const;\n\n \/\/ |index| must be in [0, number_of_segments()[. Sets the iterators to denote\n \/\/ the given trajectory segment.\n virtual void GetSegment(\n int const index,\n not_null::Iterator*> begin,\n not_null::Iterator*> end) const;\n virtual void GetAllSegments(\n not_null::Iterator*> begin,\n not_null::Iterator*> end) const;\n\n void WriteToMessage(not_null const message) const;\n\n \/\/ This may return a null pointer if the flight plan contained in the\n \/\/ |message| is anomalous.\n static std::unique_ptr ReadFromMessage(\n serialization::FlightPlan const& message,\n not_null*> const root,\n not_null*> const ephemeris);\n\n static std::int64_t constexpr max_ephemeris_steps_per_frame = 1000;\n\n protected:\n \/\/ For mocking.\n FlightPlan();\n\n private:\n \/\/ Appends |manœuvre| to |manœuvres_|, adds a burn and a coast segment.\n \/\/ |manœuvre| must fit between |start_of_last_coast()| and |final_time_|,\n \/\/ the last coast segment must end at |manœuvre.initial_time()|.\n void Append(NavigationManœuvre manœuvre);\n\n \/\/ Recomputes all trajectories in |segments_|. Returns false if the\n \/\/ recomputation resulted in more than 2 anomalous segments.\n bool RecomputeSegments();\n\n \/\/ Flows the last segment for the duration of |manœuvre| using its intrinsic\n \/\/ acceleration.\n void BurnLastSegment(NavigationManœuvre const& manœuvre);\n \/\/ Flows the last segment until |final_time| with no intrinsic acceleration.\n void CoastLastSegment(Instant const& final_time);\n\n \/\/ Replaces the last segment with |segment|. |segment| must be forked from\n \/\/ the same trajectory as the last segment, and at the same time. |segment|\n \/\/ must not be anomalous.\n void ReplaceLastSegment(\n not_null*> const segment);\n\n \/\/ Adds a trajectory to |segments_|, forked at the end of the last one.\n void AddSegment();\n \/\/ Forgets the last segment after its fork.\n void ResetLastSegment();\n\n \/\/ Deletes the last segment and removes it from |segments_|.\n void PopLastSegment();\n\n \/\/ If the integration of a coast from the fork of |coast| until\n \/\/ |manœuvre.initial_time()| reaches the end, returns the integrated\n \/\/ trajectory. Otherwise, returns null.\n DiscreteTrajectory* CoastIfReachesManœuvreInitialTime(\n DiscreteTrajectory& coast,\n NavigationManœuvre const& manœuvre);\n\n Instant start_of_last_coast() const;\n Instant start_of_penultimate_coast() const;\n\n DiscreteTrajectory& last_coast();\n DiscreteTrajectory& penultimate_coast();\n\n Mass const initial_mass_;\n Instant initial_time_;\n DegreesOfFreedom initial_degrees_of_freedom_;\n Instant final_time_;\n \/\/ The root of the flight plan. Contains a single point, not part of\n \/\/ |segments_|. Owns all the |segments_|.\n not_null>> root_;\n \/\/ Never empty; Starts and ends with a coasting segment; coasting and burning\n \/\/ alternate. This simulates a stack. Each segment is a fork of the previous\n \/\/ one.\n std::vector*>> segments_;\n std::vector manœuvres_;\n not_null*> ephemeris_;\n Ephemeris::AdaptiveStepParameters adaptive_step_parameters_;\n \/\/ The last |anomalous_segments_| of |segments_| are anomalous, i.e. they\n \/\/ either end prematurely or follow an anomalous segment; in the latter case\n \/\/ they are empty.\n \/\/ The contract of |Append| and |ReplaceLast| implies that\n \/\/ |anomalous_segments_| is at most 2: the penultimate coast is never\n \/\/ anomalous.\n int anomalous_segments_ = 0;\n};\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\nTypo.\n#pragma once\n\n#include \n\n#include \"base\/not_null.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"integrators\/ordinary_differential_equations.hpp\"\n#include \"ksp_plugin\/burn.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"ksp_plugin\/manœuvre.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"physics\/discrete_trajectory.hpp\"\n#include \"physics\/ephemeris.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"serialization\/ksp_plugin.pb.h\"\n\nnamespace principia {\n\nusing base::not_null;\nusing geometry::Instant;\nusing integrators::AdaptiveStepSizeIntegrator;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::Ephemeris;\nusing quantities::Length;\nusing quantities::Mass;\nusing quantities::Speed;\n\nnamespace ksp_plugin {\n\n\/\/ A stack of |Burn|s that manages a chain of trajectories obtained by executing\n\/\/ the corresponding |NavigationManœuvre|s.\nclass FlightPlan {\n public:\n \/\/ Creates a |FlightPlan| with no burns starting at |initial_time| with\n \/\/ |initial_degrees_of_freedom| and with the given |initial_mass|. The\n \/\/ trajectories are computed using the given |integrator| in the given\n \/\/ |ephemeris|.\n FlightPlan(Mass const& initial_mass,\n Instant const& initial_time,\n DegreesOfFreedom const& initial_degrees_of_freedom,\n Instant const& final_time,\n not_null*> const ephemeris,\n Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters);\n\n virtual Instant initial_time() const;\n virtual Instant final_time() const;\n\n virtual int number_of_manœuvres() const;\n \/\/ |index| must be in [0, number_of_manœuvres()[.\n virtual NavigationManœuvre const& GetManœuvre(int const index) const;\n\n \/\/ The following two functions return false and have no effect if the given\n \/\/ |burn| would start before |initial_time_| or before the end of the previous\n \/\/ burn, or end after |final_time_|, or if the integration of the coasting\n \/\/ phase times out or is singular before the burn.\n virtual bool Append(Burn burn);\n\n \/\/ Forgets the flight plan at least before |time|. The actual cutoff time\n \/\/ will be in a coast trajectory and may be after |time|. |on_empty| is run\n \/\/ if the flight plan would become empty (it is not modified before running\n \/\/ |on_empty|).\n virtual void ForgetBefore(Instant const& time,\n std::function const& on_empty);\n\n\n \/\/ |size()| must be greater than 0.\n virtual void RemoveLast();\n \/\/ |size()| must be greater than 0.\n virtual bool ReplaceLast(Burn burn);\n\n \/\/ Returns false and has no effect if |final_time| is before the end of the\n \/\/ last manœuvre or before |initial_time_|.\n virtual bool SetFinalTime(Instant const& final_time);\n\n virtual Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters() const;\n\n \/\/ Sets the parameters used to compute the trajectories. The trajectories are\n \/\/ recomputed. Returns false (and doesn't change this object) if the\n \/\/ parameters would make it impossible to recompute the trajectories.\n virtual bool SetAdaptiveStepParameters(\n Ephemeris::AdaptiveStepParameters const&\n adaptive_step_parameters);\n\n \/\/ Returns the number of trajectory segments in this object.\n virtual int number_of_segments() const;\n\n \/\/ |index| must be in [0, number_of_segments()[. Sets the iterators to denote\n \/\/ the given trajectory segment.\n virtual void GetSegment(\n int const index,\n not_null::Iterator*> begin,\n not_null::Iterator*> end) const;\n virtual void GetAllSegments(\n not_null::Iterator*> begin,\n not_null::Iterator*> end) const;\n\n void WriteToMessage(not_null const message) const;\n\n \/\/ This may return a null pointer if the flight plan contained in the\n \/\/ |message| is anomalous.\n static std::unique_ptr ReadFromMessage(\n serialization::FlightPlan const& message,\n not_null*> const root,\n not_null*> const ephemeris);\n\n static std::int64_t constexpr max_ephemeris_steps_per_frame = 1000;\n\n protected:\n \/\/ For mocking.\n FlightPlan();\n\n private:\n \/\/ Appends |manœuvre| to |manœuvres_|, adds a burn and a coast segment.\n \/\/ |manœuvre| must fit between |start_of_last_coast()| and |final_time_|,\n \/\/ the last coast segment must end at |manœuvre.initial_time()|.\n void Append(NavigationManœuvre manœuvre);\n\n \/\/ Recomputes all trajectories in |segments_|. Returns false if the\n \/\/ recomputation resulted in more than 2 anomalous segments.\n bool RecomputeSegments();\n\n \/\/ Flows the last segment for the duration of |manœuvre| using its intrinsic\n \/\/ acceleration.\n void BurnLastSegment(NavigationManœuvre const& manœuvre);\n \/\/ Flows the last segment until |final_time| with no intrinsic acceleration.\n void CoastLastSegment(Instant const& final_time);\n\n \/\/ Replaces the last segment with |segment|. |segment| must be forked from\n \/\/ the same trajectory as the last segment, and at the same time. |segment|\n \/\/ must not be anomalous.\n void ReplaceLastSegment(\n not_null*> const segment);\n\n \/\/ Adds a trajectory to |segments_|, forked at the end of the last one.\n void AddSegment();\n \/\/ Forgets the last segment after its fork.\n void ResetLastSegment();\n\n \/\/ Deletes the last segment and removes it from |segments_|.\n void PopLastSegment();\n\n \/\/ If the integration of a coast from the fork of |coast| until\n \/\/ |manœuvre.initial_time()| reaches the end, returns the integrated\n \/\/ trajectory. Otherwise, returns null.\n DiscreteTrajectory* CoastIfReachesManœuvreInitialTime(\n DiscreteTrajectory& coast,\n NavigationManœuvre const& manœuvre);\n\n Instant start_of_last_coast() const;\n Instant start_of_penultimate_coast() const;\n\n DiscreteTrajectory& last_coast();\n DiscreteTrajectory& penultimate_coast();\n\n Mass const initial_mass_;\n Instant initial_time_;\n DegreesOfFreedom initial_degrees_of_freedom_;\n Instant final_time_;\n \/\/ The root of the flight plan. Contains a single point, not part of\n \/\/ |segments_|. Owns all the |segments_|.\n not_null>> root_;\n \/\/ Never empty; Starts and ends with a coasting segment; coasting and burning\n \/\/ alternate. This simulates a stack. Each segment is a fork of the previous\n \/\/ one.\n std::vector*>> segments_;\n std::vector manœuvres_;\n not_null*> ephemeris_;\n Ephemeris::AdaptiveStepParameters adaptive_step_parameters_;\n \/\/ The last |anomalous_segments_| of |segments_| are anomalous, i.e. they\n \/\/ either end prematurely or follow an anomalous segment; in the latter case\n \/\/ they are empty.\n \/\/ The contract of |Append| and |ReplaceLast| implies that\n \/\/ |anomalous_segments_| is at most 2: the penultimate coast is never\n \/\/ anomalous.\n int anomalous_segments_ = 0;\n};\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"base\/not_null.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"geometry\/orthogonal_map.hpp\"\n#include \"geometry\/perspective.hpp\"\n#include \"geometry\/rp2_point.hpp\"\n#include \"geometry\/sphere.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"physics\/discrete_trajectory.hpp\"\n#include \"physics\/rigid_motion.hpp\"\n#include \"physics\/trajectory.hpp\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_planetarium {\n\nusing base::not_null;\nusing geometry::Instant;\nusing geometry::OrthogonalMap;\nusing geometry::Perspective;\nusing geometry::RP2Point;\nusing geometry::Sphere;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::RigidMotion;\nusing physics::Trajectory;\nusing quantities::Length;\n\n\/\/ A planetarium is a system of spheres together with a perspective. In this\n\/\/ setting it is possible to draw trajectories in the projective plane.\nclass Planetarium final {\n public:\n \/\/ TODO(phl): All this Navigation is weird. Should it be named Plotting?\n \/\/ In particular Navigration vs. NavigationFrame is a mess.\n \/\/ TODO(phl): Maybe replace the spheres with an ephemeris.\n Planetarium(std::vector> const& spheres,\n Perspective const&\n perspective,\n not_null plotting_frame);\n\n \/\/ A no-op method that just returns all the points in the |trajectory|.\n std::vector> PlotMethod0(\n DiscreteTrajectory const& trajectory,\n Instant const& now) const;\n\n \/\/ A nave method that doesn't pay any attention to the perspective but tries\n \/\/ to ensure that the points before the perspective are separated by less than\n \/\/ |tolerance|.\n std::vector> PlotMethod1(\n Trajectory const& trajectory,\n Instant const& now,\n Length const& tolerance) const;\n\n private:\n std::vector> ComputePlottableSpheres(\n Instant const& now) const;\n\n void AppendRP2PointIfNeeded(\n Instant const& t,\n DegreesOfFreedom const& barycentric_degrees_of_freedom,\n std::vector> const& plottable_spheres,\n std::vector>& rp2_points) const;\n\n std::vector> const spheres_;\n Perspective const\n perspective_;\n not_null const plotting_frame_;\n};\n\n} \/\/ namespace internal_planetarium\n\nusing internal_planetarium::Planetarium;\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\nReadying.\n#pragma once\n\n#include \"base\/not_null.hpp\"\n#include \"geometry\/named_quantities.hpp\"\n#include \"geometry\/orthogonal_map.hpp\"\n#include \"geometry\/perspective.hpp\"\n#include \"geometry\/rp2_point.hpp\"\n#include \"geometry\/sphere.hpp\"\n#include \"ksp_plugin\/frames.hpp\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"physics\/discrete_trajectory.hpp\"\n#include \"physics\/rigid_motion.hpp\"\n#include \"physics\/trajectory.hpp\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_planetarium {\n\nusing base::not_null;\nusing geometry::Instant;\nusing geometry::OrthogonalMap;\nusing geometry::Perspective;\nusing geometry::RP2Point;\nusing geometry::Sphere;\nusing physics::DegreesOfFreedom;\nusing physics::DiscreteTrajectory;\nusing physics::RigidMotion;\nusing physics::Trajectory;\nusing quantities::Length;\n\n\/\/ A planetarium is a system of spheres together with a perspective. In this\n\/\/ setting it is possible to draw trajectories in the projective plane.\nclass Planetarium final {\n public:\n \/\/ TODO(phl): All this Navigation is weird. Should it be named Plotting?\n \/\/ In particular Navigration vs. NavigationFrame is a mess.\n \/\/ TODO(phl): Maybe replace the spheres with an ephemeris.\n Planetarium(std::vector> const& spheres,\n Perspective const&\n perspective,\n not_null plotting_frame);\n\n \/\/ A no-op method that just returns all the points in the |trajectory|.\n std::vector> PlotMethod0(\n DiscreteTrajectory const& trajectory,\n Instant const& now) const;\n\n \/\/ A nave method that doesn't pay any attention to the perspective but tries\n \/\/ to ensure that the points before the perspective are separated by less than\n \/\/ |tolerance|.\n std::vector> PlotMethod1(\n Trajectory const& trajectory,\n Instant const& now,\n Length const& tolerance) const;\n\n private:\n \/\/ Computes the coordinates of the |spheres_| in the |plotting_frame_| at time\n \/\/ |now|.\n std::vector> ComputePlottableSpheres(\n Instant const& now) const;\n\n \/\/ Appends to |rp2_points| a point corresponding to the\n \/\/ |barycentric_degrees_of_freedom| transformed in the |plotting_frame_| at\n \/\/ time |t|, but only if that point is not hidden by a sphere.\n void AppendRP2PointIfNeeded(\n Instant const& t,\n DegreesOfFreedom const& barycentric_degrees_of_freedom,\n std::vector> const& plottable_spheres,\n std::vector>& rp2_points) const;\n\n std::vector> const spheres_;\n Perspective const\n perspective_;\n not_null const plotting_frame_;\n};\n\n} \/\/ namespace internal_planetarium\n\nusing internal_planetarium::Planetarium;\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 The libmumble Developers\n\/\/ The use of this source code is goverened by a BSD-style\n\/\/ license that can be found in the LICENSE-file.\n\n#include \n#include \"X509Verifier_win.h\"\n#include \"X509HostnameVerifier.h\"\n#include \n#include \"X509Certificate_p.h\"\n#include \"OpenSSLUtils.h\"\n\n#include \n#include \n\n#define WIN32_LEAN_AND_MEAN\n#include \n#include \n\n#include \"uv.h\"\n\nnamespace mumble {\n\nstatic uv_once_t system_verifier_once_ = UV_ONCE_INIT;\nstatic X509Verifier *system_verifier_ptr_;\n\nvoid X509VerifierPrivate::InitializeSystemVerifier() {\n\tOpenSSLUtils::EnsureInitialized();\n\tsystem_verifier_ptr_ = new X509Verifier;\n}\n\nX509Verifier &X509Verifier::SystemVerifier() {\n\tuv_once(&system_verifier_once_, X509VerifierPrivate::InitializeSystemVerifier);\n\treturn *system_verifier_ptr_;\n}\n\nX509Verifier::X509Verifier() : dptr_(new X509VerifierPrivate) {\n}\n\nX509Verifier::~X509Verifier() {\n}\n\nbool X509Verifier::VerifyChain(std::vector chain, const mumble::X509VerifierOptions &opts) {\n\treturn dptr_->VerifyChain(chain, opts);\n}\n\nX509VerifierPrivate::X509VerifierPrivate() {\n}\n\n\/\/ AddCertToStore creates a CERT_CONTEXT of the certificate passed in as cert and adds it to the certificate store represented\n\/\/ by store. If ctx_out points to a non-nullptr CERT_CONTEXT, ctx_out will be updated to point to a copy of the CERT_CONTEXT that\n\/\/ is added to store.\nbool X509VerifierPrivate::AddCertToStore(HCERTSTORE store, const X509Certificate &cert, const CERT_CONTEXT **ctx_out) const {\n\tconst ByteArray &buf = cert.dptr_->cert_der_;\n\tconst CERT_CONTEXT *ctx = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, reinterpret_cast(buf.ConstData()), buf.Length());\n\tif (ctx == nullptr) {\n\t\treturn false;\n\t}\n\n\tbool ok = CertAddCertificateContextToStore(store, ctx, CERT_STORE_ADD_ALWAYS, ctx_out);\n\tif (!ok) {\n\t\tCertFreeCertificateContext(ctx);\n\t\treturn false;\n\t}\n\n\tCertFreeCertificateContext(ctx);\n\treturn true;\n}\n\n\/\/ CreateCertContextFromChain creates a CERT_CONTEXT representing the leaf certificate (index 0 of the chain)\r\n\/\/ in an in-memory certificate store which will also contains any intermediate certificates found in the chain.\r\n\/\/\r\n\/\/ While the method returns a CERT_CONTEXT that represents the leaf certificate, this CERT_CONTEXT contains a pointer\r\n\/\/ to the in-memory store that holds the whole certificate chain. This store can be accessed via the hCertStore field\r\n\/\/ of the returned CERT_CONTEXT. The store is automatically closed when the CERT_CONTEXT that this function returns\r\n\/\/ is freed using CertFreeCertificateContext (it holds the only reference to the store).\nconst CERT_CONTEXT *X509VerifierPrivate::CreateCertContextFromChain(const std::vector &chain) const {\n\tconst CERT_CONTEXT *store_ctx = nullptr;\n\n\tHCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, nullptr);\n\tif (store == nullptr) {\n\t\tgoto err;\n\t}\n\n\tif (!this->AddCertToStore(store, chain.at(0), &store_ctx)) {\n\t\tgoto err;\n\t}\n\n\tfor (int i = 1; i < chain.size(); i++) {\n\t\tif (!this->AddCertToStore(store, chain.at(i))) {\n\t\t\tgoto err;\n\t\t}\n\t}\n\n\treturn store_ctx;\n\nerr:\n\tif (store != nullptr) {\n\t\tCertCloseStore(store, 0);\n\t}\n\tif (store_ctx != nullptr) {\n\t\tCertFreeCertificateContext(store_ctx);\n\t}\n\treturn nullptr;\n}\n\n\/\/ FileTimeForStdTimeT converts a std::time_t to a FILETIME.\nFILETIME X509VerifierPrivate::FileTimeFromStdTimeT(std::time_t time) const {\n\tFILETIME ft;\n\tULARGE_INTEGER lint;\n\n\t\/\/ 1 Jan 1601 00:00:00 UTC is -11644473600 in Unix epoch representation.\n\tconst ULONGLONG epoch_1601 = 11644473600ULL;\n\t\/\/ Factor that converts from 1 sec (Unix epoch) increments to 100 nsec (FILETIME) increments.\n\tconst ULONGLONG secs_to_100ns = 10000000ULL;\n\n\tlint.QuadPart = (epoch_1601 + time) * secs_to_100ns;\n\tft.dwLowDateTime = lint.LowPart;\n\tft.dwHighDateTime = lint.HighPart;\n\n\treturn ft;\n}\n\n\/\/ UTF16StringFromStdString converts a UTF-8 encoded std::string to a UTF-16 WCHAR *.\n\/\/ The returned pointer must be freed with free().\nWCHAR *X509VerifierPrivate::UTF16StringFromStdString(const std::string &str) const {\n\tWCHAR *buf;\n\tint sz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), -1, nullptr, 0);\n\tif (sz == 0) {\n\t\treturn nullptr;\n\t}\n\n\tbuf = reinterpret_cast(malloc(sz*sizeof(WCHAR)));\n\tsz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), -1, buf, sz);\n\tif (sz == 0) {\n\t\treturn nullptr;\n\t}\n\n\treturn buf;\n}\n\n\/\/ VerifyChain verifies the certificate chain in chain\n\/\/ according to the verification options given as opts.\nbool X509VerifierPrivate::VerifyChain(std::vector chain, const X509VerifierOptions &opts) {\n\tbool status = false;\n\tFILETIME verify_time;\n\tWCHAR *wide_dns_name = nullptr;\n\n\tif (chain.empty()) {\n\t\tgoto out;\n\t}\n\n\tconst CERT_CONTEXT *store_ctx = this->CreateCertContextFromChain(chain);\n\tif (store_ctx == nullptr) {\n\t\tgoto out;\n\t}\n\n\tCERT_CHAIN_PARA para;\n\tmemset(¶, 0, sizeof(para));\n\tpara.cbSize = sizeof(CERT_CHAIN_PARA);\n\n\tLPSTR ssl_oids[] = {\n\t\tszOID_PKIX_KP_SERVER_AUTH,\n\t\tszOID_SERVER_GATED_CRYPTO,\n\t\tszOID_SGC_NETSCAPE,\n\t};\n\n\tif (!opts.dns_name.empty()) {\n\t\tpara.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;\n\t\tpara.RequestedUsage.Usage.cUsageIdentifier = sizeof(ssl_oids)\/sizeof(ssl_oids[0]);\n\t\tpara.RequestedUsage.Usage.rgpszUsageIdentifier = ssl_oids;\n\t} else {\n\t\tpara.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;\n\t\tpara.RequestedUsage.Usage.cUsageIdentifier = 0;\n\t\tpara.RequestedUsage.Usage.rgpszUsageIdentifier = nullptr;\n\t}\n\n\tconst CERT_CHAIN_CONTEXT *chain_ctx = nullptr;\n\tverify_time = this->FileTimeFromStdTimeT(opts.time);\n\tbool ok = CertGetCertificateChain(nullptr, store_ctx, (opts.time != 0) ? &verify_time : nullptr, store_ctx->hCertStore, ¶, 0, nullptr, &chain_ctx);\n\tif (!ok) {\n\t\tgoto out;\n\t}\n\n\tif (chain_ctx->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {\n\t\tgoto out;\n\t}\n\n\tif (!opts.dns_name.empty()) {\n\t\twide_dns_name = this->UTF16StringFromStdString(opts.dns_name);\n\n\t\tSSL_EXTRA_CERT_CHAIN_POLICY_PARA sslpara;\n\t\tmemset(&sslpara, 0, sizeof(sslpara));\n\t\tsslpara.cbSize = sizeof(sslpara);\n\t\tsslpara.dwAuthType = AUTHTYPE_SERVER;\n\t\tsslpara.pwszServerName = wide_dns_name;\n\n\t\tCERT_CHAIN_POLICY_PARA chainpara;\n\t\tmemset(&chainpara, 0, sizeof(chainpara));\n\t\tchainpara.pvExtraPolicyPara = &sslpara;\n\t\tchainpara.dwFlags = 0;\n\t\tchainpara.cbSize = sizeof(chainpara);\n\n\t\tCERT_CHAIN_POLICY_STATUS chain_status;\n\t\tmemset(&chain_status, 0, sizeof(chain_status));\n\t\tok = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_ctx, &chainpara, &chain_status);\n\t\tif (!ok) {\n\t\t\tgoto out;\n\t\t}\n\t\tif (chain_status.dwError == 0) {\n\t\t\tstatus = true;\n\t\t}\n\t} else {\n\t\tstatus = true;\n\t}\n\nout:\n\tif (store_ctx != nullptr) {\n\t\tCertFreeCertificateContext(store_ctx);\n\t}\n\tif (chain_ctx != nullptr) {\n\t\tCertFreeCertificateChain(chain_ctx);\n\t}\n\tif (wide_dns_name != nullptr) {\n\t\tfree(wide_dns_name);\n\t}\n\treturn status;\n}\n\n}\nX509Verifier_win: fix access of uninitialized local vars in VerifyChain.\/\/ Copyright (c) 2013 The libmumble Developers\n\/\/ The use of this source code is goverened by a BSD-style\n\/\/ license that can be found in the LICENSE-file.\n\n#include \n#include \"X509Verifier_win.h\"\n#include \"X509HostnameVerifier.h\"\n#include \n#include \"X509Certificate_p.h\"\n#include \"OpenSSLUtils.h\"\n\n#include \n#include \n\n#define WIN32_LEAN_AND_MEAN\n#include \n#include \n\n#include \"uv.h\"\n\nnamespace mumble {\n\nstatic uv_once_t system_verifier_once_ = UV_ONCE_INIT;\nstatic X509Verifier *system_verifier_ptr_;\n\nvoid X509VerifierPrivate::InitializeSystemVerifier() {\n\tOpenSSLUtils::EnsureInitialized();\n\tsystem_verifier_ptr_ = new X509Verifier;\n}\n\nX509Verifier &X509Verifier::SystemVerifier() {\n\tuv_once(&system_verifier_once_, X509VerifierPrivate::InitializeSystemVerifier);\n\treturn *system_verifier_ptr_;\n}\n\nX509Verifier::X509Verifier() : dptr_(new X509VerifierPrivate) {\n}\n\nX509Verifier::~X509Verifier() {\n}\n\nbool X509Verifier::VerifyChain(std::vector chain, const mumble::X509VerifierOptions &opts) {\n\treturn dptr_->VerifyChain(chain, opts);\n}\n\nX509VerifierPrivate::X509VerifierPrivate() {\n}\n\n\/\/ AddCertToStore creates a CERT_CONTEXT of the certificate passed in as cert and adds it to the certificate store represented\n\/\/ by store. If ctx_out points to a non-nullptr CERT_CONTEXT, ctx_out will be updated to point to a copy of the CERT_CONTEXT that\n\/\/ is added to store.\nbool X509VerifierPrivate::AddCertToStore(HCERTSTORE store, const X509Certificate &cert, const CERT_CONTEXT **ctx_out) const {\n\tconst ByteArray &buf = cert.dptr_->cert_der_;\n\tconst CERT_CONTEXT *ctx = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, reinterpret_cast(buf.ConstData()), buf.Length());\n\tif (ctx == nullptr) {\n\t\treturn false;\n\t}\n\n\tbool ok = CertAddCertificateContextToStore(store, ctx, CERT_STORE_ADD_ALWAYS, ctx_out);\n\tif (!ok) {\n\t\tCertFreeCertificateContext(ctx);\n\t\treturn false;\n\t}\n\n\tCertFreeCertificateContext(ctx);\n\treturn true;\n}\n\n\/\/ CreateCertContextFromChain creates a CERT_CONTEXT representing the leaf certificate (index 0 of the chain)\r\n\/\/ in an in-memory certificate store which will also contains any intermediate certificates found in the chain.\r\n\/\/\r\n\/\/ While the method returns a CERT_CONTEXT that represents the leaf certificate, this CERT_CONTEXT contains a pointer\r\n\/\/ to the in-memory store that holds the whole certificate chain. This store can be accessed via the hCertStore field\r\n\/\/ of the returned CERT_CONTEXT. The store is automatically closed when the CERT_CONTEXT that this function returns\r\n\/\/ is freed using CertFreeCertificateContext (it holds the only reference to the store).\nconst CERT_CONTEXT *X509VerifierPrivate::CreateCertContextFromChain(const std::vector &chain) const {\n\tconst CERT_CONTEXT *store_ctx = nullptr;\n\n\tHCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, nullptr);\n\tif (store == nullptr) {\n\t\tgoto err;\n\t}\n\n\tif (!this->AddCertToStore(store, chain.at(0), &store_ctx)) {\n\t\tgoto err;\n\t}\n\n\tfor (int i = 1; i < chain.size(); i++) {\n\t\tif (!this->AddCertToStore(store, chain.at(i))) {\n\t\t\tgoto err;\n\t\t}\n\t}\n\n\treturn store_ctx;\n\nerr:\n\tif (store != nullptr) {\n\t\tCertCloseStore(store, 0);\n\t}\n\tif (store_ctx != nullptr) {\n\t\tCertFreeCertificateContext(store_ctx);\n\t}\n\treturn nullptr;\n}\n\n\/\/ FileTimeForStdTimeT converts a std::time_t to a FILETIME.\nFILETIME X509VerifierPrivate::FileTimeFromStdTimeT(std::time_t time) const {\n\tFILETIME ft;\n\tULARGE_INTEGER lint;\n\n\t\/\/ 1 Jan 1601 00:00:00 UTC is -11644473600 in Unix epoch representation.\n\tconst ULONGLONG epoch_1601 = 11644473600ULL;\n\t\/\/ Factor that converts from 1 sec (Unix epoch) increments to 100 nsec (FILETIME) increments.\n\tconst ULONGLONG secs_to_100ns = 10000000ULL;\n\n\tlint.QuadPart = (epoch_1601 + time) * secs_to_100ns;\n\tft.dwLowDateTime = lint.LowPart;\n\tft.dwHighDateTime = lint.HighPart;\n\n\treturn ft;\n}\n\n\/\/ UTF16StringFromStdString converts a UTF-8 encoded std::string to a UTF-16 WCHAR *.\n\/\/ The returned pointer must be freed with free().\nWCHAR *X509VerifierPrivate::UTF16StringFromStdString(const std::string &str) const {\n\tWCHAR *buf;\n\tint sz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), -1, nullptr, 0);\n\tif (sz == 0) {\n\t\treturn nullptr;\n\t}\n\n\tbuf = reinterpret_cast(malloc(sz*sizeof(WCHAR)));\n\tsz = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.c_str(), -1, buf, sz);\n\tif (sz == 0) {\n\t\treturn nullptr;\n\t}\n\n\treturn buf;\n}\n\n\/\/ VerifyChain verifies the certificate chain in chain\n\/\/ according to the verification options given as opts.\nbool X509VerifierPrivate::VerifyChain(std::vector chain, const X509VerifierOptions &opts) {\n\tconst CERT_CHAIN_CONTEXT *chain_ctx = nullptr;\n\tconst CERT_CONTEXT *store_ctx = nullptr;\n\tWCHAR *wide_dns_name = nullptr;\n\tFILETIME verify_time;\n\tbool status = false;\n\n\tif (chain.empty()) {\n\t\tgoto out;\n\t}\n\n\tstore_ctx = this->CreateCertContextFromChain(chain);\n\tif (store_ctx == nullptr) {\n\t\tgoto out;\n\t}\n\n\tCERT_CHAIN_PARA para;\n\tmemset(¶, 0, sizeof(para));\n\tpara.cbSize = sizeof(CERT_CHAIN_PARA);\n\n\tLPSTR ssl_oids[] = {\n\t\tszOID_PKIX_KP_SERVER_AUTH,\n\t\tszOID_SERVER_GATED_CRYPTO,\n\t\tszOID_SGC_NETSCAPE,\n\t};\n\n\tif (!opts.dns_name.empty()) {\n\t\tpara.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;\n\t\tpara.RequestedUsage.Usage.cUsageIdentifier = sizeof(ssl_oids)\/sizeof(ssl_oids[0]);\n\t\tpara.RequestedUsage.Usage.rgpszUsageIdentifier = ssl_oids;\n\t} else {\n\t\tpara.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND;\n\t\tpara.RequestedUsage.Usage.cUsageIdentifier = 0;\n\t\tpara.RequestedUsage.Usage.rgpszUsageIdentifier = nullptr;\n\t}\n\n\tverify_time = this->FileTimeFromStdTimeT(opts.time);\n\tbool ok = CertGetCertificateChain(nullptr, store_ctx, (opts.time != 0) ? &verify_time : nullptr, store_ctx->hCertStore, ¶, 0, nullptr, &chain_ctx);\n\tif (!ok) {\n\t\tgoto out;\n\t}\n\n\tif (chain_ctx->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {\n\t\tgoto out;\n\t}\n\n\tif (!opts.dns_name.empty()) {\n\t\twide_dns_name = this->UTF16StringFromStdString(opts.dns_name);\n\n\t\tSSL_EXTRA_CERT_CHAIN_POLICY_PARA sslpara;\n\t\tmemset(&sslpara, 0, sizeof(sslpara));\n\t\tsslpara.cbSize = sizeof(sslpara);\n\t\tsslpara.dwAuthType = AUTHTYPE_SERVER;\n\t\tsslpara.pwszServerName = wide_dns_name;\n\n\t\tCERT_CHAIN_POLICY_PARA chainpara;\n\t\tmemset(&chainpara, 0, sizeof(chainpara));\n\t\tchainpara.pvExtraPolicyPara = &sslpara;\n\t\tchainpara.dwFlags = 0;\n\t\tchainpara.cbSize = sizeof(chainpara);\n\n\t\tCERT_CHAIN_POLICY_STATUS chain_status;\n\t\tmemset(&chain_status, 0, sizeof(chain_status));\n\t\tok = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_ctx, &chainpara, &chain_status);\n\t\tif (!ok) {\n\t\t\tgoto out;\n\t\t}\n\t\tif (chain_status.dwError == 0) {\n\t\t\tstatus = true;\n\t\t}\n\t} else {\n\t\tstatus = true;\n\t}\n\nout:\n\tif (store_ctx != nullptr) {\n\t\tCertFreeCertificateContext(store_ctx);\n\t}\n\tif (chain_ctx != nullptr) {\n\t\tCertFreeCertificateChain(chain_ctx);\n\t}\n\tif (wide_dns_name != nullptr) {\n\t\tfree(wide_dns_name);\n\t}\n\treturn status;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * main.cpp\n * Program: kalarm\n * Copyright © 2001-2007 by David Jarvie \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kalarmapp.h\"\n\n#define PROGRAM_NAME \"kalarm\"\n\nstatic KCmdLineOptions options[] =\n{\n\t{ \"a\", 0, 0 },\n\t{ \"ack-confirm\", I18N_NOOP(\"Prompt for confirmation when alarm is acknowledged\"), 0 },\n\t{ \"A\", 0, 0 },\n\t{ \"attach \", I18N_NOOP(\"Attach file to email (repeat as needed)\"), 0 },\n\t{ \"auto-close\", I18N_NOOP(\"Auto-close alarm window after --late-cancel period\"), 0 },\n\t{ \"bcc\", I18N_NOOP(\"Blind copy email to self\"), 0 },\n\t{ \"b\", 0, 0 },\n\t{ \"beep\", I18N_NOOP(\"Beep when message is displayed\"), 0 },\n\t{ \"colour\", 0, 0 },\n\t{ \"c\", 0, 0 },\n\t{ \"color \", I18N_NOOP(\"Message background color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"colourfg\", 0, 0 },\n\t{ \"C\", 0, 0 },\n\t{ \"colorfg \", I18N_NOOP(\"Message foreground color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"calendarURL \", I18N_NOOP(\"URL of calendar file\"), 0 },\n\t{ \"cancelEvent \", I18N_NOOP(\"Cancel alarm with the specified event ID\"), 0 },\n\t{ \"d\", 0, 0 },\n\t{ \"disable\", I18N_NOOP(\"Disable the alarm\"), 0 },\n\t{ \"e\", 0, 0 },\n\t{ \"!exec \", I18N_NOOP(\"Execute a shell command line\"), 0 },\n\t{ \"edit \", I18N_NOOP(\"Display the alarm edit dialog to edit the specified alarm\"), 0 },\n\t{ \"n\", 0, 0 },\n\t{ \"edit-new\", I18N_NOOP(\"Display the alarm edit dialog to edit a new alarm\"), 0 },\n\t{ \"edit-new-preset \", I18N_NOOP(\"Display the alarm edit dialog, preset with a template\"), 0 },\n\t{ \"f\", 0, 0 },\n\t{ \"file \", I18N_NOOP(\"File to display\"), 0 },\n\t{ \"F\", 0, 0 },\n\t{ \"from-id \", I18N_NOOP(\"KMail identity to use as sender of email\"), 0 },\n\t{ \"handleEvent \", I18N_NOOP(\"Trigger or cancel alarm with the specified event ID\"), 0 },\n\t{ \"i\", 0, 0 },\n\t{ \"interval \", I18N_NOOP(\"Interval between alarm repetitions\"), 0 },\n\t{ \"k\", 0, 0 },\n\t{ \"korganizer\", I18N_NOOP(\"Show alarm as an event in KOrganizer\"), 0 },\n\t{ \"l\", 0, 0 },\n\t{ \"late-cancel \", I18N_NOOP(\"Cancel alarm if more than 'period' late when triggered\"), \"1\" },\n\t{ \"L\", 0, 0 },\n\t{ \"login\", I18N_NOOP(\"Repeat alarm at every login\"), 0 },\n\t{ \"m\", 0, 0 },\n\t{ \"mail
\", I18N_NOOP(\"Send an email to the given address (repeat as needed)\"), 0 },\n\t{ \"p\", 0, 0 },\n\t{ \"play \", I18N_NOOP(\"Audio file to play once\"), 0 },\n#ifndef WITHOUT_ARTS\n\t{ \"P\", 0, 0 },\n\t{ \"play-repeat \", I18N_NOOP(\"Audio file to play repeatedly\"), 0 },\n#endif\n\t{ \"recurrence \", I18N_NOOP(\"Specify alarm recurrence using iCalendar syntax\"), 0 },\n\t{ \"R\", 0, 0 },\n\t{ \"reminder \", I18N_NOOP(\"Display reminder in advance of alarm\"), 0 },\n\t{ \"reminder-once \", I18N_NOOP(\"Display reminder once, before first alarm recurrence\"), 0 },\n\t{ \"r\", 0, 0 },\n\t{ \"repeat \", I18N_NOOP(\"Number of times to repeat alarm (including initial occasion)\"), 0 },\n\t{ \"reset\", I18N_NOOP(\"Reset the alarm scheduling daemon\"), 0 },\n\t{ \"s\", 0, 0 },\n\t{ \"speak\", I18N_NOOP(\"Speak the message when it is displayed\"), 0 },\n\t{ \"stop\", I18N_NOOP(\"Stop the alarm scheduling daemon\"), 0 },\n\t{ \"S\", 0, 0 },\n\t{ \"subject\", I18N_NOOP(\"Email subject line\"), 0 },\n\t{ \"t\", 0, 0 },\n\t{ \"time