commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
c54f98634e9ca8e2a8fd57b028160261f8102bc6
src/tests/TestHelpers.cpp
src/tests/TestHelpers.cpp
#include "catch.hpp" #include "../Config.h" #include "../ProgramOptions.h" TEST_CASE( "parseColor") { REQUIRE((helpers::parseColor("0,0,0") == Config::Color{0, 0, 0})); REQUIRE((helpers::parseColor("255,255,255") == Config::Color{255, 255, 255})); REQUIRE((helpers::parseColor(" 255 , 255 , 255 ") == Config::Color{255, 255, 255})); REQUIRE_THROWS_AS(helpers::parseColor(""), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("foo"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,2,3"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,a,1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,256"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,-1"), std::logic_error); } TEST_CASE("parseCharsString") { REQUIRE((helpers::parseCharsString("") == std::set<uint32_t>{})); REQUIRE((helpers::parseCharsString("0") == std::set<uint32_t>{0})); REQUIRE((helpers::parseCharsString("42") == std::set<uint32_t>{42})); REQUIRE((helpers::parseCharsString("0-1") == std::set<uint32_t>{0,1})); REQUIRE((helpers::parseCharsString("1-3") == std::set<uint32_t>{1,2,3})); REQUIRE((helpers::parseCharsString(" 1 - 3 ") == std::set<uint32_t>{1,2,3})); REQUIRE_THROWS_AS(helpers::parseCharsString("foo"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseCharsString("-1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseCharsString("-1-2"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseCharsString("1-2 3"), std::logic_error); }
#include "catch.hpp" #include "../Config.h" #include "../ProgramOptions.h" TEST_CASE( "parseColor") { REQUIRE((helpers::parseColor("0,0,0") == Config::Color{0, 0, 0})); REQUIRE((helpers::parseColor("255,255,255") == Config::Color{255, 255, 255})); REQUIRE((helpers::parseColor(" 255 , 255 , 255 ") == Config::Color{255, 255, 255})); REQUIRE_THROWS_AS(helpers::parseColor(""), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("foo"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,2,3"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,a,1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,256"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseColor("0,1,-1"), std::logic_error); } TEST_CASE("parseCharsString") { REQUIRE((helpers::parseCharsString("") == std::set<uint32_t>{})); REQUIRE((helpers::parseCharsString("0") == std::set<uint32_t>{0})); REQUIRE((helpers::parseCharsString("42") == std::set<uint32_t>{42})); REQUIRE((helpers::parseCharsString("0-1") == std::set<uint32_t>{0,1})); REQUIRE((helpers::parseCharsString("1-3") == std::set<uint32_t>{1,2,3})); REQUIRE((helpers::parseCharsString(" 1 - 3 ") == std::set<uint32_t>{1,2,3})); REQUIRE_THROWS_AS(helpers::parseCharsString("foo"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseCharsString("-1"), std::logic_error); REQUIRE_THROWS_AS(helpers::parseCharsString("-1-2"), std::logic_error); //REQUIRE_THROWS_AS(helpers::parseCharsString("1-2 3"), std::logic_error); }
Fix travis build
Fix travis build
C++
mit
vladimirgamalian/fontbm,vladimirgamalian/fontbm,vladimirgamalian/fontbm
74b3ccae52fe5a74c1d9d3845d4fdb4353d6244b
src/tools/PaletteTool.cpp
src/tools/PaletteTool.cpp
#include "tools/PaletteTool.h" #include "MainFrame.h" #include "coloroutputs.h" #include <wx/confbase.h> #include <wx/toolbar.h> #include <wx/statusbr.h> #include <wx/dataview.h> #include <wx/brush.h> #include <wx/dc.h> #include <wx/artprov.h> #include <wx/msgdlg.h> #include <wx/filedlg.h> #include <wx/wfstream.h> #include <wx/regex.h> #include <wx/stdpaths.h> #include <wx/dir.h> class ColorColumnRenderer : public wxDataViewCustomRenderer { private: wxColour color; public: ColorColumnRenderer() : wxDataViewCustomRenderer("wxColour") { } bool GetValue(wxVariant& value) const { wxVariant variant; variant << color; return variant; } bool SetValue(const wxVariant& value) { color << value; return true; } wxSize GetSize() const { return wxSize(30, 20); } bool Render(wxRect cell, wxDC* dc, int state) { wxBrush brush(color); dc->SetBackground(brush); dc->SetBrush(brush); dc->DrawRectangle(cell); return true; } }; PaletteTool::PaletteTool(MainFrame* main) : ToolWindow(main, wxID_ANY, _("Palette Tool"), wxDefaultPosition, wxSize(220, 300)), filePath(""), isSaved(true), isNew(true) { ColorDropTarget* dt = new ColorDropTarget(this); SetDropTarget(dt); toolBar = CreateToolBar(); statusBar = CreateStatusBar(); t_new = toolBar->AddTool(wxID_ANY, _("New Palette"), wxArtProvider::GetBitmap(wxART_NEW, wxART_TOOLBAR, wxSize(16, 16))); t_open = toolBar->AddTool(wxID_ANY, _("Open Palette"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, wxSize(16, 16))); toolBar->AddSeparator(); t_save = toolBar->AddTool(wxID_ANY, _("Save"), wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, wxSize(16, 16))); t_saveAs = toolBar->AddTool(wxID_ANY, _("Save As..."), wxArtProvider::GetBitmap(wxART_FILE_SAVE_AS, wxART_TOOLBAR, wxSize(16, 16))); toolBar->AddSeparator(); t_addColor = toolBar->AddTool(wxID_ANY, _("Add Color"), wxArtProvider::GetBitmap(wxART_PLUS, wxART_TOOLBAR, wxSize(16, 16))); t_removeColor = toolBar->AddTool(wxID_ANY, _("Remove Color"), wxArtProvider::GetBitmap(wxART_MINUS, wxART_TOOLBAR, wxSize(16, 16))); t_removeColor->Enable(false); toolBar->Realize(); colorList = new wxDataViewListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxDV_ROW_LINES | wxDV_MULTIPLE | wxWANTS_CHARS); colorList->AppendColumn(new wxDataViewColumn("", new ColorColumnRenderer, 0)); colorList->AppendTextColumn(_("Name"), wxDATAVIEW_CELL_EDITABLE ); Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, &PaletteTool::OnColorSelected, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &PaletteTool::OnColorPush, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_BEGIN_DRAG, &PaletteTool::OnColorDrag, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_EDITING_DONE, &PaletteTool::OnNameEdited, this, colorList->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnNew, this, t_new->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnOpen, this, t_open->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnSave, this, t_save->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnSaveAs, this, t_saveAs->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnAddColor, this, t_addColor->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnRemoveColor, this, t_removeColor->GetId()); colorList->Bind(wxEVT_CHAR, &PaletteTool::OnKeyDown, this); } std::string PaletteTool::GetName() { return "PaletteTool"; } void PaletteTool::Store(wxConfigBase* config) { ToolWindow::Store(config); config->Write("Width0", colorList->GetColumn(0)->GetWidth()); config->Write("Width1", colorList->GetColumn(1)->GetWidth()); config->Write("Saved", isSaved); config->Write("File", filePath); if (!isSaved) { wxString userData = wxStandardPaths::Get().GetUserDataDir(); if (wxDir::Exists(userData) || wxDir::Make(userData)) { wxDir dir(userData); SaveFile(wxString::Format("%s%s", dir.GetNameWithSep(), "unsaved.gpl")); } } } void PaletteTool::Restore(wxConfigBase* config) { ToolWindow::Restore(config); colorList->GetColumn(0)->SetWidth(config->ReadLong("Width0", 30)); colorList->GetColumn(1)->SetWidth(config->ReadLong("Width1", 160)); isSaved = config->ReadBool("Saved", false); if (!isSaved) { wxString userData = wxStandardPaths::Get().GetUserDataDir(); OpenFile(wxString::Format("%s%c%s", userData, wxFILE_SEP_PATH, "unsaved.gpl")); filePath = config->Read("File", wxT("")); isSaved = false; isNew = filePath.IsEmpty(); SetStatusText(filePath); } else { wxString file = config->Read("File", wxT("")); if (!file.IsEmpty()) OpenFile(file); } RefreshTitle(); } void PaletteTool::RefreshTitle() { if (isSaved) SetTitle(_("Palette Tool")); else SetTitle(_("Palette Tool (*)")); } void PaletteTool::AddColor(const wxColour& color, const wxString& name) { wxVector<wxVariant> data; data.push_back(wxVariant(color)); data.push_back(wxVariant(name)); colorList->AppendItem(data); isSaved = false; RefreshTitle(); } bool PaletteTool::ParseColor(std::string colorString) { wxColour color; if (main->GetColorOutput()->parseColor(colorString, color)) { AddColor(color, main->GetColorOutput()->format(color)); return true; } return false; } void PaletteTool::RemoveSelectedColors() { if (colorList->HasSelection()) { wxDataViewItemArray items; int n = colorList->GetSelections(items); for (int i = 0; i < n; i++) { colorList->DeleteItem(colorList->ItemToRow(items[i])); } t_removeColor->Enable(false); toolBar->Realize(); } } wxString read_line(wxFileInputStream& input) { wxString line(""); while (!input.Eof()) { int c = input.GetC(); if (c == '\r') continue; if (c == '\n') break; line << (wchar_t) c; } return line; } void write_line(wxFileOutputStream& output, const wxString& line) { for (size_t i = 0; i < line.size(); i++) output.PutC(line[i]); output.PutC('\n'); } void PaletteTool::OpenFile(const wxString& path) { if (!wxFile::Exists(path)) { SetStatusText("Could not open file"); return; } wxFileInputStream input(path); if (!input.IsOk()) { SetStatusText("Could not open file"); return; } wxString t = read_line(input); if (t != "GIMP Palette") { SetStatusText("nvalid file format"); return; } colorList->DeleteAllItems(); t_removeColor->Enable(false); toolBar->Realize(); // Read palette settings wxRegEx settingRegex("([^:]+): *(.*)"); while (!input.Eof()) { wxString line = read_line(input); if (line[0] == '#') break; if (settingRegex.Matches(line)) { wxString key = settingRegex.GetMatch(line, 1); wxString value = settingRegex.GetMatch(line, 2); } } // Read palette colors wxRegEx colorRegex(" *([0-9]{1,3}) +([0-9]{1,3}) +([0-9]{1,3})[ \t]*(.*)"); while (!input.Eof()) { wxString line = read_line(input); if (colorRegex.Matches(line)) { long red = 0, green = 0, blue = 0; colorRegex.GetMatch(line, 1).ToLong(&red); colorRegex.GetMatch(line, 2).ToLong(&green); colorRegex.GetMatch(line, 3).ToLong(&blue); wxString name = colorRegex.GetMatch(line, 4); AddColor(wxColour(red, green, blue), name); } } filePath = path; isSaved = true; isNew = false; SetStatusText(filePath); RefreshTitle(); } void PaletteTool::SaveFile(const wxString& path) { wxFileName fileName(path); wxFileOutputStream output(path); if (!output.IsOk()) { SetStatusText("Could not open file"); return; } write_line(output, "GIMP Palette"); write_line(output, wxString::Format("Name: %s", fileName.GetName())); write_line(output, "#"); for (int i = 0; i < colorList->GetItemCount(); i++) { wxColour color; wxVariant variant; colorList->GetValue(variant, i, 0); color << variant; wxString name = colorList->GetTextValue(i, 1); write_line(output, wxString::Format("%3d %3d %3d\t%s", color.Red(), color.Green(), color.Blue(), name)); } filePath = path; isSaved = true; isNew = false; RefreshTitle(); } void PaletteTool::OnNew(wxCommandEvent& event) { if (!isSaved) { if (wxMessageBox(_("Current palette has not been saved! Proceed?"), _("Please confirm"), wxICON_QUESTION | wxYES_NO, this) == wxNO) return; } colorList->DeleteAllItems(); isSaved = true; isNew = true; filePath = ""; RefreshTitle(); } void PaletteTool::OnOpen(wxCommandEvent& event) { if (!isSaved) { if (wxMessageBox(_("Current palette has not been saved! Proceed?"), _("Please confirm"), wxICON_QUESTION | wxYES_NO, this) == wxNO) return; } wxFileDialog openFileDialog(main, _("Open palette file"), "", "", "GIMP palette (*.gpl)|*.gpl", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL) return; OpenFile(openFileDialog.GetPath()); } void PaletteTool::OnSave(wxCommandEvent& event) { if (isNew) { OnSaveAs(event); } else if (!isSaved) { SaveFile(filePath); } } void PaletteTool::OnSaveAs(wxCommandEvent& event) { wxFileDialog saveFileDialog(main, _("Save palette file"), "", "", "GIMP palette (*.gpl)|*.gpl", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; SaveFile(saveFileDialog.GetPath()); } void PaletteTool::OnAddColor(wxCommandEvent& event) { wxColour color = main->GetColor(); AddColor(color, main->GetColorOutput()->getOutput()); } void PaletteTool::OnRemoveColor(wxCommandEvent& event) { RemoveSelectedColors(); } void PaletteTool::OnColorSelected(wxDataViewEvent& event) { // Set main color if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; main->SetColor(color); } // Enable delete color button t_removeColor->Enable(event.GetItem().IsOk()); toolBar->Realize(); } void PaletteTool::OnColorPush(wxDataViewEvent& event) { if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; main->PushColor(color); } } void PaletteTool::OnColorDrag(wxDataViewEvent& event) { if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; wxTextDataObject colorData(main->GetColorOutput()->format(color)); wxDropSource dragSource(this); dragSource.SetData(colorData); dragSource.DoDragDrop(true); } } void PaletteTool::OnNameEdited(wxDataViewEvent& event) { isSaved = false; RefreshTitle(); } void PaletteTool::OnKeyDown(wxKeyEvent& event) { if (event.GetKeyCode() == WXK_DELETE) { RemoveSelectedColors(); } else { event.Skip(); } }
#include "tools/PaletteTool.h" #include "MainFrame.h" #include "coloroutputs.h" #include <wx/confbase.h> #include <wx/toolbar.h> #include <wx/statusbr.h> #include <wx/dataview.h> #include <wx/brush.h> #include <wx/dc.h> #include <wx/artprov.h> #include <wx/msgdlg.h> #include <wx/filedlg.h> #include <wx/wfstream.h> #include <wx/regex.h> #include <wx/stdpaths.h> #include <wx/dir.h> class ColorColumnRenderer : public wxDataViewCustomRenderer { private: wxColour color; public: ColorColumnRenderer() : wxDataViewCustomRenderer("wxColour") { } bool GetValue(wxVariant& value) const { wxVariant variant; variant << color; return variant; } bool SetValue(const wxVariant& value) { color << value; return true; } wxSize GetSize() const { return wxSize(30, 20); } bool Render(wxRect cell, wxDC* dc, int state) { wxBrush brush(color); dc->SetBackground(brush); dc->SetBrush(brush); dc->DrawRectangle(cell); return true; } }; PaletteTool::PaletteTool(MainFrame* main) : ToolWindow(main, wxID_ANY, _("Palette Tool"), wxDefaultPosition, wxSize(220, 300)), filePath(""), isSaved(true), isNew(true) { ColorDropTarget* dt = new ColorDropTarget(this); SetDropTarget(dt); toolBar = CreateToolBar(); statusBar = CreateStatusBar(); t_new = toolBar->AddTool(wxID_ANY, _("New Palette"), wxArtProvider::GetBitmap(wxART_NEW, wxART_TOOLBAR, wxSize(16, 16))); t_open = toolBar->AddTool(wxID_ANY, _("Open Palette"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, wxSize(16, 16))); toolBar->AddSeparator(); t_save = toolBar->AddTool(wxID_ANY, _("Save"), wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, wxSize(16, 16))); t_saveAs = toolBar->AddTool(wxID_ANY, _("Save As..."), wxArtProvider::GetBitmap(wxART_FILE_SAVE_AS, wxART_TOOLBAR, wxSize(16, 16))); toolBar->AddSeparator(); t_addColor = toolBar->AddTool(wxID_ANY, _("Add Color"), wxArtProvider::GetBitmap(wxART_PLUS, wxART_TOOLBAR, wxSize(16, 16))); t_removeColor = toolBar->AddTool(wxID_ANY, _("Remove Color"), wxArtProvider::GetBitmap(wxART_MINUS, wxART_TOOLBAR, wxSize(16, 16))); t_removeColor->Enable(false); toolBar->Realize(); colorList = new wxDataViewListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxDV_ROW_LINES | wxDV_MULTIPLE | wxWANTS_CHARS); colorList->AppendColumn(new wxDataViewColumn("", new ColorColumnRenderer, 0)); colorList->AppendTextColumn(_("Name"), wxDATAVIEW_CELL_EDITABLE ); Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, &PaletteTool::OnColorSelected, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &PaletteTool::OnColorPush, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_BEGIN_DRAG, &PaletteTool::OnColorDrag, this, colorList->GetId()); Bind(wxEVT_DATAVIEW_ITEM_EDITING_DONE, &PaletteTool::OnNameEdited, this, colorList->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnNew, this, t_new->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnOpen, this, t_open->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnSave, this, t_save->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnSaveAs, this, t_saveAs->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnAddColor, this, t_addColor->GetId()); Bind(wxEVT_COMMAND_TOOL_CLICKED, &PaletteTool::OnRemoveColor, this, t_removeColor->GetId()); colorList->Bind(wxEVT_CHAR, &PaletteTool::OnKeyDown, this); } std::string PaletteTool::GetName() { return "PaletteTool"; } void PaletteTool::Store(wxConfigBase* config) { ToolWindow::Store(config); config->Write("Width0", colorList->GetColumn(0)->GetWidth()); config->Write("Width1", colorList->GetColumn(1)->GetWidth()); config->Write("Saved", isSaved); config->Write("File", filePath); if (!isSaved) { wxString userData = wxStandardPaths::Get().GetUserDataDir(); if (wxDir::Exists(userData) || wxDir::Make(userData)) { wxDir dir(userData); SaveFile(wxString::Format("%s%s", dir.GetNameWithSep(), "unsaved.gpl")); } } } void PaletteTool::Restore(wxConfigBase* config) { ToolWindow::Restore(config); colorList->GetColumn(0)->SetWidth(config->ReadLong("Width0", 30)); colorList->GetColumn(1)->SetWidth(config->ReadLong("Width1", 160)); isSaved = config->ReadBool("Saved", false); if (!isSaved) { wxString userData = wxStandardPaths::Get().GetUserDataDir(); OpenFile(wxString::Format("%s%c%s", userData, wxFILE_SEP_PATH, "unsaved.gpl")); filePath = config->Read("File", wxT("")); isSaved = false; isNew = filePath.IsEmpty(); SetStatusText(filePath); } else { wxString file = config->Read("File", wxT("")); if (!file.IsEmpty()) OpenFile(file); } RefreshTitle(); } void PaletteTool::RefreshTitle() { if (isSaved) SetTitle(_("Palette Tool")); else SetTitle(_("Palette Tool (*)")); } void PaletteTool::AddColor(const wxColour& color, const wxString& name) { wxVector<wxVariant> data; data.push_back(wxVariant(color)); data.push_back(wxVariant(name)); colorList->AppendItem(data); isSaved = false; RefreshTitle(); } bool PaletteTool::ParseColor(std::string colorString) { wxColour color; if (main->GetColorOutput()->parseColor(colorString, color)) { AddColor(color, main->GetColorOutput()->format(color)); return true; } return false; } void PaletteTool::RemoveSelectedColors() { if (colorList->HasSelection()) { wxDataViewItemArray items; int n = colorList->GetSelections(items); for (int i = 0; i < n; i++) { colorList->DeleteItem(colorList->ItemToRow(items[i])); } t_removeColor->Enable(false); toolBar->Realize(); } } std::string read_line(wxFileInputStream& input) { std::string line(""); while (!input.Eof()) { int c = input.GetC(); if (c == '\r') continue; if (c == '\n') break; line.push_back(c); } return line; } void write_line(wxFileOutputStream& output, const std::string& line) { for (size_t i = 0; i < line.size(); i++) output.PutC(line[i]); output.PutC('\n'); } void PaletteTool::OpenFile(const wxString& path) { if (!wxFile::Exists(path)) { SetStatusText("Could not open file"); return; } wxFileInputStream input(path); if (!input.IsOk()) { SetStatusText("Could not open file"); return; } std::string t = read_line(input); if (t != "GIMP Palette") { SetStatusText("Invalid file format"); return; } colorList->DeleteAllItems(); t_removeColor->Enable(false); toolBar->Realize(); // Read palette settings wxRegEx settingRegex("([^:]+): *(.*)"); while (!input.Eof()) { std::string line = read_line(input); if (line[0] == '#') break; if (settingRegex.Matches(line)) { wxString key = settingRegex.GetMatch(line, 1); wxString value = settingRegex.GetMatch(line, 2); } } // Read palette colors wxRegEx colorRegex(" *([0-9]{1,3}) +([0-9]{1,3}) +([0-9]{1,3})[ \t]*(.*)"); while (!input.Eof()) { std::string line = read_line(input); if (colorRegex.Matches(line)) { long red = 0, green = 0, blue = 0; colorRegex.GetMatch(line, 1).ToLong(&red); colorRegex.GetMatch(line, 2).ToLong(&green); colorRegex.GetMatch(line, 3).ToLong(&blue); wxString name = colorRegex.GetMatch(line, 4); AddColor(wxColour(red, green, blue), name); } } filePath = path; isSaved = true; isNew = false; SetStatusText(filePath); RefreshTitle(); } void PaletteTool::SaveFile(const wxString& path) { wxFileName fileName(path); wxFileOutputStream output(path); if (!output.IsOk()) { SetStatusText("Could not open file"); return; } write_line(output, "GIMP Palette"); write_line(output, wxString::Format("Name: %s", fileName.GetName()).ToStdString()); write_line(output, "#"); for (int i = 0; i < colorList->GetItemCount(); i++) { wxColour color; wxVariant variant; colorList->GetValue(variant, i, 0); color << variant; wxString name = colorList->GetTextValue(i, 1); write_line(output, wxString::Format("%3d %3d %3d\t%s", color.Red(), color.Green(), color.Blue(), name).ToStdString()); } filePath = path; isSaved = true; isNew = false; RefreshTitle(); } void PaletteTool::OnNew(wxCommandEvent& event) { if (!isSaved) { if (wxMessageBox(_("Current palette has not been saved! Proceed?"), _("Please confirm"), wxICON_QUESTION | wxYES_NO, this) == wxNO) return; } colorList->DeleteAllItems(); isSaved = true; isNew = true; filePath = ""; RefreshTitle(); } void PaletteTool::OnOpen(wxCommandEvent& event) { if (!isSaved) { if (wxMessageBox(_("Current palette has not been saved! Proceed?"), _("Please confirm"), wxICON_QUESTION | wxYES_NO, this) == wxNO) return; } wxFileDialog openFileDialog(main, _("Open palette file"), "", "", "GIMP palette (*.gpl)|*.gpl", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL) return; OpenFile(openFileDialog.GetPath()); } void PaletteTool::OnSave(wxCommandEvent& event) { if (isNew) { OnSaveAs(event); } else if (!isSaved) { SaveFile(filePath); } } void PaletteTool::OnSaveAs(wxCommandEvent& event) { wxFileDialog saveFileDialog(main, _("Save palette file"), "", "", "GIMP palette (*.gpl)|*.gpl", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; SaveFile(saveFileDialog.GetPath()); } void PaletteTool::OnAddColor(wxCommandEvent& event) { wxColour color = main->GetColor(); AddColor(color, main->GetColorOutput()->getOutput()); } void PaletteTool::OnRemoveColor(wxCommandEvent& event) { RemoveSelectedColors(); } void PaletteTool::OnColorSelected(wxDataViewEvent& event) { // Set main color if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; main->SetColor(color); } // Enable delete color button t_removeColor->Enable(event.GetItem().IsOk()); toolBar->Realize(); } void PaletteTool::OnColorPush(wxDataViewEvent& event) { if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; main->PushColor(color); } } void PaletteTool::OnColorDrag(wxDataViewEvent& event) { if (event.GetItem().IsOk()) { wxColour color; wxVariant variant; colorList->GetValue(variant, colorList->ItemToRow(event.GetItem()), 0); color << variant; wxTextDataObject colorData(main->GetColorOutput()->format(color)); wxDropSource dragSource(this); dragSource.SetData(colorData); dragSource.DoDragDrop(true); } } void PaletteTool::OnNameEdited(wxDataViewEvent& event) { isSaved = false; RefreshTitle(); } void PaletteTool::OnKeyDown(wxKeyEvent& event) { if (event.GetKeyCode() == WXK_DELETE) { RemoveSelectedColors(); } else { event.Skip(); } }
Fix save/load of palettes (proper unicode support still missing).
Fix save/load of palettes (proper unicode support still missing).
C++
mit
nielssp/colorgrab,Acolarh/colorgrab,nielssp/colorgrab,Acolarh/colorgrab
bb2c425104f3786d03e656eb09b4e5ef6b4f9ea2
examples/array_iteration_basics.cpp
examples/array_iteration_basics.cpp
/** * @file * * @brief Demonstrates iteration over an array and type check functions * */ #include <exception> #include <iostream> // jsoncpp #include <valijson/adapters/jsoncpp_adapter.hpp> #include <valijson/utils/jsoncpp_utils.hpp> // RapidJSON #include <valijson/adapters/rapidjson_adapter.hpp> #include <valijson/utils/rapidjson_utils.hpp> using std::cerr; using std::cout; using std::endl; using std::runtime_error; // The first example uses RapidJson to load a JSON document. If the document // contains an array, this function will print any array values that have a // valid string representation. void usingRapidJson(const char *filename); // The second example uses JsonCpp to perform the same task, but unlike the // RapidJson example, we see how to use strict type checks and exception // handling. void usingJsonCpp(const char *filename); int main(int argc, char **argv) { if (argc != 2) { cerr << "Usage: " << endl; cerr << " " << argv[0] << " <filename>" << endl; return 1; } // Load the document using rapidjson cout << "-- Iteration using RapidJSON --" << endl; usingRapidJson(argv[1]); cout << endl; // Load the document using jsoncpp cout << "-- Iteration using jsoncpp --" << endl; usingJsonCpp(argv[1]); cout << endl; return 0; } void usingRapidJson(const char *filename) { using valijson::adapters::RapidJsonAdapter; rapidjson::Document document; if (!valijson::utils::loadDocument(filename, document)) { return; } RapidJsonAdapter adapter(document); if (!adapter.isArray()) { cout << "Not an array." << endl; return; } cout << "Array values:" << endl; int index = 0; // We support the old way of doing things... const RapidJsonAdapter::Array array = adapter.asArray(); for (RapidJsonAdapter::Array::const_iterator itr = array.begin(); itr != array.end(); ++itr) { cout << " " << index++ << ": "; // Each element of the array is just another RapidJsonAdapter const RapidJsonAdapter &value = *itr; // maybeString is a loose type check if (value.maybeString()) { // If a value may be a string, we are allowed to get a string // representation of the value using asString cout << value.asString(); } cout << endl; } } void usingJsonCpp(const char *filename) { Json::Value value; if (!valijson::utils::loadDocument(filename, value)) { return; } valijson::adapters::JsonCppAdapter adapter(value); // isArray is a strict type check if (!adapter.isArray()) { cout << "Not an array." << endl; return; } cout << "Array values:" << endl; int index = 0; // If a value is not an array, then calling getArray will cause a runtime // exception to be raised. for (auto value : adapter.getArray()) { cout << " " << index++ << ": "; // isString is another strict type check. Valijson uses the convention // that strict type check functions are prefixed with 'is'. if (!value.isString()) { cout << "Not a string. "; } try { // Also by convention, functions prefixed with 'get' will raise a // runtime exception if the value is not of the correct type. cout << value.getString() << endl; } catch (runtime_error &e) { cout << "Caught exception: " << e.what() << endl; } } }
/** * @file * * @brief Demonstrates iteration over an array, and how to use type check functions */ #include <iostream> // jsoncpp #include <valijson/adapters/jsoncpp_adapter.hpp> #include <valijson/utils/jsoncpp_utils.hpp> // RapidJSON #include <valijson/adapters/rapidjson_adapter.hpp> #include <valijson/utils/rapidjson_utils.hpp> using std::cerr; using std::cout; using std::endl; using std::runtime_error; // The first example uses RapidJson to load a JSON document. If the document // contains an array, this function will print any array values that have a // valid string representation. void usingRapidJson(const char *filename) { using valijson::adapters::RapidJsonAdapter; rapidjson::Document document; if (!valijson::utils::loadDocument(filename, document)) { return; } const RapidJsonAdapter adapter(document); if (!adapter.isArray()) { cout << "Not an array." << endl; return; } cout << "Array values:" << endl; int index = 0; const RapidJsonAdapter::Array array = adapter.asArray(); for (auto &&item : array) { cout << " " << index++ << ": "; // maybeString is a loose type check if (item.maybeString()) { // If a value may be a string, we are allowed to get a string // representation of the value using asString cout << item.asString(); } cout << endl; } } // The second example uses JsonCpp to perform the same task, but unlike the // RapidJson example, we see how to use strict type checks and exception // handling. void usingJsonCpp(const char *filename) { using valijson::adapters::JsonCppAdapter; Json::Value value; if (!valijson::utils::loadDocument(filename, value)) { return; } const JsonCppAdapter adapter(value); if (!adapter.isArray()) { cout << "Not an array." << endl; return; } cout << "Array values:" << endl; int index = 0; // If a value is not an array, then calling getArray will cause a runtime // exception to be raised. const JsonCppAdapter::Array array = adapter.getArray(); for (auto &&item : array) { cout << " " << index++ << ": "; // isString is another strict type check. Valijson uses the convention // that strict type check functions are prefixed with 'is'. if (!item.isString()) { cout << "Not a string. "; } try { // Also by convention, functions prefixed with 'get' will raise a // runtime exception if the item is not of the correct type. cout << item.getString() << endl; } catch (const runtime_error &e) { cout << "Caught exception: " << e.what() << endl; } } } int main(int argc, char **argv) { if (argc != 2) { cerr << "Usage: " << endl; cerr << " " << argv[0] << " <filename>" << endl; return 1; } // Load the document using rapidjson cout << "-- Iteration using RapidJSON --" << endl; usingRapidJson(argv[1]); cout << endl; // Load the document using jsoncpp cout << "-- Iteration using jsoncpp --" << endl; usingJsonCpp(argv[1]); cout << endl; return 0; }
Improve array_iteration_basics example
Improve array_iteration_basics example
C++
bsd-2-clause
tristanpenman/valijson,tristanpenman/valijson
935d5bc3dd45a10d1545363c9b1f6185ac5e0ae8
examples/commandlineoutput/main.cpp
examples/commandlineoutput/main.cpp
#include <GL/glew.h> #include <iostream> #include <iomanip> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glow/Error.h> #include <glow/Uniform.h> #include <glow/Program.h> #include <glow/Shader.h> #include <glow/Buffer.h> #include <glow/Query.h> #include <glow/FrameBufferObject.h> #include <glow/RenderBufferObject.h> #include <glow/Sampler.h> #include <glow/Texture.h> #include <glow/TransformFeedback.h> #include <glow/VertexArrayObject.h> #include <glow/logging.h> #include <glow/ref_ptr.h> #include <glow/formatString.h> #include <glowwindow/ContextFormat.h> #include <glowwindow/Context.h> #include <glowwindow/Window.h> #include <glowwindow/WindowEventHandler.h> class EventHandler : public glowwindow::WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { } virtual void initialize(glowwindow::Window & window) override { glow::DebugMessageOutput::enable(); std::cout << "glow Objects tests" << std::endl; glow::ref_ptr<glow::Buffer> buffer(new glow::Buffer()); std::cout << "glow::Buffer = "; glow::info() << buffer.get(); std::cout << "glow::FrameBufferObject = "; glow::info() << glow::FrameBufferObject::defaultFBO(); glow::ref_ptr<glow::Program> program(new glow::Program()); std::cout << "glow::Program = "; glow::info() << program.get(); glow::ref_ptr<glow::Query> query(new glow::Query()); std::cout << "glow::Query = "; glow::info() << query.get(); glow::ref_ptr<glow::RenderBufferObject> rbo(new glow::RenderBufferObject()); std::cout << "glow::RenderBufferObject = "; glow::info() << rbo.get(); glow::ref_ptr<glow::Sampler> sampler(new glow::Sampler()); std::cout << "glow::Sampler = "; glow::info() << sampler.get(); glow::ref_ptr<glow::Shader> shader(new glow::Shader(GL_VERTEX_SHADER)); std::cout << "glow::Shader = "; glow::info() << shader.get(); glow::ref_ptr<glow::Texture> texture(new glow::Texture()); std::cout << "glow::Texture = "; glow::info() << texture.get(); glow::ref_ptr<glow::TransformFeedback> tf(new glow::TransformFeedback()); std::cout << "glow::TransformFeedback = "; glow::info() << tf.get(); glow::ref_ptr<glow::VertexArrayObject> vao(new glow::VertexArrayObject()); std::cout << "glow::VertexArrayObject = "; glow::info() << vao.get(); glow::ref_ptr<glow::Uniform<float>> uniform(new glow::Uniform<float>("Pi", 3.14)); std::cout << "glow::Uniform = "; glow::info() << uniform.get(); std::cout << "glow::Version = "; glow::info() << glow::Version::current(); window.close(); } }; /** This example shows ... . */ int main(int argc, char* argv[]) { glowwindow::ContextFormat format; format.setVersion(3, 0); glowwindow::Window window; window.setEventHandler(new EventHandler()); std::cout << "Standard types test" << std::endl; std::cout << "const char* \"Hello\" = "; glow::info() << "Hello"; std::cout << "const std::string& \"Master\" = "; glow::info() << std::string("Master"); std::cout << "bool true = "; glow::info() << true; std::cout << "char 'a' = "; glow::info() << 'a'; std::cout << "int 42 = "; glow::info() << 42; std::cout << "float 3.14 = "; glow::info() << 3.14f; std::cout << "double 3.141592654 = "; glow::info() << std::setprecision(10) << 3.141592654; std::cout << "long double 2.71828 = "; glow::info() << 2.71828l; std::cout << "unsigned integer 23 = "; glow::info() << 23u; std::cout << "long integer 1337 = "; glow::info() << 1337l; std::cout << "long long integer 1234567890 = "; glow::info() << 1234567890ll; std::cout << "unsigned long integer 45123 = "; glow::info() << 45123ul; std::cout << "unsigned char 97 = "; glow::info() << 'a'; std::cout << "void* " << &window << " = "; glow::info() << static_cast<void*>(&window); std::cout << std::endl; std::cout << "Format string test" << std::endl; std::cout << "Expected: " << "This is a test: 42 pi = +3.14159E+00" << std::endl; glow::info(" Actual: This is a test: %; pi = %+0E10.5;", 42, 3.141592653589793); std::cout << "Expected: " << "a string - 255 - ______2.72" << std::endl; glow::info(" Actual: %; - %X; - %rf?_10.2;", "a string", 255, 2.71828182846); std::cout << std::endl; if (!window.create(format, "Command Line Output Example")) { return 1; } window.show(); return glowwindow::MainLoop::run(); }
#include <GL/glew.h> #include <iostream> #include <iomanip> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glow/Error.h> #include <glow/Uniform.h> #include <glow/Program.h> #include <glow/Shader.h> #include <glow/Buffer.h> #include <glow/Query.h> #include <glow/FrameBufferObject.h> #include <glow/RenderBufferObject.h> #include <glow/Sampler.h> #include <glow/Texture.h> #include <glow/TransformFeedback.h> #include <glow/VertexArrayObject.h> #include <glow/logging.h> #include <glow/ref_ptr.h> #include <glow/formatString.h> #include <glowwindow/ContextFormat.h> #include <glowwindow/Context.h> #include <glowwindow/Window.h> #include <glowwindow/WindowEventHandler.h> class EventHandler : public glowwindow::WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { } virtual void initialize(glowwindow::Window & window) override { glow::DebugMessageOutput::enable(); std::cout << "glow Objects tests" << std::endl; glow::ref_ptr<glow::Buffer> buffer(new glow::Buffer()); std::cout << "glow::Buffer = "; glow::info() << buffer.get(); std::cout << "glow::FrameBufferObject = "; glow::info() << glow::FrameBufferObject::defaultFBO(); glow::ref_ptr<glow::Program> program(new glow::Program()); std::cout << "glow::Program = "; glow::info() << program.get(); glow::ref_ptr<glow::Query> query(new glow::Query()); std::cout << "glow::Query = "; glow::info() << query.get(); glow::ref_ptr<glow::RenderBufferObject> rbo(new glow::RenderBufferObject()); std::cout << "glow::RenderBufferObject = "; glow::info() << rbo.get(); glow::ref_ptr<glow::Sampler> sampler(new glow::Sampler()); std::cout << "glow::Sampler = "; glow::info() << sampler.get(); glow::ref_ptr<glow::Shader> shader(new glow::Shader(GL_VERTEX_SHADER)); std::cout << "glow::Shader = "; glow::info() << shader.get(); glow::ref_ptr<glow::Texture> texture(new glow::Texture()); std::cout << "glow::Texture = "; glow::info() << texture.get(); glow::ref_ptr<glow::TransformFeedback> tf(new glow::TransformFeedback()); std::cout << "glow::TransformFeedback = "; glow::info() << tf.get(); glow::ref_ptr<glow::VertexArrayObject> vao(new glow::VertexArrayObject()); std::cout << "glow::VertexArrayObject = "; glow::info() << vao.get(); glow::ref_ptr<glow::Uniform<float>> uniform(new glow::Uniform<float>("Pi", 3.14f)); std::cout << "glow::Uniform = "; glow::info() << uniform.get(); std::cout << "glow::Version = "; glow::info() << glow::Version::current(); window.close(); } }; /** This example shows ... . */ int main(int /*argc*/, char* /*argv*/[]) { glowwindow::ContextFormat format; format.setVersion(3, 0); glowwindow::Window window; window.setEventHandler(new EventHandler()); std::cout << "Standard types test" << std::endl; std::cout << "const char* \"Hello\" = "; glow::info() << "Hello"; std::cout << "const std::string& \"Master\" = "; glow::info() << std::string("Master"); std::cout << "bool true = "; glow::info() << true; std::cout << "char 'a' = "; glow::info() << 'a'; std::cout << "int 42 = "; glow::info() << 42; std::cout << "float 3.14 = "; glow::info() << 3.14f; std::cout << "double 3.141592654 = "; glow::info() << std::setprecision(10) << 3.141592654; std::cout << "long double 2.71828 = "; glow::info() << 2.71828l; std::cout << "unsigned integer 23 = "; glow::info() << 23u; std::cout << "long integer 1337 = "; glow::info() << 1337l; std::cout << "long long integer 1234567890 = "; glow::info() << 1234567890ll; std::cout << "unsigned long integer 45123 = "; glow::info() << 45123ul; std::cout << "unsigned char 97 = "; glow::info() << 'a'; std::cout << "void* " << &window << " = "; glow::info() << static_cast<void*>(&window); std::cout << std::endl; std::cout << "Format string test" << std::endl; std::cout << "Expected: " << "This is a test: 42 pi = +3.14159E+00" << std::endl; glow::info(" Actual: This is a test: %; pi = %+0E10.5;", 42, 3.141592653589793); std::cout << "Expected: " << "a string - 255 - ______2.72" << std::endl; glow::info(" Actual: %; - %X; - %rf?_10.2;", "a string", 255, 2.71828182846); std::cout << std::endl; if (!window.create(format, "Command Line Output Example")) { return 1; } window.show(); return glowwindow::MainLoop::run(); }
Fix warnings for master
Fix warnings for master
C++
mit
j-o/globjects,hpi-r2d2/globjects,j-o/globjects,j-o/globjects,cginternals/globjects,j-o/globjects,hpi-r2d2/globjects,cginternals/globjects
80821abd6410f47130fc031b15e9ac220de5b1b9
tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc
tensorflow/contrib/lite/toco/graph_transformations/remove_trivial_passthrough.cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { // Reroute all edges involving a given discardable array to another // array instead. from_array is assumed to be discardable, and consequently // this only updates operator edges (since discardable arrays only // appear there, and not e.g. in model flags). void RerouteEdges(const string& from_array, const string& to_array, Model* model) { for (const auto& op : model->operators) { for (auto& output : op->outputs) { if (output == from_array) { output = to_array; } } for (auto& input : op->inputs) { if (input == from_array) { input = to_array; } } } } } // namespace bool RemoveTrivialPassthroughOp(GraphTransformation* transformation, Model* model, std::size_t op_index, int input_index) { const auto passthru_it = model->operators.begin() + op_index; auto* passthru_op = passthru_it->get(); CHECK_EQ(passthru_op->outputs.size(), 1); CHECK_GE(passthru_op->inputs.size(), 1); int main_input_array_index = 0; if (input_index != -1) { main_input_array_index = input_index; } else { // We call 'main input' the unique nonconstant input array if there is one, // or else the 0-th input. int count_nonconstant_input_arrays = 0; for (int i = 0; i < passthru_op->inputs.size(); i++) { if (!model->GetArray(passthru_op->inputs[i]).buffer) { count_nonconstant_input_arrays++; if (count_nonconstant_input_arrays == 1) { main_input_array_index = i; } } } } const string main_input_name = passthru_op->inputs[main_input_array_index]; const string output_name = passthru_op->outputs[0]; // Build the list of all input and output arrays of the passthrough node // that we are considering removing. Any of these arrays is a candidate // for being removed as well, if nothing else references it. Doing that // arrays-removal together with the passthrough-node-removal proved too // error-prone. std::vector<string> removal_candidates; for (const string& input : passthru_op->inputs) { removal_candidates.push_back(input); } removal_candidates.push_back(output_name); if (IsDiscardableArray(*model, output_name)) { transformation->AddMessageF( "Removing %s, keeping its non-constant input array %s and removing %s", LogName(*passthru_op), main_input_name, output_name); RerouteEdges(output_name, main_input_name, model); } else if (IsDiscardableArray(*model, main_input_name) && !IsConstantParameterArray(*model, main_input_name)) { transformation->AddMessageF( "Removing %s, keeping its output array %s and removing non-constant " "input %s", LogName(*passthru_op), output_name, main_input_name); RerouteEdges(main_input_name, output_name, model); } else { transformation->AddMessageF( "Cannot remove %s, neither its main input nor its output may be " "discarded", LogName(*passthru_op)); if (passthru_op->type != OperatorType::kReshape && model->GetArray(main_input_name).has_shape()) { // We can't remove either array but we can remove the op. Converting it to // a reshape gives us some hope of later on fixing that (either in the // final runtime or as an additional fixup step). // // Note that we don't try to insert copies in place of reshapes as the // copy itself is a trivial reshape and we'd go into an infinite loop! transformation->AddMessageF("Replacing with a copy (reshape) instead"); InsertCopyOperator(model, main_input_name, output_name); } else { return false; } } // Remove the pass-through node. CHECK_EQ(passthru_it->get(), passthru_op); model->operators.erase(passthru_it); // Remove any array that is no longer used. for (const string& removal_candidate : removal_candidates) { bool is_referenced = false; for (const auto& array : model->flags.input_arrays()) { if (array.name() == removal_candidate) { is_referenced = true; } } for (const auto& array_name : model->flags.output_arrays()) { if (array_name == removal_candidate) { is_referenced = true; } } for (const auto& op : model->operators) { for (const string& input : op->inputs) { if (input == removal_candidate) { is_referenced = true; } } for (const string& output : op->outputs) { if (output == removal_candidate) { is_referenced = true; } } } if (!is_referenced) { model->EraseArray(removal_candidate); } } return true; } } // namespace toco
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { // Reroute all edges involving a given discardable array to another // array instead. from_array is assumed to be discardable, and consequently // this only updates operator edges (since discardable arrays only // appear there, and not e.g. in model flags). void Reroute(const string& from, const string& to, Model* model) { for (const auto& op : model->operators) { for (auto& output : op->outputs) { if (output == from) { output = to; } } for (auto& input : op->inputs) { if (input == from) { input = to; } } } const Array& from_array = model->GetArray(from); Array& to_array = model->GetOrCreateArray(to); // Preserve minmax information if to_array didn't already have any. if (from_array.minmax && !to_array.minmax) { to_array.GetOrCreateMinMax() = from_array.GetMinMax(); // If we're copying minmax info, then we should also be copying // narrow_range, which affects how minmax info is to be interpreted. to_array.narrow_range = from_array.narrow_range; } // Separately, also preserve final_data_type if to_array didn't already // have any. if (from_array.final_data_type != ArrayDataType::kNone && to_array.final_data_type == ArrayDataType::kNone) { to_array.final_data_type = from_array.final_data_type; } } } // namespace bool RemoveTrivialPassthroughOp(GraphTransformation* transformation, Model* model, std::size_t op_index, int input_index) { const auto passthru_it = model->operators.begin() + op_index; auto* passthru_op = passthru_it->get(); CHECK_EQ(passthru_op->outputs.size(), 1); CHECK_GE(passthru_op->inputs.size(), 1); int main_input_array_index = 0; if (input_index != -1) { main_input_array_index = input_index; } else { // We call 'main input' the unique nonconstant input array if there is one, // or else the 0-th input. int count_nonconstant_input_arrays = 0; for (int i = 0; i < passthru_op->inputs.size(); i++) { if (!model->GetArray(passthru_op->inputs[i]).buffer) { count_nonconstant_input_arrays++; if (count_nonconstant_input_arrays == 1) { main_input_array_index = i; } } } } const string main_input_name = passthru_op->inputs[main_input_array_index]; const string output_name = passthru_op->outputs[0]; // Build the list of all input and output arrays of the passthrough node // that we are considering removing. Any of these arrays is a candidate // for being removed as well, if nothing else references it. Doing that // arrays-removal together with the passthrough-node-removal proved too // error-prone. std::vector<string> removal_candidates; for (const string& input : passthru_op->inputs) { removal_candidates.push_back(input); } removal_candidates.push_back(output_name); if (IsDiscardableArray(*model, output_name)) { transformation->AddMessageF( "Removing %s, keeping its non-constant input array %s and removing %s", LogName(*passthru_op), main_input_name, output_name); Reroute(output_name, main_input_name, model); } else if (IsDiscardableArray(*model, main_input_name) && !IsConstantParameterArray(*model, main_input_name)) { transformation->AddMessageF( "Removing %s, keeping its output array %s and removing non-constant " "input %s", LogName(*passthru_op), output_name, main_input_name); Reroute(main_input_name, output_name, model); } else { transformation->AddMessageF( "Cannot remove %s, neither its main input nor its output may be " "discarded", LogName(*passthru_op)); if (passthru_op->type != OperatorType::kReshape && model->GetArray(main_input_name).has_shape()) { // We can't remove either array but we can remove the op. Converting it to // a reshape gives us some hope of later on fixing that (either in the // final runtime or as an additional fixup step). // // Note that we don't try to insert copies in place of reshapes as the // copy itself is a trivial reshape and we'd go into an infinite loop! transformation->AddMessageF("Replacing with a copy (reshape) instead"); InsertCopyOperator(model, main_input_name, output_name); } else { return false; } } // Remove the pass-through node. CHECK_EQ(passthru_it->get(), passthru_op); model->operators.erase(passthru_it); // Remove any array that is no longer used. for (const string& removal_candidate : removal_candidates) { bool is_referenced = false; for (const auto& array : model->flags.input_arrays()) { if (array.name() == removal_candidate) { is_referenced = true; } } for (const auto& array_name : model->flags.output_arrays()) { if (array_name == removal_candidate) { is_referenced = true; } } for (const auto& op : model->operators) { for (const string& input : op->inputs) { if (input == removal_candidate) { is_referenced = true; } } for (const string& output : op->outputs) { if (output == removal_candidate) { is_referenced = true; } } } if (!is_referenced) { model->EraseArray(removal_candidate); } } return true; } } // namespace toco
Make RemoveTrivialPassthrough preserve minmax-related info
Make RemoveTrivialPassthrough preserve minmax-related info PiperOrigin-RevId: 215487633
C++
apache-2.0
petewarden/tensorflow,karllessard/tensorflow,renyi533/tensorflow,seanli9jan/tensorflow,jbedorf/tensorflow,frreiss/tensorflow-fred,hehongliang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,frreiss/tensorflow-fred,alshedivat/tensorflow,dancingdan/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,asimshankar/tensorflow,theflofly/tensorflow,dongjoon-hyun/tensorflow,petewarden/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,Bismarrck/tensorflow,ageron/tensorflow,jhseu/tensorflow,yongtang/tensorflow,Bismarrck/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,ppwwyyxx/tensorflow,apark263/tensorflow,DavidNorman/tensorflow,arborh/tensorflow,jhseu/tensorflow,seanli9jan/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,alsrgv/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,dongjoon-hyun/tensorflow,jendap/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,girving/tensorflow,kevin-coder/tensorflow-fork,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,snnn/tensorflow,annarev/tensorflow,ageron/tensorflow,theflofly/tensorflow,sarvex/tensorflow,alshedivat/tensorflow,gautam1858/tensorflow,ghchinoy/tensorflow,frreiss/tensorflow-fred,girving/tensorflow,chemelnucfin/tensorflow,jendap/tensorflow,aam-at/tensorflow,asimshankar/tensorflow,Intel-tensorflow/tensorflow,jbedorf/tensorflow,alsrgv/tensorflow,girving/tensorflow,aam-at/tensorflow,arborh/tensorflow,jbedorf/tensorflow,frreiss/tensorflow-fred,dongjoon-hyun/tensorflow,tensorflow/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,gautam1858/tensorflow,alsrgv/tensorflow,freedomtan/tensorflow,arborh/tensorflow,ppwwyyxx/tensorflow,dancingdan/tensorflow,apark263/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,hehongliang/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,theflofly/tensorflow,chemelnucfin/tensorflow,annarev/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,apark263/tensorflow,Bismarrck/tensorflow,jhseu/tensorflow,jendap/tensorflow,kevin-coder/tensorflow-fork,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,dancingdan/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,dongjoon-hyun/tensorflow,alshedivat/tensorflow,snnn/tensorflow,apark263/tensorflow,hfp/tensorflow-xsmm,ageron/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,Intel-tensorflow/tensorflow,ageron/tensorflow,davidzchen/tensorflow,theflofly/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,xzturn/tensorflow,davidzchen/tensorflow,hfp/tensorflow-xsmm,freedomtan/tensorflow,dongjoon-hyun/tensorflow,sarvex/tensorflow,yongtang/tensorflow,theflofly/tensorflow,seanli9jan/tensorflow,dancingdan/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,asimshankar/tensorflow,Intel-Corporation/tensorflow,jbedorf/tensorflow,arborh/tensorflow,hehongliang/tensorflow,brchiu/tensorflow,brchiu/tensorflow,DavidNorman/tensorflow,ghchinoy/tensorflow,jendap/tensorflow,kevin-coder/tensorflow-fork,girving/tensorflow,DavidNorman/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,arborh/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,karllessard/tensorflow,alsrgv/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,theflofly/tensorflow,Bismarrck/tensorflow,frreiss/tensorflow-fred,dongjoon-hyun/tensorflow,petewarden/tensorflow,annarev/tensorflow,gautam1858/tensorflow,jbedorf/tensorflow,gunan/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,dancingdan/tensorflow,frreiss/tensorflow-fred,snnn/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,jendap/tensorflow,Intel-Corporation/tensorflow,apark263/tensorflow,jendap/tensorflow,snnn/tensorflow,davidzchen/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow,asimshankar/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,ghchinoy/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,hfp/tensorflow-xsmm,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,jendap/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,ppwwyyxx/tensorflow,jendap/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,gunan/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,dongjoon-hyun/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,annarev/tensorflow,seanli9jan/tensorflow,hfp/tensorflow-xsmm,Intel-tensorflow/tensorflow,xzturn/tensorflow,alsrgv/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,chemelnucfin/tensorflow,renyi533/tensorflow,chemelnucfin/tensorflow,kevin-coder/tensorflow-fork,snnn/tensorflow,kevin-coder/tensorflow-fork,dancingdan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,Bismarrck/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,dancingdan/tensorflow,theflofly/tensorflow,gunan/tensorflow,girving/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,ghchinoy/tensorflow,frreiss/tensorflow-fred,Bismarrck/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,dancingdan/tensorflow,adit-chandra/tensorflow,freedomtan/tensorflow,alshedivat/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,ghchinoy/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,karllessard/tensorflow,snnn/tensorflow,gautam1858/tensorflow,jbedorf/tensorflow,aldian/tensorflow,asimshankar/tensorflow,renyi533/tensorflow,Bismarrck/tensorflow,alshedivat/tensorflow,seanli9jan/tensorflow,renyi533/tensorflow,petewarden/tensorflow,jendap/tensorflow,yongtang/tensorflow,hfp/tensorflow-xsmm,annarev/tensorflow,apark263/tensorflow,tensorflow/tensorflow,aldian/tensorflow,seanli9jan/tensorflow,jbedorf/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,jbedorf/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,brchiu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,apark263/tensorflow,DavidNorman/tensorflow,asimshankar/tensorflow,gunan/tensorflow,girving/tensorflow,jbedorf/tensorflow,theflofly/tensorflow,gunan/tensorflow,yongtang/tensorflow,renyi533/tensorflow,petewarden/tensorflow,aam-at/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,chemelnucfin/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,dancingdan/tensorflow,dancingdan/tensorflow,xzturn/tensorflow,apark263/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alsrgv/tensorflow,gunan/tensorflow,dongjoon-hyun/tensorflow,ghchinoy/tensorflow,adit-chandra/tensorflow,jbedorf/tensorflow,aam-at/tensorflow,girving/tensorflow,gautam1858/tensorflow,alsrgv/tensorflow,xzturn/tensorflow,cxxgtxy/tensorflow,ageron/tensorflow,seanli9jan/tensorflow,asimshankar/tensorflow,adit-chandra/tensorflow,snnn/tensorflow,xzturn/tensorflow,aldian/tensorflow,hehongliang/tensorflow,brchiu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hehongliang/tensorflow,kevin-coder/tensorflow-fork,tensorflow/tensorflow,theflofly/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,DavidNorman/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,petewarden/tensorflow,brchiu/tensorflow,alsrgv/tensorflow,aam-at/tensorflow,brchiu/tensorflow,cxxgtxy/tensorflow,hehongliang/tensorflow,annarev/tensorflow,brchiu/tensorflow,dongjoon-hyun/tensorflow,paolodedios/tensorflow,alsrgv/tensorflow,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,snnn/tensorflow,arborh/tensorflow,dongjoon-hyun/tensorflow,hfp/tensorflow-xsmm,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,theflofly/tensorflow,ghchinoy/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,hfp/tensorflow-xsmm,Bismarrck/tensorflow,xzturn/tensorflow,karllessard/tensorflow,petewarden/tensorflow,ageron/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,hfp/tensorflow-xsmm,snnn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ghchinoy/tensorflow,karllessard/tensorflow,dancingdan/tensorflow,apark263/tensorflow,adit-chandra/tensorflow,karllessard/tensorflow,jbedorf/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,snnn/tensorflow,Intel-Corporation/tensorflow,ageron/tensorflow,arborh/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,arborh/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,ghchinoy/tensorflow,gunan/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,girving/tensorflow,chemelnucfin/tensorflow,alshedivat/tensorflow,alshedivat/tensorflow,yongtang/tensorflow,arborh/tensorflow,davidzchen/tensorflow,brchiu/tensorflow,kevin-coder/tensorflow-fork,apark263/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,dongjoon-hyun/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,jhseu/tensorflow,DavidNorman/tensorflow,gunan/tensorflow,renyi533/tensorflow,asimshankar/tensorflow,asimshankar/tensorflow,karllessard/tensorflow,aam-at/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,aldian/tensorflow,ghchinoy/tensorflow,girving/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,alshedivat/tensorflow,alsrgv/tensorflow,theflofly/tensorflow,sarvex/tensorflow,hehongliang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,asimshankar/tensorflow,DavidNorman/tensorflow,alshedivat/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,ppwwyyxx/tensorflow,ageron/tensorflow,alsrgv/tensorflow,cxxgtxy/tensorflow,renyi533/tensorflow,hfp/tensorflow-xsmm,petewarden/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,kevin-coder/tensorflow-fork,jendap/tensorflow,jhseu/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,aam-at/tensorflow,yongtang/tensorflow,Intel-Corporation/tensorflow,ppwwyyxx/tensorflow,seanli9jan/tensorflow,tensorflow/tensorflow,brchiu/tensorflow,brchiu/tensorflow,ghchinoy/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,cxxgtxy/tensorflow,renyi533/tensorflow,theflofly/tensorflow,apark263/tensorflow,seanli9jan/tensorflow,gunan/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow,brchiu/tensorflow,petewarden/tensorflow,seanli9jan/tensorflow,cxxgtxy/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,ageron/tensorflow,Intel-tensorflow/tensorflow,jendap/tensorflow,chemelnucfin/tensorflow,paolodedios/tensorflow,snnn/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jhseu/tensorflow,xzturn/tensorflow,asimshankar/tensorflow,aldian/tensorflow,girving/tensorflow,ghchinoy/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,cxxgtxy/tensorflow,seanli9jan/tensorflow,hfp/tensorflow-xsmm,aldian/tensorflow,gunan/tensorflow,aldian/tensorflow,jbedorf/tensorflow,Bismarrck/tensorflow,kevin-coder/tensorflow-fork,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,girving/tensorflow,sarvex/tensorflow
bc760707c802f98d8a4c2a2814604ddc94c035b4
eval/src/tests/instruction/join_with_number/join_with_number_function_test.cpp
eval/src/tests/instruction/join_with_number/join_with_number_function_test.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/eval/instruction/join_with_number_function.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; using Primary = JoinWithNumberFunction::Primary; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } } struct FunInfo { using LookFor = JoinWithNumberFunction; Primary primary; bool inplace; void verify(const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.primary(), primary); EXPECT_EQUAL(fun.inplace(), inplace); } }; void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) { // fprintf(stderr, "%s\n", expr.c_str()); const auto stable_types = CellTypeSpace({CellType::FLOAT, CellType::DOUBLE}, 2); FunInfo stable_details{primary, inplace}; TEST_DO(EvalFixture::verify<FunInfo>(expr, {stable_details}, stable_types)); } void verify_not_optimized(const vespalib::string &expr) { // fprintf(stderr, "%s\n", expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); TEST_DO(EvalFixture::verify<FunInfo>(expr, {}, all_types)); } TEST("require that dense number join can be optimized") { TEST_DO(verify_optimized("x3y5+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5*reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)*x3y5", Primary::RHS, false)); } TEST("require that dense number join can be inplace") { TEST_DO(verify_optimized("@x3y5*reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)*@x3y5", Primary::RHS, true)); TEST_DO(verify_optimized("@x3y5+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3y5", Primary::RHS, true)); } TEST("require that asymmetric operations work") { TEST_DO(verify_optimized("x3y5/reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)/x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5-reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)-x3y5", Primary::RHS, false)); } TEST("require that sparse number join can be optimized") { TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); } TEST("require that sparse number join can be inplace") { TEST_DO(verify_optimized("@x3_1z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1z2_1", Primary::RHS, true)); } TEST("require that mixed number join can be optimized") { TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); } TEST("require that mixed number join can be inplace") { TEST_DO(verify_optimized("@x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1y5z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1y5z2_1", Primary::RHS, true)); } TEST("require that inappropriate cases are not optimized") { for (vespalib::string lhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { for (vespalib::string rhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { auto expr = fmt("%s$1*%s$2", lhs.c_str(), rhs.c_str()); verify_not_optimized(expr); } verify_optimized(fmt("reduce(v3,sum)*%s", lhs.c_str()), Primary::RHS, false); verify_optimized(fmt("%s*reduce(v3,sum)", lhs.c_str()), Primary::LHS, false); } // two scalars -> not optimized verify_not_optimized("reduce(v3,sum)*reduce(k4,sum)"); } TEST_MAIN() { TEST_RUN_ALL(); }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/eval/instruction/join_with_number_function.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; using Primary = JoinWithNumberFunction::Primary; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } } struct FunInfo { using LookFor = JoinWithNumberFunction; Primary primary; bool inplace; void verify(const EvalFixture &fixture, const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.primary(), primary); EXPECT_EQUAL(fun.inplace(), inplace); if (inplace) { size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1; EXPECT_EQUAL(fixture.result_value().cells().data, fixture.param_value(idx).cells().data); } } }; void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) { // fprintf(stderr, "%s\n", expr.c_str()); const auto stable_types = CellTypeSpace({CellType::FLOAT, CellType::DOUBLE}, 2); FunInfo stable_details{primary, inplace}; TEST_DO(EvalFixture::verify<FunInfo>(expr, {stable_details}, stable_types)); } void verify_not_optimized(const vespalib::string &expr) { // fprintf(stderr, "%s\n", expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); TEST_DO(EvalFixture::verify<FunInfo>(expr, {}, all_types)); } TEST("require that dense number join can be optimized") { TEST_DO(verify_optimized("x3y5+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5*reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)*x3y5", Primary::RHS, false)); } TEST("require that dense number join can be inplace") { TEST_DO(verify_optimized("@x3y5*reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)*@x3y5", Primary::RHS, true)); TEST_DO(verify_optimized("@x3y5+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3y5", Primary::RHS, true)); } TEST("require that asymmetric operations work") { TEST_DO(verify_optimized("x3y5/reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)/x3y5", Primary::RHS, false)); TEST_DO(verify_optimized("x3y5-reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)-x3y5", Primary::RHS, false)); } TEST("require that sparse number join can be optimized") { TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1z2_1", Primary::RHS, false)); } TEST("require that sparse number join can be inplace") { TEST_DO(verify_optimized("@x3_1z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1z2_1", Primary::RHS, true)); } TEST("require that mixed number join can be optimized") { TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)+x3_1y5z2_1", Primary::RHS, false)); TEST_DO(verify_optimized("x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, false)); TEST_DO(verify_optimized("reduce(v3,sum)<x3_1y5z2_1", Primary::RHS, false)); } TEST("require that mixed number join can be inplace") { TEST_DO(verify_optimized("@x3_1y5z2_1+reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)+@x3_1y5z2_1", Primary::RHS, true)); TEST_DO(verify_optimized("@x3_1y5z2_1<reduce(v3,sum)", Primary::LHS, true)); TEST_DO(verify_optimized("reduce(v3,sum)<@x3_1y5z2_1", Primary::RHS, true)); } TEST("require that inappropriate cases are not optimized") { for (vespalib::string lhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { for (vespalib::string rhs: {"y5", "x3_1z2_1", "x3_1y5z2_1"}) { auto expr = fmt("%s$1*%s$2", lhs.c_str(), rhs.c_str()); verify_not_optimized(expr); } verify_optimized(fmt("reduce(v3,sum)*%s", lhs.c_str()), Primary::RHS, false); verify_optimized(fmt("%s*reduce(v3,sum)", lhs.c_str()), Primary::LHS, false); } // two scalars -> not optimized verify_not_optimized("reduce(v3,sum)*reduce(k4,sum)"); } TEST_MAIN() { TEST_RUN_ALL(); }
check inplace better
check inplace better
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
805d04378d8352487940afbf01c51d632646c35f
webkit/appcache/appcache_group.cc
webkit/appcache/appcache_group.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/appcache/appcache_group.h" #include <algorithm> #include "base/logging.h" #include "base/message_loop.h" #include "webkit/appcache/appcache.h" #include "webkit/appcache/appcache_host.h" #include "webkit/appcache/appcache_service.h" #include "webkit/appcache/appcache_storage.h" #include "webkit/appcache/appcache_update_job.h" namespace appcache { class AppCacheGroup; // Use this helper class because we cannot make AppCacheGroup a derived class // of AppCacheHost::Observer as it would create a circular dependency between // AppCacheHost and AppCacheGroup. class AppCacheGroup::HostObserver : public AppCacheHost::Observer { public: explicit HostObserver(AppCacheGroup* group) : group_(group) {} // Methods for AppCacheHost::Observer. void OnCacheSelectionComplete(AppCacheHost* host) {} // N/A void OnDestructionImminent(AppCacheHost* host) { group_->HostDestructionImminent(host); } private: AppCacheGroup* group_; }; AppCacheGroup::AppCacheGroup(AppCacheService* service, const GURL& manifest_url, int64 group_id) : group_id_(group_id), manifest_url_(manifest_url), update_status_(IDLE), is_obsolete_(false), newest_complete_cache_(NULL), update_job_(NULL), service_(service), restart_update_task_(NULL) { service_->storage()->working_set()->AddGroup(this); host_observer_.reset(new HostObserver(this)); } AppCacheGroup::~AppCacheGroup() { DCHECK(old_caches_.empty()); DCHECK(!newest_complete_cache_); DCHECK(!restart_update_task_); DCHECK(queued_updates_.empty()); if (update_job_) delete update_job_; DCHECK_EQ(IDLE, update_status_); service_->storage()->working_set()->RemoveGroup(this); service_->storage()->DeleteResponses( manifest_url_, newly_deletable_response_ids_); } void AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) { // If observer being added is a host that has been queued for later update, // add observer to a different observer list. AppCacheHost* host = static_cast<AppCacheHost*>(observer); if (queued_updates_.find(host) != queued_updates_.end()) queued_observers_.AddObserver(observer); else observers_.AddObserver(observer); } void AppCacheGroup::RemoveUpdateObserver(UpdateObserver* observer) { observers_.RemoveObserver(observer); queued_observers_.RemoveObserver(observer); } void AppCacheGroup::AddCache(AppCache* complete_cache) { DCHECK(complete_cache->is_complete()); complete_cache->set_owning_group(this); if (!newest_complete_cache_) { newest_complete_cache_ = complete_cache; return; } if (complete_cache->IsNewerThan(newest_complete_cache_)) { old_caches_.push_back(newest_complete_cache_); newest_complete_cache_ = complete_cache; // Update hosts of older caches to add a reference to the newest cache. for (Caches::iterator it = old_caches_.begin(); it != old_caches_.end(); ++it) { AppCache::AppCacheHosts& hosts = (*it)->associated_hosts(); for (AppCache::AppCacheHosts::iterator host_it = hosts.begin(); host_it != hosts.end(); ++host_it) { (*host_it)->SetSwappableCache(this); } } } else { old_caches_.push_back(complete_cache); } } void AppCacheGroup::RemoveCache(AppCache* cache) { DCHECK(cache->associated_hosts().empty()); if (cache == newest_complete_cache_) { AppCache* tmp_cache = newest_complete_cache_; newest_complete_cache_ = NULL; tmp_cache->set_owning_group(NULL); // may cause this group to be deleted } else { scoped_refptr<AppCacheGroup> protect(this); Caches::iterator it = std::find(old_caches_.begin(), old_caches_.end(), cache); if (it != old_caches_.end()) { AppCache* tmp_cache = *it; old_caches_.erase(it); tmp_cache->set_owning_group(NULL); // may cause group to be released } if (!is_obsolete() && old_caches_.empty() && !newly_deletable_response_ids_.empty()) { service_->storage()->DeleteResponses( manifest_url_, newly_deletable_response_ids_); newly_deletable_response_ids_.clear(); } } } void AppCacheGroup::AddNewlyDeletableResponseIds( std::vector<int64>* response_ids) { if (!is_obsolete() && old_caches_.empty()) { service_->storage()->DeleteResponses( manifest_url_, *response_ids); response_ids->clear(); return; } if (newly_deletable_response_ids_.empty()) { newly_deletable_response_ids_.swap(*response_ids); return; } newly_deletable_response_ids_.insert( newly_deletable_response_ids_.end(), response_ids->begin(), response_ids->end()); response_ids->clear(); } void AppCacheGroup::StartUpdateWithNewMasterEntry( AppCacheHost* host, const GURL& new_master_resource) { if (!update_job_) update_job_ = new AppCacheUpdateJob(service_, this); update_job_->StartUpdate(host, new_master_resource); // Run queued update immediately as an update has been started manually. if (restart_update_task_) { restart_update_task_->Cancel(); restart_update_task_ = NULL; RunQueuedUpdates(); } } void AppCacheGroup::QueueUpdate(AppCacheHost* host, const GURL& new_master_resource) { DCHECK(update_job_ && host && !new_master_resource.is_empty()); queued_updates_.insert(QueuedUpdates::value_type(host, new_master_resource)); // Need to know when host is destroyed. host->AddObserver(host_observer_.get()); // If host is already observing for updates, move host to queued observers // list so that host is not notified when the current update completes. if (FindObserver(host, observers_)) { observers_.RemoveObserver(host); queued_observers_.AddObserver(host); } } void AppCacheGroup::RunQueuedUpdates() { if (restart_update_task_) restart_update_task_ = NULL; if (queued_updates_.empty()) return; QueuedUpdates updates_to_run; queued_updates_.swap(updates_to_run); DCHECK(queued_updates_.empty()); for (QueuedUpdates::iterator it = updates_to_run.begin(); it != updates_to_run.end(); ++it) { AppCacheHost* host = it->first; host->RemoveObserver(host_observer_.get()); if (FindObserver(host, queued_observers_)) { queued_observers_.RemoveObserver(host); observers_.AddObserver(host); } if (!is_obsolete()) StartUpdateWithNewMasterEntry(host, it->second); } } bool AppCacheGroup::FindObserver(UpdateObserver* find_me, const ObserverList<UpdateObserver>& observer_list) { ObserverList<UpdateObserver>::Iterator it(observer_list); UpdateObserver* obs; while ((obs = it.GetNext()) != NULL) { if (obs == find_me) return true; } return false; } void AppCacheGroup::ScheduleUpdateRestart(int delay_ms) { DCHECK(!restart_update_task_); restart_update_task_ = NewRunnableMethod(this, &AppCacheGroup::RunQueuedUpdates); MessageLoop::current()->PostDelayedTask(FROM_HERE, restart_update_task_, delay_ms); } void AppCacheGroup::HostDestructionImminent(AppCacheHost* host) { queued_updates_.erase(host); if (queued_updates_.empty() && restart_update_task_) { restart_update_task_->Cancel(); restart_update_task_ = NULL; } } void AppCacheGroup::SetUpdateStatus(UpdateStatus status) { if (status == update_status_) return; update_status_ = status; if (status != IDLE) { DCHECK(update_job_); } else { update_job_ = NULL; // Check member variable before notifying observers about update finishing. // Observers may remove reference to group, causing group to be deleted // after the notifications. If there are queued updates, then the group // will continue to exist. bool restart_update = !queued_updates_.empty(); FOR_EACH_OBSERVER(UpdateObserver, observers_, OnUpdateComplete(this)); if (restart_update) ScheduleUpdateRestart(kUpdateRestartDelayMs); } } } // namespace appcache
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/appcache/appcache_group.h" #include <algorithm> #include "base/logging.h" #include "base/message_loop.h" #include "webkit/appcache/appcache.h" #include "webkit/appcache/appcache_host.h" #include "webkit/appcache/appcache_service.h" #include "webkit/appcache/appcache_storage.h" #include "webkit/appcache/appcache_update_job.h" namespace appcache { class AppCacheGroup; // Use this helper class because we cannot make AppCacheGroup a derived class // of AppCacheHost::Observer as it would create a circular dependency between // AppCacheHost and AppCacheGroup. class AppCacheGroup::HostObserver : public AppCacheHost::Observer { public: explicit HostObserver(AppCacheGroup* group) : group_(group) {} // Methods for AppCacheHost::Observer. void OnCacheSelectionComplete(AppCacheHost* host) {} // N/A void OnDestructionImminent(AppCacheHost* host) { group_->HostDestructionImminent(host); } private: AppCacheGroup* group_; }; AppCacheGroup::AppCacheGroup(AppCacheService* service, const GURL& manifest_url, int64 group_id) : group_id_(group_id), manifest_url_(manifest_url), update_status_(IDLE), is_obsolete_(false), newest_complete_cache_(NULL), update_job_(NULL), service_(service), restart_update_task_(NULL) { service_->storage()->working_set()->AddGroup(this); host_observer_.reset(new HostObserver(this)); } AppCacheGroup::~AppCacheGroup() { DCHECK(old_caches_.empty()); DCHECK(!newest_complete_cache_); DCHECK(!restart_update_task_); DCHECK(queued_updates_.empty()); if (update_job_) delete update_job_; DCHECK_EQ(IDLE, update_status_); service_->storage()->working_set()->RemoveGroup(this); service_->storage()->DeleteResponses( manifest_url_, newly_deletable_response_ids_); } void AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) { // If observer being added is a host that has been queued for later update, // add observer to a different observer list. AppCacheHost* host = static_cast<AppCacheHost*>(observer); if (queued_updates_.find(host) != queued_updates_.end()) queued_observers_.AddObserver(observer); else observers_.AddObserver(observer); } void AppCacheGroup::RemoveUpdateObserver(UpdateObserver* observer) { observers_.RemoveObserver(observer); queued_observers_.RemoveObserver(observer); } void AppCacheGroup::AddCache(AppCache* complete_cache) { DCHECK(complete_cache->is_complete()); complete_cache->set_owning_group(this); if (!newest_complete_cache_) { newest_complete_cache_ = complete_cache; return; } if (complete_cache->IsNewerThan(newest_complete_cache_)) { old_caches_.push_back(newest_complete_cache_); newest_complete_cache_ = complete_cache; // Update hosts of older caches to add a reference to the newest cache. for (Caches::iterator it = old_caches_.begin(); it != old_caches_.end(); ++it) { AppCache::AppCacheHosts& hosts = (*it)->associated_hosts(); for (AppCache::AppCacheHosts::iterator host_it = hosts.begin(); host_it != hosts.end(); ++host_it) { (*host_it)->SetSwappableCache(this); } } } else { old_caches_.push_back(complete_cache); } } void AppCacheGroup::RemoveCache(AppCache* cache) { DCHECK(cache->associated_hosts().empty()); if (cache == newest_complete_cache_) { AppCache* tmp_cache = newest_complete_cache_; newest_complete_cache_ = NULL; tmp_cache->set_owning_group(NULL); // may cause this group to be deleted } else { scoped_refptr<AppCacheGroup> protect(this); Caches::iterator it = std::find(old_caches_.begin(), old_caches_.end(), cache); if (it != old_caches_.end()) { AppCache* tmp_cache = *it; old_caches_.erase(it); tmp_cache->set_owning_group(NULL); // may cause group to be released } if (!is_obsolete() && old_caches_.empty() && !newly_deletable_response_ids_.empty()) { service_->storage()->DeleteResponses( manifest_url_, newly_deletable_response_ids_); newly_deletable_response_ids_.clear(); } } } void AppCacheGroup::AddNewlyDeletableResponseIds( std::vector<int64>* response_ids) { if (!is_obsolete() && old_caches_.empty()) { service_->storage()->DeleteResponses( manifest_url_, *response_ids); response_ids->clear(); return; } if (newly_deletable_response_ids_.empty()) { newly_deletable_response_ids_.swap(*response_ids); return; } newly_deletable_response_ids_.insert( newly_deletable_response_ids_.end(), response_ids->begin(), response_ids->end()); response_ids->clear(); } void AppCacheGroup::StartUpdateWithNewMasterEntry( AppCacheHost* host, const GURL& new_master_resource) { if (!update_job_) update_job_ = new AppCacheUpdateJob(service_, this); update_job_->StartUpdate(host, new_master_resource); // Run queued update immediately as an update has been started manually. if (restart_update_task_) { restart_update_task_->Cancel(); restart_update_task_ = NULL; RunQueuedUpdates(); } } void AppCacheGroup::QueueUpdate(AppCacheHost* host, const GURL& new_master_resource) { DCHECK(update_job_ && host && !new_master_resource.is_empty()); queued_updates_.insert(QueuedUpdates::value_type(host, new_master_resource)); // Need to know when host is destroyed. host->AddObserver(host_observer_.get()); // If host is already observing for updates, move host to queued observers // list so that host is not notified when the current update completes. if (FindObserver(host, observers_)) { observers_.RemoveObserver(host); queued_observers_.AddObserver(host); } } void AppCacheGroup::RunQueuedUpdates() { if (restart_update_task_) restart_update_task_ = NULL; if (queued_updates_.empty()) return; QueuedUpdates updates_to_run; queued_updates_.swap(updates_to_run); DCHECK(queued_updates_.empty()); for (QueuedUpdates::iterator it = updates_to_run.begin(); it != updates_to_run.end(); ++it) { AppCacheHost* host = it->first; host->RemoveObserver(host_observer_.get()); if (FindObserver(host, queued_observers_)) { queued_observers_.RemoveObserver(host); observers_.AddObserver(host); } if (!is_obsolete()) StartUpdateWithNewMasterEntry(host, it->second); } } bool AppCacheGroup::FindObserver(UpdateObserver* find_me, const ObserverList<UpdateObserver>& observer_list) { ObserverList<UpdateObserver>::Iterator it(observer_list); UpdateObserver* obs; while ((obs = it.GetNext()) != NULL) { if (obs == find_me) return true; } return false; } void AppCacheGroup::ScheduleUpdateRestart(int delay_ms) { DCHECK(!restart_update_task_); restart_update_task_ = NewRunnableMethod(this, &AppCacheGroup::RunQueuedUpdates); MessageLoop::current()->PostDelayedTask(FROM_HERE, restart_update_task_, delay_ms); } void AppCacheGroup::HostDestructionImminent(AppCacheHost* host) { queued_updates_.erase(host); if (queued_updates_.empty() && restart_update_task_) { restart_update_task_->Cancel(); restart_update_task_ = NULL; } } void AppCacheGroup::SetUpdateStatus(UpdateStatus status) { if (status == update_status_) return; update_status_ = status; if (status != IDLE) { DCHECK(update_job_); } else { update_job_ = NULL; // Note, this method may be called from within our destructor so we have // to be careful about calling addref and release in here. If there are // any observers, this will not be the case since each observer will have // a reference to us. if (observers_.size() || queued_observers_.size()) { // Observers may release us in these callbacks, so we protect against // deletion by adding an extra ref in this scope. scoped_refptr<AppCacheGroup> protect(this); FOR_EACH_OBSERVER(UpdateObserver, observers_, OnUpdateComplete(this)); if (!queued_updates_.empty()) ScheduleUpdateRestart(kUpdateRestartDelayMs); } } } } // namespace appcache
Fix a refcounting memory bug.
Fix a refcounting memory bug. BUG=none TEST=none Review URL: http://codereview.chromium.org/552222 git-svn-id: http://src.chromium.org/svn/trunk/src@37466 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: a861a6b11967fd92e14981d8f134b7496b591373
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
3c6fb4ef318931c2932d9d40d416e64c74679088
copasi/UI/CQTSSATimeScaleWidget.cpp
copasi/UI/CQTSSATimeScaleWidget.cpp
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQTSSATimeScaleWidget.cpp,v $ // $Revision: 1.1 $ // $Name: $ // $Author: akoenig $ // $Date: 2008/02/24 17:33:04 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQTSSATimeScaleWidget.h" #include <math.h> #include <qbitmap.h> #include <qcolor.h> #include <qtooltip.h> /* * Constructs a CScanWidgetRepeat as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQTSSATimeScaleWidget::CQTSSATimeScaleWidget(QWidget* parent, const char* name, WFlags fl) : QWidget(parent, name, fl) { if (!name) setName("CQTSSATimeScaleWidget"); mpVLayout = new QVBoxLayout(this); mpPaintWidget = new PaintWidget(this, "PaintWidget"); mpSlider = new QSlider(Qt::Horizontal, this); mpSlider->setDisabled(true); mpVLayout->addWidget(mpPaintWidget); mpVLayout->addWidget(mpSlider); mpPaintWidget->setBackgroundColor(Qt::white); mpPaintWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mpSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); QToolTip::add(mpSlider, "move Slider to set focus on prefered time scale"); // <- helpful connect(mpSlider, SIGNAL(valueChanged(int)), this, SLOT(changedInterval())); } /* * Destroys the object and frees any allocated resources */ CQTSSATimeScaleWidget::~CQTSSATimeScaleWidget() { // no need to delete child widgets, Qt does it all for us } void CQTSSATimeScaleWidget::paintTimeScale(CVector< C_FLOAT64> vector) { if (vector.size() > 0) { mpPaintWidget->mClear = false; mpSlider->setDisabled(false); mpSlider->setRange(0, (vector.size() - 1)); mpSlider->setValue(mpSlider->minValue()); mpPaintWidget->paintTimeScale(0); mpPaintWidget->mVector = vector; mpPaintWidget->repaint(); } } void CQTSSATimeScaleWidget::changedInterval() { if (mpPaintWidget->mVector.size() == 0) return; mpPaintWidget->paintTimeScale(mpSlider->value()); } void CQTSSATimeScaleWidget::clearWidget() { mpPaintWidget->mClear = true; mpPaintWidget->repaint(); mpSlider->setDisabled(true); } /* * Constructs a CScanWidgetRepeat as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ PaintWidget::PaintWidget(QWidget* parent, const char* name, WFlags fl) : QWidget(parent, name, fl) { if (!name) setName("PaintWidget"); } /* * Destroys the object and frees any allocated resources */ PaintWidget::~PaintWidget() { // no need to delete child widgets, Qt does it all for us } void PaintWidget::paintTimeScale(int select) { mSelection = select; repaint(); } void PaintWidget::paintEvent(QPaintEvent *) { if (mVector.size() == 0) return; if (mClear) return; uint i; int position; int space = 50; C_FLOAT64 scaleEnd; C_FLOAT64 scaleBegin; C_FLOAT64 maxScaleValue = (int)(log10(fabs(mVector[0])) + 1); C_FLOAT64 minScaleValue = (int)(log10(fabs(mVector[mVector.size() - 1])) - 1); C_FLOAT64 scaleValueRange = maxScaleValue - minScaleValue; QPainter paint(this); paint.save(); paint.setWindow(0, 0, 1000, 1000); paint.setFont(QFont::QFont("Courier", 15)); paint.setPen(QPen::QPen(QColor(180, 0, 0), 5)); paint.drawLine(space, 100, space, 110); paint.setPen(QPen::QPen(QColor(0, 0, 0), 1)); paint.drawText (space + 5, 110, " - negativ time scale values"); paint.setPen(QPen::QPen(QColor(0, 180, 0), 5)); paint.drawLine(space, 130, space, 140); paint.setPen(QPen::QPen(QColor(0, 0, 0), 1)); paint.drawText (space + 5, 140, " - positiv time scale values"); paint.setPen(QPen::QPen(QColor(100, 100, 100), 1)); scaleBegin = space; scaleEnd = (maxScaleValue - minScaleValue) * (1000 - 2 * space) / scaleValueRange + space; paint.drawLine((int)scaleBegin, 700, (int)scaleEnd, 700); for (i = 0; i <= scaleValueRange; i++) { position = (int)((i) * (1000 - 2 * space) / scaleValueRange + space); paint.drawLine(position, 720, position, 680); paint.drawText ((position - 4), 750, QString::number(minScaleValue + i)); } paint.setPen(QPen::QPen(QColor(0, 180, 0), 1)); for (i = 0; i < mVector.size(); i++) { position = (int)(((log10(fabs(mVector[i]))) - minScaleValue) * (1000 - 2 * space) / scaleValueRange + space); if ((uint)mSelection == (uint)(mVector.size() - 1 - i)) { if (mVector[i] < 0) paint.setPen(QPen::QPen(QColor(180, 20, 20), 4)); else paint.setPen(QPen::QPen(QColor(20, 180, 20), 4)); paint.drawLine(position, 697, position, 600); paint.setPen(QPen::QPen(QColor(200, 200, 200), 1)); paint.setFont(QFont::QFont("Courier", 20)); paint.drawLine(500, 400, position + 1, 599); paint.drawLine(500, 400, 930, 400); paint.setPen(QPen::QPen(QColor(0, 0, 0), 1)); if (mVector[i] < 0) paint.drawText (510, 380, " log10 (|" + QString::number(mVector[i]) + "|) = " + QString::number(log10(fabs(mVector[i])))); else paint.drawText (510, 380, " log10 (" + QString::number(fabs(mVector[i])) + ") = " + QString::number(log10(fabs(mVector[i])))); paint.drawText (450, 800, " log10 (X)"); } else { if (mVector[i] < 0) paint.setPen(QPen::QPen(QColor(180, 20, 20), 2)); else paint.setPen(QPen::QPen(QColor(20, 180, 20), 2)); paint.drawLine(position, 699, position, 600); } } paint.restore(); }
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQTSSATimeScaleWidget.cpp,v $ // $Revision: 1.2 $ // $Name: $ // $Author: gauges $ // $Date: 2008/07/01 11:09:50 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQTSSATimeScaleWidget.h" #include <math.h> #include <qbitmap.h> #include <qcolor.h> #include <qtooltip.h> /* * Constructs a CScanWidgetRepeat as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQTSSATimeScaleWidget::CQTSSATimeScaleWidget(QWidget* parent, const char* name, WFlags fl) : QWidget(parent, name, fl) { if (!name) setName("CQTSSATimeScaleWidget"); mpVLayout = new QVBoxLayout(this); mpPaintWidget = new PaintWidget(this, "PaintWidget"); mpSlider = new QSlider(Qt::Horizontal, this); mpSlider->setDisabled(true); mpVLayout->addWidget(mpPaintWidget); mpVLayout->addWidget(mpSlider); mpPaintWidget->setBackgroundColor(Qt::white); mpPaintWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mpSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); QToolTip::add(mpSlider, "move Slider to set focus on prefered time scale"); // <- helpful connect(mpSlider, SIGNAL(valueChanged(int)), this, SLOT(changedInterval())); } /* * Destroys the object and frees any allocated resources */ CQTSSATimeScaleWidget::~CQTSSATimeScaleWidget() { // no need to delete child widgets, Qt does it all for us } void CQTSSATimeScaleWidget::paintTimeScale(CVector< C_FLOAT64> vector) { if (vector.size() > 0) { mpPaintWidget->mClear = false; mpSlider->setDisabled(false); mpSlider->setRange(0, (vector.size() - 1)); mpSlider->setValue(mpSlider->minValue()); mpPaintWidget->paintTimeScale(0); mpPaintWidget->mVector = vector; mpPaintWidget->repaint(); } } void CQTSSATimeScaleWidget::changedInterval() { if (mpPaintWidget->mVector.size() == 0) return; mpPaintWidget->paintTimeScale(mpSlider->value()); } void CQTSSATimeScaleWidget::clearWidget() { mpPaintWidget->mClear = true; mpPaintWidget->repaint(); mpSlider->setDisabled(true); } /* * Constructs a CScanWidgetRepeat as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ PaintWidget::PaintWidget(QWidget* parent, const char* name, WFlags fl) : QWidget(parent, name, fl) { if (!name) setName("PaintWidget"); } /* * Destroys the object and frees any allocated resources */ PaintWidget::~PaintWidget() { // no need to delete child widgets, Qt does it all for us } void PaintWidget::paintTimeScale(int select) { mSelection = select; repaint(); } void PaintWidget::paintEvent(QPaintEvent *) { if (mVector.size() == 0) return; if (mClear) return; uint i; int position; int space = 50; C_FLOAT64 scaleEnd; C_FLOAT64 scaleBegin; C_FLOAT64 maxScaleValue = (int)(log10(fabs(mVector[0])) + 1); C_FLOAT64 minScaleValue = (int)(log10(fabs(mVector[mVector.size() - 1])) - 1); C_FLOAT64 scaleValueRange = maxScaleValue - minScaleValue; QPainter paint(this); paint.save(); paint.setWindow(0, 0, 1000, 1000); paint.setFont(QFont("Courier", 15)); paint.setPen(QPen(QColor(180, 0, 0), 5)); paint.drawLine(space, 100, space, 110); paint.setPen(QPen(QColor(0, 0, 0), 1)); paint.drawText (space + 5, 110, " - negativ time scale values"); paint.setPen(QPen(QColor(0, 180, 0), 5)); paint.drawLine(space, 130, space, 140); paint.setPen(QPen(QColor(0, 0, 0), 1)); paint.drawText (space + 5, 140, " - positiv time scale values"); paint.setPen(QPen(QColor(100, 100, 100), 1)); scaleBegin = space; scaleEnd = (maxScaleValue - minScaleValue) * (1000 - 2 * space) / scaleValueRange + space; paint.drawLine((int)scaleBegin, 700, (int)scaleEnd, 700); for (i = 0; i <= scaleValueRange; i++) { position = (int)((i) * (1000 - 2 * space) / scaleValueRange + space); paint.drawLine(position, 720, position, 680); paint.drawText ((position - 4), 750, QString::number(minScaleValue + i)); } paint.setPen(QPen(QColor(0, 180, 0), 1)); for (i = 0; i < mVector.size(); i++) { position = (int)(((log10(fabs(mVector[i]))) - minScaleValue) * (1000 - 2 * space) / scaleValueRange + space); if ((uint)mSelection == (uint)(mVector.size() - 1 - i)) { if (mVector[i] < 0) paint.setPen(QPen(QColor(180, 20, 20), 4)); else paint.setPen(QPen(QColor(20, 180, 20), 4)); paint.drawLine(position, 697, position, 600); paint.setPen(QPen(QColor(200, 200, 200), 1)); paint.setFont(QFont("Courier", 20)); paint.drawLine(500, 400, position + 1, 599); paint.drawLine(500, 400, 930, 400); paint.setPen(QPen(QColor(0, 0, 0), 1)); if (mVector[i] < 0) paint.drawText (510, 380, " log10 (|" + QString::number(mVector[i]) + "|) = " + QString::number(log10(fabs(mVector[i])))); else paint.drawText (510, 380, " log10 (" + QString::number(fabs(mVector[i])) + ") = " + QString::number(log10(fabs(mVector[i])))); paint.drawText (450, 800, " log10 (X)"); } else { if (mVector[i] < 0) paint.setPen(QPen(QColor(180, 20, 20), 2)); else paint.setPen(QPen(QColor(20, 180, 20), 2)); paint.drawLine(position, 699, position, 600); } } paint.restore(); }
Remove extra qualifiers to compile with SunCC.
Remove extra qualifiers to compile with SunCC.
C++
artistic-2.0
copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI
469278bb2f37d77149104657b6b2d0becdfc9238
parser/parserTemplates.cpp
parser/parserTemplates.cpp
//MIT License //Copyright 2017 Patrick Laughrea #include "parser.hpp" #include "containerSwitcher.hpp" #include "errors.hpp" #include "paramDocumentIncluder.hpp" #include "patternsContainers.hpp" #include "utils/utilsWebss.hpp" using namespace std; using namespace webss; const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented"; void setDefaultValue(Webss& value, const ParamStandard& defaultValue); template <class Parameters> Tuple makeDefaultTuple(const Parameters& params) { Tuple tuple(params.getSharedKeys()); for (Tuple::size_type i = 0; i < params.size(); ++i) setDefaultValue(tuple[i], params[i]); return tuple; } void setDefaultValue(Webss& value, const ParamStandard& defaultValue) { if (defaultValue.hasTemplateHead()) value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters()); else if (!defaultValue.hasDefaultValue()) throw runtime_error(ERROR_NO_DEFAULT); else value = Webss(defaultValue.getDefaultPointer()); } template <class Parameters> void checkDefaultValues(Tuple& tuple, const Parameters& params) { for (Tuple::size_type index = 0; index < tuple.size(); ++index) if (tuple.at(index).getTypeRaw() == WebssType::NONE) setDefaultValue(tuple[index], params[index]); } template <> void checkDefaultValues<TemplateHeadBinary::Parameters>(Tuple&, const TemplateHeadBinary::Parameters&) {} //already checked while parsing binary class ParserTemplates : public Parser { private: using ParametersStandard = TemplateHeadStandard::Parameters; using ParametersBinary = TemplateHeadBinary::Parameters; public: Webss parseTemplateBodyStandard(const ParametersStandard& params) { return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<false>(params)); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }); } Webss parseTemplateBodyText(const ParametersStandard& params) { return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }); } Webss parseTemplateBodyStandard(const ParametersStandard& params, function<Webss(const ParametersStandard& params)>&& funcTemplTupleRegular, function<Webss(const ParametersStandard& params)>&& funcTemplTupleText) { switch (nextTag = getTag(it)) { case Tag::START_DICTIONARY: return parseTemplateDictionary<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_LIST: return parseTemplateList<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_TUPLE: return funcTemplTupleRegular(params); case Tag::TEXT_TUPLE: return funcTemplTupleText(params); case Tag::NAME_START: return checkTemplateBodyEntity(params, WebssType::DICTIONARY); default: throw runtime_error(ERROR_UNEXPECTED); } } Webss parseTemplateBodyBinary(const ParametersBinary& params, function<Webss(const ParametersBinary& params)>&& funcTemplTupleRegular, function<Webss(const ParametersBinary& params)>&& funcTemplTupleText) { switch (nextTag = getTag(it)) { case Tag::START_DICTIONARY: return parseTemplateDictionary<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_LIST: return parseTemplateList<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_TUPLE: return funcTemplTupleRegular(params); case Tag::TEXT_TUPLE: return funcTemplTupleText(params); default: throw runtime_error(ERROR_UNEXPECTED); } } template <bool isText> Tuple parseTemplateTuple(const TemplateHeadStandard::Parameters& params) { Tuple tuple(params.getSharedKeys()); Tuple::size_type index = 0; ContainerSwitcher switcher(*this, ConType::TUPLE, true); if (!containerEmpty()) { do { switch (nextTag) { case Tag::EXPAND: { auto ent = parseExpandEntity(); switch (ent.getContent().getType()) { case WebssType::TUPLE: case WebssType::TUPLE_TEXT: case WebssType::TUPLE_ABSTRACT: for (const auto& item : ent.getContent().getTuple()) { tuple.at(index) = checkTemplateContainer(params, params.at(index), item); ++index; } break; default: throw runtime_error("expand entity in tuple must be a tuple"); } continue; } case Tag::SEPARATOR: //void break; case Tag::EXPLICIT_NAME: { auto name = parseNameExplicit(); nextTag = getTag(it); tuple.at(name) = isText ? Webss(parseLineString()) : parseTemplateContainer(params, params.at(name)); break; } case Tag::NAME_START: if (isText) tuple.at(index) = Webss(parseLineString()); else { auto nameType = parseNameType(); if (nameType.type == NameType::NAME) { nextTag = getTag(it); tuple.at(nameType.name) = parseTemplateContainer(params, params.at(nameType.name)); } else { if (params.at(index).hasTemplateHead()) throw runtime_error(ERROR_UNEXPECTED); switch (nameType.type) { case NameType::KEYWORD: tuple.at(index) = move(nameType.keyword); break; case NameType::ENTITY_ABSTRACT: { auto otherValue = checkAbstractEntity(nameType.entity); if (otherValue.type != OtherValue::VALUE_ONLY) throw runtime_error(ERROR_UNEXPECTED); tuple.at(index) = move(otherValue.value); break; } case NameType::ENTITY_CONCRETE: tuple.at(index) = move(nameType.entity); break; } } } break; default: tuple.at(index) = isText ? Webss(parseLineString()) : parseTemplateContainer(params, params.at(index)); break; } ++index; } while (checkNextElement()); } checkDefaultValues(tuple, params); return tuple; } private: template <class Parameters> Webss checkTemplateBodyEntity(const Parameters& params, WebssType filter) { auto value = parseValueOnly(); switch (value.getType()) { case WebssType::DICTIONARY: if (filter != WebssType::DICTIONARY) throw runtime_error(ERROR_UNEXPECTED); return checkTemplateBodyEntityDict(params, value.getDictionary()); case WebssType::LIST: if (filter == WebssType::TUPLE) throw runtime_error(ERROR_UNEXPECTED); return checkTemplateBodyEntityList(params, value.getList()); case WebssType::TUPLE: case WebssType::TUPLE_TEXT: return checkTemplateBodyEntityTuple(params, value.getTuple()); default: throw runtime_error("expected entity with template body structure"); } } template <class Parameters> Dictionary checkTemplateBodyEntityDict(const Parameters& params, const Dictionary& entityDict) { Dictionary dict; for (const auto& keyValue : entityDict) { if (keyValue.second.isList()) dict.add(keyValue.first, checkTemplateBodyEntityList(params, keyValue.second.getList())); else dict.add(keyValue.first, checkTemplateBodyEntityTuple(params, keyValue.second.getTuple())); } return dict; } template <class Parameters> List checkTemplateBodyEntityList(const Parameters& params, const List& entityList) { List list; for (const auto& elem : entityList) list.add(checkTemplateBodyEntityTuple(params, elem.getTuple())); return list; } template <class Parameters> Tuple checkTemplateBodyEntityTuple(const Parameters& params, const Tuple& entityTuple) { Tuple tuple(params.getSharedKeys(), entityTuple.getData()); checkDefaultValues(tuple, params); return tuple; } template <class Parameters> Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText) { return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict) { if (nextTag == Tag::EXPAND) expandDictionary(dict); else { string name = parseNameDictionary(); switch (nextTag = getTag(it)) { case Tag::START_LIST: dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText))); break; case Tag::START_TUPLE: dict.addSafe(move(name), funcTemplTupleRegular(params)); break; case Tag::TEXT_TUPLE: dict.addSafe(move(name), funcTemplTupleText(params)); break; case Tag::NAME_START: dict.addSafe(move(name), checkTemplateBodyEntity(params, WebssType::LIST)); break; default: throw runtime_error(ERROR_UNEXPECTED); } } }); } template <class Parameters> List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText) { return parseContainer<List, ConType::LIST>(List(), [&](List& list) { switch (nextTag) { case Tag::EXPAND: expandList(list); break; case Tag::START_TUPLE: list.add(funcTemplTupleRegular(params)); break; case Tag::TEXT_TUPLE: list.add(funcTemplTupleText(params)); break; case Tag::NAME_START: list.add(checkTemplateBodyEntity(params, WebssType::TUPLE)); break; default: throw runtime_error(ERROR_UNEXPECTED); } }); } }; Webss Parser::parseTemplate() { auto headWebss = parseTemplateHead(); switch (headWebss.getTypeRaw()) { case WebssType::BLOCK_HEAD: nextTag = getTag(it); return Block(move(headWebss.getBlockHeadRaw()), parseValueOnly()); case WebssType::TEMPLATE_HEAD_BINARY: { auto head = move(headWebss.getTemplateHeadBinaryRaw()); auto body = parseTemplateBodyBinary(head.getParameters()); return{ move(head), move(body) }; } case WebssType::TEMPLATE_HEAD_SCOPED: { auto head = move(headWebss.getTemplateHeadScopedRaw()); auto body = parseTemplateBodyScoped(head.getParameters()); return TemplateScoped(move(head), move(body)); } case WebssType::TEMPLATE_HEAD_SELF: throw runtime_error("self in a thead must be within a non-empty thead"); case WebssType::TEMPLATE_HEAD_STANDARD: { auto head = move(headWebss.getTemplateHeadStandardRaw()); auto body = parseTemplateBodyStandard(head.getParameters()); return{ move(head), move(body) }; } case WebssType::TEMPLATE_HEAD_TEXT: { auto head = move(headWebss.getTemplateHeadStandardRaw()); auto body = parseTemplateBodyText(head.getParameters()); return{ move(head), move(body), true }; } #ifdef assert default: assert(false); throw domain_error(""); #endif } } Webss Parser::parseTemplateText() { auto head = parseTemplateHeadText(); auto body = parseTemplateBodyText(head.getParameters()); return{ move(head), move(body), true }; } Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyBinary(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters&) -> Webss { throw runtime_error(ERROR_UNEXPECTED); }); } Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params) { ParamDocumentIncluder includer(ents, params); nextTag = getTag(it); return parseValueOnly(); } Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params); } Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params); } Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue) { switch (defaultValue.getTypeThead()) { case WebssType::TEMPLATE_HEAD_BINARY: return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters()); case WebssType::TEMPLATE_HEAD_SCOPED: return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters()); case WebssType::TEMPLATE_HEAD_SELF: return parseTemplateBodyStandard(params); case WebssType::TEMPLATE_HEAD_STANDARD: return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters()); case WebssType::TEMPLATE_HEAD_TEXT: return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters()); default: return parseValueOnly(); } } Tuple Parser::parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateTuple<false>(params); } Tuple Parser::parseTemplateTupleText(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateTuple<true>(params); } Webss Parser::checkTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& param, const Webss& value) { switch (param.getTypeThead()) { case WebssType::TEMPLATE_HEAD_BINARY: throw runtime_error("can't expand for a binary template"); case WebssType::TEMPLATE_HEAD_SCOPED: throw runtime_error("can't expand for a scoped template"); case WebssType::TEMPLATE_HEAD_SELF: throw runtime_error("can't expand for a self template"); case WebssType::TEMPLATE_HEAD_STANDARD: case WebssType::TEMPLATE_HEAD_TEXT: switch (value.getType()) { case WebssType::DICTIONARY: //... case WebssType::LIST: //... case WebssType::TUPLE: { const auto& params2 = param.getTemplateHeadStandard().getParameters(); Tuple tuple(params2.getSharedKeys()); Tuple::size_type index = 0; const auto& valueTuple = value.getTuple(); if (valueTuple.size() > tuple.size()) throw runtime_error("tuple to implement is too big"); for (Tuple::size_type i = 0; i < valueTuple.size(); ++i) tuple[index] = checkTemplateContainer(params2, params2[i], valueTuple[i]); return tuple; } default: throw runtime_error("template head must be implemented"); } default: return value; } }
//MIT License //Copyright 2017 Patrick Laughrea #include "parser.hpp" #include "containerSwitcher.hpp" #include "errors.hpp" #include "paramDocumentIncluder.hpp" #include "patternsContainers.hpp" #include "utils/utilsWebss.hpp" using namespace std; using namespace webss; const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented"; void setDefaultValue(Webss& value, const ParamStandard& defaultValue); template <class Parameters> Tuple makeDefaultTuple(const Parameters& params) { Tuple tuple(params.getSharedKeys()); for (Tuple::size_type i = 0; i < params.size(); ++i) setDefaultValue(tuple[i], params[i]); return tuple; } void setDefaultValue(Webss& value, const ParamStandard& defaultValue) { if (defaultValue.hasTemplateHead()) value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters()); else if (!defaultValue.hasDefaultValue()) throw runtime_error(ERROR_NO_DEFAULT); else value = Webss(defaultValue.getDefaultPointer()); } void checkDefaultValues(Tuple& tuple, const TemplateHeadStandard::Parameters& params) { for (Tuple::size_type index = 0; index < tuple.size(); ++index) if (tuple.at(index).getTypeRaw() == WebssType::NONE) setDefaultValue(tuple[index], params[index]); } class ParserTemplates : public Parser { private: using ParametersStandard = TemplateHeadStandard::Parameters; using ParametersBinary = TemplateHeadBinary::Parameters; public: Webss parseTemplateBodyStandard(const ParametersStandard& params) { return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<false>(params)); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }); } Webss parseTemplateBodyText(const ParametersStandard& params) { return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTuple<true>(params), true); }); } Webss parseTemplateBodyStandard(const ParametersStandard& params, function<Webss(const ParametersStandard& params)>&& funcTemplTupleRegular, function<Webss(const ParametersStandard& params)>&& funcTemplTupleText) { switch (nextTag = getTag(it)) { case Tag::START_DICTIONARY: return parseTemplateDictionary<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_LIST: return parseTemplateList<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_TUPLE: return funcTemplTupleRegular(params); case Tag::TEXT_TUPLE: return funcTemplTupleText(params); default: throw runtime_error(ERROR_UNEXPECTED); } } Webss parseTemplateBodyBinary(const ParametersBinary& params, function<Webss(const ParametersBinary& params)>&& funcTemplTupleRegular, function<Webss(const ParametersBinary& params)>&& funcTemplTupleText) { switch (nextTag = getTag(it)) { case Tag::START_DICTIONARY: return parseTemplateDictionary<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_LIST: return parseTemplateList<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)); case Tag::START_TUPLE: return funcTemplTupleRegular(params); case Tag::TEXT_TUPLE: return funcTemplTupleText(params); default: throw runtime_error(ERROR_UNEXPECTED); } } template <bool isText> Tuple parseTemplateTuple(const TemplateHeadStandard::Parameters& params) { Tuple tuple(params.getSharedKeys()); Tuple::size_type index = 0; ContainerSwitcher switcher(*this, ConType::TUPLE, true); if (!containerEmpty()) { do { switch (nextTag) { case Tag::EXPAND: { auto ent = parseExpandEntity(); switch (ent.getContent().getType()) { case WebssType::TUPLE: case WebssType::TUPLE_TEXT: case WebssType::TUPLE_ABSTRACT: for (const auto& item : ent.getContent().getTuple()) { tuple.at(index) = checkTemplateContainer(params, params.at(index), item); ++index; } break; default: throw runtime_error("expand entity in tuple must be a tuple"); } continue; } case Tag::SEPARATOR: //void break; case Tag::EXPLICIT_NAME: { auto name = parseNameExplicit(); nextTag = getTag(it); tuple.at(name) = isText ? Webss(parseLineString()) : parseTemplateContainer(params, params.at(name)); break; } case Tag::NAME_START: if (isText) tuple.at(index) = Webss(parseLineString()); else { auto nameType = parseNameType(); if (nameType.type == NameType::NAME) { nextTag = getTag(it); tuple.at(nameType.name) = parseTemplateContainer(params, params.at(nameType.name)); } else { if (params.at(index).hasTemplateHead()) throw runtime_error(ERROR_UNEXPECTED); switch (nameType.type) { case NameType::KEYWORD: tuple.at(index) = move(nameType.keyword); break; case NameType::ENTITY_ABSTRACT: { auto otherValue = checkAbstractEntity(nameType.entity); if (otherValue.type != OtherValue::VALUE_ONLY) throw runtime_error(ERROR_UNEXPECTED); tuple.at(index) = move(otherValue.value); break; } case NameType::ENTITY_CONCRETE: tuple.at(index) = move(nameType.entity); break; } } } break; default: tuple.at(index) = isText ? Webss(parseLineString()) : parseTemplateContainer(params, params.at(index)); break; } ++index; } while (checkNextElement()); } checkDefaultValues(tuple, params); return tuple; } private: template <class Parameters> Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText) { return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict) { if (nextTag == Tag::EXPAND) expandDictionary(dict); else { string name = parseNameDictionary(); switch (nextTag = getTag(it)) { case Tag::START_LIST: dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText))); break; case Tag::START_TUPLE: dict.addSafe(move(name), funcTemplTupleRegular(params)); break; case Tag::TEXT_TUPLE: dict.addSafe(move(name), funcTemplTupleText(params)); break; default: throw runtime_error(ERROR_UNEXPECTED); } } }); } template <class Parameters> List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText) { return parseContainer<List, ConType::LIST>(List(), [&](List& list) { switch (nextTag) { case Tag::EXPAND: expandList(list); break; case Tag::START_TUPLE: list.add(funcTemplTupleRegular(params)); break; case Tag::TEXT_TUPLE: list.add(funcTemplTupleText(params)); break; default: throw runtime_error(ERROR_UNEXPECTED); } }); } }; Webss Parser::parseTemplate() { auto headWebss = parseTemplateHead(); switch (headWebss.getTypeRaw()) { case WebssType::BLOCK_HEAD: nextTag = getTag(it); return Block(move(headWebss.getBlockHeadRaw()), parseValueOnly()); case WebssType::TEMPLATE_HEAD_BINARY: { auto head = move(headWebss.getTemplateHeadBinaryRaw()); auto body = parseTemplateBodyBinary(head.getParameters()); return{ move(head), move(body) }; } case WebssType::TEMPLATE_HEAD_SCOPED: { auto head = move(headWebss.getTemplateHeadScopedRaw()); auto body = parseTemplateBodyScoped(head.getParameters()); return TemplateScoped(move(head), move(body)); } case WebssType::TEMPLATE_HEAD_SELF: throw runtime_error("self in a thead must be within a non-empty thead"); case WebssType::TEMPLATE_HEAD_STANDARD: { auto head = move(headWebss.getTemplateHeadStandardRaw()); auto body = parseTemplateBodyStandard(head.getParameters()); return{ move(head), move(body) }; } case WebssType::TEMPLATE_HEAD_TEXT: { auto head = move(headWebss.getTemplateHeadStandardRaw()); auto body = parseTemplateBodyText(head.getParameters()); return{ move(head), move(body), true }; } #ifdef assert default: assert(false); throw domain_error(""); #endif } } Webss Parser::parseTemplateText() { auto head = parseTemplateHeadText(); auto body = parseTemplateBodyText(head.getParameters()); return{ move(head), move(body), true }; } Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyBinary(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters&) -> Webss { throw runtime_error(ERROR_UNEXPECTED); }); } Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params) { ParamDocumentIncluder includer(ents, params); nextTag = getTag(it); return parseValueOnly(); } Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params); } Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params); } Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue) { switch (defaultValue.getTypeThead()) { case WebssType::TEMPLATE_HEAD_BINARY: return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters()); case WebssType::TEMPLATE_HEAD_SCOPED: return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters()); case WebssType::TEMPLATE_HEAD_SELF: return parseTemplateBodyStandard(params); case WebssType::TEMPLATE_HEAD_STANDARD: return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters()); case WebssType::TEMPLATE_HEAD_TEXT: return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters()); default: return parseValueOnly(); } } Tuple Parser::parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateTuple<false>(params); } Tuple Parser::parseTemplateTupleText(const TemplateHeadStandard::Parameters& params) { return static_cast<ParserTemplates*>(this)->parseTemplateTuple<true>(params); } Webss Parser::checkTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& param, const Webss& value) { switch (param.getTypeThead()) { case WebssType::TEMPLATE_HEAD_BINARY: throw runtime_error("can't expand for a binary template"); case WebssType::TEMPLATE_HEAD_SCOPED: throw runtime_error("can't expand for a scoped template"); case WebssType::TEMPLATE_HEAD_SELF: throw runtime_error("can't expand for a self template"); case WebssType::TEMPLATE_HEAD_STANDARD: case WebssType::TEMPLATE_HEAD_TEXT: switch (value.getType()) { case WebssType::DICTIONARY: //... case WebssType::LIST: //... case WebssType::TUPLE: { const auto& params2 = param.getTemplateHeadStandard().getParameters(); Tuple tuple(params2.getSharedKeys()); Tuple::size_type index = 0; const auto& valueTuple = value.getTuple(); if (valueTuple.size() > tuple.size()) throw runtime_error("tuple to implement is too big"); for (Tuple::size_type i = 0; i < valueTuple.size(); ++i) tuple[index] = checkTemplateContainer(params2, params2[i], valueTuple[i]); return tuple; } default: throw runtime_error("template head must be implemented"); } default: return value; } }
Remove unnecessary code
Remove unnecessary code Code related to having a template tuple after a template has been removed. This feature was removed when the expand operator was introduced.
C++
mit
pat-laugh/websson-libraries,Pat-Laugh/WebssonProjects
d63c8ed15625b7192879107b18fd30d517936e2a
penguinRush/Background.cpp
penguinRush/Background.cpp
#include "Background.hpp" Background::Background(){ sprites = std::vector<sf::Sprite> (constant::qttBackgrounds); textures = std::vector<sf::Texture> (constant::qttBackgrounds+1); secondSprites = std::vector<sf::Sprite> (constant::qttBackgrounds); textures[0].loadFromFile("res/background.png"); textures[1].loadFromFile("res/background1.png"); textures[2].loadFromFile("res/background2.png"); textures[3].loadFromFile("res/background3.png"); for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].setTexture(textures[i]); secondSprites[i].setTexture(textures[i]); sprites[i].setPosition(0,0); secondSprites[i].setPosition(sprites[i].getLocalBounds().width,0); } textures[4].loadFromFile("res/background1_2.png"); secondSprites[0].setTexture(textures[4]); } void Background::update(float deltatime){ // /cry for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].move(-constant::backgroundSpeed[i]*deltatime, 0); secondSprites[i].move(-constant::backgroundSpeed[i]*deltatime, 0); if(sprites[i].getPosition().x <= -sprites[i].getLocalBounds().width) sprites[i].setPosition(sprites[i].getLocalBounds().width,0); if(secondSprites[i].getPosition().x <= -secondSprites[i].getLocalBounds().width) secondSprites[i].setPosition(secondSprites[i].getLocalBounds().width,0); } } void Background::draw(sf::RenderWindow &window){ for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].setScale(window.getSize().x/sprites[i].getLocalBounds().width, window.getSize().y/sprites[i].getLocalBounds().height); secondSprites[i].setScale(window.getSize().x/secondSprites[i].getLocalBounds().width, window.getSize().y/secondSprites[i].getLocalBounds().height); window.draw(sprites[i]); window.draw(secondSprites[i]); } }
#include "Background.hpp" Background::Background(){ sprites = std::vector<sf::Sprite> (constant::qttBackgrounds); textures = std::vector<sf::Texture> (constant::qttBackgrounds+1); secondSprites = std::vector<sf::Sprite> (constant::qttBackgrounds); textures[0].loadFromFile("res/background.png"); textures[1].loadFromFile("res/background1.png"); textures[2].loadFromFile("res/background2.png"); textures[3].loadFromFile("res/background3.png"); for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].setTexture(textures[i]); secondSprites[i].setTexture(textures[i]); sprites[i].setPosition(0,0); secondSprites[i].setPosition(sprites[i].getLocalBounds().width,0); } textures[4].loadFromFile("res/background1_2.png"); secondSprites[1].setTexture(textures[4]); } void Background::update(float deltatime){ // /cry for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].move(-constant::backgroundSpeed[i]*deltatime, 0); secondSprites[i].move(-constant::backgroundSpeed[i]*deltatime, 0); if(sprites[i].getPosition().x <= -sprites[i].getLocalBounds().width) sprites[i].setPosition(sprites[i].getLocalBounds().width,0); if(secondSprites[i].getPosition().x <= -secondSprites[i].getLocalBounds().width) secondSprites[i].setPosition(secondSprites[i].getLocalBounds().width,0); } } void Background::draw(sf::RenderWindow &window){ for(int i = 0; i < constant::qttBackgrounds; ++i){ sprites[i].setScale(window.getSize().x/sprites[i].getLocalBounds().width, window.getSize().y/sprites[i].getLocalBounds().height); secondSprites[i].setScale(window.getSize().x/secondSprites[i].getLocalBounds().width, window.getSize().y/secondSprites[i].getLocalBounds().height); window.draw(sprites[i]); window.draw(secondSprites[i]); } }
Update Background.cpp
Update Background.cpp
C++
mit
DigitalPenguinGames/KHack,Pinkii-/KHack,Pinkii-/KHack,DigitalPenguinGames/KHack
f8f0df840e3e1552c63d86e28476d293baf75de1
fflas-ffpack/fflas/fflas_freivalds.inl
fflas-ffpack/fflas/fflas_freivalds.inl
/* fflas/fflas_freivalds.inl * Copyright (C) 2014 Jean-Guillaume Dumas * * Written by Jean-Guillaume Dumas <[email protected]> * * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ #ifndef __FFLASFFPACK_freivalds_INL #define __FFLASFFPACK_freivalds_INL // #include "fflas-ffpack/utils/Matio.h" namespace FFLAS{ /** @brief freivalds: <b>F</b>reivalds <b>GE</b>neral <b>M</b>atrix <b>M</b>ultiply <b>R</b>andom <b>C</b>heck. * * Randomly Checks \f$C = \alpha \mathrm{op}(A) \times \mathrm{op}(B)\f$ * \param F field. * \param ta if \c ta==FflasTrans then \f$\mathrm{op}(A)=A^t\f$, else \f$\mathrm{op}(A)=A\f$, * \param tb same for matrix \p B * \param m see \p A * \param n see \p B * \param k see \p A * \param alpha scalar * \param A \f$\mathrm{op}(A)\f$ is \f$m \times k\f$ * \param B \f$\mathrm{op}(B)\f$ is \f$k \times n\f$ * \param C \f$C\f$ is \f$m \times n\f$ * \param lda leading dimension of \p A * \param ldb leading dimension of \p B * \param ldc leading dimension of \p C */ template<class Field> inline bool freivalds (const Field& F, const FFLAS_TRANSPOSE ta, const FFLAS_TRANSPOSE tb, const size_t m, const size_t n, const size_t k, const typename Field::Element alpha, typename Field::ConstElement_ptr A, const size_t lda, typename Field::ConstElement_ptr B, const size_t ldb, typename Field::ConstElement_ptr C, const size_t ldc) { typename Field::Element_ptr v, y, x; v = FFLAS::fflas_new(F,n,1); y = FFLAS::fflas_new(F,k,1); x = FFLAS::fflas_new(F,m,1); typename Field::RandIter G(F); for(size_t j=0; j<n; ++j) G.random(v[j]); // F.write(std::cerr<< "alpha:", alpha) << std::endl; // write_field(F,std::cerr<<"A:",A,m,k,lda,true) << std::endl; // write_field(F,std::cerr<<"B:",B,k,n,ldb,true) << std::endl; // write_field(F,std::cerr<<"C:",C,m,n,ldc,true) << std::endl; // y <-- 1.\mathrm{op}(B).v FFLAS::fgemv(F, tb, k,n, F.one, B, ldb, v, 1, F.zero, y, 1); // x <-- alpha.\mathrm{op}(A).y // x <-- alpha.\mathrm{op}(A).\mathrm{op}(B).v FFLAS::fgemv(F, ta, m,k, alpha, A, lda, y, 1, F.zero, x, 1); // x <-- -C.v+x =?= 0 FFLAS::fgemv(F, FFLAS::FflasNoTrans,m,n, F.mOne, C, ldc, v, 1, F.one, x, 1); bool pass=true; for(size_t j=0; j<m; ++j) pass &= F.isZero (x[j]); FFLAS::fflas_delete(y); FFLAS::fflas_delete(v); FFLAS::fflas_delete(x); return pass; } } #endif // __FFLASFFPACK_freivalds_INL
/* fflas/fflas_freivalds.inl * Copyright (C) 2014 Jean-Guillaume Dumas * * Written by Jean-Guillaume Dumas <[email protected]> * * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ #ifndef __FFLASFFPACK_freivalds_INL #define __FFLASFFPACK_freivalds_INL // #include "fflas-ffpack/utils/Matio.h" namespace FFLAS{ /** @brief freivalds: <b>F</b>reivalds <b>GE</b>neral <b>M</b>atrix <b>M</b>ultiply <b>R</b>andom <b>C</b>heck. * * Randomly Checks \f$C = \alpha \mathrm{op}(A) \times \mathrm{op}(B)\f$ * \param F field. * \param ta if \c ta==FflasTrans then \f$\mathrm{op}(A)=A^t\f$, else \f$\mathrm{op}(A)=A\f$, * \param tb same for matrix \p B * \param m see \p A * \param n see \p B * \param k see \p A * \param alpha scalar * \param A \f$\mathrm{op}(A)\f$ is \f$m \times k\f$ * \param B \f$\mathrm{op}(B)\f$ is \f$k \times n\f$ * \param C \f$C\f$ is \f$m \times n\f$ * \param lda leading dimension of \p A * \param ldb leading dimension of \p B * \param ldc leading dimension of \p C */ template<class Field> inline bool freivalds (const Field& F, const FFLAS_TRANSPOSE ta, const FFLAS_TRANSPOSE tb, const size_t m, const size_t n, const size_t k, const typename Field::Element alpha, typename Field::ConstElement_ptr A, const size_t lda, typename Field::ConstElement_ptr B, const size_t ldb, typename Field::ConstElement_ptr C, const size_t ldc) { typename Field::Element_ptr v, y, x; v = FFLAS::fflas_new(F,n,1); y = FFLAS::fflas_new(F,k,1); x = FFLAS::fflas_new(F,m,1); typename Field::RandIter G(F); for(size_t j=0; j<n; ++j) G.random(v[j]); // F.write(std::cerr<< "alpha:", alpha) << std::endl; // write_field(F,std::cerr<<"A:",A,m,k,lda,true) << std::endl; // write_field(F,std::cerr<<"B:",B,k,n,ldb,true) << std::endl; // write_field(F,std::cerr<<"C:",C,m,n,ldc,true) << std::endl; // y <-- 1.\mathrm{op}(B).v size_t Bnrows = (tb == FflasNoTrans)? k : n; size_t Bncols = (tb == FflasNoTrans)? n : k; size_t Anrows = (ta == FflasNoTrans)? m : k; size_t Ancols = (ta == FflasNoTrans)? k : m; FFLAS::fgemv(F, tb, Bnrows, Bncols, F.one, B, ldb, v, 1, F.zero, y, 1); // x <-- alpha.\mathrm{op}(A).y // x <-- alpha.\mathrm{op}(A).\mathrm{op}(B).v FFLAS::fgemv(F, ta, Anrows, Ancols, alpha, A, lda, y, 1, F.zero, x, 1); // x <-- -C.v+x =?= 0 FFLAS::fgemv(F, FFLAS::FflasNoTrans,m,n, F.mOne, C, ldc, v, 1, F.one, x, 1); bool pass=true; for(size_t j=0; j<m; ++j) pass &= F.isZero (x[j]); FFLAS::fflas_delete(y); FFLAS::fflas_delete(v); FFLAS::fflas_delete(x); return pass; } } #endif // __FFLASFFPACK_freivalds_INL
fix possible future bug with transposes in freivalds
fix possible future bug with transposes in freivalds
C++
lgpl-2.1
linbox-team/fflas-ffpack,linbox-team/fflas-ffpack,linbox-team/fflas-ffpack
75275a5596d60a53c5c9bc1550d384e9a5de8891
codecs/mozjpeg/dec/mozjpeg_dec.cpp
codecs/mozjpeg/dec/mozjpeg_dec.cpp
#include <emscripten/bind.h> #include <emscripten/val.h> #include "config.h" #include "jpeglib.h" extern "C" { #include "cdjpeg.h" } using namespace emscripten; thread_local const val Uint8ClampedArray = val::global("Uint8ClampedArray"); thread_local const val ImageData = val::global("ImageData"); val decode(std::string image_in) { uint8_t* image_buffer = (uint8_t*)image_in.c_str(); jpeg_decompress_struct cinfo; jpeg_error_mgr jerr; // Initialize the JPEG decompression object with default error handling. cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, image_buffer, image_in.length()); // Read file header, set default decompression parameters jpeg_read_header(&cinfo, TRUE); // Force RGBA decoding, even for grayscale images cinfo.out_color_space = JCS_EXT_RGBA; jpeg_start_decompress(&cinfo); // Prepare output buffer size_t output_size = cinfo.output_width * cinfo.output_height * 4; std::vector<uint8_t> output_buffer(output_size); auto stride = cinfo.output_width * 4; // Process data while (cinfo.output_scanline < cinfo.output_height) { uint8_t* ptr = &output_buffer[stride * cinfo.output_scanline]; jpeg_read_scanlines(&cinfo, &ptr, 1); } jpeg_finish_decompress(&cinfo); // Step 7: release JPEG compression object auto data = Uint8ClampedArray.new_(typed_memory_view(output_size, &output_buffer[0])); auto js_result = ImageData.new_(data, cinfo.output_width, cinfo.output_height); // This is an important step since it will release a good deal of memory. jpeg_destroy_decompress(&cinfo); // And we're done! return js_result; } EMSCRIPTEN_BINDINGS(my_module) { function("decode", &decode); }
#include <emscripten/bind.h> #include <emscripten/val.h> #include "config.h" #include "jpeglib.h" extern "C" { #include "cdjpeg.h" } using namespace emscripten; thread_local const val Uint8ClampedArray = val::global("Uint8ClampedArray"); thread_local const val ImageData = val::global("ImageData"); val decode(std::string image_in) { uint8_t* image_buffer = (uint8_t*)image_in.c_str(); jpeg_decompress_struct cinfo; jpeg_error_mgr jerr; // Initialize the JPEG decompression object with default error handling. cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, image_buffer, image_in.length()); // Read file header, set default decompression parameters jpeg_read_header(&cinfo, TRUE); // Force RGBA decoding, even for grayscale images cinfo.out_color_space = JCS_EXT_RGBA; jpeg_start_decompress(&cinfo); // Prepare output buffer size_t output_size = cinfo.output_width * cinfo.output_height * 4; std::vector<uint8_t> output_buffer(output_size); auto stride = cinfo.output_width * 4; // Process data while (cinfo.output_scanline < cinfo.output_height) { uint8_t* ptr = &output_buffer[stride * cinfo.output_scanline]; jpeg_read_scanlines(&cinfo, &ptr, 1); } jpeg_finish_decompress(&cinfo); // Step 7: release JPEG compression object auto data = Uint8ClampedArray.new_(typed_memory_view(output_buffer.size(), output_buffer.data())); auto js_result = ImageData.new_(data, cinfo.output_width, cinfo.output_height); // This is an important step since it will release a good deal of memory. jpeg_destroy_decompress(&cinfo); // And we're done! return js_result; } EMSCRIPTEN_BINDINGS(my_module) { function("decode", &decode); }
Update codecs/mozjpeg/dec/mozjpeg_dec.cpp
Update codecs/mozjpeg/dec/mozjpeg_dec.cpp Co-authored-by: Ingvar Stepanyan <[email protected]>
C++
apache-2.0
GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh
65a2fa1d95d94787564fb08e80c3e784ee72285e
copasi/plot/CPlotSpecification.cpp
copasi/plot/CPlotSpecification.cpp
/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/CPlotSpecification.cpp,v $ $Revision: 1.7 $ $Name: $ $Author: gauges $ $Date: 2004/08/10 10:58:56 $ End CVS Header */ #include "model/CModel.h" #include "CPlotSpecification.h" CPlotSpecification::CPlotSpecification(const std::string & name, const CCopasiContainer * pParent, const CPlotSpecification::Type & type): CPlotItem(name, pParent, type), mActive(true) {} CPlotSpecification::CPlotSpecification(const CPlotSpecification & src, const CCopasiContainer * pParent): CPlotItem(src, pParent), items(src.getItems()), mActive(true) {} CPlotSpecification::~CPlotSpecification() {} void CPlotSpecification::cleanup() { items.cleanup(); this->CPlotItem::cleanup(); } void CPlotSpecification::initObjects() {} CPlotItem* CPlotSpecification::createItem(const std::string & name, CPlotItem::Type type) { CPlotItem * itm = new CPlotItem(name, NULL, type); if (!items.add(itm, true)) { delete itm; return NULL; } return itm; } bool CPlotSpecification::createDefaultPlot(const CModel* model) { mActive = true; //TODO cleanup before? //title = "Default Data Plot 2D"; /*axes.resize(4); axes[QwtPlot::xBottom].active = true; axes[QwtPlot::xBottom].autoscale = true; axes[QwtPlot::xBottom].title = "X-Achse"; axes[QwtPlot::yLeft].active = true; axes[QwtPlot::yLeft].autoscale = true; axes[QwtPlot::yLeft].title = "Y-Achse"; axes[QwtPlot::xTop].active = false; axes[QwtPlot::xTop].autoscale = true; axes[QwtPlot::xTop].title = "X2-Achse"; axes[QwtPlot::yRight].active = false; axes[QwtPlot::yRight].autoscale = true; axes[QwtPlot::yRight].title = "Y2-Achse";*/ CPlotItem * plItem; std::string itemTitle; CPlotDataChannelSpec name2; CPlotDataChannelSpec name1 = model->getObject(CCopasiObjectName("Reference=Time"))->getCN(); std::cout << name1 << std::endl; unsigned C_INT32 i, imax = model->getMetabolites().size(); for (i = 0; i < imax; ++i) { name2 = model->getMetabolites()[i]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN(); itemTitle = model->getMetabolites()[i]->getObjectName(); std::cout << itemTitle << " : " << name2 << std::endl; plItem = this->createItem(itemTitle, CPlotItem::curve2d); plItem->addChannel(name1); plItem->addChannel(name2); } return true; //TODO: really check; }
/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/CPlotSpecification.cpp,v $ $Revision: 1.8 $ $Name: $ $Author: ssahle $ $Date: 2004/12/17 14:49:17 $ End CVS Header */ #include "model/CModel.h" #include "CPlotSpecification.h" CPlotSpecification::CPlotSpecification(const std::string & name, const CCopasiContainer * pParent, const CPlotSpecification::Type & type): CPlotItem(name, pParent, type), items("Curves", this), mActive(true) {} CPlotSpecification::CPlotSpecification(const CPlotSpecification & src, const CCopasiContainer * pParent): CPlotItem(src, pParent), items(src.getItems(), this), mActive(true) {} CPlotSpecification::~CPlotSpecification() {} void CPlotSpecification::cleanup() { items.cleanup(); this->CPlotItem::cleanup(); } void CPlotSpecification::initObjects() {} CPlotItem* CPlotSpecification::createItem(const std::string & name, CPlotItem::Type type) { CPlotItem * itm = new CPlotItem(name, NULL, type); if (!items.add(itm, true)) { delete itm; return NULL; } return itm; } bool CPlotSpecification::createDefaultPlot(const CModel* model) { mActive = true; //TODO cleanup before? //title = "Default Data Plot 2D"; /*axes.resize(4); axes[QwtPlot::xBottom].active = true; axes[QwtPlot::xBottom].autoscale = true; axes[QwtPlot::xBottom].title = "X-Achse"; axes[QwtPlot::yLeft].active = true; axes[QwtPlot::yLeft].autoscale = true; axes[QwtPlot::yLeft].title = "Y-Achse"; axes[QwtPlot::xTop].active = false; axes[QwtPlot::xTop].autoscale = true; axes[QwtPlot::xTop].title = "X2-Achse"; axes[QwtPlot::yRight].active = false; axes[QwtPlot::yRight].autoscale = true; axes[QwtPlot::yRight].title = "Y2-Achse";*/ CPlotItem * plItem; std::string itemTitle; CPlotDataChannelSpec name2; CPlotDataChannelSpec name1 = model->getObject(CCopasiObjectName("Reference=Time"))->getCN(); std::cout << name1 << std::endl; unsigned C_INT32 i, imax = model->getMetabolites().size(); for (i = 0; i < imax; ++i) { name2 = model->getMetabolites()[i]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN(); itemTitle = model->getMetabolites()[i]->getObjectName(); std::cout << itemTitle << " : " << name2 << std::endl; plItem = this->createItem(itemTitle, CPlotItem::curve2d); plItem->addChannel(name1); plItem->addChannel(name2); } return true; //TODO: really check; }
put the curves in the object hierarchy
put the curves in the object hierarchy
C++
artistic-2.0
jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI
305f327590dd56c76ff61d25bbbe43ba62d45ea0
core/roscpp/src/libros/service.cpp
core/roscpp/src/libros/service.cpp
/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/service.h" #include "ros/connection.h" #include "ros/service_server_link.h" #include "ros/service_manager.h" #include "ros/transport/transport_tcp.h" #include "ros/poll_manager.h" #include "ros/init.h" #include "ros/names.h" #include "ros/this_node.h" using namespace ros; bool service::exists(const std::string& service_name, bool print_failure_reason) { std::string mapped_name = names::resolve(service_name); std::string host; uint32_t port; if (ServiceManager::instance()->lookupService(mapped_name, host, port)) { TransportTCPPtr transport(new TransportTCP(&PollManager::instance()->getPollSet())); if (transport->connect(host, port)) { transport->close(); return true; } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] could not connect to host [%s:%d], waiting...", mapped_name.c_str(), host.c_str(), port); } } } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] has not been advertised, waiting...", mapped_name.c_str()); } } return false; } bool service::waitForService(const std::string& service_name, ros::Duration timeout) { std::string mapped_name = names::resolve(service_name); Time start_time = Time::now(); bool printed = false; bool result = false; while (ros::ok()) { if (exists(service_name, !printed)) { result = true; break; } else { printed = true; if (timeout >= Duration(0)) { Time current_time = Time::now(); if ((current_time - start_time) >= timeout) { return false; } } Duration(0.02).sleep(); } } if (printed && ros::ok()) { ROS_INFO("waitForService: Service [%s] is now available.", mapped_name.c_str()); } return result; } bool service::waitForService(const std::string& service_name, int32_t timeout) { return waitForService(service_name, ros::Duration(timeout / 1000.0)); }
/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/service.h" #include "ros/connection.h" #include "ros/service_server_link.h" #include "ros/service_manager.h" #include "ros/transport/transport_tcp.h" #include "ros/poll_manager.h" #include "ros/init.h" #include "ros/names.h" #include "ros/this_node.h" #include "ros/header.h" using namespace ros; bool service::exists(const std::string& service_name, bool print_failure_reason) { std::string mapped_name = names::resolve(service_name); std::string host; uint32_t port; if (ServiceManager::instance()->lookupService(mapped_name, host, port)) { TransportTCPPtr transport(new TransportTCP(0, TransportTCP::SYNCHRONOUS)); if (transport->connect(host, port)) { M_string m; m["probe"] = "1"; m["md5sum"] = "*"; m["callerid"] = this_node::getName(); m["service"] = mapped_name; boost::shared_array<uint8_t> buffer; uint32_t size = 0;; Header::write(m, buffer, size); transport->write((uint8_t*)&size, sizeof(size)); transport->write(buffer.get(), size); transport->close(); return true; } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] could not connect to host [%s:%d], waiting...", mapped_name.c_str(), host.c_str(), port); } } } else { if (print_failure_reason) { ROS_INFO("waitForService: Service [%s] has not been advertised, waiting...", mapped_name.c_str()); } } return false; } bool service::waitForService(const std::string& service_name, ros::Duration timeout) { std::string mapped_name = names::resolve(service_name); Time start_time = Time::now(); bool printed = false; bool result = false; while (ros::ok()) { if (exists(service_name, !printed)) { result = true; break; } else { printed = true; if (timeout >= Duration(0)) { Time current_time = Time::now(); if ((current_time - start_time) >= timeout) { return false; } } Duration(0.02).sleep(); } } if (printed && ros::ok()) { ROS_INFO("waitForService: Service [%s] is now available.", mapped_name.c_str()); } return result; } bool service::waitForService(const std::string& service_name, int32_t timeout) { return waitForService(service_name, ros::Duration(timeout / 1000.0)); }
Fix ros::service::exists() to set the TCP connection it's using to synchronous (#2737)
Fix ros::service::exists() to set the TCP connection it's using to synchronous (#2737) Add probe header to ros::service::exists() to prevent rospy from complaining about a failed inbound connection (#802)
C++
bsd-3-clause
ros/ros,ros/ros,ros/ros
3ee0127044a10a27576332f596d11b9baf5c816e
core/src/oned/ODDataBarReader.cpp
core/src/oned/ODDataBarReader.cpp
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * Copyright 2020 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ODDataBarReader.h" #include "BarcodeFormat.h" #include "DecoderResult.h" #include "GTIN.h" #include "ODDataBarCommon.h" #include "Result.h" #include <unordered_set> namespace ZXing::OneD { using namespace DataBar; static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight) { float modSizeRef = ModSizeFinder(v); return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef); } static bool IsLeftPair(const PatternView& v) { return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15); } static bool IsRightPair(const PatternView& v) { return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16); } static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair) { constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126}; constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81}; constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715}; constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516}; constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1}; constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8}; Array4I oddPattern = {}, evnPattern = {}; if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern)) return {}; auto calcChecksumPortion = [](const Array4I& counts) { int res = 0; for (auto it = counts.rbegin(); it != counts.rend(); ++it) res = 9 * res + *it; return res; }; int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern); if (outsideChar) { int oddSum = Reduce(oddPattern); assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw int group = (12 - oddSum) / 2; int oddWidest = OUTSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, false); int vEvn = GetValue(evnPattern, evnWidest, true); int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group]; int gSum = OUTSIDE_GSUM[group]; return {vOdd * tEvn + vEvn + gSum, checksumPortion}; } else { int evnSum = Reduce(evnPattern); assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw int group = (10 - evnSum) / 2; int oddWidest = INSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, true); int vEvn = GetValue(evnPattern, evnWidest, false); int tOdd = INSIDE_ODD_TOTAL_SUBSET[group]; int gSum = INSIDE_GSUM[group]; return {vEvn * tOdd + vOdd + gSum, checksumPortion}; } } int ParseFinderPattern(const PatternView& view, bool reversed) { static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{ {3, 8, 2, 1, 1}, {3, 5, 5, 1, 1}, {3, 3, 7, 1, 1}, {3, 1, 9, 1, 1}, {2, 7, 4, 1, 1}, {2, 5, 6, 1, 1}, {2, 3, 8, 1, 1}, {1, 5, 7, 1, 1}, {1, 3, 9, 1, 1}, }}; // TODO: c++20 constexpr inversion from FIND_PATTERN? static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{ {1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2}, {1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1}, }}; return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS); } static Pair ReadPair(const PatternView& view, bool rightPair) { if (int pattern = ParseFinderPattern(Finder(view), rightPair)) if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair)) if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) { // include left and right guards int xStart = view.pixelsInFront() - view[-1]; int xStop = view.pixelsTillEnd() + 2 * view[FULL_PAIR_SIZE]; return {outside, inside, pattern, xStart, xStop}; } return {}; } static bool ChecksumIsValid(Pair leftPair, Pair rightPair) { auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; }; int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79; int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1); if (b > 72) b--; if (b > 8) b--; return a == b; } static std::string ConstructText(Pair leftPair, Pair rightPair) { auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; }; auto res = 4537077LL * value(leftPair) + value(rightPair); if (res >= 10000000000000LL) { // Strip 2D linkage flag (GS1 Composite) if any (ISO/IEC 24724:2011 Section 5.2.3) res -= 10000000000000LL; assert(res <= 9999999999999LL); // 13 digits } auto txt = ToString(res, 13); return txt + GTIN::ComputeCheckDigit(txt); } struct State : public RowReader::DecodingState { std::unordered_set<Pair, PairHash> leftPairs; std::unordered_set<Pair, PairHash> rightPairs; }; Result DataBarReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<RowReader::DecodingState>& state) const { #if 0 // non-stacked version next = next.subView(-1, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair()); // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(2)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false); leftPair && next.shift(FULL_PAIR_SIZE) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true); rightPair && ChecksumIsValid(leftPair, rightPair)) { return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop, BarcodeFormat::DataBar}; } } } } #else if (!state) state.reset(new State); auto* prevState = static_cast<State*>(state.get()); next = next.subView(0, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair() // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(1)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false)) { leftPair.y = rowNumber; prevState->leftPairs.insert(leftPair); next.shift(FULL_PAIR_SIZE - 1); } } if (next.shift(1) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true)) { rightPair.y = rowNumber; prevState->rightPairs.insert(rightPair); next.shift(FULL_PAIR_SIZE + 2); } } } for (const auto& leftPair : prevState->leftPairs) for (const auto& rightPair : prevState->rightPairs) if (ChecksumIsValid(leftPair, rightPair)) { // Symbology identifier ISO/IEC 24724:2011 Section 9 and GS1 General Specifications 5.1.3 Figure 5.1.3-2 Result res{DecoderResult(Content(ByteArray(ConstructText(leftPair, rightPair)), {'e', '0'})) .setLineCount(EstimateLineCount(leftPair, rightPair)), EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar}; prevState->leftPairs.erase(leftPair); prevState->rightPairs.erase(rightPair); return res; } #endif // guaratee progress (see loop in ODReader.cpp) next = {}; return {}; } } // namespace ZXing::OneD
/* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * Copyright 2020 Axel Waggershauser */ // SPDX-License-Identifier: Apache-2.0 #include "ODDataBarReader.h" #include "BarcodeFormat.h" #include "DecoderResult.h" #include "GTIN.h" #include "ODDataBarCommon.h" #include "Result.h" #include <unordered_set> namespace ZXing::OneD { using namespace DataBar; static bool IsCharacterPair(PatternView v, int modsLeft, int modsRight) { float modSizeRef = ModSizeFinder(v); return IsCharacter(LeftChar(v), modsLeft, modSizeRef) && IsCharacter(RightChar(v), modsRight, modSizeRef); } static bool IsLeftPair(const PatternView& v) { return IsFinder(v[8], v[9], v[10], v[11], v[12]) && IsGuard(v[-1], v[11]) && IsCharacterPair(v, 16, 15); } static bool IsRightPair(const PatternView& v) { return IsFinder(v[12], v[11], v[10], v[9], v[8]) && IsGuard(v[9], v[21]) && IsCharacterPair(v, 15, 16); } static Character ReadDataCharacter(const PatternView& view, bool outsideChar, bool rightPair) { constexpr int OUTSIDE_EVEN_TOTAL_SUBSET[] = {1, 10, 34, 70, 126}; constexpr int INSIDE_ODD_TOTAL_SUBSET[] = {4, 20, 48, 81}; constexpr int OUTSIDE_GSUM[] = {0, 161, 961, 2015, 2715}; constexpr int INSIDE_GSUM[] = {0, 336, 1036, 1516}; constexpr int OUTSIDE_ODD_WIDEST[] = {8, 6, 4, 3, 1}; constexpr int INSIDE_ODD_WIDEST[] = {2, 4, 6, 8}; Array4I oddPattern = {}, evnPattern = {}; if (!ReadDataCharacterRaw(view, outsideChar ? 16 : 15, outsideChar == rightPair, oddPattern, evnPattern)) return {}; auto calcChecksumPortion = [](const Array4I& counts) { int res = 0; for (auto it = counts.rbegin(); it != counts.rend(); ++it) res = 9 * res + *it; return res; }; int checksumPortion = calcChecksumPortion(oddPattern) + 3 * calcChecksumPortion(evnPattern); if (outsideChar) { int oddSum = Reduce(oddPattern); assert((oddSum & 1) == 0 && oddSum <= 12 && oddSum >= 4); // checked in ReadDataCharacterRaw int group = (12 - oddSum) / 2; int oddWidest = OUTSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, false); int vEvn = GetValue(evnPattern, evnWidest, true); int tEvn = OUTSIDE_EVEN_TOTAL_SUBSET[group]; int gSum = OUTSIDE_GSUM[group]; return {vOdd * tEvn + vEvn + gSum, checksumPortion}; } else { int evnSum = Reduce(evnPattern); assert((evnSum & 1) == 0 && evnSum <= 12 && evnSum >= 4); // checked in ReadDataCharacterRaw int group = (10 - evnSum) / 2; int oddWidest = INSIDE_ODD_WIDEST[group]; int evnWidest = 9 - oddWidest; int vOdd = GetValue(oddPattern, oddWidest, true); int vEvn = GetValue(evnPattern, evnWidest, false); int tOdd = INSIDE_ODD_TOTAL_SUBSET[group]; int gSum = INSIDE_GSUM[group]; return {vEvn * tOdd + vOdd + gSum, checksumPortion}; } } int ParseFinderPattern(const PatternView& view, bool reversed) { static constexpr std::array<FixedPattern<5, 15>, 10> FINDER_PATTERNS = {{ {3, 8, 2, 1, 1}, {3, 5, 5, 1, 1}, {3, 3, 7, 1, 1}, {3, 1, 9, 1, 1}, {2, 7, 4, 1, 1}, {2, 5, 6, 1, 1}, {2, 3, 8, 1, 1}, {1, 5, 7, 1, 1}, {1, 3, 9, 1, 1}, }}; // TODO: c++20 constexpr inversion from FIND_PATTERN? static constexpr std::array<FixedPattern<5, 15>, 10> REVERSED_FINDER_PATTERNS = {{ {1, 1, 2, 8, 3}, {1, 1, 5, 5, 3}, {1, 1, 7, 3, 3}, {1, 1, 9, 1, 3}, {1, 1, 4, 7, 2}, {1, 1, 6, 5, 2}, {1, 1, 8, 3, 2}, {1, 1, 7, 5, 1}, {1, 1, 9, 3, 1}, }}; return ParseFinderPattern(view, reversed, FINDER_PATTERNS, REVERSED_FINDER_PATTERNS); } static Pair ReadPair(const PatternView& view, bool rightPair) { if (int pattern = ParseFinderPattern(Finder(view), rightPair)) if (auto outside = ReadDataCharacter(rightPair ? RightChar(view) : LeftChar(view), true, rightPair)) if (auto inside = ReadDataCharacter(rightPair ? LeftChar(view) : RightChar(view), false, rightPair)) { // include left and right guards int xStart = view.pixelsInFront() - view[-1]; int xStop = view.pixelsTillEnd() + 2 * view[FULL_PAIR_SIZE]; return {outside, inside, pattern, xStart, xStop}; } return {}; } static bool ChecksumIsValid(Pair leftPair, Pair rightPair) { auto checksum = [](Pair p) { return p.left.checksum + 4 * p.right.checksum; }; int a = (checksum(leftPair) + 16 * checksum(rightPair)) % 79; int b = 9 * (std::abs(leftPair.finder) - 1) + (std::abs(rightPair.finder) - 1); if (b > 72) b--; if (b > 8) b--; return a == b; } static std::string ConstructText(Pair leftPair, Pair rightPair) { auto value = [](Pair p) { return 1597 * p.left.value + p.right.value; }; auto res = 4537077LL * value(leftPair) + value(rightPair); if (res >= 10000000000000LL) { // Strip 2D linkage flag (GS1 Composite) if any (ISO/IEC 24724:2011 Section 5.2.3) res -= 10000000000000LL; assert(res <= 9999999999999LL); // 13 digits } auto txt = ToString(res, 13); return txt + GTIN::ComputeCheckDigit(txt); } struct State : public RowReader::DecodingState { std::unordered_set<Pair, PairHash> leftPairs; std::unordered_set<Pair, PairHash> rightPairs; }; Result DataBarReader::decodePattern(int rowNumber, PatternView& next, std::unique_ptr<RowReader::DecodingState>& state) const { #if 0 // non-stacked version next = next.subView(-1, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair()); // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(2)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false); leftPair && next.shift(FULL_PAIR_SIZE) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true); rightPair && ChecksumIsValid(leftPair, rightPair)) { return {ConstructText(leftPair, rightPair), rowNumber, leftPair.xStart, rightPair.xStop, BarcodeFormat::DataBar}; } } } } #else if (!state) state.reset(new State); auto* prevState = static_cast<State*>(state.get()); next = next.subView(0, FULL_PAIR_SIZE + 1); // +1 reflects the guard pattern on the right, see IsRightPair() // yes: the first view we test is at index 1 (black bar at 0 would be the guard pattern) while (next.shift(1)) { if (IsLeftPair(next)) { if (auto leftPair = ReadPair(next, false)) { leftPair.y = rowNumber; prevState->leftPairs.insert(leftPair); next.shift(FULL_PAIR_SIZE - 1); } } if (next.shift(1) && IsRightPair(next)) { if (auto rightPair = ReadPair(next, true)) { rightPair.y = rowNumber; prevState->rightPairs.insert(rightPair); next.shift(FULL_PAIR_SIZE + 2); } } } for (const auto& leftPair : prevState->leftPairs) for (const auto& rightPair : prevState->rightPairs) if (ChecksumIsValid(leftPair, rightPair)) { // Symbology identifier ISO/IEC 24724:2011 Section 9 and GS1 General Specifications 5.1.3 Figure 5.1.3-2 Result res{DecoderResult(Content(ByteArray(ConstructText(leftPair, rightPair)), {'e', '0'})) .setLineCount(EstimateLineCount(leftPair, rightPair)), EstimatePosition(leftPair, rightPair), BarcodeFormat::DataBar}; prevState->leftPairs.erase(leftPair); prevState->rightPairs.erase(rightPair); return res; } #endif // guarantee progress (see loop in ODReader.cpp) next = {}; return {}; } } // namespace ZXing::OneD
comment typo
ODDataBarReader: comment typo
C++
apache-2.0
nu-book/zxing-cpp,nu-book/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp,huycn/zxing-cpp,huycn/zxing-cpp,nu-book/zxing-cpp
20b771c7eaa62dcfd58f2c9fa5c4e8660b72d579
cpp/tests/unit-tests/UtilTest.cpp
cpp/tests/unit-tests/UtilTest.cpp
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <limits> #include <string> #include <vector> #include "tests/utils/Gtest.h" #include "tests/utils/Gmock.h" #include "joynr/Util.h" using namespace joynr; namespace { void validatePartitionsAlwaysThrow(bool allowWildCard) { EXPECT_THROW(util::validatePartitions({""}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({" "}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"_"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"not_valid"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"ä"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "_ ./$"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "_ ./$"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"+a", "bc"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "bc"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "*"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"abc", "*", "123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*", ""}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"a+b", "123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"a*b", "123"}, allowWildCard), std::invalid_argument); } } // anonymous namespace TEST(UtilTest, createMulticastIdWithPartitions) { EXPECT_EQ("providerParticipantId/multicastName/partition0/partition1", util::createMulticastId( "providerParticipantId", "multicastName", {"partition0", "partition1"})); } TEST(UtilTest, createMulticastIdWithoutPartitions) { std::vector<std::string> partitions; EXPECT_EQ("providerParticipantId/multicastName", util::createMulticastId("providerParticipantId", "multicastName", partitions)); } TEST(UtilTest, validateValidPartitionsWithWildCardsDoesNotThrow) { bool allowWildCard = true; EXPECT_NO_THROW(util::validatePartitions( {"valid", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "+", "123"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "+", "*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "+", "+"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "+", "123"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "123", "*"}, allowWildCard)); allowWildCard = false; EXPECT_NO_THROW(util::validatePartitions( {"valid", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}, allowWildCard)); } TEST(UtilTest, validateValidPartitionsWithWildCardsThrows) { bool doNotAllowWildCard = false; EXPECT_THROW(util::validatePartitions({"*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"+"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "+", "123"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"abc", "+", "*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "+", "+"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "+", "123"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "123", "*"}, doNotAllowWildCard), std::invalid_argument); validatePartitionsAlwaysThrow(doNotAllowWildCard); validatePartitionsAlwaysThrow(!doNotAllowWildCard); } TEST(UtilTest, checkFileExists) { EXPECT_TRUE(util::fileExists(".")); EXPECT_TRUE(util::fileExists("..")); EXPECT_FALSE(util::fileExists(util::createUuid() + "_NOT_EXISTING_FILE")); const std::string fileToTest = "TEST_ThisFileIsCreatedAndDeletedAtRuntime.check"; EXPECT_FALSE(util::fileExists(fileToTest)); util::saveStringToFile(fileToTest, " "); EXPECT_TRUE(util::fileExists(fileToTest)); std::remove(fileToTest.c_str()); EXPECT_FALSE(util::fileExists(fileToTest)); } TEST(UtilTest, extractParticipantIdFromMulticastId) { EXPECT_EQ("participantId", util::extractParticipantIdFromMulticastId( "participantId/multicastname/partition1/partition2")); EXPECT_EQ("participantId", util::extractParticipantIdFromMulticastId("participantId/")); EXPECT_THROW(util::extractParticipantIdFromMulticastId("participantId"), std::invalid_argument); } TEST(UtilTest, isAdditionOnPointerSafe) { constexpr std::uintptr_t address = std::numeric_limits<std::uintptr_t>::max() - 1; // no overflow int payloadLength = 0x1; EXPECT_FALSE(util::isAdditionOnPointerCausesOverflow(address, payloadLength)); // overflow payloadLength = 0x2; EXPECT_TRUE(util::isAdditionOnPointerCausesOverflow(address, payloadLength)); } TEST(UtilTest, setContainsSet) { const std::set<std::string> haystack{"s1", "s2", "s3", "s4"}; std::set<std::string> needles{"s1", "s2", "s3", "s4"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s2"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s1", "s2"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s1", "s4"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); } TEST(UtilTest, setDoesNotContainSet) { const std::set<std::string> haystack{"s1", "s2", "s3"}; std::set<std::string> needles{"s1", "s3", "s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s1", "s2", "s3", "s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s0", "s1", "s3"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); } TEST(UtilTest, getErrorStringDeliversCorrectString) { int i; // check whether MT-safe util::getErrorString() returns // same error strings as standard MT-unsafe strerror() for (i = 0; i < 255; i++) { char* str = strerror(i); if (str != NULL) { std::string s1(str); std::string s2(util::getErrorString(i)); EXPECT_EQ(s1, s2); } } }
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include <limits> #include <string> #include <vector> #include "muesli/detail/IncrementalTypeList.h" #include "tests/utils/Gmock.h" #include "tests/utils/Gtest.h" #include "joynr/Util.h" #include <boost/filesystem.hpp> #include <boost/mpl/find.hpp> #include <fstream> using namespace joynr; namespace { void validatePartitionsAlwaysThrow(bool allowWildCard) { EXPECT_THROW(util::validatePartitions({""}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({" "}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"_"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"not_valid"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"ä"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "_ ./$"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "_ ./$"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"+a", "bc"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "bc"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "*"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*", "+"}, allowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"abc", "*", "123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*", ""}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"a+b", "123"}, allowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"a*b", "123"}, allowWildCard), std::invalid_argument); } } // anonymous namespace TEST(UtilTest, createMulticastIdWithPartitions) { EXPECT_EQ("providerParticipantId/multicastName/partition0/partition1", util::createMulticastId( "providerParticipantId", "multicastName", {"partition0", "partition1"})); } TEST(UtilTest, createMulticastIdWithoutPartitions) { std::vector<std::string> partitions; EXPECT_EQ("providerParticipantId/multicastName", util::createMulticastId("providerParticipantId", "multicastName", partitions)); } TEST(UtilTest, validateValidPartitionsWithWildCardsDoesNotThrow) { bool allowWildCard = true; EXPECT_NO_THROW(util::validatePartitions( {"valid", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "+", "123"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"abc", "+", "*"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "+", "+"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "+", "123"}, allowWildCard)); EXPECT_NO_THROW(util::validatePartitions({"+", "123", "*"}, allowWildCard)); allowWildCard = false; EXPECT_NO_THROW(util::validatePartitions( {"valid", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}, allowWildCard)); } TEST(UtilTest, validateValidPartitionsWithWildCardsThrows) { bool doNotAllowWildCard = false; EXPECT_THROW(util::validatePartitions({"*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"+"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW(util::validatePartitions({"abc", "+", "123"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"abc", "+", "*"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "+", "+"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "+", "123"}, doNotAllowWildCard), std::invalid_argument); EXPECT_THROW( util::validatePartitions({"+", "123", "*"}, doNotAllowWildCard), std::invalid_argument); validatePartitionsAlwaysThrow(doNotAllowWildCard); validatePartitionsAlwaysThrow(!doNotAllowWildCard); } TEST(UtilTest, checkFileExists) { EXPECT_TRUE(util::fileExists(".")); EXPECT_TRUE(util::fileExists("..")); EXPECT_FALSE(util::fileExists(util::createUuid() + "_NOT_EXISTING_FILE")); const std::string fileToTest = "TEST_ThisFileIsCreatedAndDeletedAtRuntime.check"; EXPECT_FALSE(util::fileExists(fileToTest)); util::saveStringToFile(fileToTest, " "); EXPECT_TRUE(util::fileExists(fileToTest)); std::remove(fileToTest.c_str()); EXPECT_FALSE(util::fileExists(fileToTest)); } TEST(UtilTest, extractParticipantIdFromMulticastId) { EXPECT_EQ("participantId", util::extractParticipantIdFromMulticastId( "participantId/multicastname/partition1/partition2")); EXPECT_EQ("participantId", util::extractParticipantIdFromMulticastId("participantId/")); EXPECT_THROW(util::extractParticipantIdFromMulticastId("participantId"), std::invalid_argument); } TEST(UtilTest, isAdditionOnPointerSafe) { constexpr std::uintptr_t address = std::numeric_limits<std::uintptr_t>::max() - 1; // no overflow int payloadLength = 0x1; EXPECT_FALSE(util::isAdditionOnPointerCausesOverflow(address, payloadLength)); // overflow payloadLength = 0x2; EXPECT_TRUE(util::isAdditionOnPointerCausesOverflow(address, payloadLength)); } TEST(UtilTest, setContainsSet) { const std::set<std::string> haystack{"s1", "s2", "s3", "s4"}; std::set<std::string> needles{"s1", "s2", "s3", "s4"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s2"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s1", "s2"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); needles = {"s1", "s4"}; EXPECT_TRUE(util::setContainsSet(haystack, needles)); } TEST(UtilTest, setDoesNotContainSet) { const std::set<std::string> haystack{"s1", "s2", "s3"}; std::set<std::string> needles{"s1", "s3", "s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s1", "s2", "s3", "s4"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); needles = {"s0", "s1", "s3"}; EXPECT_FALSE(util::setContainsSet(haystack, needles)); } TEST(UtilTest, getErrorStringDeliversCorrectString) { int i; // check whether MT-safe util::getErrorString() returns // same error strings as standard MT-unsafe strerror() for (i = 0; i < 255; i++) { char* str = strerror(i); if (str != NULL) { std::string s1(str); std::string s2(util::getErrorString(i)); EXPECT_EQ(s1, s2); } } } TEST(UtilTest, createValidUuid) { std::string uuid1 = util::createUuid(); std::string uuid2 = util::createUuid(); EXPECT_NE(uuid1, uuid2); } TEST(UtilTest, vectorContainsContainsValue) { const std::vector<std::string> stringValues{"s1", "s2", "s3", "s4"}; std::string stringValue = "s1"; EXPECT_TRUE(util::vectorContains(stringValues, stringValue)); const std::vector<int> intValues{1, 2, 3, 4, 5}; int intValue = 3; EXPECT_TRUE(util::vectorContains(intValues, intValue)); const std::vector<double> doubleValues{1.2, 2.3, 3.4, 4.5, 5.6, 6.7}; double doubleValue = 1.2; EXPECT_TRUE(util::vectorContains(doubleValues, doubleValue)); } TEST(UtilTest, vectorDoesNotContainValue) { const std::vector<std::string> stringValues{"s1", "s2", "s3", "s4y"}; std::string stringValue = "s5"; EXPECT_FALSE(util::vectorContains(stringValues, stringValue)); const std::vector<int> intValues{1, 2, 3, 4, 5}; int intValue = 7; EXPECT_FALSE(util::vectorContains(intValues, intValue)); const std::vector<double> doubleValues{1.2, 2.3, 3.4, 4.5, 5.6, 6.7}; double doubleValue = 0.5; EXPECT_FALSE(util::vectorContains(doubleValues, doubleValue)); } TEST(UtilTest, removeAllTest) { std::vector<int> intValues{1, 2, 3, 4, 5}; EXPECT_EQ(intValues.size(), 5); util::removeAll(intValues, 3); EXPECT_EQ(std::find(intValues.begin(), intValues.end(), 3), intValues.end()); EXPECT_EQ(intValues.size(), 4); std::vector<double> doubleValues{1.1, 1.1, 1.1, 1.1}; EXPECT_EQ(doubleValues.size(), 4); util::removeAll(doubleValues, 1.1); EXPECT_EQ(std::find(doubleValues.begin(), doubleValues.end(), 1.1), doubleValues.end()); EXPECT_EQ(doubleValues.size(), 0); std::vector<std::string> stringValues{"s1", "s2", "s3", "s4", "s4"}; EXPECT_EQ(stringValues.size(), 5); std::string valueToBeremoved = "s4"; util::removeAll(stringValues, valueToBeremoved); EXPECT_EQ(std::find(stringValues.begin(), stringValues.end(), valueToBeremoved), stringValues.end()); EXPECT_EQ(stringValues.size(), 3); } TEST(UtilTest, asWeakPtrTest) { std::shared_ptr<int> intPtr = std::make_shared<int>(10); EXPECT_EQ(intPtr.use_count(), 1); std::shared_ptr<int> secondPtr = intPtr; EXPECT_EQ(intPtr.use_count(), 2); auto weakPtr = util::as_weak_ptr(intPtr); EXPECT_EQ(intPtr.use_count(), 2); } TEST(UtilTest, compareValuesTest) { int intValue1 = 10; int intValue2 = 10; int intValue3 = 20; EXPECT_TRUE(util::compareValues(intValue1, intValue2)); EXPECT_TRUE(util::compareValues(intValue1, intValue1)); EXPECT_FALSE(util::compareValues(intValue1, intValue3)); double doubleValue1 = 5.5; double doubleValue2 = 5.5; double doubleValue3 = 5.9; EXPECT_TRUE(util::compareValues(doubleValue1, doubleValue2)); EXPECT_TRUE(util::compareValues(doubleValue1, doubleValue1)); EXPECT_FALSE(util::compareValues(doubleValue1, doubleValue3)); } TEST(UtilTest, invokeOnTest) { typedef boost::mpl::vector<int, long, float, unsigned> vectorTypes; std::vector<std::string> typeIDs; typeIDs.push_back(typeid(int).name()); typeIDs.push_back(typeid(long).name()); typeIDs.push_back(typeid(float).name()); typeIDs.push_back(typeid(unsigned).name()); unsigned int counter = 0; auto fun = [&counter, &typeIDs](auto&& holder) { using iterType = std::decay_t<decltype(holder)>; EXPECT_TRUE((typeIDs[counter].compare(typeid(iterType).name()) == 0)); counter++; return true; }; util::invokeOn<vectorTypes>(fun); } TEST(UtilTest, fileExistsTest) { std::string filename = "test.out"; std::ofstream g(filename); g.close(); EXPECT_TRUE(util::fileExists(filename)); std::remove(filename.c_str()); EXPECT_FALSE(util::fileExists(filename)); } TEST(UtilTest, writeToFileTestSyncFalse) { std::string filename = "test.out"; std::string stringToWrite = "this is first line\nthis is secondLine\r"; util::writeToFile(filename, stringToWrite, std::ios::out, false); std::stringstream buffer; std::ifstream f(filename, std::ios_base::binary); buffer << f.rdbuf(); f.close(); EXPECT_EQ(stringToWrite, buffer.str()); std::remove(filename.c_str()); } TEST(UtilTest, writeToFileTestSyncTrue) { std::string filename = "test.out"; std::string stringToWrite = "this is first line\nthis is secondLine\r"; util::writeToFile(filename, stringToWrite, std::ios::out, true); std::stringstream buffer; std::ifstream f(filename, std::ios_base::binary); buffer << f.rdbuf(); f.close(); EXPECT_EQ(stringToWrite, buffer.str()); std::remove(filename.c_str()); } TEST(UtilTest, writeToFileException) { std::string folderName = "test"; boost::filesystem::create_directory(folderName); EXPECT_THROW( util::writeToFile(folderName, "testString", std::ios::out, false), std::runtime_error); std::remove(folderName.c_str()); } TEST(UtilTest, loadStringFromFileTest) { std::string filename = "test.out"; std::string stringToWrite = "this is first line\nthis is secondLine"; std::ofstream g(filename); g << stringToWrite; g.close(); std::string readString = util::loadStringFromFile(filename); EXPECT_EQ(stringToWrite, readString); g.open(filename, std::ios_base::app); g << stringToWrite; g.close(); stringToWrite.append(stringToWrite); readString = util::loadStringFromFile(filename); EXPECT_EQ(stringToWrite, readString); std::remove(filename.c_str()); } TEST(UtilTest, loadStringFromFileSizeExceeded) { std::string filename = "sparseFile"; std::ofstream g(filename, std::ios::binary | std::ios::out); std::uint64_t size = 2 * 1024 * 1024 * 1024UL + 10; g.seekp((std::streamoff)size); g.write("", 1); g.close(); EXPECT_THROW(util::loadStringFromFile(filename), std::runtime_error); std::remove(filename.c_str()); } TEST(UtilTest, loadStringFromFileNoFileTest) { std::string filename = "test.out"; std::string stringToWrite = "this is first line\nthis is secondLine\n"; EXPECT_THROW(util::loadStringFromFile(filename), std::runtime_error); }
Add remaining tests for Util.h
[C++] Add remaining tests for Util.h
C++
apache-2.0
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
94666d616188d23fb377be7d072552f5d03fc8c5
crawler/main/signal.generator.cpp
crawler/main/signal.generator.cpp
/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "sdkconfig.h" #include <cmath> #define ms(x) (x/portTICK_PERIOD_MS) #define DUMP_VAR_d(x) \ printf("%s:%d:%s=<%d>\n",__FILE__,__LINE__,#x,x) #define DUMP_VAR_f(x) \ printf("%s:%d:%s=<%f>\n",__FILE__,__LINE__,#x,x) static const int iConstSampleRate = 100; static const int iConstSampleDelay = 1000/iConstSampleRate; static const double pi = std::acos(-1); static char signal(int counter) { double x = 2 * pi * (double)counter/(double)iConstSampleRate; double y = sin(x); DUMP_VAR_d(counter); DUMP_VAR_f(x); DUMP_VAR_f(y); return y *126; } static int gSamplerCounter = 0; void signal_generator_task(void *pvParameter) { while(true) { auto sign = signal(gSamplerCounter++%iConstSampleRate); vTaskDelay(ms(iConstSampleDelay)); } } extern "C" void signal_generator_app_main() { xTaskCreate(&signal_generator_task, "signal_generator_task", 2048, NULL, 5, NULL); }
/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "esp_system.h" #include "sdkconfig.h" #include <cmath> #define ms(x) (x/portTICK_PERIOD_MS) #define DUMP_VAR_d(x) \ printf("%s:%d:%s=<%d>\n",__FILE__,__LINE__,#x,x) #define DUMP_VAR_f(x) \ printf("%s:%d:%s=<%f>\n",__FILE__,__LINE__,#x,x) static const int iConstSampleRate = 100; static const int iConstSampleDelay = 1000/iConstSampleRate; static const double pi = std::acos(-1); static char signal(int counter) { double x = 2 * pi * (double)counter/(double)iConstSampleRate; double y = sin(x); DUMP_VAR_d(counter); DUMP_VAR_f(x); DUMP_VAR_f(y); return y *126; } static int gSamplerCounter = 0; void signal_generator_task(void *pvParameter) { while(true) { auto sign = signal(gSamplerCounter++%iConstSampleRate); vTaskDelay(ms(iConstSampleDelay)); } } extern "C" void signal_generator_app_main() { xTaskCreate(&signal_generator_task, "signal_generator_task", 2048, NULL, 5, NULL); }
Update signal.generator.cpp
Update signal.generator.cpp
C++
mit
RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler,RobotTeam2/esp32.crawler
7e1617b1a80a2edad10aa4a0212918ea1d46724d
yahttp/router.cpp
yahttp/router.cpp
/* @file * @brief Concrete implementation of Router */ #include "yahttp.hpp" #include "router.hpp" namespace YaHTTP { typedef funcptr::tuple<int,int> TDelim; // router is defined here. YaHTTP::Router Router::router; void Router::map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name) { std::string method2 = method; bool isopen=false; // add into vector for(std::string::const_iterator i = url.begin(); i != url.end(); i++) { if (*i == '<' && isopen) throw Error("Invalid URL mask, cannot have < after <"); if (*i == '<') isopen = true; if (*i == '>' && !isopen) throw Error("Invalid URL mask, cannot have > without < first"); if (*i == '>') isopen = false; } std::transform(method2.begin(), method2.end(), method2.begin(), ::toupper); routes.push_back(funcptr::make_tuple(method2, url, handler, name)); }; bool Router::route(Request *req, Response *resp) { std::map<std::string, TDelim> params; int pos1,pos2; std::string pname; bool matched = false; THandlerFunction handler; // iterate routes for(TRouteList::iterator i = routes.begin(); !matched && i != routes.end(); i++) { int pos1,pos2,k1,k2,k3; std::string pname; std::string method, url; funcptr::tie(method, url, handler, IGNORE) = *i; if (method.empty() == false && req->method != method) continue; // no match on method // see if we can't match the url params.clear(); // simple matcher func for(k1=0, k2=0; k1 < url.size() && k2 < req->url.path.size(); ) { if (url[k1] == '<') { pos1 = k2; k3 = k1+1; // start of parameter while(k1 < url.size() && url[k1] != '>') k1++; pname = std::string(url.begin()+k3, url.begin()+k1); // then we also look it on the url if (pname[0]=='*') { pname = pname.substr(1); // this matches whatever comes after it, basically end of string pos2 = req->url.path.size(); matched = true; params[pname] = funcptr::tie(pos1,pos2); k1 = url.size(); k2 = req->url.path.size(); break; } else { // match until url[k1] while(k2 < req->url.path.size() && req->url.path[k2] != url[k1+1]) k2++; pos2 = k2; params[pname] = funcptr::tie(pos1,pos2); } k2--; } else if (url[k1] == '*') { matched = true; break; } else if (url[k1] != req->url.path[k2]) { break; } k1++; k2++; } // ensure. if (url[k1] != req->url.path[k2]) matched = false; else matched = true; } if (!matched) { return false; } // no route req->params.clear(); for(std::map<std::string, TDelim>::iterator i = params.begin(); i != params.end(); i++) { int p1,p2; funcptr::tie(p1,p2) = i->second; req->params[i->first] = std::string(req->url.path.begin() + p1, req->url.path.begin() + p2); } return handler(req,resp); }; void Router::printRoutes(std::ostream &os) { for(TRouteList::iterator i = routes.begin(); i != routes.end(); i++) { #ifdef HAVE_CXX11 os << std::get<0>(*i) << " " << std::get<1>(*i) << " " << std::get<3>(*i) << std::endl; #else os << i->get<0>() << " " << i->get<1>() << " " << i->get<3>() << std::endl; #endif } }; std::pair<std::string,std::string> Router::urlFor(const std::string &name, const strstr_map_t& arguments) { std::ostringstream path; std::string mask,method,result; int k1,k2,k3; bool found = false; for(TRouteList::iterator i = routes.begin(); !found && i != routes.end(); i++) { #ifdef HAVE_CXX11 if (std::get<3>(*i) == name) { mask = std::get<1>(*i); method = std::get<0>(*i); found = true; } #else if (i->get<3>() == name) { mask = i->get<1>(); method = i->get<0>(); found = true; } #endif } if (!found) throw Error("Route not found"); for(k1=0,k3=0;k1<mask.size();k1++) { if (mask[k1] == '<') { std::string pname; strstr_map_t::const_iterator pptr; k2=k1; while(k1<mask.size() && mask[k1]!='>') k1++; path << mask.substr(k3,k2-k3); if (mask[k2+1] == '*') pname = std::string(mask.begin() + k2 + 2, mask.begin() + k1); else pname = std::string(mask.begin() + k2 + 1, mask.begin() + k1); if ((pptr = arguments.find(pname)) != arguments.end()) path << pptr->second; k3 = k1+1; } else if (mask[k1] == '*') { // ready k3++; continue; } } std::cout << mask.substr(k3) << std::endl; path << mask.substr(k3); result = path.str(); return std::make_pair(method, result); } };
/* @file * @brief Concrete implementation of Router */ #include "yahttp.hpp" #include "router.hpp" namespace YaHTTP { typedef funcptr::tuple<int,int> TDelim; // router is defined here. YaHTTP::Router Router::router; void Router::map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name) { std::string method2 = method; bool isopen=false; // add into vector for(std::string::const_iterator i = url.begin(); i != url.end(); i++) { if (*i == '<' && isopen) throw Error("Invalid URL mask, cannot have < after <"); if (*i == '<') isopen = true; if (*i == '>' && !isopen) throw Error("Invalid URL mask, cannot have > without < first"); if (*i == '>') isopen = false; } std::transform(method2.begin(), method2.end(), method2.begin(), ::toupper); routes.push_back(funcptr::make_tuple(method2, url, handler, name)); }; bool Router::route(Request *req, Response *resp) { std::map<std::string, TDelim> params; int pos1,pos2; std::string pname; bool matched = false; THandlerFunction handler; std::string rname; // iterate routes for(TRouteList::iterator i = routes.begin(); !matched && i != routes.end(); i++) { int pos1,pos2,k1,k2,k3; std::string pname; std::string method, url; funcptr::tie(method, url, handler, rname) = *i; if (method.empty() == false && req->method != method) continue; // no match on method // see if we can't match the url params.clear(); // simple matcher func for(k1=0, k2=0; k1 < url.size() && k2 < req->url.path.size(); ) { if (url[k1] == '<') { pos1 = k2; k3 = k1+1; // start of parameter while(k1 < url.size() && url[k1] != '>') k1++; pname = std::string(url.begin()+k3, url.begin()+k1); // then we also look it on the url if (pname[0]=='*') { pname = pname.substr(1); // this matches whatever comes after it, basically end of string pos2 = req->url.path.size(); matched = true; params[pname] = funcptr::tie(pos1,pos2); k1 = url.size(); k2 = req->url.path.size(); break; } else { // match until url[k1] while(k2 < req->url.path.size() && req->url.path[k2] != url[k1+1]) k2++; pos2 = k2; params[pname] = funcptr::tie(pos1,pos2); } k2--; } else if (url[k1] == '*') { matched = true; break; } else if (url[k1] != req->url.path[k2]) { break; } k1++; k2++; } // ensure. if (url[k1] != req->url.path[k2]) matched = false; else matched = true; } if (!matched) { return false; } // no route req->params.clear(); for(std::map<std::string, TDelim>::iterator i = params.begin(); i != params.end(); i++) { int p1,p2; funcptr::tie(p1,p2) = i->second; std::string value(req->url.path.begin() + p1, req->url.path.begin() + p2); value = Utility::decodeURL(value); req->params[i->first] = value; } req->routeName = rname; return handler(req,resp); }; void Router::printRoutes(std::ostream &os) { for(TRouteList::iterator i = routes.begin(); i != routes.end(); i++) { #ifdef HAVE_CXX11 std::streamsize ss = os.width(); std::ios::fmtflags ff = os.setf(std::ios::left); os.width(10); os << std::get<0>(*i); os.width(50); os << std::get<1>(*i); os.width(ss); os.setf(ff); os << " " << std::get<3>(*i); os << std::endl; #else os << i->get<0>() << " " << i->get<1>() << " " << i->get<3>() << std::endl; #endif } }; std::pair<std::string,std::string> Router::urlFor(const std::string &name, const strstr_map_t& arguments) { std::ostringstream path; std::string mask,method,result; int k1,k2,k3; bool found = false; for(TRouteList::iterator i = routes.begin(); !found && i != routes.end(); i++) { #ifdef HAVE_CXX11 if (std::get<3>(*i) == name) { mask = std::get<1>(*i); method = std::get<0>(*i); found = true; } #else if (i->get<3>() == name) { mask = i->get<1>(); method = i->get<0>(); found = true; } #endif } if (!found) throw Error("Route not found"); for(k1=0,k3=0;k1<mask.size();k1++) { if (mask[k1] == '<') { std::string pname; strstr_map_t::const_iterator pptr; k2=k1; while(k1<mask.size() && mask[k1]!='>') k1++; path << mask.substr(k3,k2-k3); if (mask[k2+1] == '*') pname = std::string(mask.begin() + k2 + 2, mask.begin() + k1); else pname = std::string(mask.begin() + k2 + 1, mask.begin() + k1); if ((pptr = arguments.find(pname)) != arguments.end()) path << Utility::encodeURL(pptr->second); k3 = k1+1; } else if (mask[k1] == '*') { // ready k3++; continue; } } std::cout << mask.substr(k3) << std::endl; path << mask.substr(k3); result = path.str(); return std::make_pair(method, result); } };
Add route name to request, pretty print routes, encode URL parameters
Add route name to request, pretty print routes, encode URL parameters
C++
mit
cmouse/yahttp,cmouse/yahttp,cmouse/yahttp
3175d088d0a878926bac2cc6021037b5049912ea
yahttp/router.hpp
yahttp/router.hpp
#ifndef _YAHTTP_ROUTER_HPP #define _YAHTTP_ROUTER_HPP 1 /* @file * @brief Defines router class and support structures */ #ifdef HAVE_CXX11 #include <functional> #include <tuple> #define HAVE_CPP_FUNC_PTR #define IGNORE std::ignore namespace funcptr = std; #else #ifdef HAVE_BOOST #include <boost/function.hpp> #include <boost/tuple/tuple.hpp> #define IGNORE boost::tuples::ignore namespace funcptr = boost; #define HAVE_CPP_FUNC_PTR #else #warning "You need to configure with boost or have C++11 capable compiler for router" #endif #endif #ifdef HAVE_CPP_FUNC_PTR #include <vector> #include <utility> namespace YaHTTP { typedef funcptr::function <void(Request* req, Response* resp)> THandlerFunction; //!< Handler function pointer typedef funcptr::tuple<std::string, std::string, THandlerFunction, std::string> TRoute; //!< Route tuple (method, urlmask, handler, name) typedef std::vector<TRoute> TRouteList; //!< List of routes in order of evaluation /*! Implements simple router. This class implements a router for masked urls. The URL mask syntax is as of follows /&lt;masked&gt;/url&lt;number&gt;/&lt;hi&gt;.&lt;format&gt; You can use &lt;*param&gt; to denote that everything will be matched and consumed into the parameter, including slash (/). Use &lt;*&gt; to denote that URL is consumed but not stored. Note that only path is matched, scheme, host and url parameters are ignored. */ class Router { private: Router() {}; static Router router; //<! Singleton instance of Router public: void map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name); //<! Instance method for mapping urls bool route(Request *req, THandlerFunction& handler); //<! Instance method for performing routing void printRoutes(std::ostream &os); //<! Instance method for printing routes std::pair<std::string, std::string> urlFor(const std::string &name, const strstr_map_t& arguments); //<! Instance method for generating paths /*! Map an URL. If method is left empty, it will match any method. Name is also optional, but needed if you want to find it for making URLs */ static void Map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map(method, url, handler, name); }; static void Get(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("GET", url, handler, name); }; //<! Helper for mapping GET static void Post(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("POST", url, handler, name); }; //<! Helper for mapping POST static void Put(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PUT", url, handler, name); }; //<! Helper for mapping PUT static void Patch(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PATCH", url, handler, name); }; //<! Helper for mapping PATCH static void Delete(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("DELETE", url, handler, name); }; //<! Helper for mapping DELETE static void Any(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("", url, handler, name); }; //<! Helper for mapping any method static bool Route(Request *req, THandlerFunction& handler) { return router.route(req, handler); }; //<! Performs routing based on req->url.path static void PrintRoutes(std::ostream &os) { router.printRoutes(os); }; //<! Prints all known routes to given output stream static std::pair<std::string, std::string> URLFor(const std::string &name, const strstr_map_t& arguments) { return router.urlFor(name,arguments); }; //<! Generates url from named route and arguments. Missing arguments are assumed empty static const TRouteList& GetRoutes() { return router.routes; } //<! Reference to route list TRouteList routes; //<! Instance variable for routes }; }; #endif #endif
#ifndef _YAHTTP_ROUTER_HPP #define _YAHTTP_ROUTER_HPP 1 /* @file * @brief Defines router class and support structures */ #ifdef HAVE_CXX11 #include <functional> #include <tuple> #define HAVE_CPP_FUNC_PTR #define IGNORE std::ignore namespace funcptr = std; #else #ifdef HAVE_BOOST #include <boost/function.hpp> #include <boost/tuple/tuple.hpp> #define IGNORE boost::tuples::ignore namespace funcptr = boost; #define HAVE_CPP_FUNC_PTR #else #warning "You need to configure with boost or have C++11 capable compiler for router" #endif #endif #ifdef HAVE_CPP_FUNC_PTR #include <vector> #include <utility> namespace YaHTTP { typedef funcptr::function <void(Request* req, Response* resp)> THandlerFunction; //!< Handler function pointer typedef funcptr::tuple<std::string, std::string, THandlerFunction, std::string> TRoute; //!< Route tuple (method, urlmask, handler, name) typedef std::vector<TRoute> TRouteList; //!< List of routes in order of evaluation /*! Implements simple router. This class implements a router for masked urls. The URL mask syntax is as of follows /&lt;masked&gt;/url&lt;number&gt;/&lt;hi&gt;.&lt;format&gt; You can use &lt;*param&gt; to denote that everything will be matched and consumed into the parameter, including slash (/). Use &lt;*&gt; to denote that URL is consumed but not stored. Note that only path is matched, scheme, host and url parameters are ignored. */ class Router { private: Router() {}; static Router router; //<! Singleton instance of Router public: void map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name); //<! Instance method for mapping urls bool route(Request *req, THandlerFunction& handler); //<! Instance method for performing routing void printRoutes(std::ostream &os); //<! Instance method for printing routes std::pair<std::string, std::string> urlFor(const std::string &name, const strstr_map_t& arguments); //<! Instance method for generating paths /*! Map an URL. If method is left empty, it will match any method. Name is also optional, but needed if you want to find it for making URLs */ static void Map(const std::string& method, const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map(method, url, handler, name); }; static void Get(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("GET", url, handler, name); }; //<! Helper for mapping GET static void Post(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("POST", url, handler, name); }; //<! Helper for mapping POST static void Put(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PUT", url, handler, name); }; //<! Helper for mapping PUT static void Patch(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("PATCH", url, handler, name); }; //<! Helper for mapping PATCH static void Delete(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("DELETE", url, handler, name); }; //<! Helper for mapping DELETE static void Any(const std::string& url, THandlerFunction handler, const std::string& name = "") { router.map("", url, handler, name); }; //<! Helper for mapping any method static bool Route(Request *req, THandlerFunction& handler) { return router.route(req, handler); }; //<! Performs routing based on req->url.path static void PrintRoutes(std::ostream &os) { router.printRoutes(os); }; //<! Prints all known routes to given output stream static std::pair<std::string, std::string> URLFor(const std::string &name, const strstr_map_t& arguments) { return router.urlFor(name,arguments); }; //<! Generates url from named route and arguments. Missing arguments are assumed empty static const TRouteList& GetRoutes() { return router.routes; } //<! Reference to route list static void Clear() { router.routes.clear(); } //<! Clear all routes TRouteList routes; //<! Instance variable for routes }; }; #endif #endif
Add clear method to clear routes
router: Add clear method to clear routes
C++
mit
cmouse/yahttp,cmouse/yahttp,cmouse/yahttp
d96eda42e531eabf57d4d16288d2a8af680af4ca
PWGDQ/dielectron/macrosLMEE/AddTask_shin_pPb.C
PWGDQ/dielectron/macrosLMEE/AddTask_shin_pPb.C
AliAnalysisTask *AddTask_shin_pPb(){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_shin_pPb", "No analysis manager found."); return 0; } //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0); //Get the current train configuration // TString trainConfig=gSystem->Getenv("CONFIG_FILE"); //set config file name TString configBasePath("$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/"); TString configFile("Config_shin_pPb.C"); TString configFilePath(configBasePath+configFile); // TString list=gSystem->Getenv("LIST"); //create task and add it to the manager AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDieData"); if (!hasMC ) task->UsePhysicsSelection(); task->SetTriggerMask(AliVEvent::kINT7); mgr->AddTask(task); //load dielectron configuration file gROOT->LoadMacro(configFile.Data()); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliDielectron *dile=Config_shin_pPb(i); if (!dile) continue; task->AddDielectron(dile); } //Add event filter AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0"); eventCuts->SetRequireVertex(); eventCuts->SetMinVtxContributors(1); eventCuts->SetVertexZ(-10.,10.); task->SetEventFilter(eventCuts); //create output container TString containerName = "hayashi_lowmass.root"; AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("tree_lowmass", TTree::Class(), AliAnalysisManager::kExchangeContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("Histos_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("CF_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer("sweber_EventStat", TH1D::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; }
AliAnalysisTask *AddTask_shin_pPb(){ //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_shin_pPb", "No analysis manager found."); return 0; } //Do we have an MC handler? Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0); //Get the current train configuration // TString trainConfig=gSystem->Getenv("CONFIG_FILE"); //set config file name TString configBasePath("$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/"); TString configFile("Config_shin_pPb.C"); TString configFilePath(configBasePath+configFile); // TString list=gSystem->Getenv("LIST"); //create task and add it to the manager AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDieData"); if (!hasMC ) task->UsePhysicsSelection(); task->SetTriggerMask(AliVEvent::kINT7); mgr->AddTask(task); //load dielectron configuration file gROOT->LoadMacro(configFilePath.Data()); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliDielectron *dile=Config_shin_pPb(i); if (!dile) continue; task->AddDielectron(dile); } //Add event filter AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0"); eventCuts->SetRequireVertex(); eventCuts->SetMinVtxContributors(1); eventCuts->SetVertexZ(-10.,10.); task->SetEventFilter(eventCuts); //create output container TString containerName = "hayashi_lowmass.root"; AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("tree_lowmass", TTree::Class(), AliAnalysisManager::kExchangeContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist1 = mgr->CreateContainer("Histos_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist2 = mgr->CreateContainer("CF_diel_lowmass", TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); AliAnalysisDataContainer *cOutputHist3 = mgr->CreateContainer("sweber_EventStat", TH1D::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 0, coutput1 ); mgr->ConnectOutput(task, 1, cOutputHist1); mgr->ConnectOutput(task, 2, cOutputHist2); mgr->ConnectOutput(task, 3, cOutputHist3); return task; }
update ShinIchi's Add Task
update ShinIchi's Add Task
C++
bsd-3-clause
pchrista/AliPhysics,mkrzewic/AliPhysics,dmuhlhei/AliPhysics,dmuhlhei/AliPhysics,sebaleh/AliPhysics,mvala/AliPhysics,amatyja/AliPhysics,kreisl/AliPhysics,mvala/AliPhysics,adriansev/AliPhysics,amatyja/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,fbellini/AliPhysics,preghenella/AliPhysics,adriansev/AliPhysics,carstooon/AliPhysics,mkrzewic/AliPhysics,dstocco/AliPhysics,preghenella/AliPhysics,mazimm/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,pchrista/AliPhysics,pbuehler/AliPhysics,sebaleh/AliPhysics,hcab14/AliPhysics,hcab14/AliPhysics,mvala/AliPhysics,jmargutt/AliPhysics,sebaleh/AliPhysics,lcunquei/AliPhysics,pbuehler/AliPhysics,yowatana/AliPhysics,AudreyFrancisco/AliPhysics,nschmidtALICE/AliPhysics,AudreyFrancisco/AliPhysics,sebaleh/AliPhysics,alisw/AliPhysics,amatyja/AliPhysics,victor-gonzalez/AliPhysics,pbatzing/AliPhysics,hzanoli/AliPhysics,btrzecia/AliPhysics,adriansev/AliPhysics,AudreyFrancisco/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,dlodato/AliPhysics,AMechler/AliPhysics,hcab14/AliPhysics,SHornung1/AliPhysics,dlodato/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,mbjadhav/AliPhysics,jgronefe/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,AMechler/AliPhysics,btrzecia/AliPhysics,kreisl/AliPhysics,mazimm/AliPhysics,hzanoli/AliPhysics,victor-gonzalez/AliPhysics,mpuccio/AliPhysics,aaniin/AliPhysics,ALICEHLT/AliPhysics,rbailhac/AliPhysics,mbjadhav/AliPhysics,victor-gonzalez/AliPhysics,amatyja/AliPhysics,akubera/AliPhysics,mkrzewic/AliPhysics,AMechler/AliPhysics,mazimm/AliPhysics,mazimm/AliPhysics,jgronefe/AliPhysics,rderradi/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,amatyja/AliPhysics,btrzecia/AliPhysics,AudreyFrancisco/AliPhysics,jmargutt/AliPhysics,mpuccio/AliPhysics,akubera/AliPhysics,rihanphys/AliPhysics,ALICEHLT/AliPhysics,ALICEHLT/AliPhysics,kreisl/AliPhysics,AudreyFrancisco/AliPhysics,yowatana/AliPhysics,victor-gonzalez/AliPhysics,aaniin/AliPhysics,preghenella/AliPhysics,fbellini/AliPhysics,fcolamar/AliPhysics,nschmidtALICE/AliPhysics,ppribeli/AliPhysics,ALICEHLT/AliPhysics,fbellini/AliPhysics,dlodato/AliPhysics,fbellini/AliPhysics,mbjadhav/AliPhysics,mpuccio/AliPhysics,aaniin/AliPhysics,amatyja/AliPhysics,amaringarcia/AliPhysics,akubera/AliPhysics,mbjadhav/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,dstocco/AliPhysics,fcolamar/AliPhysics,SHornung1/AliPhysics,pbuehler/AliPhysics,akubera/AliPhysics,AMechler/AliPhysics,mkrzewic/AliPhysics,btrzecia/AliPhysics,kreisl/AliPhysics,amaringarcia/AliPhysics,pbatzing/AliPhysics,jgronefe/AliPhysics,alisw/AliPhysics,pbuehler/AliPhysics,hcab14/AliPhysics,mbjadhav/AliPhysics,mvala/AliPhysics,jmargutt/AliPhysics,yowatana/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,rihanphys/AliPhysics,rihanphys/AliPhysics,btrzecia/AliPhysics,akubera/AliPhysics,btrzecia/AliPhysics,amaringarcia/AliPhysics,pbatzing/AliPhysics,lfeldkam/AliPhysics,ALICEHLT/AliPhysics,hzanoli/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,hzanoli/AliPhysics,fbellini/AliPhysics,lfeldkam/AliPhysics,lfeldkam/AliPhysics,AudreyFrancisco/AliPhysics,pbatzing/AliPhysics,btrzecia/AliPhysics,pbuehler/AliPhysics,fbellini/AliPhysics,mvala/AliPhysics,dmuhlhei/AliPhysics,rbailhac/AliPhysics,kreisl/AliPhysics,dmuhlhei/AliPhysics,mbjadhav/AliPhysics,mbjadhav/AliPhysics,victor-gonzalez/AliPhysics,pbuehler/AliPhysics,jgronefe/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,rbailhac/AliPhysics,lfeldkam/AliPhysics,pchrista/AliPhysics,ppribeli/AliPhysics,dmuhlhei/AliPhysics,mkrzewic/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,dmuhlhei/AliPhysics,rderradi/AliPhysics,alisw/AliPhysics,jgronefe/AliPhysics,jgronefe/AliPhysics,aaniin/AliPhysics,carstooon/AliPhysics,mvala/AliPhysics,aaniin/AliPhysics,rihanphys/AliPhysics,mkrzewic/AliPhysics,nschmidtALICE/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,SHornung1/AliPhysics,nschmidtALICE/AliPhysics,sebaleh/AliPhysics,sebaleh/AliPhysics,dstocco/AliPhysics,pchrista/AliPhysics,ppribeli/AliPhysics,carstooon/AliPhysics,pbatzing/AliPhysics,dlodato/AliPhysics,hzanoli/AliPhysics,dlodato/AliPhysics,mkrzewic/AliPhysics,hcab14/AliPhysics,mazimm/AliPhysics,victor-gonzalez/AliPhysics,pbuehler/AliPhysics,yowatana/AliPhysics,AMechler/AliPhysics,dstocco/AliPhysics,rihanphys/AliPhysics,yowatana/AliPhysics,preghenella/AliPhysics,rderradi/AliPhysics,rbailhac/AliPhysics,preghenella/AliPhysics,dstocco/AliPhysics,AMechler/AliPhysics,SHornung1/AliPhysics,lcunquei/AliPhysics,mazimm/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,carstooon/AliPhysics,dlodato/AliPhysics,ppribeli/AliPhysics,ppribeli/AliPhysics,carstooon/AliPhysics,fbellini/AliPhysics,sebaleh/AliPhysics,akubera/AliPhysics,lcunquei/AliPhysics,pchrista/AliPhysics,lfeldkam/AliPhysics,yowatana/AliPhysics,AMechler/AliPhysics,hcab14/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,lcunquei/AliPhysics,rderradi/AliPhysics,pbatzing/AliPhysics,pbatzing/AliPhysics,lcunquei/AliPhysics,aaniin/AliPhysics,carstooon/AliPhysics,dstocco/AliPhysics,ppribeli/AliPhysics,fcolamar/AliPhysics,ALICEHLT/AliPhysics,jmargutt/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,rderradi/AliPhysics,jmargutt/AliPhysics,dmuhlhei/AliPhysics,dstocco/AliPhysics,AudreyFrancisco/AliPhysics,aaniin/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,mvala/AliPhysics,dlodato/AliPhysics,ALICEHLT/AliPhysics,hzanoli/AliPhysics,lfeldkam/AliPhysics,carstooon/AliPhysics,adriansev/AliPhysics,hcab14/AliPhysics,lcunquei/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,rihanphys/AliPhysics,akubera/AliPhysics,preghenella/AliPhysics,jmargutt/AliPhysics,amaringarcia/AliPhysics,preghenella/AliPhysics,rihanphys/AliPhysics,amatyja/AliPhysics,mazimm/AliPhysics,yowatana/AliPhysics,victor-gonzalez/AliPhysics,lfeldkam/AliPhysics,rderradi/AliPhysics,jmargutt/AliPhysics,rderradi/AliPhysics,jgronefe/AliPhysics
42913fb3f6429c37f5dd3cfc289b25e426306049
core/src/processing/failover.cc
core/src/processing/failover.cc
/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QCoreApplication> #include <QMutexLocker> #include <QReadLocker> #include <QTimer> #include <QWriteLocker> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/exceptions/with_pointer.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/multiplexing/subscriber.hh" #include "com/centreon/broker/processing/failover.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::processing; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] is_out true if the failover thread is an output thread. */ failover::failover(bool is_out) : _initial(true), _is_out(is_out), _retry_interval(30), _immediate(true), _should_exit(false), _should_exitm(QMutex::Recursive) { if (_is_out) _from = QSharedPointer<io::stream>(new multiplexing::subscriber); else _to = QSharedPointer<io::stream>(new multiplexing::publisher); } /** * Copy constructor. * * @param[in] f Object to copy. */ failover::failover(failover const& f) : QThread(), io::stream(), _endpoint(f._endpoint), _failover(f._failover), _initial(true), _is_out(f._is_out), _retry_interval(f._retry_interval), _immediate(true), _should_exit(false), _should_exitm(QMutex::Recursive) { { QMutexLocker lock(&f._datam); _data = f._data; } { QWriteLocker lock(&f._fromm); _from = f._from; } { QWriteLocker lock(&f._tom); _to = f._to; } } /** * Destructor. */ failover::~failover() {} /** * Assignment operator. * * @param[in] f Object to copy. * * @return This object. */ failover& failover::operator=(failover const& f) { if (this != &f) { _endpoint = f._endpoint; _failover = f._failover; _is_out = f._is_out; _retry_interval = f._retry_interval; { QMutexLocker lock(&f._datam); _data = f._data; } { QWriteLocker lock(&f._fromm); _from = f._from; } { QWriteLocker lock(&f._tom); _to = f._to; } } return (*this); } /** * Get retry interval. * * @return Failover thread retry interval. */ time_t failover::get_retry_interval() const throw () { return (_retry_interval); } /** * Stop or start processing. * * @param[in] in true to process inputs. * @param[in] out true to process outputs. */ void failover::process(bool in, bool out) { // Set exit flag. QMutexLocker lock(&_should_exitm); _immediate = (!in && out); _should_exit = (!in || !out); // Quit event loop. if ((!in || !out) && isRunning()) { QTimer::singleShot(0, this, SLOT(quit())); QCoreApplication::processEvents(); } // Full delayed shutdown. if (!in && !out) { _endpoint->close(); bool tweaked_in(_failover.isNull()); QReadLocker lock(&_fromm); if (!_from.isNull()) _from->process(tweaked_in, false); } // Single delayed shutdown. else if (in && !out) { _endpoint->close(); QReadLocker lock(&_fromm); if (!_from.isNull()) _from->process(true, false); } // Immediate shutdown. else if (!in && out) { _endpoint->close(); QList<QSharedPointer<QMutexLocker> > locks; bool all_failover_not_running(true); failover* last(this); for (QSharedPointer<failover> fo = _failover; !fo.isNull(); fo = fo->_failover) { QSharedPointer<QMutexLocker> lock(new QMutexLocker(&fo->_should_exitm)); all_failover_not_running = all_failover_not_running && !fo->isRunning(); locks.push_back(lock); last = fo.data(); } // Shutdown subscriber. if (all_failover_not_running) { QReadLocker rl(&last->_fromm); if (!last->_from.isNull()) last->_from->process(false, true); } // Wait for thread to terminate. locks.clear(); lock.unlock(); QThread::wait(); process(true, true); } // Reinitialization. else { QReadLocker rl(&_fromm); if (!_from.isNull()) _from->process(true, true); } return ; } /** * Read data. * * @param[out] data Data buffer. * @param[out] type Data type. */ QSharedPointer<io::data> failover::read() { // Read retained data. QSharedPointer<io::data> data; QMutexLocker exit_lock(&_should_exitm); if (isRunning() && QThread::currentThread() != this) { // Release thread lock. exit_lock.unlock(); // Read data from destination. logging::debug(logging::low) << "failover: reading retained data from failover thread"; bool caught(false); QReadLocker tom(&_tom); try { if (!_to.isNull()) data = _to->read(); logging::debug(logging::low) << "failover: got retained event from failover thread"; } catch (...) { caught = true; } // End of destination is reached, shutdown this thread. if (caught || data.isNull()) { logging::debug(logging::low) << "failover: could not get event from failover thread"; logging::info(logging::medium) << "failover: requesting failover thread termination"; // Reset lock. _to.clear(); _tom.unlock(); // Exit this thread immediately. process(false, true); // Recursive data reading. data = this->read(); } } // Fetch next available event. else { // Release thread lock. exit_lock.unlock(); // Try the one retained event. QMutexLocker lock(&_datam); if (!_data.isNull()) { data = _data; _data.clear(); lock.unlock(); } // Read from source. else { lock.unlock(); QReadLocker fromm(&_fromm); data = _from->read(); } logging::debug(logging::low) << "failover: got event from normal source"; } return (data); } /** * Thread core function. */ void failover::run() { // Check endpoint. if (_endpoint.isNull()) { logging::error(logging::high) << "failover: attempt to run a " \ "thread with a non-existent endpoint"; return ; } // Launch subfailover to fetch retained data. if (_initial && !_failover.isNull()) { connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit())); connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit())); connect(&*_failover, SIGNAL(finished()), SLOT(quit())); connect(&*_failover, SIGNAL(terminated()), SLOT(quit())); _failover->start(); exec(); disconnect( &*_failover, SIGNAL(exception_caught()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(initial_lock()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(finished()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(terminated()), this, SLOT(quit())); _initial = false; } // Failover should continue as long as not exit request was received. logging::debug(logging::medium) << "failover: launching loop"; QMutexLocker exit_lock(&_should_exitm); _should_exit = false; while (!_should_exit) { exit_lock.unlock(); try { // Close previous endpoint if any and then open it. logging::debug(logging::medium) << "failover: opening endpoint"; QReadWriteLock* rwl; QSharedPointer<io::stream>* s; if (_is_out) { rwl = &_tom; s = &_to; } else { rwl = &_fromm; s = &_from; } { QWriteLocker wl(rwl); s->clear(); wl.unlock(); QSharedPointer<io::stream> tmp(_endpoint->open()); wl.relock(); emit initial_lock(); *s = tmp; if (s->isNull()) { // Retry connection. logging::debug(logging::medium) << "failover: resulting stream is nul, retrying"; exit_lock.relock(); continue ; } } // Process input and output. logging::debug(logging::medium) << "failover: launching feeding"; QSharedPointer<io::data> data; exit_lock.relock(); while (!_should_exit || !_immediate) { exit_lock.unlock(); try { { QReadLocker lock(&_fromm); if (!_from.isNull()) data = _from->read(); } if (data.isNull()) { exit_lock.relock(); _immediate = true; _should_exit = true; exit_lock.unlock(); } else { QWriteLocker lock(&_tom); if (!_to.isNull()) _to->write(data); } } catch (exceptions::msg const& e) { try { throw (exceptions::with_pointer(e, data)); } catch (exceptions::with_pointer const& e) { throw ; } catch (...) {} throw ; } data.clear(); exit_lock.relock(); } } catch (exceptions::with_pointer const& e) { logging::error(logging::high) << e.what(); if (!e.ptr().isNull() && !_failover.isNull() && !_failover->isRunning()) _failover->write(e.ptr()); } catch (io::exceptions::shutdown const& e) { logging::info(logging::medium) << "failover: a stream has shutdown: " << e.what(); } catch (exceptions::msg const& e) { logging::error(logging::high) << e.what(); } catch (std::exception const& e) { logging::error(logging::high) << "failover: standard library error: " << e.what(); } catch (...) { logging::error(logging::high) << "failover: unknown error caught in processing thread"; } emit exception_caught(); if (_is_out) { QWriteLocker lock(&_tom); _to.clear(); } else { QWriteLocker lock(&_fromm); _from.clear(); } // Relock thread lock. exit_lock.relock(); if (!_failover.isNull() && !_failover->isRunning() && !_should_exit) { connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit())); connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit())); connect(&*_failover, SIGNAL(finished()), SLOT(quit())); connect(&*_failover, SIGNAL(terminated()), SLOT(quit())); _failover->start(); exec(); disconnect( &*_failover, SIGNAL(exception_caught()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(initial_lock()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(finished()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(terminated()), this, SLOT(quit())); } if (!_should_exit) { // Unlock thread lock. exit_lock.unlock(); logging::info(logging::medium) << "failover: sleeping " << _retry_interval << " seconds before reconnection"; QTimer::singleShot(_retry_interval * 1000, this, SLOT(quit())); exec(); // Relock thread lock. exit_lock.relock(); } } return ; } /** * Set thread endpoint. * * @param[in] endp Thread endpoint. */ void failover::set_endpoint(QSharedPointer<io::endpoint> endp) { _endpoint = endp; return ; } /** * Set the thread's failover. * * @param[in] fo Thread's failover. */ void failover::set_failover(QSharedPointer<failover> fo) { _failover = fo; if (!fo.isNull() && _is_out) { // failover object will act as input for output threads. QWriteLocker lock(&_fromm); _from = _failover; } return ; } /** * Set the connection retry interval. * * @param[in] retry_interval Time to wait between two connection * attempts. */ void failover::set_retry_interval(time_t retry_interval) { _retry_interval = retry_interval; return ; } /** * Wait for this thread to terminate along with other failovers. * * @param[in] time Maximum time to wait for thread termination. */ bool failover::wait(unsigned long time) { if (!_failover.isNull()) _failover->wait(time); return (this->QThread::wait(time)); } /** * Write data. * * @param[in] d Unused. * * @return Does not return, throw an exception. */ void failover::write(QSharedPointer<io::data> d) { QMutexLocker lock(&_datam); _data = d; return ; }
/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <QCoreApplication> #include <QMutexLocker> #include <QReadLocker> #include <QTimer> #include <QWriteLocker> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/exceptions/with_pointer.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/multiplexing/publisher.hh" #include "com/centreon/broker/multiplexing/subscriber.hh" #include "com/centreon/broker/processing/failover.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::processing; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] is_out true if the failover thread is an output thread. */ failover::failover(bool is_out) : _initial(true), _is_out(is_out), _retry_interval(30), _immediate(true), _should_exit(false), _should_exitm(QMutex::Recursive) { if (_is_out) _from = QSharedPointer<io::stream>(new multiplexing::subscriber); else _to = QSharedPointer<io::stream>(new multiplexing::publisher); } /** * Copy constructor. * * @param[in] f Object to copy. */ failover::failover(failover const& f) : QThread(), io::stream(), _endpoint(f._endpoint), _failover(f._failover), _initial(true), _is_out(f._is_out), _retry_interval(f._retry_interval), _immediate(true), _should_exit(false), _should_exitm(QMutex::Recursive) { { QMutexLocker lock(&f._datam); _data = f._data; } { QWriteLocker lock(&f._fromm); _from = f._from; } { QWriteLocker lock(&f._tom); _to = f._to; } } /** * Destructor. */ failover::~failover() {} /** * Assignment operator. * * @param[in] f Object to copy. * * @return This object. */ failover& failover::operator=(failover const& f) { if (this != &f) { _endpoint = f._endpoint; _failover = f._failover; _is_out = f._is_out; _retry_interval = f._retry_interval; { QMutexLocker lock(&f._datam); _data = f._data; } { QWriteLocker lock(&f._fromm); _from = f._from; } { QWriteLocker lock(&f._tom); _to = f._to; } } return (*this); } /** * Get retry interval. * * @return Failover thread retry interval. */ time_t failover::get_retry_interval() const throw () { return (_retry_interval); } /** * Stop or start processing. * * @param[in] in true to process inputs. * @param[in] out true to process outputs. */ void failover::process(bool in, bool out) { // Set exit flag. QMutexLocker lock(&_should_exitm); _immediate = (!in && out); _should_exit = (!in || !out); // Quit event loop. if ((!in || !out) && isRunning()) { QTimer::singleShot(0, this, SLOT(quit())); QCoreApplication::processEvents(); } // Full delayed shutdown. if (!in && !out) { _endpoint->close(); bool tweaked_in(_failover.isNull()); QReadLocker lock(&_fromm); if (!_from.isNull()) _from->process(tweaked_in, false); } // Single delayed shutdown. else if (in && !out) { _endpoint->close(); QReadLocker lock(&_fromm); if (!_from.isNull()) _from->process(true, false); } // Immediate shutdown. else if (!in && out) { _endpoint->close(); QList<QSharedPointer<QMutexLocker> > locks; bool all_failover_not_running(true); failover* last(this); for (QSharedPointer<failover> fo = _failover; !fo.isNull(); fo = fo->_failover) { QSharedPointer<QMutexLocker> lock(new QMutexLocker(&fo->_should_exitm)); all_failover_not_running = all_failover_not_running && !fo->isRunning(); locks.push_back(lock); last = fo.data(); } // Shutdown subscriber. if (all_failover_not_running) { QReadLocker rl(&last->_fromm); if (!last->_from.isNull()) last->_from->process(false, true); } // Wait for thread to terminate. locks.clear(); lock.unlock(); QThread::wait(); lock.relock(); process(true, !_should_exit); lock.unlock(); } // Reinitialization. else { QReadLocker rl(&_fromm); if (!_from.isNull()) _from->process(true, true); } return ; } /** * Read data. * * @param[out] data Data buffer. * @param[out] type Data type. */ QSharedPointer<io::data> failover::read() { // Read retained data. QSharedPointer<io::data> data; QMutexLocker exit_lock(&_should_exitm); if (isRunning() && QThread::currentThread() != this) { // Release thread lock. exit_lock.unlock(); // Read data from destination. logging::debug(logging::low) << "failover: reading retained data from failover thread"; bool caught(false); QReadLocker tom(&_tom); try { if (!_to.isNull()) data = _to->read(); logging::debug(logging::low) << "failover: got retained event from failover thread"; } catch (...) { caught = true; } // End of destination is reached, shutdown this thread. if (caught || data.isNull()) { logging::debug(logging::low) << "failover: could not get event from failover thread"; logging::info(logging::medium) << "failover: requesting failover thread termination"; // Reset lock. _to.clear(); _tom.unlock(); // Exit this thread immediately. process(false, true); // Recursive data reading. exit_lock.relock(); if (!_should_exit) { exit_lock.unlock(); data = this->read(); } else exit_lock.unlock(); } } // Fetch next available event. else { // Release thread lock. exit_lock.unlock(); // Try the one retained event. QMutexLocker lock(&_datam); if (!_data.isNull()) { data = _data; _data.clear(); lock.unlock(); } // Read from source. else { lock.unlock(); QReadLocker fromm(&_fromm); data = _from->read(); } logging::debug(logging::low) << "failover: got event from normal source"; } return (data); } /** * Thread core function. */ void failover::run() { // Check endpoint. if (_endpoint.isNull()) { logging::error(logging::high) << "failover: attempt to run a " \ "thread with a non-existent endpoint"; return ; } // Launch subfailover to fetch retained data. if (_initial && !_failover.isNull()) { connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit())); connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit())); connect(&*_failover, SIGNAL(finished()), SLOT(quit())); connect(&*_failover, SIGNAL(terminated()), SLOT(quit())); _failover->start(); exec(); disconnect( &*_failover, SIGNAL(exception_caught()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(initial_lock()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(finished()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(terminated()), this, SLOT(quit())); _initial = false; } // Failover should continue as long as not exit request was received. logging::debug(logging::medium) << "failover: launching loop"; QMutexLocker exit_lock(&_should_exitm); _should_exit = false; while (!_should_exit) { exit_lock.unlock(); try { // Close previous endpoint if any and then open it. logging::debug(logging::medium) << "failover: opening endpoint"; QReadWriteLock* rwl; QSharedPointer<io::stream>* s; if (_is_out) { rwl = &_tom; s = &_to; } else { rwl = &_fromm; s = &_from; } { QWriteLocker wl(rwl); s->clear(); wl.unlock(); QSharedPointer<io::stream> tmp(_endpoint->open()); wl.relock(); emit initial_lock(); *s = tmp; if (s->isNull()) { // Retry connection. logging::debug(logging::medium) << "failover: resulting stream is nul, retrying"; exit_lock.relock(); continue ; } } // Process input and output. logging::debug(logging::medium) << "failover: launching feeding"; QSharedPointer<io::data> data; exit_lock.relock(); while (!_should_exit || !_immediate) { exit_lock.unlock(); try { { QReadLocker lock(&_fromm); if (!_from.isNull()) data = _from->read(); } if (data.isNull()) { exit_lock.relock(); _immediate = true; _should_exit = true; exit_lock.unlock(); } else { QWriteLocker lock(&_tom); if (!_to.isNull()) _to->write(data); } } catch (exceptions::msg const& e) { try { throw (exceptions::with_pointer(e, data)); } catch (exceptions::with_pointer const& e) { throw ; } catch (...) {} throw ; } data.clear(); exit_lock.relock(); } } catch (exceptions::with_pointer const& e) { logging::error(logging::high) << e.what(); if (!e.ptr().isNull() && !_failover.isNull() && !_failover->isRunning()) _failover->write(e.ptr()); } catch (io::exceptions::shutdown const& e) { logging::info(logging::medium) << "failover: a stream has shutdown: " << e.what(); } catch (exceptions::msg const& e) { logging::error(logging::high) << e.what(); } catch (std::exception const& e) { logging::error(logging::high) << "failover: standard library error: " << e.what(); } catch (...) { logging::error(logging::high) << "failover: unknown error caught in processing thread"; } emit exception_caught(); if (_is_out) { QWriteLocker lock(&_tom); _to.clear(); } else { QWriteLocker lock(&_fromm); _from.clear(); } // Relock thread lock. exit_lock.relock(); if (!_failover.isNull() && !_failover->isRunning() && !_should_exit) { connect(&*_failover, SIGNAL(exception_caught()), SLOT(quit())); connect(&*_failover, SIGNAL(initial_lock()), SLOT(quit())); connect(&*_failover, SIGNAL(finished()), SLOT(quit())); connect(&*_failover, SIGNAL(terminated()), SLOT(quit())); _failover->start(); exec(); disconnect( &*_failover, SIGNAL(exception_caught()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(initial_lock()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(finished()), this, SLOT(quit())); disconnect( &*_failover, SIGNAL(terminated()), this, SLOT(quit())); } if (!_should_exit) { // Unlock thread lock. exit_lock.unlock(); logging::info(logging::medium) << "failover: sleeping " << _retry_interval << " seconds before reconnection"; QTimer::singleShot(_retry_interval * 1000, this, SLOT(quit())); exec(); // Relock thread lock. exit_lock.relock(); } } return ; } /** * Set thread endpoint. * * @param[in] endp Thread endpoint. */ void failover::set_endpoint(QSharedPointer<io::endpoint> endp) { _endpoint = endp; return ; } /** * Set the thread's failover. * * @param[in] fo Thread's failover. */ void failover::set_failover(QSharedPointer<failover> fo) { _failover = fo; if (!fo.isNull() && _is_out) { // failover object will act as input for output threads. QWriteLocker lock(&_fromm); _from = _failover; } return ; } /** * Set the connection retry interval. * * @param[in] retry_interval Time to wait between two connection * attempts. */ void failover::set_retry_interval(time_t retry_interval) { _retry_interval = retry_interval; return ; } /** * Wait for this thread to terminate along with other failovers. * * @param[in] time Maximum time to wait for thread termination. */ bool failover::wait(unsigned long time) { if (!_failover.isNull()) _failover->wait(time); return (this->QThread::wait(time)); } /** * Write data. * * @param[in] d Unused. * * @return Does not return, throw an exception. */ void failover::write(QSharedPointer<io::data> d) { QMutexLocker lock(&_datam); _data = d; return ; }
Fix dead lock on failover unload.
Fix dead lock on failover unload. git-svn-id: a49aa41e49c69a6ab6ef43f172843a2fef6cb475@978 7c7d615a-03b3-410d-a316-1135b1bd9499
C++
apache-2.0
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker
2aad0b4854aaab6bfbb568106bef851b81cba7b3
Video.cpp
Video.cpp
#include "Video.h" Video::Video(Memory *memory, CPU *cpu) { this->memory = memory; this->cpu = cpu; this->createSDLWindow(); this->resetFrameBuffer(); this->renderGame(); this->scanlineCounter = MAX_VIDEO_CYCLES; } void Video::updateGraphics(short cycles) { // printVideoRegistersState(); if (isLCDEnabled()) { scanlineCounter -= cycles; byte currentScanline = memory->readDirectly(LY_REGISTER); byte lcdStatus = memory->readDirectly(LCD_STATUS); mode = getLCDMode(); if (currentScanline <= VERTICAL_BLANK_SCAN_LINE) { if (scanlineCounter >= (MAX_VIDEO_CYCLES - MIN_OAM_MODE_CYCLES)) { handleOAMMode(); } else if (scanlineCounter >= (MAX_VIDEO_CYCLES - MIN_OAM_AND_VRAM_MODE_CYCLES - MIN_OAM_MODE_CYCLES)) { handleOAMAndVRamMode(); } else { handleHBlankMode(); } } else { handleVBlankMode(); } byte lyRegister = memory->readDirectly(LY_REGISTER); byte lyCompare = memory->readDirectly(LY_COMPARE); if (lyCompare == lyRegister) { if (isBitSet(lcdStatus, 6)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } } else { scanlineCounter = MAX_VIDEO_CYCLES; byte lcdStatus = memory->readDirectly(LCD_STATUS); clearBit(&lcdStatus, 1); setBit(&lcdStatus, 0); memory->writeDirectly(LY_REGISTER, lcdStatus); } } void Video::handleHBlankMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); byte scanline = memory->readDirectly(LY_REGISTER); memory->writeDirectly(LY_REGISTER, ++scanline); if (scanline < VERTICAL_BLANK_SCAN_LINE) { drawScanline(); } else { clearBit(&lcdStatus, 1); setBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 4)) { cpu->requestInterrupt(CPU::Interrupts::VBLANK); } } } void Video::handleVBlankMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); byte scanline = memory->readDirectly(LY_REGISTER); memory->writeDirectly(LY_REGISTER, ++scanline); if (scanline == VERTICAL_BLANK_SCAN_LINE_MAX) { scanlineCounter = MAX_VIDEO_CYCLES; memory->writeDirectly(LY_REGISTER, 0x0); setBit(&lcdStatus, 1); clearBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 5)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } } void Video::handleOAMMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); setBit(&lcdStatus, 1); clearBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 3)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } void Video::handleOAMAndVRamMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); setBit(&lcdStatus,1); setBit(&lcdStatus,0); memory->writeDirectly(LCD_STATUS, lcdStatus); } bool Video::isLCDEnabled() const { return isBitSet(memory->read(LCDS_CONTROL), 7); } void Video::drawScanline() { byte lcdControl = memory->readDirectly(LCDS_CONTROL); if ( isBitSet(lcdControl, 0) ) { renderBackground(lcdControl); } else if ( isBitSet(lcdControl, 1) ) { renderSprites(lcdControl); } } void Video::renderBackground(byte lcdControl) { if ( isBitSet(lcdControl,0) ) { word tileData = 0 ; word backgroundMemory =0 ; bool unsig = true ; byte scrollY = memory->read(SCROLL_Y); byte scrollX = memory->read(SCROLL_X); byte windowY = memory->read(WINDOWS_Y); byte windowX = memory->read(WINDOWS_X) - 7; bool usingWindow = false; if ( isBitSet(lcdControl, 5) ) { if (windowY <= memory->read(LY_REGISTER) ) { usingWindow = true; } } if ( isBitSet(lcdControl,4) ) { tileData = 0x8000; } else { tileData = 0x8800; unsig= false; } if ( !usingWindow ) { if ( isBitSet(lcdControl, 3) ) { backgroundMemory = 0x9C00; } else { backgroundMemory = 0x9800; } } else { if ( isBitSet(lcdControl, 6) ) { backgroundMemory = 0x9C00; } else { backgroundMemory = 0x9800; } } byte yPos = 0; if ( !usingWindow ) { yPos = scrollY + memory->read(LY_REGISTER); } else { yPos = memory->read(LY_REGISTER) - windowY; } word tileRow = (((byte)(yPos/8))*32); for ( int pixel = 0 ; pixel < 160; pixel++ ) { byte xPos = pixel+scrollX; if ( usingWindow ) { if ( pixel >= windowX ) { xPos = pixel - windowX; } } word tileCol = (xPos/8); signed short tileNum; if( unsig ) { tileNum = (byte)memory->read(backgroundMemory+tileRow + tileCol); } else { tileNum = (signed short)memory->read(backgroundMemory+tileRow + tileCol); } word tileLocation = tileData; if ( unsig ) { tileLocation += (tileNum * 16); } else { tileLocation += ((tileNum+128) *16); } byte line = yPos % 8; line *= 2; byte data1 = memory->read(tileLocation + line); byte data2 = memory->read(tileLocation + line + 1); int colourBit = xPos % 8; colourBit -= 7; colourBit *= -1; int colourNum = getBitValue(data2, colourBit); colourNum <<= 1; colourNum |= getBitValue(data1,colourBit); Colour col = getColour(colourNum, 0xFF47); int red, green, blue = red = green = 0; switch( col ) { case white: red = 255; green = 255; blue = 255; break; case lightGray: red = 0xCC; green = 0xCC; blue = 0xCC; break; case darkGray: red = 0x77; green = 0x77; blue = 0x77; break; case black: red = 0x0; green = 0x0; blue = 0x0; break; } int scanline = memory->read(LY_REGISTER); frameBuffer[scanline][pixel][0] = red; frameBuffer[scanline][pixel][1] = green; frameBuffer[scanline][pixel][2] = blue; } } } Video::Colour Video::getColour(const byte colourNumber, const word address) const { Colour res = white; byte palette = memory->readDirectly(address); int hi = 0; int lo = 0; switch ( colourNumber ) { case 0: hi = 1; lo = 0; break; case 1: hi = 3; lo = 2; break; case 2: hi = 5; lo = 4; break; case 3: hi = 7; lo = 6; break; } int colour = 0; colour = getBitValue(palette, hi) << 1; colour |= getBitValue(palette, lo) ; switch ( colour ) { case 0: res = white; break; case 1: res = lightGray; break; case 2: res = darkGray; break; case 3: res = black; break; } return res; } void Video::renderSprites(byte lcdControl) { if ( isBitSet(lcdControl, 1) ) { bool use8x16 = false ; if ( isBitSet(lcdControl, 2) ) { use8x16 = true ; } for (int sprite = 0 ; sprite < 40; sprite++) { byte index = sprite*4 ; byte yPos = memory->read(0xFE00+index) - 16; byte xPos = memory->read(0xFE00+index+1)-8; byte tileLocation = memory->read(0xFE00+index+2) ; byte attributes = memory->read(0xFE00+index+3) ; bool yFlip = isBitSet(attributes, 6); bool xFlip = isBitSet(attributes, 5); bool hidden = isBitSet(attributes, 7); int scanline = memory->read(LY_REGISTER); int ysize = 8; if ( use8x16 ) { ysize = 16; } if ( (scanline >= yPos) && (scanline < (yPos+ysize)) ) { int line = scanline - yPos; if ( yFlip ) { line -= ysize; line *= -1; } line *= 2; byte data1 = memory->read((0x8000 + (tileLocation * 16)) + line); byte data2 = memory->read((0x8000 + (tileLocation * 16)) + line+1); for ( int tilePixel = 7; tilePixel >= 0; tilePixel-- ) { int colourbit = tilePixel ; if ( xFlip ) { colourbit -= 7; colourbit *= -1; } int colourNum = getBitValue(data2,colourbit) ; colourNum <<= 1; colourNum |= getBitValue(data1,colourbit) ; Colour color; if ( isBitSet(attributes, 4) ) { color = getColour(colourNum, 0xFF49); } else { color = getColour(colourNum, 0xFF48); } int red, green, blue; red = green = blue = 0; switch ( color ) { case white: red = 255; green = 255; blue = 255; break; case lightGray: red = 0xCC; green = 0xCC; blue = 0xCC; break; case darkGray: red = 0x77; green = 0x77; blue = 0x77; break; case black: red = 0x0; green = 0x0; blue = 0x0; break; } int xPix = 0 - tilePixel; xPix += 7; int pixel = xPos+xPix; if ( hidden && frameBuffer[scanline][pixel][0] == white ) { hidden = false; } if ( !hidden ){ frameBuffer[scanline][pixel][0] = red; frameBuffer[scanline][pixel][1] = green; frameBuffer[scanline][pixel][2] = blue; } } } } } } byte Video::getLCDMode() const { byte lcdStatus = memory->readDirectly(LCD_STATUS); return lcdStatus & 0x3; } bool Video::createSDLWindow() { if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32); window = SDL_CreateWindow("PatBoy", 0, 0,GAMEBOY_WIDTH, GAMEBOY_HEIGHT, SDL_WINDOW_OPENGL); SDL_GL_CreateContext(window); initializeOpenGL(); return true ; } void Video::initializeOpenGL() { glViewport(0, 0, GAMEBOY_WIDTH, GAMEBOY_HEIGHT); glMatrixMode(GL_MODELVIEW); glOrtho(0, GAMEBOY_WIDTH, GAMEBOY_HEIGHT, 0, -1.0, 1.0); glClearColor(0, 0, 0, 1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glShadeModel(GL_FLAT); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_DITHER); glDisable(GL_BLEND); } void Video::renderGame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRasterPos2i(-1, 1); glPixelZoom(1, -1); glDrawPixels(GAMEBOY_WIDTH, GAMEBOY_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, this->frameBuffer); SDL_GL_SwapWindow(window); } void Video::resetFrameBuffer() { for ( int x = 0 ; x < 144; x++ ) { for ( int y = 0; y < 160; y++ ) { frameBuffer[x][y][0] = 255; frameBuffer[x][y][1] = 255; frameBuffer[x][y][2] = 255; } } } void Video::printVideoRegistersState() const { printf("LCDS CONTROL: %02X\t", memory->readDirectly(LCDS_CONTROL)); printf("LCD STATUS: %02X\t", memory->readDirectly(LCD_STATUS)); printf("LY_REGISTER: %02X\t" , memory->readDirectly(LY_REGISTER)); printf("LY_COMPARE: %02X\t", memory->readDirectly(LY_COMPARE)); printf("SCROLL X: %02X\t", memory->readDirectly(SCROLL_X)); printf("SCROLL Y: %02X\n\n", memory->readDirectly(SCROLL_Y)); }
#include "Video.h" Video::Video(Memory *memory, CPU *cpu) { this->memory = memory; this->cpu = cpu; this->createSDLWindow(); this->resetFrameBuffer(); this->renderGame(); this->scanlineCounter = MAX_VIDEO_CYCLES; } void Video::updateGraphics(short cycles) { // printVideoRegistersState(); if (isLCDEnabled()) { scanlineCounter -= cycles; byte currentScanline = memory->readDirectly(LY_REGISTER); byte lcdStatus = memory->readDirectly(LCD_STATUS); mode = getLCDMode(); if (currentScanline <= VERTICAL_BLANK_SCAN_LINE) { if (scanlineCounter >= (MAX_VIDEO_CYCLES - MIN_OAM_MODE_CYCLES)) { handleOAMMode(); } else if (scanlineCounter >= (MAX_VIDEO_CYCLES - MIN_OAM_AND_VRAM_MODE_CYCLES - MIN_OAM_MODE_CYCLES)) { handleOAMAndVRamMode(); } else { if (mode != 0x0) { clearBit(&lcdStatus, 1); clearBit(&lcdStatus, 0); } handleHBlankMode(); } } else { handleVBlankMode(); } byte lyRegister = memory->readDirectly(LY_REGISTER); byte lyCompare = memory->readDirectly(LY_COMPARE); if (lyCompare == lyRegister) { if (isBitSet(lcdStatus, 6)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } } else { scanlineCounter = MAX_VIDEO_CYCLES; byte lcdStatus = memory->readDirectly(LCD_STATUS); clearBit(&lcdStatus, 1); setBit(&lcdStatus, 0); memory->writeDirectly(LY_REGISTER, lcdStatus); } } void Video::handleHBlankMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); byte scanline = memory->readDirectly(LY_REGISTER); memory->writeDirectly(LY_REGISTER, ++scanline); if (scanline < VERTICAL_BLANK_SCAN_LINE) { drawScanline(); } else { clearBit(&lcdStatus, 1); setBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 4)) { cpu->requestInterrupt(CPU::Interrupts::VBLANK); } } } void Video::handleVBlankMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); byte scanline = memory->readDirectly(LY_REGISTER); memory->writeDirectly(LY_REGISTER, ++scanline); if (scanline == VERTICAL_BLANK_SCAN_LINE_MAX) { scanlineCounter = MAX_VIDEO_CYCLES; memory->writeDirectly(LY_REGISTER, 0x0); setBit(&lcdStatus, 1); clearBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 5)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } } void Video::handleOAMMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); setBit(&lcdStatus, 1); clearBit(&lcdStatus, 0); memory->writeDirectly(LCD_STATUS, lcdStatus); if (isBitSet(lcdStatus, 3)) { cpu->requestInterrupt(CPU::Interrupts::LCD); } } void Video::handleOAMAndVRamMode() { byte lcdStatus = memory->readDirectly(LCD_STATUS); setBit(&lcdStatus,1); setBit(&lcdStatus,0); memory->writeDirectly(LCD_STATUS, lcdStatus); } bool Video::isLCDEnabled() const { return isBitSet(memory->read(LCDS_CONTROL), 7); } void Video::drawScanline() { byte lcdControl = memory->readDirectly(LCDS_CONTROL); if ( isBitSet(lcdControl, 0) ) { renderBackground(lcdControl); } else if ( isBitSet(lcdControl, 1) ) { renderSprites(lcdControl); } } void Video::renderBackground(byte lcdControl) { if ( isBitSet(lcdControl,0) ) { word tileData = 0 ; word backgroundMemory =0 ; bool unsig = true ; byte scrollY = memory->read(SCROLL_Y); byte scrollX = memory->read(SCROLL_X); byte windowY = memory->read(WINDOWS_Y); byte windowX = memory->read(WINDOWS_X) - 7; bool usingWindow = false; if ( isBitSet(lcdControl, 5) ) { if (windowY <= memory->read(LY_REGISTER) ) { usingWindow = true; } } if ( isBitSet(lcdControl,4) ) { tileData = 0x8000; } else { tileData = 0x8800; unsig= false; } if ( !usingWindow ) { if ( isBitSet(lcdControl, 3) ) { backgroundMemory = 0x9C00; } else { backgroundMemory = 0x9800; } } else { if ( isBitSet(lcdControl, 6) ) { backgroundMemory = 0x9C00; } else { backgroundMemory = 0x9800; } } byte yPos = 0; if ( !usingWindow ) { yPos = scrollY + memory->read(LY_REGISTER); } else { yPos = memory->read(LY_REGISTER) - windowY; } word tileRow = (((byte)(yPos/8))*32); for ( int pixel = 0 ; pixel < 160; pixel++ ) { byte xPos = pixel+scrollX; if ( usingWindow ) { if ( pixel >= windowX ) { xPos = pixel - windowX; } } word tileCol = (xPos/8); signed short tileNum; if( unsig ) { tileNum = (byte)memory->read(backgroundMemory+tileRow + tileCol); } else { tileNum = (signed short)memory->read(backgroundMemory+tileRow + tileCol); } word tileLocation = tileData; if ( unsig ) { tileLocation += (tileNum * 16); } else { tileLocation += ((tileNum+128) *16); } byte line = yPos % 8; line *= 2; byte data1 = memory->read(tileLocation + line); byte data2 = memory->read(tileLocation + line + 1); int colourBit = xPos % 8; colourBit -= 7; colourBit *= -1; int colourNum = getBitValue(data2, colourBit); colourNum <<= 1; colourNum |= getBitValue(data1,colourBit); Colour col = getColour(colourNum, 0xFF47); int red, green, blue = red = green = 0; switch( col ) { case white: red = 255; green = 255; blue = 255; break; case lightGray: red = 0xCC; green = 0xCC; blue = 0xCC; break; case darkGray: red = 0x77; green = 0x77; blue = 0x77; break; case black: red = 0x0; green = 0x0; blue = 0x0; break; } int scanline = memory->read(LY_REGISTER); frameBuffer[scanline][pixel][0] = red; frameBuffer[scanline][pixel][1] = green; frameBuffer[scanline][pixel][2] = blue; } } } Video::Colour Video::getColour(const byte colourNumber, const word address) const { Colour res = white; byte palette = memory->readDirectly(address); int hi = 0; int lo = 0; switch ( colourNumber ) { case 0: hi = 1; lo = 0; break; case 1: hi = 3; lo = 2; break; case 2: hi = 5; lo = 4; break; case 3: hi = 7; lo = 6; break; } int colour = 0; colour = getBitValue(palette, hi) << 1; colour |= getBitValue(palette, lo) ; switch ( colour ) { case 0: res = white; break; case 1: res = lightGray; break; case 2: res = darkGray; break; case 3: res = black; break; } return res; } void Video::renderSprites(byte lcdControl) { if ( isBitSet(lcdControl, 1) ) { bool use8x16 = false ; if ( isBitSet(lcdControl, 2) ) { use8x16 = true ; } for (int sprite = 0 ; sprite < 40; sprite++) { byte index = sprite*4 ; byte yPos = memory->read(0xFE00+index) - 16; byte xPos = memory->read(0xFE00+index+1)-8; byte tileLocation = memory->read(0xFE00+index+2) ; byte attributes = memory->read(0xFE00+index+3) ; bool yFlip = isBitSet(attributes, 6); bool xFlip = isBitSet(attributes, 5); bool hidden = isBitSet(attributes, 7); int scanline = memory->read(LY_REGISTER); int ysize = 8; if ( use8x16 ) { ysize = 16; } if ( (scanline >= yPos) && (scanline < (yPos+ysize)) ) { int line = scanline - yPos; if ( yFlip ) { line -= ysize; line *= -1; } line *= 2; byte data1 = memory->read((0x8000 + (tileLocation * 16)) + line); byte data2 = memory->read((0x8000 + (tileLocation * 16)) + line+1); for ( int tilePixel = 7; tilePixel >= 0; tilePixel-- ) { int colourbit = tilePixel ; if ( xFlip ) { colourbit -= 7; colourbit *= -1; } int colourNum = getBitValue(data2,colourbit) ; colourNum <<= 1; colourNum |= getBitValue(data1,colourbit) ; Colour color; if ( isBitSet(attributes, 4) ) { color = getColour(colourNum, 0xFF49); } else { color = getColour(colourNum, 0xFF48); } int red, green, blue; red = green = blue = 0; switch ( color ) { case white: red = 255; green = 255; blue = 255; break; case lightGray: red = 0xCC; green = 0xCC; blue = 0xCC; break; case darkGray: red = 0x77; green = 0x77; blue = 0x77; break; case black: red = 0x0; green = 0x0; blue = 0x0; break; } int xPix = 0 - tilePixel; xPix += 7; int pixel = xPos+xPix; if ( hidden && frameBuffer[scanline][pixel][0] == white ) { hidden = false; } if ( !hidden ){ frameBuffer[scanline][pixel][0] = red; frameBuffer[scanline][pixel][1] = green; frameBuffer[scanline][pixel][2] = blue; } } } } } } byte Video::getLCDMode() const { byte lcdStatus = memory->readDirectly(LCD_STATUS); return lcdStatus & 0x3; } bool Video::createSDLWindow() { if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32); window = SDL_CreateWindow("PatBoy", 0, 0,GAMEBOY_WIDTH, GAMEBOY_HEIGHT, SDL_WINDOW_OPENGL); SDL_GL_CreateContext(window); initializeOpenGL(); return true ; } void Video::initializeOpenGL() { glViewport(0, 0, GAMEBOY_WIDTH, GAMEBOY_HEIGHT); glMatrixMode(GL_MODELVIEW); glOrtho(0, GAMEBOY_WIDTH, GAMEBOY_HEIGHT, 0, -1.0, 1.0); glClearColor(0, 0, 0, 1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glShadeModel(GL_FLAT); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_DITHER); glDisable(GL_BLEND); } void Video::renderGame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRasterPos2i(-1, 1); glPixelZoom(1, -1); glDrawPixels(GAMEBOY_WIDTH, GAMEBOY_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, this->frameBuffer); SDL_GL_SwapWindow(window); } void Video::resetFrameBuffer() { for ( int x = 0 ; x < 144; x++ ) { for ( int y = 0; y < 160; y++ ) { frameBuffer[x][y][0] = 255; frameBuffer[x][y][1] = 255; frameBuffer[x][y][2] = 255; } } } void Video::printVideoRegistersState() const { printf("LCDS CONTROL: %02X\t", memory->readDirectly(LCDS_CONTROL)); printf("LCD STATUS: %02X\t", memory->readDirectly(LCD_STATUS)); printf("LY_REGISTER: %02X\t" , memory->readDirectly(LY_REGISTER)); printf("LY_COMPARE: %02X\t", memory->readDirectly(LY_COMPARE)); printf("SCROLL X: %02X\t", memory->readDirectly(SCROLL_X)); printf("SCROLL Y: %02X\n\n", memory->readDirectly(SCROLL_Y)); }
Set mode HBLANK properly in LCD STATUS register.
Set mode HBLANK properly in LCD STATUS register.
C++
mit
Jonazan2/PatBoy,Jonazan2/PatBoy,Jonazan2/PatBoy,Jonazan2/PatBoy,Jonazan2/PatBoy
9d9de40c48c9db02c9b42bea1295a7a92ff6015a
src/apps/calibrate_vignetting_response/calibrate_vignetting_response.cpp
src/apps/calibrate_vignetting_response/calibrate_vignetting_response.cpp
/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <radical/exceptions.h> #include <radical/nonparametric_vignetting_model.h> #include <radical/polynomial_vignetting_model.h> #include <radical/radiometric_response.h> #include <radical/vignetting_response.h> #include "grabbers/grabber.h" #include "utils/arrange_images_in_grid.h" #include "utils/mask_saturated_pixels.h" #include "utils/mean_image.h" #include "utils/plot_polynomial_vignetting_model.h" #include "utils/program_options.h" #include "utils/key_code.h" #include "blob_tracker.h" #include "model_fitting.h" using utils::KeyCode; class Options : public OptionsBase { public: std::string camera = ""; std::string output; std::string crf; unsigned int num_samples = 100; unsigned int exposure = 20; std::string model = "nonparametric"; bool fixed_center = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("output,o", po::value<std::string>(&output), "Output filename with calibrated vignetting response (default: camera model name + \".\" + " "camera serial number + \".vgn\" suffix)"); desc.add_options()( "crf", po::value<std::string>(&crf), "Camera response function (default: camera model name + \".\" camera serial number + \".crf\" suffix)"); desc.add_options()("num-samples,s", po::value<unsigned int>(&num_samples), "Number of samples to collect for each pixel (default: 100)"); desc.add_options()("exposure,e", po::value<unsigned int>(&exposure), "Initial exposure time (default: 20)"); desc.add_options()("model,m", po::value<std::string>(&model), "Vignetting model type (default: nonparametric)"); desc.add_options()("fixed-center,c", po::bool_switch(&fixed_center), "Fix model center of symmetry to image center (only for polynomial model)"); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("camera", po::value<std::string>(&camera), "Camera to calibrate (\"asus\", \"intel\")"); positional.add("camera", -1); } virtual void printHelp() override { std::cout << "Usage: calibrate_vignetting_response [options] <camera>" << std::endl; std::cout << "" << std::endl; std::cout << "Calibrate vignetting response of a camera. Two vignetting models are available:" << std::endl; std::cout << " * nonparametric" << std::endl; std::cout << " * polynomial" << std::endl; std::cout << "" << std::endl; } virtual void validate() override { #ifndef HAVE_CERES if (model == "polynomial") throw boost::program_options::error( "unable to calibrate polynomial vignetting model because the app was compiled without Ceres"); #endif if (model != "nonparametric" && model != "polynomial") throw boost::program_options::error("unknown vignetting model type " + model); } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; auto imshow = [&options](const cv::Mat& image, int w = -1) { if (image.empty()) return -1; cv::imshow("Calibration", image); return cv::waitKey(w); }; cv::Mat data; grabbers::Grabber::Ptr grabber; try { grabber = grabbers::createGrabber(options.camera); } catch (grabbers::GrabberException& e) { std::cerr << "Failed to create a grabber" << (options.camera != "" ? " for camera " + options.camera : "") << std::endl; return 1; } if (!options("output")) options.output = grabber->getCameraUID() + ".vgn"; if (!options("crf")) options.crf = grabber->getCameraUID() + ".crf"; radical::RadiometricResponse::Ptr rr; try { rr.reset(new radical::RadiometricResponse(options.crf)); } catch (radical::Exception& e) { std::cerr << "Failed to load radiometric response: " << e.what() << std::endl; return 1; } grabber->setAutoExposureEnabled(false); grabber->setAutoWhiteBalanceEnabled(false); auto range = grabber->getExposureRange(); // Change exposure to requested initial value and let user adjust it int exposure = options.exposure; KeyCode key = 0; while (key != KeyCode::ENTER) { int old_exposure = exposure; cv::Mat frame; grabber->grabFrame(frame); key = imshow(frame, 30); if (key == KeyCode::PLUS || key == KeyCode::ARROW_UP || key == KeyCode::ARROW_RIGHT) ++exposure; if (key == KeyCode::MINUS || key == KeyCode::ARROW_DOWN || key == KeyCode::ARROW_LEFT) --exposure; if (old_exposure != exposure) { if (exposure > range.second) exposure = range.second; else if (exposure < range.first) exposure = range.first; else { grabber->setExposure(exposure); std::cout << "Exposure: " << old_exposure << " → " << exposure << std::endl; } } } std::cout << "Starting data collection" << std::endl; utils::MeanImage mean(false, options.num_samples); BlobTracker tracker; cv::Mat frame; cv::Mat mask; cv::Mat irradiance; cv::Mat mean_color; int frame_counter = 0; while (grabber->hasMoreFrames()) { grabber->grabFrame(frame); tracker(frame, mask); maskSaturatedPixels(frame, mask); rr->inverseMap(frame, irradiance); if (mean.add(irradiance, mask)) break; cv::Mat masked; frame.copyTo(masked, mask); // Mean computation and especially direct mapping is expensive, so we do not do it every frame if (frame_counter++ % 10 == 0) rr->directMap(mean.getMean(), mean_color); cv::Mat m8u; mean.getNumSamples(true).convertTo(m8u, CV_8U, 255); cv::cvtColor(m8u, m8u, CV_GRAY2BGR); // duplicate channels for (auto i = m8u.begin<cv::Vec3b>(); i != m8u.end<cv::Vec3b>(); ++i) if (*i == cv::Vec3b(255, 255, 255)) *i = cv::Vec3b(77, 175, 74); auto m = arrangeImagesInGrid({frame, masked, m8u, mean_color}, {2, 2}); imshow(m, 30); } data = mean.getMean(); // Normalize each channel separately std::vector<cv::Mat> channels; cv::split(data, channels); for (auto& c : channels) { double min, max; cv::minMaxLoc(c, &min, &max); c /= max; } cv::merge(channels, data); radical::VignettingModel::Ptr model; cv::Mat plot; if (options.model == "nonparametric") { model.reset(new radical::NonparametricVignettingModel(data)); #ifdef HAVE_CERES } else if (options.model == "polynomial") { auto poly_model = fitPolynomialModel(data, options.fixed_center, 50, false); plot = plotPolynomialVignettingModel(*poly_model); model = poly_model; #endif } std::cout << "Done, writing response to: " << options.output << std::endl; model->save(options.output); imshow(plot, -1); return 0; }
/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <radical/exceptions.h> #include <radical/nonparametric_vignetting_model.h> #include <radical/polynomial_vignetting_model.h> #include <radical/radiometric_response.h> #include <radical/vignetting_response.h> #include "grabbers/grabber.h" #include "utils/arrange_images_in_grid.h" #include "utils/mask_saturated_pixels.h" #include "utils/mean_image.h" #include "utils/plot_polynomial_vignetting_model.h" #include "utils/program_options.h" #include "utils/key_code.h" #include "utils/colors.h" #include "blob_tracker.h" #include "model_fitting.h" using utils::KeyCode; class Options : public OptionsBase { public: std::string camera = ""; std::string output; std::string crf; unsigned int num_samples = 100; unsigned int exposure = 20; std::string model = "nonparametric"; bool fixed_center = false; protected: virtual void addOptions(boost::program_options::options_description& desc) override { namespace po = boost::program_options; desc.add_options()("output,o", po::value<std::string>(&output), "Output filename with calibrated vignetting response (default: camera model name + \".\" + " "camera serial number + \".vgn\" suffix)"); desc.add_options()( "crf", po::value<std::string>(&crf), "Camera response function (default: camera model name + \".\" camera serial number + \".crf\" suffix)"); desc.add_options()("num-samples,s", po::value<unsigned int>(&num_samples), "Number of samples to collect for each pixel (default: 100)"); desc.add_options()("exposure,e", po::value<unsigned int>(&exposure), "Initial exposure time (default: 20)"); desc.add_options()("model,m", po::value<std::string>(&model), "Vignetting model type (default: nonparametric)"); desc.add_options()("fixed-center,c", po::bool_switch(&fixed_center), "Fix model center of symmetry to image center (only for polynomial model)"); } virtual void addPositional(boost::program_options::options_description& desc, boost::program_options::positional_options_description& positional) override { namespace po = boost::program_options; desc.add_options()("camera", po::value<std::string>(&camera), "Camera to calibrate (\"asus\", \"intel\")"); positional.add("camera", -1); } virtual void printHelp() override { std::cout << "Usage: calibrate_vignetting_response [options] <camera>" << std::endl; std::cout << "" << std::endl; std::cout << "Calibrate vignetting response of a camera. Two vignetting models are available:" << std::endl; std::cout << " * nonparametric" << std::endl; std::cout << " * polynomial" << std::endl; std::cout << "" << std::endl; } virtual void validate() override { #ifndef HAVE_CERES if (model == "polynomial") throw boost::program_options::error( "unable to calibrate polynomial vignetting model because the app was compiled without Ceres"); #endif if (model != "nonparametric" && model != "polynomial") throw boost::program_options::error("unknown vignetting model type " + model); } }; int main(int argc, const char** argv) { Options options; if (!options.parse(argc, argv)) return 1; auto imshow = [&options](const cv::Mat& image, int w = -1) { if (image.empty()) return -1; cv::imshow("Calibration", image); return cv::waitKey(w); }; cv::Mat data; grabbers::Grabber::Ptr grabber; try { grabber = grabbers::createGrabber(options.camera); } catch (grabbers::GrabberException& e) { std::cerr << "Failed to create a grabber" << (options.camera != "" ? " for camera " + options.camera : "") << std::endl; return 1; } if (!options("output")) options.output = grabber->getCameraUID() + ".vgn"; if (!options("crf")) options.crf = grabber->getCameraUID() + ".crf"; radical::RadiometricResponse::Ptr rr; try { rr.reset(new radical::RadiometricResponse(options.crf)); } catch (radical::Exception& e) { std::cerr << "Failed to load radiometric response: " << e.what() << std::endl; return 1; } grabber->setAutoExposureEnabled(false); grabber->setAutoWhiteBalanceEnabled(false); auto range = grabber->getExposureRange(); // Change exposure to requested initial value and let user adjust it int exposure = options.exposure; KeyCode key = 0; while (key != KeyCode::ENTER) { int old_exposure = exposure; cv::Mat frame; grabber->grabFrame(frame); key = imshow(frame, 30); if (key == KeyCode::PLUS || key == KeyCode::ARROW_UP || key == KeyCode::ARROW_RIGHT) ++exposure; if (key == KeyCode::MINUS || key == KeyCode::ARROW_DOWN || key == KeyCode::ARROW_LEFT) --exposure; if (old_exposure != exposure) { if (exposure > range.second) exposure = range.second; else if (exposure < range.first) exposure = range.first; else { grabber->setExposure(exposure); std::cout << "Exposure: " << old_exposure << " → " << exposure << std::endl; } } } std::cout << "Starting data collection" << std::endl; utils::MeanImage mean(false, options.num_samples); BlobTracker tracker; cv::Mat frame; cv::Mat mask; cv::Mat irradiance; cv::Mat mean_color; int frame_counter = 0; while (grabber->hasMoreFrames()) { grabber->grabFrame(frame); tracker(frame, mask); maskSaturatedPixels(frame, mask); rr->inverseMap(frame, irradiance); if (mean.add(irradiance, mask)) break; cv::Mat masked; frame.copyTo(masked, mask); // Mean computation and especially direct mapping is expensive, so we do not do it every frame if (frame_counter++ % 10 == 0) rr->directMap(mean.getMean(), mean_color); cv::Mat m8u; mean.getNumSamples(true).convertTo(m8u, CV_8U, 255); cv::cvtColor(m8u, m8u, CV_GRAY2BGR); // duplicate channels for (auto i = m8u.begin<cv::Vec3b>(); i != m8u.end<cv::Vec3b>(); ++i) if (*i == cv::Vec3b(255, 255, 255)) *i = cv::Vec3b(utils::colors::BGR[1][0], utils::colors::BGR[1][1], utils::colors::BGR[1][2]); auto m = arrangeImagesInGrid({frame, masked, m8u, mean_color}, {2, 2}); imshow(m, 30); } data = mean.getMean(); // Normalize each channel separately std::vector<cv::Mat> channels; cv::split(data, channels); for (auto& c : channels) { double min, max; cv::minMaxLoc(c, &min, &max); c /= max; } cv::merge(channels, data); radical::VignettingModel::Ptr model; cv::Mat plot; if (options.model == "nonparametric") { model.reset(new radical::NonparametricVignettingModel(data)); #ifdef HAVE_CERES } else if (options.model == "polynomial") { auto poly_model = fitPolynomialModel(data, options.fixed_center, 50, false); plot = plotPolynomialVignettingModel(*poly_model); model = poly_model; #endif } std::cout << "Done, writing response to: " << options.output << std::endl; model->save(options.output); imshow(plot, -1); return 0; }
Use green color from Brewer palette in vignetting calibration app
Use green color from Brewer palette in vignetting calibration app
C++
mit
taketwo/radical,taketwo/radical,taketwo/radical
0ad713261cbd03e02ce6116f571b53b4985ea506
mzn2fzn.cpp
mzn2fzn.cpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <fstream> #include <minizinc/model.hh> #include <minizinc/parser.hh> #include <minizinc/prettyprinter.hh> #include <minizinc/typecheck.hh> #include <minizinc/exception.hh> #include <minizinc/eval_par.hh> #include <minizinc/flatten.hh> #include <minizinc/copy.hh> #include <minizinc/builtins.hh> using namespace MiniZinc; using namespace std; int main(int argc, char** argv) { int i=1; string filename; vector<string> datafiles; vector<string> includePaths; bool ignoreStdlib = false; bool typecheck = true; bool eval = true; bool output = true; bool outputFundecls = false; bool verbose = false; bool allSolutions = false; bool free = false; int nbThreads = 1; if (argc < 2) goto error; GC::init(); for (;;) { if (string(argv[i])==string("-I")) { i++; if (i==argc) { goto error; } includePaths.push_back(argv[i]+string("/")); } else if (string(argv[i])==string("--ignore-stdlib")) { ignoreStdlib = true; } else if (string(argv[i])==string("--no-output")) { output = false; } else if (string(argv[i])==string("--no-fundecl-output")) { outputFundecls = false; } else if (string(argv[i])==string("--no-typecheck")) { typecheck = false; eval=false; } else if (string(argv[i])==string("--no-eval")) { eval = false; } else if (string(argv[i])==string("--verbose")) { verbose = true; } else if (string(argv[i])==string("-a")) { allSolutions = true; } else if (string(argv[i])==string("-f")) { free = true; } else if (string(argv[i])==string("-p")) { i++; nbThreads = atoi(argv[i]); } else { break; } i++; } if (i==argc) { goto error; } filename = argv[i++]; while (i<argc) datafiles.push_back(argv[i++]); { if (Model* m = parse(filename, datafiles, includePaths, ignoreStdlib, std::cerr)) { try { if (verbose) std::cerr << "parsing " << filename << std::endl; if (typecheck) { MiniZinc::typecheck(m); MiniZinc::registerBuiltins(m); Model* flat = flatten(m); // optimize(flat); oldflatzinc(flat); Printer p; p.print(flat,std::cout); } } catch (LocationException& e) { std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; exit(EXIT_FAILURE); } catch (Exception& e) { std::cerr << e.what() << ": " << e.msg() << std::endl; exit(EXIT_FAILURE); } delete m; } } return 0; error: std::cerr << "Usage: "<< argv[0] << " [--ignore-stdlib] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl; exit(EXIT_FAILURE); }
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <fstream> #include <minizinc/model.hh> #include <minizinc/parser.hh> #include <minizinc/prettyprinter.hh> #include <minizinc/typecheck.hh> #include <minizinc/exception.hh> #include <minizinc/eval_par.hh> #include <minizinc/flatten.hh> #include <minizinc/copy.hh> #include <minizinc/builtins.hh> using namespace MiniZinc; using namespace std; int main(int argc, char** argv) { int i=1; string filename; vector<string> datafiles; vector<string> includePaths; bool ignoreStdlib = false; bool typecheck = true; bool eval = true; bool output = true; bool outputFundecls = false; bool verbose = false; bool allSolutions = false; bool newfzn = false; bool free = false; int nbThreads = 1; if (argc < 2) goto error; GC::init(); for (;;) { if (string(argv[i])==string("-I")) { i++; if (i==argc) { goto error; } includePaths.push_back(argv[i]+string("/")); } else if (string(argv[i])==string("--ignore-stdlib")) { ignoreStdlib = true; } else if (string(argv[i])==string("--no-output")) { output = false; } else if (string(argv[i])==string("--no-fundecl-output")) { outputFundecls = false; } else if (string(argv[i])==string("--no-typecheck")) { typecheck = false; eval=false; } else if (string(argv[i])==string("--no-eval")) { eval = false; } else if (string(argv[i])==string("--verbose")) { verbose = true; } else if (string(argv[i])==string("--newfzn")) { newfzn = true; } else if (string(argv[i])==string("-a")) { allSolutions = true; } else if (string(argv[i])==string("-f")) { free = true; } else if (string(argv[i])==string("-p")) { i++; nbThreads = atoi(argv[i]); } else { break; } i++; } if (i==argc) { goto error; } filename = argv[i++]; while (i<argc) datafiles.push_back(argv[i++]); { if (Model* m = parse(filename, datafiles, includePaths, ignoreStdlib, std::cerr)) { try { if (verbose) std::cerr << "parsing " << filename << std::endl; if (typecheck) { MiniZinc::typecheck(m); MiniZinc::registerBuiltins(m); Model* flat = flatten(m); // optimize(flat); if (!newfzn) oldflatzinc(flat); Printer p; p.print(flat,std::cout); } } catch (LocationException& e) { std::cerr << e.what() << ": " << e.msg() << std::endl; std::cerr << e.loc() << std::endl; exit(EXIT_FAILURE); } catch (Exception& e) { std::cerr << e.what() << ": " << e.msg() << std::endl; exit(EXIT_FAILURE); } delete m; } } return 0; error: std::cerr << "Usage: "<< argv[0] << " [--ignore-stdlib] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl; exit(EXIT_FAILURE); }
Add switch for old/new flatzinc
Add switch for old/new flatzinc
C++
mpl-2.0
nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,tias/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,tias/libminizinc
46519997e46f5088d627e537086cab14e8e14e6d
cores/arduino/stdlib_noniso.cpp
cores/arduino/stdlib_noniso.cpp
/* core_esp8266_noniso.c - nonstandard (but usefull) conversion functions Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 03 April 2015 by Markus Sattler */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "stdlib_noniso.h" #include "math.h" #include "inttypes.h" int atoi(const char* s) { return (int) atol(s); } long atol(const char* s) { char * tmp; return strtol(s, &tmp, 10); } double atof(const char* s) { char * tmp; return strtod(s, &tmp); } void reverse(char* begin, char* end) { char *is = begin; char *ie = end - 1; while(is < ie) { char tmp = *ie; *ie = *is; *is = tmp; ++is; --ie; } } char* itoa( int val, char *string, int radix ) { return ltoa( val, string, radix ) ; } char* ltoa( long val, char *string, int radix ) { char tmp[33]; char *tp = tmp; long i; unsigned long v; int sign; char *sp; if ( string == NULL ) { return 0 ; } if (radix > 36 || radix <= 1) { return 0 ; } sign = (radix == 10 && val < 0); if (sign) { v = -val; } else { v = (unsigned long)val; } while (v || tp == tmp) { i = v % radix; v = v / radix; if (i < 10) *tp++ = i+'0'; else *tp++ = i + 'a' - 10; } sp = string; if (sign) *sp++ = '-'; while (tp > tmp) *sp++ = *--tp; *sp = 0; return string; } char* utoa( unsigned int val, char *string, int radix ) { return ultoa( val, string, radix ) ; } char* ultoa( unsigned long val, char *string, int radix ) { char tmp[33]; char *tp = tmp; long i; unsigned long v = val; char *sp; if ( string == NULL ) { return 0; } if (radix > 36 || radix <= 1) { return 0; } while (v || tp == tmp) { i = v % radix; v = v / radix; if (i < 10) *tp++ = i+'0'; else *tp++ = i + 'a' - 10; } sp = string; while (tp > tmp) *sp++ = *--tp; *sp = 0; return string; } char * dtostrf(double number, signed char width, unsigned char prec, char *s) { if (isnan(number)) { strcpy(s, "nan"); return s; } if (isinf(number)) { strcpy(s, "inf"); return s; } if (number > 4294967040.0 || number < -4294967040.0) { strcpy(s, "ovf"); return s; } char* out = s; int signInt_Part = 1; // Handle negative numbers if (number < 0.0) { signInt_Part = -1; number = -number; } // calc left over digits if (prec > 0) { width -= (prec + 1); } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i = 0; i < prec; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; out += sprintf(out, "%*ld", width, int_part * signInt_Part); // Print the decimal point, but only if there are digits beyond if (prec > 0) { *out = '.'; ++out; for (unsigned char decShift = prec; decShift > 0; decShift--) { remainder *= 10.0; } sprintf(out, "%0*d", prec, (int)remainder); } return s; }
/* core_esp8266_noniso.c - nonstandard (but usefull) conversion functions Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 03 April 2015 by Markus Sattler */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "stdlib_noniso.h" #include "math.h" #include "inttypes.h" int atoi(const char* s) { return (int) atol(s); } long atol(const char* s) { char * tmp; return strtol(s, &tmp, 10); } double atof(const char* s) { char * tmp; return strtod(s, &tmp); } void reverse(char* begin, char* end) { char *is = begin; char *ie = end - 1; while(is < ie) { char tmp = *ie; *ie = *is; *is = tmp; ++is; --ie; } } char* itoa( int val, char *string, int radix ) { return ltoa( val, string, radix ) ; } char* ltoa( long val, char *string, int radix ) { char tmp[33]; char *tp = tmp; long i; unsigned long v; int sign; char *sp; if ( string == NULL ) { return 0 ; } if (radix > 36 || radix <= 1) { return 0 ; } sign = (radix == 10 && val < 0); if (sign) { v = -val; } else { v = (unsigned long)val; } while (v || tp == tmp) { i = v % radix; v = v / radix; if (i < 10) *tp++ = i+'0'; else *tp++ = i + 'a' - 10; } sp = string; if (sign) *sp++ = '-'; while (tp > tmp) *sp++ = *--tp; *sp = 0; return string; } char* utoa( unsigned int val, char *string, int radix ) { return ultoa( val, string, radix ) ; } char* ultoa( unsigned long val, char *string, int radix ) { char tmp[33]; char *tp = tmp; long i; unsigned long v = val; char *sp; if ( string == NULL ) { return 0; } if (radix > 36 || radix <= 1) { return 0; } while (v || tp == tmp) { i = v % radix; v = v / radix; if (i < 10) *tp++ = i+'0'; else *tp++ = i + 'a' - 10; } sp = string; while (tp > tmp) *sp++ = *--tp; *sp = 0; return string; } char * dtostrf(double number, signed char width, unsigned char prec, char *s) { if (isnan(number)) { strcpy(s, "nan"); return s; } if (isinf(number)) { strcpy(s, "inf"); return s; } if (number > 4294967040.0 || number < -4294967040.0) { strcpy(s, "ovf"); return s; } char* out = s; int signInt_Part = 1; // Handle negative numbers if (number < 0.0) { signInt_Part = -1; number = -number; } // calc left over digits if (prec > 0) { width -= (prec + 1); } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i = 0; i < prec; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; out += sprintf(out, "%*ld", width, int_part * signInt_Part); // Print the decimal point, but only if there are digits beyond if (prec > 0) { *out = '.'; ++out; // Copy character by character to 'out' string for (unsigned char decShift = prec; decShift > 0; decShift--) { remainder *= 10.0; sprintf(out, "%d", (int)remainder); out++; remainder -= (double)(int)remainder; } } return s; }
fix overflow problem
dtostrf: fix overflow problem JIRA: ATLEDGE-315
C++
lgpl-2.1
sgbihu/corelibs-arduino101,sgbihu/corelibs-arduino101,sgbihu/corelibs-arduino101,eriknyquist/corelibs-arduino101,01org/corelibs-arduino101,SidLeung/corelibs-arduino101,yashaswini-hanji/corelibs-arduino101,bigdinotech/corelibs-arduino101,linrjing/corelibs-arduino101,sandeepmistry/corelibs-arduino101,yashaswini-hanji/corelibs-arduino101,eriknyquist/corelibs-arduino101,bigdinotech/corelibs-arduino101,yashaswini-hanji/corelibs-arduino101,SidLeung/corelibs-arduino101,facchinm/corelibs-arduino101,01org/corelibs-arduino101,sandeepmistry/corelibs-arduino101,linrjing/corelibs-arduino101,facchinm/corelibs-arduino101,01org/corelibs-arduino101,sandeepmistry/corelibs-arduino101,bigdinotech/corelibs-arduino101
81ebcdcf9d0b5e229f67a5caae9d1fee625030ff
RobotControlSotfware/RobotControl/src/controlmanager/mapdata/StartingPoint.cpp
RobotControlSotfware/RobotControl/src/controlmanager/mapdata/StartingPoint.cpp
//------------------------------------------------------------------------------------------------ // File: StartingPoint.cpp // Project: LG Exec Ed Program // Versions: // 1.0 April 2017 - initial version // Send and receives OpenCV Mat Images in a UDP message commpressed as Jpeg images //------------------------------------------------------------------------------------------------ #include "StartingPoint.h" #include "Direction.h" #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; StartingPoint::StartingPoint(int initialPositionX, int initialPositionY) { PositionX = initialPositionX; PositionY = initialPositionY; } void StartingPoint::reset(int robotEWSNDirection, int robotPositionX, int robotPositionY) { switch (robotEWSNDirection) { case EAST: resetPosition(5-robotPosionY, -(5-robotPositonX)); break; case WEST: resetPosition(-(5-robotPositionY) , 5-robotPositionX); break; case SOUTH: resetPosition(-(5-robotPositionX), -(5-robotPositionY)); break; case NORTH: resetPosition(5-robotPositionX, 5-robotPositionY); break; default: printf("reset() - This is not supported direction. (%d)\n", robotEWSNDirection); break; } } void StartingPoint::resetPosition(int robotPositionX, int robotPositionY) { // TODO: Caculate reset position... PositionX = 5+robotPositionX; PositionY = 5+robotPositionY; } bool StartingPoint::isStartingPoint(int robotPositionX, int robotPositionY) { if ((PositionX == robotPositionX) && (PositionY == robotPositionY)) { printf("isStartingPoint() - This is staring point.\n"); return true; } return false; } //----------------------------------------------------------------- // END WallFinder //----------------------------------------------------------------- //----------------------------------------------------------------- // END of File //-----------------------------------------------------------------
//------------------------------------------------------------------------------------------------ // File: StartingPoint.cpp // Project: LG Exec Ed Program // Versions: // 1.0 April 2017 - initial version // Send and receives OpenCV Mat Images in a UDP message commpressed as Jpeg images //------------------------------------------------------------------------------------------------ #include "StartingPoint.h" #include "Direction.h" #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; StartingPoint::StartingPoint(int initialPositionX, int initialPositionY) { PositionX = initialPositionX; PositionY = initialPositionY; } void StartingPoint::reset(int robotEWSNDirection, int robotPositionX, int robotPositionY) { switch (robotEWSNDirection) { case EAST: resetPosition(5-robotPositionY, -(5-robotPositionX)); break; case WEST: resetPosition(-(5-robotPositionY) , 5-robotPositionX); break; case SOUTH: resetPosition(-(5-robotPositionX), -(5-robotPositionY)); break; case NORTH: resetPosition(5-robotPositionX, 5-robotPositionY); break; default: printf("reset() - This is not supported direction. (%d)\n", robotEWSNDirection); break; } } void StartingPoint::resetPosition(int robotPositionX, int robotPositionY) { // TODO: Caculate reset position... PositionX = 5+robotPositionX; PositionY = 5+robotPositionY; } bool StartingPoint::isStartingPoint(int robotPositionX, int robotPositionY) { if ((PositionX == robotPositionX) && (PositionY == robotPositionY)) { printf("isStartingPoint() - This is staring point.\n"); return true; } return false; } //----------------------------------------------------------------- // END WallFinder //----------------------------------------------------------------- //----------------------------------------------------------------- // END of File //-----------------------------------------------------------------
reset postion 수정
reset postion 수정
C++
apache-2.0
orderlatte/mazerobot,orderlatte/mazerobot,orderlatte/mazerobot,orderlatte/mazerobot
a916f7f5e9bbc096e7c6fab18be01b8013a39fe1
lib/Frontend/ModuleDependencyCollector.cpp
lib/Frontend/ModuleDependencyCollector.cpp
//===--- ModuleDependencyCollector.cpp - Collect module dependencies ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the dependencies of a set of modules. // //===----------------------------------------------------------------------===// #include "clang/Frontend/Utils.h" #include "clang/Lex/Preprocessor.h" #include "clang/Serialization/ASTReader.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace { /// Private implementations for ModuleDependencyCollector class ModuleDependencyListener : public ASTReaderListener { ModuleDependencyCollector &Collector; public: ModuleDependencyListener(ModuleDependencyCollector &Collector) : Collector(Collector) {} bool needsInputFileVisitation() override { return true; } bool needsSystemInputFileVisitation() override { return true; } bool visitInputFile(StringRef Filename, bool IsSystem, bool IsOverridden, bool IsExplicitModule) override { Collector.addFile(Filename); return true; } }; struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks { ModuleDependencyCollector &Collector; ModuleDependencyMMCallbacks(ModuleDependencyCollector &Collector) : Collector(Collector) {} void moduleMapAddHeader(const FileEntry &File) override { StringRef HeaderPath = File.getName(); if (llvm::sys::path::is_absolute(HeaderPath)) Collector.addFile(HeaderPath); } }; } // TODO: move this to Support/Path.h and check for HAVE_REALPATH? static bool real_path(StringRef SrcPath, SmallVectorImpl<char> &RealPath) { #ifdef LLVM_ON_UNIX char CanonicalPath[PATH_MAX]; // TODO: emit a warning in case this fails...? if (!realpath(SrcPath.str().c_str(), CanonicalPath)) return false; SmallString<256> RPath(CanonicalPath); RealPath.swap(RPath); return true; #else // FIXME: Add support for systems without realpath. return false; #endif } void ModuleDependencyCollector::attachToASTReader(ASTReader &R) { R.addListener(llvm::make_unique<ModuleDependencyListener>(*this)); } void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) { PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks( llvm::make_unique<ModuleDependencyMMCallbacks>(*this)); } static bool isCaseSensitivePath(StringRef Path) { SmallString<PATH_MAX> TmpDest = Path, UpperDest, RealDest; // Remove component traversals, links, etc. if (!real_path(Path, TmpDest)) return true; // Current default value in vfs.yaml Path = TmpDest; // Change path to all upper case and ask for its real path, if the latter // exists and is equal to Path, it's not case sensitive. Default to case // sensitive in the absense of realpath, since this is what the VFSWriter // already expects when sensitivity isn't setup. for (auto &C : Path) UpperDest.push_back(::toupper(C)); if (real_path(UpperDest, RealDest) && Path.equals(RealDest)) return false; return true; } void ModuleDependencyCollector::writeFileMap() { if (Seen.empty()) return; StringRef VFSDir = getDest(); // Default to use relative overlay directories in the VFS yaml file. This // allows crash reproducer scripts to work across machines. VFSWriter.setOverlayDir(VFSDir); // Explicitly set case sensitivity for the YAML writer. For that, find out // the sensitivity at the path where the headers all collected to. VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir)); std::error_code EC; SmallString<256> YAMLPath = VFSDir; llvm::sys::path::append(YAMLPath, "vfs.yaml"); llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::F_Text); if (EC) { HasErrors = true; return; } VFSWriter.write(OS); } bool ModuleDependencyCollector::getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result) { using namespace llvm::sys; SmallString<256> RealPath; StringRef FileName = path::filename(SrcPath); std::string Dir = path::parent_path(SrcPath).str(); auto DirWithSymLink = SymLinkMap.find(Dir); // Use real_path to fix any symbolic link component present in a path. // Computing the real path is expensive, cache the search through the // parent path directory. if (DirWithSymLink == SymLinkMap.end()) { if (!real_path(Dir, RealPath)) return false; SymLinkMap[Dir] = RealPath.str(); } else { RealPath = DirWithSymLink->second; } path::append(RealPath, FileName); Result.swap(RealPath); return true; } std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src) { using namespace llvm::sys; // We need an absolute path to append to the root. SmallString<256> AbsoluteSrc = Src; fs::make_absolute(AbsoluteSrc); // Canonicalize to a native path to avoid mixed separator styles. path::native(AbsoluteSrc); // Remove redundant leading "./" pieces and consecutive separators. AbsoluteSrc = path::remove_leading_dotslash(AbsoluteSrc); // Canonicalize path by removing "..", "." components. SmallString<256> CanonicalPath = AbsoluteSrc; path::remove_dots(CanonicalPath, /*remove_dot_dot=*/true); // If a ".." component is present after a symlink component, remove_dots may // lead to the wrong real destination path. Let the source be canonicalized // like that but make sure the destination uses the real path. bool HasDotDotInPath = std::count(path::begin(AbsoluteSrc), path::end(AbsoluteSrc), "..") > 0; SmallString<256> RealPath; bool HasRemovedSymlinkComponent = HasDotDotInPath && getRealPath(AbsoluteSrc, RealPath) && !StringRef(CanonicalPath).equals(RealPath); // Build the destination path. SmallString<256> Dest = getDest(); path::append(Dest, path::relative_path(HasRemovedSymlinkComponent ? RealPath : CanonicalPath)); // Copy the file into place. if (std::error_code EC = fs::create_directories(path::parent_path(Dest), /*IgnoreExisting=*/true)) return EC; if (std::error_code EC = fs::copy_file( HasRemovedSymlinkComponent ? RealPath : CanonicalPath, Dest)) return EC; // Use the canonical path under the root for the file mapping. Also create // an additional entry for the real path. addFileMapping(CanonicalPath, Dest); if (HasRemovedSymlinkComponent) addFileMapping(RealPath, Dest); return std::error_code(); } void ModuleDependencyCollector::addFile(StringRef Filename) { if (insertSeen(Filename)) if (copyToRoot(Filename)) HasErrors = true; }
//===--- ModuleDependencyCollector.cpp - Collect module dependencies ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the dependencies of a set of modules. // //===----------------------------------------------------------------------===// #include "clang/Basic/CharInfo.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/Preprocessor.h" #include "clang/Serialization/ASTReader.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace { /// Private implementations for ModuleDependencyCollector class ModuleDependencyListener : public ASTReaderListener { ModuleDependencyCollector &Collector; public: ModuleDependencyListener(ModuleDependencyCollector &Collector) : Collector(Collector) {} bool needsInputFileVisitation() override { return true; } bool needsSystemInputFileVisitation() override { return true; } bool visitInputFile(StringRef Filename, bool IsSystem, bool IsOverridden, bool IsExplicitModule) override { Collector.addFile(Filename); return true; } }; struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks { ModuleDependencyCollector &Collector; ModuleDependencyMMCallbacks(ModuleDependencyCollector &Collector) : Collector(Collector) {} void moduleMapAddHeader(const FileEntry &File) override { StringRef HeaderPath = File.getName(); if (llvm::sys::path::is_absolute(HeaderPath)) Collector.addFile(HeaderPath); } }; } // TODO: move this to Support/Path.h and check for HAVE_REALPATH? static bool real_path(StringRef SrcPath, SmallVectorImpl<char> &RealPath) { #ifdef LLVM_ON_UNIX char CanonicalPath[PATH_MAX]; // TODO: emit a warning in case this fails...? if (!realpath(SrcPath.str().c_str(), CanonicalPath)) return false; SmallString<256> RPath(CanonicalPath); RealPath.swap(RPath); return true; #else // FIXME: Add support for systems without realpath. return false; #endif } void ModuleDependencyCollector::attachToASTReader(ASTReader &R) { R.addListener(llvm::make_unique<ModuleDependencyListener>(*this)); } void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) { PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks( llvm::make_unique<ModuleDependencyMMCallbacks>(*this)); } static bool isCaseSensitivePath(StringRef Path) { SmallString<PATH_MAX> TmpDest = Path, UpperDest, RealDest; // Remove component traversals, links, etc. if (!real_path(Path, TmpDest)) return true; // Current default value in vfs.yaml Path = TmpDest; // Change path to all upper case and ask for its real path, if the latter // exists and is equal to Path, it's not case sensitive. Default to case // sensitive in the absense of realpath, since this is what the VFSWriter // already expects when sensitivity isn't setup. for (auto &C : Path) UpperDest.push_back(toUppercase(C)); if (real_path(UpperDest, RealDest) && Path.equals(RealDest)) return false; return true; } void ModuleDependencyCollector::writeFileMap() { if (Seen.empty()) return; StringRef VFSDir = getDest(); // Default to use relative overlay directories in the VFS yaml file. This // allows crash reproducer scripts to work across machines. VFSWriter.setOverlayDir(VFSDir); // Explicitly set case sensitivity for the YAML writer. For that, find out // the sensitivity at the path where the headers all collected to. VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir)); std::error_code EC; SmallString<256> YAMLPath = VFSDir; llvm::sys::path::append(YAMLPath, "vfs.yaml"); llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::F_Text); if (EC) { HasErrors = true; return; } VFSWriter.write(OS); } bool ModuleDependencyCollector::getRealPath(StringRef SrcPath, SmallVectorImpl<char> &Result) { using namespace llvm::sys; SmallString<256> RealPath; StringRef FileName = path::filename(SrcPath); std::string Dir = path::parent_path(SrcPath).str(); auto DirWithSymLink = SymLinkMap.find(Dir); // Use real_path to fix any symbolic link component present in a path. // Computing the real path is expensive, cache the search through the // parent path directory. if (DirWithSymLink == SymLinkMap.end()) { if (!real_path(Dir, RealPath)) return false; SymLinkMap[Dir] = RealPath.str(); } else { RealPath = DirWithSymLink->second; } path::append(RealPath, FileName); Result.swap(RealPath); return true; } std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src) { using namespace llvm::sys; // We need an absolute path to append to the root. SmallString<256> AbsoluteSrc = Src; fs::make_absolute(AbsoluteSrc); // Canonicalize to a native path to avoid mixed separator styles. path::native(AbsoluteSrc); // Remove redundant leading "./" pieces and consecutive separators. AbsoluteSrc = path::remove_leading_dotslash(AbsoluteSrc); // Canonicalize path by removing "..", "." components. SmallString<256> CanonicalPath = AbsoluteSrc; path::remove_dots(CanonicalPath, /*remove_dot_dot=*/true); // If a ".." component is present after a symlink component, remove_dots may // lead to the wrong real destination path. Let the source be canonicalized // like that but make sure the destination uses the real path. bool HasDotDotInPath = std::count(path::begin(AbsoluteSrc), path::end(AbsoluteSrc), "..") > 0; SmallString<256> RealPath; bool HasRemovedSymlinkComponent = HasDotDotInPath && getRealPath(AbsoluteSrc, RealPath) && !StringRef(CanonicalPath).equals(RealPath); // Build the destination path. SmallString<256> Dest = getDest(); path::append(Dest, path::relative_path(HasRemovedSymlinkComponent ? RealPath : CanonicalPath)); // Copy the file into place. if (std::error_code EC = fs::create_directories(path::parent_path(Dest), /*IgnoreExisting=*/true)) return EC; if (std::error_code EC = fs::copy_file( HasRemovedSymlinkComponent ? RealPath : CanonicalPath, Dest)) return EC; // Use the canonical path under the root for the file mapping. Also create // an additional entry for the real path. addFileMapping(CanonicalPath, Dest); if (HasRemovedSymlinkComponent) addFileMapping(RealPath, Dest); return std::error_code(); } void ModuleDependencyCollector::addFile(StringRef Filename) { if (insertSeen(Filename)) if (copyToRoot(Filename)) HasErrors = true; }
Use toUppercase from include/clang/Basic/CharInfo.h
[CrashReproducer] Use toUppercase from include/clang/Basic/CharInfo.h Use toUppercase instead of ::toupper() git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@265632 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
03da4f32fe82891ca7b9cfa6b0b707f34953d2fb
PWGDQ/dielectron/macrosLMEE/AddTask_rbailhac_ElectronEfficiencyV2_PbPb.C
PWGDQ/dielectron/macrosLMEE/AddTask_rbailhac_ElectronEfficiencyV2_PbPb.C
AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE, TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C", UInt_t trigger = AliVEvent::kINT7, Bool_t rejpileup = kTRUE, const Int_t CenMin = 0, const Int_t CenMax = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10.0, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const Bool_t UsePtVec = kTRUE, const Bool_t DoULSLS = kTRUE, const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;", const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root") { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_rbailhac_test", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+cFileName); std::cout << "Configpath: " << configFilePath << std::endl; if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) { printf("Load macro now\n"); gROOT->LoadMacro(configFilePath.Data()); } // trigger TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; // generators TString suffixgen = ""; if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB"; else if(generators.Contains("Pythia CC")) suffixgen = "_CC"; else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB"; else if(generators.Contains("pizero_0")) suffixgen = "_LF"; else suffixgen = ""; // generator index TString suffixgenID = ""; std::vector<UInt_t> genID; const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()"); if(ngenID > 0) { for (unsigned int i = 0; i < ngenID+1; ++i){ UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i))); genID.push_back(valuegenID); suffixgenID += valuegenID; } } //create task and add it to the manager (MB) TString appendix; appendix += TString::Format("Cen%d_%d_%s_%s_%s",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data()); printf("appendix %s\n", appendix.Data()); //########################################################## //############################################################ // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data())); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); // ######################################################### // ######################################################### // Set TOF correction // if(tofcor){ // SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); // SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); //} // ######################################################### // ######################################################### // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M"))))); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // ######################################################### // ######################################################### // Set minimum and maximum values for pairing task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax); // ######################################################### // ######################################################### // Set Binning single variables if (UsePtVec == true) { std::vector<double> ptBinsVec; const Int_t nBinsPt = (Int_t)gROOT->ProcessLine("GetnBinsPt()"); for (unsigned int i = 0; i < nBinsPt+1; ++i){ Double_t valuesptbins = (Double_t)(gROOT->ProcessLine(Form("GetptBins(%d)",i))); ptBinsVec.push_back(valuesptbins); } task->SetPtBins(ptBinsVec); } else task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1.,1.,20); // 40 before task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); // 90 before task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); // pair variables const Int_t Nmee = 150; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 130; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); //task->SetPhiVBinsLinear(0, TMath::Pi(), 100); //task->SetFillPhiV(kTRUE); // ######################################################### // ######################################################### //task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resolutionFilename); task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename); task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()")); task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine("GetNbinsRelMom()")); task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()")); task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()")); task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()")); //########################################################### //############################################################ // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // ######################################################### // ######################################################### // Set centrality correction. If resoFilename = "" no correction is applied task->SetCentralityFile(centralityFilename); // ######################################################### // ######################################################### // Pairing related config task->SetDoPairing(kTRUE); task->SetULSandLS(DoULSLS); //##################################################### //###################################################### // Generators cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); //################################################# //################################################# // generator ID to select pile-up or not if(ngenID > 0) { task->SetGeneratorMCSignalIndex(genID); task->SetGeneratorULSSignalIndex(genID); task->SetCheckGenID(kTRUE); } //############################################### //############################################## task->SetCocktailWeighting(cocktailFilename); task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename); // ######################################################### // ######################################################### // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name // ######################################################### // ######################################################### // Adding cutsettings // Cuts // Number of cuts const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i))); task->AddTrackCuts(filter); } //######################################## //######################################## TString outlistname = Form("efficiency_%s",appendix.Data()); const TString fileName = outname; mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; }
AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE, TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C", UInt_t trigger = AliVEvent::kINT7, Bool_t rejpileup = kTRUE, const Int_t CenMin = 0, const Int_t CenMax = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10.0, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const Bool_t UsePtVec = kTRUE, const Bool_t DoULSLS = kTRUE, const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;", const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root") { //get the current analysis manager AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_rbailhac_test", "No analysis manager found."); return 0; } //Base Directory for GRID / LEGO Train TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+cFileName); std::cout << "Configpath: " << configFilePath << std::endl; if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) { printf("Load macro now\n"); gROOT->LoadMacro(configFilePath.Data()); } // trigger TString triggername = "NULL"; if(trigger == (UInt_t)AliVEvent::kINT7) triggername = "kINT7"; else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = "kCentral"; else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = "kCombinedCentral"; else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = "kCombinedSemiCentral"; // generators TString suffixgen = ""; if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB"; else if(generators.Contains("Pythia CC")) suffixgen = "_CC"; else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB"; else if(generators.Contains("pizero_0")) suffixgen = "_LF"; else suffixgen = ""; // generator index TString suffixgenID = ""; std::vector<UInt_t> genID; const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()"); if(ngenID > 0) { for (unsigned int i = 0; i < ngenID+1; ++i){ UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i))); genID.push_back(valuegenID); suffixgenID += valuegenID; } } //create task and add it to the manager (MB) TString appendix; appendix += TString::Format("Cen%d_%d_%s_%s_%s",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data()); printf("appendix %s\n", appendix.Data()); //########################################################## //############################################################ // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data())); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); // ######################################################### // ######################################################### // Set TOF correction // if(tofcor){ // SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); // SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); //} // ######################################################### // ######################################################### // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M"))))); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // ######################################################### // ######################################################### // Set minimum and maximum values for pairing task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax); // ######################################################### // ######################################################### // Set Binning single variables if (UsePtVec == true) { const Int_t Npt = 68; Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0}; std::vector<double> v_pte(pte,std::end(pte)); task->SetPtBins(v_pte); } else task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1.,1.,20); // 40 before task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); // 90 before task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); // pair variables const Int_t Nmee = 150; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 130; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); //task->SetPhiVBinsLinear(0, TMath::Pi(), 100); //task->SetFillPhiV(kTRUE); // ######################################################### // ######################################################### //task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resolutionFilename); task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename); task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()")); task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine("GetNbinsRelMom()")); task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()")); task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()")); task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()")); //########################################################### //############################################################ // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // ######################################################### // ######################################################### // Set centrality correction. If resoFilename = "" no correction is applied task->SetCentralityFile(centralityFilename); // ######################################################### // ######################################################### // Pairing related config task->SetDoPairing(kTRUE); task->SetULSandLS(DoULSLS); //##################################################### //###################################################### // Generators cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); //################################################# //################################################# // generator ID to select pile-up or not if(ngenID > 0) { task->SetGeneratorMCSignalIndex(genID); task->SetGeneratorULSSignalIndex(genID); task->SetCheckGenID(kTRUE); } //############################################### //############################################## task->SetCocktailWeighting(cocktailFilename); task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename); // ######################################################### // ######################################################### // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name // ######################################################### // ######################################################### // Adding cutsettings // Cuts // Number of cuts const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()"); //add dielectron analysis with different cuts to the task for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i))); task->AddTrackCuts(filter); } //######################################## //######################################## TString outlistname = Form("efficiency_%s",appendix.Data()); const TString fileName = outname; mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; }
Fix single pte bins
Fix single pte bins
C++
bsd-3-clause
mpuccio/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,dmuhlhei/AliPhysics,adriansev/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,mpuccio/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,dmuhlhei/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,fcolamar/AliPhysics,SHornung1/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,rbailhac/AliPhysics,rbailhac/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,fbellini/AliPhysics,SHornung1/AliPhysics,mpuccio/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,dmuhlhei/AliPhysics,fbellini/AliPhysics,rbailhac/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,rihanphys/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,fbellini/AliPhysics,pchrista/AliPhysics,lcunquei/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,SHornung1/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,fbellini/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,fcolamar/AliPhysics,dmuhlhei/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,lcunquei/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,dmuhlhei/AliPhysics,SHornung1/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,fbellini/AliPhysics,pchrista/AliPhysics,fcolamar/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,rihanphys/AliPhysics,fbellini/AliPhysics,nschmidtALICE/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,nschmidtALICE/AliPhysics,rbailhac/AliPhysics,fbellini/AliPhysics,amaringarcia/AliPhysics,rihanphys/AliPhysics,hzanoli/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,hzanoli/AliPhysics,hzanoli/AliPhysics,adriansev/AliPhysics,hzanoli/AliPhysics,rihanphys/AliPhysics,hzanoli/AliPhysics,nschmidtALICE/AliPhysics
6f3b16d9e63a63775d5f97c465f4a9a6d97b9c58
unittests/Host/FileSystemTest.cpp
unittests/Host/FileSystemTest.cpp
//===-- FileSystemTest.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "lldb/Host/FileSystem.h" #include "llvm/Support/Errc.h" extern const char *TestMainArgv0; using namespace lldb_private; using namespace llvm; using llvm::sys::fs::UniqueID; // Modified from llvm/unittests/Support/VirtualFileSystemTest.cpp namespace { struct DummyFile : public vfs::File { vfs::Status S; explicit DummyFile(vfs::Status S) : S(S) {} llvm::ErrorOr<vfs::Status> status() override { return S; } llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) override { llvm_unreachable("unimplemented"); } std::error_code close() override { return std::error_code(); } }; class DummyFileSystem : public vfs::FileSystem { int FSID; // used to produce UniqueIDs int FileID; // used to produce UniqueIDs std::string cwd; std::map<std::string, vfs::Status> FilesAndDirs; static int getNextFSID() { static int Count = 0; return Count++; } public: DummyFileSystem() : FSID(getNextFSID()), FileID(0) {} ErrorOr<vfs::Status> status(const Twine &Path) override { std::map<std::string, vfs::Status>::iterator I = FilesAndDirs.find(Path.str()); if (I == FilesAndDirs.end()) return make_error_code(llvm::errc::no_such_file_or_directory); return I->second; } ErrorOr<std::unique_ptr<vfs::File>> openFileForRead(const Twine &Path) override { auto S = status(Path); if (S) return std::unique_ptr<vfs::File>(new DummyFile{*S}); return S.getError(); } llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override { return cwd; } std::error_code setCurrentWorkingDirectory(const Twine &Path) override { cwd = Path.str(); return std::error_code(); } // Map any symlink to "/symlink". std::error_code getRealPath(const Twine &Path, SmallVectorImpl<char> &Output) const override { auto I = FilesAndDirs.find(Path.str()); if (I == FilesAndDirs.end()) return make_error_code(llvm::errc::no_such_file_or_directory); if (I->second.isSymlink()) { Output.clear(); Twine("/symlink").toVector(Output); return std::error_code(); } Output.clear(); Path.toVector(Output); return std::error_code(); } struct DirIterImpl : public llvm::vfs::detail::DirIterImpl { std::map<std::string, vfs::Status> &FilesAndDirs; std::map<std::string, vfs::Status>::iterator I; std::string Path; bool isInPath(StringRef S) { if (Path.size() < S.size() && S.find(Path) == 0) { auto LastSep = S.find_last_of('/'); if (LastSep == Path.size() || LastSep == Path.size() - 1) return true; } return false; } DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs, const Twine &_Path) : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()), Path(_Path.str()) { for (; I != FilesAndDirs.end(); ++I) { if (isInPath(I->first)) { CurrentEntry = vfs::directory_entry(I->second.getName(), I->second.getType()); break; } } } std::error_code increment() override { ++I; for (; I != FilesAndDirs.end(); ++I) { if (isInPath(I->first)) { CurrentEntry = vfs::directory_entry(I->second.getName(), I->second.getType()); break; } } if (I == FilesAndDirs.end()) CurrentEntry = vfs::directory_entry(); return std::error_code(); } }; vfs::directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override { return vfs::directory_iterator( std::make_shared<DirIterImpl>(FilesAndDirs, Dir)); } void addEntry(StringRef Path, const vfs::Status &Status) { FilesAndDirs[Path] = Status; } void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 1024, sys::fs::file_type::regular_file, Perms); addEntry(Path, S); } void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 0, sys::fs::file_type::directory_file, Perms); addEntry(Path, S); } void addSymlink(StringRef Path) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all); addEntry(Path, S); } }; } // namespace TEST(FileSystemTest, FileAndDirectoryComponents) { using namespace std::chrono; FileSystem fs; #ifdef _WIN32 FileSpec fs1("C:\\FILE\\THAT\\DOES\\NOT\\EXIST.TXT"); #else FileSpec fs1("/file/that/does/not/exist.txt"); #endif FileSpec fs2(TestMainArgv0); fs.Resolve(fs2); EXPECT_EQ(system_clock::time_point(), fs.GetModificationTime(fs1)); EXPECT_LT(system_clock::time_point() + hours(24 * 365 * 20), fs.GetModificationTime(fs2)); } static IntrusiveRefCntPtr<DummyFileSystem> GetSimpleDummyFS() { IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem()); D->addRegularFile("/foo"); D->addDirectory("/bar"); D->addSymlink("/baz"); D->addRegularFile("/qux", ~sys::fs::perms::all_read); D->setCurrentWorkingDirectory("/"); return D; } TEST(FileSystemTest, Exists) { FileSystem fs(GetSimpleDummyFS()); EXPECT_TRUE(fs.Exists("/foo")); EXPECT_TRUE(fs.Exists(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, Readable) { FileSystem fs(GetSimpleDummyFS()); EXPECT_TRUE(fs.Readable("/foo")); EXPECT_TRUE(fs.Readable(FileSpec("/foo", FileSpec::Style::posix))); EXPECT_FALSE(fs.Readable("/qux")); EXPECT_FALSE(fs.Readable(FileSpec("/qux", FileSpec::Style::posix))); } TEST(FileSystemTest, GetByteSize) { FileSystem fs(GetSimpleDummyFS()); EXPECT_EQ((uint64_t)1024, fs.GetByteSize("/foo")); EXPECT_EQ((uint64_t)1024, fs.GetByteSize(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, GetPermissions) { FileSystem fs(GetSimpleDummyFS()); EXPECT_EQ(sys::fs::all_all, fs.GetPermissions("/foo")); EXPECT_EQ(sys::fs::all_all, fs.GetPermissions(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, MakeAbsolute) { FileSystem fs(GetSimpleDummyFS()); { StringRef foo_relative = "foo"; SmallString<16> foo(foo_relative); auto EC = fs.MakeAbsolute(foo); EXPECT_FALSE(EC); EXPECT_TRUE(foo.equals("/foo")); } { FileSpec file_spec("foo"); auto EC = fs.MakeAbsolute(file_spec); EXPECT_FALSE(EC); EXPECT_EQ("/foo", file_spec.GetPath()); } } TEST(FileSystemTest, Resolve) { FileSystem fs(GetSimpleDummyFS()); { StringRef foo_relative = "foo"; SmallString<16> foo(foo_relative); fs.Resolve(foo); EXPECT_TRUE(foo.equals("/foo")); } { FileSpec file_spec("foo"); fs.Resolve(file_spec); EXPECT_EQ("/foo", file_spec.GetPath()); } { StringRef foo_relative = "bogus"; SmallString<16> foo(foo_relative); fs.Resolve(foo); EXPECT_TRUE(foo.equals("bogus")); } { FileSpec file_spec("bogus"); fs.Resolve(file_spec); EXPECT_EQ("bogus", file_spec.GetPath()); } } FileSystem::EnumerateDirectoryResult VFSCallback(void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef path) { auto visited = static_cast<std::vector<std::string> *>(baton); visited->push_back(path.str()); return FileSystem::eEnumerateDirectoryResultNext; } TEST(FileSystemTest, EnumerateDirectory) { FileSystem fs(GetSimpleDummyFS()); std::vector<std::string> visited; constexpr bool find_directories = true; constexpr bool find_files = true; constexpr bool find_other = true; fs.EnumerateDirectory("/", find_directories, find_files, find_other, VFSCallback, &visited); EXPECT_THAT(visited, testing::UnorderedElementsAre("/foo", "/bar", "/baz", "/qux")); }
//===-- FileSystemTest.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "lldb/Host/FileSystem.h" #include "llvm/Support/Errc.h" extern const char *TestMainArgv0; using namespace lldb_private; using namespace llvm; using llvm::sys::fs::UniqueID; // Modified from llvm/unittests/Support/VirtualFileSystemTest.cpp namespace { struct DummyFile : public vfs::File { vfs::Status S; explicit DummyFile(vfs::Status S) : S(S) {} llvm::ErrorOr<vfs::Status> status() override { return S; } llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) override { llvm_unreachable("unimplemented"); } std::error_code close() override { return std::error_code(); } }; class DummyFileSystem : public vfs::FileSystem { int FSID; // used to produce UniqueIDs int FileID; // used to produce UniqueIDs std::string cwd; std::map<std::string, vfs::Status> FilesAndDirs; static int getNextFSID() { static int Count = 0; return Count++; } public: DummyFileSystem() : FSID(getNextFSID()), FileID(0) {} ErrorOr<vfs::Status> status(const Twine &Path) override { std::map<std::string, vfs::Status>::iterator I = FilesAndDirs.find(Path.str()); if (I == FilesAndDirs.end()) return make_error_code(llvm::errc::no_such_file_or_directory); return I->second; } ErrorOr<std::unique_ptr<vfs::File>> openFileForRead(const Twine &Path) override { auto S = status(Path); if (S) return std::unique_ptr<vfs::File>(new DummyFile{*S}); return S.getError(); } llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override { return cwd; } std::error_code setCurrentWorkingDirectory(const Twine &Path) override { cwd = Path.str(); return std::error_code(); } // Map any symlink to "/symlink". std::error_code getRealPath(const Twine &Path, SmallVectorImpl<char> &Output, bool ExpandTilde = false) const override { auto I = FilesAndDirs.find(Path.str()); if (I == FilesAndDirs.end()) return make_error_code(llvm::errc::no_such_file_or_directory); if (I->second.isSymlink()) { Output.clear(); Twine("/symlink").toVector(Output); return std::error_code(); } Output.clear(); Path.toVector(Output); return std::error_code(); } struct DirIterImpl : public llvm::vfs::detail::DirIterImpl { std::map<std::string, vfs::Status> &FilesAndDirs; std::map<std::string, vfs::Status>::iterator I; std::string Path; bool isInPath(StringRef S) { if (Path.size() < S.size() && S.find(Path) == 0) { auto LastSep = S.find_last_of('/'); if (LastSep == Path.size() || LastSep == Path.size() - 1) return true; } return false; } DirIterImpl(std::map<std::string, vfs::Status> &FilesAndDirs, const Twine &_Path) : FilesAndDirs(FilesAndDirs), I(FilesAndDirs.begin()), Path(_Path.str()) { for (; I != FilesAndDirs.end(); ++I) { if (isInPath(I->first)) { CurrentEntry = vfs::directory_entry(I->second.getName(), I->second.getType()); break; } } } std::error_code increment() override { ++I; for (; I != FilesAndDirs.end(); ++I) { if (isInPath(I->first)) { CurrentEntry = vfs::directory_entry(I->second.getName(), I->second.getType()); break; } } if (I == FilesAndDirs.end()) CurrentEntry = vfs::directory_entry(); return std::error_code(); } }; vfs::directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override { return vfs::directory_iterator( std::make_shared<DirIterImpl>(FilesAndDirs, Dir)); } void addEntry(StringRef Path, const vfs::Status &Status) { FilesAndDirs[Path] = Status; } void addRegularFile(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 1024, sys::fs::file_type::regular_file, Perms); addEntry(Path, S); } void addDirectory(StringRef Path, sys::fs::perms Perms = sys::fs::all_all) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 0, sys::fs::file_type::directory_file, Perms); addEntry(Path, S); } void addSymlink(StringRef Path) { vfs::Status S(Path, UniqueID(FSID, FileID++), std::chrono::system_clock::now(), 0, 0, 0, sys::fs::file_type::symlink_file, sys::fs::all_all); addEntry(Path, S); } }; } // namespace TEST(FileSystemTest, FileAndDirectoryComponents) { using namespace std::chrono; FileSystem fs; #ifdef _WIN32 FileSpec fs1("C:\\FILE\\THAT\\DOES\\NOT\\EXIST.TXT"); #else FileSpec fs1("/file/that/does/not/exist.txt"); #endif FileSpec fs2(TestMainArgv0); fs.Resolve(fs2); EXPECT_EQ(system_clock::time_point(), fs.GetModificationTime(fs1)); EXPECT_LT(system_clock::time_point() + hours(24 * 365 * 20), fs.GetModificationTime(fs2)); } static IntrusiveRefCntPtr<DummyFileSystem> GetSimpleDummyFS() { IntrusiveRefCntPtr<DummyFileSystem> D(new DummyFileSystem()); D->addRegularFile("/foo"); D->addDirectory("/bar"); D->addSymlink("/baz"); D->addRegularFile("/qux", ~sys::fs::perms::all_read); D->setCurrentWorkingDirectory("/"); return D; } TEST(FileSystemTest, Exists) { FileSystem fs(GetSimpleDummyFS()); EXPECT_TRUE(fs.Exists("/foo")); EXPECT_TRUE(fs.Exists(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, Readable) { FileSystem fs(GetSimpleDummyFS()); EXPECT_TRUE(fs.Readable("/foo")); EXPECT_TRUE(fs.Readable(FileSpec("/foo", FileSpec::Style::posix))); EXPECT_FALSE(fs.Readable("/qux")); EXPECT_FALSE(fs.Readable(FileSpec("/qux", FileSpec::Style::posix))); } TEST(FileSystemTest, GetByteSize) { FileSystem fs(GetSimpleDummyFS()); EXPECT_EQ((uint64_t)1024, fs.GetByteSize("/foo")); EXPECT_EQ((uint64_t)1024, fs.GetByteSize(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, GetPermissions) { FileSystem fs(GetSimpleDummyFS()); EXPECT_EQ(sys::fs::all_all, fs.GetPermissions("/foo")); EXPECT_EQ(sys::fs::all_all, fs.GetPermissions(FileSpec("/foo", FileSpec::Style::posix))); } TEST(FileSystemTest, MakeAbsolute) { FileSystem fs(GetSimpleDummyFS()); { StringRef foo_relative = "foo"; SmallString<16> foo(foo_relative); auto EC = fs.MakeAbsolute(foo); EXPECT_FALSE(EC); EXPECT_TRUE(foo.equals("/foo")); } { FileSpec file_spec("foo"); auto EC = fs.MakeAbsolute(file_spec); EXPECT_FALSE(EC); EXPECT_EQ("/foo", file_spec.GetPath()); } } TEST(FileSystemTest, Resolve) { FileSystem fs(GetSimpleDummyFS()); { StringRef foo_relative = "foo"; SmallString<16> foo(foo_relative); fs.Resolve(foo); EXPECT_TRUE(foo.equals("/foo")); } { FileSpec file_spec("foo"); fs.Resolve(file_spec); EXPECT_EQ("/foo", file_spec.GetPath()); } { StringRef foo_relative = "bogus"; SmallString<16> foo(foo_relative); fs.Resolve(foo); EXPECT_TRUE(foo.equals("bogus")); } { FileSpec file_spec("bogus"); fs.Resolve(file_spec); EXPECT_EQ("bogus", file_spec.GetPath()); } } FileSystem::EnumerateDirectoryResult VFSCallback(void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef path) { auto visited = static_cast<std::vector<std::string> *>(baton); visited->push_back(path.str()); return FileSystem::eEnumerateDirectoryResultNext; } TEST(FileSystemTest, EnumerateDirectory) { FileSystem fs(GetSimpleDummyFS()); std::vector<std::string> visited; constexpr bool find_directories = true; constexpr bool find_files = true; constexpr bool find_other = true; fs.EnumerateDirectory("/", find_directories, find_files, find_other, VFSCallback, &visited); EXPECT_THAT(visited, testing::UnorderedElementsAre("/foo", "/bar", "/baz", "/qux")); }
Fix signature in test to match rL346453
[lldb] Fix signature in test to match rL346453 git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@346478 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb
82691cb185e6a0b3657efc444d74e42412eaf00a
Texture/Texture.cpp
Texture/Texture.cpp
/* openfx-arena - https://github.com/olear/openfx-arena Copyright (c) 2015, Ole-André Rodlie <[email protected]> Copyright (c) 2015, FxArena DA <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Neither the name of FxArena DA nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Texture.h" #include "ofxsMacros.h" #include <Magick++.h> #define kPluginName "Texture" #define kPluginGrouping "Draw" #define kPluginDescription "A simple texture generator. \n\nhttps://github.com/olear/openfx-arena" #define kPluginIdentifier "net.fxarena.openfx.Texture" #define kPluginVersionMajor 1 #define kPluginVersionMinor 0 #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderInstanceSafe #define kParamEffect "background" #define kParamEffectLabel "Background" #define kParamEffectHint "Background" #define kParamEffectOptions "effect" #define kParamEffectOptionsLabel "Effect" #define kParamEffectOptionsHint "Apply effect to background" using namespace OFX; class TexturePlugin : public OFX::ImageEffect { public: TexturePlugin(OfxImageEffectHandle handle); virtual ~TexturePlugin(); virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: OFX::Clip *dstClip_; OFX::ChoiceParam *effect_; OFX::ChoiceParam *options_; }; TexturePlugin::TexturePlugin(OfxImageEffectHandle handle) : OFX::ImageEffect(handle) , dstClip_(0) { Magick::InitializeMagick(NULL); dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB)); effect_ = fetchChoiceParam(kParamEffect); options_ = fetchChoiceParam(kParamEffectOptions); assert(effect_ && options_); } TexturePlugin::~TexturePlugin() { } /* Override the render */ void TexturePlugin::render(const OFX::RenderArguments &args) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (!dstClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } std::string channels; switch (dstComponents) { case ePixelComponentRGBA: channels = "RGBA"; break; case ePixelComponentRGB: channels = "RGB"; break; case ePixelComponentAlpha: channels = "A"; break; } // are we in the image bounds OfxRectI dstBounds = dstImg->getBounds(); OfxRectI dstRod = dstImg->getRegionOfDefinition(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { OFX::throwSuiteStatusException(kOfxStatErrValue); return; } // Get params int effect,options; effect_->getValueAtTime(args.time, effect); options_->getValueAtTime(args.time, options); // Generate empty image int width = dstRod.x2-dstRod.x1; int height = dstRod.y2-dstRod.y1; Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)")); switch (effect) { case 1: // Plasma image.read("plasma:fractal"); break; } // apply effect to background, TODO! add params switch (options) { case 1: // Shade image.shade(120,45,true); break; case 2: // Emboss image.blur(0,5); image.emboss(1); break; case 3: // Edge image.blur(0,2); image.edge(10); break; case 4: // Lines image.blur(0,10); image.emboss(4); image.edge(1); break; case 5: // Blobs TODO! image.blur(0,10); image.edge(1); break; case 6: // Filaments TODO! image.blur(0,5); image.normalize(); image.fx("g"); image.sigmoidalContrast(1,15,50); image.solarize(50); break; } // return image switch (dstBitDepth) { case eBitDepthUByte: if (image.depth()>8) image.depth(8); image.write(0,0,width,height,channels,Magick::CharPixel,(float*)dstImg->getPixelData()); break; case eBitDepthUShort: if (image.depth()>16) image.depth(16); image.write(0,0,width,height,channels,Magick::ShortPixel,(float*)dstImg->getPixelData()); break; case eBitDepthFloat: image.write(0,0,width,height,channels,Magick::FloatPixel,(float*)dstImg->getPixelData()); break; } } bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return false; } rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; return true; } mDeclarePluginFactory(TexturePluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextGenerator); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthUByte); desc.addSupportedBitDepth(eBitDepthUShort); desc.addSupportedBitDepth(eBitDepthFloat); desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/) { // there has to be an input clip, even for generators ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->addSupportedComponent(ePixelComponentRGB); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setOptional(true); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->setSupportsTiles(kSupportsTiles); // make some pages PageParamDescriptor *page = desc.definePageParam(kPluginName); { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect); param->setLabel(kParamEffectLabel); param->setHint(kParamEffectHint); param->appendOption("None"); param->appendOption("Plasma"); param->setAnimates(true); page->addChild(*param); } { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffectOptions); param->setLabel(kParamEffectOptionsLabel); param->setHint(kParamEffectOptionsHint); param->appendOption("None"); param->appendOption("Shade"); param->appendOption("Emboss"); param->appendOption("Edge"); param->appendOption("Lines"); //param->appendOption("Blobs"); //param->appendOption("Filaments"); param->setAnimates(true); page->addChild(*param); } } /** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */ ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new TexturePlugin(handle); } void getTexturePluginID(OFX::PluginFactoryArray &ids) { static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); ids.push_back(&p); }
/* openfx-arena - https://github.com/olear/openfx-arena Copyright (c) 2015, Ole-André Rodlie <[email protected]> Copyright (c) 2015, FxArena DA <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Neither the name of FxArena DA nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Texture.h" #include "ofxsMacros.h" #include <Magick++.h> #define kPluginName "Texture" #define kPluginGrouping "Draw" #define kPluginDescription "A simple texture generator. \n\nhttps://github.com/olear/openfx-arena" #define kPluginIdentifier "net.fxarena.openfx.Texture" #define kPluginVersionMajor 1 #define kPluginVersionMinor 0 #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderInstanceSafe #define kParamEffect "background" #define kParamEffectLabel "Background" #define kParamEffectHint "Background" #define kParamEffectOptions "effect" #define kParamEffectOptionsLabel "Effect" #define kParamEffectOptionsHint "Apply effect to background" #define kParamBlurX "blurX" #define kParamBlurXLabel "Blur X" #define kParamBlurXHint "Apply blur effect" #define kParamBlurXDefault 0 #define kParamBlurY "blurY" #define kParamBlurYLabel "Blur Y" #define kParamBlurYHint "Apply blur effect" #define kParamBlurYDefault 10 #define kParamEmboss "emboss" #define kParamEmbossLabel "Emboss" #define kParamEmbossHint "Apply emboss effect" #define kParamEmbossDefault 1 #define kParamEdge "edge" #define kParamEdgeLabel "Edge" #define kParamEdgeHint "Apply edge effect" #define kParamEdgeDefault 1 using namespace OFX; class TexturePlugin : public OFX::ImageEffect { public: TexturePlugin(OfxImageEffectHandle handle); virtual ~TexturePlugin(); virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: OFX::Clip *dstClip_; OFX::ChoiceParam *effect_; OFX::ChoiceParam *options_; OFX::DoubleParam *blurx_; OFX::DoubleParam *blury_; OFX::DoubleParam *emboss_; OFX::DoubleParam *edge_; }; TexturePlugin::TexturePlugin(OfxImageEffectHandle handle) : OFX::ImageEffect(handle) , dstClip_(0) { Magick::InitializeMagick(NULL); dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB)); effect_ = fetchChoiceParam(kParamEffect); options_ = fetchChoiceParam(kParamEffectOptions); blurx_ = fetchDoubleParam(kParamBlurX); blury_ = fetchDoubleParam(kParamBlurY); emboss_ = fetchDoubleParam(kParamEmboss); edge_ = fetchDoubleParam(kParamEdge); assert(effect_ && options_ && blurx_ && blury_ && emboss_ && edge_); } TexturePlugin::~TexturePlugin() { } /* Override the render */ void TexturePlugin::render(const OFX::RenderArguments &args) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (!dstClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != OFX::eBitDepthFloat && dstBitDepth != OFX::eBitDepthUShort && dstBitDepth != OFX::eBitDepthUByte) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha)) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } std::string channels; switch (dstComponents) { case ePixelComponentRGBA: channels = "RGBA"; break; case ePixelComponentRGB: channels = "RGB"; break; case ePixelComponentAlpha: channels = "A"; break; } // are we in the image bounds OfxRectI dstBounds = dstImg->getBounds(); OfxRectI dstRod = dstImg->getRegionOfDefinition(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { OFX::throwSuiteStatusException(kOfxStatErrValue); return; } // Get params int effect,options; double blurx,blury,emboss,edge; effect_->getValueAtTime(args.time, effect); options_->getValueAtTime(args.time, options); blurx_->getValueAtTime(args.time, blurx); blury_->getValueAtTime(args.time, blury); emboss_->getValueAtTime(args.time, emboss); edge_->getValueAtTime(args.time, edge); // Generate empty image int width = dstRod.x2-dstRod.x1; int height = dstRod.y2-dstRod.y1; Magick::Image image(Magick::Geometry(width,height),Magick::Color("rgba(0,0,0,0)")); // generate background switch (effect) { case 1: // Plasma image.read("plasma:"); break; case 2: // Plasma Fractal image.read("plasma:fractal"); break; } // apply options to background, TODO! add params switch (options) { case 1: // Shade image.shade(120,45,true); break; case 2: // Emboss image.blur(blurx,blury); image.emboss(emboss); break; case 3: // Edge image.blur(blurx,blury); image.edge(edge); break; case 4: // Lines image.blur(blurx,blury); image.emboss(emboss); image.edge(edge); break; case 5: // Loops image.blur(blurx,blury); image.edge(edge); image.edge(edge/15); image.blur(0,blury/10); break; case 6: // Filaments TODO! image.blur(blurx,blury); image.normalize(); image.fx("g"); image.sigmoidalContrast(1,15,50); image.solarize(50); break; } // return image switch (dstBitDepth) { case eBitDepthUByte: if (image.depth()>8) image.depth(8); image.write(0,0,width,height,channels,Magick::CharPixel,(float*)dstImg->getPixelData()); break; case eBitDepthUShort: if (image.depth()>16) image.depth(16); image.write(0,0,width,height,channels,Magick::ShortPixel,(float*)dstImg->getPixelData()); break; case eBitDepthFloat: image.write(0,0,width,height,channels,Magick::FloatPixel,(float*)dstImg->getPixelData()); break; } } bool TexturePlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return false; } rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; return true; } mDeclarePluginFactory(TexturePluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void TexturePluginFactory::describe(OFX::ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextGenerator); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthUByte); desc.addSupportedBitDepth(eBitDepthUShort); desc.addSupportedBitDepth(eBitDepthFloat); desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void TexturePluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/) { // there has to be an input clip, even for generators ClipDescriptor* srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->addSupportedComponent(ePixelComponentRGB); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setOptional(true); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->setSupportsTiles(kSupportsTiles); // make some pages PageParamDescriptor *page = desc.definePageParam(kPluginName); { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffect); param->setLabel(kParamEffectLabel); param->setHint(kParamEffectHint); param->appendOption("None"); param->appendOption("Plasma"); param->appendOption("Plasma Fractal"); param->setAnimates(true); page->addChild(*param); } { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamEffectOptions); param->setLabel(kParamEffectOptionsLabel); param->setHint(kParamEffectOptionsHint); param->appendOption("None"); param->appendOption("Shade"); param->appendOption("Emboss"); param->appendOption("Edge"); param->appendOption("Lines"); param->appendOption("Loops"); //param->appendOption("Filaments"); param->setAnimates(true); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamBlurX); param->setLabel(kParamBlurXLabel); param->setHint(kParamBlurXHint); param->setRange(0, 500); param->setDisplayRange(0, 100); param->setDefault(kParamBlurXDefault); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamBlurY); param->setLabel(kParamBlurYLabel); param->setHint(kParamBlurYHint); param->setRange(0, 500); param->setDisplayRange(0, 100); param->setDefault(kParamBlurYDefault); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamEmboss); param->setLabel(kParamEmbossLabel); param->setHint(kParamEmbossHint); param->setRange(0, 500); param->setDisplayRange(0, 25); param->setDefault(kParamEmbossDefault); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamEdge); param->setLabel(kParamEdgeLabel); param->setHint(kParamEdgeHint); param->setRange(0, 500); param->setDisplayRange(0, 25); param->setDefault(kParamEdgeDefault); page->addChild(*param); } } /** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */ ImageEffect* TexturePluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new TexturePlugin(handle); } void getTexturePluginID(OFX::PluginFactoryArray &ids) { static TexturePluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); ids.push_back(&p); }
add some params
Texture: add some params
C++
bsd-3-clause
MrKepzie/openfx-arena,MrKepzie/openfx-arena,MrKepzie/openfx-arena
da442b4d59d0d2d18c63d3df1dde6f735480a9bd
Tipster/Tipster.cpp
Tipster/Tipster.cpp
/* * Copyright 2015 Vale Tolpegin <[email protected]> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Tipster.h" #include <Application.h> #include <Catalog.h> #include <Directory.h> #include <Entry.h> #include <File.h> #include <FindDirectory.h> #include <Path.h> #include <PathFinder.h> #include <stdio.h> #include <stdlib.h> #include <StringList.h> #include <TranslationUtils.h> enum { M_UPDATE_TIP = 'uptp', M_CHECK_TIME = 'cktm' }; Tipster::Tipster() : BTextView("TipView") { fTipsList = BStringList(); SetText(""); UpdateTip(); MakeEditable(false); } bool Tipster::QuitRequested(void) { return true; } void Tipster::AttachedToWindow() { BMessage message(M_CHECK_TIME); fRunner = new BMessageRunner(this, &message, 1000000); BTextView::AttachedToWindow(); } void Tipster::MessageReceived(BMessage* msg) { switch (msg->what) { case M_CHECK_TIME: { if (fTime + 60000000 < system_time()) { //Update the tip every 60 seconds UpdateTip(); } break; } case M_UPDATE_TIP: { UpdateTip(); break; } default: { BTextView::MessageReceived(msg); break; } } } void Tipster::MouseDown(BPoint pt) { BPoint temp; uint32 buttons; GetMouse(&temp, &buttons); if (Bounds().Contains(temp)) { if (buttons == 1) { //1 = left mouse button UpdateTip(); } } } void Tipster::UpdateTip() { entry_ref ref = GetTipsFile(); LoadTips(ref); } entry_ref Tipster::GetTipsFile() { entry_ref ref; BStringList paths; status_t status = BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, "tipster-tips.txt", paths); if (!paths.IsEmpty() && status == B_OK) { for (int32 i = 0; i < paths.CountStrings(); i++) { BEntry data_entry(paths.StringAt(i).String()); data_entry.GetRef(&ref); return ref; } } BEntry entry("tipster-tips.txt"); entry.GetRef(&ref); return ref; } void Tipster::LoadTips(entry_ref ref) { BFile file(&ref, B_READ_ONLY); if (file.InitCheck() != B_OK) return; fTipsList.MakeEmpty(); BString fTips; off_t size = 0; file.GetSize(&size); char* buf = fTips.LockBuffer(size); file.Read(buf, size); fTips.UnlockBuffer(size); fTips.Split("\n%\n", false, fTipsList); fTipNumber = random() % fTipsList.CountStrings(); BStringList fUpdatedList; fTipsList.StringAt(fTipNumber).Split("\n", false, fUpdatedList); fUpdatedList.Remove(0); BString text(fUpdatedList.Join("\n")); SetText(text.String()); fTime = system_time(); }
/* * Copyright 2015 Vale Tolpegin <[email protected]> * All rights reserved. Distributed under the terms of the MIT license. */ #include "Tipster.h" #include <Application.h> #include <Catalog.h> #include <Directory.h> #include <Entry.h> #include <File.h> #include <FindDirectory.h> #include <Path.h> #include <PathFinder.h> #include <stdio.h> #include <stdlib.h> #include <StringList.h> #include <TranslationUtils.h> enum { M_UPDATE_TIP = 'uptp', M_CHECK_TIME = 'cktm' }; Tipster::Tipster() : BTextView("TipView") { fTipsList = BStringList(); SetText(""); UpdateTip(); MakeEditable(false); } bool Tipster::QuitRequested(void) { return true; } void Tipster::AttachedToWindow() { BMessage message(M_CHECK_TIME); fRunner = new BMessageRunner(this, &message, 1000000); BTextView::AttachedToWindow(); } void Tipster::MessageReceived(BMessage* msg) { switch (msg->what) { case M_CHECK_TIME: { if (fTime + 60000000 < system_time()) { //Update the tip every 60 seconds UpdateTip(); } break; } case M_UPDATE_TIP: { UpdateTip(); break; } default: { BTextView::MessageReceived(msg); break; } } } void Tipster::MouseDown(BPoint pt) { BPoint temp; uint32 buttons; GetMouse(&temp, &buttons); if (Bounds().Contains(temp)) { if (buttons == 1) { //1 = left mouse button UpdateTip(); } } } void Tipster::UpdateTip() { entry_ref ref = GetTipsFile(); LoadTips(ref); } entry_ref Tipster::GetTipsFile() { entry_ref ref; BStringList paths; status_t status = BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, "tipster-tips.txt", B_FIND_PATH_EXISTING_ONLY, paths); if (!paths.IsEmpty() && status == B_OK) { for (int32 i = 0; i < paths.CountStrings(); i++) { BEntry data_entry(paths.StringAt(i).String()); data_entry.GetRef(&ref); return ref; } } BEntry entry("tipster-tips.txt"); entry.GetRef(&ref); return ref; } void Tipster::LoadTips(entry_ref ref) { BFile file(&ref, B_READ_ONLY); if (file.InitCheck() != B_OK) return; fTipsList.MakeEmpty(); BString fTips; off_t size = 0; file.GetSize(&size); char* buf = fTips.LockBuffer(size); file.Read(buf, size); fTips.UnlockBuffer(size); fTips.Split("\n%\n", false, fTipsList); fTipNumber = random() % fTipsList.CountStrings(); BStringList fUpdatedList; fTipsList.StringAt(fTipNumber).Split("\n", false, fUpdatedList); fUpdatedList.Remove(0); BString text(fUpdatedList.Join("\n")); SetText(text.String()); fTime = system_time(); }
Fix issues when no file is found on system
Fix issues when no file is found on system
C++
mit
HaikuArchives/Tipster,hannahyp/Tipster
dba7e4cfe09e52ae7e6d298b0119b524d71724f0
PbniHash.cpp
PbniHash.cpp
// PbniHash.cpp : PBNI class #define _CRT_SECURE_NO_DEPRECATE #include "PbniHash.h" #include "libhashish.h" // default constructor PbniHash::PbniHash() { } PbniHash::PbniHash( IPB_Session * pSession ) :m_pSession( pSession ) { struct hi_init_set hi_set; hi_set_zero(&hi_set); hi_set_bucket_size(&hi_set, TABLE_SIZE); hi_set_hash_alg(&hi_set, HI_HASH_DEFAULT); hi_set_coll_eng(&hi_set, COLL_ENG_LIST); hi_set_key_cmp_func(&hi_set, hi_cmp_int32); hi_create(&m_hi_handle, &hi_set); //todo: check error } // destructor PbniHash::~PbniHash() { hi_fini(m_hi_handle); } // method called by PowerBuilder to invoke PBNI class methods PBXRESULT PbniHash::Invoke ( IPB_Session * session, pbobject obj, pbmethodID mid, PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; switch ( mid ) { case mid_Hello: pbxr = this->Hello( ci ); break; case mid_Add: pbxr = this->Add(ci); break; case mid_Get: pbxr = this->Get(ci); break; case mid_Remove: pbxr = this->Remove(ci); break; case mid_Count: pbxr = this->Count(ci); break; case mid_GetKeys: pbxr = this ->GetKeys(ci); break; default: pbxr = PBX_E_INVOKE_METHOD_AMBIGUOUS; } return pbxr; } void PbniHash::Destroy() { delete this; } // Method callable from PowerBuilder PBXRESULT PbniHash::Hello( PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; // return value ci->returnValue->SetString( _T("Hello from PbniHash") ); return pbxr; } PBXRESULT PbniHash::Add( PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; int hi_res; // check arguments if ( ci->pArgs->GetAt(0)->IsNull() || ci->pArgs->GetAt(1)->IsNull() ) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //ce qui suit est identique a faire un AcquireValue sur la key... wchar_t *localKey = (wchar_t *)malloc((wcslen(tszKey) + 1) * sizeof(wchar_t)); wcscpy(localKey, tszKey); //convert the key into ansi //int iKeyLen = wcstombs(NULL, (LPWSTR)tszKey, 0) + 1; //LPSTR ansiKey = (LPSTR)malloc(iKeyLen); //ne pas oublier le free la fermeture //wcstombs(ansiKey, (LPWSTR)(LPWSTR)tszKey, iKeyLen); IPB_Value *data = m_pSession->AcquireValue(ci->pArgs->GetAt(1)); PPBDATAREC dataRecord = (PPBDATAREC)malloc(sizeof(PBDATAREC)); dataRecord->key = localKey; dataRecord->data = data; if (HI_SUCCESS == hi_insert(m_hi_handle, (void*)dataRecord->key, wcslen((LPWSTR)(dataRecord->key))* sizeof(WCHAR), dataRecord /*tszData*/)) ci->returnValue->SetBool(true); else ci->returnValue->SetBool(false); //TODO: need to tell if HI_ERR_DUPKEY } return pbxr; } PBXRESULT PbniHash::Get(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; int iRet; PPBDATAREC data_ptr; if ( ci->pArgs->GetAt(0)->IsNull()) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //wchar_t *localKey = (wchar_t *)malloc((wcslen(tszKey) + 1) * sizeof(wchar_t)); //wcscpy(localKey, tszKey); //search the key iRet = hi_get(m_hi_handle, (void*)tszKey, wcslen(tszKey) * sizeof(WCHAR), (void**)&data_ptr); if (HI_SUCCESS == iRet) m_pSession->SetValue(ci->returnValue, (IPB_Value*)data_ptr->data); else ci->returnValue->SetToNull(); //free(localKey); } return pbxr; } PBXRESULT PbniHash::Remove(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; int iRet; PPBDATAREC data_ptr; if ( ci->pArgs->GetAt(0)->IsNull()) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //wchar_t *localKey = (wchar_t *)malloc((wcslen(tszKey) + 1) * sizeof(wchar_t)); //wcscpy(localKey, tszKey); //search the key iRet = hi_remove(m_hi_handle, (void*)tszKey, wcslen(tszKey) * sizeof(WCHAR),(void**)&data_ptr); if (HI_SUCCESS == iRet) { //TODO: need to free the hashed key, for now we have a *memory leak* :( free(data_ptr->key); m_pSession->ReleaseValue((IPB_Value*)data_ptr->data); free(data_ptr); ci->returnValue->SetBool(true); } else ci->returnValue->SetBool(false); //free(localKey); } return pbxr; } PBXRESULT PbniHash::Count(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; pbulong ulRet = m_hi_handle->no_objects; ci->returnValue->SetUlong(ulRet); return pbxr; } PBXRESULT PbniHash::GetKeys(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; if(ci->pArgs->GetAt(0)->IsNull() || !ci->pArgs->GetAt(0)->IsArray() || !ci->pArgs->GetAt(0)->IsByRef()) { //there must be one reference to an array ci->returnValue->SetBool(false); } else { pblong dim[1] = {1}; //on peut avoir des tableaux avec plusieurs dimensions //ici on utilise un tableau 1 dimension, et on commence 1 pbuint numdim = 1; //arg for the array creation PBArrayInfo::ArrayBound bound; pbarray keys; void *key, *data; unsigned long keylen; hi_iterator_t *iter; if(HI_SUCCESS == hi_iterator_create(m_hi_handle, &iter)) { bound.lowerBound = 1; bound.upperBound = m_hi_handle->no_objects; keys = m_pSession->NewBoundedSimpleArray(pbvalue_string, numdim, &bound); while(HI_SUCCESS == hi_iterator_getnext(iter, &data, &key, &keylen)) { pbstring pVal = m_pSession->NewString((LPCWSTR)key); OutputDebugString((LPCWSTR)key); m_pSession->SetPBStringArrayItem(keys, dim, pVal); dim[0]++; //prochain index //liberer la pbstring ? } hi_iterator_fini(iter); ci->pArgs->GetAt(0)->SetArray(keys); ci->returnValue->SetBool(true); } } return pbxr; }
// PbniHash.cpp : PBNI class #define _CRT_SECURE_NO_DEPRECATE #include "PbniHash.h" #include "libhashish.h" // default constructor PbniHash::PbniHash() { } PbniHash::PbniHash( IPB_Session * pSession ) :m_pSession( pSession ) { struct hi_init_set hi_set; hi_set_zero(&hi_set); hi_set_bucket_size(&hi_set, TABLE_SIZE); hi_set_hash_alg(&hi_set, HI_HASH_DEFAULT); hi_set_coll_eng(&hi_set, COLL_ENG_LIST); hi_set_key_cmp_func(&hi_set, hi_cmp_int32); hi_create(&m_hi_handle, &hi_set); //todo: check error } // destructor PbniHash::~PbniHash() { hi_fini(m_hi_handle); } // method called by PowerBuilder to invoke PBNI class methods PBXRESULT PbniHash::Invoke ( IPB_Session * session, pbobject obj, pbmethodID mid, PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; switch ( mid ) { case mid_Hello: pbxr = this->Hello( ci ); break; case mid_Add: pbxr = this->Add(ci); break; case mid_Get: pbxr = this->Get(ci); break; case mid_Remove: pbxr = this->Remove(ci); break; case mid_Count: pbxr = this->Count(ci); break; case mid_GetKeys: pbxr = this ->GetKeys(ci); break; default: pbxr = PBX_E_INVOKE_METHOD_AMBIGUOUS; } return pbxr; } void PbniHash::Destroy() { delete this; } // Method callable from PowerBuilder PBXRESULT PbniHash::Hello( PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; // return value ci->returnValue->SetString( _T("Hello from PbniHash") ); return pbxr; } PBXRESULT PbniHash::Add( PBCallInfo * ci ) { PBXRESULT pbxr = PBX_OK; int hi_res; // check arguments if ( ci->pArgs->GetAt(0)->IsNull() || ci->pArgs->GetAt(1)->IsNull() ) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //ce qui suit est identique a faire un AcquireValue sur la key... wchar_t *localKey = (wchar_t *)malloc((wcslen(tszKey) + 1) * sizeof(wchar_t)); wcscpy(localKey, tszKey); IPB_Value *data = m_pSession->AcquireValue(ci->pArgs->GetAt(1)); PPBDATAREC dataRecord = (PPBDATAREC)malloc(sizeof(PBDATAREC)); dataRecord->key = localKey; dataRecord->data = data; if (HI_SUCCESS == hi_insert(m_hi_handle, (void*)dataRecord->key, wcslen((LPWSTR)(dataRecord->key))* sizeof(WCHAR), dataRecord /*tszData*/)) ci->returnValue->SetBool(true); else ci->returnValue->SetBool(false); //TODO: need to tell if HI_ERR_DUPKEY } return pbxr; } PBXRESULT PbniHash::Get(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; int iRet; PPBDATAREC data_ptr; if ( ci->pArgs->GetAt(0)->IsNull()) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //search the key iRet = hi_get(m_hi_handle, (void*)tszKey, wcslen(tszKey) * sizeof(WCHAR), (void**)&data_ptr); if (HI_SUCCESS == iRet) m_pSession->SetValue(ci->returnValue, (IPB_Value*)data_ptr->data); else ci->returnValue->SetToNull(); } return pbxr; } PBXRESULT PbniHash::Remove(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; int iRet; PPBDATAREC data_ptr; if ( ci->pArgs->GetAt(0)->IsNull()) { // if any of the passed arguments is null, return the null value ci->returnValue->SetToNull(); } else { pbstring key = ci->pArgs->GetAt(0)->GetString(); LPCTSTR tszKey = m_pSession->GetString(key); //search the key iRet = hi_remove(m_hi_handle, (void*)tszKey, wcslen(tszKey) * sizeof(WCHAR),(void**)&data_ptr); if (HI_SUCCESS == iRet) { //TODO: need to free the hashed key, for now we have a *memory leak* :( free(data_ptr->key); m_pSession->ReleaseValue((IPB_Value*)data_ptr->data); free(data_ptr); ci->returnValue->SetBool(true); } else ci->returnValue->SetBool(false); } return pbxr; } PBXRESULT PbniHash::Count(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; pbulong ulRet = m_hi_handle->no_objects; ci->returnValue->SetUlong(ulRet); return pbxr; } PBXRESULT PbniHash::GetKeys(PBCallInfo *ci) { PBXRESULT pbxr = PBX_OK; if(ci->pArgs->GetAt(0)->IsNull() || !ci->pArgs->GetAt(0)->IsArray() || !ci->pArgs->GetAt(0)->IsByRef()) { //there must be one reference to an array ci->returnValue->SetBool(false); } else { pblong dim[1] = {1}; //on peut avoir des tableaux avec plusieurs dimensions //ici on utilise un tableau 1 dimension, et on commence 1 pbuint numdim = 1; //arg for the array creation PBArrayInfo::ArrayBound bound; pbarray keys; void *key, *data; unsigned long keylen; hi_iterator_t *iter; if(HI_SUCCESS == hi_iterator_create(m_hi_handle, &iter)) { bound.lowerBound = 1; bound.upperBound = m_hi_handle->no_objects; keys = m_pSession->NewBoundedSimpleArray(pbvalue_string, numdim, &bound); while(HI_SUCCESS == hi_iterator_getnext(iter, &data, &key, &keylen)) { pbstring pVal = m_pSession->NewString((LPCWSTR)key); OutputDebugString((LPCWSTR)key); m_pSession->SetPBStringArrayItem(keys, dim, pVal); dim[0]++; //prochain index //liberer la pbstring ? } hi_iterator_fini(iter); ci->pArgs->GetAt(0)->SetArray(keys); ci->returnValue->SetBool(true); } } return pbxr; }
clean up (bis)
clean up (bis)
C++
mit
sebkirche/pbnihash,sebkirche/pbnihash,sebkirche/pbnihash
49c43ac1d33146620a7288827f8a4da01f53be39
C++/continuous-subarray-sum-ii.cpp
C++/continuous-subarray-sum-ii.cpp
// Time: O(n) // Space: O(n) class Solution { public: /** * @param A an integer array * @return A list of integers includes the index of * the first number and the index of the last number */ vector<int> continuousSubarraySumII(vector<int>& A) { if (A.empty()) { return {-1, -1}; } // Case for all elements are negative. const auto it = max_element(A.cbegin(), A.cend()); if (*it < 0) { const int i = distance(A.cbegin(), it); return {i, i}; } // Calculates the circular / non-circular solution. vector<int> circular(2), non_circular(2); if (findMaxSubarray(A, &non_circular) >= findCircularMaxSubarray(A, &circular)) { return non_circular; } else { return circular; } } // Calculates the non-circular solution. int findMaxSubarray(const vector<int>& A, vector<int> *max_i_j) { int curr_sum = 0; int max_sum = INT_MIN; int i = 0, j = 0; *max_i_j = move(vector<int>{i, j}); while (j < A.size()) { curr_sum += A[j]; if (curr_sum >= 0) { if (curr_sum > max_sum) { max_sum = curr_sum; (*max_i_j)[0] = i, (*max_i_j)[1] = j; } } else { curr_sum = 0; i = j + 1; } ++j; } return max_sum; } // Calculates the solution which is circular. int findCircularMaxSubarray(const vector<int>& A, vector<int> *max_i_j) { // Max subarray sum starts at index 0 and ends at or before index i. vector<int> max_sum_from_start(A.size()); vector<int> max_j(A.size()); int sum = A.front(); max_sum_from_start[0] = sum; max_j[0] = 0; for (int j = 1; j < A.size(); ++j) { sum += A[j]; if (sum > max_sum_from_start.back()) { max_sum_from_start[j] = sum; max_j[j] = j; } else { max_sum_from_start[j] = max_sum_from_start[j - 1]; max_j[j] = max_j[j - 1]; } } // Max subarray sum starts at index i + 1 and ends at the last element. vector<int> max_sum_to_end(A.size()); vector<int> max_i(A.size()); sum = 0; max_sum_to_end.back() = sum; max_i.back() = 0; for (int i = A.size() - 2; i >= 0; --i) { sum += A[i + 1]; if (sum > max_sum_to_end[i + 1]) { max_sum_to_end[i] = sum; max_i[i] = i + 1; } else { max_sum_to_end[i] = max_sum_to_end[i + 1]; max_i[i] = max_i[i + 1]; } } // Calculates the max subarray which is circular. int circular_max = 0; for (int i = 0; i < A.size(); ++i) { if (max_sum_from_start[i] + max_sum_to_end[i] > circular_max) { circular_max = max_sum_from_start[i] + max_sum_to_end[i]; (*max_i_j)[0] = max_i[i], (*max_i_j)[1] = max_j[i]; } } return circular_max; } };
// Time: O(n) // Space: O(n) class Solution { public: /** * @param A an integer array * @return A list of integers includes the index of * the first number and the index of the last number */ vector<int> continuousSubarraySumII(vector<int>& A) { if (A.empty()) { return {-1, -1}; } // Calculates the circular / non-circular solution. vector<int> circular(2), non_circular(2); if (findMaxSubarray(A, &non_circular) >= findCircularMaxSubarray(A, &circular)) { return non_circular; } else { return circular; } } // Calculates the non-circular solution. int findMaxSubarray(const vector<int>& A, vector<int> *max_i_j) { int curr_sum = A[0]; int max_sum = curr_sum; for (int i = 0, j = 1; j < A.size(); ++j) { if (curr_sum < 0) { i = j; curr_sum = 0; } curr_sum += A[j]; if (curr_sum > max_sum) { max_sum = curr_sum; (*max_i_j)[0] = i, (*max_i_j)[1] = j; } } return max_sum; } // Calculates the solution which is circular. int findCircularMaxSubarray(const vector<int>& A, vector<int> *max_i_j) { // Max subarray sum starts at index 0 and ends at or before index i. vector<int> max_sum_from_start(A.size()); vector<int> max_j(A.size()); int sum = A.front(); max_sum_from_start[0] = sum; max_j[0] = 0; for (int j = 1; j < A.size(); ++j) { sum += A[j]; if (sum > max_sum_from_start.back()) { max_sum_from_start[j] = sum; max_j[j] = j; } else { max_sum_from_start[j] = max_sum_from_start[j - 1]; max_j[j] = max_j[j - 1]; } } // Max subarray sum starts at index i + 1 and ends at the last element. vector<int> max_sum_to_end(A.size()); vector<int> max_i(A.size()); sum = 0; max_sum_to_end.back() = sum; max_i.back() = 0; for (int i = A.size() - 2; i >= 0; --i) { sum += A[i + 1]; if (sum > max_sum_to_end[i + 1]) { max_sum_to_end[i] = sum; max_i[i] = i + 1; } else { max_sum_to_end[i] = max_sum_to_end[i + 1]; max_i[i] = max_i[i + 1]; } } // Calculates the max subarray which is circular. int circular_max = INT_MIN; for (int i = 0; i < A.size(); ++i) { if (max_sum_from_start[i] + max_sum_to_end[i] > circular_max) { circular_max = max_sum_from_start[i] + max_sum_to_end[i]; (*max_i_j)[0] = max_i[i], (*max_i_j)[1] = max_j[i]; } } return circular_max; } };
Update continuous-subarray-sum-ii.cpp
Update continuous-subarray-sum-ii.cpp
C++
mit
kamyu104/LintCode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode,kamyu104/LintCode,jaredkoontz/lintcode
c90d47e9bf27ef4d814eaee3f2f1abb2f1a813ec
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
NaoTHSoccer/Source/Motion/Engine/InverseKinematicsMotion/Motions/IKParameters.cpp
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.allowedDeviation)= 5; // [mm] PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.allowedDeviation)= 5; // [mm] PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { }
make bodyPitch angle
bugfix: make bodyPitch angle
C++
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
85cb28f40ba5f925ba0105489f1435a5ea4528ab
content/child/runtime_features.cc
content/child/runtime_features.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/runtime_features.h" #include "base/command_line.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #if defined(OS_ANDROID) #include <cpu-features.h> #include "base/android/build_info.h" #endif using WebKit::WebRuntimeFeatures; namespace content { static void SetRuntimeFeatureDefaultsForPlatform() { #if defined(OS_ANDROID) #if !defined(GOOGLE_TV) // MSE/EME implementation needs Android MediaCodec API that was introduced // in JellyBrean. if (base::android::BuildInfo::GetInstance()->sdk_int() < 16) { WebRuntimeFeatures::enableWebKitMediaSource(false); WebRuntimeFeatures::enableLegacyEncryptedMedia(false); } #endif // !defined(GOOGLE_TV) bool enable_webaudio = false; #if defined(ARCH_CPU_ARMEL) // WebAudio needs Android MediaCodec API that was introduced in // JellyBean, and also currently needs NEON support for the FFT. enable_webaudio = (base::android::BuildInfo::GetInstance()->sdk_int() >= 16) && ((android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0); #endif // defined(ARCH_CPU_ARMEL) WebRuntimeFeatures::enableWebAudio(enable_webaudio); // Android does not support the Gamepad API. WebRuntimeFeatures::enableGamepad(false); // Android does not have support for PagePopup WebRuntimeFeatures::enablePagePopup(false); // datalist on Android is not enabled WebRuntimeFeatures::enableDataListElement(false); #endif // defined(OS_ANDROID) } void SetRuntimeFeaturesDefaultsAndUpdateFromArgs( const CommandLine& command_line) { WebRuntimeFeatures::enableStableFeatures(true); if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures)) WebRuntimeFeatures::enableExperimentalFeatures(true); SetRuntimeFeatureDefaultsForPlatform(); if (command_line.HasSwitch(switches::kDisableDatabases)) WebRuntimeFeatures::enableDatabase(false); if (command_line.HasSwitch(switches::kDisableApplicationCache)) WebRuntimeFeatures::enableApplicationCache(false); if (command_line.HasSwitch(switches::kDisableDesktopNotifications)) WebRuntimeFeatures::enableNotifications(false); if (command_line.HasSwitch(switches::kDisableLocalStorage)) WebRuntimeFeatures::enableLocalStorage(false); if (command_line.HasSwitch(switches::kDisableSessionStorage)) WebRuntimeFeatures::enableSessionStorage(false); if (command_line.HasSwitch(switches::kDisableGeolocation)) WebRuntimeFeatures::enableGeolocation(false); if (command_line.HasSwitch(switches::kDisableWebKitMediaSource)) WebRuntimeFeatures::enableWebKitMediaSource(false); #if defined(OS_ANDROID) if (command_line.HasSwitch(switches::kDisableWebRTC)) { WebRuntimeFeatures::enableMediaStream(false); WebRuntimeFeatures::enablePeerConnection(false); } if (!command_line.HasSwitch(switches::kEnableSpeechRecognition) || !command_line.HasSwitch( switches::kEnableExperimentalWebPlatformFeatures)) { WebRuntimeFeatures::enableScriptedSpeech(false); } #endif if (command_line.HasSwitch(switches::kDisableWebAudio)) WebRuntimeFeatures::enableWebAudio(false); if (command_line.HasSwitch(switches::kDisableFullScreen)) WebRuntimeFeatures::enableFullscreen(false); if (command_line.HasSwitch(switches::kEnableEncryptedMedia)) WebRuntimeFeatures::enableEncryptedMedia(true); if (command_line.HasSwitch(switches::kDisableLegacyEncryptedMedia)) WebRuntimeFeatures::enableLegacyEncryptedMedia(false); if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS)) WebRuntimeFeatures::enableWebAnimationsCSS(); if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG)) WebRuntimeFeatures::enableWebAnimationsSVG(); if (command_line.HasSwitch(switches::kEnableWebMIDI)) WebRuntimeFeatures::enableWebMIDI(true); #if defined(OS_ANDROID) // Enable Device Motion on Android by default. WebRuntimeFeatures::enableDeviceMotion( !command_line.HasSwitch(switches::kDisableDeviceMotion)); #else if (command_line.HasSwitch(switches::kEnableDeviceMotion)) WebRuntimeFeatures::enableDeviceMotion(true); #endif if (command_line.HasSwitch(switches::kDisableDeviceOrientation)) WebRuntimeFeatures::enableDeviceOrientation(false); if (command_line.HasSwitch(switches::kDisableSpeechInput)) WebRuntimeFeatures::enableSpeechInput(false); if (command_line.HasSwitch(switches::kDisableFileSystem)) WebRuntimeFeatures::enableFileSystem(false); if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures)) WebRuntimeFeatures::enableExperimentalCanvasFeatures(true); if (command_line.HasSwitch(switches::kEnableSpeechSynthesis)) WebRuntimeFeatures::enableSpeechSynthesis(true); if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions)) WebRuntimeFeatures::enableWebGLDraftExtensions(true); if (command_line.HasSwitch(switches::kEnableHTMLImports)) WebRuntimeFeatures::enableHTMLImports(true); if (command_line.HasSwitch(switches::kEnableOverlayScrollbars)) WebRuntimeFeatures::enableOverlayScrollbars(true); if (command_line.HasSwitch(switches::kEnableInputModeAttribute)) WebRuntimeFeatures::enableInputModeAttribute(true); } } // namespace content
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/child/runtime_features.h" #include "base/command_line.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #if defined(OS_ANDROID) #include <cpu-features.h> #include "base/android/build_info.h" #endif using WebKit::WebRuntimeFeatures; namespace content { static void SetRuntimeFeatureDefaultsForPlatform() { #if defined(OS_ANDROID) #if !defined(GOOGLE_TV) // MSE/EME implementation needs Android MediaCodec API that was introduced // in JellyBrean. if (base::android::BuildInfo::GetInstance()->sdk_int() < 16) { WebRuntimeFeatures::enableWebKitMediaSource(false); WebRuntimeFeatures::enableLegacyEncryptedMedia(false); } #endif // !defined(GOOGLE_TV) bool enable_webaudio = false; #if defined(ARCH_CPU_ARMEL) // WebAudio needs Android MediaCodec API that was introduced in // JellyBean, and also currently needs NEON support for the FFT. enable_webaudio = (base::android::BuildInfo::GetInstance()->sdk_int() >= 16) && ((android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0); #endif // defined(ARCH_CPU_ARMEL) WebRuntimeFeatures::enableWebAudio(enable_webaudio); // Android does not support the Gamepad API. WebRuntimeFeatures::enableGamepad(false); // Android does not have support for PagePopup WebRuntimeFeatures::enablePagePopup(false); // datalist on Android is not enabled WebRuntimeFeatures::enableDataListElement(false); // Android does not yet support the Web Notification API. crbug.com/115320 WebRuntimeFeatures::enableNotifications(false); #endif // defined(OS_ANDROID) } void SetRuntimeFeaturesDefaultsAndUpdateFromArgs( const CommandLine& command_line) { WebRuntimeFeatures::enableStableFeatures(true); if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures)) WebRuntimeFeatures::enableExperimentalFeatures(true); SetRuntimeFeatureDefaultsForPlatform(); if (command_line.HasSwitch(switches::kDisableDatabases)) WebRuntimeFeatures::enableDatabase(false); if (command_line.HasSwitch(switches::kDisableApplicationCache)) WebRuntimeFeatures::enableApplicationCache(false); if (command_line.HasSwitch(switches::kDisableDesktopNotifications)) WebRuntimeFeatures::enableNotifications(false); if (command_line.HasSwitch(switches::kDisableLocalStorage)) WebRuntimeFeatures::enableLocalStorage(false); if (command_line.HasSwitch(switches::kDisableSessionStorage)) WebRuntimeFeatures::enableSessionStorage(false); if (command_line.HasSwitch(switches::kDisableGeolocation)) WebRuntimeFeatures::enableGeolocation(false); if (command_line.HasSwitch(switches::kDisableWebKitMediaSource)) WebRuntimeFeatures::enableWebKitMediaSource(false); #if defined(OS_ANDROID) if (command_line.HasSwitch(switches::kDisableWebRTC)) { WebRuntimeFeatures::enableMediaStream(false); WebRuntimeFeatures::enablePeerConnection(false); } if (!command_line.HasSwitch(switches::kEnableSpeechRecognition) || !command_line.HasSwitch( switches::kEnableExperimentalWebPlatformFeatures)) { WebRuntimeFeatures::enableScriptedSpeech(false); } #endif if (command_line.HasSwitch(switches::kDisableWebAudio)) WebRuntimeFeatures::enableWebAudio(false); if (command_line.HasSwitch(switches::kDisableFullScreen)) WebRuntimeFeatures::enableFullscreen(false); if (command_line.HasSwitch(switches::kEnableEncryptedMedia)) WebRuntimeFeatures::enableEncryptedMedia(true); if (command_line.HasSwitch(switches::kDisableLegacyEncryptedMedia)) WebRuntimeFeatures::enableLegacyEncryptedMedia(false); if (command_line.HasSwitch(switches::kEnableWebAnimationsCSS)) WebRuntimeFeatures::enableWebAnimationsCSS(); if (command_line.HasSwitch(switches::kEnableWebAnimationsSVG)) WebRuntimeFeatures::enableWebAnimationsSVG(); if (command_line.HasSwitch(switches::kEnableWebMIDI)) WebRuntimeFeatures::enableWebMIDI(true); #if defined(OS_ANDROID) // Enable Device Motion on Android by default. WebRuntimeFeatures::enableDeviceMotion( !command_line.HasSwitch(switches::kDisableDeviceMotion)); #else if (command_line.HasSwitch(switches::kEnableDeviceMotion)) WebRuntimeFeatures::enableDeviceMotion(true); #endif if (command_line.HasSwitch(switches::kDisableDeviceOrientation)) WebRuntimeFeatures::enableDeviceOrientation(false); if (command_line.HasSwitch(switches::kDisableSpeechInput)) WebRuntimeFeatures::enableSpeechInput(false); if (command_line.HasSwitch(switches::kDisableFileSystem)) WebRuntimeFeatures::enableFileSystem(false); if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures)) WebRuntimeFeatures::enableExperimentalCanvasFeatures(true); if (command_line.HasSwitch(switches::kEnableSpeechSynthesis)) WebRuntimeFeatures::enableSpeechSynthesis(true); if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions)) WebRuntimeFeatures::enableWebGLDraftExtensions(true); if (command_line.HasSwitch(switches::kEnableHTMLImports)) WebRuntimeFeatures::enableHTMLImports(true); if (command_line.HasSwitch(switches::kEnableOverlayScrollbars)) WebRuntimeFeatures::enableOverlayScrollbars(true); if (command_line.HasSwitch(switches::kEnableInputModeAttribute)) WebRuntimeFeatures::enableInputModeAttribute(true); } } // namespace content
Disable the Web Notification API on Android.
Disable the Web Notification API on Android. Now that we always compile in the code, make sure that we don't accidentally expose the API to websites. BUG=115320 Review URL: https://chromiumcodereview.appspot.com/23514027 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@220937 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,littlstar/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,littlstar/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,patrickm/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,dushu1203/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,M4sse/chromium.src,anirudhSK/chromium,anirudhSK/chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,Just-D/chromium-1,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,Just-D/chromium-1,Just-D/chromium-1,ondra-novak/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,littlstar/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,anirudhSK/chromium,anirudhSK/chromium,littlstar/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,M4sse/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,M4sse/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,patrickm/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,patrickm/chromium.src,patrickm/chromium.src,anirudhSK/chromium,ltilve/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk
d72958ecda785cf10edb5a40f9314c229add9b0b
src/mlpack/methods/logistic_regression/logistic_regression_main.cpp
src/mlpack/methods/logistic_regression/logistic_regression_main.cpp
/** * @file logistic_regression_main.cpp * @author Ryan Curtin * * Main executable for logistic regression. */ #include <mlpack/core.hpp> #include "logistic_regression.hpp" #include <mlpack/core/optimizers/sgd/sgd.hpp> using namespace std; using namespace mlpack; using namespace mlpack::regression; using namespace mlpack::optimization; PROGRAM_INFO("L2-regularized Logistic Regression and Prediction", "An implementation of L2-regularized logistic regression using either the " "L-BFGS optimizer or SGD (stochastic gradient descent). This solves the " "regression problem" "\n\n" " y = (1 / 1 + e^-(X * b))" "\n\n" "where y takes values 0 or 1." "\n\n" "This program allows loading a logistic regression model from a file (-i) " "or training a logistic regression model given training data (-t), or both " "those things at once. In addition, this program allows classification on " "a test dataset (-T) and will save the classification results to the given " "output file (-o). The logistic regression model itself may be saved with " "a file specified using the -m option." "\n\n" "The training data given with the -t option should have class labels as its" " last dimension (so, if the training data is in CSV format, labels should " "be the last column). Alternately, the -l (--labels_file) option may be " "used to specify a separate file of labels." "\n\n" "When a model is being trained, there are many options. L2 regularization " "(to prevent overfitting) can be specified with the -l option, and the " "optimizer used to train the model can be specified with the --optimizer " "option. Available options are 'sgd' (stochastic gradient descent) and " "'lbfgs' (the L-BFGS optimizer). There are also various parameters for the" " optimizer; the --max_iterations parameter specifies the maximum number of" " allowed iterations, and the --tolerance (-e) parameter specifies the " "tolerance for convergence. For the SGD optimizer, the --step_size " "parameter controls the step size taken at each iteration by the optimizer." " If the objective function for your data is oscillating between Inf and " "0, the step size is probably too large. There are more parameters for the" " SGD and L-BFGS optimizers, but the C++ interface must be used to access " "these." "\n\n" "Optionally, the model can be used to predict the responses for another " "matrix of data points, if --test_file is specified. The --test_file " "option can be specified without --input_file, so long as an existing " "logistic regression model is given with --model_file. The output " "predictions from the logistic regression model are stored in the file " "given with --output_predictions." "\n\n" "This implementation of logistic regression does not support the general " "multi-class case but instead only the two-class case. Any responses must " "be either 0 or 1."); // Training parameters. PARAM_STRING("training_file", "A file containing the training set (the matrix " "of predictors, X).", "t", ""); PARAM_STRING("labels_file", "A file containing labels (0 or 1) for the points " "in the training set (y).", "l", ""); // Optimizer parameters. PARAM_DOUBLE("lambda", "L2-regularization parameter for training.", "L", 0.0); PARAM_STRING("optimizer", "Optimizer to use for training ('lbfgs' or 'sgd').", "O", "lbfgs"); PARAM_DOUBLE("tolerance", "Convergence tolerance for optimizer.", "e", 1e-10); PARAM_INT("max_iterations", "Maximum iterations for optimizer (0 indicates no " "limit).", "n", 10000); PARAM_DOUBLE("step_size", "Step size for SGD optimizer.", "s", 0.01); // Model loading/saving. PARAM_STRING("input_model_file", "File containing existing model (parameters).", "m", ""); PARAM_STRING("output_model_file", "File to save trained logistic regression " "model to.", "M", ""); // Testing. PARAM_STRING("test_file", "File containing test dataset.", "T", ""); PARAM_STRING("output_file", "If --test_file is specified, this file is " "where the predicted responses will be saved.", "o", ""); PARAM_DOUBLE("decision_boundary", "Decision boundary for prediction; if the " "logistic function for a point is less than the boundary, the class is " "taken to be 0; otherwise, the class is 1.", "d", 0.5); int main(int argc, char** argv) { CLI::ParseCommandLine(argc, argv); // Collect command-line options. const string trainingFile = CLI::GetParam<string>("training_file"); const string labelsFile = CLI::GetParam<string>("labels_file"); const double lambda = CLI::GetParam<double>("lambda"); const string optimizerType = CLI::GetParam<string>("optimizer"); const double tolerance = CLI::GetParam<double>("tolerance"); const double stepSize = CLI::GetParam<double>("step_size"); const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations"); const string inputModelFile = CLI::GetParam<string>("input_model"); const string outputModelFile = CLI::GetParam<string>("output_model"); const string testFile = CLI::GetParam<string>("test_file"); const string outputFile = CLI::GetParam<string>("output_file"); const double decisionBoundary = CLI::GetParam<double>("decision_boundary"); // One of inputFile and modelFile must be specified. if (trainingFile.empty() && inputModelFile.empty()) Log::Fatal << "One of --input_model or --training_file must be specified." << endl; // If no output file is given, the user should know that the model will not be // saved, but only if a model is being trained. if (outputFile.empty() && !trainingFile.empty()) Log::Warn << "--output_model not given; trained model will not be saved." << endl; // Tolerance needs to be positive. if (tolerance < 0.0) Log::Fatal << "Tolerance must be positive (received " << tolerance << ")." << endl; // Optimizer has to be L-BFGS or SGD. if (optimizerType != "lbfgs" && optimizerType != "sgd") Log::Fatal << "--optimizer must be 'lbfgs' or 'sgd'." << endl; // Lambda must be positive. if (lambda < 0.0) Log::Fatal << "L2-regularization parameter (--lambda) must be positive (" << "received " << lambda << ")." << endl; // Decision boundary must be between 0 and 1. if (decisionBoundary < 0.0 || decisionBoundary > 1.0) Log::Fatal << "Decision boundary (--decision_boundary) must be between 0.0 " << "and 1.0 (received " << decisionBoundary << ")." << endl; if ((stepSize < 0.0) && (optimizerType == "sgd")) Log::Fatal << "Step size (--step_size) must be positive (received " << stepSize << ")." << endl; if (CLI::HasParam("step_size") && optimizerType == "lbfgs") Log::Warn << "Step size (--step_size) ignored because 'sgd' optimizer is " << "not being used." << endl; // These are the matrices we might use. arma::mat regressors; arma::Mat<size_t> responsesMat; arma::Row<size_t> responses; arma::mat testSet; arma::Row<size_t> predictions; // Load data matrix. if (!trainingFile.empty()) data::Load(trainingFile, regressors, true); // Load the model, if necessary. LogisticRegression<> model(0, 0); // Empty model. if (!inputModelFile.empty()) { data::Load(inputModelFile, "logistic_regression_model", model); } else { // Set the size of the parameters vector, if necessary. if (labelsFile.empty()) model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows - 1); else model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows); } // Check if the responses are in a separate file. if (!trainingFile.empty() && !labelsFile.empty()) { data::Load(labelsFile, responsesMat, true); if (responsesMat.n_cols == 1) responses = responsesMat.col(0).t(); else responses = responsesMat.row(0); if (responses.n_cols != regressors.n_cols) Log::Fatal << "The labels (--labels_file) must have the same number of " << "points as the training dataset (--training_file)." << endl; } else if (!trainingFile.empty()) { // The initial predictors for y, Nx1. responses = arma::conv_to<arma::Row<size_t>>::from( regressors.row(regressors.n_rows - 1)); regressors.shed_row(regressors.n_rows - 1); } // Verify the labels. if (!trainingFile.empty() && max(responses) > 1) Log::Fatal << "The labels must be either 0 or 1, not " << max(responses) << "!" << endl; // Now, do the training. if (!trainingFile.empty()) { LogisticRegressionFunction<> lrf(regressors, responses, model.Parameters()); if (optimizerType == "sgd") { SGD<LogisticRegressionFunction<>> sgdOpt(lrf); sgdOpt.MaxIterations() = maxIterations; sgdOpt.Tolerance() = tolerance; sgdOpt.StepSize() = stepSize; Log::Info << "Training model with SGD optimizer." << endl; // This will train the model. model.Train(sgdOpt); } else if (optimizerType == "lbfgs") { L_BFGS<LogisticRegressionFunction<>> lbfgsOpt(lrf); lbfgsOpt.MaxIterations() = maxIterations; lbfgsOpt.MinGradientNorm() = tolerance; Log::Info << "Training model with L-BFGS optimizer." << endl; // This will train the model. model.Train(lbfgsOpt); } } if (!testFile.empty()) { data::Load(testFile, testSet, true); // We must perform predictions on the test set. Training (and the // optimizer) are irrelevant here; we'll pass in the model we have. Log::Info << "Predicting classes of points in '" << testFile << "'." << endl; model.Predict(testSet, predictions, decisionBoundary); // Save the results, if necessary. if (!outputFile.empty()) data::Save(outputFile, predictions, false); } if (!outputModelFile.empty()) { Log::Info << "Saving model to '" << outputModelFile << "'." << endl; data::Save(outputModelFile, "logistic_regression_model", model, false); } }
/** * @file logistic_regression_main.cpp * @author Ryan Curtin * * Main executable for logistic regression. */ #include <mlpack/core.hpp> #include "logistic_regression.hpp" #include <mlpack/core/optimizers/sgd/sgd.hpp> using namespace std; using namespace mlpack; using namespace mlpack::regression; using namespace mlpack::optimization; PROGRAM_INFO("L2-regularized Logistic Regression and Prediction", "An implementation of L2-regularized logistic regression using either the " "L-BFGS optimizer or SGD (stochastic gradient descent). This solves the " "regression problem" "\n\n" " y = (1 / 1 + e^-(X * b))" "\n\n" "where y takes values 0 or 1." "\n\n" "This program allows loading a logistic regression model from a file (-i) " "or training a logistic regression model given training data (-t), or both " "those things at once. In addition, this program allows classification on " "a test dataset (-T) and will save the classification results to the given " "output file (-o). The logistic regression model itself may be saved with " "a file specified using the -m option." "\n\n" "The training data given with the -t option should have class labels as its" " last dimension (so, if the training data is in CSV format, labels should " "be the last column). Alternately, the -l (--labels_file) option may be " "used to specify a separate file of labels." "\n\n" "When a model is being trained, there are many options. L2 regularization " "(to prevent overfitting) can be specified with the -l option, and the " "optimizer used to train the model can be specified with the --optimizer " "option. Available options are 'sgd' (stochastic gradient descent) and " "'lbfgs' (the L-BFGS optimizer). There are also various parameters for the" " optimizer; the --max_iterations parameter specifies the maximum number of" " allowed iterations, and the --tolerance (-e) parameter specifies the " "tolerance for convergence. For the SGD optimizer, the --step_size " "parameter controls the step size taken at each iteration by the optimizer." " If the objective function for your data is oscillating between Inf and " "0, the step size is probably too large. There are more parameters for the" " SGD and L-BFGS optimizers, but the C++ interface must be used to access " "these." "\n\n" "Optionally, the model can be used to predict the responses for another " "matrix of data points, if --test_file is specified. The --test_file " "option can be specified without --input_file, so long as an existing " "logistic regression model is given with --model_file. The output " "predictions from the logistic regression model are stored in the file " "given with --output_predictions." "\n\n" "This implementation of logistic regression does not support the general " "multi-class case but instead only the two-class case. Any responses must " "be either 0 or 1."); // Training parameters. PARAM_STRING("training_file", "A file containing the training set (the matrix " "of predictors, X).", "t", ""); PARAM_STRING("labels_file", "A file containing labels (0 or 1) for the points " "in the training set (y).", "l", ""); // Optimizer parameters. PARAM_DOUBLE("lambda", "L2-regularization parameter for training.", "L", 0.0); PARAM_STRING("optimizer", "Optimizer to use for training ('lbfgs' or 'sgd').", "O", "lbfgs"); PARAM_DOUBLE("tolerance", "Convergence tolerance for optimizer.", "e", 1e-10); PARAM_INT("max_iterations", "Maximum iterations for optimizer (0 indicates no " "limit).", "n", 10000); PARAM_DOUBLE("step_size", "Step size for SGD optimizer.", "s", 0.01); // Model loading/saving. PARAM_STRING("input_model_file", "File containing existing model (parameters).", "m", ""); PARAM_STRING("output_model_file", "File to save trained logistic regression " "model to.", "M", ""); // Testing. PARAM_STRING("test_file", "File containing test dataset.", "T", ""); PARAM_STRING("output_file", "If --test_file is specified, this file is " "where the predicted responses will be saved.", "o", ""); PARAM_DOUBLE("decision_boundary", "Decision boundary for prediction; if the " "logistic function for a point is less than the boundary, the class is " "taken to be 0; otherwise, the class is 1.", "d", 0.5); int main(int argc, char** argv) { CLI::ParseCommandLine(argc, argv); // Collect command-line options. const string trainingFile = CLI::GetParam<string>("training_file"); const string labelsFile = CLI::GetParam<string>("labels_file"); const double lambda = CLI::GetParam<double>("lambda"); const string optimizerType = CLI::GetParam<string>("optimizer"); const double tolerance = CLI::GetParam<double>("tolerance"); const double stepSize = CLI::GetParam<double>("step_size"); const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations"); const string inputModelFile = CLI::GetParam<string>("input_model"); const string outputModelFile = CLI::GetParam<string>("output_model"); const string testFile = CLI::GetParam<string>("test_file"); const string outputFile = CLI::GetParam<string>("output_file"); const double decisionBoundary = CLI::GetParam<double>("decision_boundary"); // One of inputFile and modelFile must be specified. if (trainingFile.empty() && inputModelFile.empty()) Log::Fatal << "One of --input_model or --training_file must be specified." << endl; // If no output file is given, the user should know that the model will not be // saved, but only if a model is being trained. if (outputModelFile.empty() && !trainingFile.empty()) Log::Warn << "--output_model not given; trained model will not be saved." << endl; // Tolerance needs to be positive. if (tolerance < 0.0) Log::Fatal << "Tolerance must be positive (received " << tolerance << ")." << endl; // Optimizer has to be L-BFGS or SGD. if (optimizerType != "lbfgs" && optimizerType != "sgd") Log::Fatal << "--optimizer must be 'lbfgs' or 'sgd'." << endl; // Lambda must be positive. if (lambda < 0.0) Log::Fatal << "L2-regularization parameter (--lambda) must be positive (" << "received " << lambda << ")." << endl; // Decision boundary must be between 0 and 1. if (decisionBoundary < 0.0 || decisionBoundary > 1.0) Log::Fatal << "Decision boundary (--decision_boundary) must be between 0.0 " << "and 1.0 (received " << decisionBoundary << ")." << endl; if ((stepSize < 0.0) && (optimizerType == "sgd")) Log::Fatal << "Step size (--step_size) must be positive (received " << stepSize << ")." << endl; if (CLI::HasParam("step_size") && optimizerType == "lbfgs") Log::Warn << "Step size (--step_size) ignored because 'sgd' optimizer is " << "not being used." << endl; // These are the matrices we might use. arma::mat regressors; arma::Mat<size_t> responsesMat; arma::Row<size_t> responses; arma::mat testSet; arma::Row<size_t> predictions; // Load data matrix. if (!trainingFile.empty()) data::Load(trainingFile, regressors, true); // Load the model, if necessary. LogisticRegression<> model(0, 0); // Empty model. if (!inputModelFile.empty()) { data::Load(inputModelFile, "logistic_regression_model", model); } else { // Set the size of the parameters vector, if necessary. if (labelsFile.empty()) model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows - 1); else model.Parameters() = arma::zeros<arma::vec>(regressors.n_rows); } // Check if the responses are in a separate file. if (!trainingFile.empty() && !labelsFile.empty()) { data::Load(labelsFile, responsesMat, true); if (responsesMat.n_cols == 1) responses = responsesMat.col(0).t(); else responses = responsesMat.row(0); if (responses.n_cols != regressors.n_cols) Log::Fatal << "The labels (--labels_file) must have the same number of " << "points as the training dataset (--training_file)." << endl; } else if (!trainingFile.empty()) { // The initial predictors for y, Nx1. responses = arma::conv_to<arma::Row<size_t>>::from( regressors.row(regressors.n_rows - 1)); regressors.shed_row(regressors.n_rows - 1); } // Verify the labels. if (!trainingFile.empty() && max(responses) > 1) Log::Fatal << "The labels must be either 0 or 1, not " << max(responses) << "!" << endl; // Now, do the training. if (!trainingFile.empty()) { LogisticRegressionFunction<> lrf(regressors, responses, model.Parameters()); if (optimizerType == "sgd") { SGD<LogisticRegressionFunction<>> sgdOpt(lrf); sgdOpt.MaxIterations() = maxIterations; sgdOpt.Tolerance() = tolerance; sgdOpt.StepSize() = stepSize; Log::Info << "Training model with SGD optimizer." << endl; // This will train the model. model.Train(sgdOpt); } else if (optimizerType == "lbfgs") { L_BFGS<LogisticRegressionFunction<>> lbfgsOpt(lrf); lbfgsOpt.MaxIterations() = maxIterations; lbfgsOpt.MinGradientNorm() = tolerance; Log::Info << "Training model with L-BFGS optimizer." << endl; // This will train the model. model.Train(lbfgsOpt); } } if (!testFile.empty()) { data::Load(testFile, testSet, true); // We must perform predictions on the test set. Training (and the // optimizer) are irrelevant here; we'll pass in the model we have. Log::Info << "Predicting classes of points in '" << testFile << "'." << endl; model.Predict(testSet, predictions, decisionBoundary); // Save the results, if necessary. if (!outputFile.empty()) data::Save(outputFile, predictions, false); } if (!outputModelFile.empty()) { Log::Info << "Saving model to '" << outputModelFile << "'." << endl; data::Save(outputModelFile, "logistic_regression_model", model, false); } }
Fix confusion in error message
Fix confusion in error message The error message was "missing output_model", while the variable used for detecting it was "outputFile", which refers to the testing output, rather than the model output.
C++
bsd-3-clause
darcyliu/mlpack,darcyliu/mlpack,theranger/mlpack,ajjl/mlpack,palashahuja/mlpack,ranjan1990/mlpack,palashahuja/mlpack,theranger/mlpack,ajjl/mlpack,palashahuja/mlpack,ajjl/mlpack,darcyliu/mlpack,ranjan1990/mlpack,theranger/mlpack,ranjan1990/mlpack
338f5127c4d40c5c6a40b130e83b41e42ed8bdf7
test/TestPolarDecoder.cpp
test/TestPolarDecoder.cpp
#include <gtest/gtest.h> #include <cstdlib> #include "FEC/Polar.h" TEST(PolarDecoderTest, CorruptedPacket) { constexpr std::size_t N = 2048u; constexpr std::size_t M = 2048u; constexpr std::size_t K = 1024u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, M / 8u> test_code = { 48, 77, 88, 229, 144, 16, 207, 156, 241, 237, 136, 38, 204, 99, 180, 7, 251, 231, 234, 207, 204, 54, 168, 52, 29, 145, 84, 174, 16, 243, 253, 216, 239, 125, 114, 126, 97, 123, 182, 92, 14, 0, 191, 219, 139, 183, 125, 232, 39, 131, 26, 197, 144, 135, 253, 98, 247, 231, 168, 67, 170, 203, 248, 53, 122, 12, 226, 146, 21, 241, 102, 117, 191, 133, 62, 121, 221, 252, 123, 226, 37, 45, 144, 16, 91, 23, 49, 30, 41, 129, 198, 47, 101, 195, 53, 61, 113, 37, 155, 138, 111, 98, 120, 129, 21, 80, 122, 168, 143, 92, 13, 81, 139, 80, 176, 95, 182, 65, 227, 66, 136, 93, 185, 66, 104, 60, 228, 143, 2, 178, 115, 229, 20, 62, 160, 118, 123, 37, 240, 74, 183, 195, 26, 227, 100, 102, 216, 177, 11, 60, 45, 224, 51, 234, 233, 49, 162, 182, 231, 46, 90, 149, 136, 109, 9, 109, 108, 168, 163, 128, 33, 82, 63, 73, 232, 121, 74, 191, 190, 243, 49, 218, 51, 200, 186, 17, 151, 203, 244, 185, 158, 246, 77, 149, 26, 222, 194, 100, 54, 225, 46, 111, 15, 142, 255, 151, 67, 56, 225, 151, 70, 211, 160, 87, 13, 85, 247, 44, 63, 127, 147, 152, 148, 160, 250, 231, 255, 177, 189, 47, 229, 113, 46, 201, 212, 97, 14, 52, 77, 214, 209, 82, 25, 238, 204, 63, 117, 27, 120, 129, 171, 78, 8, 160, 53, 205 }; std::array<uint8_t, K / 8u> test_data = { 126, 39, 149, 254, 48, 138, 55, 210, 161, 181, 214, 72, 61, 234, 184, 41, 79, 77, 247, 139, 157, 161, 58, 239, 174, 224, 225, 56, 176, 222, 221, 124, 233, 10, 215, 155, 240, 190, 58, 139, 19, 203, 146, 94, 24, 128, 242, 246, 37, 74, 0, 61, 136, 123, 84, 64, 93, 2, 6, 170, 160, 227, 188, 28, 139, 7, 50, 4, 164, 245, 140, 188, 195, 176, 128, 225, 5, 199, 145, 115, 146, 174, 255, 188, 94, 200, 82, 40, 86, 110, 91, 141, 195, 241, 152, 38, 223, 206, 155, 89, 143, 19, 143, 111, 15, 11, 228, 175, 215, 94, 66, 210, 250, 228, 192, 80, 158, 135, 22, 214, 45, 118, 45, 25, 255, 235, 152, 251 }; auto test_decoded = TestDecoder::decode(test_code); for (std::size_t i = 0u; i < test_data.size(); i++) { EXPECT_EQ((int)test_data[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize1024) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 1024u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize768) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 768u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize520) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 520u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize512) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 512u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } }
#include <gtest/gtest.h> #include <cstdlib> #include "FEC/Polar.h" TEST(PolarDecoderTest, CorruptedPacket) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 1024u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, M / 8u> test_code = { 130, 203, 189, 91, 191, 32, 12, 119, 244, 197, 173, 72, 151, 140, 64, 119, 192, 16, 108, 135, 221, 241, 253, 243, 174, 212, 255, 251, 50, 95, 39, 180, 198, 196, 125, 219, 105, 229, 81, 124, 136, 27, 190, 68, 32, 244, 111, 67, 2, 51, 207, 252, 111, 223, 65, 21, 39, 26, 69, 48, 247, 143, 193, 4, 221, 28, 121, 227, 231, 169, 145, 220, 86, 130, 26, 168, 80, 121, 66, 160, 212, 240, 6, 100, 65, 7, 121, 46, 172, 67, 129, 54, 237, 107, 247, 200, 22, 207, 37, 110, 190, 234, 108, 221, 234, 101, 43, 93, 159, 185, 135, 97, 243, 250, 206, 226, 168, 16, 37, 157, 138, 81, 119, 247, 167, 119, 173, 248 }; std::array<uint8_t, K / 8u> test_data = { 247, 187, 97, 143, 15, 205, 248, 34, 174, 106, 41, 135, 120, 220, 24, 199, 138, 81, 30, 36, 80, 33, 178, 0, 127, 178, 230, 41, 136, 155, 118, 181, 251, 228, 52, 173, 15, 186, 155, 119, 117, 50, 181, 238, 207, 220, 194, 176, 226, 234, 206, 226, 168, 16, 36, 29, 138, 91, 55, 247, 167, 127, 141, 248 }; auto test_decoded = TestDecoder::decode(test_code); for (std::size_t i = 0u; i < test_data.size(); i++) { EXPECT_EQ((int)test_data[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize1024) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 1024u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize768) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 768u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize520) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 520u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } } TEST(PolarDecoderTest, DecodeBlockSize512) { constexpr std::size_t N = 1024u; constexpr std::size_t M = 512u; constexpr std::size_t K = 512u; using TestDataIndices = Thiemar::Polar::PolarCodeConstructor<N, M, K, -2>::data_index_sequence; using TestEncoder = Thiemar::Polar::PolarEncoder<N, M, K, TestDataIndices>; using TestDecoder = Thiemar::Polar::SuccessiveCancellationListDecoder<N, M, K, TestDataIndices>; /* Set up test buffers. */ std::array<uint8_t, K / 8u> test_in = {}; /* Seed RNG for repeatibility. */ std::srand(123u); for (std::size_t i = 0u; i < test_in.size(); i++) { test_in[i] = std::rand() & 0xffu; } auto test_out = TestEncoder::encode(test_in); auto test_decoded = TestDecoder::decode(test_out); for (std::size_t i = 0u; i < test_in.size(); i++) { EXPECT_EQ((int)test_in[i], (int)test_decoded[i]) << "Buffers differ at index " << i; } }
Update corrupted packet test cases
Update corrupted packet test cases
C++
mit
thiemar/fec,thiemar/fec,thiemar/fec
944c80e14407bf49b75d50052fa15459524bfd8f
test/compile_function.cpp
test/compile_function.cpp
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE compile_function #include <boost/test/unit_test.hpp> #include "../src/compile_function.hpp" #include "../src/core_unique_ids.hpp" #include "../src/error/compile_exception.hpp" #include "state_utils.hpp" #include <llvm/IR/Function.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Value.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> #include <memory> #include <unordered_map> #include <utility> #include <iterator> #include <string> using std::pair; using std::tie; using std::ignore; using std::unique_ptr; using std::unordered_map; using std::advance; using std::string; using llvm::Function; using llvm::Value; using llvm::IntegerType; using llvm::Type; using llvm::verifyFunction; using llvm::raw_string_ostream; using boost::get; using namespace symbol_shortcuts; BOOST_AUTO_TEST_CASE(compile_signature_test) { const type_symbol int64_type{IntegerType::get(context.llvm(), 64)}; const ref a{"a"_id}; const ref b{"b"_id}; const ref c{"c"_id}; const any_symbol params1 = list { list{a, int64_type}, list{b, int64_type}, list{c, int64_type}, }; const any_symbol return_type1 = int64_type; unique_ptr<Function> function1; unordered_map<identifier_id_t, named_value_info> parameter_table1; tie(function1, parameter_table1) = compile_signature(params1, return_type1, context); BOOST_CHECK(function1 != nullptr); BOOST_CHECK_EQUAL(parameter_table1.size(), 3); BOOST_CHECK(parameter_table1.count(a.identifier())); BOOST_CHECK(parameter_table1.count(b.identifier())); BOOST_CHECK(parameter_table1.count(c.identifier())); BOOST_CHECK(parameter_table1.at(b.identifier()).llvm_value == (++function1->arg_begin())); const any_symbol params2 = list { list{a, int64_type}, list{b, int64_type}, list{a, int64_type}, // duplicate parameter name }; const any_symbol return_type2 = int64_type; BOOST_CHECK_THROW(compile_signature(params2, return_type2, context), compile_exception); } BOOST_AUTO_TEST_CASE(compile_instruction_test) { Type* llvm_int64 = IntegerType::get(context.llvm(), 64); const type_symbol int64_type{llvm_int64}; const id_symbol add_constructor{unique_ids::ADD}; const list_symbol instruction1{add_constructor, int64_type}; const instruction_info got1 = parse_instruction(instruction1); BOOST_CHECK(get<instruction_info::add>(got1.kind).type == int64_type); const id_symbol div_constructor{unique_ids::DIV}; const list_symbol instruction2{div_constructor, int64_type}; const instruction_info got2 = parse_instruction(instruction2); BOOST_CHECK(get<instruction_info::div>(got2.kind).type == int64_type); const id_symbol cmp_constructor{unique_ids::CMP}; const ref_symbol cmp_ref{"asdfasdf"_id, &cmp_constructor}; const id_symbol lt{unique_ids::LT}; const list_symbol instruction3{cmp_ref, lt, int64_type}; const instruction_info got3 = parse_instruction(instruction3); BOOST_CHECK(get<instruction_info::cmp>(got3.kind).cmp_kind == unique_ids::LT); BOOST_CHECK(get<instruction_info::cmp>(got3.kind).type == int64_type); } const type_symbol int64_type{IntegerType::get(context.llvm(), 64)}; const ref a{"a"_id}; const ref b{"b"_id}; const ref v{"v"_id}; const ref w{"w"_id}; const ref x{"x"_id}; const ref y{"y"_id}; const ref z{"z"_id}; const ref block1{"block1"_id}; const ref block2{"block2"_id}; const ref block3{"block3"_id}; const ref block4{"block4"_id}; const id_symbol let{unique_ids::LET}; const list_symbol add_int64 = {id_symbol{unique_ids::ADD}, int64_type}; const list_symbol sub_int64 = {id_symbol{unique_ids::SUB}, int64_type}; const list_symbol return_int64 = {id_symbol{unique_ids::RETURN}, int64_type}; const list_symbol alloc_int64 = {id_symbol{unique_ids::ALLOC}, int64_type}; const list_symbol cmp_eq_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::EQ}, int64_type}; const list_symbol cond_branch = {id_symbol{unique_ids::COND_BRANCH}}; const list_symbol branch = {id_symbol{unique_ids::BRANCH}}; const list_symbol phi_int64 = {id_symbol{unique_ids::PHI}, int64_type}; BOOST_AUTO_TEST_CASE(branch_test) { const list_symbol params = { list{a, int64_type}, list{b, int64_type}, }; const type_symbol return_type = int64_type; const list_symbol body = { list{block1, list { list{let, x, cmp_eq_int64, a, b}, list{cond_branch, x, block2, block3} }}, list{block2, list { list{let, y, add_int64, a, b}, list{return_int64, y} }}, list{block3, list { list{let, z, sub_int64, a, b}, list{return_int64, z} }} }; const list_symbol func_source = { params, return_type, body }; unique_ptr<Function> function_owner; tie(function_owner, ignore) = compile_function(func_source.begin(), func_source.end(), context); Function* function = function_owner.get(); context.llvm_macro_module().getFunctionList().push_back(function_owner.get()); function_owner.release(); string str; raw_string_ostream os(str); //BOOST_CHECK_MESSAGE(verifyFunction(*function, &os), os.str()); // TODO: this fails - I don't know why, function->dump() looks good to me and verifyFunction doesn't produce a message auto fptr = (uint64_t (*)(uint64_t, uint64_t)) context.llvm_execution_engine().getPointerToFunction(function); BOOST_CHECK(fptr); BOOST_CHECK_EQUAL(fptr(2, 2), 2 + 2); BOOST_CHECK_EQUAL(fptr(5, 3), 5 - 3); } BOOST_AUTO_TEST_CASE(phi_test) { const list_symbol params = { list{a, int64_type}, list{b, int64_type}, }; const type_symbol return_type = int64_type; const list_symbol block1_def = {block1, list { list{let, x, cmp_eq_int64, a, b}, list{cond_branch, x, block2, block3} }}; const list_symbol block2_def = list{block2, list { list{let, y, add_int64, a, b}, list{branch, block4} }}; const list_symbol block3_def = {block3, list { list{let, z, sub_int64, a, b}, list{branch, block4} }}; const list_symbol block4_def = {block4, list { list{let, w, phi_int64, list{y, block2}, list{z, block3}}, list{return_int64, w} }}; const list_symbol func1_source = { params, return_type, list { block1_def, block2_def, block3_def, block4_def } }; unique_ptr<Function> function_owner; tie(function_owner, ignore) = compile_function(func1_source.begin(), func1_source.end(), context); Function* function = function_owner.get(); context.llvm_macro_module().getFunctionList().push_back(function_owner.get()); function_owner.release(); //BOOST_CHECK_MESSAGE(verifyFunction(*function, &os)); // TODO: this fails - I don't know why, function->dump() looks good to me and verifyFunction doesn't produce a message auto f1ptr = (uint64_t (*)(uint64_t, uint64_t)) context.llvm_execution_engine().getPointerToFunction(function); BOOST_CHECK(f1ptr); BOOST_CHECK_EQUAL(f1ptr(2, 2), 2 + 2); BOOST_CHECK_EQUAL(f1ptr(5, 3), 5 - 3); const list_symbol block4_invalid_def = {block4, list { list{let, w, phi_int64, list{z, block3}}, // missing incoming specification for block2 list{return_int64, w} }}; const list_symbol func2_source = { params, return_type, list { block1_def, block2_def, block3_def, block4_invalid_def } }; BOOST_CHECK_THROW(compile_function(func2_source.begin(), func2_source.end(), context), compile_exception); }
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE compile_function #include <boost/test/unit_test.hpp> #include "../src/compile_function.hpp" #include "../src/core_unique_ids.hpp" #include "../src/error/compile_exception.hpp" #include "state_utils.hpp" #include <llvm/IR/Function.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Value.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> #include <memory> #include <unordered_map> #include <utility> #include <iterator> #include <string> using std::pair; using std::tie; using std::ignore; using std::unique_ptr; using std::unordered_map; using std::advance; using std::string; using llvm::Function; using llvm::Value; using llvm::IntegerType; using llvm::Type; using llvm::verifyFunction; using llvm::raw_string_ostream; using boost::get; using namespace symbol_shortcuts; BOOST_AUTO_TEST_CASE(compile_signature_test) { const type_symbol int64_type{IntegerType::get(context.llvm(), 64)}; const ref a{"a"_id}; const ref b{"b"_id}; const ref c{"c"_id}; const any_symbol params1 = list { list{a, int64_type}, list{b, int64_type}, list{c, int64_type}, }; const any_symbol return_type1 = int64_type; unique_ptr<Function> function1; unordered_map<identifier_id_t, named_value_info> parameter_table1; tie(function1, parameter_table1) = compile_signature(params1, return_type1, context); BOOST_CHECK(function1 != nullptr); BOOST_CHECK_EQUAL(parameter_table1.size(), 3); BOOST_CHECK(parameter_table1.count(a.identifier())); BOOST_CHECK(parameter_table1.count(b.identifier())); BOOST_CHECK(parameter_table1.count(c.identifier())); BOOST_CHECK(parameter_table1.at(b.identifier()).llvm_value == (++function1->arg_begin())); const any_symbol params2 = list { list{a, int64_type}, list{b, int64_type}, list{a, int64_type}, // duplicate parameter name }; const any_symbol return_type2 = int64_type; BOOST_CHECK_THROW(compile_signature(params2, return_type2, context), compile_exception); } BOOST_AUTO_TEST_CASE(compile_instruction_test) { Type* llvm_int64 = IntegerType::get(context.llvm(), 64); const type_symbol int64_type{llvm_int64}; const id_symbol add_constructor{unique_ids::ADD}; const list_symbol instruction1{add_constructor, int64_type}; const instruction_info got1 = parse_instruction(instruction1); BOOST_CHECK(get<instruction_info::add>(got1.kind).type == int64_type); const id_symbol div_constructor{unique_ids::DIV}; const list_symbol instruction2{div_constructor, int64_type}; const instruction_info got2 = parse_instruction(instruction2); BOOST_CHECK(get<instruction_info::div>(got2.kind).type == int64_type); const id_symbol cmp_constructor{unique_ids::CMP}; const ref_symbol cmp_ref{"asdfasdf"_id, &cmp_constructor}; const id_symbol lt{unique_ids::LT}; const list_symbol instruction3{cmp_ref, lt, int64_type}; const instruction_info got3 = parse_instruction(instruction3); BOOST_CHECK(get<instruction_info::cmp>(got3.kind).cmp_kind == unique_ids::LT); BOOST_CHECK(get<instruction_info::cmp>(got3.kind).type == int64_type); } const type_symbol int64_type{IntegerType::get(context.llvm(), 64)}; const ref a{"a"_id}; const ref b{"b"_id}; const ref v{"v"_id}; const ref w{"w"_id}; const ref x{"x"_id}; const ref y{"y"_id}; const ref z{"z"_id}; const ref block1{"block1"_id}; const ref block2{"block2"_id}; const ref block3{"block3"_id}; const ref block4{"block4"_id}; const id_symbol let{unique_ids::LET}; const list_symbol alloc_int64 = {id_symbol{unique_ids::ALLOC}, int64_type}; const list_symbol store_int64 = {id_symbol{unique_ids::STORE}, int64_type}; const list_symbol load_int64 = {id_symbol{unique_ids::LOAD}, int64_type}; const list_symbol add_int64 = {id_symbol{unique_ids::ADD}, int64_type}; const list_symbol sub_int64 = {id_symbol{unique_ids::SUB}, int64_type}; const list_symbol return_int64 = {id_symbol{unique_ids::RETURN}, int64_type}; const list_symbol cmp_eq_int64 = {id_symbol{unique_ids::CMP}, id_symbol{unique_ids::EQ}, int64_type}; const list_symbol cond_branch = {id_symbol{unique_ids::COND_BRANCH}}; const list_symbol branch = {id_symbol{unique_ids::BRANCH}}; const list_symbol phi_int64 = {id_symbol{unique_ids::PHI}, int64_type}; template<class T> T get_compiled_function(const list_symbol& function_source) { unique_ptr<Function> function_owner; tie(function_owner, ignore) = compile_function(function_source.begin(), function_source.end(), context); Function* function = function_owner.get(); context.llvm_macro_module().getFunctionList().push_back(function_owner.get()); function_owner.release(); string str; raw_string_ostream os(str); //BOOST_CHECK_MESSAGE(verifyFunction(*function, &os), os.str()); // TODO: this fails - I don't know why, function->dump() looks good to me and verifyFunction doesn't produce a message return (T) context.llvm_execution_engine().getPointerToFunction(function); } BOOST_AUTO_TEST_CASE(store_load_test) { const list_symbol params = { list{a, int64_type} }; const type_symbol return_type = int64_type; const list_symbol body = { list{block1, list { list{let, x, alloc_int64}, list{store_int64, a, x}, list{let, y, load_int64, x}, list{return_int64, y} }} }; const list_symbol function_source = { params, return_type, body }; auto function_ptr = get_compiled_function<uint64_t (*)(uint64_t)>(function_source); BOOST_CHECK(function_ptr(2) == 2); BOOST_CHECK(function_ptr(1231) == 1231); } BOOST_AUTO_TEST_CASE(branch_test) { const list_symbol params = { list{a, int64_type}, list{b, int64_type}, }; const type_symbol return_type = int64_type; const list_symbol body = { list{block1, list { list{let, x, cmp_eq_int64, a, b}, list{cond_branch, x, block2, block3} }}, list{block2, list { list{let, y, add_int64, a, b}, list{return_int64, y} }}, list{block3, list { list{let, z, sub_int64, a, b}, list{return_int64, z} }} }; const list_symbol func_source = { params, return_type, body }; auto compiled_function = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func_source); BOOST_CHECK(compiled_function); BOOST_CHECK_EQUAL(compiled_function(2, 2), 2 + 2); BOOST_CHECK_EQUAL(compiled_function(5, 3), 5 - 3); } BOOST_AUTO_TEST_CASE(phi_test) { const list_symbol params = { list{a, int64_type}, list{b, int64_type}, }; const type_symbol return_type = int64_type; const list_symbol block1_def = {block1, list { list{let, x, cmp_eq_int64, a, b}, list{cond_branch, x, block2, block3} }}; const list_symbol block2_def = list{block2, list { list{let, y, add_int64, a, b}, list{branch, block4} }}; const list_symbol block3_def = {block3, list { list{let, z, sub_int64, a, b}, list{branch, block4} }}; const list_symbol block4_def = {block4, list { list{let, w, phi_int64, list{y, block2}, list{z, block3}}, list{return_int64, w} }}; const list_symbol func1_source = { params, return_type, list { block1_def, block2_def, block3_def, block4_def } }; auto compiled_function1 = get_compiled_function<uint64_t (*)(uint64_t, uint64_t)>(func1_source); BOOST_CHECK(compiled_function1); BOOST_CHECK_EQUAL(compiled_function1(2, 2), 2 + 2); BOOST_CHECK_EQUAL(compiled_function1(5, 3), 5 - 3); const list_symbol block4_invalid_def = {block4, list { list{let, w, phi_int64, list{z, block3}}, // missing incoming for block2 list{return_int64, w} }}; const list_symbol func2_source = { params, return_type, list { block1_def, block2_def, block3_def, block4_invalid_def } }; BOOST_CHECK_THROW(compile_function(func2_source.begin(), func2_source.end(), context), compile_exception); }
refactor test, add alloca/store/load test
refactor test, add alloca/store/load test
C++
mit
mbid/asm-lisp
9eaf7a6f859546b50de2b21eb5f451df46887c98
test/cpp/util/cli_call.cc
test/cpp/util/cli_call.cc
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "test/cpp/util/cli_call.h" #include <iostream> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/support/byte_buffer.h> #include <grpc/grpc.h> #include <grpc/slice.h> #include <grpc/support/log.h> namespace grpc { namespace testing { namespace { void* tag(int i) { return (void*)(intptr_t)i; } } // namespace Status CliCall::Call(std::shared_ptr<grpc::Channel> channel, const grpc::string& method, const grpc::string& request, grpc::string* response, const OutgoingMetadataContainer& metadata, IncomingMetadataContainer* server_initial_metadata, IncomingMetadataContainer* server_trailing_metadata) { CliCall call(channel, method, metadata); call.Write(request); call.WritesDone(); if (!call.Read(response, server_initial_metadata)) { fprintf(stderr, "Failed to read response.\n"); } return call.Finish(server_trailing_metadata); } CliCall::CliCall(std::shared_ptr<grpc::Channel> channel, const grpc::string& method, const OutgoingMetadataContainer& metadata) : stub_(new grpc::GenericStub(channel)) { gpr_mu_init(&write_mu_); gpr_cv_init(&write_cv_); if (!metadata.empty()) { for (OutgoingMetadataContainer::const_iterator iter = metadata.begin(); iter != metadata.end(); ++iter) { ctx_.AddMetadata(iter->first, iter->second); } } call_ = stub_->Call(&ctx_, method, &cq_, tag(1)); void* got_tag; bool ok; cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } CliCall::~CliCall() { gpr_cv_destroy(&write_cv_); gpr_mu_destroy(&write_mu_); } void CliCall::Write(const grpc::string& request) { void* got_tag; bool ok; grpc_slice s = grpc_slice_from_copied_string(request.c_str()); grpc::Slice req_slice(s, grpc::Slice::STEAL_REF); grpc::ByteBuffer send_buffer(&req_slice, 1); call_->Write(send_buffer, tag(2)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } bool CliCall::Read(grpc::string* response, IncomingMetadataContainer* server_initial_metadata) { void* got_tag; bool ok; grpc::ByteBuffer recv_buffer; call_->Read(&recv_buffer, tag(3)); if (!cq_.Next(&got_tag, &ok) || !ok) { return false; } std::vector<grpc::Slice> slices; GPR_ASSERT(recv_buffer.Dump(&slices).ok()); response->clear(); for (size_t i = 0; i < slices.size(); i++) { response->append(reinterpret_cast<const char*>(slices[i].begin()), slices[i].size()); } if (server_initial_metadata) { *server_initial_metadata = ctx_.GetServerInitialMetadata(); } return true; } void CliCall::WritesDone() { void* got_tag; bool ok; call_->WritesDone(tag(4)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } void CliCall::WriteAndWait(const grpc::string& request) { grpc_slice s = grpc_slice_from_copied_string(request.c_str()); grpc::Slice req_slice(s, grpc::Slice::STEAL_REF); grpc::ByteBuffer send_buffer(&req_slice, 1); gpr_mu_lock(&write_mu_); call_->Write(send_buffer, tag(2)); write_done_ = false; while (!write_done_) { gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&write_mu_); } void CliCall::WritesDoneAndWait() { gpr_mu_lock(&write_mu_); call_->WritesDone(tag(4)); write_done_ = false; while (!write_done_) { gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&write_mu_); } bool CliCall::ReadAndMaybeNotifyWrite( grpc::string* response, IncomingMetadataContainer* server_initial_metadata) { void* got_tag; bool ok; grpc::ByteBuffer recv_buffer; call_->Read(&recv_buffer, tag(3)); bool cq_result = cq_.Next(&got_tag, &ok); while (got_tag != tag(3)) { gpr_mu_lock(&write_mu_); write_done_ = true; gpr_cv_signal(&write_cv_); gpr_mu_unlock(&write_mu_); cq_result = cq_.Next(&got_tag, &ok); if (got_tag == tag(2)) { GPR_ASSERT(ok); } } if (!cq_result || !ok) { // If the RPC is ended on the server side, we should still wait for the // pending write on the client side to be done. if (!ok) { gpr_mu_lock(&write_mu_); if (!write_done_) { cq_.Next(&got_tag, &ok); GPR_ASSERT(got_tag != tag(2)); write_done_ = true; gpr_cv_signal(&write_cv_); } gpr_mu_unlock(&write_mu_); } return false; } std::vector<grpc::Slice> slices; GPR_ASSERT(recv_buffer.Dump(&slices).ok()); response->clear(); for (size_t i = 0; i < slices.size(); i++) { response->append(reinterpret_cast<const char*>(slices[i].begin()), slices[i].size()); } if (server_initial_metadata) { *server_initial_metadata = ctx_.GetServerInitialMetadata(); } return true; } Status CliCall::Finish(IncomingMetadataContainer* server_trailing_metadata) { void* got_tag; bool ok; grpc::Status status; call_->Finish(&status, tag(5)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); if (server_trailing_metadata) { *server_trailing_metadata = ctx_.GetServerTrailingMetadata(); } return status; } } // namespace testing } // namespace grpc
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "test/cpp/util/cli_call.h" #include <iostream> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/support/byte_buffer.h> #include <grpc/grpc.h> #include <grpc/slice.h> #include <grpc/support/log.h> namespace grpc { namespace testing { namespace { void* tag(int i) { return (void*)(intptr_t)i; } } // namespace Status CliCall::Call(std::shared_ptr<grpc::Channel> channel, const grpc::string& method, const grpc::string& request, grpc::string* response, const OutgoingMetadataContainer& metadata, IncomingMetadataContainer* server_initial_metadata, IncomingMetadataContainer* server_trailing_metadata) { CliCall call(channel, method, metadata); call.Write(request); call.WritesDone(); if (!call.Read(response, server_initial_metadata)) { fprintf(stderr, "Failed to read response.\n"); } return call.Finish(server_trailing_metadata); } CliCall::CliCall(std::shared_ptr<grpc::Channel> channel, const grpc::string& method, const OutgoingMetadataContainer& metadata) : stub_(new grpc::GenericStub(channel)) { gpr_mu_init(&write_mu_); gpr_cv_init(&write_cv_); if (!metadata.empty()) { for (OutgoingMetadataContainer::const_iterator iter = metadata.begin(); iter != metadata.end(); ++iter) { ctx_.AddMetadata(iter->first, iter->second); } } call_ = stub_->Call(&ctx_, method, &cq_, tag(1)); void* got_tag; bool ok; cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } CliCall::~CliCall() { gpr_cv_destroy(&write_cv_); gpr_mu_destroy(&write_mu_); } void CliCall::Write(const grpc::string& request) { void* got_tag; bool ok; gpr_slice s = gpr_slice_from_copied_buffer(request.data(), request.size()); grpc::Slice req_slice(s, grpc::Slice::STEAL_REF); grpc::ByteBuffer send_buffer(&req_slice, 1); call_->Write(send_buffer, tag(2)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } bool CliCall::Read(grpc::string* response, IncomingMetadataContainer* server_initial_metadata) { void* got_tag; bool ok; grpc::ByteBuffer recv_buffer; call_->Read(&recv_buffer, tag(3)); if (!cq_.Next(&got_tag, &ok) || !ok) { return false; } std::vector<grpc::Slice> slices; GPR_ASSERT(recv_buffer.Dump(&slices).ok()); response->clear(); for (size_t i = 0; i < slices.size(); i++) { response->append(reinterpret_cast<const char*>(slices[i].begin()), slices[i].size()); } if (server_initial_metadata) { *server_initial_metadata = ctx_.GetServerInitialMetadata(); } return true; } void CliCall::WritesDone() { void* got_tag; bool ok; call_->WritesDone(tag(4)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); } void CliCall::WriteAndWait(const grpc::string& request) { grpc_slice s = grpc_slice_from_copied_string(request.c_str()); grpc::Slice req_slice(s, grpc::Slice::STEAL_REF); grpc::ByteBuffer send_buffer(&req_slice, 1); gpr_mu_lock(&write_mu_); call_->Write(send_buffer, tag(2)); write_done_ = false; while (!write_done_) { gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&write_mu_); } void CliCall::WritesDoneAndWait() { gpr_mu_lock(&write_mu_); call_->WritesDone(tag(4)); write_done_ = false; while (!write_done_) { gpr_cv_wait(&write_cv_, &write_mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&write_mu_); } bool CliCall::ReadAndMaybeNotifyWrite( grpc::string* response, IncomingMetadataContainer* server_initial_metadata) { void* got_tag; bool ok; grpc::ByteBuffer recv_buffer; call_->Read(&recv_buffer, tag(3)); bool cq_result = cq_.Next(&got_tag, &ok); while (got_tag != tag(3)) { gpr_mu_lock(&write_mu_); write_done_ = true; gpr_cv_signal(&write_cv_); gpr_mu_unlock(&write_mu_); cq_result = cq_.Next(&got_tag, &ok); if (got_tag == tag(2)) { GPR_ASSERT(ok); } } if (!cq_result || !ok) { // If the RPC is ended on the server side, we should still wait for the // pending write on the client side to be done. if (!ok) { gpr_mu_lock(&write_mu_); if (!write_done_) { cq_.Next(&got_tag, &ok); GPR_ASSERT(got_tag != tag(2)); write_done_ = true; gpr_cv_signal(&write_cv_); } gpr_mu_unlock(&write_mu_); } return false; } std::vector<grpc::Slice> slices; GPR_ASSERT(recv_buffer.Dump(&slices).ok()); response->clear(); for (size_t i = 0; i < slices.size(); i++) { response->append(reinterpret_cast<const char*>(slices[i].begin()), slices[i].size()); } if (server_initial_metadata) { *server_initial_metadata = ctx_.GetServerInitialMetadata(); } return true; } Status CliCall::Finish(IncomingMetadataContainer* server_trailing_metadata) { void* got_tag; bool ok; grpc::Status status; call_->Finish(&status, tag(5)); cq_.Next(&got_tag, &ok); GPR_ASSERT(ok); if (server_trailing_metadata) { *server_trailing_metadata = ctx_.GetServerTrailingMetadata(); } return status; } } // namespace testing } // namespace grpc
fix truncate bug in grpc_cli
fix truncate bug in grpc_cli
C++
apache-2.0
zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc,zhimingxie/grpc
dd5726b7f0f0db9095a593c96e300b195e663649
test/server_json_test.cpp
test/server_json_test.cpp
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "BaseTest.hpp" #include <boost/test/unit_test.hpp> #include <gst/gst.h> #include <json/json.h> #define GST_CAT_DEFAULT _server_json_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "test_server_json_test" namespace kurento { class ClientHandler : public F { public: ClientHandler() : F() {}; ~ClientHandler () {} protected: void check_error_call (); void check_create_pipeline_call (); void check_connect_call (); void check_bad_transaction_call (); void check_system_overload (); }; void ClientHandler::check_error_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; request["jsonrpc"] = "1"; request["id"] = getId(); request["method"] = "create"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"].isObject() ); BOOST_CHECK (response["error"].isMember ("code") ); BOOST_CHECK (response["error"]["code"].isInt() ); BOOST_CHECK (response["error"]["code"] == -32600); BOOST_CHECK (response["error"].isMember ("message") ); } void ClientHandler::check_connect_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; Json::Value params; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "connect"; request["params"] = params; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("sessionId") ); BOOST_CHECK (response["result"]["sessionId"].isString() ); BOOST_CHECK (response["result"].isMember ("serverId") ); BOOST_CHECK (response["result"]["serverId"].isString() ); request["id"] = getId(); params["sessionId"] = "fakeSession"; request["params"] = params; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"].isObject() ); BOOST_CHECK (response["error"].isMember ("code") ); BOOST_CHECK (response["error"]["code"].isInt() ); BOOST_CHECK (response["error"]["code"] == 40007); BOOST_CHECK (response["error"].isMember ("message") ); BOOST_CHECK (response["error"].isMember ("data") ); BOOST_CHECK (response["error"]["data"].isMember ("type") ); BOOST_CHECK (response["error"]["data"]["type"] == "INVALID_SESSION"); } void ClientHandler::check_bad_transaction_call() { Json::Value response; Json::Reader reader; std::string req_str; std::string response_str; req_str = "{" "\"id\": 50000," "\"jsonrpc\":\"2.0\"," "\"method\":\"transaction\"," "\"params\":{" "\"operations\":[" "{" "\"id\":0," "\"jsonrpc\":\"2.0\"," "\"method\":\"create\"," "\"params\":{" "\"constructorParams\":{" "\"mediaPipeline\":\"5b96c1ad-46ba-4366-8241-fbc1cd0e9bbd\"," "\"uri\":\"http://files.kurento.org/video/small.webm\"}," "\"transaction\":{" "\"_events\":{}," "\"_maxListeners\":10," "\"domain\":null," "\"members\":[]}," "\"type\":\"PlayerEndpoint\"}" "}," "{" "\"id\":1," "\"jsonrpc\":\"2.0\"," "\"method\":\"create\"," "\"params\":{\"" "constructorParams\":{" "\"mediaPipeline\":\"5b96c1ad-46ba-4366-8241-fbc1cd0e9bbd\"}," "\"transaction\":{" "\"_events\":{}," "\"_maxListeners\":10," "\"domain\":null," "\"members\":[]}," "\"type\":\"HttpGetEndpoint\"}" "}" "]," "\"sessionId\":\"c58960d9-4cac-4036-ad2e-1aef26946dae\"}}"; response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].type() != Json::ValueType::nullValue); } void ClientHandler::check_create_pipeline_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; std::string pipeId; std::string objId; Json::Value params; Json::Value constructorParams; Json::Value operationParams; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "create"; params["type"] = "MediaPipeline"; params["sessionId"] = "123456"; request["params"] = params; request["sessionId"] = "sessionId"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); pipeId = response["result"]["value"].asString(); params["type"] = "WebRtcEndpoint"; constructorParams ["mediaPipeline"] = pipeId; params["constructorParams"] = constructorParams; params["sessionId"] = "123456"; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); objId = response["result"]["value"].asString(); request["method"] = "invoke"; params.clear(); params["object"] = objId; params["operation"] = "getName"; params["sessionId"] = "123456"; params["operationParams"] = operationParams; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); request["id"] = getId(); request["method"] = "ref"; params.clear(); params["object"] = objId; params["sessionId"] = "12345"; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); request["id"] = getId(); request["method"] = "describe"; params.clear(); params["object"] = objId; params["sessionId"] = "12345"; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isMember ("type") ); BOOST_CHECK (response["result"]["type"].asString () == "WebRtcEndpoint" ); std::string sessionId = "123456"; request.removeMember ("id"); request["id"] = getId(); request["method"] = "release"; params.clear(); params["object"] = objId; params["sessionId"] = sessionId; params["operationParams"] = operationParams; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isMember ("sessionId") ); BOOST_CHECK (response["result"]["sessionId"].asString () == sessionId ); } void ClientHandler::check_system_overload() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; std::string pipeId; std::string objId; Json::Value params; Json::Value constructorParams; Json::Value operationParams; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "create"; params["type"] = "MediaPipeline"; params["sessionId"] = "1234567"; request["params"] = params; request["sessionId"] = "sessionId"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); pipeId = response["result"]["value"].asString(); int times = 0; do { params["type"] = "WebRtcEndpoint"; constructorParams ["mediaPipeline"] = pipeId; params["constructorParams"] = constructorParams; params["sessionId"] = "1234567"; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); times ++; } while (!response.isMember ("error") ); BOOST_CHECK (times > 0); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"]["data"]["type"].asString() == "NOT_ENOUGH_RESOURCES"); } BOOST_FIXTURE_TEST_SUITE ( server_unexpected_test_suite, ClientHandler) BOOST_AUTO_TEST_CASE ( server_unexpected_test ) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); check_connect_call(); check_error_call(); check_create_pipeline_call(); check_bad_transaction_call(); check_system_overload(); } BOOST_AUTO_TEST_SUITE_END() } /* kurento */
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "BaseTest.hpp" #include <boost/test/unit_test.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <json/json.h> #define GST_CAT_DEFAULT _server_json_test_ GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "test_server_json_test" namespace kurento { class ClientHandler : public F { public: ClientHandler() : F() {}; ~ClientHandler () {} protected: void check_error_call (); void check_create_pipeline_call (); void check_connect_call (); void check_bad_transaction_call (); void check_system_overload (); }; void ClientHandler::check_error_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; request["jsonrpc"] = "1"; request["id"] = getId(); request["method"] = "create"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"].isObject() ); BOOST_CHECK (response["error"].isMember ("code") ); BOOST_CHECK (response["error"]["code"].isInt() ); BOOST_CHECK (response["error"]["code"].asInt() == -32600); BOOST_CHECK (response["error"].isMember ("message") ); } void ClientHandler::check_connect_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; Json::Value params; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "connect"; request["params"] = params; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("sessionId") ); BOOST_CHECK (response["result"]["sessionId"].isString() ); BOOST_CHECK (response["result"].isMember ("serverId") ); BOOST_CHECK (response["result"]["serverId"].isString() ); request["id"] = getId(); params["sessionId"] = "fakeSession"; request["params"] = params; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"].isObject() ); BOOST_CHECK (response["error"].isMember ("code") ); BOOST_CHECK (response["error"]["code"].isInt() ); BOOST_CHECK (response["error"]["code"].asInt() == INVALID_SESSION); BOOST_CHECK (response["error"].isMember ("message") ); BOOST_CHECK (response["error"].isMember ("data") ); BOOST_CHECK (response["error"]["data"].isMember ("type") ); BOOST_CHECK (response["error"]["data"]["type"] == "INVALID_SESSION"); } void ClientHandler::check_bad_transaction_call() { Json::Value response; Json::Reader reader; std::string req_str; std::string response_str; req_str = "{" "\"id\": 50000," "\"jsonrpc\":\"2.0\"," "\"method\":\"transaction\"," "\"params\":{" "\"operations\":[" "{" "\"id\":0," "\"jsonrpc\":\"2.0\"," "\"method\":\"create\"," "\"params\":{" "\"constructorParams\":{" "\"mediaPipeline\":\"5b96c1ad-46ba-4366-8241-fbc1cd0e9bbd\"," "\"uri\":\"http://files.kurento.org/video/small.webm\"}," "\"transaction\":{" "\"_events\":{}," "\"_maxListeners\":10," "\"domain\":null," "\"members\":[]}," "\"type\":\"PlayerEndpoint\"}" "}," "{" "\"id\":1," "\"jsonrpc\":\"2.0\"," "\"method\":\"create\"," "\"params\":{\"" "constructorParams\":{" "\"mediaPipeline\":\"5b96c1ad-46ba-4366-8241-fbc1cd0e9bbd\"}," "\"transaction\":{" "\"_events\":{}," "\"_maxListeners\":10," "\"domain\":null," "\"members\":[]}," "\"type\":\"HttpGetEndpoint\"}" "}" "]," "\"sessionId\":\"c58960d9-4cac-4036-ad2e-1aef26946dae\"}}"; response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].type() != Json::ValueType::nullValue); } void ClientHandler::check_create_pipeline_call() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; std::string pipeId; std::string objId; Json::Value params; Json::Value constructorParams; Json::Value operationParams; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "create"; params["type"] = "MediaPipeline"; params["sessionId"] = "123456"; request["params"] = params; request["sessionId"] = "sessionId"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); pipeId = response["result"]["value"].asString(); params["type"] = "WebRtcEndpoint"; constructorParams ["mediaPipeline"] = pipeId; params["constructorParams"] = constructorParams; params["sessionId"] = "123456"; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); objId = response["result"]["value"].asString(); request["method"] = "invoke"; params.clear(); params["object"] = objId; params["operation"] = "getName"; params["sessionId"] = "123456"; params["operationParams"] = operationParams; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); request["id"] = getId(); request["method"] = "ref"; params.clear(); params["object"] = objId; params["sessionId"] = "12345"; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); request["id"] = getId(); request["method"] = "describe"; params.clear(); params["object"] = objId; params["sessionId"] = "12345"; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isMember ("type") ); BOOST_CHECK (response["result"]["type"].asString () == "WebRtcEndpoint" ); std::string sessionId = "123456"; request.removeMember ("id"); request["id"] = getId(); request["method"] = "release"; params.clear(); params["object"] = objId; params["sessionId"] = sessionId; params["operationParams"] = operationParams; request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isMember ("sessionId") ); BOOST_CHECK (response["result"]["sessionId"].asString () == sessionId ); } void ClientHandler::check_system_overload() { Json::Value request; Json::Value response; Json::FastWriter writer; Json::Reader reader; std::string req_str; std::string response_str; std::string pipeId; std::string objId; Json::Value params; Json::Value constructorParams; Json::Value operationParams; request["jsonrpc"] = "2.0"; request["id"] = getId(); request["method"] = "create"; params["type"] = "MediaPipeline"; params["sessionId"] = "1234567"; request["params"] = params; request["sessionId"] = "sessionId"; req_str = writer.write (request); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); BOOST_CHECK (!response.isMember ("error") ); BOOST_CHECK (response.isMember ("result") ); BOOST_CHECK (response["result"].isObject() ); BOOST_CHECK (response["result"].isMember ("value") ); BOOST_CHECK (response["result"]["value"].isString() ); pipeId = response["result"]["value"].asString(); int times = 0; do { params["type"] = "WebRtcEndpoint"; constructorParams ["mediaPipeline"] = pipeId; params["constructorParams"] = constructorParams; params["sessionId"] = "1234567"; request["id"] = getId(); request["params"] = params; req_str = writer.write (request); response_str.clear(); response_str = sendMessage (req_str); BOOST_CHECK (reader.parse (response_str, response) == true); times ++; } while (!response.isMember ("error") ); BOOST_CHECK (times > 0); BOOST_CHECK (response.isMember ("error") ); BOOST_CHECK (response["error"]["data"]["type"].asString() == "NOT_ENOUGH_RESOURCES"); } BOOST_FIXTURE_TEST_SUITE ( server_unexpected_test_suite, ClientHandler) BOOST_AUTO_TEST_CASE ( server_unexpected_test ) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); check_connect_call(); check_error_call(); check_create_pipeline_call(); check_bad_transaction_call(); check_system_overload(); } BOOST_AUTO_TEST_SUITE_END() } /* kurento */
Fix tests value checkings
Fix tests value checkings Change-Id: Ic0cc0c580d5418e005f47caaf39a2ae83025e9d8
C++
lgpl-2.1
lulufei/kurento-media-server,shelsonjava/kurento-media-server,todotobe1/kurento-media-server,shelsonjava/kurento-media-server,todotobe1/kurento-media-server,lulufei/kurento-media-server
f6777cd5d3418657bd7605660393aaeb950cacb7
Rendering/Core/vtkCompositePolyDataMapper2.cxx
Rendering/Core/vtkCompositePolyDataMapper2.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkCompositePolyDataMapper2.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCompositePolyDataMapper2.h" #include "vtkBoundingBox.h" #include "vtkCommand.h" #include "vtkCompositeDataIterator.h" #include "vtkCompositeDataPipeline.h" #include "vtkCompositeDataSet.h" #include "vtkCompositeDataDisplayAttributes.h" #include "vtkCompositePainter.h" #include "vtkDefaultPainter.h" #include "vtkDisplayListPainter.h" #include "vtkInformation.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataPainter.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkScalarsToColorsPainter.h" #include "vtkSmartPointer.h" #include "vtkUnsignedCharArray.h" vtkStandardNewMacro(vtkCompositePolyDataMapper2); //---------------------------------------------------------------------------- vtkCompositePolyDataMapper2::vtkCompositePolyDataMapper2() { // Insert the vtkCompositePainter in the selection pipeline, so that the // selection painter can handle composite datasets as well. vtkCompositePainter* selectionPainter = vtkCompositePainter::New(); selectionPainter->SetDelegatePainter(this->SelectionPainter); this->SetSelectionPainter(selectionPainter); selectionPainter->FastDelete(); this->SelectionCompositePainter = selectionPainter; this->LastOpaqueCheckTime = 0; } //---------------------------------------------------------------------------- vtkCompositePolyDataMapper2::~vtkCompositePolyDataMapper2() { } //---------------------------------------------------------------------------- int vtkCompositePolyDataMapper2::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet"); return 1; } //---------------------------------------------------------------------------- vtkExecutive* vtkCompositePolyDataMapper2::CreateDefaultExecutive() { return vtkCompositeDataPipeline::New(); } //----------------------------------------------------------------------------- //Looks at each DataSet and finds the union of all the bounds void vtkCompositePolyDataMapper2::ComputeBounds() { vtkMath::UninitializeBounds(this->Bounds); vtkCompositeDataSet *input = vtkCompositeDataSet::SafeDownCast( this->GetInputDataObject(0, 0)); // If we don't have hierarchical data, test to see if we have // plain old polydata. In this case, the bounds are simply // the bounds of the input polydata. if (!input) { this->Superclass::ComputeBounds(); return; } vtkCompositeDataIterator* iter = input->NewIterator(); vtkBoundingBox bbox; for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkPolyData *pd = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); if (pd) { double bounds[6]; pd->GetBounds(bounds); bbox.AddBounds(bounds); } } iter->Delete(); bbox.GetBounds(this->Bounds); // this->BoundsMTime.Modified(); } //----------------------------------------------------------------------------- bool vtkCompositePolyDataMapper2::GetIsOpaque() { vtkCompositeDataSet *input = vtkCompositeDataSet::SafeDownCast( this->GetInputDataObject(0, 0)); unsigned long int lastMTime = std::max(input->GetMTime(), this->GetMTime()); if (lastMTime <= this->LastOpaqueCheckTime) { return this->LastOpaqueCheckValue; } this->LastOpaqueCheckTime = lastMTime; if (this->ScalarVisibility && this->ColorMode == VTK_COLOR_MODE_DEFAULT && input) { vtkSmartPointer<vtkCompositeDataIterator> iter; iter.TakeReference(input->NewIterator()); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkPolyData *pd = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); if (pd) { int cellFlag; vtkDataArray* scalars = this->GetScalars(pd, this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); if (scalars && scalars->IsA("vtkUnsignedCharArray") && (scalars->GetNumberOfComponents() == 4 /*(RGBA)*/ || scalars->GetNumberOfComponents() == 2 /*(LuminanceAlpha)*/)) { vtkUnsignedCharArray* colors = static_cast<vtkUnsignedCharArray*>(scalars); if ((colors->GetNumberOfComponents() == 4 && colors->GetValueRange(3)[0] < 255) || (colors->GetNumberOfComponents() == 2 && colors->GetValueRange(1)[0] < 255)) { // If the opacity is 255, despite the fact that the user specified // RGBA, we know that the Alpha is 100% opaque. So treat as opaque. this->LastOpaqueCheckValue = false; return false; } } } } } else if(this->CompositeAttributes && this->CompositeAttributes->HasBlockOpacities()) { this->LastOpaqueCheckValue = false; return false; } this->LastOpaqueCheckValue = this->Superclass::GetIsOpaque(); return this->LastOpaqueCheckValue; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockVisibility(unsigned int index, bool visible) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockVisibility(index, visible); this->Modified(); } } //---------------------------------------------------------------------------- bool vtkCompositePolyDataMapper2::GetBlockVisibility(unsigned int index) const { if(this->CompositeAttributes) { return this->CompositeAttributes->GetBlockVisibility(index); } else { return true; } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockVisibility(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockVisibility(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockVisibilites() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockVisibilites(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockColor(unsigned int index, double color[3]) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockColor(index, color); this->Modified(); } } //---------------------------------------------------------------------------- double* vtkCompositePolyDataMapper2::GetBlockColor(unsigned int index) { (void) index; return 0; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockColor(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockColor(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockColors() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockColors(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockOpacity(unsigned int index, double opacity) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockOpacity(index, opacity); this->Modified(); } } //---------------------------------------------------------------------------- double vtkCompositePolyDataMapper2::GetBlockOpacity(unsigned int index) { if(this->CompositeAttributes) { return this->CompositeAttributes->GetBlockOpacity(index); } return 1.; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockOpacity(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockOpacity(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockOpacities() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockOpacities(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetCompositeDataDisplayAttributes( vtkCompositeDataDisplayAttributes *attributes) { if(this->CompositeAttributes != attributes) { this->CompositeAttributes = attributes; this->Modified(); } } //---------------------------------------------------------------------------- vtkCompositeDataDisplayAttributes* vtkCompositePolyDataMapper2::GetCompositeDataDisplayAttributes() { return this->CompositeAttributes; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::UpdatePainterInformation() { this->Superclass::UpdatePainterInformation(); this->PainterInformation->Set( vtkCompositePainter::DISPLAY_ATTRIBUTES(), this->CompositeAttributes); } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
/*========================================================================= Program: Visualization Toolkit Module: vtkCompositePolyDataMapper2.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCompositePolyDataMapper2.h" #include "vtkBoundingBox.h" #include "vtkCommand.h" #include "vtkCompositeDataIterator.h" #include "vtkCompositeDataPipeline.h" #include "vtkCompositeDataSet.h" #include "vtkCompositeDataDisplayAttributes.h" #include "vtkCompositePainter.h" #include "vtkDefaultPainter.h" #include "vtkDisplayListPainter.h" #include "vtkInformation.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataPainter.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkScalarsToColorsPainter.h" #include "vtkSmartPointer.h" #include "vtkUnsignedCharArray.h" #include <algorithm> vtkStandardNewMacro(vtkCompositePolyDataMapper2); //---------------------------------------------------------------------------- vtkCompositePolyDataMapper2::vtkCompositePolyDataMapper2() { // Insert the vtkCompositePainter in the selection pipeline, so that the // selection painter can handle composite datasets as well. vtkCompositePainter* selectionPainter = vtkCompositePainter::New(); selectionPainter->SetDelegatePainter(this->SelectionPainter); this->SetSelectionPainter(selectionPainter); selectionPainter->FastDelete(); this->SelectionCompositePainter = selectionPainter; this->LastOpaqueCheckTime = 0; } //---------------------------------------------------------------------------- vtkCompositePolyDataMapper2::~vtkCompositePolyDataMapper2() { } //---------------------------------------------------------------------------- int vtkCompositePolyDataMapper2::FillInputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet"); return 1; } //---------------------------------------------------------------------------- vtkExecutive* vtkCompositePolyDataMapper2::CreateDefaultExecutive() { return vtkCompositeDataPipeline::New(); } //----------------------------------------------------------------------------- //Looks at each DataSet and finds the union of all the bounds void vtkCompositePolyDataMapper2::ComputeBounds() { vtkMath::UninitializeBounds(this->Bounds); vtkCompositeDataSet *input = vtkCompositeDataSet::SafeDownCast( this->GetInputDataObject(0, 0)); // If we don't have hierarchical data, test to see if we have // plain old polydata. In this case, the bounds are simply // the bounds of the input polydata. if (!input) { this->Superclass::ComputeBounds(); return; } vtkCompositeDataIterator* iter = input->NewIterator(); vtkBoundingBox bbox; for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkPolyData *pd = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); if (pd) { double bounds[6]; pd->GetBounds(bounds); bbox.AddBounds(bounds); } } iter->Delete(); bbox.GetBounds(this->Bounds); // this->BoundsMTime.Modified(); } //----------------------------------------------------------------------------- bool vtkCompositePolyDataMapper2::GetIsOpaque() { vtkCompositeDataSet *input = vtkCompositeDataSet::SafeDownCast( this->GetInputDataObject(0, 0)); unsigned long int lastMTime = std::max(input->GetMTime(), this->GetMTime()); if (lastMTime <= this->LastOpaqueCheckTime) { return this->LastOpaqueCheckValue; } this->LastOpaqueCheckTime = lastMTime; if (this->ScalarVisibility && this->ColorMode == VTK_COLOR_MODE_DEFAULT && input) { vtkSmartPointer<vtkCompositeDataIterator> iter; iter.TakeReference(input->NewIterator()); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkPolyData *pd = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); if (pd) { int cellFlag; vtkDataArray* scalars = this->GetScalars(pd, this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); if (scalars && scalars->IsA("vtkUnsignedCharArray") && (scalars->GetNumberOfComponents() == 4 /*(RGBA)*/ || scalars->GetNumberOfComponents() == 2 /*(LuminanceAlpha)*/)) { vtkUnsignedCharArray* colors = static_cast<vtkUnsignedCharArray*>(scalars); if ((colors->GetNumberOfComponents() == 4 && colors->GetValueRange(3)[0] < 255) || (colors->GetNumberOfComponents() == 2 && colors->GetValueRange(1)[0] < 255)) { // If the opacity is 255, despite the fact that the user specified // RGBA, we know that the Alpha is 100% opaque. So treat as opaque. this->LastOpaqueCheckValue = false; return false; } } } } } else if(this->CompositeAttributes && this->CompositeAttributes->HasBlockOpacities()) { this->LastOpaqueCheckValue = false; return false; } this->LastOpaqueCheckValue = this->Superclass::GetIsOpaque(); return this->LastOpaqueCheckValue; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockVisibility(unsigned int index, bool visible) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockVisibility(index, visible); this->Modified(); } } //---------------------------------------------------------------------------- bool vtkCompositePolyDataMapper2::GetBlockVisibility(unsigned int index) const { if(this->CompositeAttributes) { return this->CompositeAttributes->GetBlockVisibility(index); } else { return true; } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockVisibility(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockVisibility(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockVisibilites() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockVisibilites(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockColor(unsigned int index, double color[3]) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockColor(index, color); this->Modified(); } } //---------------------------------------------------------------------------- double* vtkCompositePolyDataMapper2::GetBlockColor(unsigned int index) { (void) index; return 0; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockColor(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockColor(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockColors() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockColors(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetBlockOpacity(unsigned int index, double opacity) { if(this->CompositeAttributes) { this->CompositeAttributes->SetBlockOpacity(index, opacity); this->Modified(); } } //---------------------------------------------------------------------------- double vtkCompositePolyDataMapper2::GetBlockOpacity(unsigned int index) { if(this->CompositeAttributes) { return this->CompositeAttributes->GetBlockOpacity(index); } return 1.; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockOpacity(unsigned int index) { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockOpacity(index); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::RemoveBlockOpacities() { if(this->CompositeAttributes) { this->CompositeAttributes->RemoveBlockOpacities(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::SetCompositeDataDisplayAttributes( vtkCompositeDataDisplayAttributes *attributes) { if(this->CompositeAttributes != attributes) { this->CompositeAttributes = attributes; this->Modified(); } } //---------------------------------------------------------------------------- vtkCompositeDataDisplayAttributes* vtkCompositePolyDataMapper2::GetCompositeDataDisplayAttributes() { return this->CompositeAttributes; } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::UpdatePainterInformation() { this->Superclass::UpdatePainterInformation(); this->PainterInformation->Set( vtkCompositePainter::DISPLAY_ATTRIBUTES(), this->CompositeAttributes); } //---------------------------------------------------------------------------- void vtkCompositePolyDataMapper2::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
include <algorithm> for std::max
vtkCompositePolyDataMapper2: include <algorithm> for std::max Change-Id: I48c0bb972929e51945d9563088b8633f371fa64f
C++
bsd-3-clause
SimVascular/VTK,msmolens/VTK,hendradarwin/VTK,demarle/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,jmerkow/VTK,jmerkow/VTK,sumedhasingla/VTK,candy7393/VTK,johnkit/vtk-dev,johnkit/vtk-dev,gram526/VTK,mspark93/VTK,ashray/VTK-EVM,hendradarwin/VTK,demarle/VTK,msmolens/VTK,sankhesh/VTK,sankhesh/VTK,candy7393/VTK,ashray/VTK-EVM,msmolens/VTK,demarle/VTK,msmolens/VTK,gram526/VTK,hendradarwin/VTK,sankhesh/VTK,sankhesh/VTK,ashray/VTK-EVM,candy7393/VTK,sumedhasingla/VTK,demarle/VTK,ashray/VTK-EVM,candy7393/VTK,mspark93/VTK,mspark93/VTK,gram526/VTK,berendkleinhaneveld/VTK,keithroe/vtkoptix,ashray/VTK-EVM,msmolens/VTK,sumedhasingla/VTK,johnkit/vtk-dev,gram526/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,hendradarwin/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,jmerkow/VTK,keithroe/vtkoptix,johnkit/vtk-dev,candy7393/VTK,keithroe/vtkoptix,hendradarwin/VTK,gram526/VTK,gram526/VTK,SimVascular/VTK,keithroe/vtkoptix,sankhesh/VTK,hendradarwin/VTK,sankhesh/VTK,keithroe/vtkoptix,msmolens/VTK,mspark93/VTK,jmerkow/VTK,keithroe/vtkoptix,sumedhasingla/VTK,mspark93/VTK,SimVascular/VTK,johnkit/vtk-dev,jmerkow/VTK,candy7393/VTK,jmerkow/VTK,keithroe/vtkoptix,gram526/VTK,johnkit/vtk-dev,sumedhasingla/VTK,SimVascular/VTK,candy7393/VTK,SimVascular/VTK,demarle/VTK,berendkleinhaneveld/VTK,mspark93/VTK,demarle/VTK,sumedhasingla/VTK,demarle/VTK,mspark93/VTK,SimVascular/VTK,sankhesh/VTK,hendradarwin/VTK,ashray/VTK-EVM,msmolens/VTK,johnkit/vtk-dev,sumedhasingla/VTK,mspark93/VTK,demarle/VTK,jmerkow/VTK,gram526/VTK,jmerkow/VTK,msmolens/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,candy7393/VTK,SimVascular/VTK,keithroe/vtkoptix,berendkleinhaneveld/VTK
c3bb5f222ff404ec7dcba16ddc3c4246c7ee5d4f
test/applications/elliptic/phasefield/phasefield_patch_operator.cpp
test/applications/elliptic/phasefield/phasefield_patch_operator.cpp
#include <test/catch.hpp> #include <applications/elliptic/phasefield/phasefield_patch_operator.h> #include <test/utils/DomainReader.h> #include <ThunderEgg/ValVector.h> #include <ThunderEgg/BiLinearGhostFiller.h> #include <ThunderEgg/DomainTools.h> using namespace std; using namespace ThunderEgg; TEST_CASE("default lambda value is 999", "[applications/elliptic/phasefield]") { CHECK(phasefield::getLambda()==999); } TEST_CASE("setLambda", "[applications/elliptic/phasefield]") { double orig_lambda = phasefield::getLambda(); phasefield::setLambda(2); CHECK(phasefield::getLambda()==2); phasefield::setLambda(orig_lambda); } TEST_CASE("constructor sets s array correctly", "[applications/elliptic/phasefield]"){ double orig_lambda = phasefield::getLambda(); phasefield::setLambda(-1); DomainReader<2> reader(DATADIR "/test/mesh_files/2d_uniform_2x2_mpi1.json", {10,10}, 2); auto domain = reader.getCoarserDomain(); auto phi_n = ValVector<2>::GetNewVector(domain, 3); auto ghost_filler = make_shared<BiLinearGhostFiller>(domain); fc2d_thunderegg_options_t * mg_opt = new fc2d_thunderegg_options_t(); mg_opt->boundary_conditions = new int[4]; mg_opt->boundary_conditions[0] = GENERATE(1,2); mg_opt->boundary_conditions[1] = GENERATE(1,2); mg_opt->boundary_conditions[2] = GENERATE(1,2); mg_opt->boundary_conditions[3] = GENERATE(1,2); phasefield_options_t * phase_opt = new phasefield_options_t(); phasefield op(mg_opt, phase_opt, phi_n, domain, ghost_filler); const int* s = op.getS(); for(int i=0;i<4;i++){ if(mg_opt->boundary_conditions[i]==1){ CHECK(s[i]==-1); }else{ CHECK(s[i]==1); } } phasefield::setLambda(orig_lambda); //cleanup delete[] mg_opt->boundary_conditions; delete mg_opt; delete phase_opt; } double one(std::array<double, 2> coord){ double x = coord[0]; double y = coord[1]; return sin(x)*cos(y); } double two(std::array<double, 2> coord){ double x = coord[0]; double y = coord[1]; return cos(x)*sin(y); } TEST_CASE("addGhostToRHS", "[applications/elliptic/phasefield]"){ double orig_lambda = phasefield::getLambda(); phasefield::setLambda(-1); DomainReader<2> reader(DATADIR "/test/mesh_files/2d_uniform_2x2_mpi1.json", {10,10}, 2); auto domain = reader.getFinerDomain(); auto x = ValVector<2>::GetNewVector(domain, 2); auto x_just_ghosts = ValVector<2>::GetNewVector(domain, 2); auto y_expected = ValVector<2>::GetNewVector(domain, 2); auto y = ValVector<2>::GetNewVector(domain, 2); auto phi_n = ValVector<2>::GetNewVector(domain, 3); auto ghost_filler = make_shared<BiLinearGhostFiller>(domain); DomainTools::SetValuesWithGhost<2>(domain,x,one,one); DomainTools::SetValues<2>(domain,x_just_ghosts,one,one); ghost_filler->fillGhost(x_just_ghosts); for(auto pinfo : domain->getPatchInfoVector()){ auto lds = x_just_ghosts->getLocalDatas(pinfo->local_index); for(Side<2> s : Side<2>::getValues()){ if(pinfo->hasNbr(s)){ for(int component = 0;component<2;component++){ auto inner_slice = lds[component].getSliceOnSide(s); auto ghost_slice = lds[component].getGhostSliceOnSide(s,1); for(int i=0;i<10;i++){ ghost_slice[{i}]+=inner_slice[{i}]; } } } } } x_just_ghosts->set(0); DomainTools::SetValuesWithGhost<2>(domain,phi_n,two,two,two); fc2d_thunderegg_options_t * mg_opt = new fc2d_thunderegg_options_t(); mg_opt->boundary_conditions = new int[4]{1,1,1,1}; phasefield_options_t * phase_opt = new phasefield_options_t(); phase_opt->S = 0.5; phase_opt->alpha=400; phase_opt->m = 0.035; phase_opt->xi = 0.0065; phase_opt->k = 4; phase_opt->gamma = 0.5; phase_opt->r0 = 0.1; phasefield op(mg_opt, phase_opt, phi_n, domain, ghost_filler); op.apply(x,y); for(auto pinfo : domain->getPatchInfoVector()){ auto x_lds = x_just_ghosts->getLocalDatas(pinfo->local_index); auto y_lds = y_expected->getLocalDatas(pinfo->local_index); op.applySinglePatch(pinfo,x_lds,y_lds,false); } y_expected->scaleThenAdd(-1.0,y); ghost_filler->fillGhost(x); for(auto pinfo : domain->getPatchInfoVector()){ INFO("x_start: " <<pinfo->starts[0]); INFO("y_start: " <<pinfo->starts[1]); auto expected_lds = y_expected->getLocalDatas(pinfo->local_index); auto lds = y->getLocalDatas(pinfo->local_index); auto us = x->getLocalDatas(pinfo->local_index); op.addGhostToRHS(pinfo,us,lds); for(int component = 0;component<2;component++){ INFO("Component: "<< component); for(int yi = 0; yi<10; yi++){ INFO("yi: "<< yi); for(int xi = 0; xi<10; xi++){ INFO("xi: "<< xi); CHECK(lds[component][{xi,yi}]==Approx(expected_lds[component][{xi,yi}])); } } } } //cleanup phasefield::setLambda(orig_lambda); delete[] mg_opt->boundary_conditions; delete mg_opt; }
#include <test/catch.hpp> #include <applications/elliptic/phasefield/phasefield_patch_operator.h> #include <test/utils/DomainReader.h> #include <ThunderEgg/ValVector.h> #include <ThunderEgg/BiLinearGhostFiller.h> #include <ThunderEgg/DomainTools.h> using namespace std; using namespace ThunderEgg; TEST_CASE("default lambda value is 999", "[applications/elliptic/phasefield]") { CHECK(phasefield::getLambda()==999); } TEST_CASE("setLambda", "[applications/elliptic/phasefield]") { double orig_lambda = phasefield::getLambda(); phasefield::setLambda(2); CHECK(phasefield::getLambda()==2); phasefield::setLambda(orig_lambda); } TEST_CASE("constructor sets s array correctly", "[applications/elliptic/phasefield]"){ double orig_lambda = phasefield::getLambda(); phasefield::setLambda(-1); DomainReader<2> reader(DATADIR "/test/mesh_files/2d_uniform_2x2_mpi1.json", {10,10}, 2); auto domain = reader.getCoarserDomain(); auto phi_n = ValVector<2>::GetNewVector(domain, 3); auto ghost_filler = make_shared<BiLinearGhostFiller>(domain, GhostFillingType::Faces); fc2d_thunderegg_options_t * mg_opt = new fc2d_thunderegg_options_t(); mg_opt->boundary_conditions = new int[4]; mg_opt->boundary_conditions[0] = GENERATE(1,2); mg_opt->boundary_conditions[1] = GENERATE(1,2); mg_opt->boundary_conditions[2] = GENERATE(1,2); mg_opt->boundary_conditions[3] = GENERATE(1,2); phasefield_options_t * phase_opt = new phasefield_options_t(); phasefield op(mg_opt, phase_opt, phi_n, domain, ghost_filler); const int* s = op.getS(); for(int i=0;i<4;i++){ if(mg_opt->boundary_conditions[i]==1){ CHECK(s[i]==-1); }else{ CHECK(s[i]==1); } } phasefield::setLambda(orig_lambda); //cleanup delete[] mg_opt->boundary_conditions; delete mg_opt; delete phase_opt; } double one(std::array<double, 2> coord){ double x = coord[0]; double y = coord[1]; return sin(x)*cos(y); } double two(std::array<double, 2> coord){ double x = coord[0]; double y = coord[1]; return cos(x)*sin(y); } TEST_CASE("addGhostToRHS", "[applications/elliptic/phasefield]"){ double orig_lambda = phasefield::getLambda(); phasefield::setLambda(-1); DomainReader<2> reader(DATADIR "/test/mesh_files/2d_uniform_2x2_mpi1.json", {10,10}, 2); auto domain = reader.getFinerDomain(); auto x = ValVector<2>::GetNewVector(domain, 2); auto x_just_ghosts = ValVector<2>::GetNewVector(domain, 2); auto y_expected = ValVector<2>::GetNewVector(domain, 2); auto y = ValVector<2>::GetNewVector(domain, 2); auto phi_n = ValVector<2>::GetNewVector(domain, 3); auto ghost_filler = make_shared<BiLinearGhostFiller>(domain); DomainTools::SetValuesWithGhost<2>(domain,x,one,one); DomainTools::SetValues<2>(domain,x_just_ghosts,one,one); ghost_filler->fillGhost(x_just_ghosts); for(auto pinfo : domain->getPatchInfoVector()){ auto lds = x_just_ghosts->getLocalDatas(pinfo->local_index); for(Side<2> s : Side<2>::getValues()){ if(pinfo->hasNbr(s)){ for(int component = 0;component<2;component++){ auto inner_slice = lds[component].getSliceOnSide(s); auto ghost_slice = lds[component].getGhostSliceOn(s,{0}); for(int i=0;i<10;i++){ ghost_slice[{i}]+=inner_slice[{i}]; } } } } } x_just_ghosts->set(0); DomainTools::SetValuesWithGhost<2>(domain,phi_n,two,two,two); fc2d_thunderegg_options_t * mg_opt = new fc2d_thunderegg_options_t(); mg_opt->boundary_conditions = new int[4]{1,1,1,1}; phasefield_options_t * phase_opt = new phasefield_options_t(); phase_opt->S = 0.5; phase_opt->alpha=400; phase_opt->m = 0.035; phase_opt->xi = 0.0065; phase_opt->k = 4; phase_opt->gamma = 0.5; phase_opt->r0 = 0.1; phasefield op(mg_opt, phase_opt, phi_n, domain, ghost_filler); op.apply(x,y); for(auto pinfo : domain->getPatchInfoVector()){ auto x_lds = x_just_ghosts->getLocalDatas(pinfo->local_index); auto y_lds = y_expected->getLocalDatas(pinfo->local_index); op.applySinglePatch(pinfo,x_lds,y_lds,false); } y_expected->scaleThenAdd(-1.0,y); ghost_filler->fillGhost(x); for(auto pinfo : domain->getPatchInfoVector()){ INFO("x_start: " <<pinfo->starts[0]); INFO("y_start: " <<pinfo->starts[1]); auto expected_lds = y_expected->getLocalDatas(pinfo->local_index); auto lds = y->getLocalDatas(pinfo->local_index); auto us = x->getLocalDatas(pinfo->local_index); op.addGhostToRHS(pinfo,us,lds); for(int component = 0;component<2;component++){ INFO("Component: "<< component); for(int yi = 0; yi<10; yi++){ INFO("yi: "<< yi); for(int xi = 0; xi<10; xi++){ INFO("xi: "<< xi); CHECK(lds[component][{xi,yi}]==Approx(expected_lds[component][{xi,yi}])); } } } } //cleanup phasefield::setLambda(orig_lambda); delete[] mg_opt->boundary_conditions; delete mg_opt; }
fix test
fix test
C++
bsd-2-clause
ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw,ForestClaw/forestclaw
2e1cc0de9f4f20d47f76458aefc710015cad8cc1
tests/nfcsymbianbackend/qnearfieldmanager/tst_qnearfieldmanager.cpp
tests/nfcsymbianbackend/qnearfieldmanager/tst_qnearfieldmanager.cpp
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QCoreApplication> #include "qnfctestcommon.h" #include "qnfctestutil.h" #include <qnearfieldmanager.h> #include <qnearfieldtarget.h> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QNearFieldTarget*) Q_DECLARE_METATYPE(QNearFieldTarget::Type) class tst_QNearFieldManager : public QObject { Q_OBJECT public: tst_QNearFieldManager(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void targetDetected(); void targetDetected_data(); }; tst_QNearFieldManager::tst_QNearFieldManager() { } void tst_QNearFieldManager::initTestCase() { } void tst_QNearFieldManager::cleanupTestCase() { } void tst_QNearFieldManager::targetDetected() { QFETCH(QNearFieldTarget::Type, type); QFETCH(QString, hint); QNearFieldManager nfcManager; QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*))); nfcManager.startTargetDetection(type); QNfcTestUtil::ShowMessage(hint); QTRY_VERIFY(!targetDetectedSpy.isEmpty()); QNearFieldTarget *target = targetDetectedSpy.first().at(0).value<QNearFieldTarget *>(); QSignalSpy disconnectedSpy(target, SIGNAL(disconnected())); QVERIFY(target); QVERIFY(!target->uid().isEmpty()); if (type != QNearFieldTarget::AnyTarget) { QCOMPARE(target->type(), type); } QNfcTestUtil::ShowMessage("please remove the target"); QTRY_VERIFY(!targetLostSpy.isEmpty()); QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>(); QCOMPARE(target, lostTarget); QVERIFY(!disconnectedSpy.isEmpty()); nfcManager.stopTargetDetection(); } void tst_QNearFieldManager::targetDetected_data() { QTest::addColumn<QNearFieldTarget::Type>("type"); QTest::addColumn<QString>("hint"); QTest::newRow("llcp device") << QNearFieldTarget::AnyTarget << "Please touch llcp device"; QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << "Please touch tag type1"; QTest::newRow("NfcTagType2") << QNearFieldTarget::NfcTagType1 << "Please touch tag type2"; QTest::newRow("NfcTagType3") << QNearFieldTarget::NfcTagType1 << "Please touch tag type3"; QTest::newRow("NfcTagType4") << QNearFieldTarget::NfcTagType1 << "Please touch tag type4"; } QTEST_MAIN(tst_QNearFieldManager); #include "tst_qnearfieldmanager.moc"
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QString> #include <QtTest/QtTest> #include <QtCore/QCoreApplication> #include "qnfctestcommon.h" #include "qnfctestutil.h" #include <qnearfieldmanager.h> #include <qnearfieldtarget.h> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QNearFieldTarget*) Q_DECLARE_METATYPE(QNearFieldTarget::Type) class tst_QNearFieldManager : public QObject { Q_OBJECT public: tst_QNearFieldManager(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void targetDetected(); void targetDetected_data(); }; tst_QNearFieldManager::tst_QNearFieldManager() { } void tst_QNearFieldManager::initTestCase() { } void tst_QNearFieldManager::cleanupTestCase() { } /** * Description: Unit test for NFC target detected and lost * * TestScenario: 1. Touch and remove llcp device/Type1/Type2/Type3/Type4 tag one by one * * TestExpectedResults: 1. llcp device/Type1/Type2/Type3/Type4 tag detected/lost signal can be received */ void tst_QNearFieldManager::targetDetected() { QFETCH(QNearFieldTarget::Type, type); QFETCH(QString, hint); QNearFieldManager nfcManager; QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*))); nfcManager.startTargetDetection(type); QNfcTestUtil::ShowMessage(hint); QTRY_VERIFY(!targetDetectedSpy.isEmpty()); QNearFieldTarget *target = targetDetectedSpy.first().at(0).value<QNearFieldTarget *>(); QSignalSpy disconnectedSpy(target, SIGNAL(disconnected())); QVERIFY(target); QVERIFY(!target->uid().isEmpty()); if (type != QNearFieldTarget::AnyTarget) { QCOMPARE(target->type(), type); } QNfcTestUtil::ShowMessage("please remove the target"); QTRY_VERIFY(!targetLostSpy.isEmpty()); QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>(); QCOMPARE(target, lostTarget); QVERIFY(!disconnectedSpy.isEmpty()); nfcManager.stopTargetDetection(); } void tst_QNearFieldManager::targetDetected_data() { QTest::addColumn<QNearFieldTarget::Type>("type"); QTest::addColumn<QString>("hint"); QTest::newRow("llcp device") << QNearFieldTarget::AnyTarget << "Please touch llcp device"; QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << "Please touch tag type1"; QTest::newRow("NfcTagType2") << QNearFieldTarget::NfcTagType1 << "Please touch tag type2"; QTest::newRow("NfcTagType3") << QNearFieldTarget::NfcTagType1 << "Please touch tag type3"; QTest::newRow("NfcTagType4") << QNearFieldTarget::NfcTagType1 << "Please touch tag type4"; } QTEST_MAIN(tst_QNearFieldManager); #include "tst_qnearfieldmanager.moc"
add comments/spec. to one UT case.
add comments/spec. to one UT case.
C++
lgpl-2.1
kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility
2f98f68badbc1f198fb22541da11a283200d1578
searchcore/src/vespa/searchcore/proton/matching/unpacking_iterators_optimizer.cpp
searchcore/src/vespa/searchcore/proton/matching/unpacking_iterators_optimizer.cpp
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "unpacking_iterators_optimizer.h" #include <vespa/log/log.h> LOG_SETUP(".matching.unpacking_iterators_optimizer"); #include "querynodes.h" #include <vespa/vespalib/util/classname.h> #include <vespa/searchlib/query/tree/queryvisitor.h> #include <vespa/searchlib/query/tree/templatetermvisitor.h> #include <vespa/searchlib/query/tree/querytreecreator.h> using namespace search::query; namespace proton::matching { namespace { struct TermExpander : QueryVisitor { std::vector<Node::UP> terms; template <typename T> void expand(T &n) { n.set_expensive(true); for (Node *child: n.getChildren()) { Node::UP node = QueryTreeCreator<ProtonNodeTypes>::replicate(*child); if (Term *term = dynamic_cast<Term *>(node.get())) { term->setRanked(false); term->setPositionData(false); terms.push_back(std::move(node)); } else { LOG(error, "Required a search::query::TermNode. Got %s", vespalib::getClassName(*node).c_str()); } } } void visit(And &) override {} void visit(AndNot &) override {} void visit(Equiv &) override {} void visit(NumberTerm &) override {} void visit(LocationTerm &) override {} void visit(Near &) override {} void visit(ONear &) override {} void visit(Or &) override {} void visit(Phrase &n) override { expand(n); } void visit(SameElement &n) override { expand(n); } void visit(PrefixTerm &) override {} void visit(RangeTerm &) override {} void visit(Rank &) override {} void visit(StringTerm &) override {} void visit(SubstringTerm &) override {} void visit(SuffixTerm &) override {} void visit(WeakAnd &) override {} void visit(WeightedSetTerm &) override {} void visit(DotProduct &) override {} void visit(WandTerm &) override {} void visit(PredicateQuery &) override {} void visit(RegExpTerm &) override {} void flush(Intermediate &parent) { for (Node::UP &term: terms) { parent.append(std::move(term)); } terms.clear(); } }; struct NodeTraverser : TemplateTermVisitor<NodeTraverser, ProtonNodeTypes> { bool split_unpacking_iterators; bool delay_unpacking_iterators; NodeTraverser(bool split_unpacking_iterators_in, bool delay_unpacking_iterators_in) : split_unpacking_iterators(split_unpacking_iterators_in), delay_unpacking_iterators(delay_unpacking_iterators_in) {} template <class TermNode> void visitTerm(TermNode &) {} void visit(ProtonNodeTypes::And &n) override { for (Node *child: n.getChildren()) { child->accept(*this); } if (split_unpacking_iterators) { TermExpander expander; for (Node *child: n.getChildren()) { child->accept(expander); } expander.flush(n); } } void visit(ProtonNodeTypes::Phrase &n) override { if (delay_unpacking_iterators) { n.set_expensive(true); } } void visit(ProtonNodeTypes::SameElement &n) override { if (delay_unpacking_iterators) { n.set_expensive(true); } } }; } // namespace proton::matching::<unnamed> search::query::Node::UP UnpackingIteratorsOptimizer::optimize(search::query::Node::UP root, bool has_white_list, bool split_unpacking_iterators, bool delay_unpacking_iterators) { if (split_unpacking_iterators || delay_unpacking_iterators) { NodeTraverser traverser(split_unpacking_iterators, delay_unpacking_iterators); root->accept(traverser); } if (has_white_list && split_unpacking_iterators) { TermExpander expander; root->accept(expander); if (!expander.terms.empty()) { Intermediate::UP and_node = std::make_unique<ProtonNodeTypes::And>(); and_node->append(std::move(root)); expander.flush(*and_node); root = std::move(and_node); } } return std::move(root); } } // namespace proton::matching
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "unpacking_iterators_optimizer.h" #include <vespa/log/log.h> LOG_SETUP(".matching.unpacking_iterators_optimizer"); #include "querynodes.h" #include <vespa/vespalib/util/classname.h> #include <vespa/searchlib/query/tree/queryvisitor.h> #include <vespa/searchlib/query/tree/templatetermvisitor.h> #include <vespa/searchlib/query/tree/querytreecreator.h> using namespace search::query; namespace proton::matching { namespace { struct TermExpander : QueryVisitor { std::vector<Node::UP> terms; template <typename T> void expand(T &n) { n.set_expensive(true); for (Node *child: n.getChildren()) { Node::UP node = QueryTreeCreator<ProtonNodeTypes>::replicate(*child); if (Term *term = dynamic_cast<Term *>(node.get())) { term->setRanked(false); term->setPositionData(false); terms.push_back(std::move(node)); } else { LOG(error, "Required a search::query::TermNode. Got %s", vespalib::getClassName(*node).c_str()); } } } void visit(And &) override {} void visit(AndNot &) override {} void visit(Equiv &) override {} void visit(NumberTerm &) override {} void visit(LocationTerm &) override {} void visit(Near &) override {} void visit(ONear &) override {} void visit(Or &) override {} void visit(Phrase &n) override { expand(n); } void visit(SameElement &n) override { expand(n); } void visit(PrefixTerm &) override {} void visit(RangeTerm &) override {} void visit(Rank &) override {} void visit(StringTerm &) override {} void visit(SubstringTerm &) override {} void visit(SuffixTerm &) override {} void visit(WeakAnd &) override {} void visit(WeightedSetTerm &) override {} void visit(DotProduct &) override {} void visit(WandTerm &) override {} void visit(PredicateQuery &) override {} void visit(RegExpTerm &) override {} void flush(Intermediate &parent) { for (Node::UP &term: terms) { parent.append(std::move(term)); } terms.clear(); } }; struct NodeTraverser : TemplateTermVisitor<NodeTraverser, ProtonNodeTypes> { bool split_unpacking_iterators; bool delay_unpacking_iterators; NodeTraverser(bool split_unpacking_iterators_in, bool delay_unpacking_iterators_in) : split_unpacking_iterators(split_unpacking_iterators_in), delay_unpacking_iterators(delay_unpacking_iterators_in) {} template <class TermNode> void visitTerm(TermNode &) {} void visit(ProtonNodeTypes::And &n) override { for (Node *child: n.getChildren()) { child->accept(*this); } if (split_unpacking_iterators) { TermExpander expander; for (Node *child: n.getChildren()) { child->accept(expander); } expander.flush(n); } } void visit(ProtonNodeTypes::Phrase &n) override { if (delay_unpacking_iterators) { n.set_expensive(true); } } void visit(ProtonNodeTypes::SameElement &n) override { if (delay_unpacking_iterators) { n.set_expensive(true); } } }; } // namespace proton::matching::<unnamed> search::query::Node::UP UnpackingIteratorsOptimizer::optimize(search::query::Node::UP root, bool has_white_list, bool split_unpacking_iterators, bool delay_unpacking_iterators) { if (split_unpacking_iterators || delay_unpacking_iterators) { NodeTraverser traverser(split_unpacking_iterators, delay_unpacking_iterators); root->accept(traverser); } if (has_white_list && split_unpacking_iterators) { TermExpander expander; root->accept(expander); if (!expander.terms.empty()) { Intermediate::UP and_node = std::make_unique<ProtonNodeTypes::And>(); and_node->append(std::move(root)); expander.flush(*and_node); root = std::move(and_node); } } return root; } } // namespace proton::matching
Remove redundant move.
Remove redundant move.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
b87f34fd44a367e413f7b33b064acec2beff5ec0
sirius-suite/regex/pthread/main.cpp
sirius-suite/regex/pthread/main.cpp
#include <stdio.h> #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/time.h> #include <pthread.h> #include "slre.h" #include "../../utils/timer.h" #include "../../utils/memoryman.h" #define MAXCAPS 1000000 #define EXPRESSIONS 100 #define QUESTIONS 200 /* Data */ char *exps[256]; struct slre *slre[EXPRESSIONS]; char *bufs[MAXCAPS]; int temp[512], buf_len[512]; struct cap **caps; int iterations; int NTHREADS; int numQs; int numExps; int s_max = 512; void *slre_thread(void *tid) { int start, end, *mytid; mytid = (int *)tid; start = (*mytid * iterations); end = start + iterations; for (int i = start; i < end; ++i) { for (int j = 0; j < numQs; ++j) { slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]); } } return NULL; } int fill(FILE *f, char **toFill, int *bufLen, int len) { int i = 0; while (i < len) { int ch = getc(f); if (ch == EOF) return i; bufLen[i] = 0; char *s = (char *)sirius_malloc(5000 + 1); while (1) { s[bufLen[i]] = ch; ++bufLen[i]; ch = getc(f); if (ch == '\n') { s[bufLen[i]] = 0; toFill[i] = s; ++i; break; } } } return i; } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n"); fprintf(stderr, "Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\n\n", argv[0]); exit(0); } /* Timing */ STATS_INIT("kernel", "regular_expression"); PRINT_STAT_STRING("abrv", "pthread_regex"); NTHREADS = atoi(argv[1]); PRINT_STAT_INT("threads", NTHREADS); FILE *f = fopen(argv[2], "r"); if (f == 0) { fprintf(stderr, "File %s not found\n", argv[1]); exit(1); } numExps = fill(f, exps, temp, EXPRESSIONS); PRINT_STAT_INT("expressions", numExps); FILE *f1 = fopen(argv[3], "r"); if (f1 == 0) { fprintf(stderr, "File %s not found\n", argv[2]); exit(1); } numQs = fill(f1, bufs, buf_len, QUESTIONS); PRINT_STAT_INT("questions", numQs); tic(); for (int i = 0; i < numExps; ++i) { slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre)); if (!slre_compile(slre[i], exps[i])) { printf("error compiling: %s\n", exps[i]); } } PRINT_STAT_DOUBLE("regex_compile", toc()); caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap)); for (int i = 0; i < numExps * numQs; ++i) { char *s = (char *)sirius_malloc(s_max); struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap)); z->ptr = s; caps[i] = z; } tic(); int tids[NTHREADS]; pthread_t threads[NTHREADS]; pthread_attr_t attr; iterations = numExps / NTHREADS; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (int i = 0; i < NTHREADS; i++) { tids[i] = i; pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]); } for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL); PRINT_STAT_DOUBLE("pthread_regex", toc()); #ifdef TESTING f = fopen("../input/regex_slre.pthread", "w"); for (int i = 0; i < numExps * numQs; ++i) fprintf(f, "%s\n", caps[i]->ptr); fclose(f); #endif sirius_free(caps); STATS_END(); return 0; }
#include <stdio.h> #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/time.h> #include <pthread.h> #include "slre.h" #include "../../utils/timer.h" #include "../../utils/memoryman.h" #define MAXCAPS 1000000 #define EXPRESSIONS 100 #define QUESTIONS 200 /* Data */ char *exps[256]; struct slre *slre[EXPRESSIONS]; char *bufs[MAXCAPS]; int temp[512], buf_len[512]; struct cap **caps; int iterations; int NTHREADS; int numQs; int numExps; int s_max = 512; void *slre_thread(void *tid) { int start, end, *mytid; mytid = (int *)tid; start = (*mytid * iterations); end = start + iterations; for (int i = start; i < end; ++i) { for (int j = 0; j < numQs; ++j) { slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]); } } return NULL; } int fill(FILE *f, char **toFill, int *bufLen, int len) { int i = 0; while (i < len) { int ch = getc(f); if (ch == EOF) return i; bufLen[i] = 0; char *s = (char *)sirius_malloc(5000 + 1); while (1) { s[bufLen[i]] = ch; ++bufLen[i]; ch = getc(f); if (ch == '\n') { s[bufLen[i]] = 0; toFill[i] = s; ++i; break; } } } return i; } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n"); fprintf(stderr, "Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\n\n", argv[0]); exit(0); } /* Timing */ STATS_INIT("kernel", "regular_expression"); PRINT_STAT_STRING("abrv", "pthread_regex"); NTHREADS = atoi(argv[1]); PRINT_STAT_INT("threads", NTHREADS); FILE *f = fopen(argv[2], "r"); if (f == 0) { fprintf(stderr, "File %s not found\n", argv[1]); exit(1); } numExps = fill(f, exps, temp, EXPRESSIONS); PRINT_STAT_INT("expressions", numExps); FILE *f1 = fopen(argv[3], "r"); if (f1 == 0) { fprintf(stderr, "File %s not found\n", argv[2]); exit(1); } numQs = fill(f1, bufs, buf_len, QUESTIONS); PRINT_STAT_INT("questions", numQs); tic(); for (int i = 0; i < numExps; ++i) { slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre)); if (!slre_compile(slre[i], exps[i])) { printf("error compiling: %s\n", exps[i]); } } PRINT_STAT_DOUBLE("regex_compile", toc()); caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap)); for (int i = 0; i < numExps * numQs; ++i) { char *s = (char *)sirius_malloc(s_max); struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap)); z->ptr = s; caps[i] = z; } tic(); int tids[NTHREADS]; pthread_t threads[NTHREADS]; pthread_attr_t attr; iterations = numExps / NTHREADS; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (int i = 0; i < NTHREADS; i++) { tids[i] = i; pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]); } for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL); PRINT_STAT_DOUBLE("pthread_regex", toc()); #ifdef TESTING fclose(f); f = fopen("../input/regex_slre.pthread", "w"); for (int i = 0; i < numExps * numQs; ++i) fprintf(f, "%s\n", caps[i]->ptr); #endif fclose(f); fclose(f1); sirius_free(caps); STATS_END(); return 0; }
fix resource leak
sirius-suite/regex/pthread/main.cpp: fix resource leak Close opended files before return. Signed-off-by: Danny Al-Gaaf <[email protected]>
C++
bsd-3-clause
claritylab/sirius,hoehnp/sirius,hoehnp/sirius,claritylab/sirius,claritylab/sirius,hoehnp/sirius,claritylab/sirius,hoehnp/sirius,hoehnp/sirius,claritylab/sirius,claritylab/sirius,hoehnp/sirius,hoehnp/sirius,claritylab/sirius
109fefd92d74f33ec7efe36ad3791726099a5c16
data-structures/chain/chain.cpp
data-structures/chain/chain.cpp
#include <iostream> #include <fstream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain ifstream infile(fileName) ; string line; while(getline(infile, line)) { istringstream iss(line); int n; iss >> n; insert(listSize, n); } } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt for(int i=0; i < listSize; i++) { int value = *this->get(i); int remainder = value%theInt; cout << "value: " << value << ", Remainder: " << remainder << ", listSize: " << listSize << ", i: " << i << endl; output(); if (remainder == 0 && value > theInt) { erase(i); i--; listSize--; } } } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list for(int i=0; i < listSize; i++) { int value = *this->get(i); insert(0, value); } } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } }
#include <iostream> #include <fstream> #include <sstream> #include "Myexception.h" #include "chain.h" using namespace std; void chain :: readAndStoreFromFile(char* fileName) { //This function reads integers from the file given by fileName then store them in the chain ifstream infile(fileName) ; string line; while(getline(infile, line)) { istringstream iss(line); int n; iss >> n; insert(listSize, n); } } void chain :: eraseModuloValue(int theInt) { //This function erases all the entries from the list which are multiple of theInt for(int i=0; i < listSize; i++) { int value = *this->get(i); int remainder = value%theInt; cout << "value: " << value << ", Remainder: " << remainder << ", listSize: " << listSize << ", i: " << i << endl; if (remainder == 0 && value > theInt) { erase(i); i--; } output(); } } void chain :: oddAndEvenOrdering() { //This function reorders the list such a way that all odd numbers precede all even numbers. //Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering. } void chain :: reverse() { //Reverses the list for(int i=0; i < listSize; i++) { int value = *this->get(i); insert(0, value); } } chain :: chain(int initialCapacity) { //Constructor if(initialCapacity < 1) { ostringstream s; s << "Initial capacity = " << initialCapacity << " Must be > 0"; throw illegalParameterValue(s.str()); } firstNode = NULL; listSize = 0; } chain :: ~chain() { //Destructor. Delete all nodes in chain while(firstNode != NULL) { //delete firstNode chainNode* nextNode = firstNode->next; delete firstNode; firstNode = nextNode; } } int* chain :: get(int theIndex) const { //Return element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return NULL; } chainNode* currentNode = firstNode; for(int i=0;i<theIndex;i++) currentNode = currentNode->next; return &currentNode->element; } int chain :: indexOf(const int& theElement) const { //Return index of first occurrence of theElement. //Return -1 of theElement not in list. chainNode* currentNode = firstNode; int index = 0; while(currentNode != NULL && currentNode->element != theElement) { //move to the next node currentNode = currentNode->next; index++; } //make sure we found matching element if(currentNode == NULL) return -1; else return index; } void chain :: erase(int theIndex) { //Delete the element whose index is theIndex. //Throw illegalIndex exception if no such element. try{ checkIndex(theIndex); } catch(illegalIndex &e){ e.outputMessage(); return; } chainNode* deleteNode; if(theIndex == 0) { //remove first node from chain deleteNode = firstNode; firstNode = firstNode->next; } else { //use p to get to predecessor of desired node chainNode* p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; deleteNode = p->next; p->next = p->next->next; //remove deleteNode from chain } listSize--; delete deleteNode; } void chain :: insert(int theIndex, const int& theElement) { //Insert theElement so that its index is theIndex. try{ if (theIndex < 0 || theIndex > listSize) {// invalid index ostringstream s; s << "index = " << theIndex << " size = " << listSize; throw illegalIndex(s.str()); } } catch(illegalIndex &e){ e.outputMessage(); return; } if(theIndex == 0) //insert at front firstNode = new chainNode(theElement, firstNode); else { chainNode *p = firstNode; for(int i=0;i<theIndex-1;i++) p = p->next; //insert after p p->next = new chainNode(theElement, p->next); } listSize++; } void chain :: output() const { //Put the list into the output. for(int i=0;i<listSize;i++) cout << *this->get(i) << " "; cout<<endl; } void chain::checkIndex(int theIndex) const { // Verify that theIndex is between 0 and // listSize - 1. if (theIndex < 0 || theIndex >= listSize){ ostringstream s; s << "index = " << theIndex << " size = " << listSize<<", the input index is invalid"; throw illegalIndex(s.str()); } }
Update chain.cpp
Update chain.cpp
C++
mit
atthehotcorner/coursework,atthehotcorner/coursework,atthehotcorner/coursework
29d315d16f9521defe5c96d81fb29d4a4d166bd9
chrome/browser/chromeos/login/webui_login_display_host.cc
chrome/browser/chromeos/login/webui_login_display_host.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/webui_login_display_host.h" #include "ash/desktop_background/desktop_background_controller.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/wm/window_animations.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/time.h" #include "base/values.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h" #include "chrome/browser/chromeos/login/oobe_display.h" #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/login/webui_login_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace chromeos { namespace { // URL which corresponds to the login WebUI. const char kLoginURL[] = "chrome://oobe/login"; // URL which corresponds to the OOBE WebUI. const char kOobeURL[] = "chrome://oobe"; // Duration of sign-in transition animation. const int kLoginFadeoutTransitionDurationMs = 700; // Number of times we try to reload OOBE/login WebUI if it crashes. const int kCrashCountLimit = 5; // Whether to enable tnitializing WebUI in hidden state (see // |initialize_webui_hidden_|) by default. const bool kHiddenWebUIInitializationDefault = true; // Switch values that might be used to override WebUI init type. const char kWebUIInitParallel[] = "parallel"; const char kWebUIInitPostpone[] = "postpone"; } // namespace // WebUILoginDisplayHost ------------------------------------------------------- WebUILoginDisplayHost::WebUILoginDisplayHost(const gfx::Rect& background_bounds) : BaseLoginDisplayHost(background_bounds), login_window_(NULL), login_view_(NULL), webui_login_display_(NULL), is_showing_login_(false), is_wallpaper_loaded_(false), status_area_saved_visibility_(false), crash_count_(0), restore_path_(RESTORE_UNKNOWN) { bool is_registered = WizardController::IsDeviceRegistered(); bool zero_delay_enabled = WizardController::IsZeroDelayEnabled(); bool disable_boot_animation = CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableBootAnimation); bool disable_oobe_animation = CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableOobeAnimation); bool new_oobe_ui = !CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableNewOobe); waiting_for_wallpaper_load_ = new_oobe_ui && !zero_delay_enabled && (is_registered || !disable_oobe_animation) && (!is_registered || !disable_boot_animation); waiting_for_user_pods_ = new_oobe_ui && !zero_delay_enabled && !waiting_for_wallpaper_load_; initialize_webui_hidden_ = kHiddenWebUIInitializationDefault && (waiting_for_user_pods_ || waiting_for_wallpaper_load_); // Prevents white flashing on OOBE (http://crbug.com/131569). aura::Env::GetInstance()->set_render_white_bg(false); // Check if WebUI init type is overriden. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshWebUIInit)) { const std::string override_type = CommandLine::ForCurrentProcess()-> GetSwitchValueASCII(switches::kAshWebUIInit); if (override_type == kWebUIInitParallel) initialize_webui_hidden_ = true; else if (override_type == kWebUIInitPostpone) initialize_webui_hidden_ = false; } // Always postpone WebUI initialization on first boot, otherwise we miss // initial animation. if (!WizardController::IsOobeCompleted()) initialize_webui_hidden_ = false; if (waiting_for_wallpaper_load_) { registrar_.Add(this, chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED, content::NotificationService::AllSources()); } if (waiting_for_user_pods_ && initialize_webui_hidden_) { registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } } WebUILoginDisplayHost::~WebUILoginDisplayHost() { if (login_window_) login_window_->Close(); } // LoginDisplayHost implementation --------------------------------------------- LoginDisplay* WebUILoginDisplayHost::CreateLoginDisplay( LoginDisplay::Delegate* delegate) { webui_login_display_ = new WebUILoginDisplay(delegate); webui_login_display_->set_background_bounds(background_bounds()); return webui_login_display_; } gfx::NativeWindow WebUILoginDisplayHost::GetNativeWindow() const { return login_window_ ? login_window_->GetNativeWindow() : NULL; } views::Widget* WebUILoginDisplayHost::GetWidget() const { return login_window_; } void WebUILoginDisplayHost::OpenProxySettings() { if (login_view_) login_view_->OpenProxySettings(); } void WebUILoginDisplayHost::SetOobeProgressBarVisible(bool visible) { GetOobeUI()->ShowOobeUI(visible); } void WebUILoginDisplayHost::SetShutdownButtonEnabled(bool enable) { } void WebUILoginDisplayHost::SetStatusAreaVisible(bool visible) { if (initialize_webui_hidden_) status_area_saved_visibility_ = visible; else if (login_view_) login_view_->SetStatusAreaVisible(visible); } void WebUILoginDisplayHost::StartWizard(const std::string& first_screen_name, DictionaryValue* screen_parameters) { // Keep parameters to restore if renderer crashes. restore_path_ = RESTORE_WIZARD; wizard_first_screen_name_ = first_screen_name; if (screen_parameters) wizard_screen_parameters_.reset(screen_parameters->DeepCopy()); else wizard_screen_parameters_.reset(NULL); is_showing_login_ = false; scoped_ptr<DictionaryValue> scoped_parameters(screen_parameters); if (waiting_for_wallpaper_load_ && !initialize_webui_hidden_) return; if (!login_window_) LoadURL(GURL(kOobeURL)); BaseLoginDisplayHost::StartWizard(first_screen_name, scoped_parameters.release()); } void WebUILoginDisplayHost::StartSignInScreen() { restore_path_ = RESTORE_SIGN_IN; is_showing_login_ = true; if (waiting_for_wallpaper_load_ && !initialize_webui_hidden_) return; if (!login_window_) LoadURL(GURL(kLoginURL)); BaseLoginDisplayHost::StartSignInScreen(); CHECK(webui_login_display_); GetOobeUI()->ShowSigninScreen(webui_login_display_); if (chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) SetStatusAreaVisible(false); } void WebUILoginDisplayHost::OnPreferencesChanged() { if (is_showing_login_) webui_login_display_->OnPreferencesChanged(); } void WebUILoginDisplayHost::OnBrowserCreated() { // Close lock window now so that the launched browser can receive focus. if (login_window_) { login_window_->Close(); login_window_ = NULL; login_view_ = NULL; } } void WebUILoginDisplayHost::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { BaseLoginDisplayHost::Observe(type, source, details); if (chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED == type) { is_wallpaper_loaded_ = true; ash::Shell::GetInstance()->user_wallpaper_delegate()-> OnWallpaperBootAnimationFinished(); if (waiting_for_wallpaper_load_) { // StartWizard / StartSignInScreen could be called multiple times through // the lifetime of host. // Make sure that subsequent calls are not postponed. waiting_for_wallpaper_load_ = false; if (initialize_webui_hidden_) ShowWebUI(); else StartPostponedWebUI(); } registrar_.Remove(this, chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED, content::NotificationService::AllSources()); } else if (chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE == type) { if (waiting_for_user_pods_ && initialize_webui_hidden_) { waiting_for_user_pods_ = false; ShowWebUI(); } registrar_.Remove(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } else { NOTREACHED(); } } void WebUILoginDisplayHost::LoadURL(const GURL& url) { if (!login_window_) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = background_bounds(); params.show_state = ui::SHOW_STATE_FULLSCREEN; if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableNewOobe)) params.transparent = true; params.parent = ash::Shell::GetContainer( ash::Shell::GetPrimaryRootWindow(), ash::internal::kShellWindowId_LockScreenContainer); login_window_ = new views::Widget; login_window_->Init(params); login_view_ = new WebUILoginView(); login_view_->Init(login_window_); ash::SetWindowVisibilityAnimationDuration( login_window_->GetNativeView(), base::TimeDelta::FromMilliseconds(kLoginFadeoutTransitionDurationMs)); ash::SetWindowVisibilityAnimationTransition( login_window_->GetNativeView(), ash::ANIMATE_HIDE); login_window_->SetContentsView(login_view_); login_view_->UpdateWindowType(); // If WebUI is initialized in hidden state, show it only if we're no // longer waiting for wallpaper animation/user images loading. Otherwise, // always show it. if (!initialize_webui_hidden_ || (!waiting_for_wallpaper_load_ && !waiting_for_user_pods_)) { login_window_->Show(); } else { login_view_->set_is_hidden(true); } login_window_->GetNativeView()->SetName("WebUILoginView"); login_view_->OnWindowCreated(); } // Subscribe to crash events. content::WebContentsObserver::Observe(login_view_->GetWebContents()); login_view_->LoadURL(url); } void WebUILoginDisplayHost::RenderViewGone(base::TerminationStatus status) { // Do not try to restore on shutdown if (browser_shutdown::GetShutdownType() != browser_shutdown::NOT_VALID) return; crash_count_++; if (crash_count_ > kCrashCountLimit) return; if (status != base::TERMINATION_STATUS_NORMAL_TERMINATION) { // Restart if renderer has crashed. LOG(ERROR) << "Renderer crash on login window"; switch (restore_path_) { case RESTORE_WIZARD: StartWizard(wizard_first_screen_name_, wizard_screen_parameters_.release()); break; case RESTORE_SIGN_IN: StartSignInScreen(); break; default: NOTREACHED(); break; } } } OobeUI* WebUILoginDisplayHost::GetOobeUI() const { if (!login_view_) return NULL; return static_cast<OobeUI*>(login_view_->GetWebUI()->GetController()); } WizardController* WebUILoginDisplayHost::CreateWizardController() { // TODO(altimofeev): ensure that WebUI is ready. OobeDisplay* oobe_display = GetOobeUI(); return new WizardController(this, oobe_display); } void WebUILoginDisplayHost::ShowWebUI() { if (!login_window_ || !login_view_) { NOTREACHED(); return; } login_window_->Show(); login_view_->GetWebContents()->Focus(); login_view_->SetStatusAreaVisible(status_area_saved_visibility_); login_view_->OnPostponedShow(); } void WebUILoginDisplayHost::StartPostponedWebUI() { if (!is_wallpaper_loaded_) { NOTREACHED(); return; } // Wallpaper has finished loading before StartWizard/StartSignInScreen has // been called. In general this should not happen. // Let go through normal code path when one of those will be called. if (restore_path_ == RESTORE_UNKNOWN) { NOTREACHED(); return; } switch (restore_path_) { case RESTORE_WIZARD: StartWizard(wizard_first_screen_name_, wizard_screen_parameters_.release()); break; case RESTORE_SIGN_IN: StartSignInScreen(); break; default: NOTREACHED(); break; } } } // namespace chromeos
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/webui_login_display_host.h" #include "ash/desktop_background/desktop_background_controller.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/wm/window_animations.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/time.h" #include "base/values.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h" #include "chrome/browser/chromeos/login/oobe_display.h" #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/login/webui_login_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/views/widget/widget.h" namespace chromeos { namespace { // URL which corresponds to the login WebUI. const char kLoginURL[] = "chrome://oobe/login"; // URL which corresponds to the OOBE WebUI. const char kOobeURL[] = "chrome://oobe"; // Duration of sign-in transition animation. const int kLoginFadeoutTransitionDurationMs = 700; // Number of times we try to reload OOBE/login WebUI if it crashes. const int kCrashCountLimit = 5; // Whether to enable tnitializing WebUI in hidden state (see // |initialize_webui_hidden_|) by default. const bool kHiddenWebUIInitializationDefault = true; // Switch values that might be used to override WebUI init type. const char kWebUIInitParallel[] = "parallel"; const char kWebUIInitPostpone[] = "postpone"; } // namespace // WebUILoginDisplayHost ------------------------------------------------------- WebUILoginDisplayHost::WebUILoginDisplayHost(const gfx::Rect& background_bounds) : BaseLoginDisplayHost(background_bounds), login_window_(NULL), login_view_(NULL), webui_login_display_(NULL), is_showing_login_(false), is_wallpaper_loaded_(false), status_area_saved_visibility_(false), crash_count_(0), restore_path_(RESTORE_UNKNOWN) { bool is_registered = WizardController::IsDeviceRegistered(); bool zero_delay_enabled = WizardController::IsZeroDelayEnabled(); bool disable_boot_animation = CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableBootAnimation); bool disable_oobe_animation = CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableOobeAnimation); bool new_oobe_ui = !CommandLine::ForCurrentProcess()-> HasSwitch(switches::kDisableNewOobe); waiting_for_wallpaper_load_ = new_oobe_ui && !zero_delay_enabled && (is_registered || !disable_oobe_animation) && (!is_registered || !disable_boot_animation); waiting_for_user_pods_ = new_oobe_ui && !zero_delay_enabled && !waiting_for_wallpaper_load_; initialize_webui_hidden_ = kHiddenWebUIInitializationDefault && (waiting_for_user_pods_ || waiting_for_wallpaper_load_); // Prevents white flashing on OOBE (http://crbug.com/131569). aura::Env::GetInstance()->set_render_white_bg(false); // Check if WebUI init type is overriden. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshWebUIInit)) { const std::string override_type = CommandLine::ForCurrentProcess()-> GetSwitchValueASCII(switches::kAshWebUIInit); if (override_type == kWebUIInitParallel) initialize_webui_hidden_ = true; else if (override_type == kWebUIInitPostpone) initialize_webui_hidden_ = false; } // Always postpone WebUI initialization on first boot, otherwise we miss // initial animation. if (!WizardController::IsOobeCompleted()) initialize_webui_hidden_ = false; if (waiting_for_wallpaper_load_) { registrar_.Add(this, chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED, content::NotificationService::AllSources()); } if (waiting_for_user_pods_ && initialize_webui_hidden_) { registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } } WebUILoginDisplayHost::~WebUILoginDisplayHost() { if (login_window_) login_window_->Close(); } // LoginDisplayHost implementation --------------------------------------------- LoginDisplay* WebUILoginDisplayHost::CreateLoginDisplay( LoginDisplay::Delegate* delegate) { webui_login_display_ = new WebUILoginDisplay(delegate); webui_login_display_->set_background_bounds(background_bounds()); return webui_login_display_; } gfx::NativeWindow WebUILoginDisplayHost::GetNativeWindow() const { return login_window_ ? login_window_->GetNativeWindow() : NULL; } views::Widget* WebUILoginDisplayHost::GetWidget() const { return login_window_; } void WebUILoginDisplayHost::OpenProxySettings() { if (login_view_) login_view_->OpenProxySettings(); } void WebUILoginDisplayHost::SetOobeProgressBarVisible(bool visible) { GetOobeUI()->ShowOobeUI(visible); } void WebUILoginDisplayHost::SetShutdownButtonEnabled(bool enable) { } void WebUILoginDisplayHost::SetStatusAreaVisible(bool visible) { if (initialize_webui_hidden_) status_area_saved_visibility_ = visible; else if (login_view_) login_view_->SetStatusAreaVisible(visible); } void WebUILoginDisplayHost::StartWizard(const std::string& first_screen_name, DictionaryValue* screen_parameters) { // Keep parameters to restore if renderer crashes. restore_path_ = RESTORE_WIZARD; wizard_first_screen_name_ = first_screen_name; if (screen_parameters) wizard_screen_parameters_.reset(screen_parameters->DeepCopy()); else wizard_screen_parameters_.reset(NULL); is_showing_login_ = false; scoped_ptr<DictionaryValue> scoped_parameters(screen_parameters); if (waiting_for_wallpaper_load_ && !initialize_webui_hidden_) return; if (!login_window_) LoadURL(GURL(kOobeURL)); BaseLoginDisplayHost::StartWizard(first_screen_name, scoped_parameters.release()); } void WebUILoginDisplayHost::StartSignInScreen() { restore_path_ = RESTORE_SIGN_IN; is_showing_login_ = true; if (waiting_for_wallpaper_load_ && !initialize_webui_hidden_) return; if (!login_window_) LoadURL(GURL(kLoginURL)); BaseLoginDisplayHost::StartSignInScreen(); CHECK(webui_login_display_); GetOobeUI()->ShowSigninScreen(webui_login_display_); if (chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) SetStatusAreaVisible(false); } void WebUILoginDisplayHost::OnPreferencesChanged() { if (is_showing_login_) webui_login_display_->OnPreferencesChanged(); } void WebUILoginDisplayHost::OnBrowserCreated() { // Close lock window now so that the launched browser can receive focus. if (login_window_) { login_window_->Close(); login_window_ = NULL; login_view_ = NULL; } } void WebUILoginDisplayHost::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED == type) { is_wallpaper_loaded_ = true; ash::Shell::GetInstance()->user_wallpaper_delegate()-> OnWallpaperBootAnimationFinished(); if (waiting_for_wallpaper_load_) { // StartWizard / StartSignInScreen could be called multiple times through // the lifetime of host. // Make sure that subsequent calls are not postponed. waiting_for_wallpaper_load_ = false; if (initialize_webui_hidden_) ShowWebUI(); else StartPostponedWebUI(); } registrar_.Remove(this, chrome::NOTIFICATION_WALLPAPER_ANIMATION_FINISHED, content::NotificationService::AllSources()); } else if (chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE == type) { if (waiting_for_user_pods_ && initialize_webui_hidden_) { waiting_for_user_pods_ = false; ShowWebUI(); } registrar_.Remove(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } else { BaseLoginDisplayHost::Observe(type, source, details); } } void WebUILoginDisplayHost::LoadURL(const GURL& url) { if (!login_window_) { views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = background_bounds(); params.show_state = ui::SHOW_STATE_FULLSCREEN; if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableNewOobe)) params.transparent = true; params.parent = ash::Shell::GetContainer( ash::Shell::GetPrimaryRootWindow(), ash::internal::kShellWindowId_LockScreenContainer); login_window_ = new views::Widget; login_window_->Init(params); login_view_ = new WebUILoginView(); login_view_->Init(login_window_); ash::SetWindowVisibilityAnimationDuration( login_window_->GetNativeView(), base::TimeDelta::FromMilliseconds(kLoginFadeoutTransitionDurationMs)); ash::SetWindowVisibilityAnimationTransition( login_window_->GetNativeView(), ash::ANIMATE_HIDE); login_window_->SetContentsView(login_view_); login_view_->UpdateWindowType(); // If WebUI is initialized in hidden state, show it only if we're no // longer waiting for wallpaper animation/user images loading. Otherwise, // always show it. if (!initialize_webui_hidden_ || (!waiting_for_wallpaper_load_ && !waiting_for_user_pods_)) { login_window_->Show(); } else { login_view_->set_is_hidden(true); } login_window_->GetNativeView()->SetName("WebUILoginView"); login_view_->OnWindowCreated(); } // Subscribe to crash events. content::WebContentsObserver::Observe(login_view_->GetWebContents()); login_view_->LoadURL(url); } void WebUILoginDisplayHost::RenderViewGone(base::TerminationStatus status) { // Do not try to restore on shutdown if (browser_shutdown::GetShutdownType() != browser_shutdown::NOT_VALID) return; crash_count_++; if (crash_count_ > kCrashCountLimit) return; if (status != base::TERMINATION_STATUS_NORMAL_TERMINATION) { // Restart if renderer has crashed. LOG(ERROR) << "Renderer crash on login window"; switch (restore_path_) { case RESTORE_WIZARD: StartWizard(wizard_first_screen_name_, wizard_screen_parameters_.release()); break; case RESTORE_SIGN_IN: StartSignInScreen(); break; default: NOTREACHED(); break; } } } OobeUI* WebUILoginDisplayHost::GetOobeUI() const { if (!login_view_) return NULL; return static_cast<OobeUI*>(login_view_->GetWebUI()->GetController()); } WizardController* WebUILoginDisplayHost::CreateWizardController() { // TODO(altimofeev): ensure that WebUI is ready. OobeDisplay* oobe_display = GetOobeUI(); return new WizardController(this, oobe_display); } void WebUILoginDisplayHost::ShowWebUI() { if (!login_window_ || !login_view_) { NOTREACHED(); return; } login_window_->Show(); login_view_->GetWebContents()->Focus(); login_view_->SetStatusAreaVisible(status_area_saved_visibility_); login_view_->OnPostponedShow(); } void WebUILoginDisplayHost::StartPostponedWebUI() { if (!is_wallpaper_loaded_) { NOTREACHED(); return; } // Wallpaper has finished loading before StartWizard/StartSignInScreen has // been called. In general this should not happen. // Let go through normal code path when one of those will be called. if (restore_path_ == RESTORE_UNKNOWN) { NOTREACHED(); return; } switch (restore_path_) { case RESTORE_WIZARD: StartWizard(wizard_first_screen_name_, wizard_screen_parameters_.release()); break; case RESTORE_SIGN_IN: StartSignInScreen(); break; default: NOTREACHED(); break; } } } // namespace chromeos
Remove unnecessary NOTREACHED in WebUILoginDisplayHost::Observe
chromeos: Remove unnecessary NOTREACHED in WebUILoginDisplayHost::Observe There should no be NOTREACHED in this method since BaseLoginDisplayHost::Observe() is handling other types of notifications. BUG=145838 TEST=successfully login with debug build Review URL: https://chromiumcodereview.appspot.com/10907020 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@154400 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
M4sse/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,Chilledheart/chromium,patrickm/chromium.src,zcbenz/cefode-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,M4sse/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,patrickm/chromium.src,littlstar/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,patrickm/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,Chilledheart/chromium,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,anirudhSK/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,dushu1203/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,dednal/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,ltilve/chromium,patrickm/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,dednal/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,zcbenz/cefode-chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk
db7ecc7a4653caa21e074f8dd135f624bbe1b44d
pakfile.cpp
pakfile.cpp
#include "pakfile.h" #include <stdexcept> #include <iterator> #include <algorithm> #include <cstring> #if defined(_MSC_VER) # pragma warning(disable: 4996) # pragma warning(disable: 4244) #endif namespace scpak { void BinaryReader::readBytes(int size, byte buf[]) { for (int i=0; i<size; ++i) buf[i] = readByte(); } int BinaryReader::readInt() { int value; readBytes(4, reinterpret_cast<byte*>(&value)); return value; } int BinaryReader::read7BitEncodedInt() { int value = 0; int offset = 0; while (offset != 35) { byte b = readByte(); value |= static_cast<int>(b & 127) << offset; offset += 7; if ((b & 128) == 0) return value; } throw std::runtime_error("bad 7 bit encoded int32"); } std::string BinaryReader::readString() { int length = read7BitEncodedInt(); std::string buffer; buffer.resize(length); for (int i=0; i<length; ++i) buffer[i] = static_cast<char>(readByte()); return buffer; } StreamBinaryReader::StreamBinaryReader(std::istream *stream) { m_stream = stream; } byte StreamBinaryReader::readByte() { if (!*m_stream) throw std::runtime_error("bad stream"); char ch; m_stream->get(ch); return static_cast<byte>(ch); } MemoryBinaryReader::MemoryBinaryReader(const byte *buffer) { position = 0; m_buffer = buffer; } byte MemoryBinaryReader::readByte() { return m_buffer[++position]; } StreamBinaryWriter::StreamBinaryWriter(std::ostream *stream) { m_stream = stream; } void StreamBinaryWriter::writeByte(byte value) { if (!m_stream) throw std::runtime_error("bad stream"); char ch = static_cast<char>(value); m_stream->put(ch); } MemoryBinaryWriter::MemoryBinaryWriter(byte *buffer) { position = 0; m_buffer = buffer; } void MemoryBinaryWriter::writeByte(byte value) { m_buffer[++position] = value; } void BinaryWriter::writeBytes(int size, const byte value[]) { for (int i=0; i<size; ++i) writeByte(value[i]); } void BinaryWriter::writeInt(int value) { writeBytes(4, reinterpret_cast<byte*>(&value)); } void BinaryWriter::write7BitEncodedInt(int value) { while ((value & 128) != 0) { byte n = static_cast<byte>(value & 127); n |= 128; writeByte(n); value >>= 7; } byte n = static_cast<byte>(value); writeByte(n); } void BinaryWriter::writeString(const std::string &value) { write7BitEncodedInt(value.length()); writeBytes(value.length(), reinterpret_cast<const byte*>(value.data())); } PakFile::PakFile() { } PakFile::PakFile(PakFile &&other): m_contents(std::move(other.m_contents)) { } PakFile::~PakFile() { for (const PakItem &item : m_contents) { delete[] item.name; delete[] item.type; delete[] item.data; } } void PakFile::load(std::istream &stream) { // read header PakHeader header; stream.read(reinterpret_cast<char*>(&header), sizeof(header)); if (!header.checkMagic()) throw std::runtime_error("bad pak file"); StreamBinaryReader reader(&stream); // read content dictionary for (int i=0; i<header.contentCount; ++i) { std::string name = reader.readString(); std::string type = reader.readString(); int offset = reader.readInt(); int length = reader.readInt(); PakItem item; item.name = new char[name.length()+1]; std::strcpy(item.name, name.c_str()); item.type = new char[type.length()+1]; std::strcpy(item.type, type.c_str()); item.offset = offset; item.length = length; m_contents.push_back(item); } // read all contents for (PakItem &item : m_contents) { stream.seekg(header.contentOffset + item.offset, std::ios::beg); item.data = new byte[item.length]; stream.read(reinterpret_cast<char*>(item.data), item.length); item.offset = -1; // we will not be able to access the stream } } void PakFile::save(std::ostream &stream) { // we cannot detect the length of the file and where content begins, // so we have to write the header twice // write file header for the first time PakHeader header; header.contentCount = m_contents.size(); StreamBinaryWriter writer(&stream); stream.write(reinterpret_cast<char*>(&header), sizeof(header)); // we do not know where the content will locate, so it is also // necessary to write content dictionary twice // write content dictionary for the first time for (const PakItem &item : m_contents) { writer.writeString(item.name); writer.writeString(item.type); writer.writeInt(item.offset); // should be -1 writer.writeInt(item.length); } header.contentOffset = stream.tellp(); // write content items for (PakItem &item : m_contents) { // there are a magic number before every content data in origin Content.pak // it's DEADBEEF stream.put(0xDE); stream.put(0xAD); stream.put(0xBE); stream.put(0xEF); item.offset = static_cast<int>(stream.tellp()) - header.contentOffset; stream.write(reinterpret_cast<char*>(item.data), item.length); } header.fileLength = stream.tellp(); // write the header again stream.seekp(0, std::ios::beg); stream.write(reinterpret_cast<char*>(&header), sizeof(header)); // write content dictionary again for (PakItem &item : m_contents) { writer.writeString(item.name); writer.writeString(item.type); writer.writeInt(item.offset); writer.writeInt(item.length); item.offset = -1; // as items can be modified, it is meaningless to keep a offset } } const std::vector<PakItem>& PakFile::contents() const { return m_contents; } void PakFile::addItem(const PakItem &item) { PakItem newItem; newItem.name = new char[strlen(item.name)+1]; strcpy(newItem.name, item.name); newItem.type = new char[strlen(item.type)+1]; strcpy(newItem.type, item.type); newItem.length = item.length; newItem.data = new byte[newItem.length]; memcpy(newItem.data, item.data, newItem.length); m_contents.push_back(newItem); } void PakFile::addItem(PakItem &&item) { m_contents.push_back(item); item.name = nullptr; item.type = nullptr; item.data = nullptr; } PakItem& PakFile::getItem(std::size_t where) { return m_contents.at(where); } void PakFile::removeItem(std::size_t where) { m_contents.erase(m_contents.begin()+where); } void PakFile::deleteItem(std::size_t where) { PakItem &item = m_contents.at(where); delete[] item.name; delete[] item.type; delete[] item.data; m_contents.erase(m_contents.begin()+where); } }
#include "pakfile.h" #include <stdexcept> #include <iterator> #include <algorithm> #include <cstring> #if defined(_MSC_VER) # pragma warning(disable: 4996) # pragma warning(disable: 4244) #endif namespace scpak { void BinaryReader::readBytes(int size, byte buf[]) { for (int i=0; i<size; ++i) buf[i] = readByte(); } int BinaryReader::readInt() { int value; readBytes(4, reinterpret_cast<byte*>(&value)); return value; } int BinaryReader::read7BitEncodedInt() { int value = 0; int offset = 0; while (offset != 35) { byte b = readByte(); value |= static_cast<int>(b & 127) << offset; offset += 7; if ((b & 128) == 0) return value; } throw std::runtime_error("bad 7 bit encoded int32"); } std::string BinaryReader::readString() { int length = read7BitEncodedInt(); std::string buffer; buffer.resize(length); for (int i=0; i<length; ++i) buffer[i] = static_cast<char>(readByte()); return buffer; } StreamBinaryReader::StreamBinaryReader(std::istream *stream) { m_stream = stream; } byte StreamBinaryReader::readByte() { if (!*m_stream) throw std::runtime_error("bad stream"); char ch; m_stream->get(ch); return static_cast<byte>(ch); } MemoryBinaryReader::MemoryBinaryReader(const byte *buffer) { position = 0; m_buffer = buffer; } byte MemoryBinaryReader::readByte() { return m_buffer[position++]; } StreamBinaryWriter::StreamBinaryWriter(std::ostream *stream) { m_stream = stream; } void StreamBinaryWriter::writeByte(byte value) { if (!m_stream) throw std::runtime_error("bad stream"); char ch = static_cast<char>(value); m_stream->put(ch); } MemoryBinaryWriter::MemoryBinaryWriter(byte *buffer) { position = 0; m_buffer = buffer; } void MemoryBinaryWriter::writeByte(byte value) { m_buffer[position++] = value; } void BinaryWriter::writeBytes(int size, const byte value[]) { for (int i=0; i<size; ++i) writeByte(value[i]); } void BinaryWriter::writeInt(int value) { writeBytes(4, reinterpret_cast<byte*>(&value)); } void BinaryWriter::write7BitEncodedInt(int value) { while (value > 127) { byte n = static_cast<byte>(value & 127); n |= 128; writeByte(n); value >>= 7; } byte n = static_cast<byte>(value); writeByte(n); } void BinaryWriter::writeString(const std::string &value) { write7BitEncodedInt(value.length()); writeBytes(value.length(), reinterpret_cast<const byte*>(value.data())); } PakFile::PakFile() { } PakFile::PakFile(PakFile &&other): m_contents(std::move(other.m_contents)) { } PakFile::~PakFile() { for (const PakItem &item : m_contents) { delete[] item.name; delete[] item.type; delete[] item.data; } } void PakFile::load(std::istream &stream) { // read header PakHeader header; stream.read(reinterpret_cast<char*>(&header), sizeof(header)); if (!header.checkMagic()) throw std::runtime_error("bad pak file"); StreamBinaryReader reader(&stream); // read content dictionary for (int i=0; i<header.contentCount; ++i) { std::string name = reader.readString(); std::string type = reader.readString(); int offset = reader.readInt(); int length = reader.readInt(); PakItem item; item.name = new char[name.length()+1]; std::strcpy(item.name, name.c_str()); item.type = new char[type.length()+1]; std::strcpy(item.type, type.c_str()); item.offset = offset; item.length = length; m_contents.push_back(item); } // read all contents for (PakItem &item : m_contents) { stream.seekg(header.contentOffset + item.offset, std::ios::beg); item.data = new byte[item.length]; stream.read(reinterpret_cast<char*>(item.data), item.length); item.offset = -1; // we will not be able to access the stream } } void PakFile::save(std::ostream &stream) { // we cannot detect the length of the file and where content begins, // so we have to write the header twice // write file header for the first time PakHeader header; header.contentCount = m_contents.size(); StreamBinaryWriter writer(&stream); stream.write(reinterpret_cast<char*>(&header), sizeof(header)); // we do not know where the content will locate, so it is also // necessary to write content dictionary twice // write content dictionary for the first time for (const PakItem &item : m_contents) { writer.writeString(item.name); writer.writeString(item.type); writer.writeInt(item.offset); // should be -1 writer.writeInt(item.length); } header.contentOffset = stream.tellp(); // write content items for (PakItem &item : m_contents) { // there are a magic number before every content data in origin Content.pak // it's DEADBEEF stream.put(0xDE); stream.put(0xAD); stream.put(0xBE); stream.put(0xEF); item.offset = static_cast<int>(stream.tellp()) - header.contentOffset; stream.write(reinterpret_cast<char*>(item.data), item.length); } header.fileLength = stream.tellp(); // write the header again stream.seekp(0, std::ios::beg); stream.write(reinterpret_cast<char*>(&header), sizeof(header)); // write content dictionary again for (PakItem &item : m_contents) { writer.writeString(item.name); writer.writeString(item.type); writer.writeInt(item.offset); writer.writeInt(item.length); item.offset = -1; // as items can be modified, it is meaningless to keep a offset } } const std::vector<PakItem>& PakFile::contents() const { return m_contents; } void PakFile::addItem(const PakItem &item) { PakItem newItem; newItem.name = new char[strlen(item.name)+1]; strcpy(newItem.name, item.name); newItem.type = new char[strlen(item.type)+1]; strcpy(newItem.type, item.type); newItem.length = item.length; newItem.data = new byte[newItem.length]; memcpy(newItem.data, item.data, newItem.length); m_contents.push_back(newItem); } void PakFile::addItem(PakItem &&item) { m_contents.push_back(item); item.name = nullptr; item.type = nullptr; item.data = nullptr; } PakItem& PakFile::getItem(std::size_t where) { return m_contents.at(where); } void PakFile::removeItem(std::size_t where) { m_contents.erase(m_contents.begin()+where); } void PakFile::deleteItem(std::size_t where) { PakItem &item = m_contents.at(where); delete[] item.name; delete[] item.type; delete[] item.data; m_contents.erase(m_contents.begin()+where); } }
fix bugs
fix bugs
C++
mit
qnnnnez/scpak
9a03e1c65425d55bb078eba10cf76f77d7ba22da
tests/TestHttpRequest.cpp
tests/TestHttpRequest.cpp
// Copyright Paul Dardeau, SwampBits LLC 2014 // BSD License #include "TestHttpRequest.h" #include "HttpRequest.h" #include "MockSocket.h" // Modeled after tests from: // http://subversion.assembla.com/svn/opencats/trunk/cats-0.9.2/lib/simpletest/test/http_test.php static const std::string GET_PATH = "http://a.valid.host/here.html"; static const std::string POST_PATH = "/here.html"; static const std::string DEFAULT_GET = "GET " + GET_PATH + " HTTP/1.0\r\n" + "Host: my-proxy:8080\r\n" + "Connection: close\r\n"; static const std::string DEFAULT_POST = "POST " + POST_PATH + " HTTP/1.0\r\n" + "Host: a.valid.host\r\n" + "Connection: close\r\n"; static const std::string GET_WITH_PORT = "GET /here.html HTTP/1.0\r\n" "Host: a.valid.host:81\r\n" "Connection: close\r\n"; static const std::string GET_WITH_PARAMETERS = "GET /here.html?a=1&b=2 HTTP/1.0\r\n" "Host: a.valid.host\r\n" "Connection: close\r\n"; using namespace misere; //****************************************************************************** TestHttpRequest::TestHttpRequest() : TestSuite("TestHttpRequest") { } //****************************************************************************** void TestHttpRequest::runTests() { testConstructor(); testCopyConstructor(); testMoveConstructor(); testAssignmentCopy(); testAssignmentMove(); testStreamFromSocket(); testGetRequest(); testGetMethod(); testGetPath(); testGetRequestLine(); testHasArgument(); testGetArgument(); testGetArgumentKeys(); } //****************************************************************************** void TestHttpRequest::testConstructor() { TEST_CASE("testConstructor"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testCopyConstructor() { TEST_CASE("testCopyConstructor"); } //****************************************************************************** void TestHttpRequest::testMoveConstructor() { TEST_CASE("testMoveConstructor"); } //****************************************************************************** void TestHttpRequest::testAssignmentCopy() { TEST_CASE("testAssignmentCopy"); } //****************************************************************************** void TestHttpRequest::testAssignmentMove() { TEST_CASE("testAssignmentMove"); } //****************************************************************************** void TestHttpRequest::testStreamFromSocket() { TEST_CASE("testStreamFromSocket"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testGetRequest() { TEST_CASE("testGetRequest"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testGetMethod() { TEST_CASE("testGetMethod"); MockSocket socketGet(DEFAULT_GET); HttpRequest requestGet(socketGet); requireStringEquals("GET", requestGet.getMethod(), "method is GET"); MockSocket socketPost(DEFAULT_POST); HttpRequest requestPost(socketPost); requireStringEquals("POST", requestPost.getMethod(), "method is POST"); } //****************************************************************************** void TestHttpRequest::testGetPath() { TEST_CASE("testGetPath"); MockSocket socketGet(DEFAULT_GET); HttpRequest requestGet(socketGet); requireStringEquals(GET_PATH, requestGet.getPath(), "path should be GET path"); MockSocket socketPost(DEFAULT_POST); HttpRequest requestPost(socketPost); requireStringEquals(POST_PATH, requestPost.getPath(), "path should be POST path"); } //****************************************************************************** void TestHttpRequest::testGetRequestLine() { TEST_CASE("testGetRequestLine"); } //****************************************************************************** void TestHttpRequest::testHasArgument() { TEST_CASE("testHasArgument"); } //****************************************************************************** void TestHttpRequest::testGetArgument() { TEST_CASE("testGetArgument"); } //****************************************************************************** void TestHttpRequest::testGetArgumentKeys() { TEST_CASE("testGetArgumentKeys"); } //******************************************************************************
// Copyright Paul Dardeau, SwampBits LLC 2014 // BSD License #include "TestHttpRequest.h" #include "HttpRequest.h" #include "MockSocket.h" // Modeled after tests from: // http://subversion.assembla.com/svn/opencats/trunk/cats-0.9.2/lib/simpletest/test/http_test.php static const std::string GET_PATH = "http://a.valid.host/here.html"; static const std::string POST_PATH = "/here.html"; static const std::string DEFAULT_GET = "GET " + GET_PATH + " HTTP/1.0\r\n" + "Host: my-proxy:8080\r\n" + "Connection: close\r\n"; static const std::string DEFAULT_POST = "POST " + POST_PATH + " HTTP/1.0\r\n" + "Host: a.valid.host\r\n" + "Connection: close\r\n"; static const std::string GET_WITH_PORT = "GET /here.html HTTP/1.0\r\n" "Host: a.valid.host:81\r\n" "Connection: close\r\n"; static const std::string GET_WITH_PARAMETERS = "GET /here.html?a=1&b=2 HTTP/1.0\r\n" "Host: a.valid.host\r\n" "Connection: close\r\n"; using namespace misere; //****************************************************************************** TestHttpRequest::TestHttpRequest() : TestSuite("TestHttpRequest") { } //****************************************************************************** void TestHttpRequest::runTests() { testConstructor(); testCopyConstructor(); testMoveConstructor(); testAssignmentCopy(); testAssignmentMove(); testStreamFromSocket(); testGetRequest(); testGetMethod(); testGetPath(); testGetRequestLine(); testHasArgument(); testGetArgument(); testGetArgumentKeys(); } //****************************************************************************** void TestHttpRequest::testConstructor() { TEST_CASE("testConstructor"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testCopyConstructor() { //TEST_CASE("testCopyConstructor"); //TODO: implement testCopyConstructor } //****************************************************************************** void TestHttpRequest::testMoveConstructor() { //TEST_CASE("testMoveConstructor"); //TODO: implement testMoveConstructor } //****************************************************************************** void TestHttpRequest::testAssignmentCopy() { //TEST_CASE("testAssignmentCopy"); //TODO: implement testAssignmentCopy } //****************************************************************************** void TestHttpRequest::testAssignmentMove() { //TEST_CASE("testAssignmentMove"); //TODO: implement testAssignmentMove } //****************************************************************************** void TestHttpRequest::testStreamFromSocket() { TEST_CASE("testStreamFromSocket"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testGetRequest() { TEST_CASE("testGetRequest"); MockSocket socket(DEFAULT_GET); HttpRequest request(socket); } //****************************************************************************** void TestHttpRequest::testGetMethod() { TEST_CASE("testGetMethod"); MockSocket socketGet(DEFAULT_GET); HttpRequest requestGet(socketGet); requireStringEquals("GET", requestGet.getMethod(), "method is GET"); MockSocket socketPost(DEFAULT_POST); HttpRequest requestPost(socketPost); requireStringEquals("POST", requestPost.getMethod(), "method is POST"); } //****************************************************************************** void TestHttpRequest::testGetPath() { TEST_CASE("testGetPath"); MockSocket socketGet(DEFAULT_GET); HttpRequest requestGet(socketGet); requireStringEquals(GET_PATH, requestGet.getPath(), "path should be GET path"); MockSocket socketPost(DEFAULT_POST); HttpRequest requestPost(socketPost); requireStringEquals(POST_PATH, requestPost.getPath(), "path should be POST path"); } //****************************************************************************** void TestHttpRequest::testGetRequestLine() { //TEST_CASE("testGetRequestLine"); //TODO: implement testGetRequestLine } //****************************************************************************** void TestHttpRequest::testHasArgument() { //TEST_CASE("testHasArgument"); //TODO: implement testHasArgument } //****************************************************************************** void TestHttpRequest::testGetArgument() { //TEST_CASE("testGetArgument"); //TODO: implement testGetArgument } //****************************************************************************** void TestHttpRequest::testGetArgumentKeys() { //TEST_CASE("testGetArgumentKeys"); //TODO: implement testGetArgumentKeys } //******************************************************************************
add todo markers for un-implemented tests
add todo markers for un-implemented tests
C++
bsd-3-clause
pauldardeau/misere
30201f32a0d7b07172d6a63b8ab7b66ae5a99307
plugins/ufs/ufs-plugin.cpp
plugins/ufs/ufs-plugin.cpp
#include <functional> #include <sstream> #include <string> #include <sampgdk/core.h> #include <sampgdk/plugin.h> #include "ufs.h" namespace { class UFSPlugin: public ThisPlugin { public: UFSPlugin(): loaded_stuff_(false) {} void LoadStuff() { if (!loaded_stuff_) { ufs::UFS::Instance().LoadPlugins(); ufs::UFS::Instance().LoadScripts(); loaded_stuff_ = true; } } void UnloadStuff() { if (loaded_stuff_) { ufs::UFS::Instance().UnloadScripts(); ufs::UFS::Instance().UnloadPlugins(); loaded_stuff_ = false; } } private: bool loaded_stuff_; }; UFSPlugin ufs_plugin; } // anonymous namespace PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { if (ufs_plugin.Load(ppData) >= 0) { //ufs::UFS::Instance().LoadPlugins(); //ufs::UFS::Instance().LoadScripts(); return true; } return false; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { ufs_plugin.LoadStuff(); ufs::UFS::Instance().ForEachPlugin( std::bind2nd(std::mem_fun(&ufs::Plugin::AmxLoad), amx)); return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { ufs::UFS::Instance().ForEachPlugin( std::bind2nd(std::mem_fun(&ufs::Plugin::AmxUnload), amx)); return AMX_ERR_NONE; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { ufs_plugin.UnloadStuff(); ufs_plugin.Unload(); ufs::UFS::Instance().UnloadScripts(); } PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() { ufs_plugin.ProcessTimers(); ufs::UFS::Instance().ForEachPlugin( std::mem_fun(&ufs::Plugin::ProcessTick)); }
#include <functional> #include <sstream> #include <string> #include <sampgdk/core.h> #include <sampgdk/plugin.h> #include "ufs.h" namespace { bool can_load_stuff = false; class UFSPlugin: public ThisPlugin { public: UFSPlugin(): loaded_stuff_(false) {} void LoadStuff() { if (!loaded_stuff_) { ufs::UFS::Instance().LoadPlugins(); ufs::UFS::Instance().LoadScripts(); loaded_stuff_ = true; } } void UnloadStuff() { if (loaded_stuff_) { ufs::UFS::Instance().UnloadScripts(); ufs::UFS::Instance().UnloadPlugins(); loaded_stuff_ = false; } } private: bool loaded_stuff_; }; UFSPlugin ufs_plugin; } // anonymous namespace PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { return ufs_plugin.Load(ppData) >= 0; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { ufs::UFS::Instance().ForEachPlugin( std::bind2nd(std::mem_fun(&ufs::Plugin::AmxLoad), amx)); can_load_stuff = true; return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { ufs::UFS::Instance().ForEachPlugin( std::bind2nd(std::mem_fun(&ufs::Plugin::AmxUnload), amx)); return AMX_ERR_NONE; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { ufs_plugin.UnloadStuff(); ufs_plugin.Unload(); ufs::UFS::Instance().UnloadScripts(); } PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() { if (can_load_stuff) { ufs_plugin.LoadStuff(); can_load_stuff = false; } ufs_plugin.ProcessTimers(); ufs::UFS::Instance().ForEachPlugin( std::mem_fun(&ufs::Plugin::ProcessTick)); }
Move stuff loading to ProcessTick()
Move stuff loading to ProcessTick() Since according to my findings all "normal" scripts are loaded in just one server tick, we can detect when the last script got loaded.
C++
apache-2.0
Zeex/sampgdk,Zeex/sampgdk,WopsS/sampgdk,WopsS/sampgdk,WopsS/sampgdk,Zeex/sampgdk
5481dd36a4c66f7406337d5ee9fb131b2200fbba
Coloration/main.cxx
Coloration/main.cxx
// Copyright(c) 2016, Kitware SAS // www.kitware.fr // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met : // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // VTK includes #include <vtksys/CommandLineArguments.hxx> #include <vtksys/SystemTools.hxx> #include "vtkDoubleArray.h" #include "vtkNew.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkXMLPolyDataReader.h" #include "vtkXMLPolyDataWriter.h" #include "Helper.h" #include "ReconstructionData.h" #include <iostream> #include <string> #include <numeric> //----------------------------------------------------------------------------- // READ ARGUMENTS //----------------------------------------------------------------------------- std::string g_inputPath = ""; std::string g_outputPath = ""; std::string g_globalKRTDFilePath = ""; std::string g_globalVTIFilePath = ""; bool verbose = false; //----------------------------------------------------------------------------- // FUNCTIONS //----------------------------------------------------------------------------- bool ReadArguments(int argc, char ** argv); void ShowInformation(std::string message); void ShowFilledParameters(); //----------------------------------------------------------------------------- /* Main function */ int main(int argc, char ** argv) { if (!ReadArguments(argc, argv)) { return EXIT_FAILURE; } ShowInformation("** Read input..."); vtkNew<vtkXMLPolyDataReader> reader; reader->SetFileName(g_inputPath.c_str()); reader->Update(); ShowInformation("** Extract vti and krtd file path..."); std::vector<std::string> vtiList = help::ExtractAllFilePath(g_globalVTIFilePath.c_str()); std::vector<std::string> krtdList = help::ExtractAllFilePath(g_globalKRTDFilePath.c_str()); if (krtdList.size() < vtiList.size()) { std::cerr << "Error, no enough krtd file for each vti file" << std::endl; return EXIT_FAILURE; } int nbDepthMap = (int)vtiList.size(); ShowInformation("** Read krtd and vti..."); std::vector<ReconstructionData*> dataList; for (int id = 0; id < nbDepthMap; id++) { std::cout << "\r" << id * 100 / nbDepthMap << " %" << std::flush; ReconstructionData* data = new ReconstructionData(vtiList[id], krtdList[id]); dataList.push_back(data); } std::cout << "\r" << "100 %" << std::flush << std::endl << std::endl; ShowInformation("** Process coloration..."); vtkPolyData* mesh = reader->GetOutput(); vtkPoints* meshPointList = mesh->GetPoints(); vtkIdType nbMeshPoint = meshPointList->GetNumberOfPoints(); //vtkIdType nbMeshPoint = 3; int* depthMapDimensions = dataList[0]->GetDepthMapDimensions(); std::vector<int> pointCount(nbMeshPoint); // Contains rgb values vtkUnsignedCharArray* meanValues = vtkUnsignedCharArray::New(); meanValues->SetNumberOfComponents(3); meanValues->SetNumberOfTuples(nbMeshPoint); meanValues->FillComponent(0, 0); meanValues->FillComponent(1, 0); meanValues->FillComponent(2, 0); meanValues->SetName("meanColoration"); vtkUnsignedCharArray* medianValues = vtkUnsignedCharArray::New(); medianValues->SetNumberOfComponents(3); medianValues->SetNumberOfTuples(nbMeshPoint); medianValues->FillComponent(0, 0); medianValues->FillComponent(1, 0); medianValues->FillComponent(2, 0); medianValues->SetName("medianColoration"); // Store each rgb value for each depth map std::vector<double> list0; std::vector<double> list1; std::vector<double> list2; for (vtkIdType id = 0; id < nbMeshPoint; id++) { std::cout << "\r" << id * 100 / nbMeshPoint << " %" << std::flush; list0.reserve(nbDepthMap); list1.reserve(nbDepthMap); list2.reserve(nbDepthMap); // Get mesh position from id double position[3]; meshPointList->GetPoint(id, position); for (int idData = 0; idData < nbDepthMap; idData++) { ReconstructionData* data = dataList[idData]; // Transform to pixel index int pixelPosition[2]; help::WorldToDepthMap(data->GetMatrixTR(), data->Get4MatrixK(), position, pixelPosition); // Test if pixel is inside depth map if (pixelPosition[0] < 0 || pixelPosition[1] < 0 || pixelPosition[0] >= depthMapDimensions[0] || pixelPosition[1] >= depthMapDimensions[1]) { continue; } double color[3]; data->GetColorValue(pixelPosition, color); list0.push_back(color[0]); list1.push_back(color[1]); list2.push_back(color[2]); } // If we get elements if (list0.size() != 0) { double sum0 = std::accumulate(list0.begin(), list0.end(), 0); double sum1 = std::accumulate(list1.begin(), list1.end(), 0); double sum2 = std::accumulate(list2.begin(), list2.end(), 0); double nbVal = (double)list0.size(); meanValues->SetTuple3(id, sum0 / (double)nbVal, sum1 / (double)nbVal, sum2 / (double)nbVal); double median0, median1, median2; help::ComputeMedian<double>(list0, median0); help::ComputeMedian<double>(list1, median1); help::ComputeMedian<double>(list2, median2); medianValues->SetTuple3(id, median0, median1, median2); } list0.clear(); list1.clear(); list2.clear(); } mesh->GetPointData()->AddArray(meanValues); mesh->GetPointData()->AddArray(medianValues); std::cout << "\r" << "100 %" << std::flush << std::endl << std::endl; ShowInformation("** Write output image"); vtkNew<vtkXMLPolyDataWriter> writer; writer->SetFileName(g_outputPath.c_str()); writer->SetInputData(mesh); writer->Update(); return EXIT_SUCCESS; } //----------------------------------------------------------------------------- /* Read input argument and check if they are valid */ bool ReadArguments(int argc, char ** argv) { bool help = false; vtksys::CommandLineArguments arg; arg.Initialize(argc, argv); typedef vtksys::CommandLineArguments argT; arg.AddArgument("--input", argT::SPACE_ARGUMENT, &g_inputPath, "(required) Path to a .vtp file"); arg.AddArgument("--output", argT::SPACE_ARGUMENT, &g_outputPath, "(required) Path of the output file (.vtp)"); arg.AddArgument("--krtd", argT::SPACE_ARGUMENT, &g_globalKRTDFilePath, "(required) Path to the file which contains all krtd path"); arg.AddArgument("--vti", argT::SPACE_ARGUMENT, &g_globalVTIFilePath, "(required) Path to the file which contains all vti path"); arg.AddBooleanArgument("--verbose", &verbose, "(optional) Use to display debug information"); arg.AddBooleanArgument("--help", &help, "Print help message"); int result = arg.Parse(); if (!result || help) { std::cerr << arg.GetHelp(); return false; } // Check arguments if (g_inputPath == "" || g_outputPath == "" || g_globalKRTDFilePath == "" || g_globalVTIFilePath == "") { std::cerr << "Missing arguments..." << std::endl; std::cerr << arg.GetHelp(); return false; } return true; } //----------------------------------------------------------------------------- /* Show information on console if we are on verbose mode */ void ShowInformation(std::string information) { if (verbose) { std::cout << information << "\n" << std::endl; } } void ShowFilledParameters() { if (!verbose) return; }
// Copyright(c) 2016, Kitware SAS // www.kitware.fr // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met : // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // VTK includes #include <vtksys/CommandLineArguments.hxx> #include <vtksys/SystemTools.hxx> #include "vtkDoubleArray.h" #include "vtkNew.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkXMLPolyDataReader.h" #include "vtkXMLPolyDataWriter.h" #include "Helper.h" #include "ReconstructionData.h" #include <iostream> #include <string> #include <numeric> //----------------------------------------------------------------------------- // READ ARGUMENTS //----------------------------------------------------------------------------- std::string g_inputPath = ""; std::string g_outputPath = ""; std::string g_globalKRTDFilePath = ""; std::string g_globalVTIFilePath = ""; bool verbose = false; //----------------------------------------------------------------------------- // FUNCTIONS //----------------------------------------------------------------------------- bool ReadArguments(int argc, char ** argv); void ShowInformation(std::string message); void ShowFilledParameters(); //----------------------------------------------------------------------------- /* Main function */ int main(int argc, char ** argv) { if (!ReadArguments(argc, argv)) { return EXIT_FAILURE; } ShowInformation("** Read input..."); vtkNew<vtkXMLPolyDataReader> reader; reader->SetFileName(g_inputPath.c_str()); reader->Update(); ShowInformation("** Extract vti and krtd file path..."); std::vector<std::string> vtiList = help::ExtractAllFilePath(g_globalVTIFilePath.c_str()); std::vector<std::string> krtdList = help::ExtractAllFilePath(g_globalKRTDFilePath.c_str()); if (krtdList.size() < vtiList.size()) { std::cerr << "Error, no enough krtd file for each vti file" << std::endl; return EXIT_FAILURE; } int nbDepthMap = (int)vtiList.size(); ShowInformation("** Read krtd and vti..."); std::vector<ReconstructionData*> dataList; for (int id = 0; id < nbDepthMap; id++) { std::cout << "\r" << id * 100 / nbDepthMap << " %" << std::flush; ReconstructionData* data = new ReconstructionData(vtiList[id], krtdList[id]); dataList.push_back(data); } std::cout << "\r" << "100 %" << std::flush << std::endl << std::endl; ShowInformation("** Process coloration..."); vtkPolyData* mesh = reader->GetOutput(); vtkPoints* meshPointList = mesh->GetPoints(); vtkIdType nbMeshPoint = meshPointList->GetNumberOfPoints(); //vtkIdType nbMeshPoint = 3; int* depthMapDimensions = dataList[0]->GetDepthMapDimensions(); std::vector<int> pointCount(nbMeshPoint); // Contains rgb values vtkUnsignedCharArray* meanValues = vtkUnsignedCharArray::New(); meanValues->SetNumberOfComponents(3); meanValues->SetNumberOfTuples(nbMeshPoint); meanValues->FillComponent(0, 0); meanValues->FillComponent(1, 0); meanValues->FillComponent(2, 0); meanValues->SetName("meanColoration"); vtkUnsignedCharArray* medianValues = vtkUnsignedCharArray::New(); medianValues->SetNumberOfComponents(3); medianValues->SetNumberOfTuples(nbMeshPoint); medianValues->FillComponent(0, 0); medianValues->FillComponent(1, 0); medianValues->FillComponent(2, 0); medianValues->SetName("medianColoration"); vtkDoubleArray* projectedDMValue = vtkDoubleArray::New(); projectedDMValue->SetNumberOfComponents(1); projectedDMValue->SetNumberOfTuples(nbMeshPoint); projectedDMValue->FillComponent(0, 0); projectedDMValue->SetName("NbProjectedDepthMap"); // Store each rgb value for each depth map std::vector<double> list0; std::vector<double> list1; std::vector<double> list2; for (vtkIdType id = 0; id < nbMeshPoint; id++) { std::cout << "\r" << id * 100 / nbMeshPoint << " %" << std::flush; list0.reserve(nbDepthMap); list1.reserve(nbDepthMap); list2.reserve(nbDepthMap); // Get mesh position from id double position[3]; meshPointList->GetPoint(id, position); for (int idData = 0; idData < nbDepthMap; idData++) { ReconstructionData* data = dataList[idData]; // Transform to pixel index int pixelPosition[2]; help::WorldToDepthMap(data->GetMatrixTR(), data->Get4MatrixK(), position, pixelPosition); // Test if pixel is inside depth map if (pixelPosition[0] < 0 || pixelPosition[1] < 0 || pixelPosition[0] >= depthMapDimensions[0] || pixelPosition[1] >= depthMapDimensions[1]) { continue; } double color[3]; data->GetColorValue(pixelPosition, color); list0.push_back(color[0]); list1.push_back(color[1]); list2.push_back(color[2]); } // If we get elements if (list0.size() != 0) { double sum0 = std::accumulate(list0.begin(), list0.end(), 0); double sum1 = std::accumulate(list1.begin(), list1.end(), 0); double sum2 = std::accumulate(list2.begin(), list2.end(), 0); double nbVal = (double)list0.size(); meanValues->SetTuple3(id, sum0 / (double)nbVal, sum1 / (double)nbVal, sum2 / (double)nbVal); double median0, median1, median2; help::ComputeMedian<double>(list0, median0); help::ComputeMedian<double>(list1, median1); help::ComputeMedian<double>(list2, median2); medianValues->SetTuple3(id, median0, median1, median2); projectedDMValue->SetTuple1(id, list0.size()); } list0.clear(); list1.clear(); list2.clear(); } mesh->GetPointData()->AddArray(meanValues); mesh->GetPointData()->AddArray(medianValues); mesh->GetPointData()->AddArray(projectedDMValue); std::cout << "\r" << "100 %" << std::flush << std::endl << std::endl; ShowInformation("** Write output image"); vtkNew<vtkXMLPolyDataWriter> writer; writer->SetFileName(g_outputPath.c_str()); writer->SetInputData(mesh); writer->Update(); return EXIT_SUCCESS; } //----------------------------------------------------------------------------- /* Read input argument and check if they are valid */ bool ReadArguments(int argc, char ** argv) { bool help = false; vtksys::CommandLineArguments arg; arg.Initialize(argc, argv); typedef vtksys::CommandLineArguments argT; arg.AddArgument("--input", argT::SPACE_ARGUMENT, &g_inputPath, "(required) Path to a .vtp file"); arg.AddArgument("--output", argT::SPACE_ARGUMENT, &g_outputPath, "(required) Path of the output file (.vtp)"); arg.AddArgument("--krtd", argT::SPACE_ARGUMENT, &g_globalKRTDFilePath, "(required) Path to the file which contains all krtd path"); arg.AddArgument("--vti", argT::SPACE_ARGUMENT, &g_globalVTIFilePath, "(required) Path to the file which contains all vti path"); arg.AddBooleanArgument("--verbose", &verbose, "(optional) Use to display debug information"); arg.AddBooleanArgument("--help", &help, "Print help message"); int result = arg.Parse(); if (!result || help) { std::cerr << arg.GetHelp(); return false; } // Check arguments if (g_inputPath == "" || g_outputPath == "" || g_globalKRTDFilePath == "" || g_globalVTIFilePath == "") { std::cerr << "Missing arguments..." << std::endl; std::cerr << arg.GetHelp(); return false; } return true; } //----------------------------------------------------------------------------- /* Show information on console if we are on verbose mode */ void ShowInformation(std::string information) { if (verbose) { std::cout << information << "\n" << std::endl; } } void ShowFilledParameters() { if (!verbose) return; }
Add new array to store the number of projected depth map for each mesh point
[COLORATION] Add new array to store the number of projected depth map for each mesh point
C++
bsd-3-clause
tcoulange/CudaDepthMapIntegration
ce30542dbaa3e6f5e68b742a34cda993a351e15d
test/attitude.cpp
test/attitude.cpp
#include <cstdio> #include <stdexcept> #include <matrix/math.hpp> #include "test_macros.hpp" using namespace matrix; template class Quaternion<float>; template class Euler<float>; template class Dcm<float>; int main() { double eps = 1e-6; // check data Eulerf euler_check(0.1f, 0.2f, 0.3f); Quatf q_check(0.98334744f, 0.0342708f, 0.10602051f, .14357218f); float dcm_data[] = { 0.93629336f, -0.27509585f, 0.21835066f, 0.28962948f, 0.95642509f, -0.03695701f, -0.19866933f, 0.0978434f, 0.97517033f }; Dcmf dcm_check(dcm_data); // euler ctor TEST(isEqual(euler_check, Vector3f(0.1f, 0.2f, 0.3f))); // euler default ctor Eulerf e; Eulerf e_zero = zeros<float, 3, 1>(); TEST(isEqual(e, e_zero)); TEST(isEqual(e, e)); // euler vector ctor Vector<float, 3> v; v(0) = 0.1f; v(1) = 0.2f; v(2) = 0.3f; Eulerf euler_copy(v); TEST(isEqual(euler_copy, euler_check)); // quaternion ctor Quatf q(1, 2, 3, 4); TEST(fabs(q(0) - 1) < eps); TEST(fabs(q(1) - 2) < eps); TEST(fabs(q(2) - 3) < eps); TEST(fabs(q(3) - 4) < eps); // quat normalization q.normalize(); TEST(isEqual(q, Quatf(0.18257419f, 0.36514837f, 0.54772256f, 0.73029674f))); // quat default ctor q = Quatf(); TEST(isEqual(q, Quatf(1, 0, 0, 0))); // euler to quaternion q = Quatf(euler_check); TEST(isEqual(q, q_check)); // euler to dcm Dcmf dcm(euler_check); TEST(isEqual(dcm, dcm_check)); // quaternion to euler Eulerf e1(q_check); TEST(isEqual(e1, euler_check)); // quaternion to dcm Dcmf dcm1(q_check); TEST(isEqual(dcm1, dcm_check)); // dcm default ctor Dcmf dcm2; SquareMatrix<float, 3> I = eye<float, 3>(); TEST(isEqual(dcm2, I)); // dcm to euler Eulerf e2(dcm_check); TEST(isEqual(e2, euler_check)); // dcm to quaterion Quatf q2(dcm_check); TEST(isEqual(q2, q_check)); // constants double deg2rad = M_PI/180.0; double rad2deg = 180.0/M_PI; // euler dcm round trip check for (int roll=-90; roll<=90; roll+=90) { for (int pitch=-90; pitch<=90; pitch+=90) { for (int yaw=1; yaw<=360; yaw+=90) { // note if theta = pi/2, then roll is set to zero int roll_expected = roll; int yaw_expected = yaw; if (pitch == 90) { roll_expected = 0; yaw_expected = yaw - roll; } else if (pitch == -90) { roll_expected = 0; yaw_expected = yaw + roll; } if (yaw_expected < -180) yaw_expected += 360; if (yaw_expected > 180) yaw_expected -= 360; printf("roll:%d pitch:%d yaw:%d\n", roll, pitch, yaw); Euler<double> euler_expected( deg2rad*double(roll_expected), deg2rad*double(pitch), deg2rad*double(yaw_expected)); Euler<double> euler( deg2rad*double(roll), deg2rad*double(pitch), deg2rad*double(yaw)); Dcm<double> dcm_from_euler(euler); dcm_from_euler.print(); Euler<double> euler_out(dcm_from_euler); TEST(isEqual(rad2deg*euler_expected, rad2deg*euler_out)); Eulerf eulerf_expected( float(deg2rad)*float(roll_expected), float(deg2rad)*float(pitch), float(deg2rad)*float(yaw_expected)); Eulerf eulerf(float(deg2rad)*float(roll), float(deg2rad)*float(pitch), float(deg2rad)*float(yaw)); Dcm<float> dcm_from_eulerf(eulerf); Euler<float> euler_outf(dcm_from_eulerf); TEST(isEqual(float(rad2deg)*eulerf_expected, float(rad2deg)*euler_outf)); } } } // quaterion copy ctors float data_v4[] = {1, 2, 3, 4}; Vector<float, 4> v4(data_v4); Quatf q_from_v(v4); TEST(isEqual(q_from_v, v4)); Matrix<float, 4, 1> m4(data_v4); Quatf q_from_m(m4); TEST(isEqual(q_from_m, m4)); // quaternion derivate Vector<float, 4> q_dot = q.derivative(Vector3f(1, 2, 3)); // quaternion product Quatf q_prod_check( 0.93394439f, 0.0674002f, 0.20851f, 0.28236266f); TEST(isEqual(q_prod_check, q_check*q_check)); q_check *= q_check; TEST(isEqual(q_prod_check, q_check)); // Quaternion scalar multiplication float scalar = 0.5; Quatf q_scalar_mul(1.0f, 2.0f, 3.0f, 4.0f); Quatf q_scalar_mul_check(1.0f * scalar, 2.0f * scalar, 3.0f * scalar, 4.0f * scalar); Quatf q_scalar_mul_res = scalar * q_scalar_mul; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res)); Quatf q_scalar_mul_res2 = q_scalar_mul * scalar; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res2)); Quatf q_scalar_mul_res3(q_scalar_mul); q_scalar_mul_res3 *= scalar; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res3)); // quaternion inverse q = q_check.inversed(); TEST(fabsf(q_check(0) - q(0)) < eps); TEST(fabsf(q_check(1) + q(1)) < eps); TEST(fabsf(q_check(2) + q(2)) < eps); TEST(fabsf(q_check(3) + q(3)) < eps); q = q_check; q.invert(); TEST(fabsf(q_check(0) - q(0)) < eps); TEST(fabsf(q_check(1) + q(1)) < eps); TEST(fabsf(q_check(2) + q(2)) < eps); TEST(fabsf(q_check(3) + q(3)) < eps); // rotate quaternion (nonzero rotation) Quatf qI(1.0f, 0.0f, 0.0f, 0.0f); Vector<float, 3> rot; rot(0) = 1.0f; rot(1) = rot(2) = 0.0f; qI.rotate(rot); Quatf q_true(cosf(1.0f / 2), sinf(1.0f / 2), 0.0f, 0.0f); TEST(fabsf(qI(0) - q_true(0)) < eps); TEST(fabsf(qI(1) - q_true(1)) < eps); TEST(fabsf(qI(2) - q_true(2)) < eps); TEST(fabsf(qI(3) - q_true(3)) < eps); // rotate quaternion (zero rotation) qI = Quatf(1.0f, 0.0f, 0.0f, 0.0f); rot(0) = 0.0f; rot(1) = rot(2) = 0.0f; qI.rotate(rot); q_true = Quatf(cosf(0.0f), sinf(0.0f), 0.0f, 0.0f); TEST(fabsf(qI(0) - q_true(0)) < eps); TEST(fabsf(qI(1) - q_true(1)) < eps); TEST(fabsf(qI(2) - q_true(2)) < eps); TEST(fabsf(qI(3) - q_true(3)) < eps); // get rotation axis from quaternion (nonzero rotation) q = Quatf(cosf(1.0f / 2), 0.0f, sinf(1.0f / 2), 0.0f); rot = q.to_axis_angle(); TEST(fabsf(rot(0)) < eps); TEST(fabsf(rot(1) -1.0f) < eps); TEST(fabsf(rot(2)) < eps); // get rotation axis from quaternion (zero rotation) q = Quatf(1.0f, 0.0f, 0.0f, 0.0f); rot = q.to_axis_angle(); TEST(fabsf(rot(0)) < eps); TEST(fabsf(rot(1)) < eps); TEST(fabsf(rot(2)) < eps); // from axis angle (zero rotation) rot(0) = rot(1) = rot(2) = 0.0f; q.from_axis_angle(rot, 0.0f); q_true = Quatf(1.0f, 0.0f, 0.0f, 0.0f); TEST(fabsf(q(0) - q_true(0)) < eps); TEST(fabsf(q(1) - q_true(1)) < eps); TEST(fabsf(q(2) - q_true(2)) < eps); TEST(fabsf(q(3) - q_true(3)) < eps); }; /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
#include <cstdio> #include <stdexcept> #include <matrix/math.hpp> #include "test_macros.hpp" using namespace matrix; template class Quaternion<float>; template class Euler<float>; template class Dcm<float>; int main() { double eps = 1e-6; // check data Eulerf euler_check(0.1f, 0.2f, 0.3f); Quatf q_check(0.98334744f, 0.0342708f, 0.10602051f, .14357218f); float dcm_data[] = { 0.93629336f, -0.27509585f, 0.21835066f, 0.28962948f, 0.95642509f, -0.03695701f, -0.19866933f, 0.0978434f, 0.97517033f }; Dcmf dcm_check(dcm_data); // euler ctor TEST(isEqual(euler_check, Vector3f(0.1f, 0.2f, 0.3f))); // euler default ctor Eulerf e; Eulerf e_zero = zeros<float, 3, 1>(); TEST(isEqual(e, e_zero)); TEST(isEqual(e, e)); // euler vector ctor Vector<float, 3> v; v(0) = 0.1f; v(1) = 0.2f; v(2) = 0.3f; Eulerf euler_copy(v); TEST(isEqual(euler_copy, euler_check)); // quaternion ctor Quatf q(1, 2, 3, 4); TEST(fabs(q(0) - 1) < eps); TEST(fabs(q(1) - 2) < eps); TEST(fabs(q(2) - 3) < eps); TEST(fabs(q(3) - 4) < eps); // quat normalization q.normalize(); TEST(isEqual(q, Quatf(0.18257419f, 0.36514837f, 0.54772256f, 0.73029674f))); // quat default ctor q = Quatf(); TEST(isEqual(q, Quatf(1, 0, 0, 0))); // euler to quaternion q = Quatf(euler_check); TEST(isEqual(q, q_check)); // euler to dcm Dcmf dcm(euler_check); TEST(isEqual(dcm, dcm_check)); // quaternion to euler Eulerf e1(q_check); TEST(isEqual(e1, euler_check)); // quaternion to dcm Dcmf dcm1(q_check); TEST(isEqual(dcm1, dcm_check)); // dcm default ctor Dcmf dcm2; SquareMatrix<float, 3> I = eye<float, 3>(); TEST(isEqual(dcm2, I)); // dcm to euler Eulerf e2(dcm_check); TEST(isEqual(e2, euler_check)); // dcm to quaterion Quatf q2(dcm_check); TEST(isEqual(q2, q_check)); // constants double deg2rad = M_PI/180.0; double rad2deg = 180.0/M_PI; // euler dcm round trip check for (int roll=-90; roll<=90; roll+=90) { for (int pitch=-90; pitch<=90; pitch+=90) { for (int yaw=-179; yaw<=180; yaw+=90) { // note if theta = pi/2, then roll is set to zero int roll_expected = roll; int yaw_expected = yaw; if (pitch == 90) { roll_expected = 0; yaw_expected = yaw - roll; } else if (pitch == -90) { roll_expected = 0; yaw_expected = yaw + roll; } if (yaw_expected < -180) yaw_expected += 360; if (yaw_expected > 180) yaw_expected -= 360; printf("roll:%d pitch:%d yaw:%d\n", roll, pitch, yaw); Euler<double> euler_expected( deg2rad*double(roll_expected), deg2rad*double(pitch), deg2rad*double(yaw_expected)); Euler<double> euler( deg2rad*double(roll), deg2rad*double(pitch), deg2rad*double(yaw)); Dcm<double> dcm_from_euler(euler); dcm_from_euler.print(); Euler<double> euler_out(dcm_from_euler); TEST(isEqual(rad2deg*euler_expected, rad2deg*euler_out)); Eulerf eulerf_expected( float(deg2rad)*float(roll_expected), float(deg2rad)*float(pitch), float(deg2rad)*float(yaw_expected)); Eulerf eulerf(float(deg2rad)*float(roll), float(deg2rad)*float(pitch), float(deg2rad)*float(yaw)); Dcm<float> dcm_from_eulerf(eulerf); Euler<float> euler_outf(dcm_from_eulerf); TEST(isEqual(float(rad2deg)*eulerf_expected, float(rad2deg)*euler_outf)); } } } // quaterion copy ctors float data_v4[] = {1, 2, 3, 4}; Vector<float, 4> v4(data_v4); Quatf q_from_v(v4); TEST(isEqual(q_from_v, v4)); Matrix<float, 4, 1> m4(data_v4); Quatf q_from_m(m4); TEST(isEqual(q_from_m, m4)); // quaternion derivate Vector<float, 4> q_dot = q.derivative(Vector3f(1, 2, 3)); // quaternion product Quatf q_prod_check( 0.93394439f, 0.0674002f, 0.20851f, 0.28236266f); TEST(isEqual(q_prod_check, q_check*q_check)); q_check *= q_check; TEST(isEqual(q_prod_check, q_check)); // Quaternion scalar multiplication float scalar = 0.5; Quatf q_scalar_mul(1.0f, 2.0f, 3.0f, 4.0f); Quatf q_scalar_mul_check(1.0f * scalar, 2.0f * scalar, 3.0f * scalar, 4.0f * scalar); Quatf q_scalar_mul_res = scalar * q_scalar_mul; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res)); Quatf q_scalar_mul_res2 = q_scalar_mul * scalar; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res2)); Quatf q_scalar_mul_res3(q_scalar_mul); q_scalar_mul_res3 *= scalar; TEST(isEqual(q_scalar_mul_check, q_scalar_mul_res3)); // quaternion inverse q = q_check.inversed(); TEST(fabsf(q_check(0) - q(0)) < eps); TEST(fabsf(q_check(1) + q(1)) < eps); TEST(fabsf(q_check(2) + q(2)) < eps); TEST(fabsf(q_check(3) + q(3)) < eps); q = q_check; q.invert(); TEST(fabsf(q_check(0) - q(0)) < eps); TEST(fabsf(q_check(1) + q(1)) < eps); TEST(fabsf(q_check(2) + q(2)) < eps); TEST(fabsf(q_check(3) + q(3)) < eps); // rotate quaternion (nonzero rotation) Quatf qI(1.0f, 0.0f, 0.0f, 0.0f); Vector<float, 3> rot; rot(0) = 1.0f; rot(1) = rot(2) = 0.0f; qI.rotate(rot); Quatf q_true(cosf(1.0f / 2), sinf(1.0f / 2), 0.0f, 0.0f); TEST(fabsf(qI(0) - q_true(0)) < eps); TEST(fabsf(qI(1) - q_true(1)) < eps); TEST(fabsf(qI(2) - q_true(2)) < eps); TEST(fabsf(qI(3) - q_true(3)) < eps); // rotate quaternion (zero rotation) qI = Quatf(1.0f, 0.0f, 0.0f, 0.0f); rot(0) = 0.0f; rot(1) = rot(2) = 0.0f; qI.rotate(rot); q_true = Quatf(cosf(0.0f), sinf(0.0f), 0.0f, 0.0f); TEST(fabsf(qI(0) - q_true(0)) < eps); TEST(fabsf(qI(1) - q_true(1)) < eps); TEST(fabsf(qI(2) - q_true(2)) < eps); TEST(fabsf(qI(3) - q_true(3)) < eps); // get rotation axis from quaternion (nonzero rotation) q = Quatf(cosf(1.0f / 2), 0.0f, sinf(1.0f / 2), 0.0f); rot = q.to_axis_angle(); TEST(fabsf(rot(0)) < eps); TEST(fabsf(rot(1) -1.0f) < eps); TEST(fabsf(rot(2)) < eps); // get rotation axis from quaternion (zero rotation) q = Quatf(1.0f, 0.0f, 0.0f, 0.0f); rot = q.to_axis_angle(); TEST(fabsf(rot(0)) < eps); TEST(fabsf(rot(1)) < eps); TEST(fabsf(rot(2)) < eps); // from axis angle (zero rotation) rot(0) = rot(1) = rot(2) = 0.0f; q.from_axis_angle(rot, 0.0f); q_true = Quatf(1.0f, 0.0f, 0.0f, 0.0f); TEST(fabsf(q(0) - q_true(0)) < eps); TEST(fabsf(q(1) - q_true(1)) < eps); TEST(fabsf(q(2) - q_true(2)) < eps); TEST(fabsf(q(3) - q_true(3)) < eps); }; /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
Fix output for unit test.
Fix output for unit test.
C++
bsd-3-clause
PX4/Matrix,PX4/Matrix,PX4/Matrix
76777b1d4a2edef94a41704777d6043857931f93
moveit_ros/visualization/rviz_plugin_render_tools/src/robot_state_visualization.cpp
moveit_ros/visualization/rviz_plugin_render_tools/src/robot_state_visualization.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <QApplication> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property) , octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS) , octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR) , visible_(true) , visual_visible_(true) , collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface& descr, bool visual, bool collision) { robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); QApplication::processEvents(); } void RobotStateVisualization::clear() { robot_.clear(); render_shapes_->clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA& default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>& color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>* color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const robot_state::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (std::size_t i = 0; i < attached_bodies.size(); ++i) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_bodies[i]->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Affine3d& ab_t = attached_bodies[i]->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr>& ab_shapes = attached_bodies[i]->getShapes(); for (std::size_t j = 0; j < ab_shapes.size(); ++j) { render_shapes_->renderShape(robot_.getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(robot_.getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } }
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <QApplication> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property) , octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS) , octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR) , visible_(true) , visual_visible_(true) , collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface& descr, bool visual, bool collision) { // clear previously loaded model clear(); robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); QApplication::processEvents(); } void RobotStateVisualization::clear() { render_shapes_->clear(); robot_.clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA& default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>& color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const robot_state::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>* color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const robot_state::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (std::size_t i = 0; i < attached_bodies.size(); ++i) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_bodies[i]->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Affine3d& ab_t = attached_bodies[i]->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr>& ab_shapes = attached_bodies[i]->getShapes(); for (std::size_t j = 0; j < ab_shapes.size(); ++j) { render_shapes_->renderShape(robot_.getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(robot_.getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } }
clear before load to avoid segfault
RobotStateVisualization: clear before load to avoid segfault rviz::Robot deletes its complete SceneNode structure in the `load()` method. However, `RobotStateVisualization::render_shapes_` keeps raw pointers to some of these nodes (the attached objects), so these should be cleared to avoid broken pointers. Additionally the order of clearing was bad: the attached objects should be removed first, and `rviz::Robot` only afterwards to avoid similar problems.
C++
bsd-3-clause
davetcoleman/moveit,davetcoleman/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit
a1db7c7f684646b54fc424336afa08313c0813e9
lib/src/utils.hpp
lib/src/utils.hpp
/* Copyright (C) 2016-2019 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT !LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_UTILS_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_UTILS_HPP #include <baryonyx/core> #include "private.hpp" #include <chrono> #include <functional> #include <utility> #include <climits> #include <cmath> namespace baryonyx { /** * @brief Get a sub-string without any @c std::isspace characters at left. * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ constexpr inline std::string_view left_trim(std::string_view s) noexcept { auto found = s.find_first_not_of(" \t\n\v\f\r"); if (found == std::string::npos) return {}; return s.substr(found, std::string::npos); } /** * @brief Get a sub-string without any @c std::isspace characters at right. * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ constexpr inline std::string_view right_trim(std::string_view s) noexcept { auto found = s.find_last_not_of(" \t\n\v\f\r"); if (found == std::string::npos) return {}; return s.substr(0, found + 1); } /** * @brief Get a sub-string without any @c std::isspace characters at left and * right * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ constexpr inline std::string_view trim(std::string_view s) noexcept { return left_trim(right_trim(s)); } /** * @brief Compute the length of the @c container. * @details Return the @c size provided by the @c C::size() but cast it into a * @c int. This is a specific baryonyx function, we know that number of * variables and constraints are lower than the @c INT_MAX value. * * @code * std::vector<int> v(z); * * for (int i = 0, e = length(v); i != e; ++i) * ... * @endcode * * @param c The container to request to size. * @tparam T The of container value (must provide a @c size() member). */ template<class C> constexpr int length(const C& c) noexcept { return static_cast<int>(c.size()); } /** * @brief Compute the length of the C array. * @details Return the size of the C array but cast it into a @c int. This * is a specific baryonyx function, we know that number of variables and * constraints are lower than the @c int max value (INT_MAX). * * @code * int v[150]; * for (int i = 0, e = length(v); i != e; ++i) * ... * @endcode * * @param v The container to return size. * @tparam T The type of the C array. * @tparam N The size of the C array. */ template<class T, size_t N> constexpr int length(const T (&array)[N]) noexcept { (void)array; return static_cast<int>(N); } /** * @details Reference to @c lo if @c v is less than @c lo, reference to @c * hi if @c hi is less than @c v, otherwise reference to @c v. * * @code * assert(baryonyx::clamp(0.0, 0.0, 1.0) == 0.0); * assert(baryonyx::clamp(1.0, 0.0, 1.0) == 1.0); * assert(baryonyx::clamp(-0.5, 0.0, 1.0) == 0.0); * assert(baryonyx::clamp(1.5, 0.0, 1.0) == 1.0); * assert(baryonyx::clamp(168, -128, +127) == 127); * assert(baryonyx::clamp(168, 0, +255) == 168); * assert(baryonyx::clamp(128, -128, +127) == 127); * assert(baryonyx::clamp(128, 0, +255) == 128); * @endcode * * @param v The value to clamp. * @param lo The low value to compare. * @param hi The high value to compare. * @return value, low or high. */ template<class T> constexpr const T& clamp(const T& v, const T& lo, const T& hi) { return v < lo ? lo : v > hi ? hi : v; } template<typename Xtype, typename Ytype> constexpr Ytype linearize(Xtype p1x, Ytype p1y, Xtype p2x, Ytype p2y, Xtype value) noexcept { bx_expects(p1x - p2x != 0); auto m = static_cast<double>(p1y - p2y) / static_cast<double>(p1x - p2x); auto p = static_cast<double>(p2y) - m * static_cast<double>(p2x); return static_cast<Ytype>(std::ceil(m * static_cast<double>(value) + p)); } template<typename T> inline bool is_essentially_equal(const T v1, const T v2, const T epsilon) { static_assert(std::is_floating_point<T>::value, "is_essentially_equal required a float/double " "as template argument"); return fabs((v1) - (v2)) <= ((fabs(v1) > fabs(v2) ? fabs(v2) : fabs(v1)) * (epsilon)); } /** * @brief Check if the duration between @c begin and @c end is greater than * @c limit in second. * * @details This function checks if @c end - @c begin is greater than @c * limit. * * @code * auto begin = std::chrono::steady_clock::now(); * // computation * auto end = std::chrono::steady_clock::now(); * * if (is_time_limit(10.0, begin, end)) { * std::cout << "computation takes more than 10s.\n"; * } * @endcode * * @param limit Minimal duration in second to test. * @param begin Time point from the begining of a compuation. * @param end Time point of the current compuation. */ inline bool is_time_limit(double limit, std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end) noexcept { using std::chrono::duration; using std::chrono::duration_cast; if (limit <= 0) return false; return duration_cast<duration<double>>(end - begin).count() > limit; } /** * @brief @c is_numeric_castable checks if two integer are castable. * * @details Checks if the @c arg Source integer is castable into @c Target * template. @c Source and @c Target must be integer. The test * includes the limit of @c Target. * * @param arg The integer to test. * @return true if @c arg is castable to @c Target type. * * @code * int v1 = 10; * assert(lp::is_numeric_castable<std::int8_t>(v)); * * int v2 = 278; * assert(!lp::is_numeric_castable<std::int8_t>(v2)); * @endcode */ template<typename Target, typename Source> inline bool is_numeric_castable(Source arg) noexcept { static_assert(std::is_integral<Source>::value, "Integer required."); static_assert(std::is_integral<Target>::value, "Integer required."); using arg_traits = std::numeric_limits<Source>; using result_traits = std::numeric_limits<Target>; if (result_traits::digits == arg_traits::digits && result_traits::is_signed == arg_traits::is_signed) return true; if (result_traits::digits > arg_traits::digits) return result_traits::is_signed || arg >= 0; if (arg_traits::is_signed && arg < static_cast<Source>(result_traits::min())) return false; return arg <= static_cast<Source>(result_traits::max()); } /** * @brief @c numeric_cast cast @c s to @c Target type. * * @details Converts the integer type @c Source @c s into the integer type * @c Target. If the value @c s is !castable to @c Target, @c * numeric_cast throws an exception. * * @param s The integer to cast. * @return The cast integer. * * @code * std::vector<double> v(1024); * long int index = baryonyx::numeric_cast<long int>(v); // No throw. * @endcode */ template<typename Target, typename Source> inline Target numeric_cast(Source s) { if (!is_numeric_castable<Target>(s)) throw numeric_cast_failure(); return static_cast<Target>(s); } /** * @brief A class to compute time spent during object life. * * @code * { * ... * timer t([](double t){std::cout << t << "s."; }); * ... * } // Show time spend since timer object instantiation. * @endcode */ class timer { private: std::chrono::time_point<std::chrono::steady_clock> m_start; std::function<void(double)> m_fct; public: /** * @brief Build timer with output function. * * @param fct Output function called in destructor. */ template<typename Function> timer(Function fct) : m_start(std::chrono::steady_clock::now()) , m_fct(fct) {} double time_elapsed() const { namespace sc = std::chrono; auto diff = std::chrono::steady_clock::now() - m_start; auto dc = sc::duration_cast<sc::duration<double, std::ratio<1>>>(diff); return dc.count(); } ~timer() noexcept { try { if (m_fct) m_fct(time_elapsed()); } catch (...) { } } }; } // namespace baryonyx #endif
/* Copyright (C) 2016-2019 INRA * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT !LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ORG_VLEPROJECT_BARYONYX_SOLVER_UTILS_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_UTILS_HPP #include <baryonyx/core> #include "private.hpp" #include <chrono> #include <functional> #include <utility> #include <climits> #include <cmath> namespace baryonyx { /** * @brief Get a sub-string without any @c std::isspace characters at left. * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ inline std::string_view left_trim(std::string_view s) noexcept { auto found = s.find_first_not_of(" \t\n\v\f\r"); if (found == std::string::npos) return {}; return s.substr(found, std::string::npos); } /** * @brief Get a sub-string without any @c std::isspace characters at right. * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ inline std::string_view right_trim(std::string_view s) noexcept { auto found = s.find_last_not_of(" \t\n\v\f\r"); if (found == std::string::npos) return {}; return s.substr(0, found + 1); } /** * @brief Get a sub-string without any @c std::isspace characters at left and * right * * @param s The string-view to clean up. * * @return An update sub-string or the same string-view. */ inline std::string_view trim(std::string_view s) noexcept { return left_trim(right_trim(s)); } /** * @brief Compute the length of the @c container. * @details Return the @c size provided by the @c C::size() but cast it into a * @c int. This is a specific baryonyx function, we know that number of * variables and constraints are lower than the @c INT_MAX value. * * @code * std::vector<int> v(z); * * for (int i = 0, e = length(v); i != e; ++i) * ... * @endcode * * @param c The container to request to size. * @tparam T The of container value (must provide a @c size() member). */ template<class C> constexpr int length(const C& c) noexcept { return static_cast<int>(c.size()); } /** * @brief Compute the length of the C array. * @details Return the size of the C array but cast it into a @c int. This * is a specific baryonyx function, we know that number of variables and * constraints are lower than the @c int max value (INT_MAX). * * @code * int v[150]; * for (int i = 0, e = length(v); i != e; ++i) * ... * @endcode * * @param v The container to return size. * @tparam T The type of the C array. * @tparam N The size of the C array. */ template<class T, size_t N> constexpr int length(const T (&array)[N]) noexcept { (void)array; return static_cast<int>(N); } /** * @details Reference to @c lo if @c v is less than @c lo, reference to @c * hi if @c hi is less than @c v, otherwise reference to @c v. * * @code * assert(baryonyx::clamp(0.0, 0.0, 1.0) == 0.0); * assert(baryonyx::clamp(1.0, 0.0, 1.0) == 1.0); * assert(baryonyx::clamp(-0.5, 0.0, 1.0) == 0.0); * assert(baryonyx::clamp(1.5, 0.0, 1.0) == 1.0); * assert(baryonyx::clamp(168, -128, +127) == 127); * assert(baryonyx::clamp(168, 0, +255) == 168); * assert(baryonyx::clamp(128, -128, +127) == 127); * assert(baryonyx::clamp(128, 0, +255) == 128); * @endcode * * @param v The value to clamp. * @param lo The low value to compare. * @param hi The high value to compare. * @return value, low or high. */ template<class T> constexpr const T& clamp(const T& v, const T& lo, const T& hi) { return v < lo ? lo : v > hi ? hi : v; } template<typename Xtype, typename Ytype> constexpr Ytype linearize(Xtype p1x, Ytype p1y, Xtype p2x, Ytype p2y, Xtype value) noexcept { bx_expects(p1x - p2x != 0); auto m = static_cast<double>(p1y - p2y) / static_cast<double>(p1x - p2x); auto p = static_cast<double>(p2y) - m * static_cast<double>(p2x); return static_cast<Ytype>(std::ceil(m * static_cast<double>(value) + p)); } template<typename T> inline bool is_essentially_equal(const T v1, const T v2, const T epsilon) { static_assert(std::is_floating_point<T>::value, "is_essentially_equal required a float/double " "as template argument"); return fabs((v1) - (v2)) <= ((fabs(v1) > fabs(v2) ? fabs(v2) : fabs(v1)) * (epsilon)); } /** * @brief Check if the duration between @c begin and @c end is greater than * @c limit in second. * * @details This function checks if @c end - @c begin is greater than @c * limit. * * @code * auto begin = std::chrono::steady_clock::now(); * // computation * auto end = std::chrono::steady_clock::now(); * * if (is_time_limit(10.0, begin, end)) { * std::cout << "computation takes more than 10s.\n"; * } * @endcode * * @param limit Minimal duration in second to test. * @param begin Time point from the begining of a compuation. * @param end Time point of the current compuation. */ inline bool is_time_limit(double limit, std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end) noexcept { using std::chrono::duration; using std::chrono::duration_cast; if (limit <= 0) return false; return duration_cast<duration<double>>(end - begin).count() > limit; } /** * @brief @c is_numeric_castable checks if two integer are castable. * * @details Checks if the @c arg Source integer is castable into @c Target * template. @c Source and @c Target must be integer. The test * includes the limit of @c Target. * * @param arg The integer to test. * @return true if @c arg is castable to @c Target type. * * @code * int v1 = 10; * assert(lp::is_numeric_castable<std::int8_t>(v)); * * int v2 = 278; * assert(!lp::is_numeric_castable<std::int8_t>(v2)); * @endcode */ template<typename Target, typename Source> inline bool is_numeric_castable(Source arg) noexcept { static_assert(std::is_integral<Source>::value, "Integer required."); static_assert(std::is_integral<Target>::value, "Integer required."); using arg_traits = std::numeric_limits<Source>; using result_traits = std::numeric_limits<Target>; if (result_traits::digits == arg_traits::digits && result_traits::is_signed == arg_traits::is_signed) return true; if (result_traits::digits > arg_traits::digits) return result_traits::is_signed || arg >= 0; if (arg_traits::is_signed && arg < static_cast<Source>(result_traits::min())) return false; return arg <= static_cast<Source>(result_traits::max()); } /** * @brief @c numeric_cast cast @c s to @c Target type. * * @details Converts the integer type @c Source @c s into the integer type * @c Target. If the value @c s is !castable to @c Target, @c * numeric_cast throws an exception. * * @param s The integer to cast. * @return The cast integer. * * @code * std::vector<double> v(1024); * long int index = baryonyx::numeric_cast<long int>(v); // No throw. * @endcode */ template<typename Target, typename Source> inline Target numeric_cast(Source s) { if (!is_numeric_castable<Target>(s)) throw numeric_cast_failure(); return static_cast<Target>(s); } /** * @brief A class to compute time spent during object life. * * @code * { * ... * timer t([](double t){std::cout << t << "s."; }); * ... * } // Show time spend since timer object instantiation. * @endcode */ class timer { private: std::chrono::time_point<std::chrono::steady_clock> m_start; std::function<void(double)> m_fct; public: /** * @brief Build timer with output function. * * @param fct Output function called in destructor. */ template<typename Function> timer(Function fct) : m_start(std::chrono::steady_clock::now()) , m_fct(fct) {} double time_elapsed() const { namespace sc = std::chrono; auto diff = std::chrono::steady_clock::now() - m_start; auto dc = sc::duration_cast<sc::duration<double, std::ratio<1>>>(diff); return dc.count(); } ~timer() noexcept { try { if (m_fct) m_fct(time_elapsed()); } catch (...) { } } }; } // namespace baryonyx #endif
remove constexpr trim functions
utils: remove constexpr trim functions On appveyor image, mingw64 for both 32 and 64 bits seems use no constexpr std::string_view find_[first_|last_][not_]_of functions.
C++
mit
quesnel/baryonyx,quesnel/baryonyx,quesnel/baryonyx
b58e1fc57387e57f79545d39fcb964e0bc7fff97
test/diagonal.cpp
test/diagonal.cpp
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2010 Benoit Jacob <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" template<typename MatrixType> void diagonal(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType; Index rows = m.rows(); Index cols = m.cols(); MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols); //check diagonal() VERIFY_IS_APPROX(m1.diagonal(), m1.transpose().diagonal()); m2.diagonal() = 2 * m1.diagonal(); m2.diagonal()[0] *= 3; if (rows>2) { enum { N1 = MatrixType::RowsAtCompileTime>2 ? 2 : 0, N2 = MatrixType::RowsAtCompileTime>1 ? -1 : 0 }; // check sub/super diagonal if(MatrixType::SizeAtCompileTime!=Dynamic) { VERIFY(m1.template diagonal<N1>().RowsAtCompileTime == m1.diagonal(N1).size()); VERIFY(m1.template diagonal<N2>().RowsAtCompileTime == m1.diagonal(N2).size()); } m2.template diagonal<N1>() = 2 * m1.template diagonal<N1>(); VERIFY_IS_APPROX(m2.template diagonal<N1>(), static_cast<Scalar>(2) * m1.diagonal(N1)); m2.template diagonal<N1>()[0] *= 3; VERIFY_IS_APPROX(m2.template diagonal<N1>()[0], static_cast<Scalar>(6) * m1.template diagonal<N1>()[0]); m2.template diagonal<N2>() = 2 * m1.template diagonal<N2>(); m2.template diagonal<N2>()[0] *= 3; VERIFY_IS_APPROX(m2.template diagonal<N2>()[0], static_cast<Scalar>(6) * m1.template diagonal<N2>()[0]); m2.diagonal(N1) = 2 * m1.diagonal(N1); VERIFY_IS_APPROX(m2.diagonal<N1>(), static_cast<Scalar>(2) * m1.diagonal(N1)); m2.diagonal(N1)[0] *= 3; VERIFY_IS_APPROX(m2.diagonal(N1)[0], static_cast<Scalar>(6) * m1.diagonal(N1)[0]); m2.diagonal(N2) = 2 * m1.diagonal(N2); VERIFY_IS_APPROX(m2.diagonal<N2>(), static_cast<Scalar>(2) * m1.diagonal(N2)); m2.diagonal(N2)[0] *= 3; VERIFY_IS_APPROX(m2.diagonal(N2)[0], static_cast<Scalar>(6) * m1.diagonal(N2)[0]); } } void test_diagonal() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( diagonal(Matrix<float, 1, 1>()) ); CALL_SUBTEST_1( diagonal(Matrix<float, 4, 9>()) ); CALL_SUBTEST_1( diagonal(Matrix<float, 7, 3>()) ); CALL_SUBTEST_2( diagonal(Matrix4d()) ); CALL_SUBTEST_2( diagonal(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( diagonal(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( diagonal(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_1( diagonal(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_1( diagonal(Matrix<float,Dynamic,4>(3, 4)) ); } }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2010 Benoit Jacob <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" template<typename MatrixType> void diagonal(const MatrixType& m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<Scalar, 1, MatrixType::ColsAtCompileTime> RowVectorType; Index rows = m.rows(); Index cols = m.cols(); MatrixType m1 = MatrixType::Random(rows, cols), m2 = MatrixType::Random(rows, cols); //check diagonal() VERIFY_IS_APPROX(m1.diagonal(), m1.transpose().diagonal()); m2.diagonal() = 2 * m1.diagonal(); m2.diagonal()[0] *= 3; if (rows>2) { enum { N1 = MatrixType::RowsAtCompileTime>2 ? 2 : 0, N2 = MatrixType::RowsAtCompileTime>1 ? -1 : 0 }; // check sub/super diagonal if(MatrixType::SizeAtCompileTime!=Dynamic) { VERIFY(m1.template diagonal<N1>().RowsAtCompileTime == m1.diagonal(N1).size()); VERIFY(m1.template diagonal<N2>().RowsAtCompileTime == m1.diagonal(N2).size()); } m2.template diagonal<N1>() = 2 * m1.template diagonal<N1>(); VERIFY_IS_APPROX(m2.template diagonal<N1>(), static_cast<Scalar>(2) * m1.diagonal(N1)); m2.template diagonal<N1>()[0] *= 3; VERIFY_IS_APPROX(m2.template diagonal<N1>()[0], static_cast<Scalar>(6) * m1.template diagonal<N1>()[0]); m2.template diagonal<N2>() = 2 * m1.template diagonal<N2>(); m2.template diagonal<N2>()[0] *= 3; VERIFY_IS_APPROX(m2.template diagonal<N2>()[0], static_cast<Scalar>(6) * m1.template diagonal<N2>()[0]); m2.diagonal(N1) = 2 * m1.diagonal(N1); VERIFY_IS_APPROX(m2.template diagonal<N1>(), static_cast<Scalar>(2) * m1.diagonal(N1)); m2.diagonal(N1)[0] *= 3; VERIFY_IS_APPROX(m2.diagonal(N1)[0], static_cast<Scalar>(6) * m1.diagonal(N1)[0]); m2.diagonal(N2) = 2 * m1.diagonal(N2); VERIFY_IS_APPROX(m2.template diagonal<N2>(), static_cast<Scalar>(2) * m1.diagonal(N2)); m2.diagonal(N2)[0] *= 3; VERIFY_IS_APPROX(m2.diagonal(N2)[0], static_cast<Scalar>(6) * m1.diagonal(N2)[0]); } } void test_diagonal() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( diagonal(Matrix<float, 1, 1>()) ); CALL_SUBTEST_1( diagonal(Matrix<float, 4, 9>()) ); CALL_SUBTEST_1( diagonal(Matrix<float, 7, 3>()) ); CALL_SUBTEST_2( diagonal(Matrix4d()) ); CALL_SUBTEST_2( diagonal(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( diagonal(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( diagonal(MatrixXcd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_1( diagonal(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_1( diagonal(Matrix<float,Dynamic,4>(3, 4)) ); } }
Add missing template keyword
Add missing template keyword
C++
bsd-3-clause
madlib/eigen,madlib/eigen,madlib/eigen,madlib/eigen
36390239b686a7a1824d0844f4dcaab6690f38a3
Pi.cpp
Pi.cpp
#include <cstdio> #include <cstdlib> #include <mpi.h> #include <cstring> #include <cassert> const int SHIFT = 32; const unsigned long long BASE = (unsigned long long)1 << SHIFT; int VALID = 1000000; int LEN = VALID / 8 + 2; void add(unsigned long long dest[], unsigned src[]) { for (int i = LEN - 1; i >= 0; i--) if (dest[i] >= BASE - src[i]) { assert(i && "Oh carry overflow!"); dest[i] = (long long)dest[i] + src[i] - BASE; dest[i - 1]++; } else { dest[i] += src[i]; } } void minus(unsigned long long dest[], unsigned src[]) { bool borrow = false; for (int i = LEN - 1; i >= 0; i--) if (dest[i] < src[i] + (borrow? 1: 0)) { assert(i && "Oh borrow overflow!"); dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0); borrow = true; } else { dest[i] = dest[i] - src[i] - (borrow? 1: 0); borrow = false; } } void multiply(unsigned dest[], unsigned num) { unsigned carry = 0; for (int i = LEN - 1; i >= 0; i--) { unsigned long long tmp = (unsigned long long)num * dest[i] + carry; assert((tmp & (BASE - 1)) < BASE && "multiply truncation"); dest[i] = (tmp & (BASE - 1)); carry = tmp >> SHIFT; assert((i || !carry) && "Oh multiply overflow!"); } } void divide(unsigned dest[], unsigned num) { unsigned long long s = 0; for (int i = 0; i < LEN; i++) { s <<= SHIFT; s += dest[i]; if (s >= num) { assert(s / num < BASE && "divide truncation"); dest[i] = s / num; s %= num; } else { dest[i] = 0; } } } void test_multiply_divide() { unsigned *ptr = new unsigned[LEN]; for (int i = 0; i < LEN; i++) ptr[i] = i; unsigned num = 123454321; multiply(ptr, num); divide(ptr, num); for (int i = 0; i < LEN; i++) assert(ptr[i] == (unsigned)i && "multiply or divide error."); delete[] ptr; } void test_add_minus() { unsigned long long *ptr = new unsigned long long[LEN]; unsigned *ptr2 = new unsigned[LEN]; for (int i = 0; i < LEN; i++) { ptr[i] = LEN - i; ptr2[i] = ptr[i] + 1; } ptr[0] = 1, ptr2[0] = 0; minus(ptr, ptr2); assert(ptr[0] == 0 && "ptr[0] minus error."); assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error."); for (int i = 1; i < LEN - 1; i++) assert(ptr[i] == BASE - 2 && "substraction error."); add(ptr, ptr2); assert(ptr[0] == 1 && "ptr[0] add error."); for (int i = 1; i < LEN; i++) assert(ptr[i] == (unsigned)LEN - i && "addition error."); delete[] ptr; delete[] ptr2; } inline void print(unsigned num) { for (int pos = SHIFT - 4; pos >= 0; pos -= 4) printf("%01X", (num >> pos) & 0xF); } void test_print() { unsigned tmp = 180150013; print(tmp); } inline void output(unsigned long long array[]) { printf("%llu.\n", array[0]); int digit = 0; for (int i = 1; digit < VALID; i++) for (int pos = SHIFT - 4; pos >= 0; pos -= 4) { printf("%01X", ((unsigned)array[i] >> pos) & 0xF); if (++digit % 64 == 0) printf("\n"); } printf("\n"); } void shift_right(unsigned sub[], unsigned num) { unsigned uint_bit = 8 * sizeof(unsigned); if (LEN * uint_bit <= num) { memset(sub, 0, sizeof(unsigned) * LEN); return; } if (num >= uint_bit) { memmove(sub + num / uint_bit, sub, sizeof(unsigned) * LEN - num / uint_bit * sizeof(unsigned)); memset(sub, 0, num / uint_bit * sizeof(unsigned)); } unsigned mod = num % uint_bit; unsigned mask = (1 << mod) - 1; for (int i = LEN - 1; i > 0; i--) { sub[i] >>= mod; sub[i] |= (sub[i - 1] & mask) << (uint_bit - mod); } sub[0] >>= mod; } //TODO void test_shift_right() { unsigned *sub = new unsigned[LEN]; for (int i = 0; i < LEN; i++) sub[i] = 0xFFFFFFFF; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 1) + 6); assert(sub[LEN - 1] == 0x3FFFFFF && "shift error."); for (int i = 0; i < LEN - 1; i++) assert(sub[i] == 0 && "shift error."); for (int i = 0; i < LEN; i++) sub[i] = 0xABCDDCBE; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 2) + 4); assert(sub[LEN - 2] == 0xABCDDCB && "shift error."); assert(sub[LEN - 1] == 0xEABCDDCB && "shift error."); for (int i = 0; i < LEN - 2; i++) assert(sub[i] == 0 && "shift error."); delete[] sub; sub = new unsigned[3]; sub[0] = 0; sub[1] = 0x19999999; sub[2] = 0x99999999; shift_right(sub, 8); assert(sub[1] == 0x00199999 && "shift error!"); assert(sub[2] == 0x99999999 && "shift error!"); delete[] sub; } bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; assert((unsigned long long)k * 8 + 6 < BASE && "sub Pi overflow."); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 8 * k + 1); shift_right(sub, 4 * k); add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) return false; memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 2; divide(sub, 8 * k + 4); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 5); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 6); shift_right(sub, 4 * k); minus(Pi, sub); delete[] sub; return true; } void carry(unsigned long long Pi[]) { for (int i = LEN - 1; i >= 0; i--) if (Pi[i] >= BASE) { assert(i && "long long Pi overflow."); Pi[i - 1] += (Pi[i] & ~(BASE - 1)) >> SHIFT; Pi[i] &= (BASE - 1); } } void test_carray() { unsigned long long *ptr = new unsigned long long[LEN]; ptr[0] = 0; ptr[1] = 0xFFFFFFFFFF; carry(ptr); assert(ptr[0] == 0xFF && "carry error."); assert(ptr[1] == 0xFFFFFFFF && "carry error."); delete[] ptr; } int main(int argc, char *argv[]) { /* test_add_minus(); test_multiply_divide(); test_print(); test_shift_right(); test_carray(); */ double elapsed_time; MPI_Init(&argc, &argv); if (argc == 2) { VALID = atoi(argv[1]); LEN = VALID / 8 + 2; } unsigned long long *sub_Pi = new unsigned long long[LEN]; unsigned long long *Pi = new unsigned long long[LEN]; MPI_Barrier(MPI_COMM_WORLD); elapsed_time = -MPI_Wtime(); int size, id; MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &size); for (unsigned k = id; cal_sub_Pi(sub_Pi, k); k += size); MPI_Reduce(sub_Pi, Pi, LEN, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); elapsed_time += MPI_Wtime(); if (!id) { carry(Pi); output(Pi); printf("%.3fs\n", elapsed_time); } delete[] sub_Pi; delete[] Pi; MPI_Finalize(); return 0; }
#include <cstdio> #include <cstdlib> #include <mpi.h> #include <cstring> #include <cassert> const int SHIFT = 32; const unsigned long long BASE = (unsigned long long)1 << SHIFT; int VALID = 1000000; int LEN = VALID / 8 + 2; void add(unsigned long long dest[], unsigned src[]) { for (int i = LEN - 1; i >= 0; i--) if (dest[i] >= BASE - src[i]) { assert(i && "Oh carry overflow!"); dest[i] = (long long)dest[i] + src[i] - BASE; dest[i - 1]++; } else { dest[i] += src[i]; } } void minus(unsigned long long dest[], unsigned src[]) { bool borrow = false; for (int i = LEN - 1; i >= 0; i--) if (dest[i] < src[i] + (borrow? 1: 0)) { assert(i && "Oh borrow overflow!"); dest[i] = (unsigned long long)dest[i] + BASE - src[i] - (borrow? 1: 0); borrow = true; } else { dest[i] = dest[i] - src[i] - (borrow? 1: 0); borrow = false; } } void multiply(unsigned dest[], unsigned num) { unsigned carry = 0; for (int i = LEN - 1; i >= 0; i--) { unsigned long long tmp = (unsigned long long)num * dest[i] + carry; assert((tmp & (BASE - 1)) < BASE && "multiply truncation"); dest[i] = (tmp & (BASE - 1)); carry = tmp >> SHIFT; assert((i || !carry) && "Oh multiply overflow!"); } } void divide(unsigned dest[], unsigned num) { unsigned long long s = 0; for (int i = 0; i < LEN; i++) { s <<= SHIFT; s += dest[i]; if (s >= num) { assert(s / num < BASE && "divide truncation"); dest[i] = s / num; s %= num; } else { dest[i] = 0; } } } void test_multiply_divide() { unsigned *ptr = new unsigned[LEN]; for (int i = 0; i < LEN; i++) ptr[i] = i; unsigned num = 123454321; multiply(ptr, num); divide(ptr, num); for (int i = 0; i < LEN; i++) assert(ptr[i] == (unsigned)i && "multiply or divide error."); delete[] ptr; } void test_add_minus() { unsigned long long *ptr = new unsigned long long[LEN]; unsigned *ptr2 = new unsigned[LEN]; for (int i = 0; i < LEN; i++) { ptr[i] = LEN - i; ptr2[i] = ptr[i] + 1; } ptr[0] = 1, ptr2[0] = 0; minus(ptr, ptr2); assert(ptr[0] == 0 && "ptr[0] minus error."); assert(ptr[LEN - 1] == BASE - 1 && "ptr[LEN - 1] minus error."); for (int i = 1; i < LEN - 1; i++) assert(ptr[i] == BASE - 2 && "substraction error."); add(ptr, ptr2); assert(ptr[0] == 1 && "ptr[0] add error."); for (int i = 1; i < LEN; i++) assert(ptr[i] == (unsigned)LEN - i && "addition error."); delete[] ptr; delete[] ptr2; } inline void print(unsigned num) { for (int pos = SHIFT - 4; pos >= 0; pos -= 4) printf("%01X", (num >> pos) & 0xF); } void test_print() { unsigned tmp = 180150013; print(tmp); } inline void output(unsigned long long array[]) { printf("%llu.\n", array[0]); int digit = 0; for (int i = 1; digit < VALID; i++) for (int pos = SHIFT - 4; pos >= 0; pos -= 4) { printf("%01X", ((unsigned)array[i] >> pos) & 0xF); if (++digit % 64 == 0) printf("\n"); } printf("\n"); } void shift_right(unsigned sub[], unsigned num) { unsigned uint_bit = 8 * sizeof(unsigned); if (LEN * uint_bit <= num) { memset(sub, 0, sizeof(unsigned) * LEN); return; } if (num >= uint_bit) { memmove(sub + num / uint_bit, sub, sizeof(unsigned) * LEN - num / uint_bit * sizeof(unsigned)); memset(sub, 0, num / uint_bit * sizeof(unsigned)); } unsigned mod = num % uint_bit; unsigned mask = (1 << mod) - 1; for (int i = LEN - 1; i > 0; i--) { sub[i] >>= mod; sub[i] |= (sub[i - 1] & mask) << (uint_bit - mod); } sub[0] >>= mod; } //TODO void test_shift_right() { unsigned *sub = new unsigned[LEN]; for (int i = 0; i < LEN; i++) sub[i] = 0xFFFFFFFF; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 1) + 6); assert(sub[LEN - 1] == 0x3FFFFFF && "shift error."); for (int i = 0; i < LEN - 1; i++) assert(sub[i] == 0 && "shift error."); for (int i = 0; i < LEN; i++) sub[i] = 0xABCDDCBE; shift_right(sub, sizeof(unsigned) * 8 * (LEN - 2) + 4); assert(sub[LEN - 2] == 0xABCDDCB && "shift error."); assert(sub[LEN - 1] == 0xEABCDDCB && "shift error."); for (int i = 0; i < LEN - 2; i++) assert(sub[i] == 0 && "shift error."); delete[] sub; sub = new unsigned[3]; sub[0] = 0; sub[1] = 0x19999999; sub[2] = 0x99999999; shift_right(sub, 8); assert(sub[1] == 0x00199999 && "shift error!"); assert(sub[2] == 0x99999999 && "shift error!"); delete[] sub; } bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; assert((unsigned long long)k * 10 + 9 < BASE && "sub Pi overflow."); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 256; divide(sub, 10 * k + 1); shift_right(sub, 10 * k + 6); if (k & 1) minus(Pi, sub); else add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 32; divide(sub, 4 * k + 1); shift_right(sub, 10 * k + 6); if (k & 1) add(Pi, sub); else minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 4 * k + 3); shift_right(sub, 10 * k + 6); if (k & 1) add(Pi, sub); else minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 64; divide(sub, 10 * k + 3); shift_right(sub, 10 * k + 6); if (k & 1) add(Pi, sub); else minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 10 * k + 5); shift_right(sub, 10 * k + 6); if (k & 1) add(Pi, sub); else minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 10 * k + 7); shift_right(sub, 10 * k + 6); if (k & 1) add(Pi, sub); else minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 10 * k + 9); shift_right(sub, 10 * k + 6); if (k & 1) minus(Pi, sub); else add(Pi, sub); delete[] sub; return true; } /* bool cal_sub_Pi(unsigned long long Pi[], unsigned k) { unsigned *sub = new unsigned[LEN]; assert((unsigned long long)k * 8 + 6 < BASE && "sub Pi overflow."); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 4; divide(sub, 8 * k + 1); shift_right(sub, 4 * k); add(Pi, sub); bool zero = true; for (int i = 0; i < LEN; i++) if (sub[i] != 0) zero = false; if (zero) { delete[] sub; return false; } memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 2; divide(sub, 8 * k + 4); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 5); shift_right(sub, 4 * k); minus(Pi, sub); memset(sub, 0, sizeof(unsigned) * LEN); sub[0] = 1; divide(sub, 8 * k + 6); shift_right(sub, 4 * k); minus(Pi, sub); delete[] sub; return true; } */ void carry(unsigned long long Pi[]) { for (int i = LEN - 1; i >= 0; i--) if (Pi[i] >= BASE) { assert(i && "long long Pi overflow."); Pi[i - 1] += (Pi[i] & ~(BASE - 1)) >> SHIFT; Pi[i] &= (BASE - 1); } } void test_carray() { unsigned long long *ptr = new unsigned long long[LEN]; ptr[0] = 0; ptr[1] = 0xFFFFFFFFFF; carry(ptr); assert(ptr[0] == 0xFF && "carry error."); assert(ptr[1] == 0xFFFFFFFF && "carry error."); delete[] ptr; } int main(int argc, char *argv[]) { /* test_add_minus(); test_multiply_divide(); test_print(); test_shift_right(); test_carray(); */ double elapsed_time; MPI_Init(&argc, &argv); if (argc == 2) { VALID = atoi(argv[1]); LEN = VALID / 8 + 2; } unsigned long long *sub_Pi = new unsigned long long[LEN]; unsigned long long *Pi = new unsigned long long[LEN]; MPI_Barrier(MPI_COMM_WORLD); elapsed_time = -MPI_Wtime(); int size, id; MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &size); for (unsigned k = id; cal_sub_Pi(sub_Pi, k); k += size); MPI_Reduce(sub_Pi, Pi, LEN, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); elapsed_time += MPI_Wtime(); if (!id) { carry(Pi); output(Pi); printf("%.3fs\n", elapsed_time); } delete[] sub_Pi; delete[] Pi; MPI_Finalize(); return 0; }
change BBP to BF formula
change BBP to BF formula
C++
mit
Lw-Cui/PI,Lw-Cui/PI,Lw-Cui/PI
c56ff195318c8cb4276ee59d1a9b215431f851b3
Source/Noesis.Javascript/JavascriptContext.cpp
Source/Noesis.Javascript/JavascriptContext.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////// // File: JavascriptContext.cpp // // Copyright 2010 Noesis Innovation Inc. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////// #include <msclr\lock.h> #include <vcclr.h> #include <msclr\marshal.h> #include <signal.h> #include "libplatform/libplatform.h" #include "JavascriptContext.h" #include "SystemInterop.h" #include "JavascriptException.h" #include "JavascriptExternal.h" #include "JavascriptInterop.h" using namespace msclr; using namespace v8::platform; //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Noesis { namespace Javascript { //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma managed(push, off) void GetPathsForInitialisation(char dll_path[MAX_PATH], char natives_blob_bin_path[MAX_PATH], char snapshot_blob_bin_path[MAX_PATH]) { HMODULE hm = NULL; if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)&GetPathsForInitialisation, // any address in the module we're caring about &hm)) { int ret = GetLastError(); fprintf(stderr, "GetModuleHandle error: %d\n", ret); } int nchars = GetModuleFileNameA(hm, dll_path, MAX_PATH); if (nchars == 0 || nchars >= MAX_PATH) { int ret = GetLastError(); fprintf(stderr, "GetModuleFileNameA error: %d\n", ret); } // Because they can conflict with differently-versioned .bin files from Chromiu/CefSharp, // we'll prefer .bin files prefixed by "v8_", if present. strcpy(natives_blob_bin_path, dll_path); strcpy(snapshot_blob_bin_path, dll_path); strcpy(strrchr(natives_blob_bin_path, '\\'), "\\v8_natives_blob.bin"); strcpy(strrchr(snapshot_blob_bin_path, '\\'), "\\v8_snapshot_blob.bin"); FILE *file; if ((file = fopen(natives_blob_bin_path, "r")) != NULL) fclose(file); else strcpy(strrchr(natives_blob_bin_path, '\\'), "\\natives_blob.bin"); if ((file = fopen(snapshot_blob_bin_path, "r")) != NULL) fclose(file); else strcpy(strrchr(snapshot_blob_bin_path, '\\'), "\\snapshot_blob.bin"); } // This code didn't work in managed code, probably due to too-clever smart pointers. void UnmanagedInitialisation() { // Get location of DLL so that v8 can use it to find its .bin files. char dll_path[MAX_PATH], natives_blob_bin_path[MAX_PATH], snapshot_blob_bin_path[MAX_PATH]; GetPathsForInitialisation(dll_path, natives_blob_bin_path, snapshot_blob_bin_path); v8::V8::InitializeICUDefaultLocation(dll_path); v8::V8::InitializeExternalStartupData(natives_blob_bin_path, snapshot_blob_bin_path ); v8::Platform *platform = v8::platform::NewDefaultPlatform().release(); v8::V8::InitializePlatform(platform); v8::V8::Initialize(); } #pragma managed(pop) static JavascriptContext::JavascriptContext() { UnmanagedInitialisation(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Static function so it can be called from unmanaged code. void FatalErrorCallback(const char* location, const char* message) { JavascriptContext::FatalErrorCallbackMember(location, message); raise(SIGABRT); // Exit immediately. } void JavascriptContext::FatalErrorCallbackMember(const char* location, const char* message) { // Let's hope Out of Memory doesn't stop us allocating these strings! // I guess we can generally count on the garbage collector to find // us something, because it didn't have a chance to get involved if v8 // has just run out. System::String ^location_str = gcnew System::String(location); System::String ^message_str = gcnew System::String(message); if (fatalErrorHandler != nullptr) { fatalErrorHandler(location_str, message_str); } else { System::Console::WriteLine(location_str); System::Console::WriteLine(message_str); } } JavascriptContext::JavascriptContext() { // Unfortunately the fatal error handler is not installed early enough to catch // out-of-memory errors while creating new isolates // (see my post Catching V8::FatalProcessOutOfMemory while creating an isolate (SetFatalErrorHandler does not work)). // Also, HeapStatistics are only fetchable per-isolate, so they will not // easily allow us to work out whether we are about to run out (although they // would help us determine how much memory a new isolate used). v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); isolate = v8::Isolate::New(create_params); v8::Locker v8ThreadLock(isolate); v8::Isolate::Scope isolate_scope(isolate); V8::SetFatalErrorHandler(FatalErrorCallback); mExternals = gcnew System::Collections::Generic::Dictionary<System::Object ^, WrappedJavascriptExternal>(); HandleScope scope(isolate); mContext = new Persistent<Context>(isolate, Context::New(isolate)); } //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptContext::~JavascriptContext() { { v8::Locker v8ThreadLock(isolate); v8::Isolate::Scope isolate_scope(isolate); for each (WrappedJavascriptExternal wrapped in mExternals->Values) delete wrapped.Pointer; delete mContext; delete mExternals; } if (isolate != NULL) isolate->Dispose(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetFatalErrorHandler(FatalErrorHandler^ handler) { fatalErrorHandler = handler; } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::TerminateExecution() { isolate->TerminateExecution(); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool JavascriptContext::IsExecutionTerminating() { return isolate->IsExecutionTerminating(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetParameter(System::String^ iName, System::Object^ iObject) { SetParameter(iName, iObject, SetParameterOptions::None); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetParameter(System::String^ iName, System::Object^ iObject, SetParameterOptions options) { pin_ptr<const wchar_t> namePtr = PtrToStringChars(iName); wchar_t* name = (wchar_t*) namePtr; JavascriptScope scope(this); v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); HandleScope handleScope(isolate); Handle<Value> value = JavascriptInterop::ConvertToV8(iObject); if (options != SetParameterOptions::None) { Handle<v8::Object> obj = value.As<v8::Object>(); if (!obj.IsEmpty()) { Local<v8::External> wrap = obj->GetInternalField(0).As<v8::External>(); if (!wrap.IsEmpty()) { JavascriptExternal* external = static_cast<JavascriptExternal*>(wrap->Value()); external->SetOptions(options); } } } Local<Context>::New(isolate, *mContext)->Global()->Set(String::NewFromTwoByte(isolate, (uint16_t*)name), value); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::GetParameter(System::String^ iName) { pin_ptr<const wchar_t> namePtr = PtrToStringChars(iName); wchar_t* name = (wchar_t*) namePtr; JavascriptScope scope(this); v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); HandleScope handleScope(isolate); Local<Value> value = Local<Context>::New(isolate, *mContext)->Global()->Get(String::NewFromTwoByte(isolate, (uint16_t*)name)); return JavascriptInterop::ConvertFromV8(value); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::Run(System::String^ iScript) { pin_ptr<const wchar_t> scriptPtr = PtrToStringChars(iScript); wchar_t* script = (wchar_t*)scriptPtr; JavascriptScope scope(this); //SetStackLimit(); HandleScope handleScope(JavascriptContext::GetCurrentIsolate()); Local<Value> ret; Local<Script> compiledScript = CompileScript(script); { TryCatch tryCatch; ret = (*compiledScript)->Run(); if (ret.IsEmpty()) throw gcnew JavascriptException(tryCatch); } return JavascriptInterop::ConvertFromV8(ret); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::Run(System::String^ iScript, System::String^ iScriptResourceName) { pin_ptr<const wchar_t> scriptPtr = PtrToStringChars(iScript); wchar_t* script = (wchar_t*)scriptPtr; pin_ptr<const wchar_t> scriptResourceNamePtr = PtrToStringChars(iScriptResourceName); wchar_t* scriptResourceName = (wchar_t*)scriptResourceNamePtr; JavascriptScope scope(this); //SetStackLimit(); HandleScope handleScope(JavascriptContext::GetCurrentIsolate()); Local<Value> ret; Local<Script> compiledScript = CompileScript(script, scriptResourceName); { TryCatch tryCatch; ret = (*compiledScript)->Run(); if (ret.IsEmpty()) throw gcnew JavascriptException(tryCatch); } return JavascriptInterop::ConvertFromV8(ret); } //////////////////////////////////////////////////////////////////////////////////////////////////// //void //JavascriptContext::SetStackLimit() //{ // // This stack limit needs to be set for each Run because the // // stack of the caller could be in completely different spots (e.g. // // different threads), or have moved up/down because calls/returns. // v8::ResourceConstraints rc; // // // Copied form v8/test/cctest/test-api.cc // uint32_t size = 500000; // uint32_t* limit = &size - (size / sizeof(size)); // // If the size is very large and the stack is very near the bottom of // // memory then the calculation above may wrap around and give an address // // that is above the (downwards-growing) stack. In that case we return // // a very low address. // if (limit > &size) // limit = reinterpret_cast<uint32_t*>(sizeof(size)); // // int mos = rc.max_old_space_size(); // // rc.set_stack_limit((uint32_t *)(limit)); // rc.set_max_old_space_size(1700); // v8::SetResourceConstraints(isolate, &rc); //} //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptContext^ JavascriptContext::GetCurrent() { return sCurrentContext; } //////////////////////////////////////////////////////////////////////////////////////////////////// v8::Isolate * JavascriptContext::GetCurrentIsolate() { return sCurrentContext->isolate; } //////////////////////////////////////////////////////////////////////////////////////////////////// v8::Locker * JavascriptContext::Enter([System::Runtime::InteropServices::Out] JavascriptContext^% old_context) { v8::Locker *locker = new v8::Locker(isolate); isolate->Enter(); old_context = sCurrentContext; sCurrentContext = this; HandleScope scope(isolate); Local<Context>::New(isolate, *mContext)->Enter(); return locker; } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::Exit(v8::Locker *locker, JavascriptContext^ old_context) { { HandleScope scope(isolate); Local<Context>::New(isolate, *mContext)->Exit(); } sCurrentContext = old_context; isolate->Exit(); delete locker; } //////////////////////////////////////////////////////////////////////////////////////////////////// // Exposed for the benefit of a regression test. void JavascriptContext::Collect() { while(!this->isolate->IdleNotification(1)) {}; } //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptExternal* JavascriptContext::WrapObject(System::Object^ iObject) { WrappedJavascriptExternal external_wrapped; if (mExternals->TryGetValue(iObject, external_wrapped)) { // We've wrapped this guy before. return external_wrapped.Pointer; } else { JavascriptExternal* external = new JavascriptExternal(iObject); mExternals[iObject] = WrappedJavascriptExternal(external); return external; } } //////////////////////////////////////////////////////////////////////////////////////////////////// Handle<ObjectTemplate> JavascriptContext::GetObjectWrapperTemplate() { if (objectWrapperTemplate == NULL) objectWrapperTemplate = new Persistent<ObjectTemplate>(isolate, JavascriptInterop::NewObjectWrapperTemplate()); return Local<ObjectTemplate>::New(isolate, *objectWrapperTemplate); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::String^ JavascriptContext::V8Version::get() { return gcnew System::String(v8::V8::GetVersion()); } //////////////////////////////////////////////////////////////////////////////////////////////////// Local<Script> CompileScript(wchar_t const *source_code, wchar_t const *resource_name) { // convert source v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); Local<String> source = String::NewFromTwoByte(isolate, (uint16_t const *)source_code); // compile { TryCatch tryCatch; Local<Script> script; if (resource_name == NULL) { script = Script::Compile(source); } else { Local<String> resource = String::NewFromTwoByte(isolate, (uint16_t const *)resource_name); script = Script::Compile(source, resource); } if (script.IsEmpty()) throw gcnew JavascriptException(tryCatch); return script; } } } } // namespace Noesis::Javascript ////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////// // File: JavascriptContext.cpp // // Copyright 2010 Noesis Innovation Inc. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////// #include <msclr\lock.h> #include <vcclr.h> #include <msclr\marshal.h> #include <signal.h> #include "libplatform/libplatform.h" #include "JavascriptContext.h" #include "SystemInterop.h" #include "JavascriptException.h" #include "JavascriptExternal.h" #include "JavascriptInterop.h" using namespace msclr; using namespace v8::platform; //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Noesis { namespace Javascript { //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma managed(push, off) void GetPathsForInitialisation(char dll_path[MAX_PATH], char natives_blob_bin_path[MAX_PATH], char snapshot_blob_bin_path[MAX_PATH]) { HMODULE hm = NULL; if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)&GetPathsForInitialisation, // any address in the module we're caring about &hm)) { int ret = GetLastError(); fprintf(stderr, "GetModuleHandle error: %d\n", ret); raise(SIGABRT); // Exit immediately. } int nchars = GetModuleFileNameA(hm, dll_path, MAX_PATH); if (nchars == 0 || nchars >= MAX_PATH) { int ret = GetLastError(); fprintf(stderr, "GetModuleFileNameA error: %d\n", ret); raise(SIGABRT); // Exit immediately. } // Because they can conflict with differently-versioned .bin files from Chromiu/CefSharp, // we'll prefer .bin files prefixed by "v8_", if present. strcpy_s(natives_blob_bin_path, MAX_PATH, dll_path); strcpy_s(snapshot_blob_bin_path, MAX_PATH, dll_path); if (strlen(dll_path) > MAX_PATH - 20) { fprintf(stderr, "Path is too long - don't want to overflow our buffers."); raise(SIGABRT); // Exit immediately. } strcpy_s(strrchr(natives_blob_bin_path, '\\'), 21, "\\v8_natives_blob.bin"); strcpy_s(strrchr(snapshot_blob_bin_path, '\\'), 22, "\\v8_snapshot_blob.bin"); FILE *file; if (fopen_s(&file, natives_blob_bin_path, "r") == 0) fclose(file); else strcpy_s(strrchr(natives_blob_bin_path, '\\'), 18, "\\natives_blob.bin"); if (fopen_s(&file, snapshot_blob_bin_path, "r") == 0) fclose(file); else strcpy_s(strrchr(snapshot_blob_bin_path, '\\'), 19, "\\snapshot_blob.bin"); } // This code didn't work in managed code, probably due to too-clever smart pointers. void UnmanagedInitialisation() { // Get location of DLL so that v8 can use it to find its .bin files. char dll_path[MAX_PATH], natives_blob_bin_path[MAX_PATH], snapshot_blob_bin_path[MAX_PATH]; GetPathsForInitialisation(dll_path, natives_blob_bin_path, snapshot_blob_bin_path); v8::V8::InitializeICUDefaultLocation(dll_path); v8::V8::InitializeExternalStartupData(natives_blob_bin_path, snapshot_blob_bin_path); v8::Platform *platform = v8::platform::NewDefaultPlatform().release(); v8::V8::InitializePlatform(platform); v8::V8::Initialize(); } #pragma managed(pop) static JavascriptContext::JavascriptContext() { UnmanagedInitialisation(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Static function so it can be called from unmanaged code. void FatalErrorCallback(const char* location, const char* message) { JavascriptContext::FatalErrorCallbackMember(location, message); raise(SIGABRT); // Exit immediately. } void JavascriptContext::FatalErrorCallbackMember(const char* location, const char* message) { // Let's hope Out of Memory doesn't stop us allocating these strings! // I guess we can generally count on the garbage collector to find // us something, because it didn't have a chance to get involved if v8 // has just run out. System::String ^location_str = gcnew System::String(location); System::String ^message_str = gcnew System::String(message); if (fatalErrorHandler != nullptr) { fatalErrorHandler(location_str, message_str); } else { System::Console::WriteLine(location_str); System::Console::WriteLine(message_str); } } JavascriptContext::JavascriptContext() { // Unfortunately the fatal error handler is not installed early enough to catch // out-of-memory errors while creating new isolates // (see my post Catching V8::FatalProcessOutOfMemory while creating an isolate (SetFatalErrorHandler does not work)). // Also, HeapStatistics are only fetchable per-isolate, so they will not // easily allow us to work out whether we are about to run out (although they // would help us determine how much memory a new isolate used). v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); isolate = v8::Isolate::New(create_params); v8::Locker v8ThreadLock(isolate); v8::Isolate::Scope isolate_scope(isolate); V8::SetFatalErrorHandler(FatalErrorCallback); mExternals = gcnew System::Collections::Generic::Dictionary<System::Object ^, WrappedJavascriptExternal>(); HandleScope scope(isolate); mContext = new Persistent<Context>(isolate, Context::New(isolate)); } //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptContext::~JavascriptContext() { { v8::Locker v8ThreadLock(isolate); v8::Isolate::Scope isolate_scope(isolate); for each (WrappedJavascriptExternal wrapped in mExternals->Values) delete wrapped.Pointer; delete mContext; delete mExternals; } if (isolate != NULL) isolate->Dispose(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetFatalErrorHandler(FatalErrorHandler^ handler) { fatalErrorHandler = handler; } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::TerminateExecution() { isolate->TerminateExecution(); } //////////////////////////////////////////////////////////////////////////////////////////////////// bool JavascriptContext::IsExecutionTerminating() { return isolate->IsExecutionTerminating(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetParameter(System::String^ iName, System::Object^ iObject) { SetParameter(iName, iObject, SetParameterOptions::None); } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::SetParameter(System::String^ iName, System::Object^ iObject, SetParameterOptions options) { pin_ptr<const wchar_t> namePtr = PtrToStringChars(iName); wchar_t* name = (wchar_t*) namePtr; JavascriptScope scope(this); v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); HandleScope handleScope(isolate); Handle<Value> value = JavascriptInterop::ConvertToV8(iObject); if (options != SetParameterOptions::None) { Handle<v8::Object> obj = value.As<v8::Object>(); if (!obj.IsEmpty()) { Local<v8::External> wrap = obj->GetInternalField(0).As<v8::External>(); if (!wrap.IsEmpty()) { JavascriptExternal* external = static_cast<JavascriptExternal*>(wrap->Value()); external->SetOptions(options); } } } Local<Context>::New(isolate, *mContext)->Global()->Set(String::NewFromTwoByte(isolate, (uint16_t*)name), value); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::GetParameter(System::String^ iName) { pin_ptr<const wchar_t> namePtr = PtrToStringChars(iName); wchar_t* name = (wchar_t*) namePtr; JavascriptScope scope(this); v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); HandleScope handleScope(isolate); Local<Value> value = Local<Context>::New(isolate, *mContext)->Global()->Get(String::NewFromTwoByte(isolate, (uint16_t*)name)); return JavascriptInterop::ConvertFromV8(value); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::Run(System::String^ iScript) { pin_ptr<const wchar_t> scriptPtr = PtrToStringChars(iScript); wchar_t* script = (wchar_t*)scriptPtr; JavascriptScope scope(this); //SetStackLimit(); HandleScope handleScope(JavascriptContext::GetCurrentIsolate()); Local<Value> ret; Local<Script> compiledScript = CompileScript(script); { TryCatch tryCatch; ret = (*compiledScript)->Run(); if (ret.IsEmpty()) throw gcnew JavascriptException(tryCatch); } return JavascriptInterop::ConvertFromV8(ret); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::Object^ JavascriptContext::Run(System::String^ iScript, System::String^ iScriptResourceName) { pin_ptr<const wchar_t> scriptPtr = PtrToStringChars(iScript); wchar_t* script = (wchar_t*)scriptPtr; pin_ptr<const wchar_t> scriptResourceNamePtr = PtrToStringChars(iScriptResourceName); wchar_t* scriptResourceName = (wchar_t*)scriptResourceNamePtr; JavascriptScope scope(this); //SetStackLimit(); HandleScope handleScope(JavascriptContext::GetCurrentIsolate()); Local<Value> ret; Local<Script> compiledScript = CompileScript(script, scriptResourceName); { TryCatch tryCatch; ret = (*compiledScript)->Run(); if (ret.IsEmpty()) throw gcnew JavascriptException(tryCatch); } return JavascriptInterop::ConvertFromV8(ret); } //////////////////////////////////////////////////////////////////////////////////////////////////// //void //JavascriptContext::SetStackLimit() //{ // // This stack limit needs to be set for each Run because the // // stack of the caller could be in completely different spots (e.g. // // different threads), or have moved up/down because calls/returns. // v8::ResourceConstraints rc; // // // Copied form v8/test/cctest/test-api.cc // uint32_t size = 500000; // uint32_t* limit = &size - (size / sizeof(size)); // // If the size is very large and the stack is very near the bottom of // // memory then the calculation above may wrap around and give an address // // that is above the (downwards-growing) stack. In that case we return // // a very low address. // if (limit > &size) // limit = reinterpret_cast<uint32_t*>(sizeof(size)); // // int mos = rc.max_old_space_size(); // // rc.set_stack_limit((uint32_t *)(limit)); // rc.set_max_old_space_size(1700); // v8::SetResourceConstraints(isolate, &rc); //} //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptContext^ JavascriptContext::GetCurrent() { return sCurrentContext; } //////////////////////////////////////////////////////////////////////////////////////////////////// v8::Isolate * JavascriptContext::GetCurrentIsolate() { return sCurrentContext->isolate; } //////////////////////////////////////////////////////////////////////////////////////////////////// v8::Locker * JavascriptContext::Enter([System::Runtime::InteropServices::Out] JavascriptContext^% old_context) { v8::Locker *locker = new v8::Locker(isolate); isolate->Enter(); old_context = sCurrentContext; sCurrentContext = this; HandleScope scope(isolate); Local<Context>::New(isolate, *mContext)->Enter(); return locker; } //////////////////////////////////////////////////////////////////////////////////////////////////// void JavascriptContext::Exit(v8::Locker *locker, JavascriptContext^ old_context) { { HandleScope scope(isolate); Local<Context>::New(isolate, *mContext)->Exit(); } sCurrentContext = old_context; isolate->Exit(); delete locker; } //////////////////////////////////////////////////////////////////////////////////////////////////// // Exposed for the benefit of a regression test. void JavascriptContext::Collect() { while(!this->isolate->IdleNotification(1)) {}; } //////////////////////////////////////////////////////////////////////////////////////////////////// JavascriptExternal* JavascriptContext::WrapObject(System::Object^ iObject) { WrappedJavascriptExternal external_wrapped; if (mExternals->TryGetValue(iObject, external_wrapped)) { // We've wrapped this guy before. return external_wrapped.Pointer; } else { JavascriptExternal* external = new JavascriptExternal(iObject); mExternals[iObject] = WrappedJavascriptExternal(external); return external; } } //////////////////////////////////////////////////////////////////////////////////////////////////// Handle<ObjectTemplate> JavascriptContext::GetObjectWrapperTemplate() { if (objectWrapperTemplate == NULL) objectWrapperTemplate = new Persistent<ObjectTemplate>(isolate, JavascriptInterop::NewObjectWrapperTemplate()); return Local<ObjectTemplate>::New(isolate, *objectWrapperTemplate); } //////////////////////////////////////////////////////////////////////////////////////////////////// System::String^ JavascriptContext::V8Version::get() { return gcnew System::String(v8::V8::GetVersion()); } //////////////////////////////////////////////////////////////////////////////////////////////////// Local<Script> CompileScript(wchar_t const *source_code, wchar_t const *resource_name) { // convert source v8::Isolate *isolate = JavascriptContext::GetCurrentIsolate(); Local<String> source = String::NewFromTwoByte(isolate, (uint16_t const *)source_code); // compile { TryCatch tryCatch; Local<Script> script; if (resource_name == NULL) { script = Script::Compile(source); } else { Local<String> resource = String::NewFromTwoByte(isolate, (uint16_t const *)resource_name); script = Script::Compile(source, resource); } if (script.IsEmpty()) throw gcnew JavascriptException(tryCatch); return script; } } } } // namespace Noesis::Javascript ////////////////////////////////////////////////////////////////////////////////////////////////////
Fix warnings about using old string manipulation functions.
Fix warnings about using old string manipulation functions.
C++
bsd-2-clause
JavascriptNet/Javascript.Net,JavascriptNet/Javascript.Net
5c72d8904cbb3aa32c578470086cc10cdc9b271f
re2jit/threads.cc
re2jit/threads.cc
#include <stdlib.h> #include <string.h> #include "threads.h" static struct rejit_thread_t *rejit_thread_acquire(struct rejit_threadset_t *r) { struct rejit_thread_t *t; if (r->free) { t = r->free; r->free = t->next; return t; } t = (struct rejit_thread_t *) malloc(sizeof(struct rejit_thread_t) + sizeof(int) * r->groups); if (t == NULL) { return NULL; } rejit_list_init(&t->category); rejit_list_init(t); return t; } static void rejit_thread_release(struct rejit_threadset_t *r, struct rejit_thread_t *t) { t->_prev_before_release = t->prev; rejit_list_remove(t); rejit_list_remove(&t->category); t->next = r->free; r->free = t; } // Restore the running thread from the free chain. (It was freed by `thread_dispatch`.) // It it has already been reclaimed, spawn a copy instead. static struct rejit_thread_t *rejit_thread_reclaim(struct rejit_threadset_t *r) { struct rejit_thread_t *t = rejit_thread_acquire(r); if (t == NULL) { return NULL; } if (t == r->running) { rejit_list_append(t->_prev_before_release, t); } else { // `r->running` has already been reclaimed. memcpy(t->groups, r->running->groups, sizeof(int) * r->groups); rejit_list_append(r->running, t); } return t; } // Spawn a copy of the initial thread, pointing at the regexp's entry point. static struct rejit_thread_t *rejit_thread_entry(struct rejit_threadset_t *r) { struct rejit_thread_t *t = rejit_thread_acquire(r); if (t == NULL) { return NULL; } memset(t->groups, 255, sizeof(int) * r->groups); t->entry = r->entry; t->groups[0] = r->offset; rejit_list_append(r->all_threads.last, t); rejit_list_append(r->queues[r->active_queue].last, &t->category); return t; } int rejit_thread_init(struct rejit_threadset_t *r) { rejit_list_init(&r->all_threads); r->visited = (uint8_t *) calloc(sizeof(uint8_t), (r->states + 7) / 8); if (r->visited == NULL) { return 0; } size_t i; for (i = 0; i <= RE2JIT_THREAD_LOOKAHEAD; i++) { rejit_list_init(&r->queues[i]); } r->empty = RE2JIT_EMPTY_BEGIN_LINE | RE2JIT_EMPTY_BEGIN_TEXT; r->offset = 0; r->active_queue = 0; r->free = NULL; r->running = NULL; if (!r->length) { r->empty |= RE2JIT_EMPTY_END_LINE | RE2JIT_EMPTY_END_TEXT; } if (rejit_thread_entry(r) == NULL) { free(r->visited); r->visited = NULL; return 0; } return 1; } void rejit_thread_free(struct rejit_threadset_t *r) { struct rejit_thread_t *a, *b; #define FREE_LIST(init, end) do { \ for (a = init; a != end; ) { \ b = a; \ a = a->next; \ free(b); \ } \ } while (0) FREE_LIST(r->free, NULL); FREE_LIST(r->all_threads.first, rejit_list_end(&r->all_threads)); free(r->visited); r->visited = NULL; #undef FREE_LIST } int rejit_thread_dispatch(struct rejit_threadset_t *r) { size_t queue = r->active_queue; while (1) { struct rejit_thread_t *t = r->queues[queue].first; while (t != rejit_list_end(&r->queues[queue])) { r->running = RE2JIT_DEREF_THREAD(t); rejit_thread_release(r, RE2JIT_DEREF_THREAD(t)); #if RE2JIT_VM return 1; #else RE2JIT_DEREF_THREAD(t)->entry(r); #endif t = r->queues[queue].first; } // this bit vector is shared across all threads on a single queue. // whichever thread first enters a state gets to own that state. memset(r->visited, 0, (r->states + 7) / 8); r->active_queue = queue = (queue + 1) % (RE2JIT_THREAD_LOOKAHEAD + 1); if (!r->length) { if (r->queues[queue].first != rejit_list_end(&r->queues[queue])) { // Allow remaining greedy threads to fail. continue; } return 0; } r->offset++; r->empty = 0; if (*r->input++ == '\n') { r->empty |= RE2JIT_EMPTY_BEGIN_LINE; } if (! --(r->length)) { r->empty |= RE2JIT_EMPTY_END_LINE | RE2JIT_EMPTY_END_TEXT; } else if (*r->input == '\n') { r->empty |= RE2JIT_EMPTY_END_LINE; } // Word boundaries not supported because UTF-8. if (!(r->flags & RE2JIT_ANCHOR_START)) { if (rejit_thread_entry(r) == NULL) { // XOO < *ac was completely screwed out of memory // and nothing can fix that!!* } } } } int rejit_thread_match(struct rejit_threadset_t *r) { if ((r->flags & RE2JIT_ANCHOR_END) && r->length) { // No, it did not. Not EOF yet. return 0; } struct rejit_thread_t *t = rejit_thread_reclaim(r); t->groups[1] = r->offset; while (t->next != rejit_list_end(&r->all_threads)) { // Can safely fail all less important threads. If they fail, this one // has matched, so whatever. If they match, this one contains better results. rejit_thread_release(r, t->next); } // Remove this thread from the queue, but leave it in the list of all threads. rejit_list_remove(&t->category); return 0; } int rejit_thread_wait(struct rejit_threadset_t *r, rejit_entry_t entry, size_t shift) { struct rejit_thread_t *t = rejit_thread_reclaim(r); if (t == NULL) { // :33 < oh shit return 0; } t->entry = entry; size_t queue = (r->active_queue + shift) % (RE2JIT_THREAD_LOOKAHEAD + 1); rejit_list_append(r->queues[queue].last, &t->category); return 0; } int rejit_thread_result(struct rejit_threadset_t *r, int **groups) { if (r->all_threads.first == rejit_list_end(&r->all_threads)) { return 0; } *groups = r->all_threads.first->groups; return 1; }
#include <stdlib.h> #include <string.h> #include "threads.h" static struct rejit_thread_t *rejit_thread_acquire(struct rejit_threadset_t *r) { struct rejit_thread_t *t; if (r->free) { t = r->free; r->free = t->next; return t; } t = (struct rejit_thread_t *) malloc(sizeof(struct rejit_thread_t) + sizeof(int) * r->groups); if (t == NULL) { return NULL; } rejit_list_init(&t->category); rejit_list_init(t); return t; } static void rejit_thread_release(struct rejit_threadset_t *r, struct rejit_thread_t *t) { t->_prev_before_release = t->prev; rejit_list_remove(t); rejit_list_remove(&t->category); t->next = r->free; r->free = t; } // Restore the running thread from the free chain. (It was freed by `thread_dispatch`.) // It it has already been reclaimed, spawn a copy instead. static struct rejit_thread_t *rejit_thread_reclaim(struct rejit_threadset_t *r) { struct rejit_thread_t *t = rejit_thread_acquire(r); if (t == NULL) { return NULL; } if (t == r->running) { rejit_list_append(t->_prev_before_release, t); } else { // `r->running` has already been reclaimed. memcpy(t->groups, r->running->groups, sizeof(int) * r->groups); rejit_list_append(r->running, t); } return t; } // Spawn a copy of the initial thread, pointing at the regexp's entry point. static struct rejit_thread_t *rejit_thread_entry(struct rejit_threadset_t *r) { struct rejit_thread_t *t = rejit_thread_acquire(r); if (t == NULL) { return NULL; } memset(t->groups, 255, sizeof(int) * r->groups); t->entry = r->entry; t->groups[0] = r->offset; rejit_list_append(r->all_threads.last, t); rejit_list_append(r->queues[r->active_queue].last, &t->category); return t; } int rejit_thread_init(struct rejit_threadset_t *r) { rejit_list_init(&r->all_threads); r->visited = (uint8_t *) calloc(sizeof(uint8_t), (r->states + 7) / 8); if (r->visited == NULL) { return 0; } size_t i; for (i = 0; i <= RE2JIT_THREAD_LOOKAHEAD; i++) { rejit_list_init(&r->queues[i]); } r->empty = RE2JIT_EMPTY_BEGIN_LINE | RE2JIT_EMPTY_BEGIN_TEXT; r->offset = 0; r->active_queue = 0; r->free = NULL; r->running = NULL; if (!r->length) { r->empty |= RE2JIT_EMPTY_END_LINE | RE2JIT_EMPTY_END_TEXT; } if (rejit_thread_entry(r) == NULL) { free(r->visited); r->visited = NULL; return 0; } return 1; } void rejit_thread_free(struct rejit_threadset_t *r) { struct rejit_thread_t *a, *b; #define FREE_LIST(init, end) do { \ for (a = init; a != end; ) { \ b = a; \ a = a->next; \ free(b); \ } \ } while (0) FREE_LIST(r->free, NULL); FREE_LIST(r->all_threads.first, rejit_list_end(&r->all_threads)); free(r->visited); r->visited = NULL; #undef FREE_LIST } int rejit_thread_dispatch(struct rejit_threadset_t *r) { size_t queue = r->active_queue; while (1) { struct rejit_thread_t *t = r->queues[queue].first; while (t != rejit_list_end(&r->queues[queue])) { r->running = RE2JIT_DEREF_THREAD(t); rejit_thread_release(r, RE2JIT_DEREF_THREAD(t)); #if RE2JIT_VM return 1; #else RE2JIT_DEREF_THREAD(t)->entry(r); #endif t = r->queues[queue].first; } // this bit vector is shared across all threads on a single queue. // whichever thread first enters a state gets to own that state. memset(r->visited, 0, (r->states + 7) / 8); r->active_queue = queue = (queue + 1) % (RE2JIT_THREAD_LOOKAHEAD + 1); if (!r->length) { if (r->queues[queue].first != rejit_list_end(&r->queues[queue])) { // Allow remaining greedy threads to fail. continue; } return 0; } r->offset++; r->empty = 0; if (*r->input++ == '\n') { r->empty |= RE2JIT_EMPTY_BEGIN_LINE; } if (! --(r->length)) { r->empty |= RE2JIT_EMPTY_END_LINE | RE2JIT_EMPTY_END_TEXT; } else if (*r->input == '\n') { r->empty |= RE2JIT_EMPTY_END_LINE; } // Word boundaries not supported because UTF-8. if (!(r->flags & RE2JIT_ANCHOR_START)) { if (rejit_thread_entry(r) == NULL) { // XOO < *ac was completely screwed out of memory // and nothing can fix that!!* } } } } int rejit_thread_match(struct rejit_threadset_t *r) { if ((r->flags & RE2JIT_ANCHOR_END) && r->length) { // No, it did not. Not EOF yet. return 0; } struct rejit_thread_t *t = rejit_thread_reclaim(r); t->groups[1] = r->offset; while (t->next != rejit_list_end(&r->all_threads)) { // Can safely fail all less important threads. If they fail, this one // has matched, so whatever. If they match, this one contains better results. rejit_thread_release(r, t->next); } // Remove this thread from the queue, but leave it in the list of all threads. rejit_list_remove(&t->category); return 1; } int rejit_thread_wait(struct rejit_threadset_t *r, rejit_entry_t entry, size_t shift) { struct rejit_thread_t *t = rejit_thread_reclaim(r); if (t == NULL) { // :33 < oh shit return 0; } t->entry = entry; size_t queue = (r->active_queue + shift) % (RE2JIT_THREAD_LOOKAHEAD + 1); rejit_list_append(r->queues[queue].last, &t->category); return 0; } int rejit_thread_result(struct rejit_threadset_t *r, int **groups) { if (r->all_threads.first == rejit_list_end(&r->all_threads)) { return 0; } *groups = r->all_threads.first->groups; return 1; }
Fix a typo.
Fix a typo. `thread_match` should return *1* if everything's OK.
C++
mit
pyos/re2jit,pyos/re2jit,pyos/re2jit
9636a3399376e98b89c1e8fa9beff52904db8c93
redis/commands.cc
redis/commands.cc
/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "redis/commands.hh" #include "seastar/core/shared_ptr.hh" #include "redis/request.hh" #include "redis/reply.hh" #include "types.hh" #include "service_permit.hh" #include "service/client_state.hh" #include "redis/options.hh" #include "redis/query_utils.hh" #include "redis/mutation_utils.hh" #include "redis/lolwut.hh" namespace redis { namespace commands { shared_ptr<abstract_command> get::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<get> (std::move(req._command), std::move(req._args[0])); } future<redis_message> get::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { return redis_message::make_strings_result(std::move(result->result())); } // return nil string if key does not exist return redis_message::nil(); }); } exists::exists(bytes&& name, std::vector<bytes>&& keys) : abstract_command(std::move(name)) , _keys(std::move(keys)) {} shared_ptr<abstract_command> exists::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() < 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<exists>(std::move(req._command), std::move(req._args)); } future<redis_message> exists::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return seastar::do_for_each(_keys, [&proxy, &options, &permit, this] (bytes key) { return redis::read_strings(proxy, options, key, permit).then([this] (lw_shared_ptr<strings_result> result) { if (result->has_result()) { _count++; } }); }).then([this] () { return redis_message::number(_count); }); } shared_ptr<abstract_command> ttl::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<ttl> (std::move(req._command), std::move(req._args[0])); } future<redis_message> ttl::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { if (result->has_ttl()) { return redis_message::number(result->ttl().count()); }else{ return redis_message::number(-1); } } return redis_message::number(-2); }); } shared_ptr<abstract_command> strlen::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<strlen> (std::move(req._command), std::move(req._args[0])); } future<redis_message> strlen::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { return redis_message::number(result->result().length()); } // return 0 string if key does not exist return redis_message::zero(); }); } shared_ptr<abstract_command> set::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() == 2) { return seastar::make_shared<set> (std::move(req._command), std::move(req._args[0]), std::move(req._args[1])); } else if (req.arguments_size() == 4) { bytes opt; opt.resize(req._args[2].size()); std::transform(req._args[2].begin(), req._args[2].end(), opt.begin(), ::tolower); if (opt == "ex") { long ttl; try { ttl = std::stol(std::string(reinterpret_cast<const char*>(req._args[3].data()), req._args[3].size())); } catch (...) { throw invalid_arguments_exception(req._command); } return seastar::make_shared<set> (std::move(req._command), std::move(req._args[0]), std::move(req._args[1]), ttl); } } throw invalid_arguments_exception(req._command); } future<redis_message> set::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::write_strings(proxy, options, std::move(_key), std::move(_data), _ttl, permit).then([] { return redis_message::ok(); }); } shared_ptr<abstract_command> setex::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 3) { throw wrong_arguments_exception(3, req.arguments_size(), req._command); } long ttl; try { ttl = std::stol(std::string(reinterpret_cast<const char*>(req._args[1].data()), req._args[1].size())); } catch (...) { throw invalid_arguments_exception(req._command); } return seastar::make_shared<setex> (std::move(req._command), std::move(req._args[0]), std::move(req._args[2]), ttl); } shared_ptr<abstract_command> del::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() == 0) { throw wrong_number_of_arguments_exception(req._command); } return seastar::make_shared<del> (std::move(req._command), std::move(req._args)); } future<redis_message> del::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { //FIXME: We should return the count of the actually deleted keys. auto size = _keys.size(); return redis::delete_objects(proxy, options, std::move(_keys), permit).then([size] { return redis_message::number(size); }); } shared_ptr<abstract_command> select::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } long index = -1; try { index = std::stol(std::string(reinterpret_cast<const char*>(req._args[0].data()), req._args[0].size())); } catch (...) { throw invalid_db_index_exception(); } return seastar::make_shared<select> (std::move(req._command), index); } future<redis_message> select::execute(service::storage_proxy&, redis::redis_options& options, service_permit) { if (_index < 0 || static_cast<size_t>(_index) >= options.get_total_redis_db_count()) { throw invalid_db_index_exception(); } options.set_keyspace_name(sprint("REDIS_%zu", static_cast<size_t>(_index))); return redis_message::ok(); } shared_ptr<abstract_command> unknown::prepare(service::storage_proxy& proxy, request&& req) { return seastar::make_shared<unknown> (std::move(req._command)); } future<redis_message> unknown::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::unknown(_name); } shared_ptr<abstract_command> ping::prepare(service::storage_proxy& proxy, request&& req) { return seastar::make_shared<ping> (std::move(req._command)); } future<redis_message> ping::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::pong(); } shared_ptr<abstract_command> echo::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<echo> (std::move(req._command), std::move(req._args[0])); } future<redis_message> echo::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::make_strings_result(std::move(_str)); } shared_ptr<abstract_command> lolwut::prepare(service::storage_proxy& proxy, request&& req) { int cols = 66; int squares_per_row = 8; int squares_per_col = 12; try { if (req.arguments_size() >= 1) { cols = std::stoi(std::string(reinterpret_cast<const char*>(req._args[0].data()), req._args[0].size())); cols = std::clamp(cols, 1, 1000); } if (req.arguments_size() >= 2) { squares_per_row = std::stoi(std::string(reinterpret_cast<const char*>(req._args[1].data()), req._args[1].size())); squares_per_row = std::clamp(squares_per_row, 1, 200); } if (req.arguments_size() >= 3) { squares_per_col = std::stoi(std::string(reinterpret_cast<const char*>(req._args[2].data()), req._args[2].size())); squares_per_col = std::clamp(squares_per_col, 1, 200); } } catch (...) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<lolwut> (std::move(req._command), cols, squares_per_row, squares_per_col); } future<redis_message> lolwut::execute(service::storage_proxy&, redis::redis_options& options, service_permit) { return redis::lolwut5(_cols, _squares_per_row, _squares_per_col).then([] (auto result) { return redis_message::make_strings_result(std::move(result)); }); } } }
/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "redis/commands.hh" #include "seastar/core/shared_ptr.hh" #include "redis/request.hh" #include "redis/reply.hh" #include "types.hh" #include "service_permit.hh" #include "service/client_state.hh" #include "redis/options.hh" #include "redis/query_utils.hh" #include "redis/mutation_utils.hh" #include "redis/lolwut.hh" namespace redis { namespace commands { shared_ptr<abstract_command> get::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<get> (std::move(req._command), std::move(req._args[0])); } future<redis_message> get::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { return redis_message::make_strings_result(std::move(result->result())); } // return nil string if key does not exist return redis_message::nil(); }); } exists::exists(bytes&& name, std::vector<bytes>&& keys) : abstract_command(std::move(name)) , _keys(std::move(keys)) {} shared_ptr<abstract_command> exists::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() < 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<exists>(std::move(req._command), std::move(req._args)); } future<redis_message> exists::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return seastar::do_for_each(_keys, [&proxy, &options, &permit, this] (bytes& key) { return redis::read_strings(proxy, options, key, permit).then([this] (lw_shared_ptr<strings_result> result) { if (result->has_result()) { _count++; } }); }).then([this] () { return redis_message::number(_count); }); } shared_ptr<abstract_command> ttl::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<ttl> (std::move(req._command), std::move(req._args[0])); } future<redis_message> ttl::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { if (result->has_ttl()) { return redis_message::number(result->ttl().count()); }else{ return redis_message::number(-1); } } return redis_message::number(-2); }); } shared_ptr<abstract_command> strlen::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<strlen> (std::move(req._command), std::move(req._args[0])); } future<redis_message> strlen::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::read_strings(proxy, options, _key, permit).then([] (auto result) { if (result->has_result()) { return redis_message::number(result->result().length()); } // return 0 string if key does not exist return redis_message::zero(); }); } shared_ptr<abstract_command> set::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() == 2) { return seastar::make_shared<set> (std::move(req._command), std::move(req._args[0]), std::move(req._args[1])); } else if (req.arguments_size() == 4) { bytes opt; opt.resize(req._args[2].size()); std::transform(req._args[2].begin(), req._args[2].end(), opt.begin(), ::tolower); if (opt == "ex") { long ttl; try { ttl = std::stol(std::string(reinterpret_cast<const char*>(req._args[3].data()), req._args[3].size())); } catch (...) { throw invalid_arguments_exception(req._command); } return seastar::make_shared<set> (std::move(req._command), std::move(req._args[0]), std::move(req._args[1]), ttl); } } throw invalid_arguments_exception(req._command); } future<redis_message> set::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { return redis::write_strings(proxy, options, std::move(_key), std::move(_data), _ttl, permit).then([] { return redis_message::ok(); }); } shared_ptr<abstract_command> setex::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 3) { throw wrong_arguments_exception(3, req.arguments_size(), req._command); } long ttl; try { ttl = std::stol(std::string(reinterpret_cast<const char*>(req._args[1].data()), req._args[1].size())); } catch (...) { throw invalid_arguments_exception(req._command); } return seastar::make_shared<setex> (std::move(req._command), std::move(req._args[0]), std::move(req._args[2]), ttl); } shared_ptr<abstract_command> del::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() == 0) { throw wrong_number_of_arguments_exception(req._command); } return seastar::make_shared<del> (std::move(req._command), std::move(req._args)); } future<redis_message> del::execute(service::storage_proxy& proxy, redis::redis_options& options, service_permit permit) { //FIXME: We should return the count of the actually deleted keys. auto size = _keys.size(); return redis::delete_objects(proxy, options, std::move(_keys), permit).then([size] { return redis_message::number(size); }); } shared_ptr<abstract_command> select::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } long index = -1; try { index = std::stol(std::string(reinterpret_cast<const char*>(req._args[0].data()), req._args[0].size())); } catch (...) { throw invalid_db_index_exception(); } return seastar::make_shared<select> (std::move(req._command), index); } future<redis_message> select::execute(service::storage_proxy&, redis::redis_options& options, service_permit) { if (_index < 0 || static_cast<size_t>(_index) >= options.get_total_redis_db_count()) { throw invalid_db_index_exception(); } options.set_keyspace_name(sprint("REDIS_%zu", static_cast<size_t>(_index))); return redis_message::ok(); } shared_ptr<abstract_command> unknown::prepare(service::storage_proxy& proxy, request&& req) { return seastar::make_shared<unknown> (std::move(req._command)); } future<redis_message> unknown::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::unknown(_name); } shared_ptr<abstract_command> ping::prepare(service::storage_proxy& proxy, request&& req) { return seastar::make_shared<ping> (std::move(req._command)); } future<redis_message> ping::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::pong(); } shared_ptr<abstract_command> echo::prepare(service::storage_proxy& proxy, request&& req) { if (req.arguments_size() != 1) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<echo> (std::move(req._command), std::move(req._args[0])); } future<redis_message> echo::execute(service::storage_proxy&, redis::redis_options&, service_permit) { return redis_message::make_strings_result(std::move(_str)); } shared_ptr<abstract_command> lolwut::prepare(service::storage_proxy& proxy, request&& req) { int cols = 66; int squares_per_row = 8; int squares_per_col = 12; try { if (req.arguments_size() >= 1) { cols = std::stoi(std::string(reinterpret_cast<const char*>(req._args[0].data()), req._args[0].size())); cols = std::clamp(cols, 1, 1000); } if (req.arguments_size() >= 2) { squares_per_row = std::stoi(std::string(reinterpret_cast<const char*>(req._args[1].data()), req._args[1].size())); squares_per_row = std::clamp(squares_per_row, 1, 200); } if (req.arguments_size() >= 3) { squares_per_col = std::stoi(std::string(reinterpret_cast<const char*>(req._args[2].data()), req._args[2].size())); squares_per_col = std::clamp(squares_per_col, 1, 200); } } catch (...) { throw wrong_arguments_exception(1, req.arguments_size(), req._command); } return seastar::make_shared<lolwut> (std::move(req._command), cols, squares_per_row, squares_per_col); } future<redis_message> lolwut::execute(service::storage_proxy&, redis::redis_options& options, service_permit) { return redis::lolwut5(_cols, _squares_per_row, _squares_per_col).then([] (auto result) { return redis_message::make_strings_result(std::move(result)); }); } } }
fix use-after-free crash in "exists" command
redis: fix use-after-free crash in "exists" command A missing "&" caused the key stored in a long-living command to be copied and the copy quickly freed - and then used after freed. This caused the test test_strings.py::test_exists_multiple_existent_key for this feature to frequently crash. Fixes #6469 Signed-off-by: Nadav Har'El <[email protected]> Message-Id: <20200823190141.88816-1-625169824b719df98706d88646d0aae6f368ae4d@scylladb.com>
C++
agpl-3.0
avikivity/scylla,scylladb/scylla,avikivity/scylla,scylladb/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla
f2636e0ef1edc2d71839d8ae7eedb0a412f02604
test/geometry_encoding.cpp
test/geometry_encoding.cpp
#include "catch.hpp" #include "encoding_util.hpp" // https://github.com/mapbox/mapnik-vector-tile/issues/36 TEST_CASE( "test 1a", "should round trip without changes" ) { mapnik::geometry::point g(0,0); std::string expected( "move_to(0,0)\n" ); CHECK(compare(g) == expected); } /* TEST_CASE( "test 1", "should round trip without changes" ) { mapnik::geometry::polygon g; g.exterior_ring.add_coord(0,0); g.exterior_ring.add_coord(1,1); g.exterior_ring.add_coord(100,100); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "line_to(100,100)\n" "close_path(0,0)\n" ); CHECK(compare(g) == expected); } */ TEST_CASE( "test 2", "should drop coincident line_to moves" ) { /* mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(3,3); g.line_to(3,3); g.line_to(3,3); g.line_to(3,3); g.line_to(4,4); */ mapnik::geometry::line_string g; g.add_coord(0,0); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(4,4); std::string expected( "move_to(0,0)\n" "line_to(3,3)\n" "line_to(4,4)\n" ); CHECK(compare(g,1) == expected); } /* TEST_CASE( "test 2b", "should drop vertices" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(0,0); g.line_to(1,1); std::string expected( "move_to(0,0)\n" "line_to(0,0)\n" // TODO - should we try to drop this? "line_to(1,1)\n" ); CHECK(compare(g,1) == expected); } TEST_CASE( "test 3", "should not drop first move_to or last vertex in line" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(1,1); g.move_to(0,0); g.line_to(1,1); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "move_to(0,0)\n" "line_to(1,1)\n" ); CHECK(compare(g,1000) == expected); } TEST_CASE( "test 4", "should not drop first move_to or last vertex in polygon" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(1,1); g.move_to(0,0); g.line_to(1,1); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "move_to(0,0)\n" "line_to(1,1)\n" "close_path(0,0)\n" ); CHECK(compare(g,1000) == expected); } TEST_CASE( "test 5", "can drop duplicate move_to" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); // skipped g.line_to(4,4); // skipped g.line_to(5,5); std::string expected( "move_to(0,0)\n" // TODO - should we keep move_to(1,1) instead? "line_to(5,5)\n" ); CHECK(compare(g,2) == expected); } TEST_CASE( "test 5b", "can drop duplicate move_to" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); g.line_to(2,2); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" ); CHECK(compare(g,3) == expected); } TEST_CASE( "test 5c", "can drop duplicate move_to but not second" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); g.line_to(2,2); g.move_to(3,3); g.line_to(4,4); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "move_to(3,3)\n" "line_to(4,4)\n" ); CHECK(compare(g,3) == expected); } TEST_CASE( "test 6", "should not drop last line_to if repeated" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(2,2); g.line_to(1000,1000); // skipped g.line_to(1001,1001); // skipped g.line_to(1001,1001); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "line_to(1001,1001)\n" ); CHECK(compare(g,2) == expected); } TEST_CASE( "test 7", "ensure proper handling of skipping + close commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(2,2); g.close_path(); g.move_to(5,5); g.line_to(10,10); // skipped g.line_to(21,21); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "close_path(0,0)\n" "move_to(5,5)\n" "line_to(21,21)\n" "close_path(0,0)\n" ); CHECK(compare(g,100) == expected); } TEST_CASE( "test 8", "should drop repeated close commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(2,2); g.close_path(); g.close_path(); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "close_path(0,0)\n" ); CHECK(compare(g,100) == expected); } TEST_CASE( "test 9a", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(9,0); // skipped g.line_to(0,10); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 9b", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(10,0); // skipped g.line_to(0,10); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" "close_path(0,0)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 9c", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(0,10); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" "close_path(0,0)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 10", "should skip repeated close and coincident line_to commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(10,10); g.line_to(10,10); // skipped g.line_to(20,20); g.line_to(20,20); // skipped, but added back and replaces previous g.close_path(); g.close_path(); // skipped g.close_path(); // skipped g.close_path(); // skipped g.move_to(0,0); g.line_to(10,10); g.line_to(20,20); g.close_path(); g.close_path(); // skipped std::string expected( "move_to(0,0)\n" "line_to(10,10)\n" "line_to(20,20)\n" "close_path(0,0)\n" "move_to(0,0)\n" "line_to(10,10)\n" "line_to(20,20)\n" "close_path(0,0)\n" ); CHECK(compare(g,1) == expected); } TEST_CASE( "test 11", "should correctly encode multiple paths" ) { using namespace mapnik::vector_tile_impl; vector_tile::Tile_Feature feature0; int32_t x = 0; int32_t y = 0; unsigned path_multiplier = 1; unsigned tolerance = 10000; mapnik::geometry_type g0(mapnik::geometry_type::types::Polygon); g0.move_to(0,0); g0.line_to(-10,-10); g0.line_to(-20,-20); g0.close_path(); mapnik::vertex_adapter va(g0); encode_geometry(va,(vector_tile::Tile_GeomType)g0.type(),feature0,x,y,tolerance,path_multiplier); CHECK(x == -20); CHECK(y == -20); mapnik::geometry_type g1(mapnik::geometry_type::types::Polygon); g1.move_to(1000,1000); g1.line_to(1010,1010); g1.line_to(1020,1020); g1.close_path(); mapnik::vertex_adapter va1(g1); encode_geometry(va1,(vector_tile::Tile_GeomType)g1.type(),feature0,x,y,tolerance,path_multiplier); CHECK(x == 1020); CHECK(y == 1020); mapnik::geometry_type g2(mapnik::geometry_type::types::Polygon); double x0 = 0; double y0 = 0; decode_geometry(feature0,g2,x0,y0,path_multiplier); mapnik::vertex_adapter va2(g2); std::string actual = show_path(va2); std::string expected( "move_to(0,0)\n" "line_to(-20,-20)\n" "close_path(0,0)\n" "move_to(1000,1000)\n" "line_to(1020,1020)\n" "close_path(0,0)\n" ); CHECK(actual == expected); } TEST_CASE( "test 12", "should correctly encode multiple paths" ) { using namespace mapnik::vector_tile_impl; vector_tile::Tile_Feature feature0; int32_t x = 0; int32_t y = 0; unsigned path_multiplier = 1; unsigned tolerance = 10; mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(100,0); g.line_to(100,100); g.line_to(0,100); g.line_to(0,5); g.line_to(0,0); g.close_path(); g.move_to(20,20); g.line_to(20,60); g.line_to(60,60); g.line_to(60,20); g.line_to(25,20); g.line_to(20,20); g.close_path(); mapnik::vertex_adapter va(g); encode_geometry(va,(vector_tile::Tile_GeomType)g.type(),feature0,x,y,tolerance,path_multiplier); mapnik::geometry_type g2(mapnik::geometry_type::types::Polygon); double x0 = 0; double y0 = 0; decode_geometry(feature0,g2,x0,y0,path_multiplier); mapnik::vertex_adapter va2(g2); std::string actual = show_path(va2); std::string expected( "move_to(0,0)\n" "line_to(100,0)\n" "line_to(100,100)\n" "line_to(0,100)\n" "line_to(0,0)\n" "close_path(0,0)\n" "move_to(20,20)\n" "line_to(20,60)\n" "line_to(60,60)\n" "line_to(60,20)\n" "line_to(20,20)\n" "close_path(0,0)\n" ); CHECK(actual == expected); } */
#include "catch.hpp" #include "encoding_util.hpp" #include <mapnik/geometry_correct.hpp> #include <mapnik/geometry_unique.hpp> // https://github.com/mapbox/mapnik-vector-tile/issues/36 TEST_CASE( "test 1a", "should round trip without changes" ) { mapnik::geometry::point g(0,0); std::string expected( "move_to(0,0)\n" ); CHECK(compare(g) == expected); } /* TEST_CASE( "test 1", "should round trip without changes" ) { mapnik::geometry::polygon g; g.exterior_ring.add_coord(0,0); g.exterior_ring.add_coord(1,1); g.exterior_ring.add_coord(100,100); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "line_to(100,100)\n" "close_path(0,0)\n" ); CHECK(compare(g) == expected); } */ TEST_CASE( "test 2", "should drop coincident line_to commands" ) { /* mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(3,3); g.line_to(3,3); g.line_to(3,3); g.line_to(3,3); g.line_to(4,4); */ mapnik::geometry::line_string g; g.add_coord(0,0); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(3,3); g.add_coord(4,4); mapnik::geometry::unique(g); //std::cout << boost::geometry::dsv(g) << std::endl; std::string expected( "move_to(0,0)\n" "line_to(3,3)\n" "line_to(4,4)\n" ); CHECK(compare(g,1) == expected); } /* TEST_CASE( "test 2b", "should drop vertices" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(0,0); g.line_to(1,1); std::string expected( "move_to(0,0)\n" "line_to(0,0)\n" // TODO - should we try to drop this? "line_to(1,1)\n" ); CHECK(compare(g,1) == expected); } TEST_CASE( "test 3", "should not drop first move_to or last vertex in line" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(1,1); g.move_to(0,0); g.line_to(1,1); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "move_to(0,0)\n" "line_to(1,1)\n" ); CHECK(compare(g,1000) == expected); } TEST_CASE( "test 4", "should not drop first move_to or last vertex in polygon" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(1,1); g.move_to(0,0); g.line_to(1,1); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(1,1)\n" "move_to(0,0)\n" "line_to(1,1)\n" "close_path(0,0)\n" ); CHECK(compare(g,1000) == expected); } TEST_CASE( "test 5", "can drop duplicate move_to" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); // skipped g.line_to(4,4); // skipped g.line_to(5,5); std::string expected( "move_to(0,0)\n" // TODO - should we keep move_to(1,1) instead? "line_to(5,5)\n" ); CHECK(compare(g,2) == expected); } TEST_CASE( "test 5b", "can drop duplicate move_to" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); g.line_to(2,2); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" ); CHECK(compare(g,3) == expected); } TEST_CASE( "test 5c", "can drop duplicate move_to but not second" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.move_to(1,1); g.line_to(2,2); g.move_to(3,3); g.line_to(4,4); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "move_to(3,3)\n" "line_to(4,4)\n" ); CHECK(compare(g,3) == expected); } TEST_CASE( "test 6", "should not drop last line_to if repeated" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(2,2); g.line_to(1000,1000); // skipped g.line_to(1001,1001); // skipped g.line_to(1001,1001); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "line_to(1001,1001)\n" ); CHECK(compare(g,2) == expected); } TEST_CASE( "test 7", "ensure proper handling of skipping + close commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(2,2); g.close_path(); g.move_to(5,5); g.line_to(10,10); // skipped g.line_to(21,21); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "close_path(0,0)\n" "move_to(5,5)\n" "line_to(21,21)\n" "close_path(0,0)\n" ); CHECK(compare(g,100) == expected); } TEST_CASE( "test 8", "should drop repeated close commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(2,2); g.close_path(); g.close_path(); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(2,2)\n" "close_path(0,0)\n" ); CHECK(compare(g,100) == expected); } TEST_CASE( "test 9a", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::LineString); g.move_to(0,0); g.line_to(9,0); // skipped g.line_to(0,10); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 9b", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(10,0); // skipped g.line_to(0,10); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" "close_path(0,0)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 9c", "should not drop last vertex" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(0,10); g.close_path(); std::string expected( "move_to(0,0)\n" "line_to(0,10)\n" "close_path(0,0)\n" ); CHECK(compare(g,11) == expected); } TEST_CASE( "test 10", "should skip repeated close and coincident line_to commands" ) { mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(10,10); g.line_to(10,10); // skipped g.line_to(20,20); g.line_to(20,20); // skipped, but added back and replaces previous g.close_path(); g.close_path(); // skipped g.close_path(); // skipped g.close_path(); // skipped g.move_to(0,0); g.line_to(10,10); g.line_to(20,20); g.close_path(); g.close_path(); // skipped std::string expected( "move_to(0,0)\n" "line_to(10,10)\n" "line_to(20,20)\n" "close_path(0,0)\n" "move_to(0,0)\n" "line_to(10,10)\n" "line_to(20,20)\n" "close_path(0,0)\n" ); CHECK(compare(g,1) == expected); } TEST_CASE( "test 11", "should correctly encode multiple paths" ) { using namespace mapnik::vector_tile_impl; vector_tile::Tile_Feature feature0; int32_t x = 0; int32_t y = 0; unsigned path_multiplier = 1; unsigned tolerance = 10000; mapnik::geometry_type g0(mapnik::geometry_type::types::Polygon); g0.move_to(0,0); g0.line_to(-10,-10); g0.line_to(-20,-20); g0.close_path(); mapnik::vertex_adapter va(g0); encode_geometry(va,(vector_tile::Tile_GeomType)g0.type(),feature0,x,y,tolerance,path_multiplier); CHECK(x == -20); CHECK(y == -20); mapnik::geometry_type g1(mapnik::geometry_type::types::Polygon); g1.move_to(1000,1000); g1.line_to(1010,1010); g1.line_to(1020,1020); g1.close_path(); mapnik::vertex_adapter va1(g1); encode_geometry(va1,(vector_tile::Tile_GeomType)g1.type(),feature0,x,y,tolerance,path_multiplier); CHECK(x == 1020); CHECK(y == 1020); mapnik::geometry_type g2(mapnik::geometry_type::types::Polygon); double x0 = 0; double y0 = 0; decode_geometry(feature0,g2,x0,y0,path_multiplier); mapnik::vertex_adapter va2(g2); std::string actual = show_path(va2); std::string expected( "move_to(0,0)\n" "line_to(-20,-20)\n" "close_path(0,0)\n" "move_to(1000,1000)\n" "line_to(1020,1020)\n" "close_path(0,0)\n" ); CHECK(actual == expected); } TEST_CASE( "test 12", "should correctly encode multiple paths" ) { using namespace mapnik::vector_tile_impl; vector_tile::Tile_Feature feature0; int32_t x = 0; int32_t y = 0; unsigned path_multiplier = 1; unsigned tolerance = 10; mapnik::geometry_type g(mapnik::geometry_type::types::Polygon); g.move_to(0,0); g.line_to(100,0); g.line_to(100,100); g.line_to(0,100); g.line_to(0,5); g.line_to(0,0); g.close_path(); g.move_to(20,20); g.line_to(20,60); g.line_to(60,60); g.line_to(60,20); g.line_to(25,20); g.line_to(20,20); g.close_path(); mapnik::vertex_adapter va(g); encode_geometry(va,(vector_tile::Tile_GeomType)g.type(),feature0,x,y,tolerance,path_multiplier); mapnik::geometry_type g2(mapnik::geometry_type::types::Polygon); double x0 = 0; double y0 = 0; decode_geometry(feature0,g2,x0,y0,path_multiplier); mapnik::vertex_adapter va2(g2); std::string actual = show_path(va2); std::string expected( "move_to(0,0)\n" "line_to(100,0)\n" "line_to(100,100)\n" "line_to(0,100)\n" "line_to(0,0)\n" "close_path(0,0)\n" "move_to(20,20)\n" "line_to(20,60)\n" "line_to(60,60)\n" "line_to(60,20)\n" "line_to(20,20)\n" "close_path(0,0)\n" ); CHECK(actual == expected); } */
call mapnik::geometry_unique(geom) to remove coincident points
call mapnik::geometry_unique(geom) to remove coincident points
C++
bsd-3-clause
mapbox/mapnik-vector-tile,landsurveyorsunited/mapnik-vector-tile,mapbox/mapnik-vector-tile,mapbox/mapnik-vector-tile,tomhughes/mapnik-vector-tile,landsurveyorsunited/mapnik-vector-tile,landsurveyorsunited/mapnik-vector-tile,tomhughes/mapnik-vector-tile,tomhughes/mapnik-vector-tile,tomhughes/mapnik-vector-tile,mapbox/mapnik-vector-tile
0f3195680b07eb0eef2376b49ba0f451c699df28
libgearman/run.cc
libgearman/run.cc
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include <libgearman/common.h> #include "libgearman/assert.hpp" #include <cstdio> #include <cstdlib> #include <cstring> gearman_return_t _client_run_task(Task *task) { // This should not be possible assert_msg(task->client, "Programmer error, somehow an invalid task was specified"); if (task->client == NULL) { return gearman_universal_set_error(task->client->impl()->universal, GEARMAN_INVALID_ARGUMENT, GEARMAN_AT, "Programmer error, somehow an invalid task was specified"); } switch(task->state) { case GEARMAN_TASK_STATE_NEW: if (task->client->impl()->universal.has_connections() == false) { assert(task->client->impl()->universal.con_count == 0); assert(task->client->impl()->universal.con_list == NULL); task->client->impl()->new_tasks--; task->client->impl()->running_tasks--; return gearman_universal_set_error(task->client->impl()->universal, GEARMAN_NO_SERVERS, GEARMAN_AT, "no servers provided"); } for (task->con= task->client->impl()->universal.con_list; task->con; task->con= task->con->next_connection()) { if (task->con->send_state == GEARMAN_CON_SEND_STATE_NONE) { break; } } if (task->con == NULL) { task->client->impl()->options.no_new= true; return gearman_gerror(task->client->impl()->universal, GEARMAN_IO_WAIT); } task->client->impl()->new_tasks--; if (task->send.command != GEARMAN_COMMAND_GET_STATUS) { task->created_id= task->con->created_id_next; task->con->created_id_next++; } case GEARMAN_TASK_STATE_SUBMIT: while (1) { assert(task->con); gearman_return_t ret= task->con->send_packet(task->send, task->client->impl()->new_tasks == 0 ? true : false); if (gearman_success(ret)) { break; } else if (ret == GEARMAN_IO_WAIT) { task->state= GEARMAN_TASK_STATE_SUBMIT; return ret; } else if (gearman_failed(ret)) { /* Increment this since the job submission failed. */ task->con->created_id++; if (ret == GEARMAN_COULD_NOT_CONNECT) { for (task->con= task->con->next_connection(); task->con; task->con= task->con->next_connection()) { if (task->con->send_state == GEARMAN_CON_SEND_STATE_NONE) { break; } } } else { task->con= NULL; } if (not task->con) { task->result_rc= ret; if (ret == GEARMAN_COULD_NOT_CONNECT) // If no connection is found, we will let the user try again { task->state= GEARMAN_TASK_STATE_NEW; task->client->impl()->new_tasks++; } else { task->state= GEARMAN_TASK_STATE_FAIL; task->client->impl()->running_tasks--; } return ret; } if (task->send.command != GEARMAN_COMMAND_GET_STATUS) { task->created_id= task->con->created_id_next; task->con->created_id_next++; } } } if (task->send.data_size > 0 and not task->send.data) { if (not task->func.workload_fn) { gearman_error(task->client->impl()->universal, GEARMAN_NEED_WORKLOAD_FN, "workload size > 0, but no data pointer or workload_fn was given"); return GEARMAN_NEED_WORKLOAD_FN; } case GEARMAN_TASK_STATE_WORKLOAD: gearman_return_t ret= task->func.workload_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_WORKLOAD; return ret; } } task->client->impl()->options.no_new= false; task->state= GEARMAN_TASK_STATE_WORK; task->con->set_events(POLLIN); return GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_WORK: if (task->recv->command == GEARMAN_COMMAND_JOB_CREATED) { task->options.is_known= true; snprintf(task->job_handle, GEARMAN_JOB_HANDLE_SIZE, "%.*s", int(task->recv->arg_size[0]), static_cast<char *>(task->recv->arg[0])); case GEARMAN_TASK_STATE_CREATED: if (task->func.created_fn) { gearman_return_t ret= task->func.created_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_CREATED; return ret; } } if (task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_HIGH_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_LOW_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_EPOCH || task->send.command == GEARMAN_COMMAND_SUBMIT_REDUCE_JOB_BACKGROUND) { break; } } else if (task->recv->command == GEARMAN_COMMAND_WORK_DATA) { task->options.is_known= true; task->options.is_running= true; case GEARMAN_TASK_STATE_DATA: if (task->func.data_fn) { gearman_return_t ret= task->func.data_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_DATA; return ret; } } } else if (task->recv->command == GEARMAN_COMMAND_WORK_WARNING) { case GEARMAN_TASK_STATE_WARNING: if (task->func.warning_fn) { gearman_return_t ret= task->func.warning_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_WARNING; return ret; } } } else if (task->recv->command == GEARMAN_COMMAND_WORK_STATUS or task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE or task->recv->command == GEARMAN_COMMAND_STATUS_RES) { uint8_t x; if (task->recv->command == GEARMAN_COMMAND_STATUS_RES) { task->result_rc= GEARMAN_SUCCESS; if (atoi(static_cast<char *>(task->recv->arg[1])) == 0) { task->options.is_known= false; } else { task->options.is_known= true; } if (atoi(static_cast<char *>(task->recv->arg[2])) == 0) { task->options.is_running= false; } else { task->options.is_running= true; } x= 3; } else if (task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE) { task->result_rc= GEARMAN_SUCCESS; strncpy(task->unique, task->recv->arg[0], GEARMAN_MAX_UNIQUE_SIZE); if (atoi(static_cast<char *>(task->recv->arg[1])) == 0) { task->options.is_known= false; } else { task->options.is_known= true; } if (atoi(static_cast<char *>(task->recv->arg[2])) == 0) { task->options.is_running= false; } else { task->options.is_running= true; } x= 3; } else { x= 1; } task->numerator= uint32_t(atoi(static_cast<char *>(task->recv->arg[x]))); // denomitor { char status_buffer[11]; /* Max string size to hold a uint32_t. */ snprintf(status_buffer, 11, "%.*s", int(task->recv->arg_size[x + 1]), static_cast<char *>(task->recv->arg[x + 1])); task->denominator= uint32_t(atoi(status_buffer)); } // client_count if (task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE) { char status_buffer[11]; /* Max string size to hold a uint32_t. */ snprintf(status_buffer, 11, "%.*s", int(task->recv->arg_size[x +2]), static_cast<char *>(task->recv->arg[x +2])); task->client_count= uint32_t(atoi(status_buffer)); } case GEARMAN_TASK_STATE_STATUS: if (task->func.status_fn) { gearman_return_t ret= task->func.status_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_STATUS; return ret; } } if (task->send.command == GEARMAN_COMMAND_GET_STATUS) { break; } if (task->send.command == GEARMAN_COMMAND_GET_STATUS_UNIQUE) { break; } } else if (task->recv->command == GEARMAN_COMMAND_WORK_COMPLETE) { task->options.is_known= false; task->options.is_running= false; task->result_rc= GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_COMPLETE: if (task->func.complete_fn) { gearman_return_t ret= task->func.complete_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_COMPLETE; return ret; } } break; } else if (task->recv->command == GEARMAN_COMMAND_WORK_EXCEPTION) { case GEARMAN_TASK_STATE_EXCEPTION: task->options.is_known= false; task->options.is_running= false; task->free_result(); task->result_rc= GEARMAN_WORK_EXCEPTION; if (task->recv->argc == 1 and task->recv->data_size) { task->exception.store((const char*)(task->recv->data), task->recv->data_size); } if (task->func.exception_fn) { gearman_return_t ret= task->func.exception_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_EXCEPTION; return ret; } } break; } else if (task->recv->command == GEARMAN_COMMAND_WORK_FAIL) { // If things fail we need to delete the result, and set the result_rc // correctly. task->options.is_known= false; task->options.is_running= false; task->free_result(); task->result_rc= GEARMAN_WORK_FAIL; case GEARMAN_TASK_STATE_FAIL: if (task->func.fail_fn) { gearman_return_t ret= task->func.fail_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_FAIL; return ret; } } break; } task->state= GEARMAN_TASK_STATE_WORK; return GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_FINISHED: break; } task->client->impl()->running_tasks--; task->state= GEARMAN_TASK_STATE_FINISHED; if (task->client->impl()->options.free_tasks and task->type == GEARMAN_TASK_KIND_ADD_TASK) { gearman_task_free(task->shell()); } return GEARMAN_SUCCESS; }
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "gear_config.h" #include <libgearman/common.h> #include "libgearman/assert.hpp" #include <cstdio> #include <cstdlib> #include <cstring> gearman_return_t _client_run_task(Task *task) { // This should not be possible assert_msg(task->client, "Programmer error, somehow an invalid task was specified"); if (task->client == NULL) { return gearman_universal_set_error(task->client->impl()->universal, GEARMAN_INVALID_ARGUMENT, GEARMAN_AT, "Programmer error, somehow an invalid task was specified"); } switch(task->state) { case GEARMAN_TASK_STATE_NEW: if (task->client->impl()->universal.has_connections() == false) { assert(task->client->impl()->universal.con_count == 0); assert(task->client->impl()->universal.con_list == NULL); task->client->impl()->new_tasks--; task->client->impl()->running_tasks--; return gearman_universal_set_error(task->client->impl()->universal, GEARMAN_NO_SERVERS, GEARMAN_AT, "no servers provided"); } for (task->con= task->client->impl()->universal.con_list; task->con; task->con= task->con->next_connection()) { if (task->con->send_state == GEARMAN_CON_SEND_STATE_NONE) { break; } } if (task->con == NULL) { task->client->impl()->options.no_new= true; return gearman_gerror(task->client->impl()->universal, GEARMAN_IO_WAIT); } task->client->impl()->new_tasks--; if (task->send.command != GEARMAN_COMMAND_GET_STATUS) { task->created_id= task->con->created_id_next; task->con->created_id_next++; } case GEARMAN_TASK_STATE_SUBMIT: while (1) { assert(task->con); gearman_return_t ret= task->con->send_packet(task->send, task->client->impl()->new_tasks == 0 ? true : false); if (gearman_success(ret)) { break; } else if (ret == GEARMAN_IO_WAIT) { task->state= GEARMAN_TASK_STATE_SUBMIT; return ret; } else if (gearman_failed(ret)) { /* Increment this since the job submission failed. */ task->con->created_id++; if (ret == GEARMAN_COULD_NOT_CONNECT) { for (task->con= task->con->next_connection(); task->con; task->con= task->con->next_connection()) { if (task->con->send_state == GEARMAN_CON_SEND_STATE_NONE) { break; } } } else { task->con= NULL; } if (not task->con) { task->result_rc= ret; if (ret == GEARMAN_COULD_NOT_CONNECT) // If no connection is found, we will let the user try again { task->state= GEARMAN_TASK_STATE_NEW; task->client->impl()->new_tasks++; } else { task->state= GEARMAN_TASK_STATE_FAIL; task->client->impl()->running_tasks--; } return ret; } if (task->send.command != GEARMAN_COMMAND_GET_STATUS) { task->created_id= task->con->created_id_next; task->con->created_id_next++; } } } if (task->send.data_size > 0 and not task->send.data) { if (not task->func.workload_fn) { gearman_error(task->client->impl()->universal, GEARMAN_NEED_WORKLOAD_FN, "workload size > 0, but no data pointer or workload_fn was given"); return GEARMAN_NEED_WORKLOAD_FN; } case GEARMAN_TASK_STATE_WORKLOAD: gearman_return_t ret= task->func.workload_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_WORKLOAD; return ret; } } task->client->impl()->options.no_new= false; task->state= GEARMAN_TASK_STATE_WORK; task->con->set_events(POLLIN); return GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_WORK: if (task->recv->command == GEARMAN_COMMAND_JOB_CREATED) { task->options.is_known= true; snprintf(task->job_handle, GEARMAN_JOB_HANDLE_SIZE, "%.*s", int(task->recv->arg_size[0]), static_cast<char *>(task->recv->arg[0])); case GEARMAN_TASK_STATE_CREATED: if (task->func.created_fn) { gearman_return_t ret= task->func.created_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_CREATED; return ret; } } if (task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_HIGH_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_LOW_BG || task->send.command == GEARMAN_COMMAND_SUBMIT_JOB_EPOCH || task->send.command == GEARMAN_COMMAND_SUBMIT_REDUCE_JOB_BACKGROUND) { break; } } else if (task->recv->command == GEARMAN_COMMAND_WORK_DATA) { task->options.is_known= true; task->options.is_running= true; case GEARMAN_TASK_STATE_DATA: if (task->func.data_fn) { gearman_return_t ret= task->func.data_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_DATA; return ret; } } } else if (task->recv->command == GEARMAN_COMMAND_WORK_WARNING) { case GEARMAN_TASK_STATE_WARNING: if (task->func.warning_fn) { gearman_return_t ret= task->func.warning_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_WARNING; return ret; } } } else if (task->recv->command == GEARMAN_COMMAND_WORK_STATUS or task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE or task->recv->command == GEARMAN_COMMAND_STATUS_RES) { uint8_t x; if (task->recv->command == GEARMAN_COMMAND_STATUS_RES) { task->result_rc= GEARMAN_SUCCESS; if (atoi(static_cast<char *>(task->recv->arg[1])) == 0) { task->options.is_known= false; } else { task->options.is_known= true; } if (atoi(static_cast<char *>(task->recv->arg[2])) == 0) { task->options.is_running= false; } else { task->options.is_running= true; } x= 3; } else if (task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE) { task->result_rc= GEARMAN_SUCCESS; strncpy(task->unique, task->recv->arg[0], GEARMAN_MAX_UNIQUE_SIZE); if (atoi(static_cast<char *>(task->recv->arg[1])) == 0) { task->options.is_known= false; } else { task->options.is_known= true; } if (atoi(static_cast<char *>(task->recv->arg[2])) == 0) { task->options.is_running= false; } else { task->options.is_running= true; } x= 3; } else { x= 1; } task->numerator= uint32_t(atoi(static_cast<char *>(task->recv->arg[x]))); // denomitor { char status_buffer[11]; /* Max string size to hold a uint32_t. */ snprintf(status_buffer, 11, "%.*s", int(task->recv->arg_size[x + 1]), static_cast<char *>(task->recv->arg[x + 1])); task->denominator= uint32_t(atoi(status_buffer)); } // client_count if (task->recv->command == GEARMAN_COMMAND_STATUS_RES_UNIQUE) { char status_buffer[11]; /* Max string size to hold a uint32_t. */ snprintf(status_buffer, 11, "%.*s", int(task->recv->arg_size[x +2]), static_cast<char *>(task->recv->arg[x +2])); task->client_count= uint32_t(atoi(status_buffer)); } case GEARMAN_TASK_STATE_STATUS: if (task->func.status_fn) { gearman_return_t ret= task->func.status_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_STATUS; return ret; } } if (task->send.command == GEARMAN_COMMAND_GET_STATUS) { break; } if (task->send.command == GEARMAN_COMMAND_GET_STATUS_UNIQUE) { break; } } else if (task->recv->command == GEARMAN_COMMAND_WORK_COMPLETE) { task->options.is_known= false; task->options.is_running= false; task->result_rc= GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_COMPLETE: if (task->func.complete_fn) { gearman_return_t ret= task->func.complete_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_COMPLETE; return ret; } } break; } else if (task->recv->command == GEARMAN_COMMAND_WORK_EXCEPTION) { task->options.is_known= false; task->options.is_running= false; if (task->recv->argc == 1 and task->recv->data_size) { task->exception.store((const char*)(task->recv->data), task->recv->data_size); } task->free_result(); task->result_rc= GEARMAN_WORK_EXCEPTION; case GEARMAN_TASK_STATE_EXCEPTION: if (task->func.exception_fn) { gearman_return_t ret= task->func.exception_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_EXCEPTION; return ret; } } break; } else if (task->recv->command == GEARMAN_COMMAND_WORK_FAIL) { // If things fail we need to delete the result, and set the result_rc // correctly. task->options.is_known= false; task->options.is_running= false; task->free_result(); task->result_rc= GEARMAN_WORK_FAIL; case GEARMAN_TASK_STATE_FAIL: if (task->func.fail_fn) { gearman_return_t ret= task->func.fail_fn(task->shell()); if (gearman_failed(ret)) { task->state= GEARMAN_TASK_STATE_FAIL; return ret; } } break; } task->state= GEARMAN_TASK_STATE_WORK; return GEARMAN_SUCCESS; case GEARMAN_TASK_STATE_FINISHED: break; } task->client->impl()->running_tasks--; task->state= GEARMAN_TASK_STATE_FINISHED; if (task->client->impl()->options.free_tasks and task->type == GEARMAN_TASK_KIND_ADD_TASK) { gearman_task_free(task->shell()); } return GEARMAN_SUCCESS; }
Fix issue around when we re-enter loop for GEARMAN_TASK_STATE_EXCEPTION (this is now correct... but the original code was fine as well).
Fix issue around when we re-enter loop for GEARMAN_TASK_STATE_EXCEPTION (this is now correct... but the original code was fine as well).
C++
bsd-3-clause
dm/gearmand,beeksiwaais/gearmand,dm/gearmand,beeksiwaais/gearmand,dm/gearmand,beeksiwaais/gearmand,beeksiwaais/gearmand,dm/gearmand
64665f99375e269217f91f853af59864eb2b7f59
test/lex/single_tokens.cpp
test/lex/single_tokens.cpp
#include <gtest/gtest.h> #include <fp/diagnostic/print/to_ostream.h> #include <fp/lex/tokenize.h> namespace fp::lex { template <token EXPECTED_TOKEN> void assert_single_token(std::string_view source_str) { std::string_view name = token_name(EXPECTED_TOKEN); diagnostic::report report; fp::source_file file("single-token-test.fp", source_str); tokenized_list tokens = tokenize(file, report); if (!report.errors().empty() || !report.warnings().empty()) { diagnostic::print::to_ostream(std::cout, report); FAIL() << name; } ASSERT_EQ(1u, tokens.size()) << name << tokens; ASSERT_EQ(EXPECTED_TOKEN, tokens[0].token); ASSERT_FALSE(tokens[0].dummy) << name; using attribute_t = token_attribute_t<EXPECTED_TOKEN>; using expected_attribute_t = std::conditional_t< std::is_void_v<attribute_t>, std::monostate, attribute_t >; ASSERT_TRUE(std::holds_alternative<expected_attribute_t>( tokens[0].attribute )) << name; const auto& location = tokens[0].source_location; ASSERT_EQ(file.content , location.chars ) << name; ASSERT_EQ(file , location.file ) << name; ASSERT_EQ(file.content.begin(), location.line ) << name; ASSERT_EQ(1u , location.line_number) << name; } TEST(lex, single_tokens) { assert_single_token<token::COMMA>(","); assert_single_token<token::ANNOTATION>(":"); assert_single_token<token::SCOPE>("::"); assert_single_token<token::SEMICOLON>(";"); assert_single_token<token::OPTIONAL>("?"); assert_single_token<token::DECORATOR>("@"); assert_single_token<token::BIT_NOT>("~"); assert_single_token<token::MEMBER_ACCESS>("."); // TODO: tokenize ranges // assert_single_token<token::RANGE>(".."); // assert_single_token<token::CLOSED_RANGE>("..."); // brackets assert_single_token<token::L_PAREN>("("); assert_single_token<token::R_PAREN>(")"); assert_single_token<token::L_BRACKET>("["); assert_single_token<token::R_BRACKET>("]"); assert_single_token<token::L_BRACE>("{"); assert_single_token<token::R_BRACE>("}"); // keywords assert_single_token<token::AND>("and"); assert_single_token<token::AS>("as"); assert_single_token<token::BREAK>("break"); assert_single_token<token::CASE>("case"); assert_single_token<token::CATCH>("catch"); assert_single_token<token::CLASS>("class"); assert_single_token<token::CONCEPT>("concept"); assert_single_token<token::CONTINUE>("continue"); assert_single_token<token::DEFAULT>("dexfault"); assert_single_token<token::DO>("do"); assert_single_token<token::ELSE>("else"); assert_single_token<token::ENUM>("enum"); assert_single_token<token::EXPORT>("export"); assert_single_token<token::FOR>("for"); assert_single_token<token::IF>("if"); assert_single_token<token::IMPLICIT>("implicit"); assert_single_token<token::IMPORT>("import"); assert_single_token<token::IN>("in"); assert_single_token<token::MUT>("mut"); assert_single_token<token::NOT>("not"); assert_single_token<token::OF>("of"); assert_single_token<token::OR>("or"); assert_single_token<token::RETURN>("return"); assert_single_token<token::SWITCH>("switch"); assert_single_token<token::THROW>("throw"); assert_single_token<token::TRY>("try"); assert_single_token<token::WHILE>("while"); // arrows assert_single_token<token::TYPE_ARROW>("->"); assert_single_token<token::LAMBDA_ARROW>("=>"); // arithmetic assert_single_token<token::PLUS>("+"); assert_single_token<token::MINUS>("-"); assert_single_token<token::MUL>("*"); assert_single_token<token::DIV>("/"); assert_single_token<token::MOD>("%"); assert_single_token<token::POW>("^"); assert_single_token<token::BIT_AND>("&"); assert_single_token<token::BIT_OR>("|"); // TODO: Goddamn xor... // assert_single_token<token::XOR>("^"); assert_single_token<token::SHL>("<<"); assert_single_token<token::SHR>(">>"); // assignments assert_single_token<token::ASSIGN>("="); assert_single_token<token::PLUS_ASSIGN>("+="); assert_single_token<token::MINUS_ASSIGN>("-="); assert_single_token<token::MUL_ASSIGN>("*="); assert_single_token<token::DIV_ASSIGN>("/="); assert_single_token<token::MOD_ASSIGN>("%="); assert_single_token<token::POW_ASSIGN>("^="); assert_single_token<token::BIT_AND_ASSIGN>("&="); assert_single_token<token::BIT_OR_ASSIGN>("|="); // TODO: Goddamn xor... // assert_single_token<token::XOR_ASSIGN>("^="); assert_single_token<token::SHL_ASSIGN>("<<="); assert_single_token<token::SHR_ASSIGN>(">>="); // comparisons assert_single_token<token::EQ>("=="); assert_single_token<token::NE>("!="); assert_single_token<token::LT>("<"); assert_single_token<token::GT>(">"); assert_single_token<token::LTE>("<="); assert_single_token<token::GTE>(">="); // increment & decrement assert_single_token<token::INC>("++"); assert_single_token<token::DEC>("--"); // containing attributes assert_single_token<token::COMMENT>("# hello"); assert_single_token<token::IDENTIFIER>("foo_bar"); assert_single_token<token::NUMBER>("42"); assert_single_token<token::CHAR>("'c'"); // assert_single_token<token::STRING>(can't be produced as a single token); } } // namespace fp::lex
#include <gtest/gtest.h> #include <fp/diagnostic/print/to_ostream.h> #include <fp/lex/tokenize.h> namespace fp::lex { template <token EXPECTED_TOKEN> void assert_single_token(std::string_view source_str) { std::string_view name = token_name(EXPECTED_TOKEN); diagnostic::report report; fp::source_file file("single-token-test.fp", source_str); tokenized_list tokens = tokenize(file, report); if (!report.errors().empty() || !report.warnings().empty()) { diagnostic::print::to_ostream(std::cout, report); FAIL() << name; } ASSERT_EQ(1u, tokens.size()) << name << tokens; ASSERT_EQ(EXPECTED_TOKEN, tokens[0].token); ASSERT_FALSE(tokens[0].dummy) << name; using attribute_t = token_attribute_t<EXPECTED_TOKEN>; using expected_attribute_t = std::conditional_t< std::is_void_v<attribute_t>, std::monostate, attribute_t >; ASSERT_TRUE(std::holds_alternative<expected_attribute_t>( tokens[0].attribute )) << name; const auto& location = tokens[0].source_location; ASSERT_EQ(file.content , location.chars ) << name; ASSERT_EQ(file , location.file ) << name; ASSERT_EQ(file.content.begin(), location.line ) << name; ASSERT_EQ(1u , location.line_number) << name; } TEST(lex, single_tokens) { assert_single_token<token::COMMA>(","); assert_single_token<token::ANNOTATION>(":"); assert_single_token<token::SCOPE>("::"); assert_single_token<token::SEMICOLON>(";"); assert_single_token<token::OPTIONAL>("?"); assert_single_token<token::DECORATOR>("@"); assert_single_token<token::BIT_NOT>("~"); assert_single_token<token::MEMBER_ACCESS>("."); // TODO: tokenize ranges // assert_single_token<token::RANGE>(".."); // assert_single_token<token::CLOSED_RANGE>("..."); // brackets assert_single_token<token::L_PAREN>("("); assert_single_token<token::R_PAREN>(")"); assert_single_token<token::L_BRACKET>("["); assert_single_token<token::R_BRACKET>("]"); assert_single_token<token::L_BRACE>("{"); assert_single_token<token::R_BRACE>("}"); // keywords assert_single_token<token::AND>("and"); assert_single_token<token::AS>("as"); assert_single_token<token::BREAK>("break"); assert_single_token<token::CASE>("case"); assert_single_token<token::CATCH>("catch"); assert_single_token<token::CLASS>("class"); assert_single_token<token::CONCEPT>("concept"); assert_single_token<token::CONTINUE>("continue"); assert_single_token<token::DEFAULT>("default"); assert_single_token<token::DO>("do"); assert_single_token<token::ELSE>("else"); assert_single_token<token::ENUM>("enum"); assert_single_token<token::EXPORT>("export"); assert_single_token<token::FOR>("for"); assert_single_token<token::IF>("if"); assert_single_token<token::IMPLICIT>("implicit"); assert_single_token<token::IMPORT>("import"); assert_single_token<token::IN>("in"); assert_single_token<token::MUT>("mut"); assert_single_token<token::NOT>("not"); assert_single_token<token::OF>("of"); assert_single_token<token::OR>("or"); assert_single_token<token::RETURN>("return"); assert_single_token<token::SWITCH>("switch"); assert_single_token<token::THROW>("throw"); assert_single_token<token::TRY>("try"); assert_single_token<token::WHILE>("while"); // arrows assert_single_token<token::TYPE_ARROW>("->"); assert_single_token<token::LAMBDA_ARROW>("=>"); // arithmetic assert_single_token<token::PLUS>("+"); assert_single_token<token::MINUS>("-"); assert_single_token<token::MUL>("*"); assert_single_token<token::DIV>("/"); assert_single_token<token::MOD>("%"); assert_single_token<token::POW>("^"); assert_single_token<token::BIT_AND>("&"); assert_single_token<token::BIT_OR>("|"); // TODO: Goddamn xor... // assert_single_token<token::XOR>("^"); assert_single_token<token::SHL>("<<"); assert_single_token<token::SHR>(">>"); // assignments assert_single_token<token::ASSIGN>("="); assert_single_token<token::PLUS_ASSIGN>("+="); assert_single_token<token::MINUS_ASSIGN>("-="); assert_single_token<token::MUL_ASSIGN>("*="); assert_single_token<token::DIV_ASSIGN>("/="); assert_single_token<token::MOD_ASSIGN>("%="); assert_single_token<token::POW_ASSIGN>("^="); assert_single_token<token::BIT_AND_ASSIGN>("&="); assert_single_token<token::BIT_OR_ASSIGN>("|="); // TODO: Goddamn xor... // assert_single_token<token::XOR_ASSIGN>("^="); assert_single_token<token::SHL_ASSIGN>("<<="); assert_single_token<token::SHR_ASSIGN>(">>="); // comparisons assert_single_token<token::EQ>("=="); assert_single_token<token::NE>("!="); assert_single_token<token::LT>("<"); assert_single_token<token::GT>(">"); assert_single_token<token::LTE>("<="); assert_single_token<token::GTE>(">="); // increment & decrement assert_single_token<token::INC>("++"); assert_single_token<token::DEC>("--"); // containing attributes assert_single_token<token::COMMENT>("# hello"); assert_single_token<token::IDENTIFIER>("foo_bar"); assert_single_token<token::NUMBER>("42"); assert_single_token<token::CHAR>("'c'"); // assert_single_token<token::STRING>(can't be produced as a single token); } } // namespace fp::lex
Fix single tokens test
Fix single tokens test
C++
apache-2.0
sosz/fp,sosz/fp
f19bb1753a22a8982a4e8f7d7d59a4914659791b
Code/IO/itkGDCMSeriesFileNames.cxx
Code/IO/itkGDCMSeriesFileNames.cxx
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGDCMSeriesFileNames.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkGDCMSeriesFileNames_h #define _itkGDCMSeriesFileNames_h #include "itkGDCMSeriesFileNames.h" #include "gdcm/src/gdcmSerieHelper.h" #include "gdcm/src/gdcmFile.h" #include "gdcm/src/gdcmUtil.h" #include <itksys/SystemTools.hxx> #include <vector> #include <string> namespace itk { GDCMSeriesFileNames::GDCMSeriesFileNames() { m_SerieHelper = new gdcm::SerieHelper(); m_Directory = ""; } GDCMSeriesFileNames::~GDCMSeriesFileNames() { delete m_SerieHelper; } const SerieUIDContainer &GDCMSeriesFileNames::GetSeriesUIDs() { if ( m_Directory == "" ) { itkWarningMacro( << "You need to specify a directory where " "the DICOM files are located"); } m_SeriesUIDs.clear(); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList(); while(flist) { if( flist->size() ) //make sure we have at leat one serie { gdcm::File *file = (*flist)[0]; //for example take the first one std::string uid = file->GetEntryValue (0x0020, 0x000e); m_SeriesUIDs.push_back( uid ); } flist = m_SerieHelper->GetNextCoherentFileList(); } if( !m_SeriesUIDs.size() ) { itkWarningMacro(<<"No Series were found"); } return m_SeriesUIDs; } const FilenamesContainer &GDCMSeriesFileNames::GetFileNames(const std::string serie) { m_FileNames.clear(); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList(); bool found = false; while(flist) { if( flist->size() ) //make sure we have at leat one serie { gdcm::File *file = (*flist)[0]; //for example take the first one std::string uid = file->GetEntryValue (0x0020, 0x000e); // We need to use a specialized call to compare those two strings: if( gdcm::Util::DicomStringEqual(uid, serie.c_str()) ) { found = true; // we found a match break; } } flist = m_SerieHelper->GetNextCoherentFileList(); } if( !found) { itkWarningMacro(<<"No Series were found"); return m_FileNames; } m_SerieHelper->OrderGdcmFileList(flist); gdcm::GdcmFileList::iterator it; if( flist->size() ) { for(it = flist->begin(); it != flist->end(); ++it ) { gdcm::File * header = *it; if( !header ) { itkWarningMacro( << "GDCMSeriesFileNames got NULL header, " "this is a serious bug" ); continue; } if( !header->IsReadable() ) { itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:" << header->GetFileName() ); continue; } m_FileNames.push_back( header->GetFileName() ); } } else { itkDebugMacro(<<"No files were found"); } return m_FileNames; } const FilenamesContainer &GDCMSeriesFileNames::GetInputFileNames() { m_InputFileNames.clear(); // Get the DICOM filenames from the directory gdcm::SerieHelper *helper = new gdcm::SerieHelper(); helper->SetDirectory( m_InputDirectory ); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = helper->GetFirstCoherentFileList(); helper->OrderGdcmFileList(flist); gdcm::GdcmFileList::iterator it; if( flist->size() ) { for(it = flist->begin(); it != flist->end(); ++it ) { gdcm::File * header = *it; if( !header ) { itkWarningMacro( << "GDCMSeriesFileNames got NULL header, " "this is a serious bug" ); continue; } if( !header->IsReadable() ) { itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:" << header->GetFileName() ); continue; } m_InputFileNames.push_back( header->GetFileName() ); } } else { itkDebugMacro(<<"No files were found"); } delete helper; return m_InputFileNames; } const FilenamesContainer &GDCMSeriesFileNames::GetOutputFileNames() { // We are trying to extract the original filename and compose it with a path: //There are two different approachs if directory does not exist: // 1. Exit // 2. Mkdir //bool SystemTools::FileExists(const char* filename) //bool SystemTools::FileIsDirectory(const char* name) m_OutputFileNames.clear(); if( m_OutputDirectory.empty() ) { itkDebugMacro(<<"No output directory was specified"); return m_OutputFileNames; } itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory ); if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/') { m_OutputDirectory += '/'; } if( m_InputFileNames.size() ) { bool hasExtension = false; for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin(); it != m_InputFileNames.end(); ++it ) { // look for extension ".dcm" and ".DCM" std::string::size_type dcmPos = (*it).rfind(".dcm"); if ( (dcmPos != std::string::npos) && (dcmPos == (*it).length() - 4) ) { hasExtension = true; } else { dcmPos = (*it).rfind(".DCM"); if ( (dcmPos != std::string::npos) && (dcmPos == (*it).length() - 4) ) { hasExtension = true; } } // look for extension ".dicom" and ".DICOM" std::string::size_type dicomPos = (*it).rfind(".dicom"); if ( (dicomPos != std::string::npos) && (dicomPos == (*it).length() - 6) ) { hasExtension = true; } else { dicomPos = (*it).rfind(".DICOM"); if ( (dicomPos != std::string::npos) && (dicomPos == (*it).length() - 6) ) { hasExtension = true; } } // construct a filename, adding an extension if necessary std::string filename; if (hasExtension) { filename = m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it ); } else { // input filename has no extension, add a ".dcm" filename = m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it ) + ".dcm"; } // Add the file name to the output list m_OutputFileNames.push_back( filename ); } } else { itkDebugMacro(<<"No files were found."); } return m_OutputFileNames; } void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); unsigned int i; os << indent << "InputDirectory: " << m_InputDirectory << std::endl; for (i = 0; i < m_InputFileNames.size(); i++) { os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl; } os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl; for (i = 0; i < m_OutputFileNames.size(); i++) { os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl; } } } //namespace ITK #endif
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkGDCMSeriesFileNames.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itkGDCMSeriesFileNames_h #define _itkGDCMSeriesFileNames_h #include "itkGDCMSeriesFileNames.h" #include "gdcm/src/gdcmSerieHelper.h" #include "gdcm/src/gdcmFile.h" #include "gdcm/src/gdcmUtil.h" #include <itksys/SystemTools.hxx> #include <vector> #include <string> namespace itk { GDCMSeriesFileNames::GDCMSeriesFileNames() { m_SerieHelper = new gdcm::SerieHelper(); m_Directory = ""; } GDCMSeriesFileNames::~GDCMSeriesFileNames() { delete m_SerieHelper; } const SerieUIDContainer &GDCMSeriesFileNames::GetSeriesUIDs() { if ( m_Directory == "" ) { itkWarningMacro( << "You need to specify a directory where " "the DICOM files are located"); } m_SeriesUIDs.clear(); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList(); while(flist) { if( flist->size() ) //make sure we have at leat one serie { gdcm::File *file = (*flist)[0]; //for example take the first one std::string uid = file->GetEntryValue (0x0020, 0x000e); m_SeriesUIDs.push_back( uid ); } flist = m_SerieHelper->GetNextCoherentFileList(); } if( !m_SeriesUIDs.size() ) { itkWarningMacro(<<"No Series were found"); } return m_SeriesUIDs; } const FilenamesContainer &GDCMSeriesFileNames::GetFileNames(const std::string serie) { m_FileNames.clear(); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = m_SerieHelper->GetFirstCoherentFileList(); bool found = false; while(flist) { if( flist->size() ) //make sure we have at leat one serie { gdcm::File *file = (*flist)[0]; //for example take the first one std::string uid = file->GetEntryValue (0x0020, 0x000e); // We need to use a specialized call to compare those two strings: if( gdcm::Util::DicomStringEqual(uid, serie.c_str()) ) { found = true; // we found a match break; } } flist = m_SerieHelper->GetNextCoherentFileList(); } if( !found) { itkWarningMacro(<<"No Series were found"); return m_FileNames; } m_SerieHelper->OrderGdcmFileList(flist); gdcm::GdcmFileList::iterator it; if( flist->size() ) { for(it = flist->begin(); it != flist->end(); ++it ) { gdcm::File * header = *it; if( !header ) { itkWarningMacro( << "GDCMSeriesFileNames got NULL header, " "this is a serious bug" ); continue; } if( !header->IsReadable() ) { itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:" << header->GetFileName() ); continue; } m_FileNames.push_back( header->GetFileName() ); } } else { itkDebugMacro(<<"No files were found"); } return m_FileNames; } const FilenamesContainer &GDCMSeriesFileNames::GetInputFileNames() { m_InputFileNames.clear(); // Get the DICOM filenames from the directory gdcm::SerieHelper *helper = new gdcm::SerieHelper(); helper->SetDirectory( m_InputDirectory ); // Accessing the first serie found (assume there is at least one) gdcm::GdcmFileList *flist = helper->GetFirstCoherentFileList(); helper->OrderGdcmFileList(flist); gdcm::GdcmFileList::iterator it; if( flist && flist->size() ) { for(it = flist->begin(); it != flist->end(); ++it ) { gdcm::File * header = *it; if( !header ) { itkWarningMacro( << "GDCMSeriesFileNames got NULL header, " "this is a serious bug" ); continue; } if( !header->IsReadable() ) { itkWarningMacro( << "GDCMSeriesFileNames got a non DICOM file:" << header->GetFileName() ); continue; } m_InputFileNames.push_back( header->GetFileName() ); } } else { itkDebugMacro(<<"No files were found"); } delete helper; return m_InputFileNames; } const FilenamesContainer &GDCMSeriesFileNames::GetOutputFileNames() { // We are trying to extract the original filename and compose it with a path: //There are two different approachs if directory does not exist: // 1. Exit // 2. Mkdir //bool SystemTools::FileExists(const char* filename) //bool SystemTools::FileIsDirectory(const char* name) m_OutputFileNames.clear(); if( m_OutputDirectory.empty() ) { itkDebugMacro(<<"No output directory was specified"); return m_OutputFileNames; } itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory ); if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/') { m_OutputDirectory += '/'; } if( m_InputFileNames.size() ) { bool hasExtension = false; for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin(); it != m_InputFileNames.end(); ++it ) { // look for extension ".dcm" and ".DCM" std::string::size_type dcmPos = (*it).rfind(".dcm"); if ( (dcmPos != std::string::npos) && (dcmPos == (*it).length() - 4) ) { hasExtension = true; } else { dcmPos = (*it).rfind(".DCM"); if ( (dcmPos != std::string::npos) && (dcmPos == (*it).length() - 4) ) { hasExtension = true; } } // look for extension ".dicom" and ".DICOM" std::string::size_type dicomPos = (*it).rfind(".dicom"); if ( (dicomPos != std::string::npos) && (dicomPos == (*it).length() - 6) ) { hasExtension = true; } else { dicomPos = (*it).rfind(".DICOM"); if ( (dicomPos != std::string::npos) && (dicomPos == (*it).length() - 6) ) { hasExtension = true; } } // construct a filename, adding an extension if necessary std::string filename; if (hasExtension) { filename = m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it ); } else { // input filename has no extension, add a ".dcm" filename = m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it ) + ".dcm"; } // Add the file name to the output list m_OutputFileNames.push_back( filename ); } } else { itkDebugMacro(<<"No files were found."); } return m_OutputFileNames; } void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); unsigned int i; os << indent << "InputDirectory: " << m_InputDirectory << std::endl; for (i = 0; i < m_InputFileNames.size(); i++) { os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl; } os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl; for (i = 0; i < m_OutputFileNames.size(); i++) { os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl; } } } //namespace ITK #endif
add null pointer check
BUG: add null pointer check
C++
apache-2.0
LucasGandel/ITK,heimdali/ITK,blowekamp/ITK,daviddoria/itkHoughTransform,fedral/ITK,rhgong/itk-with-dom,msmolens/ITK,cpatrick/ITK-RemoteIO,heimdali/ITK,eile/ITK,CapeDrew/DCMTK-ITK,fuentesdt/InsightToolkit-dev,CapeDrew/DITK,BRAINSia/ITK,cpatrick/ITK-RemoteIO,fedral/ITK,malaterre/ITK,atsnyder/ITK,ajjl/ITK,zachary-williamson/ITK,spinicist/ITK,jcfr/ITK,blowekamp/ITK,hendradarwin/ITK,spinicist/ITK,daviddoria/itkHoughTransform,spinicist/ITK,fuentesdt/InsightToolkit-dev,spinicist/ITK,atsnyder/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,BlueBrain/ITK,CapeDrew/DCMTK-ITK,PlutoniumHeart/ITK,daviddoria/itkHoughTransform,vfonov/ITK,itkvideo/ITK,vfonov/ITK,Kitware/ITK,msmolens/ITK,stnava/ITK,fbudin69500/ITK,fbudin69500/ITK,CapeDrew/DCMTK-ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,InsightSoftwareConsortium/ITK,blowekamp/ITK,paulnovo/ITK,BlueBrain/ITK,richardbeare/ITK,jmerkow/ITK,PlutoniumHeart/ITK,spinicist/ITK,CapeDrew/DCMTK-ITK,wkjeong/ITK,jmerkow/ITK,fuentesdt/InsightToolkit-dev,malaterre/ITK,GEHC-Surgery/ITK,thewtex/ITK,eile/ITK,biotrump/ITK,vfonov/ITK,wkjeong/ITK,fbudin69500/ITK,eile/ITK,hendradarwin/ITK,LucasGandel/ITK,vfonov/ITK,jmerkow/ITK,vfonov/ITK,fbudin69500/ITK,GEHC-Surgery/ITK,cpatrick/ITK-RemoteIO,PlutoniumHeart/ITK,jmerkow/ITK,fbudin69500/ITK,malaterre/ITK,heimdali/ITK,spinicist/ITK,fbudin69500/ITK,msmolens/ITK,itkvideo/ITK,heimdali/ITK,daviddoria/itkHoughTransform,itkvideo/ITK,stnava/ITK,stnava/ITK,msmolens/ITK,hendradarwin/ITK,hinerm/ITK,jcfr/ITK,vfonov/ITK,daviddoria/itkHoughTransform,biotrump/ITK,ajjl/ITK,PlutoniumHeart/ITK,hendradarwin/ITK,jmerkow/ITK,LucHermitte/ITK,CapeDrew/DCMTK-ITK,atsnyder/ITK,BRAINSia/ITK,zachary-williamson/ITK,ajjl/ITK,CapeDrew/DITK,GEHC-Surgery/ITK,hendradarwin/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,CapeDrew/DITK,paulnovo/ITK,LucHermitte/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,blowekamp/ITK,fuentesdt/InsightToolkit-dev,daviddoria/itkHoughTransform,zachary-williamson/ITK,blowekamp/ITK,BRAINSia/ITK,itkvideo/ITK,jmerkow/ITK,paulnovo/ITK,ajjl/ITK,fedral/ITK,BlueBrain/ITK,Kitware/ITK,wkjeong/ITK,cpatrick/ITK-RemoteIO,LucHermitte/ITK,hinerm/ITK,itkvideo/ITK,malaterre/ITK,Kitware/ITK,Kitware/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,atsnyder/ITK,LucHermitte/ITK,rhgong/itk-with-dom,GEHC-Surgery/ITK,Kitware/ITK,msmolens/ITK,thewtex/ITK,fuentesdt/InsightToolkit-dev,hinerm/ITK,blowekamp/ITK,paulnovo/ITK,LucasGandel/ITK,LucasGandel/ITK,jcfr/ITK,zachary-williamson/ITK,eile/ITK,stnava/ITK,fbudin69500/ITK,jmerkow/ITK,richardbeare/ITK,CapeDrew/DITK,InsightSoftwareConsortium/ITK,CapeDrew/DCMTK-ITK,richardbeare/ITK,hendradarwin/ITK,rhgong/itk-with-dom,hinerm/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,itkvideo/ITK,daviddoria/itkHoughTransform,thewtex/ITK,rhgong/itk-with-dom,blowekamp/ITK,malaterre/ITK,stnava/ITK,BRAINSia/ITK,eile/ITK,heimdali/ITK,hjmjohnson/ITK,Kitware/ITK,biotrump/ITK,paulnovo/ITK,daviddoria/itkHoughTransform,hinerm/ITK,GEHC-Surgery/ITK,LucasGandel/ITK,fedral/ITK,Kitware/ITK,biotrump/ITK,jcfr/ITK,eile/ITK,GEHC-Surgery/ITK,hjmjohnson/ITK,BlueBrain/ITK,richardbeare/ITK,heimdali/ITK,hjmjohnson/ITK,msmolens/ITK,jmerkow/ITK,stnava/ITK,BlueBrain/ITK,hjmjohnson/ITK,ajjl/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,eile/ITK,atsnyder/ITK,biotrump/ITK,paulnovo/ITK,fedral/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,cpatrick/ITK-RemoteIO,stnava/ITK,LucHermitte/ITK,hendradarwin/ITK,itkvideo/ITK,fbudin69500/ITK,BRAINSia/ITK,LucHermitte/ITK,wkjeong/ITK,wkjeong/ITK,malaterre/ITK,ajjl/ITK,hinerm/ITK,cpatrick/ITK-RemoteIO,heimdali/ITK,paulnovo/ITK,spinicist/ITK,msmolens/ITK,BlueBrain/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,fuentesdt/InsightToolkit-dev,GEHC-Surgery/ITK,vfonov/ITK,jcfr/ITK,hinerm/ITK,paulnovo/ITK,fedral/ITK,biotrump/ITK,LucasGandel/ITK,stnava/ITK,LucHermitte/ITK,eile/ITK,cpatrick/ITK-RemoteIO,thewtex/ITK,wkjeong/ITK,heimdali/ITK,rhgong/itk-with-dom,atsnyder/ITK,rhgong/itk-with-dom,hjmjohnson/ITK,BRAINSia/ITK,spinicist/ITK,GEHC-Surgery/ITK,thewtex/ITK,hinerm/ITK,CapeDrew/DCMTK-ITK,InsightSoftwareConsortium/ITK,atsnyder/ITK,CapeDrew/DITK,richardbeare/ITK,vfonov/ITK,LucasGandel/ITK,ajjl/ITK,zachary-williamson/ITK,jcfr/ITK,wkjeong/ITK,hendradarwin/ITK,CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,biotrump/ITK,malaterre/ITK,richardbeare/ITK,richardbeare/ITK,thewtex/ITK,fedral/ITK,LucHermitte/ITK,rhgong/itk-with-dom,LucasGandel/ITK,PlutoniumHeart/ITK,jcfr/ITK,itkvideo/ITK,biotrump/ITK,CapeDrew/DITK,spinicist/ITK,CapeDrew/DITK,daviddoria/itkHoughTransform,CapeDrew/DITK,fedral/ITK,BRAINSia/ITK,jcfr/ITK,msmolens/ITK,hinerm/ITK,eile/ITK,ajjl/ITK,blowekamp/ITK,PlutoniumHeart/ITK,itkvideo/ITK,zachary-williamson/ITK,fuentesdt/InsightToolkit-dev,thewtex/ITK,zachary-williamson/ITK,wkjeong/ITK,stnava/ITK,malaterre/ITK,CapeDrew/DCMTK-ITK
cfeb515256aade71cc44191f74120d1a2cc6a015
aeron-driver/src/main/cpp/media/InetAddress.cpp
aeron-driver/src/main/cpp/media/InetAddress.cpp
/* * Copyright 2015 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <cinttypes> #include <string> #include <regex> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include "util/StringUtil.h" #include "util/ScopeUtils.h" #include "InetAddress.h" #include "uri/NetUtil.h" #include "util/Exceptions.h" using namespace aeron::driver::media; std::unique_ptr<InetAddress> InetAddress::fromIPv4(std::string& address, uint16_t port) { struct in_addr addr; if (!inet_pton(AF_INET, address.c_str(), &addr)) { throw aeron::util::IOException("Failed to parse IPv4 address", SOURCEINFO); } return std::unique_ptr<InetAddress>{new Inet4Address{addr, port}}; } std::unique_ptr<InetAddress> InetAddress::fromIPv6(std::string& address, uint16_t port) { struct in6_addr addr; if (!inet_pton(AF_INET6, address.c_str(), &addr)) { throw aeron::util::IOException("Failed to parse IPv6 address", SOURCEINFO); } return std::unique_ptr<InetAddress>{new Inet6Address{addr, port}}; } std::unique_ptr<InetAddress> InetAddress::fromHostname(std::string& address, uint16_t port, int familyHint) { addrinfo hints; addrinfo* info; memset(&hints, sizeof(addrinfo), 0); hints.ai_family = familyHint; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; int error; if ((error = getaddrinfo(address.c_str(), NULL, &hints, &info)) != 0) { throw aeron::util::IOException( aeron::util::strPrintf( "Unable to lookup host (%s): %s (%d)", address.c_str(), gai_strerror(error), error), SOURCEINFO); } aeron::util::OnScopeExit tidy([&]() { freeaddrinfo(info); }); if (info->ai_family == AF_INET) { sockaddr_in* addr_in = (sockaddr_in*) info->ai_addr; return std::unique_ptr<InetAddress>{new Inet4Address{addr_in->sin_addr, port}}; } else if (info->ai_family == AF_INET6) { sockaddr_in6* addr_in = (sockaddr_in6*) info->ai_addr; return std::unique_ptr<InetAddress>{new Inet6Address{addr_in->sin6_addr, port}}; } throw aeron::util::IOException{"Only IPv4 and IPv6 are supported", SOURCEINFO}; } std::unique_ptr<InetAddress> InetAddress::parse(const char* addressString, int familyHint) { std::string s{addressString}; return parse(s, familyHint); } std::unique_ptr<InetAddress> InetAddress::parse(std::string const & addressString, int familyHint) { std::regex ipV4{"([^:]+)(?::([0-9]+))?"}; std::regex ipv6{"\\[([0-9A-Fa-f:]+)(?:%([a-zA-Z0-9_.~-]+))?\\](?::([0-9]+))?"}; std::smatch results; if (std::regex_match(addressString, results, ipv6)) { auto inetAddressStr = results[1].str(); auto scope = results[2].str(); auto port = aeron::util::fromString<uint16_t>(results[3].str()); return fromIPv6(inetAddressStr, port); } if (std::regex_match(addressString, results, ipV4) && results.size() == 3) { auto inetAddressStr = results[1].str(); auto port = aeron::util::fromString<std::uint16_t>(results[2].str()); try { return fromIPv4(inetAddressStr, port); } catch (aeron::util::IOException e) { return fromHostname(inetAddressStr, port, familyHint); } } throw aeron::util::IOException("Address does not match IPv4 or IPv6 string", SOURCEINFO); } std::unique_ptr<InetAddress> InetAddress::any(int familyHint) { if (familyHint == PF_INET) { in_addr addr{INADDR_ANY}; return std::unique_ptr<InetAddress>{new Inet4Address{addr, 0}}; } else { return std::unique_ptr<InetAddress>{new Inet6Address{in6addr_any, 0}}; } } bool Inet4Address::isEven() const { return aeron::driver::uri::NetUtil::isEven(m_socketAddress.sin_addr); } bool Inet4Address::equals(const InetAddress& other) const { const Inet4Address& addr = dynamic_cast<const Inet4Address&>(other); return m_socketAddress.sin_addr.s_addr == addr.m_socketAddress.sin_addr.s_addr; } void Inet4Address::output(std::ostream &os) const { char addr[INET_ADDRSTRLEN]; inet_ntop(domain(), &m_socketAddress.sin_addr, addr, INET_ADDRSTRLEN); os << addr; } std::unique_ptr<InetAddress> Inet4Address::nextAddress() const { union _u { in_addr addr; uint8_t parts[4]; }; union _u copy; copy.addr = m_socketAddress.sin_addr; copy.parts[3]++; return std::unique_ptr<InetAddress>{new Inet4Address{copy.addr, port()}}; } bool Inet4Address::matches(const InetAddress &candidate, std::uint32_t subnetPrefix) const { const Inet4Address& addr = dynamic_cast<const Inet4Address&>(candidate); return aeron::driver::uri::NetUtil::wildcardMatch( &addr.m_socketAddress.sin_addr, &m_socketAddress.sin_addr, subnetPrefix); } bool Inet6Address::isEven() const { return aeron::driver::uri::NetUtil::isEven(m_socketAddress.sin6_addr); } bool Inet6Address::equals(const InetAddress &other) const { const Inet6Address& addr = dynamic_cast<const Inet6Address&>(other); return memcmp(&m_socketAddress.sin6_addr, &addr.m_socketAddress.sin6_addr, sizeof(in6_addr)) == 0; } void Inet6Address::output(std::ostream &os) const { char addr[INET6_ADDRSTRLEN]; inet_ntop(domain(), &m_socketAddress.sin6_addr, addr, INET6_ADDRSTRLEN); os << addr; } std::unique_ptr<InetAddress> Inet6Address::nextAddress() const { in6_addr addr = m_socketAddress.sin6_addr; addr.s6_addr[15]++; return std::unique_ptr<InetAddress>{new Inet6Address{addr, port()}}; } bool Inet6Address::matches(const InetAddress &candidate, std::uint32_t subnetPrefix) const { const Inet6Address& addr = dynamic_cast<const Inet6Address&>(candidate); return aeron::driver::uri::NetUtil::wildcardMatch( &addr.m_socketAddress.sin6_addr, &m_socketAddress.sin6_addr, subnetPrefix); }
/* * Copyright 2015 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdlib> #include <cinttypes> #include <string> #include <regex> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include "util/StringUtil.h" #include "util/ScopeUtils.h" #include "InetAddress.h" #include "uri/NetUtil.h" #include "util/Exceptions.h" using namespace aeron::driver::media; std::unique_ptr<InetAddress> InetAddress::fromIPv4(std::string& address, uint16_t port) { struct in_addr addr; if (!inet_pton(AF_INET, address.c_str(), &addr)) { throw aeron::util::IOException("Failed to parse IPv4 address", SOURCEINFO); } return std::unique_ptr<InetAddress>{new Inet4Address{addr, port}}; } std::unique_ptr<InetAddress> InetAddress::fromIPv6(std::string& address, uint16_t port) { struct in6_addr addr; if (!inet_pton(AF_INET6, address.c_str(), &addr)) { throw aeron::util::IOException("Failed to parse IPv6 address", SOURCEINFO); } return std::unique_ptr<InetAddress>{new Inet6Address{addr, port}}; } std::unique_ptr<InetAddress> InetAddress::fromHostname(std::string& address, uint16_t port, int familyHint) { addrinfo hints; addrinfo* info; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = familyHint; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; int error; if ((error = getaddrinfo(address.c_str(), NULL, &hints, &info)) != 0) { throw aeron::util::IOException( aeron::util::strPrintf( "Unable to lookup host (%s): %s (%d)", address.c_str(), gai_strerror(error), error), SOURCEINFO); } aeron::util::OnScopeExit tidy([&]() { freeaddrinfo(info); }); if (info->ai_family == AF_INET) { sockaddr_in* addr_in = (sockaddr_in*) info->ai_addr; return std::unique_ptr<InetAddress>{new Inet4Address{addr_in->sin_addr, port}}; } else if (info->ai_family == AF_INET6) { sockaddr_in6* addr_in = (sockaddr_in6*) info->ai_addr; return std::unique_ptr<InetAddress>{new Inet6Address{addr_in->sin6_addr, port}}; } throw aeron::util::IOException{"Only IPv4 and IPv6 are supported", SOURCEINFO}; } std::unique_ptr<InetAddress> InetAddress::parse(const char* addressString, int familyHint) { std::string s{addressString}; return parse(s, familyHint); } std::unique_ptr<InetAddress> InetAddress::parse(std::string const & addressString, int familyHint) { std::regex ipV4{"([^:]+)(?::([0-9]+))?"}; std::regex ipv6{"\\[([0-9A-Fa-f:]+)(?:%([a-zA-Z0-9_.~-]+))?\\](?::([0-9]+))?"}; std::smatch results; if (std::regex_match(addressString, results, ipv6)) { auto inetAddressStr = results[1].str(); auto scope = results[2].str(); auto port = aeron::util::fromString<uint16_t>(results[3].str()); return fromIPv6(inetAddressStr, port); } if (std::regex_match(addressString, results, ipV4) && results.size() == 3) { auto inetAddressStr = results[1].str(); auto port = aeron::util::fromString<std::uint16_t>(results[2].str()); try { return fromIPv4(inetAddressStr, port); } catch (aeron::util::IOException e) { return fromHostname(inetAddressStr, port, familyHint); } } throw aeron::util::IOException("Address does not match IPv4 or IPv6 string", SOURCEINFO); } std::unique_ptr<InetAddress> InetAddress::any(int familyHint) { if (familyHint == PF_INET) { in_addr addr{INADDR_ANY}; return std::unique_ptr<InetAddress>{new Inet4Address{addr, 0}}; } else { return std::unique_ptr<InetAddress>{new Inet6Address{in6addr_any, 0}}; } } bool Inet4Address::isEven() const { return aeron::driver::uri::NetUtil::isEven(m_socketAddress.sin_addr); } bool Inet4Address::equals(const InetAddress& other) const { const Inet4Address& addr = dynamic_cast<const Inet4Address&>(other); return m_socketAddress.sin_addr.s_addr == addr.m_socketAddress.sin_addr.s_addr; } void Inet4Address::output(std::ostream &os) const { char addr[INET_ADDRSTRLEN]; inet_ntop(domain(), &m_socketAddress.sin_addr, addr, INET_ADDRSTRLEN); os << addr; } std::unique_ptr<InetAddress> Inet4Address::nextAddress() const { union _u { in_addr addr; uint8_t parts[4]; }; union _u copy; copy.addr = m_socketAddress.sin_addr; copy.parts[3]++; return std::unique_ptr<InetAddress>{new Inet4Address{copy.addr, port()}}; } bool Inet4Address::matches(const InetAddress &candidate, std::uint32_t subnetPrefix) const { const Inet4Address& addr = dynamic_cast<const Inet4Address&>(candidate); return aeron::driver::uri::NetUtil::wildcardMatch( &addr.m_socketAddress.sin_addr, &m_socketAddress.sin_addr, subnetPrefix); } bool Inet6Address::isEven() const { return aeron::driver::uri::NetUtil::isEven(m_socketAddress.sin6_addr); } bool Inet6Address::equals(const InetAddress &other) const { const Inet6Address& addr = dynamic_cast<const Inet6Address&>(other); return memcmp(&m_socketAddress.sin6_addr, &addr.m_socketAddress.sin6_addr, sizeof(in6_addr)) == 0; } void Inet6Address::output(std::ostream &os) const { char addr[INET6_ADDRSTRLEN]; inet_ntop(domain(), &m_socketAddress.sin6_addr, addr, INET6_ADDRSTRLEN); os << addr; } std::unique_ptr<InetAddress> Inet6Address::nextAddress() const { in6_addr addr = m_socketAddress.sin6_addr; addr.s6_addr[15]++; return std::unique_ptr<InetAddress>{new Inet6Address{addr, port()}}; } bool Inet6Address::matches(const InetAddress &candidate, std::uint32_t subnetPrefix) const { const Inet6Address& addr = dynamic_cast<const Inet6Address&>(candidate); return aeron::driver::uri::NetUtil::wildcardMatch( &addr.m_socketAddress.sin6_addr, &m_socketAddress.sin6_addr, subnetPrefix); }
Fix random failure in getaddrinfo lookup.
[C++]: Fix random failure in getaddrinfo lookup.
C++
apache-2.0
mikeb01/Aeron,gkamal/Aeron,real-logic/Aeron,galderz/Aeron,oleksiyp/Aeron,oleksiyp/Aeron,real-logic/Aeron,galderz/Aeron,mikeb01/Aeron,galderz/Aeron,tbrooks8/Aeron,oleksiyp/Aeron,tbrooks8/Aeron,mikeb01/Aeron,gkamal/Aeron,real-logic/Aeron,tbrooks8/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,gkamal/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron
956fa518a7cd213e3023691b33747448931a3d7a
tests/unit/test_child.cpp
tests/unit/test_child.cpp
/* * Copyright (c) 2018, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "test_platform.h" #include <openthread/config.h> #include "test_util.h" #include "common/code_utils.hpp" #include "common/instance.hpp" #include "thread/topology.hpp" namespace ot { static ot::Instance *sInstance; enum { kMaxChildIp6Addresses = OPENTHREAD_CONFIG_MLE_IP_ADDRS_PER_CHILD, }; void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, const Ip6::Address aAddressList[]) { Child::Ip6AddressIterator iterator; Ip6::Address address; bool addressObserved[kMaxChildIp6Addresses]; bool addressIsMeshLocal[kMaxChildIp6Addresses]; bool hasMeshLocal = false; for (uint8_t index = 0; index < aAddressListLength; index++) { VerifyOrQuit(aChild.HasIp6Address(*sInstance, aAddressList[index]), "HasIp6Address() failed\n"); } memset(addressObserved, 0, sizeof(addressObserved)); memset(addressIsMeshLocal, 0, sizeof(addressObserved)); for (uint8_t index = 0; index < aAddressListLength; index++) { { addressIsMeshLocal[index] = true; } } while (aChild.GetNextIp6Address(*sInstance, iterator, address) == OT_ERROR_NONE) { bool addressIsInList = false; for (uint8_t index = 0; index < aAddressListLength; index++) { if (address == aAddressList[index]) { addressIsInList = true; addressObserved[index] = true; break; } } VerifyOrQuit(addressIsInList, "Child::GetNextIp6Address() returned an address not in the expected list\n"); } for (uint8_t index = 0; index < aAddressListLength; index++) { VerifyOrQuit(addressObserved[index], "Child::GetNextIp6Address() missed an entry from the expected list\n"); if (sInstance->Get<Mle::MleRouter>().IsMeshLocalAddress(aAddressList[index])) { SuccessOrQuit(aChild.GetMeshLocalIp6Address(*sInstance, address), "Child::GetMeshLocalIp6Address() failed\n"); VerifyOrQuit(address == aAddressList[index], "GetMeshLocalIp6Address() did not return expected address\n"); hasMeshLocal = true; } } if (!hasMeshLocal) { VerifyOrQuit(aChild.GetMeshLocalIp6Address(*sInstance, address) == OT_ERROR_NOT_FOUND, "Child::GetMeshLocalIp6Address() returned an address not in the exptect list\n"); } } void TestChildIp6Address(void) { Child child; Ip6::Address addresses[kMaxChildIp6Addresses]; uint8_t numAddresses; const char * ip6Addresses[] = { "fd00:1234::1234", "fd6b:e251:52fb:0:12e6:b94c:1c28:c56a", "fd00:1234::204c:3d7c:98f6:9a1b", }; const uint8_t meshLocalIid[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; sInstance = testInitInstance(); VerifyOrQuit(sInstance != NULL, "Null instance"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("\nConverting IPv6 addresses from string"); numAddresses = 0; // First addresses uses the mesh local prefix (mesh-local address). addresses[numAddresses] = sInstance->Get<Mle::MleRouter>().GetMeshLocal64(); addresses[numAddresses].SetIid(meshLocalIid); numAddresses++; for (uint8_t index = 0; index < static_cast<uint8_t>(OT_ARRAY_LENGTH(ip6Addresses)); index++) { VerifyOrQuit(numAddresses < kMaxChildIp6Addresses, "Too many IPv6 addresses in the unit test"); SuccessOrQuit(addresses[numAddresses++].FromString(ip6Addresses[index]), "could not convert IPv6 address from string"); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Child state after init"); memset(&child, 0, sizeof(child)); VerifyChildIp6Addresses(child, 0, NULL); printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Adding a single IPv6 address"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); VerifyChildIp6Addresses(child, 1, &addresses[index]); child.ClearIp6Addresses(); VerifyChildIp6Addresses(child, 0, NULL); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Adding multiple IPv6 addresses"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); VerifyChildIp6Addresses(child, index + 1, addresses); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Checking for failure when adding an address already in list"); for (uint8_t index = 0; index < numAddresses; index++) { VerifyOrQuit(child.AddIp6Address(*sInstance, addresses[index]) == OT_ERROR_ALREADY, "AddIp6Address() did not fail when adding same address"); VerifyChildIp6Addresses(child, numAddresses, addresses); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing addresses from list starting from front of the list"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]), "RemoveIp6Address() failed"); VerifyChildIp6Addresses(child, numAddresses - 1 - index, &addresses[index + 1]); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); } VerifyChildIp6Addresses(child, 0, NULL); printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing addresses from list starting from back of the list"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); } for (uint8_t index = numAddresses - 1; index > 0; index--) { SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]), "RemoveIp6Address() failed"); VerifyChildIp6Addresses(child, index, &addresses[0]); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing address entries from middle of the list"); for (uint8_t indexToRemove = 1; indexToRemove < numAddresses - 1; indexToRemove++) { child.ClearIp6Addresses(); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); } SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[indexToRemove]), "RemoveIp6Address() failed"); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[indexToRemove]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); { Ip6::Address updatedAddressList[kMaxChildIp6Addresses]; uint8_t updatedListIndex = 0; for (uint8_t index = 0; index < numAddresses; index++) { if (index != indexToRemove) { updatedAddressList[updatedListIndex++] = addresses[index]; } } VerifyChildIp6Addresses(child, updatedListIndex, updatedAddressList); } } printf(" -- PASS\n"); testFreeInstance(sInstance); } } // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) { ot::TestChildIp6Address(); printf("\nAll tests passed.\n"); return 0; } #endif
/* * Copyright (c) 2018, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "test_platform.h" #include <openthread/config.h> #include "test_util.h" #include "common/code_utils.hpp" #include "common/instance.hpp" #include "thread/topology.hpp" namespace ot { static ot::Instance *sInstance; enum { kMaxChildIp6Addresses = OPENTHREAD_CONFIG_MLE_IP_ADDRS_PER_CHILD, }; void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, const Ip6::Address aAddressList[]) { Child::Ip6AddressIterator iterator; Ip6::Address address; bool addressObserved[kMaxChildIp6Addresses]; bool addressIsMeshLocal[kMaxChildIp6Addresses]; bool hasMeshLocal = false; for (uint8_t index = 0; index < aAddressListLength; index++) { VerifyOrQuit(aChild.HasIp6Address(*sInstance, aAddressList[index]), "HasIp6Address() failed\n"); } memset(addressObserved, 0, sizeof(addressObserved)); memset(addressIsMeshLocal, 0, sizeof(addressObserved)); for (uint8_t index = 0; index < aAddressListLength; index++) { { addressIsMeshLocal[index] = true; } } while (aChild.GetNextIp6Address(*sInstance, iterator, address) == OT_ERROR_NONE) { bool addressIsInList = false; for (uint8_t index = 0; index < aAddressListLength; index++) { if (address == aAddressList[index]) { addressIsInList = true; addressObserved[index] = true; break; } } VerifyOrQuit(addressIsInList, "Child::GetNextIp6Address() returned an address not in the expected list\n"); } for (uint8_t index = 0; index < aAddressListLength; index++) { VerifyOrQuit(addressObserved[index], "Child::GetNextIp6Address() missed an entry from the expected list\n"); if (sInstance->Get<Mle::MleRouter>().IsMeshLocalAddress(aAddressList[index])) { SuccessOrQuit(aChild.GetMeshLocalIp6Address(*sInstance, address), "Child::GetMeshLocalIp6Address() failed\n"); VerifyOrQuit(address == aAddressList[index], "GetMeshLocalIp6Address() did not return expected address\n"); hasMeshLocal = true; } } if (!hasMeshLocal) { VerifyOrQuit(aChild.GetMeshLocalIp6Address(*sInstance, address) == OT_ERROR_NOT_FOUND, "Child::GetMeshLocalIp6Address() returned an address not in the exptect list\n"); } } void TestChildIp6Address(void) { Child child; Ip6::Address addresses[kMaxChildIp6Addresses]; uint8_t numAddresses; const char * ip6Addresses[] = { "fd00:1234::1234", "fd6b:e251:52fb:0:12e6:b94c:1c28:c56a", "fd00:1234::204c:3d7c:98f6:9a1b", }; const uint8_t meshLocalIid[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; sInstance = testInitInstance(); VerifyOrQuit(sInstance != NULL, "Null instance"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("\nConverting IPv6 addresses from string"); numAddresses = 0; // First addresses uses the mesh local prefix (mesh-local address). addresses[numAddresses] = sInstance->Get<Mle::MleRouter>().GetMeshLocal64(); addresses[numAddresses].SetIid(meshLocalIid); numAddresses++; for (uint8_t index = 0; index < static_cast<uint8_t>(OT_ARRAY_LENGTH(ip6Addresses)); index++) { VerifyOrQuit(numAddresses < kMaxChildIp6Addresses, "Too many IPv6 addresses in the unit test"); SuccessOrQuit(addresses[numAddresses++].FromString(ip6Addresses[index]), "could not convert IPv6 address from string"); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Child state after init"); child.Clear(); VerifyChildIp6Addresses(child, 0, NULL); printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Adding a single IPv6 address"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); VerifyChildIp6Addresses(child, 1, &addresses[index]); child.ClearIp6Addresses(); VerifyChildIp6Addresses(child, 0, NULL); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Adding multiple IPv6 addresses"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); VerifyChildIp6Addresses(child, index + 1, addresses); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Checking for failure when adding an address already in list"); for (uint8_t index = 0; index < numAddresses; index++) { VerifyOrQuit(child.AddIp6Address(*sInstance, addresses[index]) == OT_ERROR_ALREADY, "AddIp6Address() did not fail when adding same address"); VerifyChildIp6Addresses(child, numAddresses, addresses); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing addresses from list starting from front of the list"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]), "RemoveIp6Address() failed"); VerifyChildIp6Addresses(child, numAddresses - 1 - index, &addresses[index + 1]); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); } VerifyChildIp6Addresses(child, 0, NULL); printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing addresses from list starting from back of the list"); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); } for (uint8_t index = numAddresses - 1; index > 0; index--) { SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]), "RemoveIp6Address() failed"); VerifyChildIp6Addresses(child, index, &addresses[0]); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[index]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); } printf(" -- PASS\n"); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - printf("Removing address entries from middle of the list"); for (uint8_t indexToRemove = 1; indexToRemove < numAddresses - 1; indexToRemove++) { child.ClearIp6Addresses(); for (uint8_t index = 0; index < numAddresses; index++) { SuccessOrQuit(child.AddIp6Address(*sInstance, addresses[index]), "AddIp6Address() failed"); } SuccessOrQuit(child.RemoveIp6Address(*sInstance, addresses[indexToRemove]), "RemoveIp6Address() failed"); VerifyOrQuit(child.RemoveIp6Address(*sInstance, addresses[indexToRemove]) == OT_ERROR_NOT_FOUND, "RemoveIp6Address() did not fail when removing an address not on the list"); { Ip6::Address updatedAddressList[kMaxChildIp6Addresses]; uint8_t updatedListIndex = 0; for (uint8_t index = 0; index < numAddresses; index++) { if (index != indexToRemove) { updatedAddressList[updatedListIndex++] = addresses[index]; } } VerifyChildIp6Addresses(child, updatedListIndex, updatedAddressList); } } printf(" -- PASS\n"); testFreeInstance(sInstance); } } // namespace ot #ifdef ENABLE_TEST_MAIN int main(void) { ot::TestChildIp6Address(); printf("\nAll tests passed.\n"); return 0; } #endif
update test_child to use Clear() instead of memset (#4248)
[tests] update test_child to use Clear() instead of memset (#4248)
C++
bsd-3-clause
lanyuwen/openthread,jwhui/openthread,chshu/openthread,librasungirl/openthread,bukepo/openthread,srickardti/openthread,abtink/openthread,jwhui/openthread,librasungirl/openthread,openthread/openthread,chshu/openthread,lanyuwen/openthread,srickardti/openthread,lanyuwen/openthread,openthread/openthread,bukepo/openthread,jwhui/openthread,chshu/openthread,chshu/openthread,jwhui/openthread,abtink/openthread,openthread/openthread,lanyuwen/openthread,abtink/openthread,openthread/openthread,abtink/openthread,chshu/openthread,srickardti/openthread,srickardti/openthread,librasungirl/openthread,lanyuwen/openthread,bukepo/openthread,lanyuwen/openthread,bukepo/openthread,chshu/openthread,librasungirl/openthread
8af91146c45d1be0026c5d208e5d48a83f3e68dd
test/unit/text/shaping.cpp
test/unit/text/shaping.cpp
#include "catch.hpp" #include <mapnik/text/icu_shaper.hpp> #include <mapnik/text/harfbuzz_shaper.hpp> #include <mapnik/text/font_library.hpp> #include <mapnik/unicode.hpp> namespace { void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm, std::vector<std::tuple<unsigned, unsigned>> const& expected, char const* str) { mapnik::transcoder tr("utf8"); std::map<unsigned,double> width_map; mapnik::text_itemizer itemizer; auto props = std::make_unique<mapnik::detail::evaluated_format_properties>(); props->fontset = fontset; props->text_size = 32; double scale_factor = 1; auto ustr = tr.transcode(str); auto length = ustr.length(); itemizer.add_text(ustr, props); mapnik::text_line line(0, length); mapnik::harfbuzz_shaper::shape_text(line, itemizer, width_map, fm, scale_factor); std::size_t index = 0; for (auto const& g : line) { unsigned glyph_index, char_index; CHECK(index < expected.size()); std::tie(glyph_index, char_index) = expected[index++]; REQUIRE(glyph_index == g.glyph_index); REQUIRE(char_index == g.char_index); } } } TEST_CASE("shaping") { mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc"); mapnik::freetype_engine::register_fonts("test/data/fonts/Noto"); mapnik::font_set fontset("fontset"); for (auto const& name : mapnik::freetype_engine::face_names()) { fontset.add_face_name(name); } mapnik::font_library fl; mapnik::freetype_engine::font_file_mapping_type font_file_mapping; mapnik::freetype_engine::font_memory_cache_type font_memory_cache; mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache); { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}}; // with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^ //std::vector<std::tuple<unsigned, unsigned>> expected = // {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}}; // expected results if "NotoSansTibetan-Regular.ttf is registered^^ test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (abc)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}}; test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (普兰镇)"); } }
#include "catch.hpp" #include <mapnik/text/icu_shaper.hpp> #include <mapnik/text/harfbuzz_shaper.hpp> #include <mapnik/text/font_library.hpp> #include <mapnik/unicode.hpp> namespace { void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm, std::vector<std::tuple<unsigned, unsigned>> const& expected, char const* str) { mapnik::transcoder tr("utf8"); std::map<unsigned,double> width_map; mapnik::text_itemizer itemizer; auto props = std::make_unique<mapnik::detail::evaluated_format_properties>(); props->fontset = fontset; props->text_size = 32; double scale_factor = 1; auto ustr = tr.transcode(str); auto length = ustr.length(); itemizer.add_text(ustr, props); mapnik::text_line line(0, length); mapnik::harfbuzz_shaper::shape_text(line, itemizer, width_map, fm, scale_factor); std::size_t index = 0; for (auto const& g : line) { unsigned glyph_index, char_index; CHECK(index < expected.size()); std::tie(glyph_index, char_index) = expected[index++]; REQUIRE(glyph_index == g.glyph_index); REQUIRE(char_index == g.char_index); } } } TEST_CASE("shaping") { mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc"); mapnik::freetype_engine::register_fonts("test/data/fonts/Noto"); mapnik::font_set fontset("fontset"); for (auto const& name : mapnik::freetype_engine::face_names()) { fontset.add_face_name(name); } mapnik::font_library fl; mapnik::freetype_engine::font_file_mapping_type font_file_mapping; mapnik::freetype_engine::font_memory_cache_type font_memory_cache; mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache); { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}}; // with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^ //std::vector<std::tuple<unsigned, unsigned>> expected = // {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}}; // expected results if "NotoSansTibetan-Regular.ttf is registered^^ test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (abc)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}}; test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (普兰镇)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {0, 5}, {0, 6}, {0, 7}, {12, 8}}; test_shaping(fontset, fm, expected, "abc (普兰镇)"); } }
add an extra test
add an extra test
C++
lgpl-2.1
naturalatlas/mapnik,tomhughes/mapnik,mapnik/mapnik,lightmare/mapnik,lightmare/mapnik,tomhughes/mapnik,naturalatlas/mapnik,tomhughes/mapnik,naturalatlas/mapnik,mapnik/mapnik,lightmare/mapnik,naturalatlas/mapnik,tomhughes/mapnik,mapnik/mapnik,mapnik/mapnik,lightmare/mapnik
9812b44c624ea00596b7a4c3022b6e98340e7c77
net.cc
net.cc
/* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #include "net.hh" #include <utility> using std::move; namespace net { constexpr size_t packet::internal_data_size; void packet::linearize(size_t at_frag, size_t desired_size) { size_t nr_frags = 0; size_t accum_size = 0; while (accum_size < desired_size) { accum_size += fragments[at_frag + nr_frags].size; ++nr_frags; } std::unique_ptr<char[]> new_frag{new char[accum_size]}; auto p = new_frag.get(); for (size_t i = 0; i < nr_frags; ++i) { auto& f = fragments[at_frag + i]; p = std::copy(f.base, f.base + f.size, p); } fragments.erase(fragments.begin() + at_frag + 1, fragments.begin() + at_frag + nr_frags); fragments[at_frag] = fragment{new_frag.get(), accum_size}; _deleter = make_deleter(std::move(_deleter), [buf = std::move(new_frag)] {}); } future<packet, ethernet_address> l3_protocol::receive() { return _netif->receive(_proto_num); }; future<packet, ethernet_address> interface::receive(uint16_t proto_num) { auto& pr = _proto_map[proto_num] = promise<packet, ethernet_address>(); return pr.get_future(); } interface::interface(std::unique_ptr<device> dev) : _dev(std::move(dev)), _hw_address(_dev->hw_address()) { } void interface::run() { _dev->receive().then([this] (packet p) { auto eh = p.get_header<eth_hdr>(0); if (eh) { ntoh(*eh); auto i = _proto_map.find(eh->eth_proto); if (i != _proto_map.end()) { auto from = eh->src_mac; p.trim_front(sizeof(*eh)); i->second.set_value(std::move(p), from); _proto_map.erase(i); } } run(); }); } }
/* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #include "net.hh" #include <utility> using std::move; namespace net { constexpr size_t packet::internal_data_size; void packet::linearize(size_t at_frag, size_t desired_size) { size_t nr_frags = 0; size_t accum_size = 0; while (accum_size < desired_size) { accum_size += fragments[at_frag + nr_frags].size; ++nr_frags; } std::unique_ptr<char[]> new_frag{new char[accum_size]}; auto p = new_frag.get(); for (size_t i = 0; i < nr_frags; ++i) { auto& f = fragments[at_frag + i]; p = std::copy(f.base, f.base + f.size, p); } fragments.erase(fragments.begin() + at_frag + 1, fragments.begin() + at_frag + nr_frags); fragments[at_frag] = fragment{new_frag.get(), accum_size}; _deleter = make_deleter(std::move(_deleter), [buf = std::move(new_frag)] {}); } future<packet, ethernet_address> l3_protocol::receive() { return _netif->receive(_proto_num); }; future<> l3_protocol::send(ethernet_address to, packet p) { return _netif->send(_proto_num, to, std::move(p)); } future<packet, ethernet_address> interface::receive(uint16_t proto_num) { auto& pr = _proto_map[proto_num] = promise<packet, ethernet_address>(); return pr.get_future(); } interface::interface(std::unique_ptr<device> dev) : _dev(std::move(dev)), _hw_address(_dev->hw_address()) { } void interface::run() { _dev->receive().then([this] (packet p) { auto eh = p.get_header<eth_hdr>(0); if (eh) { ntoh(*eh); auto i = _proto_map.find(eh->eth_proto); if (i != _proto_map.end()) { auto from = eh->src_mac; p.trim_front(sizeof(*eh)); i->second.set_value(std::move(p), from); _proto_map.erase(i); } } run(); }); } future<> interface::send(uint16_t proto_num, ethernet_address to, packet p) { eth_hdr eh; eh.dst_mac = to; eh.src_mac = _hw_address; eh.eth_proto = proto_num; hton(eh); return _dev->send(packet(fragment{reinterpret_cast<char*>(&eh), sizeof(eh)}, std::move(p))); } }
add missing interface:: and l3_protocol:: send() functions
net: add missing interface:: and l3_protocol:: send() functions
C++
agpl-3.0
tempbottle/scylla,syuu1228/seastar,raphaelsc/seastar,kjniemi/seastar,guiquanz/scylla,bowlofstew/scylla,chunshengster/seastar,capturePointer/scylla,rluta/scylla,scylladb/scylla,gwicke/scylla,kjniemi/scylla,tempbottle/scylla,linearregression/scylla,dreamsxin/seastar,kangkot/scylla,koolhazz/seastar,asias/scylla,bowlofstew/scylla,sjperkins/seastar,printedheart/seastar,acbellini/seastar,joerg84/seastar,bzero/seastar,phonkee/scylla,leejir/seastar,capturePointer/scylla,tempbottle/seastar,aruanruan/scylla,dwdm/seastar,phonkee/scylla,dreamsxin/seastar,mixja/seastar,leejir/seastar,raphaelsc/scylla,respu/scylla,norcimo5/seastar,slivne/seastar,gwicke/scylla,printedheart/seastar,kjniemi/seastar,cloudius-systems/seastar,avikivity/seastar,hongliangzhao/seastar,asias/scylla,linearregression/scylla,hongliangzhao/seastar,stamhe/scylla,tempbottle/seastar,kjniemi/scylla,anzihenry/seastar,senseb/scylla,xtao/seastar,glommer/scylla,shyamalschandra/seastar,jonathanleang/seastar,sjperkins/seastar,tempbottle/scylla,chunshengster/seastar,respu/scylla,bowlofstew/seastar,avikivity/scylla,mixja/seastar,stamhe/seastar,rentongzhang/scylla,scylladb/seastar,acbellini/seastar,senseb/scylla,rluta/scylla,bzero/seastar,chunshengster/seastar,victorbriz/scylla,stamhe/seastar,syuu1228/seastar,raphaelsc/seastar,flashbuckets/seastar,xtao/seastar,linearregression/seastar,cloudius-systems/seastar,justintung/scylla,rluta/scylla,rentongzhang/scylla,victorbriz/scylla,linearregression/seastar,guiquanz/scylla,tempbottle/seastar,bzero/seastar,ducthangho/imdb,raphaelsc/scylla,wildinto/scylla,capturePointer/scylla,wildinto/seastar,justintung/scylla,wildinto/scylla,linearregression/scylla,stamhe/scylla,eklitzke/scylla,norcimo5/seastar,rentongzhang/scylla,asias/scylla,joerg84/seastar,cloudius-systems/seastar,avikivity/seastar,scylladb/seastar,dwdm/scylla,duarten/scylla,shaunstanislaus/scylla,avikivity/seastar,slivne/seastar,scylladb/scylla,duarten/scylla,glommer/scylla,hongliangzhao/seastar,shaunstanislaus/scylla,victorbriz/scylla,avikivity/scylla,anzihenry/seastar,stamhe/scylla,syuu1228/seastar,stamhe/seastar,scylladb/scylla-seastar,respu/scylla,glommer/scylla,acbellini/seastar,dwdm/scylla,wildinto/scylla,acbellini/scylla,senseb/scylla,jonathanleang/seastar,slivne/seastar,aruanruan/scylla,shaunstanislaus/scylla,wildinto/seastar,ducthangho/imdb,bowlofstew/seastar,scylladb/seastar,xtao/seastar,acbellini/scylla,ducthangho/imdb,kangkot/scylla,printedheart/seastar,scylladb/scylla-seastar,mixja/seastar,dreamsxin/seastar,jonathanleang/seastar,bowlofstew/seastar,kjniemi/seastar,duarten/scylla,anzihenry/seastar,eklitzke/scylla,sjperkins/seastar,avikivity/scylla,koolhazz/seastar,joerg84/seastar,guiquanz/scylla,dwdm/seastar,phonkee/scylla,shyamalschandra/seastar,kjniemi/scylla,norcimo5/seastar,eklitzke/scylla,scylladb/scylla,justintung/scylla,linearregression/seastar,flashbuckets/seastar,scylladb/scylla,dwdm/seastar,bowlofstew/scylla,scylladb/scylla-seastar,gwicke/scylla,acbellini/scylla,aruanruan/scylla,dwdm/scylla,flashbuckets/seastar,koolhazz/seastar,wildinto/seastar,shyamalschandra/seastar,kangkot/scylla,raphaelsc/seastar,raphaelsc/scylla,leejir/seastar
d102a4d533454c5149d79e2f81723e23958a4200
nw.cpp
nw.cpp
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include <cstdlib> #include <stdio.h> #include <sstream> #include <string> #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/scoped_temp_dir.h" #include "include/cef_app.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/cef_frame.h" #include "include/cef_runnable.h" #include "include/cef_web_plugin.h" #include "nw/client_handler.h" #include "nw/client_switches.h" #include "nw/common/zip.h" #include "nw/nw.h" #include "nw/string_util.h" #include "nw/util.h" #if defined(OS_WIN) #include "base/string16.h" #endif namespace { bool MakePathAbsolute(FilePath* file_path) { DCHECK(file_path); FilePath current_directory; if (!file_util::GetCurrentDirectory(&current_directory)) return false; if (file_path->IsAbsolute()) return true; if (current_directory.empty()) return file_util::AbsolutePath(file_path); if (!current_directory.IsAbsolute()) return false; *file_path = current_directory.Append(*file_path); return true; } void ManifestConvertRelativePaths( FilePath path, base::DictionaryValue* manifest) { if (manifest->HasKey(nw::kmMain)) { #if defined(OS_WIN) string16 out; #else std::string out; #endif if (!manifest->GetString(nw::kmMain, &out)) { manifest->Remove(nw::kmMain, NULL); LOG(WARNING) << "'main' field in manifest must be a string."; return; } FilePath main_path = path.Append(out); #if defined(OS_WIN) string16 url(L"file://"); #else std::string url("file://"); #endif manifest->SetString(nw::kmMain, url + main_path.value()); } else { LOG(WARNING) << "'main' field in manifest should be specifed."; } } bool ExtractPackage(const FilePath& zip_file, FilePath* where) { // Auto clean our temporary directory static scoped_ptr<ScopedTempDir> scoped_temp_dir; if (!file_util::CreateNewTempDirectory("nw", where)) { LOG(ERROR) << "Unable to create temporary directory."; return false; } scoped_temp_dir.reset(new ScopedTempDir()); if (!scoped_temp_dir->Set(*where)) { LOG(ERROR) << "Unable to set temporary directory."; return false; } return zip::Unzip(zip_file, *where); } } // namespace CefRefPtr<ClientHandler> g_handler; CefRefPtr<CefCommandLine> g_command_line; // Don't bother with lifetime since it's used through out the program base::DictionaryValue* g_manifest = NULL; base::DictionaryValue* g_features = NULL; CefRefPtr<CefBrowser> AppGetBrowser() { if (!g_handler.get()) return NULL; return g_handler->GetBrowser(); } CefWindowHandle AppGetMainHwnd() { if (!g_handler.get()) return NULL; return g_handler->GetMainHwnd(); } bool AppInitManifest() { FilePath path; if (!g_command_line->HasArguments()) { // See itself as a package (allowing standalone) path = FilePath(g_command_line->GetProgram()); } else { // Get first argument CefCommandLine::ArgumentList arguments; g_command_line->GetArguments(arguments); path = FilePath(arguments[0]); if (!file_util::PathExists(path)) { LOG(WARNING) << "Package does not exist."; return false; } } // Convert to absoulute path if (!MakePathAbsolute(&path)) { DLOG(ERROR) << "Cannot make absolute path from " << path.value(); } // If it's a file then try to extract from it if (!file_util::DirectoryExists(path)) { DLOG(INFO) << "Extracting packaging..."; FilePath zip_file(path); if (!ExtractPackage(zip_file, &path)) { LOG(ERROR) << "Unable to extract package."; return false; } } FilePath manifest_path = path.Append("package.json"); if (!file_util::PathExists(manifest_path)) { LOG(ERROR) << "No 'package.json' in package."; return false; } // Parse file std::string error; JSONFileValueSerializer serializer(manifest_path); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error)); if (!root.get()) { if (error.empty()) { LOG(ERROR) << "It's not able to read the manifest file."; } else { LOG(ERROR) << "Manifest parsing error: " << error; } return false; } if (!root->IsType(Value::TYPE_DICTIONARY)) { LOG(ERROR) << "Manifest file is invalid, we need a dictionary type"; return false; } // Save result in global g_manifest = static_cast<DictionaryValue*>(root.release()); ManifestConvertRelativePaths(path, g_manifest); // And save the root path g_manifest->SetString(nw::kmRoot, path.value()); g_manifest->GetDictionary(nw::kmWebkit, &g_features); return true; } void AppInitCommandLine(int argc, const char* const* argv) { g_command_line = CefCommandLine::CreateCommandLine(); #if defined(OS_WIN) g_command_line->InitFromString(::GetCommandLineW()); #else g_command_line->InitFromArgv(argc, argv); #endif if (!AppInitManifest()) { // TODO show an empty page } if (g_manifest == NULL) g_manifest = new base::DictionaryValue(); } // Returns the application command line object. CefRefPtr<CefCommandLine> AppGetCommandLine() { return g_command_line; } // Returns the manifest. base::DictionaryValue* AppGetManifest() { return g_manifest; } bool ManifestIsFeatureEnabled(const char* name, bool default_value) { if (!g_features) return default_value; bool result = default_value; g_features->GetBoolean(name, &result); return result; } // Returns the application settings based on command line arguments. void AppGetSettings(CefSettings& settings, CefRefPtr<ClientApp> app) { ASSERT(app.get()); ASSERT(g_command_line.get()); if (!g_command_line.get()) return; CefString str; #if defined(OS_WIN) settings.multi_threaded_message_loop = ManifestIsFeatureEnabled(nw::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = g_command_line->GetSwitchValue(nw::kCachePath); // Retrieve command-line proxy configuration, if any. bool has_proxy = false; cef_proxy_type_t proxy_type = PROXY_TYPE_DIRECT; CefString proxy_config; if (ManifestIsFeatureEnabled(nw::kProxyType)) { std::string str = g_command_line->GetSwitchValue(nw::kProxyType); if (str == nw::kProxyType_Direct) { has_proxy = true; proxy_type = PROXY_TYPE_DIRECT; } else if (str == nw::kProxyType_Named || str == nw::kProxyType_Pac) { proxy_config = g_command_line->GetSwitchValue(nw::kProxyConfig); if (!proxy_config.empty()) { has_proxy = true; proxy_type = (str == nw::kProxyType_Named? PROXY_TYPE_NAMED:PROXY_TYPE_PAC_STRING); } } } if (has_proxy) { // Provide a ClientApp instance to handle proxy resolution. app->SetProxyConfig(proxy_type, proxy_config); } } // Returns the application browser settings based on command line arguments. void AppGetBrowserSettings(CefBrowserSettings& settings) { ASSERT(g_command_line.get()); if (!g_command_line.get()) return; // Since we're running local pages, some values are sure settings.javascript_disabled = false; settings.javascript_open_windows_disallowed = false; settings.javascript_close_windows_disallowed = false; settings.javascript_access_clipboard_disallowed = false; settings.dom_paste_disabled = false; settings.universal_access_from_file_urls_allowed = true; settings.file_access_from_file_urls_allowed = true; settings.web_security_disabled = true; settings.xss_auditor_enabled = false; settings.image_load_disabled = false; settings.hyperlink_auditing_disabled = true; settings.local_storage_disabled = false; settings.databases_disabled = false; settings.application_cache_disabled = false; CefString(&settings.default_encoding) = g_command_line->GetSwitchValue(nw::kDefaultEncoding); settings.encoding_detector_enabled = ManifestIsFeatureEnabled(nw::kEncodingDetectorEnabled); settings.remote_fonts_disabled = ManifestIsFeatureEnabled(nw::kRemoteFontsDisabled); settings.caret_browsing_enabled = ManifestIsFeatureEnabled(nw::kCaretBrowsingEnabled); settings.java_disabled = ManifestIsFeatureEnabled(nw::kJavaDisabled); settings.plugins_disabled = ManifestIsFeatureEnabled(nw::kPluginsDisabled); settings.shrink_standalone_images_to_fit = ManifestIsFeatureEnabled(nw::kShrinkStandaloneImagesToFit); settings.site_specific_quirks_disabled = ManifestIsFeatureEnabled(nw::kSiteSpecificQuirksDisabled); settings.text_area_resize_disabled = ManifestIsFeatureEnabled(nw::kTextAreaResizeDisabled); settings.page_cache_disabled = ManifestIsFeatureEnabled(nw::kPageCacheDisabled); settings.tab_to_links_disabled = ManifestIsFeatureEnabled(nw::kTabToLinksDisabled); settings.user_style_sheet_enabled = ManifestIsFeatureEnabled(nw::kUserStyleSheetEnabled); CefString(&settings.user_style_sheet_location) = g_command_line->GetSwitchValue(nw::kUserStyleSheetLocation); settings.author_and_user_styles_disabled = ManifestIsFeatureEnabled(nw::kAuthorAndUserStylesDisabled); settings.webgl_disabled = ManifestIsFeatureEnabled(nw::kWebglDisabled); settings.accelerated_compositing_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedCompositingDisabled); settings.accelerated_layers_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedLayersDisabled); settings.accelerated_video_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedVideoDisabled); settings.accelerated_2d_canvas_disabled = ManifestIsFeatureEnabled(nw::kAcceledated2dCanvasDisabled); settings.accelerated_painting_enabled = ManifestIsFeatureEnabled(nw::kAcceleratedPaintingEnabled); settings.accelerated_filters_enabled = ManifestIsFeatureEnabled(nw::kAcceleratedFiltersEnabled); settings.accelerated_plugins_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedPluginsDisabled); settings.developer_tools_disabled = ManifestIsFeatureEnabled(nw::kDeveloperToolsDisabled); settings.fullscreen_enabled = ManifestIsFeatureEnabled(nw::kFullscreenEnabled); }
// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include <cstdlib> #include <stdio.h> #include <sstream> #include <string> #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/scoped_temp_dir.h" #include "include/cef_app.h" #include "include/cef_browser.h" #include "include/cef_command_line.h" #include "include/cef_frame.h" #include "include/cef_runnable.h" #include "include/cef_web_plugin.h" #include "nw/client_handler.h" #include "nw/client_switches.h" #include "nw/common/zip.h" #include "nw/nw.h" #include "nw/string_util.h" #include "nw/util.h" #if defined(OS_WIN) #include "base/string16.h" #endif namespace { bool MakePathAbsolute(FilePath* file_path) { DCHECK(file_path); FilePath current_directory; if (!file_util::GetCurrentDirectory(&current_directory)) return false; if (file_path->IsAbsolute()) return true; if (current_directory.empty()) return file_util::AbsolutePath(file_path); if (!current_directory.IsAbsolute()) return false; *file_path = current_directory.Append(*file_path); return true; } void ManifestConvertRelativePaths( FilePath path, base::DictionaryValue* manifest) { if (manifest->HasKey(nw::kmMain)) { string16 out; if (!manifest->GetString(nw::kmMain, &out)) { manifest->Remove(nw::kmMain, NULL); LOG(WARNING) << "'main' field in manifest must be a string."; return; } FilePath main_path = path.Append(out); string16 url(L"file://"); manifest->SetString(nw::kmMain, url + main_path.value()); } else { LOG(WARNING) << "'main' field in manifest should be specifed."; } } bool ExtractPackage(const FilePath& zip_file, FilePath* where) { // Auto clean our temporary directory static scoped_ptr<ScopedTempDir> scoped_temp_dir; if (!file_util::CreateNewTempDirectory("nw", where)) { LOG(ERROR) << "Unable to create temporary directory."; return false; } scoped_temp_dir.reset(new ScopedTempDir()); if (!scoped_temp_dir->Set(*where)) { LOG(ERROR) << "Unable to set temporary directory."; return false; } return zip::Unzip(zip_file, *where); } } // namespace CefRefPtr<ClientHandler> g_handler; CefRefPtr<CefCommandLine> g_command_line; // Don't bother with lifetime since it's used through out the program base::DictionaryValue* g_manifest = NULL; base::DictionaryValue* g_features = NULL; CefRefPtr<CefBrowser> AppGetBrowser() { if (!g_handler.get()) return NULL; return g_handler->GetBrowser(); } CefWindowHandle AppGetMainHwnd() { if (!g_handler.get()) return NULL; return g_handler->GetMainHwnd(); } bool AppInitManifest() { FilePath path; if (!g_command_line->HasArguments()) { // See itself as a package (allowing standalone) path = FilePath(g_command_line->GetProgram()); } else { // Get first argument CefCommandLine::ArgumentList arguments; g_command_line->GetArguments(arguments); path = FilePath(arguments[0]); if (!file_util::PathExists(path)) { LOG(WARNING) << "Package does not exist."; return false; } } // Convert to absoulute path if (!MakePathAbsolute(&path)) { DLOG(ERROR) << "Cannot make absolute path from " << path.value(); } // If it's a file then try to extract from it if (!file_util::DirectoryExists(path)) { DLOG(INFO) << "Extracting packaging..."; FilePath zip_file(path); if (!ExtractPackage(zip_file, &path)) { LOG(ERROR) << "Unable to extract package."; return false; } } FilePath manifest_path = path.Append("package.json"); if (!file_util::PathExists(manifest_path)) { LOG(ERROR) << "No 'package.json' in package."; return false; } // Parse file std::string error; JSONFileValueSerializer serializer(manifest_path); scoped_ptr<Value> root(serializer.Deserialize(NULL, &error)); if (!root.get()) { if (error.empty()) { LOG(ERROR) << "It's not able to read the manifest file."; } else { LOG(ERROR) << "Manifest parsing error: " << error; } return false; } if (!root->IsType(Value::TYPE_DICTIONARY)) { LOG(ERROR) << "Manifest file is invalid, we need a dictionary type"; return false; } // Save result in global g_manifest = static_cast<DictionaryValue*>(root.release()); ManifestConvertRelativePaths(path, g_manifest); // And save the root path g_manifest->SetString(nw::kmRoot, path.value()); g_manifest->GetDictionary(nw::kmWebkit, &g_features); return true; } void AppInitCommandLine(int argc, const char* const* argv) { g_command_line = CefCommandLine::CreateCommandLine(); #if defined(OS_WIN) g_command_line->InitFromString(::GetCommandLineW()); #else g_command_line->InitFromArgv(argc, argv); #endif if (!AppInitManifest()) { // TODO show an empty page } if (g_manifest == NULL) g_manifest = new base::DictionaryValue(); } // Returns the application command line object. CefRefPtr<CefCommandLine> AppGetCommandLine() { return g_command_line; } // Returns the manifest. base::DictionaryValue* AppGetManifest() { return g_manifest; } bool ManifestIsFeatureEnabled(const char* name, bool default_value) { if (!g_features) return default_value; bool result = default_value; g_features->GetBoolean(name, &result); return result; } // Returns the application settings based on command line arguments. void AppGetSettings(CefSettings& settings, CefRefPtr<ClientApp> app) { ASSERT(app.get()); ASSERT(g_command_line.get()); if (!g_command_line.get()) return; CefString str; #if defined(OS_WIN) settings.multi_threaded_message_loop = ManifestIsFeatureEnabled(nw::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = g_command_line->GetSwitchValue(nw::kCachePath); // Retrieve command-line proxy configuration, if any. bool has_proxy = false; cef_proxy_type_t proxy_type = PROXY_TYPE_DIRECT; CefString proxy_config; if (ManifestIsFeatureEnabled(nw::kProxyType)) { std::string str = g_command_line->GetSwitchValue(nw::kProxyType); if (str == nw::kProxyType_Direct) { has_proxy = true; proxy_type = PROXY_TYPE_DIRECT; } else if (str == nw::kProxyType_Named || str == nw::kProxyType_Pac) { proxy_config = g_command_line->GetSwitchValue(nw::kProxyConfig); if (!proxy_config.empty()) { has_proxy = true; proxy_type = (str == nw::kProxyType_Named? PROXY_TYPE_NAMED:PROXY_TYPE_PAC_STRING); } } } if (has_proxy) { // Provide a ClientApp instance to handle proxy resolution. app->SetProxyConfig(proxy_type, proxy_config); } } // Returns the application browser settings based on command line arguments. void AppGetBrowserSettings(CefBrowserSettings& settings) { ASSERT(g_command_line.get()); if (!g_command_line.get()) return; // Since we're running local pages, some values are sure settings.javascript_disabled = false; settings.javascript_open_windows_disallowed = false; settings.javascript_close_windows_disallowed = false; settings.javascript_access_clipboard_disallowed = false; settings.dom_paste_disabled = false; settings.universal_access_from_file_urls_allowed = true; settings.file_access_from_file_urls_allowed = true; settings.web_security_disabled = true; settings.xss_auditor_enabled = false; settings.image_load_disabled = false; settings.hyperlink_auditing_disabled = true; settings.local_storage_disabled = false; settings.databases_disabled = false; settings.application_cache_disabled = false; CefString(&settings.default_encoding) = g_command_line->GetSwitchValue(nw::kDefaultEncoding); settings.encoding_detector_enabled = ManifestIsFeatureEnabled(nw::kEncodingDetectorEnabled); settings.remote_fonts_disabled = ManifestIsFeatureEnabled(nw::kRemoteFontsDisabled); settings.caret_browsing_enabled = ManifestIsFeatureEnabled(nw::kCaretBrowsingEnabled); settings.java_disabled = ManifestIsFeatureEnabled(nw::kJavaDisabled); settings.plugins_disabled = ManifestIsFeatureEnabled(nw::kPluginsDisabled); settings.shrink_standalone_images_to_fit = ManifestIsFeatureEnabled(nw::kShrinkStandaloneImagesToFit); settings.site_specific_quirks_disabled = ManifestIsFeatureEnabled(nw::kSiteSpecificQuirksDisabled); settings.text_area_resize_disabled = ManifestIsFeatureEnabled(nw::kTextAreaResizeDisabled); settings.page_cache_disabled = ManifestIsFeatureEnabled(nw::kPageCacheDisabled); settings.tab_to_links_disabled = ManifestIsFeatureEnabled(nw::kTabToLinksDisabled); settings.user_style_sheet_enabled = ManifestIsFeatureEnabled(nw::kUserStyleSheetEnabled); CefString(&settings.user_style_sheet_location) = g_command_line->GetSwitchValue(nw::kUserStyleSheetLocation); settings.author_and_user_styles_disabled = ManifestIsFeatureEnabled(nw::kAuthorAndUserStylesDisabled); settings.webgl_disabled = ManifestIsFeatureEnabled(nw::kWebglDisabled); settings.accelerated_compositing_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedCompositingDisabled); settings.accelerated_layers_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedLayersDisabled); settings.accelerated_video_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedVideoDisabled); settings.accelerated_2d_canvas_disabled = ManifestIsFeatureEnabled(nw::kAcceledated2dCanvasDisabled); settings.accelerated_painting_enabled = ManifestIsFeatureEnabled(nw::kAcceleratedPaintingEnabled); settings.accelerated_filters_enabled = ManifestIsFeatureEnabled(nw::kAcceleratedFiltersEnabled); settings.accelerated_plugins_disabled = ManifestIsFeatureEnabled(nw::kAcceleratedPluginsDisabled); settings.developer_tools_disabled = ManifestIsFeatureEnabled(nw::kDeveloperToolsDisabled); settings.fullscreen_enabled = ManifestIsFeatureEnabled(nw::kFullscreenEnabled); }
Use string16 when manipulating FilePath and string
Use string16 when manipulating FilePath and string
C++
mit
dougmolineux/nw.js,Sunggil/nw.js,advisory/nw.js,zhangtianye/node-webkit,sumyfly/nw.js,initialjk/node-webkit,wakermahmud/nw.js,angeliaz/nw.js,alex-zhang/nw.js,techlabs28/nw.js,luiseduardohdbackup/nw.js,baiwyc119/nw.js,wakermahmud/nw.js,amoylel/nw.js,chinakids/nw.js,artBrown/nw.js,angeliaz/nw.js,iesus17/nw.js,VolosSoftware/nw.js,jomaf1010/nw.js,luisbrito/nw.js,AustinKwang/nw.js,askdaddy/nw.js,KaminoDice/nw.js,luiseduardohdbackup/nw.js,Jonekee/nw.js,liu78778/node-webkit,belmer/nw.js,xzmagic/nw.js,zhangweiabc/nw.js,liu78778/node-webkit,erickuofucker/nw.js,jomolinare/nw.js,KaminoDice/nw.js,iesus17/nw.js,dushu1203/nw.js,alex-zhang/nw.js,jomaf1010/nw.js,mcdongWang/nwjs_Chinese,Sunggil/nw.js,parksangkil/nw.js,tanzhihang/nw.js,pdx1989/nw.js,parksangkil/nw.js,wpsmith/nw.js,dushu1203/nw.js,chinakids/nw.js,mylikes/nw.js,youprofit/nw.js,M4sse/nw.js,initialjk/node-webkit,nwjs/nw.js,yshyee/nw.js,mauricionr/nw.js,PUSEN/nw.js,zcczcw/nw.js,parlaylabs/nw.js,yshyee/nw.js,zhaosichao/nw.js,belmer/nw.js,Wombatpm/node-webkit,iesus17/nw.js,jaruba/nw.js,fancycode/node-webkit,eprincev-egor/nw.js,wpsmith/nw.js,nwjs/nw.js,yshyee/nw.js,trueinteractions/tint,ondra-novak/nw.js,VolosSoftware/nw.js,chinakids/nw.js,KaminoDice/nw.js,Ivshti/node-webkit,mcdongWang/nwjs_Chinese,alex-zhang/nw.js,occupytheweb/nw.js,happy-barrage/nw.js,jomolinare/nw.js,haroldoramirez/nw.js,AustinKwang/nw.js,advisory/nw.js,wakermahmud/nw.js,jomolinare/nw.js,haroldoramirez/nw.js,AustinKwang/nw.js,trojanspike/nw.js,AustinKwang/nw.js,PUSEN/nw.js,pztrick/nw.js,chengky/nw.js,Jonekee/nw.js,composite/nw.js,mauricionr/nw.js,yshyee/nw.js,zhangweiabc/nw.js,jaruba/nw.js,Arteris/nw.js,eprincev-egor/nw.js,parksangkil/nw.js,tshinnic/nw.js,InnerAc/nw.js,Ivshti/node-webkit,280455936/nw.js,GabrielNicolasAvellaneda/nw.js,amoylel/nw.js,luiseduardohdbackup/nw.js,zhangtianye/node-webkit,liu78778/node-webkit,bright-sparks/nw.js,artBrown/nw.js,xzmagic/nw.js,tanzhihang/nw.js,imshibaji/nw.js,jomaf1010/nw.js,xebitstudios/nw.js,jqk6/nw.js,M4sse/nw.js,occupytheweb/nw.js,Wombatpm/node-webkit,zhaosichao/nw.js,trevorlinton/tint,xebitstudios/nw.js,parksangkil/nw.js,angeliaz/nw.js,lifeinoppo/nw.js,xzmagic/nw.js,pztrick/nw.js,pztrick/nw.js,lifeinoppo/nw.js,luiseduardohdbackup/nw.js,GabrielNicolasAvellaneda/nw.js,tanzhihang/nw.js,jaruba/nw.js,chengky/nw.js,jqk6/nw.js,redgecombe/nw.js,KaminoDice/nw.js,280455936/nw.js,happy-barrage/nw.js,GabrielNicolasAvellaneda/nw.js,ondra-novak/nw.js,bright-sparks/nw.js,askdaddy/nw.js,dougmolineux/nw.js,M4sse/nw.js,wpsmith/nw.js,trueinteractions/tint,nwjs/nw.js,p5150j/nw.js,luiseduardohdbackup/nw.js,AustinKwang/nw.js,M4sse/nw.js,happy-barrage/nw.js,dushu1203/nw.js,mauricionr/nw.js,amoylel/nw.js,iesus17/nw.js,GabrielNicolasAvellaneda/nw.js,xebitstudios/nw.js,tshinnic/nw.js,InnerAc/nw.js,luiseduardohdbackup/nw.js,belmer/nw.js,occupytheweb/nw.js,Ivshti/node-webkit,erickuofucker/nw.js,mcanthony/nw.js,VolosSoftware/nw.js,mcdongWang/nwjs_Chinese,initialjk/node-webkit,wpsmith/nw.js,trojanspike/nw.js,dougmolineux/nw.js,imshibaji/nw.js,happy-barrage/nw.js,markYoungH/nw.js,KaminoDice/nw.js,tshinnic/nw.js,iesus17/nw.js,baiwyc119/nw.js,lidxgz/nw.js,techlabs28/nw.js,angeliaz/nw.js,XenonDevelops/nw.js,glizer/nw.js,Ivshti/node-webkit,ysjian/nw.js,luisbrito/nw.js,weave-lab/nw.js,luiseduardohdbackup/nw.js,tshinnic/nw.js,trevorlinton/tint,markYoungH/nw.js,VolosSoftware/nw.js,jomaf1010/nw.js,xebitstudios/nw.js,glizer/nw.js,ezshine/nw.js,composite/nw.js,dushu1203/nw.js,occupytheweb/nw.js,kurainooni/nw.js,bright-sparks/nw.js,youprofit/nw.js,chengky/nw.js,initialjk/node-webkit,AustinKwang/nw.js,redgecombe/nw.js,weave-lab/nw.js,mcanthony/nw.js,XenonDevelops/nw.js,redgecombe/nw.js,erickuofucker/nw.js,chengky/nw.js,Jonekee/nw.js,luisbrito/nw.js,trojanspike/nw.js,xebitstudios/nw.js,wakermahmud/nw.js,glizer/nw.js,jomolinare/nw.js,bright-sparks/nw.js,KaminoDice/nw.js,mauricionr/nw.js,trueinteractions/tint,RobertoMalatesta/nw.js,280455936/nw.js,sumyfly/nw.js,sumyfly/nw.js,mvinan/nw.js,parlaylabs/nw.js,baiwyc119/nw.js,PUSEN/nw.js,chengky/nw.js,nwjs/nw.js,jomolinare/nw.js,advisory/nw.js,parksangkil/nw.js,initialjk/node-webkit,dushu1203/nw.js,lidxgz/nw.js,angeliaz/nw.js,imshibaji/nw.js,pztrick/nw.js,Wombatpm/node-webkit,techlabs28/nw.js,tshinnic/nw.js,mcdongWang/nwjs_Chinese,p5150j/nw.js,trueinteractions/tint,dushu1203/nw.js,weave-lab/nw.js,jaruba/nw.js,baiwyc119/nw.js,belmer/nw.js,wpsmith/nw.js,redgecombe/nw.js,pdx1989/nw.js,artBrown/nw.js,dougmolineux/nw.js,pdx1989/nw.js,youprofit/nw.js,zhangweiabc/nw.js,youprofit/nw.js,angeliaz/nw.js,chengky/nw.js,xzmagic/nw.js,pztrick/nw.js,zhangtianye/node-webkit,VolosSoftware/nw.js,chinakids/nw.js,yshyee/nw.js,mcanthony/nw.js,zhangweiabc/nw.js,glizer/nw.js,eprincev-egor/nw.js,ondra-novak/nw.js,luisbrito/nw.js,Sunggil/nw.js,artBrown/nw.js,redgecombe/nw.js,trueinteractions/tint,amoylel/nw.js,KaminoDice/nw.js,mvinan/nw.js,chengky/nw.js,zcczcw/nw.js,amoylel/nw.js,haroldoramirez/nw.js,Jonekee/nw.js,parlaylabs/nw.js,p5150j/nw.js,glizer/nw.js,jqk6/nw.js,Jonekee/nw.js,Sunggil/nw.js,composite/nw.js,GabrielNicolasAvellaneda/nw.js,pztrick/nw.js,chinakids/nw.js,zhaosichao/nw.js,InnerAc/nw.js,xzmagic/nw.js,ondra-novak/nw.js,lifeinoppo/nw.js,trojanspike/nw.js,tanzhihang/nw.js,jqk6/nw.js,fancycode/node-webkit,trevorlinton/tint,chinakids/nw.js,M4sse/nw.js,Arteris/nw.js,liu78778/node-webkit,askdaddy/nw.js,mylikes/nw.js,happy-barrage/nw.js,zhaosichao/nw.js,RobertoMalatesta/nw.js,weave-lab/nw.js,ezshine/nw.js,amoylel/nw.js,lifeinoppo/nw.js,angeliaz/nw.js,Ivshti/node-webkit,liu78778/node-webkit,jaruba/nw.js,pdx1989/nw.js,tanzhihang/nw.js,youprofit/nw.js,parlaylabs/nw.js,kurainooni/nw.js,lidxgz/nw.js,glizer/nw.js,zhaosichao/nw.js,ezshine/nw.js,Arteris/nw.js,bright-sparks/nw.js,lidxgz/nw.js,tshinnic/nw.js,bright-sparks/nw.js,Wombatpm/node-webkit,InnerAc/nw.js,lidxgz/nw.js,jomaf1010/nw.js,jomaf1010/nw.js,techlabs28/nw.js,luisbrito/nw.js,Sunggil/nw.js,occupytheweb/nw.js,luisbrito/nw.js,280455936/nw.js,askdaddy/nw.js,Jonekee/nw.js,zhangtianye/node-webkit,mcanthony/nw.js,RobertoMalatesta/nw.js,dougmolineux/nw.js,lifeinoppo/nw.js,zcczcw/nw.js,composite/nw.js,amoylel/nw.js,M4sse/nw.js,xzmagic/nw.js,M4sse/nw.js,alex-zhang/nw.js,lidxgz/nw.js,parlaylabs/nw.js,zhangweiabc/nw.js,lifeinoppo/nw.js,wakermahmud/nw.js,fancycode/node-webkit,eprincev-egor/nw.js,haroldoramirez/nw.js,ysjian/nw.js,composite/nw.js,fancycode/node-webkit,dougmolineux/nw.js,zcczcw/nw.js,kurainooni/nw.js,iesus17/nw.js,pdx1989/nw.js,lidxgz/nw.js,280455936/nw.js,yshyee/nw.js,p5150j/nw.js,tanzhihang/nw.js,XenonDevelops/nw.js,ysjian/nw.js,yshyee/nw.js,nwjs/nw.js,PUSEN/nw.js,glizer/nw.js,ondra-novak/nw.js,trevorlinton/tint,trevorlinton/tint,belmer/nw.js,mcanthony/nw.js,mvinan/nw.js,pztrick/nw.js,zhangtianye/node-webkit,kurainooni/nw.js,XenonDevelops/nw.js,mvinan/nw.js,parksangkil/nw.js,mylikes/nw.js,parksangkil/nw.js,VolosSoftware/nw.js,techlabs28/nw.js,sumyfly/nw.js,jomolinare/nw.js,happy-barrage/nw.js,composite/nw.js,zhaosichao/nw.js,XenonDevelops/nw.js,iesus17/nw.js,luisbrito/nw.js,ysjian/nw.js,artBrown/nw.js,redgecombe/nw.js,weave-lab/nw.js,nwjs/nw.js,haroldoramirez/nw.js,imshibaji/nw.js,jomolinare/nw.js,imshibaji/nw.js,weave-lab/nw.js,p5150j/nw.js,alex-zhang/nw.js,jqk6/nw.js,GabrielNicolasAvellaneda/nw.js,wakermahmud/nw.js,mylikes/nw.js,askdaddy/nw.js,initialjk/node-webkit,jqk6/nw.js,parlaylabs/nw.js,baiwyc119/nw.js,trueinteractions/tint,liu78778/node-webkit,kurainooni/nw.js,Wombatpm/node-webkit,VolosSoftware/nw.js,occupytheweb/nw.js,baiwyc119/nw.js,markYoungH/nw.js,alex-zhang/nw.js,mvinan/nw.js,techlabs28/nw.js,Sunggil/nw.js,mvinan/nw.js,Sunggil/nw.js,ysjian/nw.js,Arteris/nw.js,p5150j/nw.js,sumyfly/nw.js,advisory/nw.js,trevorlinton/tint,techlabs28/nw.js,zhangweiabc/nw.js,sumyfly/nw.js,pdx1989/nw.js,trojanspike/nw.js,imshibaji/nw.js,erickuofucker/nw.js,fancycode/node-webkit,280455936/nw.js,mcdongWang/nwjs_Chinese,wakermahmud/nw.js,ondra-novak/nw.js,jomaf1010/nw.js,xebitstudios/nw.js,zcczcw/nw.js,youprofit/nw.js,zhaosichao/nw.js,ysjian/nw.js,zcczcw/nw.js,ondra-novak/nw.js,XenonDevelops/nw.js,chinakids/nw.js,jaruba/nw.js,mauricionr/nw.js,imshibaji/nw.js,zhangweiabc/nw.js,mcanthony/nw.js,mcdongWang/nwjs_Chinese,Jonekee/nw.js,bright-sparks/nw.js,initialjk/node-webkit,alex-zhang/nw.js,dougmolineux/nw.js,trojanspike/nw.js,trueinteractions/tint,sumyfly/nw.js,markYoungH/nw.js,askdaddy/nw.js,mcanthony/nw.js,belmer/nw.js,mvinan/nw.js,Arteris/nw.js,jqk6/nw.js,RobertoMalatesta/nw.js,InnerAc/nw.js,composite/nw.js,280455936/nw.js,eprincev-egor/nw.js,RobertoMalatesta/nw.js,ezshine/nw.js,erickuofucker/nw.js,happy-barrage/nw.js,p5150j/nw.js,ezshine/nw.js,ysjian/nw.js,wpsmith/nw.js,fancycode/node-webkit,GabrielNicolasAvellaneda/nw.js,zhangtianye/node-webkit,markYoungH/nw.js,mauricionr/nw.js,mylikes/nw.js,erickuofucker/nw.js,markYoungH/nw.js,kurainooni/nw.js,RobertoMalatesta/nw.js,ezshine/nw.js,tshinnic/nw.js,xebitstudios/nw.js,PUSEN/nw.js,haroldoramirez/nw.js,XenonDevelops/nw.js,eprincev-egor/nw.js,trojanspike/nw.js,Wombatpm/node-webkit,youprofit/nw.js,markYoungH/nw.js,InnerAc/nw.js,occupytheweb/nw.js,parlaylabs/nw.js,PUSEN/nw.js,advisory/nw.js,Ivshti/node-webkit,Arteris/nw.js,tanzhihang/nw.js,mylikes/nw.js,dushu1203/nw.js,AustinKwang/nw.js,redgecombe/nw.js,kurainooni/nw.js,erickuofucker/nw.js,jaruba/nw.js,Wombatpm/node-webkit,InnerAc/nw.js,Arteris/nw.js,RobertoMalatesta/nw.js,advisory/nw.js,lifeinoppo/nw.js,ezshine/nw.js,mylikes/nw.js,artBrown/nw.js,advisory/nw.js,xzmagic/nw.js,zcczcw/nw.js,artBrown/nw.js,PUSEN/nw.js,askdaddy/nw.js,belmer/nw.js,pdx1989/nw.js,weave-lab/nw.js,haroldoramirez/nw.js,baiwyc119/nw.js,eprincev-egor/nw.js,wpsmith/nw.js
cdc921b6699580f801fb7a0d0c43182c1ae0bce0
core/src/wallet/algorand/operations/AlgorandOperation.cpp
core/src/wallet/algorand/operations/AlgorandOperation.cpp
/* * AlgorandOperation * * Created by Rémi Barjon on 12/05/2020. * * The MIT License (MIT) * * Copyright (c) 2020 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include "AlgorandOperation.hpp" #include "../AlgorandAccount.hpp" #include "../transactions/api_impl/AlgorandTransactionImpl.hpp" #include <wallet/common/database/OperationDatabaseHelper.h> #include <fmt/format.h> #include <sys/stat.h> namespace ledger { namespace core { namespace algorand { Operation::Operation(const std::shared_ptr<AbstractAccount>& account) : ::ledger::core::OperationApi(account) , transaction(nullptr) , algorandType{} {} Operation::Operation(const std::shared_ptr<AbstractAccount>& account, const model::Transaction& txn) : Operation(account) { setTransaction(txn); inflate(); } api::AlgorandOperationType Operation::getAlgorandOperationType() const { return algorandType; } std::shared_ptr<api::AlgorandTransaction> Operation::getTransaction() const { return transaction; } bool Operation::isComplete() { return static_cast<bool>(transaction); } void Operation::refreshUid(const std::string&) { const auto& txn = getTransactionData(); const auto id = fmt::format("{}+{}", *txn.header.id, api::to_string(algorandType)); getBackend().uid = OperationDatabaseHelper::createUid(getBackend().accountUid, id, getOperationType()); } const model::Transaction& Operation::getTransactionData() const { return transaction->getTransactionData(); } void Operation::setTransaction(const model::Transaction& txn) { transaction = std::make_shared<AlgorandTransactionImpl>(txn); } void Operation::setAlgorandOperationType(api::AlgorandOperationType t) { algorandType = t; } void Operation::inflate() { if (!getAccount() || !transaction) { return; } inflateFromAccount(); inflateFromTransaction(); } void Operation::inflateFromAccount() { const auto& account = getAlgorandAccount(); getBackend().accountUid = account.getAccountUid(); getBackend().walletUid = account.getWallet()->getWalletUid(); getBackend().currencyName = account.getWallet()->getCurrency().name; getBackend().trust = std::make_shared<TrustIndicator>(); } void Operation::inflateFromTransaction() { inflateDate(); inflateBlock(); inflateAmountAndFees(); inflateSenders(); inflateRecipients(); inflateType(); // inflateAmountAndFees must be called first inflateAlgorandOperationType(); refreshUid(); } void Operation::inflateDate() { const auto& txn = getTransactionData(); getBackend().date = std::chrono::system_clock::time_point( std::chrono::seconds(txn.header.timestamp.getValueOr(0))); } void Operation::inflateBlock() { const auto& txn = getTransactionData(); getBackend().block = [&]() { api::Block block; block.currencyName = getBackend().currencyName; if (txn.header.round) { if (*txn.header.round > std::numeric_limits<int64_t>::max()) { throw make_exception(api::ErrorCode::OUT_OF_RANGE, "Block height exceeds maximum value"); } block.height = static_cast<int64_t>(*txn.header.round); block.blockHash = std::to_string(*txn.header.round); } if (txn.header.timestamp) { block.time = std::chrono::system_clock::time_point(std::chrono::seconds(*txn.header.timestamp)); } block.uid = BlockDatabaseHelper::createBlockUid(block); return block; }(); } void Operation::inflateAmountAndFees() { const auto& account = getAlgorandAccount().getAddress(); const auto& txn = getTransactionData(); auto amount = BigInt::ZERO; auto u64ToBigInt = [](uint64_t n) { return BigInt(static_cast<unsigned long long>(n)); }; if (account == txn.header.sender.toString()) { amount = amount - u64ToBigInt(txn.header.senderRewards.getValueOr(0)); getBackend().fees = u64ToBigInt(txn.header.fee); } if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (txn.header.sender == details.receiverAddr) { getBackend().amount = amount; return; } if (account == txn.header.sender.toString()) { amount = amount + u64ToBigInt(details.amount); } if (account == details.receiverAddr.toString()) { amount = amount + u64ToBigInt(details.amount); amount = amount + u64ToBigInt(txn.header.receiverRewards.getValueOr(0)); } if (details.closeAddr && account == details.closeAddr->toString()) { amount = amount + u64ToBigInt(details.closeAmount.getValueOr(0)); amount = amount + u64ToBigInt(txn.header.closeRewards.getValueOr(0)); } } getBackend().amount = amount; } void Operation::inflateSenders() { const auto& txn = getTransactionData(); getBackend().senders = { txn.header.sender.toString() }; } void Operation::inflateRecipients() { const auto& txn = getTransactionData(); getBackend().recipients = {}; if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); getBackend().recipients.push_back(details.receiverAddr.toString()); if (details.closeAddr) { getBackend().recipients.push_back(details.closeAddr->toString()); } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); getBackend().recipients.push_back(details.assetReceiver.toString()); if (details.assetCloseTo) { getBackend().recipients.push_back(details.assetCloseTo->toString()); } } } void Operation::inflateType() { const auto& account = getAlgorandAccount().getAddress(); const auto& txn = getTransactionData(); getBackend().type = api::OperationType::NONE; if (txn.header.sender.toString() == account) { getBackend().type = api::OperationType::SEND; } else if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (details.receiverAddr.toString() == account || details.closeAddr && details.closeAddr->toString() == account) { getBackend().type = api::OperationType::RECEIVE; } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); if (details.assetReceiver.toString() == account || details.assetCloseTo && details.assetCloseTo->toString() == account) { getBackend().type = api::OperationType::RECEIVE; } } if (getBackend().amount.isNegative()) { getBackend().amount = getBackend().amount.positive(); getBackend().type = api::OperationType::REWARDS; } } const Account& Operation::getAlgorandAccount() const { return static_cast<Account&>(*getAccount()); } void Operation::inflateAlgorandOperationType() { const auto& txn = transaction->getTransactionData(); if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (details.closeAddr) { algorandType = api::AlgorandOperationType::ACCOUNT_CLOSE; } else { algorandType = api::AlgorandOperationType::PAYMENT; } } else if (txn.header.type == model::constants::keyreg) { const auto& details = boost::get<model::KeyRegTxnFields>(txn.details); if (details.nonParticipation && !(*details.nonParticipation)) { algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_ONLINE; } else { algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_OFFLINE; } } else if (txn.header.type == model::constants::acfg) { const auto& details = boost::get<model::AssetConfigTxnFields>(txn.details); if (!details.assetId) { algorandType = api::AlgorandOperationType::ASSET_CREATE; } else if (!details.assetParams) { algorandType = api::AlgorandOperationType::ASSET_DESTROY; } else { algorandType = api::AlgorandOperationType::ASSET_RECONFIGURE; } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); if (details.assetSender) { algorandType = api::AlgorandOperationType::ASSET_REVOKE; } else if (details.assetCloseTo) { algorandType = api::AlgorandOperationType::ASSET_OPT_OUT; } else if (!details.assetAmount) { algorandType = api::AlgorandOperationType::ASSET_OPT_IN; } else { algorandType = api::AlgorandOperationType::ASSET_TRANSFER; } } else if (txn.header.type == model::constants::afreeze) { algorandType = api::AlgorandOperationType::ASSET_FREEZE; } else { algorandType = api::AlgorandOperationType::UNSUPPORTED; } } } // namespace algorand } // namespace core } // namespace ledger
/* * AlgorandOperation * * Created by Rémi Barjon on 12/05/2020. * * The MIT License (MIT) * * Copyright (c) 2020 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include "AlgorandOperation.hpp" #include "../AlgorandAccount.hpp" #include "../transactions/api_impl/AlgorandTransactionImpl.hpp" #include <wallet/common/database/OperationDatabaseHelper.h> #include <fmt/format.h> #include <sys/stat.h> namespace ledger { namespace core { namespace algorand { Operation::Operation(const std::shared_ptr<AbstractAccount>& account) : ::ledger::core::OperationApi(account) , transaction(nullptr) , algorandType{} {} Operation::Operation(const std::shared_ptr<AbstractAccount>& account, const model::Transaction& txn) : Operation(account) { setTransaction(txn); inflate(); } api::AlgorandOperationType Operation::getAlgorandOperationType() const { return algorandType; } std::shared_ptr<api::AlgorandTransaction> Operation::getTransaction() const { return transaction; } bool Operation::isComplete() { return static_cast<bool>(transaction); } void Operation::refreshUid(const std::string&) { const auto& txn = getTransactionData(); const auto id = fmt::format("{}+{}", *txn.header.id, api::to_string(algorandType)); getBackend().uid = OperationDatabaseHelper::createUid(getBackend().accountUid, id, getOperationType()); } const model::Transaction& Operation::getTransactionData() const { return transaction->getTransactionData(); } void Operation::setTransaction(const model::Transaction& txn) { transaction = std::make_shared<AlgorandTransactionImpl>(txn); } void Operation::setAlgorandOperationType(api::AlgorandOperationType t) { algorandType = t; } void Operation::inflate() { if (!getAccount() || !transaction) { return; } inflateFromAccount(); inflateFromTransaction(); } void Operation::inflateFromAccount() { const auto& account = getAlgorandAccount(); getBackend().accountUid = account.getAccountUid(); getBackend().walletUid = account.getWallet()->getWalletUid(); getBackend().currencyName = account.getWallet()->getCurrency().name; getBackend().trust = std::make_shared<TrustIndicator>(); } void Operation::inflateFromTransaction() { inflateDate(); inflateBlock(); inflateAmountAndFees(); inflateSenders(); inflateRecipients(); inflateType(); // inflateAmountAndFees must be called first inflateAlgorandOperationType(); refreshUid(); } void Operation::inflateDate() { const auto& txn = getTransactionData(); getBackend().date = std::chrono::system_clock::time_point( std::chrono::seconds(txn.header.timestamp.getValueOr(0))); } void Operation::inflateBlock() { const auto& txn = getTransactionData(); getBackend().block = [&]() { api::Block block; block.currencyName = getBackend().currencyName; if (txn.header.round) { if (*txn.header.round > std::numeric_limits<int64_t>::max()) { throw make_exception(api::ErrorCode::OUT_OF_RANGE, "Block height exceeds maximum value"); } block.height = static_cast<int64_t>(*txn.header.round); block.blockHash = std::to_string(*txn.header.round); } if (txn.header.timestamp) { block.time = std::chrono::system_clock::time_point(std::chrono::seconds(*txn.header.timestamp)); } block.uid = BlockDatabaseHelper::createBlockUid(block); return block; }(); } void Operation::inflateAmountAndFees() { const auto& account = getAlgorandAccount().getAddress(); const auto& txn = getTransactionData(); auto amount = BigInt::ZERO; auto u64ToBigInt = [](uint64_t n) { return BigInt(static_cast<unsigned long long>(n)); }; if (account == txn.header.sender.toString()) { amount = amount - u64ToBigInt(txn.header.senderRewards.getValueOr(0)); getBackend().fees = u64ToBigInt(txn.header.fee); } if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (txn.header.sender == details.receiverAddr) { getBackend().amount = amount; return; } if (account == txn.header.sender.toString()) { amount = amount + u64ToBigInt(details.amount); } if (account == details.receiverAddr.toString()) { amount = amount + u64ToBigInt(details.amount); amount = amount + u64ToBigInt(txn.header.receiverRewards.getValueOr(0)); } if (details.closeAddr && account == details.closeAddr->toString()) { amount = amount + u64ToBigInt(details.closeAmount.getValueOr(0)); amount = amount + u64ToBigInt(txn.header.closeRewards.getValueOr(0)); } } getBackend().amount = amount; } void Operation::inflateSenders() { const auto& txn = getTransactionData(); getBackend().senders = { txn.header.sender.toString() }; } void Operation::inflateRecipients() { const auto& txn = getTransactionData(); getBackend().recipients = {}; if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); getBackend().recipients.push_back(details.receiverAddr.toString()); if (details.closeAddr) { getBackend().recipients.push_back(details.closeAddr->toString()); } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); getBackend().recipients.push_back(details.assetReceiver.toString()); if (details.assetCloseTo) { getBackend().recipients.push_back(details.assetCloseTo->toString()); } } } void Operation::inflateType() { const auto& account = getAlgorandAccount().getAddress(); const auto& txn = getTransactionData(); getBackend().type = api::OperationType::NONE; if (txn.header.sender.toString() == account) { getBackend().type = api::OperationType::SEND; } else if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (details.receiverAddr.toString() == account || details.closeAddr && details.closeAddr->toString() == account) { getBackend().type = api::OperationType::RECEIVE; } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); if (details.assetReceiver.toString() == account || details.assetCloseTo && details.assetCloseTo->toString() == account) { getBackend().type = api::OperationType::RECEIVE; } } if (getBackend().amount.isNegative()) { getBackend().amount = getBackend().amount.positive(); getBackend().type = api::OperationType::REWARDS; } } const Account& Operation::getAlgorandAccount() const { return static_cast<Account&>(*getAccount()); } void Operation::inflateAlgorandOperationType() { const auto& txn = transaction->getTransactionData(); if (txn.header.type == model::constants::pay) { const auto& details = boost::get<model::PaymentTxnFields>(txn.details); if (details.closeAddr) { algorandType = api::AlgorandOperationType::ACCOUNT_CLOSE; } else { algorandType = api::AlgorandOperationType::PAYMENT; } } else if (txn.header.type == model::constants::keyreg) { const auto& details = boost::get<model::KeyRegTxnFields>(txn.details); if (details.nonParticipation && !(*details.nonParticipation)) { algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_ONLINE; } else { algorandType = api::AlgorandOperationType::ACCOUNT_REGISTER_OFFLINE; } } else if (txn.header.type == model::constants::acfg) { const auto& details = boost::get<model::AssetConfigTxnFields>(txn.details); if (!details.assetId) { algorandType = api::AlgorandOperationType::ASSET_CREATE; } else if (!details.assetParams) { algorandType = api::AlgorandOperationType::ASSET_DESTROY; } else { algorandType = api::AlgorandOperationType::ASSET_RECONFIGURE; } } else if (txn.header.type == model::constants::axfer) { const auto& details = boost::get<model::AssetTransferTxnFields>(txn.details); if (details.assetSender) { algorandType = api::AlgorandOperationType::ASSET_REVOKE; } else if (details.assetCloseTo) { algorandType = api::AlgorandOperationType::ASSET_OPT_OUT; } else if (!details.assetAmount || (*details.assetAmount == 0 && txn.header.sender == details.assetReceiver)) { algorandType = api::AlgorandOperationType::ASSET_OPT_IN; } else { algorandType = api::AlgorandOperationType::ASSET_TRANSFER; } } else if (txn.header.type == model::constants::afreeze) { algorandType = api::AlgorandOperationType::ASSET_FREEZE; } else { algorandType = api::AlgorandOperationType::UNSUPPORTED; } } } // namespace algorand } // namespace core } // namespace ledger
Fix Opt in detection for axfer transaction (#58)
Fix Opt in detection for axfer transaction (#58)
C++
mit
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
09f32fc0eb5eaf7fc18c6f342a5c34d8075856ce
tests/ExtruderPlanTest.cpp
tests/ExtruderPlanTest.cpp
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <numeric> //For calculating averages. #include <gtest/gtest.h> #include "../src/LayerPlan.h" //Code under test. namespace cura { /*! * A fixture containing some sets of GCodePaths to test with. */ class ExtruderPlanTestPathCollection { public: /*! * One path with 5 vertices printing a 1000x1000 micron square starting from * 0,0. */ std::vector<GCodePath> square; /*! * Three lines side by side, with two travel moves in between. */ std::vector<GCodePath> lines; /*! * Three lines side by side with travel moves in between, but adjusted flow. * * The first line gets 120% flow. * The second line gets 80% flow. * The third line gets 40% flow. */ std::vector<GCodePath> decreasing_flow; /*! * Three lines side by side with their speed factors adjusted. * * The first line gets 120% speed. * The second line gets 80% speed. * The third line gets 40% speed. */ std::vector<GCodePath> decreasing_speed; /*! * A series of paths with variable line width. * * This one has no travel moves in between. * The last path gets a width of 0. */ std::vector<GCodePath> variable_width; /*! * Configuration to print extruded paths with in the fixture. * * This config is referred to via pointer, so changing it will immediately * change it for all extruded paths. */ GCodePathConfig extrusion_config; /*! * Configuration to print travel paths with in the fixture. * * This config is referred to via pointer, so changing it will immediately * change it for all travel paths. */ GCodePathConfig travel_config; ExtruderPlanTestPathCollection() : extrusion_config( PrintFeatureType::OuterWall, /*line_width=*/400, /*layer_thickness=*/100, /*flow=*/1.0_r, GCodePathConfig::SpeedDerivatives(50, 1000, 10) ), travel_config( PrintFeatureType::MoveCombing, /*line_width=*/0, /*layer_thickness=*/100, /*flow=*/0.0_r, GCodePathConfig::SpeedDerivatives(120, 5000, 30) ) { const std::string mesh_id = "test_mesh"; constexpr Ratio flow_1 = 1.0_r; constexpr bool no_spiralize = false; constexpr Ratio speed_1 = 1.0_r; square.assign({GCodePath(extrusion_config, mesh_id, SpaceFillType::PolyLines, flow_1, no_spiralize, speed_1)}); square.back().points = { Point(0, 0), Point(1000, 0), Point(1000, 1000), Point(0, 1000), Point(0, 0) }; lines.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1) }); lines[0].points = {Point(0, 0), Point(1000, 0)}; lines[1].points = {Point(1000, 0), Point(1000, 400)}; lines[2].points = {Point(1000, 400), Point(0, 400)}; lines[3].points = {Point(0, 400), Point(0, 800)}; lines[4].points = {Point(0, 800), Point(1000, 800)}; constexpr Ratio flow_12 = 1.2_r; constexpr Ratio flow_08 = 0.8_r; constexpr Ratio flow_04 = 0.4_r; decreasing_flow.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_12, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_08, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_04, no_spiralize, speed_1) }); decreasing_flow[0].points = {Point(0, 0), Point(1000, 0)}; decreasing_flow[1].points = {Point(1000, 0), Point(1000, 400)}; decreasing_flow[2].points = {Point(1000, 400), Point(0, 400)}; decreasing_flow[3].points = {Point(0, 400), Point(0, 800)}; decreasing_flow[4].points = {Point(0, 800), Point(1000, 800)}; constexpr Ratio speed_12 = 1.2_r; constexpr Ratio speed_08 = 0.8_r; constexpr Ratio speed_04 = 0.4_r; decreasing_speed.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_12), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_08), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_04) }); decreasing_speed[0].points = {Point(0, 0), Point(1000, 0)}; decreasing_speed[1].points = {Point(1000, 0), Point(1000, 400)}; decreasing_speed[2].points = {Point(1000, 400), Point(0, 400)}; decreasing_speed[3].points = {Point(0, 400), Point(0, 800)}; decreasing_speed[4].points = {Point(0, 800), Point(1000, 800)}; variable_width.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.8_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.6_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.4_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.2_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.0_r, no_spiralize, speed_1), }); variable_width[0].points = {Point(0, 0), Point(1000, 0)}; variable_width[1].points = {Point(1000, 0), Point(2000, 0)}; variable_width[2].points = {Point(2000, 0), Point(3000, 0)}; variable_width[3].points = {Point(3000, 0), Point(4000, 0)}; variable_width[4].points = {Point(4000, 0), Point(5000, 0)}; variable_width[5].points = {Point(5000, 0), Point(6000, 0)}; } }; static ExtruderPlanTestPathCollection path_collection; /*! * Tests in this class get parameterized with a vector of GCodePaths to put in * the extruder plan, and an extruder plan to put it in. */ class ExtruderPlanPathsParameterizedTest : public testing::TestWithParam<std::vector<GCodePath>> { public: /*! * An extruder plan that can be used as a victim for testing. */ ExtruderPlan extruder_plan; ExtruderPlanPathsParameterizedTest() : extruder_plan( /*extruder=*/0, /*layer_nr=*/50, /*is_initial_layer=*/false, /*is_raft_layer=*/false, /*layer_thickness=*/100, FanSpeedLayerTimeSettings(), RetractionConfig() ) {} /*! * Helper method to calculate the flow rate of a path in mm3 per second. * \param path The path to calculate the flow rate of. * \return The flow rate, in cubic millimeters per second. */ double calculatePathFlow(const GCodePath& path) { return path.getExtrusionMM3perMM() * path.config->getSpeed() * path.speed_factor * path.speed_back_pressure_factor; } }; INSTANTIATE_TEST_CASE_P(ExtruderPlanTestInstantiation, ExtruderPlanPathsParameterizedTest, testing::Values( path_collection.square, path_collection.lines, path_collection.decreasing_flow, path_collection.decreasing_speed, path_collection.variable_width )); /*! * A fixture for general test cases involving extruder plans. * * This fixture provides a test extruder plan, without any paths, to test with. */ class ExtruderPlanTest : public testing::Test { public: /*! * An extruder plan that can be used as a victim for testing. */ ExtruderPlan extruder_plan; ExtruderPlanTest() : extruder_plan( /*extruder=*/0, /*layer_nr=*/50, /*is_initial_layer=*/false, /*is_raft_layer=*/false, /*layer_thickness=*/100, FanSpeedLayerTimeSettings(), RetractionConfig() ) {} }; /*! * Tests that paths remain unmodified if applying back pressure compensation * with factor 0. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationZeroIsUncompensated) { extruder_plan.paths = GetParam(); std::vector<Ratio> original_flows; std::vector<Ratio> original_speeds; for(const GCodePath& path : extruder_plan.paths) { original_flows.push_back(path.flow); original_speeds.push_back(path.speed_factor); } extruder_plan.applyBackPressureCompensation(0.0_r); ASSERT_EQ(extruder_plan.paths.size(), original_flows.size()) << "Number of paths may not have changed."; for(size_t i = 0; i < extruder_plan.paths.size(); ++i) { EXPECT_EQ(original_flows[i], extruder_plan.paths[i].flow) << "The flow rate did not change. Back pressure compensation doesn't adjust flow."; EXPECT_EQ(original_speeds[i], extruder_plan.paths[i].speed_factor) << "The speed factor did not change, since the compensation factor was 0."; } } /*! * Tests that a factor of 1 causes the back pressure compensation to be * completely equalizing the flow rate. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationFull) { extruder_plan.paths = GetParam(); extruder_plan.applyBackPressureCompensation(1.0_r); auto first_extrusion = std::find_if(extruder_plan.paths.begin(), extruder_plan.paths.end(), [](GCodePath& path) { return path.config->getPrintFeatureType() != PrintFeatureType::MoveCombing && path.config->getPrintFeatureType() != PrintFeatureType::MoveRetraction; }); if(first_extrusion == extruder_plan.paths.end()) //Only travel moves in this plan. { return; } //All flow rates must be equal to this one. const double first_flow_mm3_per_sec = calculatePathFlow(*first_extrusion); for(GCodePath& path : extruder_plan.paths) { if(path.config->getPrintFeatureType() == PrintFeatureType::MoveCombing || path.config->getPrintFeatureType() == PrintFeatureType::MoveRetraction) { continue; //Ignore travel moves. } const double flow_mm3_per_sec = calculatePathFlow(path); EXPECT_EQ(flow_mm3_per_sec, first_flow_mm3_per_sec) << "Every path must have a flow rate equal to the first, since the flow changes were completely compensated for."; } } /*! * Tests that a factor of 0.5 halves the differences in flow rate. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationHalf) { extruder_plan.paths = GetParam(); //Calculate what the flow rates were originally. std::vector<double> original_flows; for(GCodePath& path : extruder_plan.paths) { if(path.config->getPrintFeatureType() == PrintFeatureType::MoveCombing || path.config->getPrintFeatureType() == PrintFeatureType::MoveRetraction) { continue; //Ignore travel moves. } original_flows.push_back(calculatePathFlow(path)); } const double original_average = std::accumulate(original_flows.begin(), original_flows.end(), 0) / original_flows.size(); //Apply the back pressure compensation with 50% factor! extruder_plan.applyBackPressureCompensation(0.5_r); //Calculate the new flow rates. std::vector<double> new_flows; for(GCodePath& path : extruder_plan.paths) { if(path.config->getPrintFeatureType() == PrintFeatureType::MoveCombing || path.config->getPrintFeatureType() == PrintFeatureType::MoveRetraction) { continue; //Ignore travel moves. } new_flows.push_back(calculatePathFlow(path)); } const double new_average = std::accumulate(new_flows.begin(), new_flows.end(), 0) / new_flows.size(); //Note that the new average doesn't necessarily need to be the same average! It is most likely a higher average in real-world scenarios. //Test that the deviation from the average was halved. ASSERT_EQ(original_flows.size(), new_flows.size()) << "We need to have the same number of extrusion moves."; for(size_t i = 0; i < new_flows.size(); ++i) { EXPECT_DOUBLE_EQ((original_flows[i] - original_average) / 2.0, new_flows[i] - new_average); } } /*! * Tests back pressure compensation on an extruder plan that is completely * empty. */ TEST_F(ExtruderPlanTest, BackPressureCompensationEmptyPlan) { //The extruder plan starts off empty. So immediately try applying back-pressure compensation. extruder_plan.applyBackPressureCompensation(0.5_r); EXPECT_TRUE(extruder_plan.paths.empty()) << "The paths in the extruder plan should remain empty. Also it shouldn't crash."; } }
//Copyright (c) 2021 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <numeric> //For calculating averages. #include <gtest/gtest.h> #include "../src/LayerPlan.h" //Code under test. namespace cura { /*! * A fixture containing some sets of GCodePaths to test with. */ class ExtruderPlanTestPathCollection { public: /*! * One path with 5 vertices printing a 1000x1000 micron square starting from * 0,0. */ std::vector<GCodePath> square; /*! * Three lines side by side, with two travel moves in between. */ std::vector<GCodePath> lines; /*! * Three lines side by side with travel moves in between, but adjusted flow. * * The first line gets 120% flow. * The second line gets 80% flow. * The third line gets 40% flow. */ std::vector<GCodePath> decreasing_flow; /*! * Three lines side by side with their speed factors adjusted. * * The first line gets 120% speed. * The second line gets 80% speed. * The third line gets 40% speed. */ std::vector<GCodePath> decreasing_speed; /*! * A series of paths with variable line width. * * This one has no travel moves in between. * The last path gets a width of 0. */ std::vector<GCodePath> variable_width; /*! * Configuration to print extruded paths with in the fixture. * * This config is referred to via pointer, so changing it will immediately * change it for all extruded paths. */ GCodePathConfig extrusion_config; /*! * Configuration to print travel paths with in the fixture. * * This config is referred to via pointer, so changing it will immediately * change it for all travel paths. */ GCodePathConfig travel_config; ExtruderPlanTestPathCollection() : extrusion_config( PrintFeatureType::OuterWall, /*line_width=*/400, /*layer_thickness=*/100, /*flow=*/1.0_r, GCodePathConfig::SpeedDerivatives(50, 1000, 10) ), travel_config( PrintFeatureType::MoveCombing, /*line_width=*/0, /*layer_thickness=*/100, /*flow=*/0.0_r, GCodePathConfig::SpeedDerivatives(120, 5000, 30) ) { const std::string mesh_id = "test_mesh"; constexpr Ratio flow_1 = 1.0_r; constexpr bool no_spiralize = false; constexpr Ratio speed_1 = 1.0_r; square.assign({GCodePath(extrusion_config, mesh_id, SpaceFillType::PolyLines, flow_1, no_spiralize, speed_1)}); square.back().points = { Point(0, 0), Point(1000, 0), Point(1000, 1000), Point(0, 1000), Point(0, 0) }; lines.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1) }); lines[0].points = {Point(0, 0), Point(1000, 0)}; lines[1].points = {Point(1000, 0), Point(1000, 400)}; lines[2].points = {Point(1000, 400), Point(0, 400)}; lines[3].points = {Point(0, 400), Point(0, 800)}; lines[4].points = {Point(0, 800), Point(1000, 800)}; constexpr Ratio flow_12 = 1.2_r; constexpr Ratio flow_08 = 0.8_r; constexpr Ratio flow_04 = 0.4_r; decreasing_flow.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_12, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_08, no_spiralize, speed_1), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_04, no_spiralize, speed_1) }); decreasing_flow[0].points = {Point(0, 0), Point(1000, 0)}; decreasing_flow[1].points = {Point(1000, 0), Point(1000, 400)}; decreasing_flow[2].points = {Point(1000, 400), Point(0, 400)}; decreasing_flow[3].points = {Point(0, 400), Point(0, 800)}; decreasing_flow[4].points = {Point(0, 800), Point(1000, 800)}; constexpr Ratio speed_12 = 1.2_r; constexpr Ratio speed_08 = 0.8_r; constexpr Ratio speed_04 = 0.4_r; decreasing_speed.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_12), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_08), GCodePath(travel_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_04) }); decreasing_speed[0].points = {Point(0, 0), Point(1000, 0)}; decreasing_speed[1].points = {Point(1000, 0), Point(1000, 400)}; decreasing_speed[2].points = {Point(1000, 400), Point(0, 400)}; decreasing_speed[3].points = {Point(0, 400), Point(0, 800)}; decreasing_speed[4].points = {Point(0, 800), Point(1000, 800)}; variable_width.assign({ GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, flow_1, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.8_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.6_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.4_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.2_r, no_spiralize, speed_1), GCodePath(extrusion_config, mesh_id, SpaceFillType::Lines, 0.0_r, no_spiralize, speed_1), }); variable_width[0].points = {Point(0, 0), Point(1000, 0)}; variable_width[1].points = {Point(1000, 0), Point(2000, 0)}; variable_width[2].points = {Point(2000, 0), Point(3000, 0)}; variable_width[3].points = {Point(3000, 0), Point(4000, 0)}; variable_width[4].points = {Point(4000, 0), Point(5000, 0)}; variable_width[5].points = {Point(5000, 0), Point(6000, 0)}; } }; static ExtruderPlanTestPathCollection path_collection; /*! * Tests in this class get parameterized with a vector of GCodePaths to put in * the extruder plan, and an extruder plan to put it in. */ class ExtruderPlanPathsParameterizedTest : public testing::TestWithParam<std::vector<GCodePath>> { public: /*! * An extruder plan that can be used as a victim for testing. */ ExtruderPlan extruder_plan; ExtruderPlanPathsParameterizedTest() : extruder_plan( /*extruder=*/0, /*layer_nr=*/50, /*is_initial_layer=*/false, /*is_raft_layer=*/false, /*layer_thickness=*/100, FanSpeedLayerTimeSettings(), RetractionConfig() ) {} /*! * Helper method to calculate the flow rate of a path in mm3 per second. * \param path The path to calculate the flow rate of. * \return The flow rate, in cubic millimeters per second. */ double calculatePathFlow(const GCodePath& path) { return path.getExtrusionMM3perMM() * path.config->getSpeed() * path.speed_factor * path.speed_back_pressure_factor; } }; INSTANTIATE_TEST_CASE_P(ExtruderPlanTestInstantiation, ExtruderPlanPathsParameterizedTest, testing::Values( path_collection.square, path_collection.lines, path_collection.decreasing_flow, path_collection.decreasing_speed, path_collection.variable_width )); /*! * A fixture for general test cases involving extruder plans. * * This fixture provides a test extruder plan, without any paths, to test with. */ class ExtruderPlanTest : public testing::Test { public: /*! * An extruder plan that can be used as a victim for testing. */ ExtruderPlan extruder_plan; ExtruderPlanTest() : extruder_plan( /*extruder=*/0, /*layer_nr=*/50, /*is_initial_layer=*/false, /*is_raft_layer=*/false, /*layer_thickness=*/100, FanSpeedLayerTimeSettings(), RetractionConfig() ) {} }; /*! * Tests that paths remain unmodified if applying back pressure compensation * with factor 0. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationZeroIsUncompensated) { extruder_plan.paths = GetParam(); std::vector<Ratio> original_flows; std::vector<Ratio> original_speeds; for(const GCodePath& path : extruder_plan.paths) { original_flows.push_back(path.flow); original_speeds.push_back(path.speed_factor); } extruder_plan.applyBackPressureCompensation(0.0_r); ASSERT_EQ(extruder_plan.paths.size(), original_flows.size()) << "Number of paths may not have changed."; for(size_t i = 0; i < extruder_plan.paths.size(); ++i) { EXPECT_EQ(original_flows[i], extruder_plan.paths[i].flow) << "The flow rate did not change. Back pressure compensation doesn't adjust flow."; EXPECT_EQ(original_speeds[i], extruder_plan.paths[i].speed_factor) << "The speed factor did not change, since the compensation factor was 0."; } } /*! * Tests that a factor of 1 causes the back pressure compensation to be * completely equalizing the flow rate. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationFull) { extruder_plan.paths = GetParam(); extruder_plan.applyBackPressureCompensation(1.0_r); auto first_extrusion = std::find_if(extruder_plan.paths.begin(), extruder_plan.paths.end(), [](GCodePath& path) { return !path.config->isTravelPath(); }); if(first_extrusion == extruder_plan.paths.end()) //Only travel moves in this plan. { return; } //All flow rates must be equal to this one. const double first_flow_mm3_per_sec = calculatePathFlow(*first_extrusion); for(GCodePath& path : extruder_plan.paths) { if(path.config->isTravelPath()) { continue; //Ignore travel moves. } const double flow_mm3_per_sec = calculatePathFlow(path); EXPECT_EQ(flow_mm3_per_sec, first_flow_mm3_per_sec) << "Every path must have a flow rate equal to the first, since the flow changes were completely compensated for."; } } /*! * Tests that a factor of 0.5 halves the differences in flow rate. */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationHalf) { extruder_plan.paths = GetParam(); //Calculate what the flow rates were originally. std::vector<double> original_flows; for(GCodePath& path : extruder_plan.paths) { if(path.config->isTravelPath()) { continue; //Ignore travel moves. } original_flows.push_back(calculatePathFlow(path)); } const double original_average = std::accumulate(original_flows.begin(), original_flows.end(), 0) / original_flows.size(); //Apply the back pressure compensation with 50% factor! extruder_plan.applyBackPressureCompensation(0.5_r); //Calculate the new flow rates. std::vector<double> new_flows; for(GCodePath& path : extruder_plan.paths) { if(path.config->isTravelPath()) { continue; //Ignore travel moves. } new_flows.push_back(calculatePathFlow(path)); } const double new_average = std::accumulate(new_flows.begin(), new_flows.end(), 0) / new_flows.size(); //Note that the new average doesn't necessarily need to be the same average! It is most likely a higher average in real-world scenarios. //Test that the deviation from the average was halved. ASSERT_EQ(original_flows.size(), new_flows.size()) << "We need to have the same number of extrusion moves."; for(size_t i = 0; i < new_flows.size(); ++i) { EXPECT_DOUBLE_EQ((original_flows[i] - original_average) / 2.0, new_flows[i] - new_average); } } /*! * Tests back pressure compensation on an extruder plan that is completely * empty. */ TEST_F(ExtruderPlanTest, BackPressureCompensationEmptyPlan) { //The extruder plan starts off empty. So immediately try applying back-pressure compensation. extruder_plan.applyBackPressureCompensation(0.5_r); EXPECT_TRUE(extruder_plan.paths.empty()) << "The paths in the extruder plan should remain empty. Also it shouldn't crash."; } }
Use isTravelPath on the GCodePathConfig instead of checking multiple types
Use isTravelPath on the GCodePathConfig instead of checking multiple types This should break less often if we add new types of paths. Contributes to issue CURA-7279.
C++
agpl-3.0
Ultimaker/CuraEngine,Ultimaker/CuraEngine
acc509a77b6deeed0b3994a933d5cde291e17df6
tests/auto/bic/tst_bic.cpp
tests/auto/bic/tst_bic.cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QtCore> #include <QtTest/QtTest> #ifdef QT_NO_PROCESS QTEST_NOOP_MAIN #else #include "qbic.h" #include <stdlib.h> class tst_Bic: public QObject { Q_OBJECT public: tst_Bic(); QBic::Info getCurrentInfo(const QString &libName); private slots: void initTestCase_data(); void initTestCase(); void sizesAndVTables_data(); void sizesAndVTables(); private: QBic bic; }; typedef QPair<QString, QString> QStringPair; tst_Bic::tst_Bic() { bic.addBlacklistedClass(QLatin1String("std::*")); bic.addBlacklistedClass(QLatin1String("qIsNull*")); bic.addBlacklistedClass(QLatin1String("_*")); bic.addBlacklistedClass(QLatin1String("<anonymous*")); /* some system stuff we don't care for */ bic.addBlacklistedClass(QLatin1String("timespec")); bic.addBlacklistedClass(QLatin1String("itimerspec")); bic.addBlacklistedClass(QLatin1String("sched_param")); bic.addBlacklistedClass(QLatin1String("timeval")); bic.addBlacklistedClass(QLatin1String("drand")); bic.addBlacklistedClass(QLatin1String("lconv")); bic.addBlacklistedClass(QLatin1String("random")); bic.addBlacklistedClass(QLatin1String("wait")); bic.addBlacklistedClass(QLatin1String("tm")); bic.addBlacklistedClass(QLatin1String("sigcontext")); bic.addBlacklistedClass(QLatin1String("ucontext")); bic.addBlacklistedClass(QLatin1String("ucontext64")); bic.addBlacklistedClass(QLatin1String("sigaltstack")); /* QtOpenGL includes qt_windows.h, and some SDKs dont have these structs present */ bic.addBlacklistedClass(QLatin1String("tagTITLEBARINFO")); /* some bug in gcc also reported template instanciations */ bic.addBlacklistedClass(QLatin1String("QTypeInfo<*>")); bic.addBlacklistedClass(QLatin1String("QMetaTypeId<*>")); bic.addBlacklistedClass(QLatin1String("QVector<QGradientStop>*")); /* this guy is never instantiated, just for compile-time checking */ bic.addBlacklistedClass(QLatin1String("QMap<*>::PayloadNode")); /* QFileEngine was removed in 4.1 */ bic.addBlacklistedClass(QLatin1String("QFileEngine")); bic.addBlacklistedClass(QLatin1String("QFileEngineHandler")); bic.addBlacklistedClass(QLatin1String("QFlags<QFileEngine::FileFlag>")); /* Private classes */ bic.addBlacklistedClass(QLatin1String("QBrushData")); bic.addBlacklistedClass(QLatin1String("QObjectData")); bic.addBlacklistedClass(QLatin1String("QAtomic")); bic.addBlacklistedClass(QLatin1String("QBasicAtomic")); /* Jambi-related classes in Designer */ bic.addBlacklistedClass(QLatin1String("QDesignerLanguageExtension")); /* Harald says it's undocumented and private :) */ bic.addBlacklistedClass(QLatin1String("QAccessibleInterfaceEx")); bic.addBlacklistedClass(QLatin1String("QAccessibleObjectEx")); bic.addBlacklistedClass(QLatin1String("QAccessibleWidgetEx")); /* This structure is semi-private and should never shrink */ bic.addBlacklistedClass(QLatin1String("QVFbHeader")); } void tst_Bic::initTestCase_data() { QTest::addColumn<QString>("libName"); QTest::newRow("QtCore") << "QtCore"; QTest::newRow("QtGui") << "QtGui"; QTest::newRow("QtScript") << "QtScript"; QTest::newRow("QtSql") << "QtSql"; QTest::newRow("QtSvg") << "QtSvg"; QTest::newRow("QtNetwork") << "QtNetwork"; QTest::newRow("QtOpenGL") << "QtOpenGL"; QTest::newRow("QtXml") << "QtXml"; QTest::newRow("QtXmlPatterns") << "QtXmlPatterns"; QTest::newRow("Qt3Support") << "Qt3Support"; QTest::newRow("QtTest") << "QtTest"; QTest::newRow("QtDBus") << "QtDBus"; QTest::newRow("QtDesigner") << "QtDesigner"; } void tst_Bic::initTestCase() { QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR")); QVERIFY2(!qtDir.isEmpty(), "This test needs $QTDIR"); if (qgetenv("PATH").contains("teambuilder")) QTest::qWarn("This test might not work with teambuilder, consider switching it off."); } void tst_Bic::sizesAndVTables_data() { #if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) QSKIP("Test not implemented for this compiler/platform", SkipAll); #else QString archFileName400; QString archFileName410; QString archFileName420; QString archFileName430; #if defined Q_OS_LINUX && defined Q_WS_X11 # if defined(__powerpc__) && !defined(__powerpc64__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ppc32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ppc32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ppc32.txt"; # elif defined(__amd64__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-amd64.txt"; # elif defined(__i386__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ia32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ia32.txt"; archFileName430 = SRCDIR "data/%1.4.3.0.linux-gcc-ia32.txt"; # endif #elif defined Q_OS_AIX if (sizeof(void*) == 4) archFileName400 = SRCDIR "data/%1.4.0.0.aix-gcc-power32.txt"; #elif defined Q_OS_MAC && defined(__powerpc__) archFileName400 = SRCDIR "data/%1.4.0.0.macx-gcc-ppc32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ppc32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ppc32.txt"; #elif defined Q_OS_MAC && defined(__i386__) archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ia32.txt"; #elif defined Q_OS_WIN && defined Q_CC_GNU archFileName410 = SRCDIR "data/%1.4.1.0.win32-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.win32-gcc-ia32.txt"; #endif if (archFileName400.isEmpty() && archFileName410.isEmpty() && archFileName420.isEmpty()) QSKIP("No reference files found for this platform", SkipAll); bool isPatchRelease400 = false; bool isPatchRelease410 = false; bool isPatchRelease420 = false; bool isPatchRelease430 = false; QTest::addColumn<QString>("oldLib"); QTest::addColumn<bool>("isPatchRelease"); QTest::newRow("4.0") << archFileName400 << isPatchRelease400; QTest::newRow("4.1") << archFileName410 << isPatchRelease410; QTest::newRow("4.2") << archFileName420 << isPatchRelease420; QTest::newRow("4.3") << archFileName430 << isPatchRelease430; #endif } QBic::Info tst_Bic::getCurrentInfo(const QString &libName) { QTemporaryFile tmpQFile; tmpQFile.open(); QString tmpFileName = tmpQFile.fileName(); QByteArray tmpFileContents = "#include<" + libName.toLatin1() + "/" + libName.toLatin1() + ">\n"; tmpQFile.write(tmpFileContents); tmpQFile.flush(); QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR")); #ifdef Q_OS_WIN qtDir.replace('\\', '/'); #endif QString compilerName = "g++"; QStringList args; args << "-c" << "-I" + qtDir + "/include" #ifndef Q_OS_WIN << "-I/usr/X11R6/include/" #endif << "-DQT_NO_STL" << "-DQT3_SUPPORT" << "-xc++" #if !defined(Q_OS_AIX) && !defined(Q_OS_WIN) << "-o" << "/dev/null" #endif << "-fdump-class-hierarchy" << tmpFileName; QProcess proc; proc.start(compilerName, args, QIODevice::ReadOnly); if (!proc.waitForFinished(6000000)) { qWarning() << "gcc didn't finish" << proc.errorString(); return QBic::Info(); } if (proc.exitCode() != 0) { qWarning() << "gcc returned with" << proc.exitCode(); return QBic::Info(); } QString errs = QString::fromLocal8Bit(proc.readAllStandardError().constData()); if (!errs.isEmpty()) { qDebug() << "Arguments:" << args << "Warnings:" << errs; return QBic::Info(); } // See if we find the gcc output file, which seems to change // from release to release QStringList files = QDir().entryList(QStringList() << "*.class"); if (files.isEmpty()) { qFatal("Could not locate the GCC output file, update this test"); return QBic::Info(); } else if (files.size() > 1) { qFatal("Located more than one output file, please clean up before running this test"); return QBic::Info(); } QString resultFileName = files.first(); QBic::Info inf = bic.parseFile(resultFileName); QFile::remove(resultFileName); tmpQFile.close(); return inf; } void tst_Bic::sizesAndVTables() { #if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) QSKIP("Test not implemented for this compiler/platform", SkipAll); #else QFETCH_GLOBAL(QString, libName); QFETCH(QString, oldLib); QFETCH(bool, isPatchRelease); bool isFailed = false; //qDebug() << oldLib.arg(libName); if (oldLib.isEmpty() || !QFile::exists(oldLib.arg(libName))) QSKIP("No platform spec found for this platform/version.", SkipSingle); const QBic::Info oldLibInfo = bic.parseFile(oldLib.arg(libName)); QVERIFY(!oldLibInfo.classVTables.isEmpty()); const QBic::Info currentLibInfo = getCurrentInfo(libName); QVERIFY(!currentLibInfo.classVTables.isEmpty()); QBic::VTableDiff diff = bic.diffVTables(oldLibInfo, currentLibInfo); if (!diff.removedVTables.isEmpty()) { qWarning() << "VTables for the following classes were removed" << diff.removedVTables; isFailed = true; } if (!diff.modifiedVTables.isEmpty()) { foreach(QStringPair entry, diff.modifiedVTables) qWarning() << "modified VTable:\n Old: " << entry.first << "\n New: " << entry.second; isFailed = true; } if (isPatchRelease && !diff.addedVTables.isEmpty()) { qWarning() << "VTables for the following classes were added in a patch release:" << diff.addedVTables; isFailed = true; } if (isPatchRelease && !diff.reimpMethods.isEmpty()) { foreach(QStringPair entry, diff.reimpMethods) qWarning() << "reimplemented virtual in patch release:\n Old: " << entry.first << "\n New: " << entry.second; isFailed = true; } QBic::SizeDiff sizeDiff = bic.diffSizes(oldLibInfo, currentLibInfo); if (!sizeDiff.mismatch.isEmpty()) { foreach (QString className, sizeDiff.mismatch) qWarning() << "size mismatch for" << className << "old" << oldLibInfo.classSizes.value(className) << "new" << currentLibInfo.classSizes.value(className); isFailed = true; } #ifdef Q_CC_MINGW /** * These symbols are from Windows' imm.h header, and is available * conditionally depending on the value of the WINVER define. We pull * them out since they're not relevant to the testing done. */ sizeDiff.removed.removeAll(QLatin1String("tagIMECHARPOSITION")); sizeDiff.removed.removeAll(QLatin1String("tagRECONVERTSTRING")); #endif if (!sizeDiff.removed.isEmpty()) { qWarning() << "the following classes were removed:" << sizeDiff.removed; isFailed = true; } if (isPatchRelease && !sizeDiff.added.isEmpty()) { qWarning() << "the following classes were added in a patch release:" << sizeDiff.added; isFailed = true; } if (isFailed) QFAIL("Test failed, read warnings above."); #endif } QTEST_APPLESS_MAIN(tst_Bic) #include "tst_bic.moc" #endif
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QtCore> #include <QtTest/QtTest> #ifdef QT_NO_PROCESS QTEST_NOOP_MAIN #else #include "qbic.h" #include <stdlib.h> class tst_Bic: public QObject { Q_OBJECT public: tst_Bic(); QBic::Info getCurrentInfo(const QString &libName); private slots: void initTestCase_data(); void initTestCase(); void sizesAndVTables_data(); void sizesAndVTables(); private: QBic bic; }; typedef QPair<QString, QString> QStringPair; tst_Bic::tst_Bic() { bic.addBlacklistedClass(QLatin1String("std::*")); bic.addBlacklistedClass(QLatin1String("qIsNull*")); bic.addBlacklistedClass(QLatin1String("_*")); bic.addBlacklistedClass(QLatin1String("<anonymous*")); /* some system stuff we don't care for */ bic.addBlacklistedClass(QLatin1String("timespec")); bic.addBlacklistedClass(QLatin1String("itimerspec")); bic.addBlacklistedClass(QLatin1String("sched_param")); bic.addBlacklistedClass(QLatin1String("timeval")); bic.addBlacklistedClass(QLatin1String("drand")); bic.addBlacklistedClass(QLatin1String("lconv")); bic.addBlacklistedClass(QLatin1String("random")); bic.addBlacklistedClass(QLatin1String("wait")); bic.addBlacklistedClass(QLatin1String("tm")); bic.addBlacklistedClass(QLatin1String("sigcontext")); bic.addBlacklistedClass(QLatin1String("ucontext")); bic.addBlacklistedClass(QLatin1String("ucontext64")); bic.addBlacklistedClass(QLatin1String("sigaltstack")); /* QtOpenGL includes qt_windows.h, and some SDKs dont have these structs present */ bic.addBlacklistedClass(QLatin1String("tagTITLEBARINFO")); /* some bug in gcc also reported template instanciations */ bic.addBlacklistedClass(QLatin1String("QTypeInfo<*>")); bic.addBlacklistedClass(QLatin1String("QMetaTypeId<*>")); bic.addBlacklistedClass(QLatin1String("QVector<QGradientStop>*")); /* this guy is never instantiated, just for compile-time checking */ bic.addBlacklistedClass(QLatin1String("QMap<*>::PayloadNode")); /* QFileEngine was removed in 4.1 */ bic.addBlacklistedClass(QLatin1String("QFileEngine")); bic.addBlacklistedClass(QLatin1String("QFileEngineHandler")); bic.addBlacklistedClass(QLatin1String("QFlags<QFileEngine::FileFlag>")); /* Private classes */ bic.addBlacklistedClass(QLatin1String("QBrushData")); bic.addBlacklistedClass(QLatin1String("QObjectData")); bic.addBlacklistedClass(QLatin1String("QAtomic")); bic.addBlacklistedClass(QLatin1String("QBasicAtomic")); /* Jambi-related classes in Designer */ bic.addBlacklistedClass(QLatin1String("QDesignerLanguageExtension")); /* Harald says it's undocumented and private :) */ bic.addBlacklistedClass(QLatin1String("QAccessibleInterfaceEx")); bic.addBlacklistedClass(QLatin1String("QAccessibleObjectEx")); bic.addBlacklistedClass(QLatin1String("QAccessibleWidgetEx")); /* This structure is semi-private and should never shrink */ bic.addBlacklistedClass(QLatin1String("QVFbHeader")); } void tst_Bic::initTestCase_data() { QTest::addColumn<QString>("libName"); QTest::newRow("QtCore") << "QtCore"; QTest::newRow("QtGui") << "QtGui"; QTest::newRow("QtScript") << "QtScript"; QTest::newRow("QtSql") << "QtSql"; QTest::newRow("QtSvg") << "QtSvg"; QTest::newRow("QtNetwork") << "QtNetwork"; QTest::newRow("QtOpenGL") << "QtOpenGL"; QTest::newRow("QtXml") << "QtXml"; QTest::newRow("QtXmlPatterns") << "QtXmlPatterns"; QTest::newRow("Qt3Support") << "Qt3Support"; QTest::newRow("QtTest") << "QtTest"; QTest::newRow("QtDBus") << "QtDBus"; QTest::newRow("QtDesigner") << "QtDesigner"; } void tst_Bic::initTestCase() { QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR")); QVERIFY2(!qtDir.isEmpty(), "This test needs $QTDIR"); if (qgetenv("PATH").contains("teambuilder")) QTest::qWarn("This test might not work with teambuilder, consider switching it off."); } void tst_Bic::sizesAndVTables_data() { #if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) QSKIP("Test not implemented for this compiler/platform", SkipAll); #else QString archFileName400; QString archFileName410; QString archFileName420; QString archFileName430; #if defined Q_OS_LINUX && defined Q_WS_X11 # if defined(__powerpc__) && !defined(__powerpc64__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ppc32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ppc32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ppc32.txt"; # elif defined(__amd64__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-amd64.txt"; # elif defined(__i386__) archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ia32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ia32.txt"; archFileName430 = SRCDIR "data/%1.4.3.0.linux-gcc-ia32.txt"; # endif #elif defined Q_OS_AIX if (sizeof(void*) == 4) archFileName400 = SRCDIR "data/%1.4.0.0.aix-gcc-power32.txt"; #elif defined Q_OS_MAC && defined(__powerpc__) archFileName400 = SRCDIR "data/%1.4.0.0.macx-gcc-ppc32.txt"; archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ppc32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ppc32.txt"; #elif defined Q_OS_MAC && defined(__i386__) archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ia32.txt"; #elif defined Q_OS_WIN && defined Q_CC_GNU archFileName410 = SRCDIR "data/%1.4.1.0.win32-gcc-ia32.txt"; archFileName420 = SRCDIR "data/%1.4.2.0.win32-gcc-ia32.txt"; #endif if (archFileName400.isEmpty() && archFileName410.isEmpty() && archFileName420.isEmpty()) QSKIP("No reference files found for this platform", SkipAll); bool isPatchRelease400 = false; bool isPatchRelease410 = false; bool isPatchRelease420 = false; bool isPatchRelease430 = false; QTest::addColumn<QString>("oldLib"); QTest::addColumn<bool>("isPatchRelease"); QTest::newRow("4.0") << archFileName400 << isPatchRelease400; QTest::newRow("4.1") << archFileName410 << isPatchRelease410; QTest::newRow("4.2") << archFileName420 << isPatchRelease420; QTest::newRow("4.3") << archFileName430 << isPatchRelease430; #endif } QBic::Info tst_Bic::getCurrentInfo(const QString &libName) { QTemporaryFile tmpQFile; tmpQFile.open(); QString tmpFileName = tmpQFile.fileName(); QByteArray tmpFileContents = "#include<" + libName.toLatin1() + "/" + libName.toLatin1() + ">\n"; tmpQFile.write(tmpFileContents); tmpQFile.flush(); QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR")); #ifdef Q_OS_WIN qtDir.replace('\\', '/'); #endif QString compilerName = "g++"; QStringList args; args << "-c" << "-I" + qtDir + "/include" #ifndef Q_OS_WIN << "-I/usr/X11R6/include/" #endif << "-DQT_NO_STL" << "-DQT3_SUPPORT" << "-xc++" #if !defined(Q_OS_AIX) && !defined(Q_OS_WIN) << "-o" << "/dev/null" #endif << "-fdump-class-hierarchy" << tmpFileName; QProcess proc; proc.start(compilerName, args, QIODevice::ReadOnly); if (!proc.waitForFinished(6000000)) { qWarning() << "gcc didn't finish" << proc.errorString(); return QBic::Info(); } if (proc.exitCode() != 0) { qWarning() << "gcc returned with" << proc.exitCode(); qDebug() << proc.readAllStandardError(); return QBic::Info(); } QString errs = QString::fromLocal8Bit(proc.readAllStandardError().constData()); if (!errs.isEmpty()) { qDebug() << "Arguments:" << args << "Warnings:" << errs; return QBic::Info(); } // See if we find the gcc output file, which seems to change // from release to release QStringList files = QDir().entryList(QStringList() << "*.class"); if (files.isEmpty()) { qFatal("Could not locate the GCC output file, update this test"); return QBic::Info(); } else if (files.size() > 1) { qDebug() << files; qFatal("Located more than one output file, please clean up before running this test"); return QBic::Info(); } QString resultFileName = files.first(); QBic::Info inf = bic.parseFile(resultFileName); QFile::remove(resultFileName); tmpQFile.close(); return inf; } void tst_Bic::sizesAndVTables() { #if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) QSKIP("Test not implemented for this compiler/platform", SkipAll); #else QFETCH_GLOBAL(QString, libName); QFETCH(QString, oldLib); QFETCH(bool, isPatchRelease); bool isFailed = false; //qDebug() << oldLib.arg(libName); if (oldLib.isEmpty() || !QFile::exists(oldLib.arg(libName))) QSKIP("No platform spec found for this platform/version.", SkipSingle); const QBic::Info oldLibInfo = bic.parseFile(oldLib.arg(libName)); QVERIFY(!oldLibInfo.classVTables.isEmpty()); const QBic::Info currentLibInfo = getCurrentInfo(libName); QVERIFY(!currentLibInfo.classVTables.isEmpty()); QBic::VTableDiff diff = bic.diffVTables(oldLibInfo, currentLibInfo); if (!diff.removedVTables.isEmpty()) { qWarning() << "VTables for the following classes were removed" << diff.removedVTables; isFailed = true; } if (!diff.modifiedVTables.isEmpty()) { foreach(QStringPair entry, diff.modifiedVTables) qWarning() << "modified VTable:\n Old: " << entry.first << "\n New: " << entry.second; isFailed = true; } if (isPatchRelease && !diff.addedVTables.isEmpty()) { qWarning() << "VTables for the following classes were added in a patch release:" << diff.addedVTables; isFailed = true; } if (isPatchRelease && !diff.reimpMethods.isEmpty()) { foreach(QStringPair entry, diff.reimpMethods) qWarning() << "reimplemented virtual in patch release:\n Old: " << entry.first << "\n New: " << entry.second; isFailed = true; } QBic::SizeDiff sizeDiff = bic.diffSizes(oldLibInfo, currentLibInfo); if (!sizeDiff.mismatch.isEmpty()) { foreach (QString className, sizeDiff.mismatch) qWarning() << "size mismatch for" << className << "old" << oldLibInfo.classSizes.value(className) << "new" << currentLibInfo.classSizes.value(className); isFailed = true; } #ifdef Q_CC_MINGW /** * These symbols are from Windows' imm.h header, and is available * conditionally depending on the value of the WINVER define. We pull * them out since they're not relevant to the testing done. */ sizeDiff.removed.removeAll(QLatin1String("tagIMECHARPOSITION")); sizeDiff.removed.removeAll(QLatin1String("tagRECONVERTSTRING")); #endif if (!sizeDiff.removed.isEmpty()) { qWarning() << "the following classes were removed:" << sizeDiff.removed; isFailed = true; } if (isPatchRelease && !sizeDiff.added.isEmpty()) { qWarning() << "the following classes were added in a patch release:" << sizeDiff.added; isFailed = true; } if (isFailed) QFAIL("Test failed, read warnings above."); #endif } QTEST_APPLESS_MAIN(tst_Bic) #include "tst_bic.moc" #endif
Add usefull debug output to the bic test
Add usefull debug output to the bic test
C++
lgpl-2.1
radekp/qt,igor-sfdc/qt-wk,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt
950c831d4562e8c835bf76051282bff09b2b5d08
tests/test_ivfpq_codec.cpp
tests/test_ivfpq_codec.cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdio> #include <cstdlib> #include <random> #include <gtest/gtest.h> #include <faiss/IndexIVFPQ.h> #include <faiss/IndexFlat.h> #include <faiss/utils/utils.h> #include <faiss/utils/distances.h> namespace { // dimension of the vectors to index int d = 64; // size of the database we plan to index size_t nb = 8000; double eval_codec_error (long ncentroids, long m, const std::vector<float> &v) { faiss::IndexFlatL2 coarse_quantizer (d); faiss::IndexIVFPQ index (&coarse_quantizer, d, ncentroids, m, 8); index.pq.cp.niter = 10; // speed up train index.train (nb, v.data()); // encode and decode to compute reconstruction error std::vector<faiss::Index::idx_t> keys (nb); std::vector<uint8_t> codes (nb * m); index.encode_multiple (nb, keys.data(), v.data(), codes.data(), true); std::vector<float> v2 (nb * d); index.decode_multiple (nb, keys.data(), codes.data(), v2.data()); return faiss::fvec_L2sqr (v.data(), v2.data(), nb * d); } } // namespace TEST(IVFPQ, codec) { std::vector <float> database (nb * d); std::mt19937 rng; std::uniform_real_distribution<> distrib; for (size_t i = 0; i < nb * d; i++) { database[i] = distrib(rng); } double err0 = eval_codec_error(16, 8, database); // should be more accurate as there are more coarse centroids double err1 = eval_codec_error(128, 8, database); EXPECT_GT(err0, err1); // should be more accurate as there are more PQ codes double err2 = eval_codec_error(16, 16, database); EXPECT_GT(err0, err2); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdio> #include <cstdlib> #include <random> #include <omp.h> #include <gtest/gtest.h> #include <faiss/IndexIVFPQ.h> #include <faiss/IndexFlat.h> #include <faiss/utils/utils.h> #include <faiss/utils/distances.h> namespace { // dimension of the vectors to index int d = 64; // size of the database we plan to index size_t nb = 8000; double eval_codec_error (long ncentroids, long m, const std::vector<float> &v) { faiss::IndexFlatL2 coarse_quantizer (d); faiss::IndexIVFPQ index (&coarse_quantizer, d, ncentroids, m, 8); index.pq.cp.niter = 10; // speed up train index.train (nb, v.data()); // encode and decode to compute reconstruction error std::vector<faiss::Index::idx_t> keys (nb); std::vector<uint8_t> codes (nb * m); index.encode_multiple (nb, keys.data(), v.data(), codes.data(), true); std::vector<float> v2 (nb * d); index.decode_multiple (nb, keys.data(), codes.data(), v2.data()); return faiss::fvec_L2sqr (v.data(), v2.data(), nb * d); } } // namespace bool runs_on_sandcastle() { // see discussion here https://fburl.com/qc5kpdo2 const char * sandcastle = getenv("SANDCASTLE"); if (sandcastle && !strcmp(sandcastle, "1")) { return true; } const char * tw_job_user = getenv("TW_JOB_USER"); if (tw_job_user && !strcmp(tw_job_user, "sandcastle")) { return true; } return false; } TEST(IVFPQ, codec) { std::vector <float> database (nb * d); std::mt19937 rng; std::uniform_real_distribution<> distrib; for (size_t i = 0; i < nb * d; i++) { database[i] = distrib(rng); } // limit number of threads when running on heavily parallelized test environment if (runs_on_sandcastle()) { omp_set_num_threads(2); } double err0 = eval_codec_error(16, 8, database); // should be more accurate as there are more coarse centroids double err1 = eval_codec_error(128, 8, database); EXPECT_GT(err0, err1); // should be more accurate as there are more PQ codes double err2 = eval_codec_error(16, 16, database); EXPECT_GT(err0, err2); }
Fix number of threads in test_ivfpq_codec when running in sandcastle
Fix number of threads in test_ivfpq_codec when running in sandcastle Summary: When running in a heavily parallelized env, the test becomes very slow and causes timeouts. Here we reduce the nb of threads. Reviewed By: wickedfoo, Ben0mega Differential Revision: D25921771 fbshipit-source-id: 1e0aacbb3e4f6e8f33ec893984b343eb5a610424
C++
mit
facebookresearch/faiss,facebookresearch/faiss,facebookresearch/faiss,facebookresearch/faiss
3cab8f39e7caab74294ccba6c9a81c19475a31cf
GALGO-1.0/src/GeneticAlgorithm.hpp
GALGO-1.0/src/GeneticAlgorithm.hpp
//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template <typename T, int N = 16> class GeneticAlgorithm { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please choose an integer within this interval."); template <typename K, int S> friend class Population; template <typename K, int S> friend class Chromosome; template <typename K> using Functor = std::vector<K> (*)(const std::vector<K>&); private: Population<T,N> pop; // population of chromosomes public: std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) private: mutable std::uniform_int_distribution<uint64_t> udistrib; // generate uniform random unsigned long long integers static constexpr uint64_t MAXVAL = MAXVALUE<N>::value - 1; // maximum unsigned integral value obtained from N bits, evaluated at compile time public: // objective function functor Functor<T> Objective; // selection method functor initialized to roulette wheel selection void (*Selection)(Population<T,N>&) = RWS; // cross-over method functor initialized to 1-point cross-over void (*CrossOver)(const Population<T,N>&, CHR<T,N>&, CHR<T,N>&) = P1XO; // mutation method functor initialized to single-point mutation void (*Mutation)(CHR<T,N>&) = SPM; // adaptation to constraint(s) method functor void (*Adaptation)(Population<T,N>&) = nullptr; // constraint(s) functor std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor GeneticAlgorithm(Functor<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output = false); // run genetic algorithm void run(); // return best chromosome const CHR<T,N>& result() const; private: int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // check inputs validity bool check() const ; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int N> GeneticAlgorithm<T,N>::GeneticAlgorithm(Functor<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output) { this->Objective = objective; this->nbparam = upperBound.size(); this->popsize = popsize; this->matsize = popsize; this->lowerBound = lowerBound; this->upperBound = upperBound; this->nbgen = nbgen; this->output = output; // initializing uniform distribution generating random unsigned integers udistrib = std::uniform_int_distribution<uint64_t>(0, MAXVAL); } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template <typename T, int N> bool GeneticAlgorithm<T,N>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\n"; return false; } } if (initialSet.size() != (unsigned)nbparam) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\n"; return false; } } if (lowerBound.size() != upperBound.size()) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\n"; return false; } for (int i = 0; i < nbparam; ++i) { if (lowerBound[i] >= upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\n"; return false; } } if (SP < 1.0 || SP > 2.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\n"; return false; } if (elitpop > popsize || elitpop < 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\n"; return false; } if (covrate < 0.0 || covrate > 1.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\n"; return false; } if (genstep <= 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\n"; return false; } return true; } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template <typename T, int N> void GeneticAlgorithm<T,N>::run() { // checking inputs validity if (!check()) { return; } // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T,N>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template <typename T, int N> inline const CHR<T,N>& GeneticAlgorithm<T,N>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template <typename T, int N> void GeneticAlgorithm<T,N>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif
//================================================================================================= // Copyright (C) 2017 Olivier Mallet - All Rights Reserved //================================================================================================= #ifndef GENETICALGORITHM_HPP #define GENETICALGORITHM_HPP namespace galgo { //================================================================================================= template <typename T, int N = 16> class GeneticAlgorithm { static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend."); static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please choose an integer within this interval."); template <typename K, int S> friend class Population; template <typename K, int S> friend class Chromosome; template <typename K> using Func = std::vector<K> (*)(const std::vector<K>&); private: Population<T,N> pop; // population of chromosomes public: std::vector<T> lowerBound; // parameter(s) lower bound std::vector<T> upperBound; // parameter(s) upper bound std::vector<T> initialSet; // initial set of parameter(s) private: mutable std::uniform_int_distribution<uint64_t> udistrib; // generate uniform random unsigned long long integers static constexpr uint64_t MAXVAL = MAXVALUE<N>::value - 1; // maximum unsigned integral value obtained from N bits, evaluated at compile time public: // objective function pointer Func<T> Objective; // selection method functor initialized to roulette wheel selection void (*Selection)(Population<T,N>&) = RWS; // cross-over method functor initialized to 1-point cross-over void (*CrossOver)(const Population<T,N>&, CHR<T,N>&, CHR<T,N>&) = P1XO; // mutation method functor initialized to single-point mutation void (*Mutation)(CHR<T,N>&) = SPM; // adaptation to constraint(s) method void (*Adaptation)(Population<T,N>&) = nullptr; // constraint(s) std::vector<T> (*Constraint)(const std::vector<T>&) = nullptr; T covrate = .50; // cross-over rate T mutrate = .05; // mutation rate T SP = 1.5; // selective pressure for RSP selection method T tolerance = 0.0; // terminal condition (inactive if equal to zero) int elitpop = 1; // elit population size int matsize; // mating pool size, set to popsize by default int tntsize = 10; // tournament size int genstep = 10; // generation step for outputting results int precision = 5; // precision for outputting results // constructor GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output = false); // run genetic algorithm void run(); // return best chromosome const CHR<T,N>& result() const; private: int nbgen; // number of generations int nogen = 0; // numero of generation int nbparam; // number of parameters to be estimated int popsize; // population size bool output; // control if results must be outputted // check inputs validity bool check() const ; // print results for each new generation void print() const; }; /*-------------------------------------------------------------------------------------------------*/ // constructor template <typename T, int N> GeneticAlgorithm<T,N>::GeneticAlgorithm(Func<T> objective, int popsize, const std::vector<T>& lowerBound, const std::vector<T>& upperBound, int nbgen, bool output) { this->Objective = objective; this->nbparam = upperBound.size(); this->popsize = popsize; this->matsize = popsize; this->lowerBound = lowerBound; this->upperBound = upperBound; this->nbgen = nbgen; this->output = output; // initializing uniform distribution generating random unsigned integers udistrib = std::uniform_int_distribution<uint64_t>(0, MAXVAL); } /*-------------------------------------------------------------------------------------------------*/ // check inputs validity template <typename T, int N> bool GeneticAlgorithm<T,N>::check() const { if (!initialSet.empty()) { for (int i = 0; i < nbparam; ++i) { if (initialSet[i] < lowerBound[i] || initialSet[i] > upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) cannot be outside [lowerBound,upperBound], please choose a set within these boundaries.\n"; return false; } } if (initialSet.size() != (unsigned)nbparam) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, initial set of parameters (initialSet) does not have the same dimension than the number of parameters, please adjust.\n"; return false; } } if (lowerBound.size() != upperBound.size()) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) and upper bound (upperBound) must be of same dimension, please adjust.\n"; return false; } for (int i = 0; i < nbparam; ++i) { if (lowerBound[i] >= upperBound[i]) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, lower bound (lowerBound) cannot be equal or greater than upper bound (upperBound), please amend.\n"; return false; } } if (SP < 1.0 || SP > 2.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, selective pressure (SP) cannot be outside [1.0,2.0], please choose a real value within this interval.\n"; return false; } if (elitpop > popsize || elitpop < 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, elit population (elitpop) cannot outside [0,popsize], please choose an integral value within this interval.\n"; return false; } if (covrate < 0.0 || covrate > 1.0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, cross-over rate (covrate) cannot outside [0.0,1.0], please choose a real value within this interval.\n"; return false; } if (genstep <= 0) { std::cerr << " Error: in class galgo::GeneticAlgorithm<T>, generation step (genstep) cannot be <= 0, please choose an integral value > 0.\n"; return false; } return true; } /*-------------------------------------------------------------------------------------------------*/ // run genetic algorithm template <typename T, int N> void GeneticAlgorithm<T,N>::run() { // checking inputs validity if (!check()) { return; } // setting adaptation method to default if needed if (Constraint != nullptr && Adaptation == nullptr) { Adaptation = DAC; } // initializing population pop = Population<T,N>(*this); if (output) { std::cout << "\n Running Genetic Algorithm...\n"; std::cout << " ----------------------------\n"; } // creating population pop.creation(); // initializing best result and previous best result T bestResult = pop(0)->getTotal(); T prevBestResult = bestResult; // outputting results if (output) print(); // starting population evolution for (nogen = 1; nogen <= nbgen; ++nogen) { // evolving population pop.evolution(); // getting best current result bestResult = pop(0)->getTotal(); // outputting results if (output) print(); // checking convergence if (tolerance != 0.0) { if (fabs(bestResult - prevBestResult) < fabs(tolerance)) { break; } prevBestResult = bestResult; } } // outputting contraint value if (Constraint != nullptr) { // getting best parameter(s) constraint value(s) std::vector<T> cst = pop(0)->getConstraint(); if (output) { std::cout << "\n Constraint(s)\n"; std::cout << " -------------\n"; for (unsigned i = 0; i < cst.size(); ++i) { std::cout << " C"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(6) << std::fixed << std::setprecision(precision) << cst[i] << "\n"; } std::cout << "\n"; } } } /*-------------------------------------------------------------------------------------------------*/ // return best chromosome template <typename T, int N> inline const CHR<T,N>& GeneticAlgorithm<T,N>::result() const { return pop(0); } /*-------------------------------------------------------------------------------------------------*/ // print results for each new generation template <typename T, int N> void GeneticAlgorithm<T,N>::print() const { // getting best parameter(s) from best chromosome std::vector<T> bestParam = pop(0)->getParam(); std::vector<T> bestResult = pop(0)->getResult(); if (nogen % genstep == 0) { std::cout << " Generation = " << std::setw(std::to_string(nbgen).size()) << nogen << " |"; for (int i = 0; i < nbparam; ++i) { std::cout << " X"; if (nbparam > 1) { std::cout << std::to_string(i + 1); } std::cout << " = " << std::setw(9) << std::fixed << std::setprecision(precision) << bestParam[i] << " |"; } for (unsigned i = 0; i < bestResult.size(); ++i) { std::cout << " F"; if (bestResult.size() > 1) { std::cout << std::to_string(i + 1); } std::cout << "(x) = " << std::setw(12) << std::fixed << std::setprecision(precision) << bestResult[i]; if (i < bestResult.size() - 1) { std::cout << " |"; } else { std::cout << "\n"; } } } } //================================================================================================= } #endif
Update GeneticAlgorithm.hpp
Update GeneticAlgorithm.hpp
C++
mit
olmallet81/GALGO-2.0
83a2ffd953272159c41dc079a33a0a8ada977710
IO/Infovis/vtkNewickTreeReader.cxx
IO/Infovis/vtkNewickTreeReader.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkNewickTreeReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkNewickTreeReader.h" #include "vtkByteSwap.h" #include "vtkCellArray.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkFieldData.h" #include "vtkNew.h" #include "vtkTree.h" #include "vtkTreeDFSIterator.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkStringArray.h" #include <iostream> #include <fstream> vtkStandardNewMacro(vtkNewickTreeReader); #ifdef read #undef read #endif //---------------------------------------------------------------------------- vtkNewickTreeReader::vtkNewickTreeReader() { vtkTree *output = vtkTree::New(); this->SetOutput(output); // Releasing data for pipeline parallelism. // Filters will know it is empty. output->ReleaseData(); output->Delete(); } //---------------------------------------------------------------------------- vtkNewickTreeReader::~vtkNewickTreeReader() { } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput() { return this->GetOutput(0); } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput(int idx) { return vtkTree::SafeDownCast(this->GetOutputDataObject(idx)); } //---------------------------------------------------------------------------- void vtkNewickTreeReader::SetOutput(vtkTree *output) { this->GetExecutive()->SetOutputData(0, output); } //---------------------------------------------------------------------------- // I do not think this should be here, but I do not want to remove it now. int vtkNewickTreeReader::RequestUpdateExtent( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); int piece, numPieces; piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // make sure piece is valid if (piece < 0 || piece >= numPieces) { return 1; } return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader:: ReadNewickTree( const char * buffer, vtkTree & tree) { // Read through the input file to count the number of nodes in the tree. // We start at one to account for the root node vtkIdType numNodes = 1; this->CountNodes(buffer, &numNodes); // Create the edge weight array vtkNew<vtkDoubleArray> weights; weights->SetNumberOfComponents(1); weights->SetName("weight"); weights->SetNumberOfValues(numNodes-1);//the number of edges = number of nodes -1 for a tree weights->FillComponent(0, 0.0); // Create the names array vtkNew<vtkStringArray> names; names->SetNumberOfComponents(1); names->SetName("node name"); names->SetNumberOfValues(numNodes); // parse the input file to create the graph vtkNew<vtkMutableDirectedGraph> builder; this->BuildTree(const_cast<char*> (buffer), builder.GetPointer(), weights.GetPointer(), names.GetPointer(), -1); builder->GetVertexData()->AddArray(names.GetPointer()); if (!tree.CheckedShallowCopy(builder.GetPointer())) { vtkErrorMacro(<<"Edges do not create a valid tree."); return 1; } // check if our input file contained edge weight information bool haveWeights = false; for (vtkIdType i = 0; i < weights->GetNumberOfTuples(); ++i) { if (weights->GetValue(i) != 0.0) { haveWeights = true; break; } } if (!haveWeights) { return 1; } tree.GetEdgeData()->AddArray(weights.GetPointer()); vtkNew<vtkDoubleArray> nodeWeights; nodeWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); //set node weights vtkNew<vtkTreeDFSIterator> treeIterator; treeIterator->SetStartVertex(tree.GetRoot()); treeIterator->SetTree(&tree); while (treeIterator->HasNext()) { vtkIdType vertex = treeIterator->Next(); vtkIdType parent = tree.GetParent(vertex); double weight = 0.0; if (parent >= 0) { weight = weights->GetValue(tree.GetEdgeId(parent, vertex)); weight += nodeWeights->GetValue(parent); } nodeWeights->SetValue(vertex, weight); } nodeWeights->SetName("node weight"); tree.GetVertexData()->AddArray(nodeWeights.GetPointer()); return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // Return all data in the first piece ... if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkDebugMacro(<<"Reading Newick tree ..."); if( !this->ReadFromInputString) { if(!this->GetFileName()) { vtkErrorMacro("FileName not set."); return 1; } std::ifstream ifs( this->GetFileName(), std::ifstream::in ); if(!ifs.good()) { vtkErrorMacro(<<"Unable to open " << this->GetFileName() << " for reading"); return 1; } // Read the input file into a char * ifs.seekg(0, std::ios::end); this->InputStringLength = ifs.tellg(); ifs.seekg(0, std::ios::beg); this->InputString = new char[this->InputStringLength]; ifs.read(this->InputString, this->InputStringLength); ifs.close(); } else { if ( (!this->InputString) || (this->InputStringLength == 0)) { vtkErrorMacro(<<"Input string is empty!"); return 1; } } vtkTree* const output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if(!ReadNewickTree(this->InputString, *output)) { vtkErrorMacro(<<"Error reading a vtkTree from the input."); return 1; } vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and " << output->GetNumberOfEdges() <<" edges.\n"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::CountNodes(const char *buffer, vtkIdType *numNodes) { char *current; char *start; char temp; int childCount; start = const_cast<char*>(buffer); if (*start != '(') { // Leaf node. Separate name from weight. // If weight doesn't exist then take care of name only current = const_cast<char*>(buffer); while (*current != '\0') { current++; } ++(*numNodes); } else { ++(*numNodes); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } } else if (*current != ';' && *current != '\0') { while (*current != ':' && *(current+1) != ';' && *(current+1) != '\0') { current++; } current++; while (*current != '\0' && *current != ';') { current++; } } } } //---------------------------------------------------------------------------- vtkIdType vtkNewickTreeReader::BuildTree(char *buffer, vtkMutableDirectedGraph *g, vtkDoubleArray *weights, vtkStringArray *names, vtkIdType parent) { char *current; char *start; char *colon = NULL; char temp; int childCount; vtkIdType node; start = buffer; if (*start != '(') { // Leaf node. Separate name from weight (if it exists). current = buffer; while (*current != '\0') { if (*current == ':') { colon = current; } current++; } node = g->AddChild(parent); if (colon == NULL) { // Name only std::string name(start, strlen(start)); names->SetValue(node, name); } else { // Name *colon = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *colon = ':'; // Weight colon++; weights->SetValue(g->GetEdgeId(parent, node), atof(colon)); } } else { // Create node if(parent == -1) { node = g->AddVertex(); names->SetValue(node, ""); } else { node = g->AddChild(parent); } // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); names->SetValue(node, ""); *current = temp; } else if (*current != ';' && *current != '\0') { // Find ':' to retrieve distance, if any. // At this time *current should equal to ')' start = current; while (*current != ':') { current++; } temp = *current; *current = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *current = temp; current++; start = current; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); *current = temp; } } return node; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << endl; os << indent << "InputString: " << (this->InputString ? this->InputString : "(none)") << endl; os << indent << "ReadFromInputString: " << (this->ReadFromInputString ? "on" : "off") << endl; }
/*========================================================================= Program: Visualization Toolkit Module: vtkNewickTreeReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkNewickTreeReader.h" #include "vtkByteSwap.h" #include "vtkCellArray.h" #include "vtkDataSetAttributes.h" #include "vtkDoubleArray.h" #include "vtkFieldData.h" #include "vtkNew.h" #include "vtkTree.h" #include "vtkTreeDFSIterator.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkStringArray.h" #include <iostream> #include <fstream> vtkStandardNewMacro(vtkNewickTreeReader); #ifdef read #undef read #endif //---------------------------------------------------------------------------- vtkNewickTreeReader::vtkNewickTreeReader() { vtkTree *output = vtkTree::New(); this->SetOutput(output); // Releasing data for pipeline parallelism. // Filters will know it is empty. output->ReleaseData(); output->Delete(); } //---------------------------------------------------------------------------- vtkNewickTreeReader::~vtkNewickTreeReader() { } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput() { return this->GetOutput(0); } //---------------------------------------------------------------------------- vtkTree* vtkNewickTreeReader::GetOutput(int idx) { return vtkTree::SafeDownCast(this->GetOutputDataObject(idx)); } //---------------------------------------------------------------------------- void vtkNewickTreeReader::SetOutput(vtkTree *output) { this->GetExecutive()->SetOutputData(0, output); } //---------------------------------------------------------------------------- // I do not think this should be here, but I do not want to remove it now. int vtkNewickTreeReader::RequestUpdateExtent( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); int piece, numPieces; piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // make sure piece is valid if (piece < 0 || piece >= numPieces) { return 1; } return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader:: ReadNewickTree( const char * buffer, vtkTree & tree) { // Read through the input file to count the number of nodes in the tree. vtkIdType numNodes = 0; this->CountNodes(buffer, &numNodes); // Create the edge weight array vtkNew<vtkDoubleArray> weights; weights->SetNumberOfComponents(1); weights->SetName("weight"); weights->SetNumberOfValues(numNodes-1);//the number of edges = number of nodes -1 for a tree weights->FillComponent(0, 0.0); // Create the names array vtkNew<vtkStringArray> names; names->SetNumberOfComponents(1); names->SetName("node name"); names->SetNumberOfValues(numNodes); // parse the input file to create the graph vtkNew<vtkMutableDirectedGraph> builder; this->BuildTree(const_cast<char*> (buffer), builder.GetPointer(), weights.GetPointer(), names.GetPointer(), -1); builder->GetVertexData()->AddArray(names.GetPointer()); if (!tree.CheckedShallowCopy(builder.GetPointer())) { vtkErrorMacro(<<"Edges do not create a valid tree."); return 1; } // check if our input file contained edge weight information bool haveWeights = false; for (vtkIdType i = 0; i < weights->GetNumberOfTuples(); ++i) { if (weights->GetValue(i) != 0.0) { haveWeights = true; break; } } if (!haveWeights) { return 1; } tree.GetEdgeData()->AddArray(weights.GetPointer()); vtkNew<vtkDoubleArray> nodeWeights; nodeWeights->SetNumberOfTuples(tree.GetNumberOfVertices()); //set node weights vtkNew<vtkTreeDFSIterator> treeIterator; treeIterator->SetStartVertex(tree.GetRoot()); treeIterator->SetTree(&tree); while (treeIterator->HasNext()) { vtkIdType vertex = treeIterator->Next(); vtkIdType parent = tree.GetParent(vertex); double weight = 0.0; if (parent >= 0) { weight = weights->GetValue(tree.GetEdgeId(parent, vertex)); weight += nodeWeights->GetValue(parent); } nodeWeights->SetValue(vertex, weight); } nodeWeights->SetName("node weight"); tree.GetVertexData()->AddArray(nodeWeights.GetPointer()); return 1; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::RequestData( vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // Return all data in the first piece ... if(outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { return 1; } vtkDebugMacro(<<"Reading Newick tree ..."); if( !this->ReadFromInputString) { if(!this->GetFileName()) { vtkErrorMacro("FileName not set."); return 1; } std::ifstream ifs( this->GetFileName(), std::ifstream::in ); if(!ifs.good()) { vtkErrorMacro(<<"Unable to open " << this->GetFileName() << " for reading"); return 1; } // Read the input file into a char * ifs.seekg(0, std::ios::end); this->InputStringLength = ifs.tellg(); ifs.seekg(0, std::ios::beg); this->InputString = new char[this->InputStringLength]; ifs.read(this->InputString, this->InputStringLength); ifs.close(); } else { if ( (!this->InputString) || (this->InputStringLength == 0)) { vtkErrorMacro(<<"Input string is empty!"); return 1; } } vtkTree* const output = vtkTree::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if(!ReadNewickTree(this->InputString, *output)) { vtkErrorMacro(<<"Error reading a vtkTree from the input."); return 1; } vtkDebugMacro(<< "Read " << output->GetNumberOfVertices() <<" vertices and " << output->GetNumberOfEdges() <<" edges.\n"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::CountNodes(const char *buffer, vtkIdType *numNodes) { char *current; char *start; char temp; int childCount; start = const_cast<char*>(buffer); if (*start != '(') { // Leaf node. Separate name from weight. // If weight doesn't exist then take care of name only current = const_cast<char*>(buffer); while (*current != '\0') { current++; } ++(*numNodes); } else { ++(*numNodes); // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Count child nodes using recursion this->CountNodes(start, numNodes); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } } else if (*current != ';' && *current != '\0') { while (*current != ':' && *(current+1) != ';' && *(current+1) != '\0') { current++; } current++; while (*current != '\0' && *current != ';') { current++; } } } } //---------------------------------------------------------------------------- vtkIdType vtkNewickTreeReader::BuildTree(char *buffer, vtkMutableDirectedGraph *g, vtkDoubleArray *weights, vtkStringArray *names, vtkIdType parent) { char *current; char *start; char *colon = NULL; char temp; int childCount; vtkIdType node; start = buffer; if (*start != '(') { // Leaf node. Separate name from weight (if it exists). current = buffer; while (*current != '\0') { if (*current == ':') { colon = current; } current++; } node = g->AddChild(parent); if (colon == NULL) { // Name only std::string name(start, strlen(start)); names->SetValue(node, name); } else { // Name *colon = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *colon = ':'; // Weight colon++; weights->SetValue(g->GetEdgeId(parent, node), atof(colon)); } } else { // Create node if(parent == -1) { node = g->AddVertex(); names->SetValue(node, ""); } else { node = g->AddChild(parent); } // Search for all child nodes // Find all ',' until corresponding ')' is encountered childCount = 0; start++; current = start; while (childCount >= 0) { switch (*current) { case '(': // Find corresponding ')' by counting start = current; current++; childCount++; while (childCount > 0) { if (*current == '(') { childCount++; } else if (*current == ')') { childCount--; } current++; } while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; case ')': // End of this tree. Go to next part to retrieve distance childCount--; break; case ',': // Impossible separation since according to the algorithm, this symbol will never encountered. // Currently don't handle this and don't create any node break; default: // leaf node encountered start = current; while (*current != ',' && *current != ')') { current++; } temp = *current; *current = '\0'; // Create a child node using recursion this->BuildTree(start, g, weights, names, node); *current = temp; if (*current != ')') { current++; } break; } } // If start at ':', then the internal node has no name. current++; if (*current == ':') { start = current + 1; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); names->SetValue(node, ""); *current = temp; } else if (*current != ';' && *current != '\0') { // Find ':' to retrieve distance, if any. // At this time *current should equal to ')' start = current; while (*current != ':') { current++; } temp = *current; *current = '\0'; std::string name(start, strlen(start)); names->SetValue(node, name); *current = temp; current++; start = current; while (*current != '\0' && *current != ';') { current++; } temp = *current; *current = '\0'; weights->SetValue(g->GetEdgeId(parent, node), atof(start)); *current = temp; } } return node; } //---------------------------------------------------------------------------- int vtkNewickTreeReader::FillOutputPortInformation(int, vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkTree"); return 1; } //---------------------------------------------------------------------------- void vtkNewickTreeReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << endl; os << indent << "InputString: " << (this->InputString ? this->InputString : "(none)") << endl; os << indent << "ReadFromInputString: " << (this->ReadFromInputString ? "on" : "off") << endl; }
fix lingering off-by-one error
fix lingering off-by-one error The arrays added to the EdgeData and VertexData of the newly created tree were one tuple larger than they should have been. Change-Id: I4a33585a98f274ecfeb69c66ced5244a895f6fad
C++
bsd-3-clause
gram526/VTK,berendkleinhaneveld/VTK,keithroe/vtkoptix,sumedhasingla/VTK,msmolens/VTK,sankhesh/VTK,keithroe/vtkoptix,jmerkow/VTK,hendradarwin/VTK,gram526/VTK,keithroe/vtkoptix,sumedhasingla/VTK,SimVascular/VTK,sankhesh/VTK,jmerkow/VTK,candy7393/VTK,jmerkow/VTK,demarle/VTK,johnkit/vtk-dev,gram526/VTK,mspark93/VTK,mspark93/VTK,sankhesh/VTK,sumedhasingla/VTK,johnkit/vtk-dev,demarle/VTK,demarle/VTK,sankhesh/VTK,keithroe/vtkoptix,ashray/VTK-EVM,sankhesh/VTK,SimVascular/VTK,msmolens/VTK,SimVascular/VTK,keithroe/vtkoptix,msmolens/VTK,candy7393/VTK,jmerkow/VTK,hendradarwin/VTK,mspark93/VTK,mspark93/VTK,msmolens/VTK,ashray/VTK-EVM,johnkit/vtk-dev,johnkit/vtk-dev,mspark93/VTK,msmolens/VTK,jmerkow/VTK,jmerkow/VTK,jmerkow/VTK,sumedhasingla/VTK,mspark93/VTK,demarle/VTK,demarle/VTK,keithroe/vtkoptix,SimVascular/VTK,gram526/VTK,demarle/VTK,candy7393/VTK,sankhesh/VTK,msmolens/VTK,demarle/VTK,keithroe/vtkoptix,johnkit/vtk-dev,berendkleinhaneveld/VTK,hendradarwin/VTK,gram526/VTK,keithroe/vtkoptix,hendradarwin/VTK,gram526/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,jmerkow/VTK,mspark93/VTK,gram526/VTK,sumedhasingla/VTK,gram526/VTK,berendkleinhaneveld/VTK,candy7393/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,ashray/VTK-EVM,hendradarwin/VTK,hendradarwin/VTK,johnkit/vtk-dev,sankhesh/VTK,SimVascular/VTK,ashray/VTK-EVM,sumedhasingla/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,mspark93/VTK,berendkleinhaneveld/VTK,demarle/VTK,msmolens/VTK,ashray/VTK-EVM,sumedhasingla/VTK,ashray/VTK-EVM,ashray/VTK-EVM,candy7393/VTK,msmolens/VTK,johnkit/vtk-dev,SimVascular/VTK,candy7393/VTK,candy7393/VTK,ashray/VTK-EVM,candy7393/VTK,sankhesh/VTK,SimVascular/VTK
f34e568fc6c4b62df7b9af87fa828d250704643a
tree/src/TBranchClones.cxx
tree/src/TBranchClones.cxx
// @(#)root/tree:$Name: $:$Id: TBranchClones.cxx,v 1.3 2000/09/29 07:51:12 brun Exp $ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A Branch for the case of an array of clone objects // // // See TTree. // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TBranchClones.h" #include "TFile.h" #include "TTree.h" #include "TBasket.h" #include "TClass.h" #include "TRealData.h" #include "TDataType.h" #include "TDataMember.h" #include "TLeafI.h" R__EXTERN TTree *gTree; ClassImp(TBranchClones) //______________________________________________________________________________ TBranchClones::TBranchClones(): TBranch() { //*-*-*-*-*-*Default constructor for BranchClones*-*-*-*-*-*-*-*-*-* //*-* ==================================== fList = 0; fRead = 0; fN = 0; fNdataMax = 0; fBranchCount = 0; } //______________________________________________________________________________ TBranchClones::TBranchClones(const char *name, void *pointer, Int_t basketsize, Int_t compress, Int_t splitlevel) :TBranch() { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a BranchClones*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== // char leaflist[80]; char branchname[80]; char branchcount[64]; SetName(name); if (compress == -1 && gTree->GetDirectory()) { TFile *bfile = 0; if (gTree->GetDirectory()) bfile = gTree->GetDirectory()->GetFile(); if (bfile) compress = bfile->GetCompressionLevel(); } char *cpointer = (char*)pointer; char **ppointer = (char**)(cpointer); fList = (TClonesArray*)(*ppointer); fAddress = cpointer; fRead = 0; fN = 0; fNdataMax = 0; TClass *cl = fList->GetClass(); if (!cl) return; if (!cl->GetListOfRealData()) cl->BuildRealData(); fClassName = cl->GetName(); //*-*- Create a branch to store the array count if (basketsize < 100) basketsize = 100; sprintf(leaflist,"%s_/I",name); sprintf(branchcount,"%s_",name); fBranchCount = new TBranch(branchcount,&fN,leaflist,basketsize); fBranchCount->SetBit(kIsClone); TLeaf *leafcount = (TLeaf*)fBranchCount->GetListOfLeaves()->UncheckedAt(0); fTree = gTree; fDirectory = fTree->GetDirectory(); fFileName = ""; //*-*- Create the first basket TBasket *basket = new TBasket(branchcount,fTree->GetName(),this); fBaskets.Add(basket); //*-*- Loop on all public data members of the class and its base classes const char *itype = 0; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *member = rd->GetDataMember(); if (!member->IsPersistent()) continue; //do not process members with a ! as the first // character in the comment field if (!member->IsBasic() || member->IsaPointer() ) { Warning("BranchClones","Cannot process member:%s",member->GetName()); continue; } // forget TObject part if splitlevel = 2 if (splitlevel > 1 || fList->TestBit(TClonesArray::kForgetBits)) { if (strcmp(member->GetName(),"fBits") == 0) continue; if (strcmp(member->GetName(),"fUniqueID") == 0) continue; } TDataType *membertype = member->GetDataType(); Int_t type = membertype->GetType(); if (type == 0) { Warning("BranchClones","Cannot process member:%s",member->GetName()); continue; } if (type == 1) itype = "B"; if (type == 11) itype = "b"; if (type == 3) itype = "I"; if (type == 5) itype = "F"; if (type == 8) itype = "D"; if (type == 13) itype = "i"; if (type == 2) itype = "S"; if (type == 12) itype = "s"; sprintf(leaflist,"%s[%s]/%s",member->GetName(),branchcount,itype); Int_t comp = compress; if (type == 5) comp--; sprintf(branchname,"%s.%s",name,rd->GetName()); TBranch *branch = new TBranch(branchname,this,leaflist,basketsize,comp); branch->SetBit(kIsClone); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetOffset(rd->GetThisOffset()); leaf->SetLeafCount(leafcount); Int_t arraydim = member->GetArrayDim(); if (arraydim) { Int_t maxindex = member->GetMaxIndex(arraydim-1); leaf->SetLen(maxindex); } fBranches.Add(branch); } } //______________________________________________________________________________ TBranchClones::~TBranchClones() { //*-*-*-*-*-*Default destructor for a BranchClones*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================================== delete fBranchCount; fBranchCount = 0; fBranches.Delete(); fList = 0; } //______________________________________________________________________________ void TBranchClones::Browse(TBrowser *b) { fBranches.Browse( b ); } //______________________________________________________________________________ Int_t TBranchClones::Fill() { //*-*-*-*-*Loop on all Branches of this BranchClones to fill Basket buffer*-* //*-* =============================================================== Int_t i; Int_t nbytes = 0; Int_t nbranches = fBranches.GetEntriesFast(); char **ppointer = (char**)(fAddress); if (ppointer == 0) return 0; fList = (TClonesArray*)(*ppointer); fN = fList->GetEntriesFast(); fEntries++; if (fN > fNdataMax) { fNdataMax = fList->GetSize(); char branchcount[64]; sprintf(branchcount,"%s_",GetName()); TLeafI *leafi = (TLeafI*)fBranchCount->GetLeaf(branchcount); leafi->SetMaximum(fNdataMax); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.UncheckedAt(i); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetAddress(); } } nbytes += fBranchCount->Fill(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.UncheckedAt(i); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->Import(fList, fN); nbytes += branch->Fill(); } return nbytes; } //______________________________________________________________________________ Int_t TBranchClones::GetEntry(Int_t entry, Int_t getall) { //*-*-*-*-*Read all branches of a BranchClones and return total number of bytes //*-* ==================================================================== if (TestBit(kDoNotProcess) && !getall) return 0; Int_t nbytes = fBranchCount->GetEntry(entry); TLeaf *leafcount = (TLeaf*)fBranchCount->GetListOfLeaves()->UncheckedAt(0); fN = Int_t(leafcount->GetValue()); if (fN <= 0) return 0; TBranch *branch; Int_t nbranches = fBranches.GetEntriesFast(); // if fList exists, create clonesarray objects if (fList) { fList->Clear(); fList->ExpandCreateFast(fN); for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches.UncheckedAt(i); nbytes += branch->GetEntryExport(entry, getall, fList, fN); } } else { for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches.UncheckedAt(i); nbytes += branch->GetEntry(entry, getall); } } return nbytes; } //______________________________________________________________________________ void TBranchClones::Print(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*-*Print TBranch parameters*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== fBranchCount->Print(option); Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Print(option); } } //______________________________________________________________________________ void TBranchClones::Reset(Option_t *option) { //*-*-*-*-*-*-*-*Reset a Branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // // Existing buffers are deleted // Entries, max and min are reset // fEntries = 0; fTotBytes = 0; fZipBytes = 0; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Reset(option); } fBranchCount->Reset(); } //______________________________________________________________________________ void TBranchClones::SetAddress(void *add) { //*-*-*-*-*-*-*-*Set address of this branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== //*-* fReadEntry = -1; fAddress = (char*)add; char **ppointer = (char**)(fAddress); // test if the pointer is null // in this case create the correct TClonesArray if ( (*ppointer)==0 ) { *ppointer = (char*) new TClonesArray(fClassName); fAddress = (char*)ppointer; } fList = (TClonesArray*)(*ppointer); fBranchCount->SetAddress(&fN); } //______________________________________________________________________________ void TBranchClones::SetBasketSize(Int_t buffsize) { //*-*-*-*-*-*-*-*Reset basket size for all subbranches of this branchclones //*-* ========================================================== // fBasketSize = buffsize; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetBasketSize(buffsize); } } //_______________________________________________________________________ void TBranchClones::Streamer(TBuffer &b) { //*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= UInt_t R__s, R__c; if (b.IsReading()) { b.ReadVersion(&R__s, &R__c); TNamed::Streamer(b); b >> fCompress; b >> fBasketSize; b >> fEntryOffsetLen; b >> fMaxBaskets; b >> fWriteBasket; b >> fEntryNumber; b >> fEntries; b >> fTotBytes; b >> fZipBytes; b >> fOffset; b >> fBranchCount; fClassName.Streamer(b); fBranches.Streamer(b); fTree = gTree; TBranch *branch; TLeaf *leaf; Int_t nbranches = fBranches.GetEntriesFast(); for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches[i]; branch->SetBit(kIsClone); leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); leaf->SetOffset(0); } fRead = 1; TClass *cl = gROOT->GetClass((const char*)fClassName); if (!cl) { Warning("Streamer","Unknow class: %s. Cannot read BranchClones: %s", fClassName.Data(),GetName()); return; } if (!cl->GetListOfRealData()) cl->BuildRealData(); char branchname[80]; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *member = rd->GetDataMember(); if (!member->IsBasic()) continue; if (!member->IsPersistent()) continue; TDataType *membertype = member->GetDataType(); if (membertype->GetType() == 0) continue; sprintf(branchname,"%s.%s",GetName(),rd->GetName()); branch = (TBranch*)fBranches.FindObject(branchname); if (!branch) continue; TObjArray *leaves = branch->GetListOfLeaves(); leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetOffset(rd->GetThisOffset()); } b.CheckByteCount(R__s, R__c, TBranchClones::IsA()); } else { R__c = b.WriteVersion(TBranchClones::IsA(), kTRUE); TNamed::Streamer(b); b << fCompress; b << fBasketSize; b << fEntryOffsetLen; b << fMaxBaskets; b << fWriteBasket; b << fEntryNumber; b << fEntries; b << fTotBytes; b << fZipBytes; b << fOffset; b << fBranchCount; fClassName.Streamer(b); fBranches.Streamer(b); b.SetByteCount(R__c, kTRUE); } }
// @(#)root/tree:$Name: $:$Id: TBranchClones.cxx,v 1.4 2000/12/04 16:45:09 brun Exp $ // Author: Rene Brun 11/02/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A Branch for the case of an array of clone objects // // // See TTree. // // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TBranchClones.h" #include "TFile.h" #include "TTree.h" #include "TBasket.h" #include "TClass.h" #include "TRealData.h" #include "TDataType.h" #include "TDataMember.h" #include "TLeafI.h" R__EXTERN TTree *gTree; ClassImp(TBranchClones) //______________________________________________________________________________ TBranchClones::TBranchClones(): TBranch() { //*-*-*-*-*-*Default constructor for BranchClones*-*-*-*-*-*-*-*-*-* //*-* ==================================== fList = 0; fRead = 0; fN = 0; fNdataMax = 0; fBranchCount = 0; } //______________________________________________________________________________ TBranchClones::TBranchClones(const char *name, void *pointer, Int_t basketsize, Int_t compress, Int_t splitlevel) :TBranch() { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a BranchClones*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================== // char leaflist[80]; char branchname[80]; char branchcount[64]; SetName(name); if (compress == -1 && gTree->GetDirectory()) { TFile *bfile = 0; if (gTree->GetDirectory()) bfile = gTree->GetDirectory()->GetFile(); if (bfile) compress = bfile->GetCompressionLevel(); } char *cpointer = (char*)pointer; char **ppointer = (char**)(cpointer); fList = (TClonesArray*)(*ppointer); fAddress = cpointer; fRead = 0; fN = 0; fNdataMax = 0; TClass *cl = fList->GetClass(); if (!cl) return; if (!cl->GetListOfRealData()) cl->BuildRealData(); fClassName = cl->GetName(); //*-*- Create a branch to store the array count if (basketsize < 100) basketsize = 100; sprintf(leaflist,"%s_/I",name); sprintf(branchcount,"%s_",name); fBranchCount = new TBranch(branchcount,&fN,leaflist,basketsize); fBranchCount->SetBit(kIsClone); TLeaf *leafcount = (TLeaf*)fBranchCount->GetListOfLeaves()->UncheckedAt(0); fTree = gTree; fDirectory = fTree->GetDirectory(); fFileName = ""; //*-*- Create the first basket TBasket *basket = new TBasket(branchcount,fTree->GetName(),this); fBaskets.Add(basket); //*-*- Loop on all public data members of the class and its base classes const char *itype = 0; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *member = rd->GetDataMember(); if (!member->IsPersistent()) continue; //do not process members with a ! as the first // character in the comment field if (!member->IsBasic() || member->IsaPointer() ) { Warning("BranchClones","Cannot process member:%s",member->GetName()); continue; } // forget TObject part if splitlevel = 2 if (splitlevel > 1 || fList->TestBit(TClonesArray::kForgetBits)) { if (strcmp(member->GetName(),"fBits") == 0) continue; if (strcmp(member->GetName(),"fUniqueID") == 0) continue; } TDataType *membertype = member->GetDataType(); Int_t type = membertype->GetType(); if (type == 0) { Warning("BranchClones","Cannot process member:%s",member->GetName()); continue; } if (type == 1) itype = "B"; if (type == 11) itype = "b"; if (type == 3) itype = "I"; if (type == 5) itype = "F"; if (type == 8) itype = "D"; if (type == 13) itype = "i"; if (type == 2) itype = "S"; if (type == 12) itype = "s"; sprintf(leaflist,"%s[%s]/%s",member->GetName(),branchcount,itype); Int_t comp = compress; if (type == 5) comp--; sprintf(branchname,"%s.%s",name,rd->GetName()); TBranch *branch = new TBranch(branchname,this,leaflist,basketsize,comp); branch->SetBit(kIsClone); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetOffset(rd->GetThisOffset()); leaf->SetLeafCount(leafcount); Int_t arraydim = member->GetArrayDim(); if (arraydim) { Int_t maxindex=1; while (arraydim) { maxindex *= member->GetMaxIndex(--arraydim); } leaf->SetLen(maxindex); } fBranches.Add(branch); } } //______________________________________________________________________________ TBranchClones::~TBranchClones() { //*-*-*-*-*-*Default destructor for a BranchClones*-*-*-*-*-*-*-*-*-*-*-* //*-* ===================================== delete fBranchCount; fBranchCount = 0; fBranches.Delete(); fList = 0; } //______________________________________________________________________________ void TBranchClones::Browse(TBrowser *b) { fBranches.Browse( b ); } //______________________________________________________________________________ Int_t TBranchClones::Fill() { //*-*-*-*-*Loop on all Branches of this BranchClones to fill Basket buffer*-* //*-* =============================================================== Int_t i; Int_t nbytes = 0; Int_t nbranches = fBranches.GetEntriesFast(); char **ppointer = (char**)(fAddress); if (ppointer == 0) return 0; fList = (TClonesArray*)(*ppointer); fN = fList->GetEntriesFast(); fEntries++; if (fN > fNdataMax) { fNdataMax = fList->GetSize(); char branchcount[64]; sprintf(branchcount,"%s_",GetName()); TLeafI *leafi = (TLeafI*)fBranchCount->GetLeaf(branchcount); leafi->SetMaximum(fNdataMax); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.UncheckedAt(i); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetAddress(); } } nbytes += fBranchCount->Fill(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches.UncheckedAt(i); TObjArray *leaves = branch->GetListOfLeaves(); TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->Import(fList, fN); nbytes += branch->Fill(); } return nbytes; } //______________________________________________________________________________ Int_t TBranchClones::GetEntry(Int_t entry, Int_t getall) { //*-*-*-*-*Read all branches of a BranchClones and return total number of bytes //*-* ==================================================================== if (TestBit(kDoNotProcess) && !getall) return 0; Int_t nbytes = fBranchCount->GetEntry(entry); TLeaf *leafcount = (TLeaf*)fBranchCount->GetListOfLeaves()->UncheckedAt(0); fN = Int_t(leafcount->GetValue()); if (fN <= 0) return 0; TBranch *branch; Int_t nbranches = fBranches.GetEntriesFast(); // if fList exists, create clonesarray objects if (fList) { fList->Clear(); fList->ExpandCreateFast(fN); for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches.UncheckedAt(i); nbytes += branch->GetEntryExport(entry, getall, fList, fN); } } else { for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches.UncheckedAt(i); nbytes += branch->GetEntry(entry, getall); } } return nbytes; } //______________________________________________________________________________ void TBranchClones::Print(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*-*Print TBranch parameters*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== fBranchCount->Print(option); Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Print(option); } } //______________________________________________________________________________ void TBranchClones::Reset(Option_t *option) { //*-*-*-*-*-*-*-*Reset a Branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== // // Existing buffers are deleted // Entries, max and min are reset // fEntries = 0; fTotBytes = 0; fZipBytes = 0; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->Reset(option); } fBranchCount->Reset(); } //______________________________________________________________________________ void TBranchClones::SetAddress(void *add) { //*-*-*-*-*-*-*-*Set address of this branch*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ==================== //*-* fReadEntry = -1; fAddress = (char*)add; char **ppointer = (char**)(fAddress); // test if the pointer is null // in this case create the correct TClonesArray if ( (*ppointer)==0 ) { *ppointer = (char*) new TClonesArray(fClassName); fAddress = (char*)ppointer; } fList = (TClonesArray*)(*ppointer); fBranchCount->SetAddress(&fN); } //______________________________________________________________________________ void TBranchClones::SetBasketSize(Int_t buffsize) { //*-*-*-*-*-*-*-*Reset basket size for all subbranches of this branchclones //*-* ========================================================== // fBasketSize = buffsize; Int_t i; Int_t nbranches = fBranches.GetEntriesFast(); for (i=0;i<nbranches;i++) { TBranch *branch = (TBranch*)fBranches[i]; branch->SetBasketSize(buffsize); } } //_______________________________________________________________________ void TBranchClones::Streamer(TBuffer &b) { //*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= UInt_t R__s, R__c; if (b.IsReading()) { b.ReadVersion(&R__s, &R__c); TNamed::Streamer(b); b >> fCompress; b >> fBasketSize; b >> fEntryOffsetLen; b >> fMaxBaskets; b >> fWriteBasket; b >> fEntryNumber; b >> fEntries; b >> fTotBytes; b >> fZipBytes; b >> fOffset; b >> fBranchCount; fClassName.Streamer(b); fBranches.Streamer(b); fTree = gTree; TBranch *branch; TLeaf *leaf; Int_t nbranches = fBranches.GetEntriesFast(); for (Int_t i=0;i<nbranches;i++) { branch = (TBranch*)fBranches[i]; branch->SetBit(kIsClone); leaf = (TLeaf*)branch->GetListOfLeaves()->UncheckedAt(0); leaf->SetOffset(0); } fRead = 1; TClass *cl = gROOT->GetClass((const char*)fClassName); if (!cl) { Warning("Streamer","Unknow class: %s. Cannot read BranchClones: %s", fClassName.Data(),GetName()); return; } if (!cl->GetListOfRealData()) cl->BuildRealData(); char branchname[80]; TRealData *rd; TIter next(cl->GetListOfRealData()); while ((rd = (TRealData *) next())) { TDataMember *member = rd->GetDataMember(); if (!member->IsBasic()) continue; if (!member->IsPersistent()) continue; TDataType *membertype = member->GetDataType(); if (membertype->GetType() == 0) continue; sprintf(branchname,"%s.%s",GetName(),rd->GetName()); branch = (TBranch*)fBranches.FindObject(branchname); if (!branch) continue; TObjArray *leaves = branch->GetListOfLeaves(); leaf = (TLeaf*)leaves->UncheckedAt(0); leaf->SetOffset(rd->GetThisOffset()); } b.CheckByteCount(R__s, R__c, TBranchClones::IsA()); } else { R__c = b.WriteVersion(TBranchClones::IsA(), kTRUE); TNamed::Streamer(b); b << fCompress; b << fBasketSize; b << fEntryOffsetLen; b << fMaxBaskets; b << fWriteBasket; b << fEntryNumber; b << fEntries; b << fTotBytes; b << fZipBytes; b << fOffset; b << fBranchCount; fClassName.Streamer(b); fBranches.Streamer(b); b.SetByteCount(R__c, kTRUE); } }
Fix a bug in TBranchClones.cxx in case the class in the TClonesArray has a member that is a multi-dim array (thanks Emmanuel Gangler)
Fix a bug in TBranchClones.cxx in case the class in the TClonesArray has a member that is a multi-dim array (thanks Emmanuel Gangler) git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@1145 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
tc3t/qoot,omazapa/root-old,perovic/root,gbitzes/root,esakellari/root,beniz/root,esakellari/my_root_for_test,bbockelm/root,perovic/root,omazapa/root-old,esakellari/my_root_for_test,tc3t/qoot,davidlt/root,mkret2/root,karies/root,gbitzes/root,esakellari/root,root-mirror/root,vukasinmilosevic/root,dfunke/root,krafczyk/root,esakellari/root,gganis/root,perovic/root,zzxuanyuan/root,thomaskeck/root,zzxuanyuan/root,abhinavmoudgil95/root,0x0all/ROOT,beniz/root,smarinac/root,krafczyk/root,evgeny-boger/root,dfunke/root,arch1tect0r/root,beniz/root,gganis/root,mattkretz/root,buuck/root,BerserkerTroll/root,esakellari/my_root_for_test,Dr15Jones/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,Dr15Jones/root,gbitzes/root,sirinath/root,Dr15Jones/root,sirinath/root,CristinaCristescu/root,tc3t/qoot,CristinaCristescu/root,Y--/root,agarciamontoro/root,Duraznos/root,georgtroska/root,cxx-hep/root-cern,arch1tect0r/root,pspe/root,arch1tect0r/root,jrtomps/root,smarinac/root,davidlt/root,gganis/root,smarinac/root,bbockelm/root,lgiommi/root,dfunke/root,gbitzes/root,pspe/root,mhuwiler/rootauto,jrtomps/root,sbinet/cxx-root,nilqed/root,BerserkerTroll/root,abhinavmoudgil95/root,vukasinmilosevic/root,mhuwiler/rootauto,krafczyk/root,lgiommi/root,veprbl/root,vukasinmilosevic/root,omazapa/root,bbockelm/root,mattkretz/root,lgiommi/root,sawenzel/root,evgeny-boger/root,olifre/root,jrtomps/root,mkret2/root,bbockelm/root,mattkretz/root,Y--/root,omazapa/root-old,perovic/root,nilqed/root,satyarth934/root,omazapa/root,vukasinmilosevic/root,vukasinmilosevic/root,root-mirror/root,omazapa/root-old,krafczyk/root,satyarth934/root,davidlt/root,kirbyherm/root-r-tools,gganis/root,esakellari/my_root_for_test,jrtomps/root,root-mirror/root,CristinaCristescu/root,omazapa/root-old,ffurano/root5,omazapa/root-old,georgtroska/root,bbockelm/root,sawenzel/root,beniz/root,esakellari/root,Duraznos/root,simonpf/root,gbitzes/root,alexschlueter/cern-root,nilqed/root,Y--/root,krafczyk/root,Duraznos/root,evgeny-boger/root,buuck/root,CristinaCristescu/root,cxx-hep/root-cern,zzxuanyuan/root-compressor-dummy,Duraznos/root,georgtroska/root,georgtroska/root,ffurano/root5,veprbl/root,cxx-hep/root-cern,perovic/root,pspe/root,gganis/root,davidlt/root,strykejern/TTreeReader,bbockelm/root,omazapa/root,agarciamontoro/root,omazapa/root-old,karies/root,dfunke/root,sawenzel/root,strykejern/TTreeReader,beniz/root,gganis/root,beniz/root,nilqed/root,Duraznos/root,root-mirror/root,omazapa/root,agarciamontoro/root,simonpf/root,satyarth934/root,olifre/root,omazapa/root-old,veprbl/root,abhinavmoudgil95/root,vukasinmilosevic/root,pspe/root,mhuwiler/rootauto,strykejern/TTreeReader,mkret2/root,jrtomps/root,thomaskeck/root,sirinath/root,krafczyk/root,mkret2/root,jrtomps/root,smarinac/root,krafczyk/root,nilqed/root,tc3t/qoot,sbinet/cxx-root,sirinath/root,CristinaCristescu/root,evgeny-boger/root,mkret2/root,esakellari/my_root_for_test,evgeny-boger/root,jrtomps/root,BerserkerTroll/root,omazapa/root-old,root-mirror/root,jrtomps/root,zzxuanyuan/root,mkret2/root,sbinet/cxx-root,BerserkerTroll/root,evgeny-boger/root,ffurano/root5,Y--/root,arch1tect0r/root,mattkretz/root,sirinath/root,ffurano/root5,kirbyherm/root-r-tools,zzxuanyuan/root-compressor-dummy,omazapa/root,sbinet/cxx-root,ffurano/root5,satyarth934/root,krafczyk/root,esakellari/root,karies/root,esakellari/my_root_for_test,omazapa/root,tc3t/qoot,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,davidlt/root,nilqed/root,olifre/root,root-mirror/root,karies/root,zzxuanyuan/root,gbitzes/root,buuck/root,CristinaCristescu/root,gganis/root,sawenzel/root,esakellari/root,BerserkerTroll/root,smarinac/root,olifre/root,zzxuanyuan/root-compressor-dummy,Y--/root,perovic/root,olifre/root,nilqed/root,buuck/root,karies/root,lgiommi/root,davidlt/root,perovic/root,gbitzes/root,karies/root,strykejern/TTreeReader,satyarth934/root,cxx-hep/root-cern,mattkretz/root,BerserkerTroll/root,root-mirror/root,kirbyherm/root-r-tools,agarciamontoro/root,mattkretz/root,Dr15Jones/root,CristinaCristescu/root,tc3t/qoot,pspe/root,simonpf/root,mhuwiler/rootauto,simonpf/root,georgtroska/root,evgeny-boger/root,satyarth934/root,lgiommi/root,thomaskeck/root,karies/root,buuck/root,omazapa/root,mattkretz/root,arch1tect0r/root,sbinet/cxx-root,veprbl/root,lgiommi/root,Y--/root,tc3t/qoot,cxx-hep/root-cern,evgeny-boger/root,veprbl/root,bbockelm/root,tc3t/qoot,abhinavmoudgil95/root,simonpf/root,smarinac/root,esakellari/my_root_for_test,davidlt/root,Dr15Jones/root,arch1tect0r/root,gbitzes/root,BerserkerTroll/root,tc3t/qoot,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,sawenzel/root,CristinaCristescu/root,sawenzel/root,mattkretz/root,mkret2/root,zzxuanyuan/root-compressor-dummy,davidlt/root,karies/root,Y--/root,Y--/root,olifre/root,davidlt/root,esakellari/my_root_for_test,omazapa/root,dfunke/root,sawenzel/root,pspe/root,strykejern/TTreeReader,olifre/root,dfunke/root,satyarth934/root,zzxuanyuan/root,perovic/root,strykejern/TTreeReader,lgiommi/root,georgtroska/root,beniz/root,BerserkerTroll/root,lgiommi/root,simonpf/root,cxx-hep/root-cern,gganis/root,Duraznos/root,mhuwiler/rootauto,BerserkerTroll/root,thomaskeck/root,sbinet/cxx-root,mhuwiler/rootauto,sirinath/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,arch1tect0r/root,abhinavmoudgil95/root,smarinac/root,gganis/root,mhuwiler/rootauto,omazapa/root,gganis/root,smarinac/root,davidlt/root,thomaskeck/root,sawenzel/root,Y--/root,buuck/root,dfunke/root,vukasinmilosevic/root,krafczyk/root,mkret2/root,veprbl/root,Dr15Jones/root,krafczyk/root,alexschlueter/cern-root,nilqed/root,pspe/root,cxx-hep/root-cern,agarciamontoro/root,sirinath/root,sawenzel/root,kirbyherm/root-r-tools,sirinath/root,sbinet/cxx-root,sawenzel/root,pspe/root,jrtomps/root,esakellari/root,sbinet/cxx-root,veprbl/root,abhinavmoudgil95/root,kirbyherm/root-r-tools,nilqed/root,tc3t/qoot,sirinath/root,smarinac/root,perovic/root,bbockelm/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,simonpf/root,gbitzes/root,karies/root,strykejern/TTreeReader,beniz/root,lgiommi/root,mhuwiler/rootauto,mkret2/root,georgtroska/root,mhuwiler/rootauto,jrtomps/root,beniz/root,alexschlueter/cern-root,0x0all/ROOT,buuck/root,0x0all/ROOT,arch1tect0r/root,thomaskeck/root,vukasinmilosevic/root,perovic/root,zzxuanyuan/root,karies/root,zzxuanyuan/root,thomaskeck/root,olifre/root,mhuwiler/rootauto,esakellari/my_root_for_test,esakellari/my_root_for_test,gbitzes/root,Duraznos/root,olifre/root,esakellari/root,arch1tect0r/root,agarciamontoro/root,bbockelm/root,zzxuanyuan/root,0x0all/ROOT,abhinavmoudgil95/root,pspe/root,alexschlueter/cern-root,0x0all/ROOT,mattkretz/root,evgeny-boger/root,Dr15Jones/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,veprbl/root,root-mirror/root,buuck/root,simonpf/root,satyarth934/root,Y--/root,abhinavmoudgil95/root,perovic/root,CristinaCristescu/root,buuck/root,esakellari/root,karies/root,omazapa/root-old,georgtroska/root,sawenzel/root,mkret2/root,CristinaCristescu/root,beniz/root,nilqed/root,BerserkerTroll/root,Duraznos/root,dfunke/root,thomaskeck/root,beniz/root,root-mirror/root,zzxuanyuan/root,bbockelm/root,0x0all/ROOT,omazapa/root-old,Duraznos/root,georgtroska/root,satyarth934/root,simonpf/root,olifre/root,zzxuanyuan/root,dfunke/root,dfunke/root,smarinac/root,olifre/root,mkret2/root,simonpf/root,lgiommi/root,buuck/root,zzxuanyuan/root-compressor-dummy,ffurano/root5,lgiommi/root,kirbyherm/root-r-tools,sirinath/root,veprbl/root,jrtomps/root,pspe/root,satyarth934/root,gbitzes/root,evgeny-boger/root,zzxuanyuan/root,agarciamontoro/root,agarciamontoro/root,sbinet/cxx-root,mattkretz/root,veprbl/root,georgtroska/root,agarciamontoro/root,vukasinmilosevic/root,zzxuanyuan/root,omazapa/root,arch1tect0r/root,Y--/root,alexschlueter/cern-root,davidlt/root,gganis/root,dfunke/root,nilqed/root,vukasinmilosevic/root,thomaskeck/root,vukasinmilosevic/root,pspe/root,alexschlueter/cern-root,kirbyherm/root-r-tools,buuck/root,esakellari/root,0x0all/ROOT,0x0all/ROOT,arch1tect0r/root,alexschlueter/cern-root,abhinavmoudgil95/root,esakellari/root,bbockelm/root,sirinath/root,abhinavmoudgil95/root,krafczyk/root,sbinet/cxx-root,simonpf/root,root-mirror/root,cxx-hep/root-cern,georgtroska/root,BerserkerTroll/root,mhuwiler/rootauto,CristinaCristescu/root,veprbl/root,omazapa/root,satyarth934/root,Duraznos/root,ffurano/root5,Duraznos/root,mattkretz/root
a149b82b135f8970813293339f566a473a0283c0
modules/SofaBoundaryCondition/SofaBoundaryCondition_test/FixedConstraint_test.cpp
modules/SofaBoundaryCondition/SofaBoundaryCondition_test/FixedConstraint_test.cpp
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <SofaTest/Sofa_test.h> #include <SofaTest/TestMessageHandler.h> #include <SofaBoundaryCondition/FixedConstraint.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/simulation/Simulation.h> #include <SofaSimulationGraph/DAGSimulation.h> #include <sofa/simulation/Node.h> #include <SofaBaseMechanics/MechanicalObject.h> #include <SofaBaseMechanics/UniformMass.h> #include <SceneCreator/SceneCreator.h> #include <SofaBoundaryCondition/ConstantForceField.h> namespace sofa{ namespace { using namespace modeling; using core::objectmodel::New; template<typename DataTypes> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<DataTypes>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<DataTypes, typename DataTypes::Real> >()); } template<> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<defaulttype::Rigid3Types>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<defaulttype::Rigid3Types, defaulttype::Rigid3Mass> >()); } template<> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<defaulttype::Rigid2Types>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<defaulttype::Rigid2Types, defaulttype::Rigid2Mass> >()); } template <typename _DataTypes> struct FixedConstraint_test : public Sofa_test<typename _DataTypes::Real> { typedef _DataTypes DataTypes; typedef component::projectiveconstraintset::FixedConstraint<DataTypes> FixedConstraint; typedef component::forcefield::ConstantForceField<DataTypes> ForceField; typedef component::container::MechanicalObject<DataTypes> MechanicalObject; typedef typename MechanicalObject::VecCoord VecCoord; typedef typename MechanicalObject::Coord Coord; typedef typename MechanicalObject::VecDeriv VecDeriv; typedef typename MechanicalObject::Deriv Deriv; typedef typename DataTypes::Real Real; bool test(double epsilon, const std::string &integrationScheme ) { //Init simulation::Simulation* simulation; sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); Coord initCoord; Deriv force; for(unsigned i=0; i<force.size(); i++) force[i]=10; /// Scene creation simulation::Node::SPtr root = simulation->createNewGraph("root"); root->setGravity( defaulttype::Vector3(0,0,0) ); simulation::Node::SPtr node = createEulerSolverNode(root,"test", integrationScheme); typename MechanicalObject::SPtr dofs = addNew<MechanicalObject>(node); dofs->resize(1); createUniformMass<DataTypes>(node, *dofs.get()); typename ForceField::SPtr forceField = addNew<ForceField>(node); forceField->setForce( 0, force ); node->addObject(sofa::core::objectmodel::New<FixedConstraint>()); // Init simulation sofa::simulation::getSimulation()->init(root.get()); // Perform one time step sofa::simulation::getSimulation()->animate(root.get(),0.5); // Check if the particle moved typename MechanicalObject::ReadVecCoord readX = dofs->readPositions(); if( (readX[0]-initCoord).norm2()>epsilon ) { ADD_FAILURE() << "Error: unmatching position between " << readX[0] << " and " << initCoord<< std::endl; return false; } return true; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< defaulttype::Vec1Types, defaulttype::Vec2Types, defaulttype::Vec3Types, defaulttype::Vec6Types, defaulttype::Rigid2Types, defaulttype::Rigid3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(FixedConstraint_test, DataTypes); // first test case TYPED_TEST( FixedConstraint_test , testValueImplicitWithCG ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8,std::string("Implicit")) ); } TYPED_TEST( FixedConstraint_test , testValueExplicit ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8, std::string("Explicit")) ); } #ifdef SOFA_HAVE_METIS TYPED_TEST( FixedConstraint_test , testValueImplicitWithSparseLDL ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8, std::string("Implicit_SparseLDL")) ); } #endif }// namespace }// namespace sofa
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <SofaTest/Sofa_test.h> #include <SofaTest/TestMessageHandler.h> #include <SofaBoundaryCondition/FixedConstraint.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/simulation/Simulation.h> #include <SofaSimulationGraph/DAGSimulation.h> #include <sofa/simulation/Node.h> #include <SofaBaseMechanics/MechanicalObject.h> #include <SofaBaseMechanics/UniformMass.h> #include <SceneCreator/SceneCreator.h> #include <SofaBoundaryCondition/ConstantForceField.h> namespace sofa{ namespace { using namespace modeling; using core::objectmodel::New; template<typename DataTypes> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<DataTypes>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<DataTypes, typename DataTypes::Real> >()); } template<> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<defaulttype::Rigid3Types>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<defaulttype::Rigid3Types, defaulttype::Rigid3Mass> >()); } template<> void createUniformMass(simulation::Node::SPtr node, component::container::MechanicalObject<defaulttype::Rigid2Types>& /*dofs*/) { node->addObject(New<component::mass::UniformMass<defaulttype::Rigid2Types, defaulttype::Rigid2Mass> >()); } template <typename _DataTypes> struct FixedConstraint_test : public Sofa_test<typename _DataTypes::Real> { typedef _DataTypes DataTypes; typedef component::projectiveconstraintset::FixedConstraint<DataTypes> FixedConstraint; typedef component::forcefield::ConstantForceField<DataTypes> ForceField; typedef component::container::MechanicalObject<DataTypes> MechanicalObject; typedef typename MechanicalObject::VecCoord VecCoord; typedef typename MechanicalObject::Coord Coord; typedef typename MechanicalObject::VecDeriv VecDeriv; typedef typename MechanicalObject::Deriv Deriv; typedef typename DataTypes::Real Real; bool test(double epsilon, const std::string &integrationScheme ) { //Init simulation::Simulation* simulation; sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); Coord initCoord1, initCoord2; Deriv force; for(unsigned i=0; i<force.size(); i++) force[i]=10; /// Scene creation simulation::Node::SPtr root = simulation->createNewGraph("root"); root->setGravity( defaulttype::Vector3(0,0,0) ); simulation::Node::SPtr node = createEulerSolverNode(root,"test", integrationScheme); typename MechanicalObject::SPtr dofs = addNew<MechanicalObject>(node); dofs->resize(2); typename MechanicalObject::WriteVecCoord writeX = dofs->writePositions(); for(unsigned int i=0;i<writeX[0].size();i++) { writeX[0][i] = 1.0+0.1*i ; writeX[1][i] = 2.0+0.1*i ; } typename MechanicalObject::ReadVecCoord readX = dofs->readPositions(); initCoord1 = readX[0]; initCoord2 = readX[1]; createUniformMass<DataTypes>(node, *dofs.get()); typename ForceField::SPtr forceField = addNew<ForceField>(node); forceField->setForce( 0, force ); forceField->setForce( 1, force ); /// Let's fix the particle's movement for particle number 1 (the second one). typename FixedConstraint::SPtr cst = sofa::core::objectmodel::New<FixedConstraint>(); cst->findData("indices")->read("1"); node->addObject(cst); /// Init simulation sofa::simulation::getSimulation()->init(root.get()); /// Perform one time step sofa::simulation::getSimulation()->animate(root.get(),0.5); /// Check if the first particle moved...this one should because it is not fixed /// so it is a failure if the particle is not moving at all. if( (readX[0]-initCoord1).norm2() < epsilon ) { ADD_FAILURE() << "similar position between [" << "-> " << readX[0] << ", " << readX[1] << "] and [" << "-> " << initCoord1 << ", " << initCoord2 << "] while they shouldn't." << std::endl; return false; } /// Check if the second particle have not moved. This one shouldn't move so it is /// a failure if it does. if( (readX[1]-initCoord2).norm2() >= epsilon ) { ADD_FAILURE() << "different position between [" << readX[0] << ", ->" << readX[1] << "] and [" << initCoord1 << ", ->" << initCoord2 << "] while they shouldn't." << std::endl; return false; } return true; } }; // Define the list of DataTypes to instanciate using testing::Types; typedef Types< defaulttype::Vec1Types, defaulttype::Vec2Types, defaulttype::Vec3Types, defaulttype::Vec6Types, defaulttype::Rigid2Types, defaulttype::Rigid3Types > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(FixedConstraint_test, DataTypes); // first test case TYPED_TEST( FixedConstraint_test , testValueImplicitWithCG ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8,std::string("Implicit")) ); } TYPED_TEST( FixedConstraint_test , testValueExplicit ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8, std::string("Explicit")) ); } #ifdef SOFA_HAVE_METIS TYPED_TEST( FixedConstraint_test , testValueImplicitWithSparseLDL ) { EXPECT_MSG_NOEMIT(Error) ; EXPECT_TRUE( this->test(1e-8, std::string("Implicit_SparseLDL")) ); } #endif }// namespace }// namespace sofa
Increase the test strengh to detect more efficiently the defect.
[FixedConstraint_test] Increase the test strengh to detect more efficiently the defect.
C++
lgpl-2.1
FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,Anatoscope/sofa,FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa
729ce18f5ed1c2dffb59604f71d44395e93f80c8
core/base/v7/inc/ROOT/TLogger.hxx
core/base/v7/inc/ROOT/TLogger.hxx
/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <[email protected]> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "ROOT/RStringView.hxx" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); /// Returns false if further emission of this Log should be suppressed. virtual bool Emit(const TLogEntry &entry) = 0; }; /** A TLogHandler that multiplexes diagnostics to different client `TLogHandler`s. `TLogHandler::Get()` returns the process's (static) log manager. */ class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; long long fNumWarnings{0}; long long fNumErrors{0}; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } /// Returns the current number of warnings seen by this log manager. long long GetNumWarnings() const { return fNumWarnings; } /// Returns the current number of errors seen by this log manager. long long GetNumErrors() const { return fNumErrors; } }; /** Object to count the number of warnings and errors emitted by a section of code, after construction of this type. */ class TLogDiagCounter { private: /// The number of the TLogManager's emitted warnings at construction time of *this. long long fInitialWarnings{TLogManager::Get().GetNumWarnings()}; /// The number of the TLogManager's emitted errors at construction time. long long fInitialErrors{TLogManager::Get().GetNumErrors()}; public: /// Get the number of warnings that the TLogManager has emitted since construction of *this. long long GetAccumulatedWarnings() const { return TLogManager::Get().GetNumWarnings() - fInitialWarnings; } /// Get the number of errors that the TLogManager has emitted since construction of *this. long long GetAccumulatedErrors() const { return TLogManager::Get().GetNumErrors() - fInitialErrors; } /// Whether the TLogManager has emitted a warnings since construction time of *this. bool HasWarningOccurred() const { return GetAccumulatedWarnings(); } /// Whether the TLogManager has emitted an error since construction time of *this. bool HasErrorOccurred() const { return GetAccumulatedErrors(); } /// Whether the TLogManager has emitted an error or a warning since construction time of *this. bool HasErrorOrWarningOccurred() const { return HasWarningOccurred() || HasErrorOccurred(); } }; /** A diagnostic, emitted by the TLogManager upon destruction of the TLogEntry. One can construct a TLogEntry through the utility preprocessor macros R__ERROR_HERE, R__WARNING_HERE etc like this: R__INFO_HERE("CodeGroupForInstanceLibrary") << "All we know is " << 42; This will automatically capture the current class and function name, the file and line number. */ class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define R__LOG_PRETTY_FUNCTION __FUNCSIG__ #else #define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(R__LOG_PRETTY_FUNCTION) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif
/// \file ROOT/TLogger.h /// \ingroup Base ROOT7 /// \author Axel Naumann <[email protected]> /// \date 2015-03-29 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TLog #define ROOT7_TLog #include <array> #include <memory> #include <sstream> #include "ROOT/RStringView.hxx" #include <vector> namespace ROOT { namespace Experimental { /** Kinds of diagnostics. */ enum class ELogLevel { kDebug, ///< Debug information; only useful for developers kInfo, ///< Informational messages; used for instance for tracing kWarning, ///< Warnings about likely unexpected behavior kError, kFatal }; class TLogEntry; /** Abstract TLogHandler base class. ROOT logs everything from info to error to entities of this class. */ class TLogHandler { public: virtual ~TLogHandler(); /// Emit a log entry. /// \param entry - the TLogEntry to be emitted. /// \returns false if further emission of this Log should be suppressed. /// /// \note This function is called concurrently; log emission must be locked /// if needed. (The default log handler using ROOT's DefaultErrorHandler is locked.) virtual bool Emit(const TLogEntry &entry) = 0; }; /** A TLogHandler that multiplexes diagnostics to different client `TLogHandler`s. `TLogHandler::Get()` returns the process's (static) log manager. */ class TLogManager: public TLogHandler { private: std::vector<std::unique_ptr<TLogHandler>> fHandlers; long long fNumWarnings{0}; long long fNumErrors{0}; /// Initialize taking a TLogHandlerDefault. TLogManager(std::unique_ptr<TLogHandler> &&lh) { fHandlers.emplace_back(std::move(lh)); } public: static TLogManager &Get(); /// Add a TLogHandler in the front - to be called before all others. void PushFront(std::unique_ptr<TLogHandler> handler) { fHandlers.insert(fHandlers.begin(), std::move(handler)); } /// Add a TLogHandler in the back - to be called after all others. void PushBack(std::unique_ptr<TLogHandler> handler) { fHandlers.emplace_back(std::move(handler)); } // Emit a `TLogEntry` to the TLogHandlers. // Returns false if further emission of this Log should be suppressed. bool Emit(const TLogEntry &entry) override { for (auto &&handler: fHandlers) if (!handler->Emit(entry)) return false; return true; } /// Returns the current number of warnings seen by this log manager. long long GetNumWarnings() const { return fNumWarnings; } /// Returns the current number of errors seen by this log manager. long long GetNumErrors() const { return fNumErrors; } }; /** Object to count the number of warnings and errors emitted by a section of code, after construction of this type. */ class TLogDiagCounter { private: /// The number of the TLogManager's emitted warnings at construction time of *this. long long fInitialWarnings{TLogManager::Get().GetNumWarnings()}; /// The number of the TLogManager's emitted errors at construction time. long long fInitialErrors{TLogManager::Get().GetNumErrors()}; public: /// Get the number of warnings that the TLogManager has emitted since construction of *this. long long GetAccumulatedWarnings() const { return TLogManager::Get().GetNumWarnings() - fInitialWarnings; } /// Get the number of errors that the TLogManager has emitted since construction of *this. long long GetAccumulatedErrors() const { return TLogManager::Get().GetNumErrors() - fInitialErrors; } /// Whether the TLogManager has emitted a warnings since construction time of *this. bool HasWarningOccurred() const { return GetAccumulatedWarnings(); } /// Whether the TLogManager has emitted an error since construction time of *this. bool HasErrorOccurred() const { return GetAccumulatedErrors(); } /// Whether the TLogManager has emitted an error or a warning since construction time of *this. bool HasErrorOrWarningOccurred() const { return HasWarningOccurred() || HasErrorOccurred(); } }; /** A diagnostic, emitted by the TLogManager upon destruction of the TLogEntry. One can construct a TLogEntry through the utility preprocessor macros R__ERROR_HERE, R__WARNING_HERE etc like this: R__INFO_HERE("CodeGroupForInstanceLibrary") << "All we know is " << 42; This will automatically capture the current class and function name, the file and line number. */ class TLogEntry: public std::ostringstream { public: std::string fGroup; std::string fFile; std::string fFuncName; int fLine = 0; ELogLevel fLevel; public: TLogEntry() = default; TLogEntry(ELogLevel level, std::string_view group): fGroup(group), fLevel(level) {} TLogEntry(ELogLevel level, std::string_view group, std::string_view filename, int line, std::string_view funcname) : fGroup(group), fFile(filename), fFuncName(funcname), fLine(line), fLevel(level) {} TLogEntry &SetFile(const std::string &file) { fFile = file; return *this; } TLogEntry &SetFunction(const std::string &func) { fFuncName = func; return *this; } TLogEntry &SetLine(int line) { fLine = line; return *this; } ~TLogEntry() { TLogManager::Get().Emit(*this); } }; } // namespace Experimental } // namespace ROOT #if defined(_MSC_VER) #define R__LOG_PRETTY_FUNCTION __FUNCSIG__ #else #define R__LOG_PRETTY_FUNCTION __PRETTY_FUNCTION__ #endif #define R__LOG_HERE(LEVEL, GROUP) \ ROOT::Experimental::TLogEntry(LEVEL, GROUP).SetFile(__FILE__).SetLine(__LINE__).SetFunction(R__LOG_PRETTY_FUNCTION) #define R__FATAL_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kFatal, GROUP) #define R__ERROR_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kError, GROUP) #define R__WARNING_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kWarning, GROUP) #define R__INFO_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kInfo, GROUP) #define R__DEBUG_HERE(GROUP) R__LOG_HERE(ROOT::Experimental::ELogLevel::kDebug, GROUP) #endif
Clarify that log emission needs to be locked.
Clarify that log emission needs to be locked.
C++
lgpl-2.1
olifre/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,karies/root,olifre/root,karies/root,karies/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,karies/root,karies/root,karies/root,karies/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,karies/root
b8e4b183a430cc3cfdc7e2aea69c81b2725eb8e6
DXCompress/main.cpp
DXCompress/main.cpp
// // main.cpp // DXCompress // // Created by Oliver Kahrmann on 08.05.11. // Copyright 2011 DHELIXSoft. All rights reserved. // #include <iostream> #include <string> #include <fstream> #include <math.h> #include <deque> #include <stack> using namespace std; class area { long pos; long length; }; void compress() { cout << "Filename to compress: "; //Startvariablen string filename; fstream compressfile; long datalength; char *tempdata; fstream output; //Kompressorvariablen stack<long> matches; long pruefblocklaenge; long pruefposition; long pruefblockposition; string data; //Zu komprimierende Datei öffnen cin >> filename; compressfile.open(filename.c_str(), ios::in); //Daten in Speicher laden compressfile.seekg(0, ios::end); datalength = compressfile.tellg(); datalength++; compressfile.seekg(0, ios::beg); if(datalength < 10) { cout << "The file is shorter than 10 characters. There is no value for compression." << endl; return; } tempdata = new char[datalength]; compressfile.read(tempdata, datalength); data.append(tempdata); //Zu komprimierende Daten werden nicht mehr gebraucht, also schließen. compressfile.close(); //Ausgabedatei öffnen output.open("compressed.txt", ios::out); //Prüfblocklänge auf die Hälfte der Datei setzen pruefblocklaenge = floor(datalength/2); if(pruefblocklaenge > 100) { pruefblocklaenge = 100; } //cout << data; while (true) { //Prüfblock auf Start setzen pruefblockposition = 0; //Statusausgabe cout << "Datalength: " << data.length() << ", "; cout << "Checkblocklength: " << pruefblocklaenge << endl; while ((pruefblocklaenge+pruefblockposition) <= (data.length()-pruefblocklaenge)) { //Prüfposition direkt hinter den Prüfblock setzen, vorher haben wir ja schon in vorherigen Durchläufen getestet. pruefposition = pruefblocklaenge + pruefblockposition; //Indikator, ob eine Übereinstimmung gefunden wurde bool hatWasGepasst = false; while (pruefposition+pruefblocklaenge <= data.length()) { //Prüfblock und Prüfposition gleich? if (data.compare(pruefblockposition, pruefblocklaenge, data, pruefposition, pruefblocklaenge) == 0) { //Ja, also Adresse merken matches.push(pruefposition); //Und den Indikator auf true setzen hatWasGepasst = true; //Jeztzt können wir den Rest der gefundenen Übereinstimmung überspringen, die wird ja später gelöscht. pruefposition+= pruefblocklaenge; } else { //Nein, also weiter bei der nächsten Position pruefposition++; } } //Gab es eine Übereinstimmung? if(hatWasGepasst) { //Berechnung, ob es eine Speicherersparnis gibt unsigned long length = pruefblocklaenge + sizeof(int)*(3 + matches.size()); unsigned long lengthbefore = (matches.size() + 1) * pruefblocklaenge; //Statusausgabe cout << "Compression matches: " << matches.size() << endl; cout << "Length before: " << lengthbefore << ", length after: " << length << endl; //Speicherersparnis? if(length < lengthbefore) { //Ja, also gefundene Blöcke aus den Daten entfernen (rückwärts) long pos; while (!matches.empty()) { //Nächsten Block holen pos = matches.top(); matches.pop(); //Entpackanweisung in Binärform in die Kommandodatei schreiben output.write((char *)&pos, sizeof(int)); //Datenblock löschen data.erase(pos, pruefblocklaenge); } //Anweisungen, welche Daten gepackt wurden in die Kommandodatei schreiben output.write((char *)&pruefblockposition, sizeof(int)); output.write((char *)&pruefblocklaenge, sizeof(int)); //Trennzeichen schreiben, um von nächsten Datenpaaren zu trennen int delim = -1; output.write((char *)&delim, sizeof(int)); } else { //Nein, also die gefundenen Datenpaare aus der Arbeitsliste entfernen while (!matches.empty()) { matches.pop(); } cout << "No value, I won't do it." << endl; } } hatWasGepasst = false; //Prüfblock verschieben pruefblockposition++; } //Weiter verschieben geht nicht, also machen wir den Prüfblock eins kleiner. pruefblocklaenge--; //Ist die Länge des Prüfblocks noch größer als ein Positionseintrag? if(pruefblocklaenge < sizeof(int)) { //Wenn nicht, wird die Komprimierte Datei geschrieben und das Programm beendet. //Trennzeichen schreiben, um vom Datenblock zu trennen int delim = -2; output.write((char *)&delim, sizeof(int)); output << data; //Jetzt noch die Ausgabedatei schließen, und das war's. Rücksprung! output.close(); return; } } } void decompress() { //Datei zum dekomprimieren öffnen cout << "Filename to decompress: "; string filename; cin >> filename; cin.ignore(); fstream compressfile; compressfile.open(filename.c_str(), ios::in); string data = ""; deque<int> matches; stack< deque<int> > fullmatches; //Kommandos lesen int c; while (compressfile.read((char *)&c, sizeof(int))) { if(c == -1) { //Trennzeichen zwischen Datenpaaren, also die Datenpaare kopieren... deque<int> tempmatches; while (!matches.empty()) { tempmatches.push_front(matches.back()); matches.pop_back(); } // ...und in die Datenpaarliste schieben fullmatches.push(tempmatches); } else if(c == -2) { //Jetzt kommen Daten, wir können aufhören mit Kommandolesen break; } else { //Kein Trennzeichen, also ist es ein Teil enes Datenpaares. Ab in die Liste damit! matches.push_front(c); } } //Bis hierhin waren es Kommandos. long offset = compressfile.tellg(); //Dateiende herausfinden compressfile.seekg(0, ios::end); long datalength = compressfile.tellg(); datalength++; //Dateilänge ist natürlich ohne die Kommandos zu betrachten, also wir die Kommandodatenlänge abgezogen... datalength -= offset; // ...und der Lesekopf auf das erste Datenbyte nach den Kommandos gesetzt. compressfile.seekg(offset); //Daten lesen und in den String schreiben char *tempdata = new char[datalength]; compressfile.read(tempdata, datalength); data.append(tempdata); //Die Datei brauchen wir jetzt nicht mehr. compressfile.close(); //Durch alle Datenpaare arbeiten while (!fullmatches.empty()) { //Ein Datenpaar aus dem Stapel holen matches = fullmatches.top(); fullmatches.pop(); //Blocklänge und Blockposition der vorhandenen Daten auslesen long blocklength = matches.front(); matches.pop_front(); long blockpos = matches.front(); matches.pop_front(); //Und jetzt für jede Kopieposition die passenden Daten schreiben while (!matches.empty()) { //Eine Position holen long postoinsert = matches.front(); matches.pop_front(); //Originaldaten auslesen string substring = data.substr(blockpos, blocklength); //Kopie schreiben data.insert(postoinsert, substring); } } //Ausgabedatei öffnen fstream output; output.open("decompressed.txt", ios::out); //Dekomprimierte Daten schreiben output << data; //Und die Datei wirder schließen output.close(); } int main (int argc, const char * argv[]) { bool cont = true; while (cont) { cout << "DXCompress\n\nMenu:\n(1) Compress\n(2) Decompress\n(0) Quit\n\nPlease choose an option: "; int choise; cin >> choise; cin.ignore(); if (choise == 0) { cont = false; } else if (choise == 1) {//Compress compress(); } else if (choise == 2) {//Decompress decompress(); } else { cont = false; } } return 0; }
// // main.cpp // DXCompress // // Created by Oliver Kahrmann on 08.05.11. // Copyright 2011 DHELIXSoft, Licensed under MIT: // // The MIT License (MIT) // // Copyright (c) 2015 Oliver Kahrmann // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include <iostream> #include <string> #include <fstream> #include <math.h> #include <deque> #include <stack> using namespace std; class area { long pos; long length; }; void compress() { cout << "Filename to compress: "; //Startvariablen string filename; fstream compressfile; long datalength; char *tempdata; fstream output; //Kompressorvariablen stack<long> matches; long pruefblocklaenge; long pruefposition; long pruefblockposition; string data; //Zu komprimierende Datei öffnen cin >> filename; compressfile.open(filename.c_str(), ios::in); //Daten in Speicher laden compressfile.seekg(0, ios::end); datalength = compressfile.tellg(); datalength++; compressfile.seekg(0, ios::beg); if(datalength < 10) { cout << "The file is shorter than 10 characters. There is no value for compression." << endl; return; } tempdata = new char[datalength]; compressfile.read(tempdata, datalength); data.append(tempdata); //Zu komprimierende Daten werden nicht mehr gebraucht, also schließen. compressfile.close(); //Ausgabedatei öffnen output.open("compressed.txt", ios::out); //Prüfblocklänge auf die Hälfte der Datei setzen pruefblocklaenge = floor(datalength/2); if(pruefblocklaenge > 100) { pruefblocklaenge = 100; } //cout << data; while (true) { //Prüfblock auf Start setzen pruefblockposition = 0; //Statusausgabe cout << "Datalength: " << data.length() << ", "; cout << "Checkblocklength: " << pruefblocklaenge << endl; while ((pruefblocklaenge+pruefblockposition) <= (data.length()-pruefblocklaenge)) { //Prüfposition direkt hinter den Prüfblock setzen, vorher haben wir ja schon in vorherigen Durchläufen getestet. pruefposition = pruefblocklaenge + pruefblockposition; //Indikator, ob eine Übereinstimmung gefunden wurde bool hatWasGepasst = false; while (pruefposition+pruefblocklaenge <= data.length()) { //Prüfblock und Prüfposition gleich? if (data.compare(pruefblockposition, pruefblocklaenge, data, pruefposition, pruefblocklaenge) == 0) { //Ja, also Adresse merken matches.push(pruefposition); //Und den Indikator auf true setzen hatWasGepasst = true; //Jeztzt können wir den Rest der gefundenen Übereinstimmung überspringen, die wird ja später gelöscht. pruefposition+= pruefblocklaenge; } else { //Nein, also weiter bei der nächsten Position pruefposition++; } } //Gab es eine Übereinstimmung? if(hatWasGepasst) { //Berechnung, ob es eine Speicherersparnis gibt unsigned long length = pruefblocklaenge + sizeof(int)*(3 + matches.size()); unsigned long lengthbefore = (matches.size() + 1) * pruefblocklaenge; //Statusausgabe cout << "Compression matches: " << matches.size() << endl; cout << "Length before: " << lengthbefore << ", length after: " << length << endl; //Speicherersparnis? if(length < lengthbefore) { //Ja, also gefundene Blöcke aus den Daten entfernen (rückwärts) long pos; while (!matches.empty()) { //Nächsten Block holen pos = matches.top(); matches.pop(); //Entpackanweisung in Binärform in die Kommandodatei schreiben output.write((char *)&pos, sizeof(int)); //Datenblock löschen data.erase(pos, pruefblocklaenge); } //Anweisungen, welche Daten gepackt wurden in die Kommandodatei schreiben output.write((char *)&pruefblockposition, sizeof(int)); output.write((char *)&pruefblocklaenge, sizeof(int)); //Trennzeichen schreiben, um von nächsten Datenpaaren zu trennen int delim = -1; output.write((char *)&delim, sizeof(int)); } else { //Nein, also die gefundenen Datenpaare aus der Arbeitsliste entfernen while (!matches.empty()) { matches.pop(); } cout << "No value, I won't do it." << endl; } } hatWasGepasst = false; //Prüfblock verschieben pruefblockposition++; } //Weiter verschieben geht nicht, also machen wir den Prüfblock eins kleiner. pruefblocklaenge--; //Ist die Länge des Prüfblocks noch größer als ein Positionseintrag? if(pruefblocklaenge < sizeof(int)) { //Wenn nicht, wird die Komprimierte Datei geschrieben und das Programm beendet. //Trennzeichen schreiben, um vom Datenblock zu trennen int delim = -2; output.write((char *)&delim, sizeof(int)); output << data; //Jetzt noch die Ausgabedatei schließen, und das war's. Rücksprung! output.close(); return; } } } void decompress() { //Datei zum dekomprimieren öffnen cout << "Filename to decompress: "; string filename; cin >> filename; cin.ignore(); fstream compressfile; compressfile.open(filename.c_str(), ios::in); string data = ""; deque<int> matches; stack< deque<int> > fullmatches; //Kommandos lesen int c; while (compressfile.read((char *)&c, sizeof(int))) { if(c == -1) { //Trennzeichen zwischen Datenpaaren, also die Datenpaare kopieren... deque<int> tempmatches; while (!matches.empty()) { tempmatches.push_front(matches.back()); matches.pop_back(); } // ...und in die Datenpaarliste schieben fullmatches.push(tempmatches); } else if(c == -2) { //Jetzt kommen Daten, wir können aufhören mit Kommandolesen break; } else { //Kein Trennzeichen, also ist es ein Teil enes Datenpaares. Ab in die Liste damit! matches.push_front(c); } } //Bis hierhin waren es Kommandos. long offset = compressfile.tellg(); //Dateiende herausfinden compressfile.seekg(0, ios::end); long datalength = compressfile.tellg(); datalength++; //Dateilänge ist natürlich ohne die Kommandos zu betrachten, also wir die Kommandodatenlänge abgezogen... datalength -= offset; // ...und der Lesekopf auf das erste Datenbyte nach den Kommandos gesetzt. compressfile.seekg(offset); //Daten lesen und in den String schreiben char *tempdata = new char[datalength]; compressfile.read(tempdata, datalength); data.append(tempdata); //Die Datei brauchen wir jetzt nicht mehr. compressfile.close(); //Durch alle Datenpaare arbeiten while (!fullmatches.empty()) { //Ein Datenpaar aus dem Stapel holen matches = fullmatches.top(); fullmatches.pop(); //Blocklänge und Blockposition der vorhandenen Daten auslesen long blocklength = matches.front(); matches.pop_front(); long blockpos = matches.front(); matches.pop_front(); //Und jetzt für jede Kopieposition die passenden Daten schreiben while (!matches.empty()) { //Eine Position holen long postoinsert = matches.front(); matches.pop_front(); //Originaldaten auslesen string substring = data.substr(blockpos, blocklength); //Kopie schreiben data.insert(postoinsert, substring); } } //Ausgabedatei öffnen fstream output; output.open("decompressed.txt", ios::out); //Dekomprimierte Daten schreiben output << data; //Und die Datei wirder schließen output.close(); } int main (int argc, const char * argv[]) { bool cont = true; while (cont) { cout << "DXCompress\n\nMenu:\n(1) Compress\n(2) Decompress\n(0) Quit\n\nPlease choose an option: "; int choise; cin >> choise; cin.ignore(); if (choise == 0) { cont = false; } else if (choise == 1) {//Compress compress(); } else if (choise == 2) {//Decompress decompress(); } else { cont = false; } } return 0; }
Apply license
Apply license
C++
mit
founderio/DXCompress
0a88a08670917331ce76c23123e150e649e7bee4
test/tcpcli.ut.cc
test/tcpcli.ut.cc
#include <handy/conn.h> #include <handy/logging.h> #include "test_harness.h" using namespace std; using namespace handy; TcpConnPtr connectto(EventBase* base, const char* host, short port) { TcpConnPtr con1 = TcpConn::createConnection(base, host, port); if (!con1) { return NULL; } con1->onState( [=](const TcpConnPtr con) { if (con->getState() == TcpConn::Connected) { con->send("GET / HTTP/1.1\r\n\r\n"); } else if (con->getState() == TcpConn::Closed) { info("connection to %s %d closed", host, port); } else if (con->getState() == TcpConn::Failed) { info("connect to %s %d failed", host, port); } } ); con1->onRead( [=](const TcpConnPtr con) { printf("%s %d response length is %lu bytes\n", host, port, con->getInput().size()); con->getInput().clear(); } ); return con1; } TEST(test::TestBase, tcpcli) { EventBase base; TcpConnPtr baidu = connectto(&base, "www.baidu.com", 80); TcpConnPtr c = connectto(&base, "www.baidu.com", 81); TcpConnPtr local = connectto(&base, "localhost", 10000); TcpConnPtr p = connectto(&base, "127...", 80); for (int i = 0; i < 5; i ++) { base.loop_once(50); } ASSERT_EQ(TcpConn::Connected, baidu->getState()); ASSERT_EQ(TcpConn::Handshaking, c->getState()); ASSERT_EQ(TcpConn::Failed, local->getState()); ASSERT_FALSE(p); }
#include <handy/conn.h> #include <handy/logging.h> #include "test_harness.h" using namespace std; using namespace handy; TcpConnPtr connectto(EventBase* base, const char* host, short port) { TcpConnPtr con1 = TcpConn::createConnection(base, host, port); if (!con1) { return NULL; } con1->onState( [=](const TcpConnPtr con) { if (con->getState() == TcpConn::Connected) { con->send("GET / HTTP/1.1\r\n\r\n"); } else if (con->getState() == TcpConn::Closed) { info("connection to %s %d closed", host, port); } else if (con->getState() == TcpConn::Failed) { info("connect to %s %d failed", host, port); } } ); con1->onRead( [=](const TcpConnPtr con) { printf("%s %d response length is %lu bytes\n", host, port, con->getInput().size()); con->getInput().clear(); } ); return con1; } TEST(test::TestBase, tcpcli) { EventBase base; TcpConnPtr baidu = connectto(&base, "www.baidu.com", 80); TcpConnPtr c = connectto(&base, "www.baidu.com", 81); TcpConnPtr local = connectto(&base, "localhost", 10000); TcpConnPtr p = connectto(&base, "127...", 80); for (int i = 0; i < 5; i ++) { base.loop_once(50); } //ASSERT_EQ(TcpConn::Connected, baidu->getState()); ASSERT_EQ(TcpConn::Handshaking, c->getState()); ASSERT_EQ(TcpConn::Failed, local->getState()); ASSERT_FALSE(p); }
test for travis update
test for travis update
C++
bsd-2-clause
tempbottle/handy,busyluo/handy,denis1008/handy,denis1008/handy,yedf/handy,yedf/handy,yedf/handy,busyluo/handy,tempbottle/handy,tempbottle/handy,busyluo/handy
5519bb024c188cc5445ffed11b8cc1538c562ada
test/testBone.cpp
test/testBone.cpp
#include "TestPrologue.h" #include <cal3d/bone.h> #include <cal3d/corebone.h> #include <cal3d/coreskeleton.h> #include <cal3d/mixer.h> #include <cal3d/skeleton.h> #include <cal3d/streamops.h> static cal3d::RotateTranslate makeTranslation(float x, float y, float z) { return cal3d::RotateTranslate(CalQuaternion(), CalVector(x, y, z)); } FIXTURE(BoneFixture) { SETUP(BoneFixture) : coreBone(testBone()) , bone(coreBone) {} static CalCoreBone testBone() { CalCoreBone cb("test"); // bind pose = 1.0f, 1.0f, 1.0f cb.relativeTransform = makeTranslation(1.0f, 1.0f, 1.0f); return cb; } CalCoreBone coreBone; CalBone bone; }; TEST_F(BoneFixture, bone_with_no_animation_returns_bind_position) { BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(1.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_zero_weight_is_replaced) { bone.blendPose(0.0f, makeTranslation(0, 0, 0), false, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(1.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_one_full_animation_returns_animation) { bone.blendPose(1.0f, makeTranslation(0, 0, 0), false, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(0.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_scaled_animation_returns_blend_of_bind_position_and_animation) { bone.blendPose(1.0f, makeTranslation(0, 0, 0), false, 0.5f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(0.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_two_replacements_uses_first_replacement) { bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 1.0f); bone.blendPose(1.0f, makeTranslation(0, 0, 0), true, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(2.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_two_replacements_uses_first_replacement_partially_scaled) { bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 0.8f); bone.blendPose(1.0f, makeTranslation(10, 10, 10), true, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(3.6f, bt.rowx.w); } //TEST_F(BoneFixture, can_ramp_in_at_zero) { // bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 0.0f); // BoneTransform bt = bone.calculateAbsolutePose(&bone, true); // CHECK_EQUAL(1.0f, bt.rowx.w); //} FIXTURE(MixerFixture) { static CalCoreSkeletonPtr fakeSkeleton() { CalCoreBonePtr coreRoot(new CalCoreBone("root")); coreRoot->relativeTransform.translation.x = 1; coreRoot->inverseBindPoseTransform.translation = CalVector(10, 10, 10); CalCoreBonePtr coreBone(new CalCoreBone("bone", 0)); coreBone->relativeTransform.translation.x = 2; coreBone->inverseBindPoseTransform.translation = CalVector(20, 20, 20); CalCoreSkeletonPtr cs(new CalCoreSkeleton); cs->addCoreBone(coreRoot); cs->addCoreBone(coreBone); return cs; } SETUP(MixerFixture) : skeleton(fakeSkeleton()) {} CalSkeleton skeleton; CalMixer mixer; }; TEST_F(MixerFixture, boneTransform_accumulates_transforms) { mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), std::vector<BoneScaleAdjustment>(), IncludeRootTransform); CHECK_EQUAL(11, skeleton.boneTransforms[0].rowx.w); CHECK_EQUAL(23, skeleton.boneTransforms[1].rowx.w); } inline CalVector transformPoint(const BoneTransform& bt, const CalVector& point) { return CalVector( bt.rowx.x * point.x + bt.rowx.y * point.y + bt.rowx.z * point.z + bt.rowx.w, bt.rowy.x * point.x + bt.rowy.y * point.y + bt.rowy.z * point.z + bt.rowy.w, bt.rowz.x * point.x + bt.rowz.y * point.y + bt.rowz.z * point.z + bt.rowz.w); } TEST_F(MixerFixture, boneTransform_accumulates_transforms_and_scales) { std::vector<BoneScaleAdjustment> boneScaleAdjustments; boneScaleAdjustments.push_back(BoneScaleAdjustment(0, CalVector(2, 2, 2))); boneScaleAdjustments.push_back(BoneScaleAdjustment(1, CalVector(0.5f, 0.5f, 0.5f))); mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), boneScaleAdjustments, IncludeRootTransform); CHECK_EQUAL(CalVector(25, 28, 36), transformPoint(skeleton.boneTransforms[0], CalVector(2, 4, 8))); CHECK_EQUAL(CalVector(27, 24, 28), transformPoint(skeleton.boneTransforms[1], CalVector(2, 4, 8))); } TEST(scale_is_in_bone_space) { CalQuaternion aboutZ; aboutZ.setAxisAngle(CalVector(0, 0, 1), 3.1415927410125732421875f / 2.0f); CHECK_EQUAL(CalVector(-4, 2, 8), aboutZ * CalVector(2, 4, 8)); CalCoreBonePtr root(new CalCoreBone("root")); root->inverseBindPoseTransform = cal3d::RotateTranslate(aboutZ, CalVector(2, 4, 8)); CalCoreSkeletonPtr coreSkeleton(new CalCoreSkeleton); coreSkeleton->addCoreBone(root); CalSkeleton skeleton(coreSkeleton); std::vector<BoneScaleAdjustment> boneScaleAdjustments; boneScaleAdjustments.push_back(BoneScaleAdjustment(0, CalVector(0.5f, 1, 2))); CalMixer mixer; mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), boneScaleAdjustments, IncludeRootTransform); CHECK_EQUAL(CalVector(-1, 6, 32), transformPoint(skeleton.boneTransforms[0], CalVector(2, 4, 8))); } TEST_F(MixerFixture, can_optionally_disregard_root_transform) { mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), std::vector<BoneScaleAdjustment>(), IgnoreRootTransform); CHECK_EQUAL(10, skeleton.boneTransforms[0].rowx.w); CHECK_EQUAL(22, skeleton.boneTransforms[1].rowx.w); }
#include "TestPrologue.h" #include <cal3d/bone.h> #include <cal3d/corebone.h> #include <cal3d/coreskeleton.h> #include <cal3d/mixer.h> #include <cal3d/skeleton.h> #include <cal3d/streamops.h> static cal3d::RotateTranslate makeTranslation(float x, float y, float z) { return cal3d::RotateTranslate(CalQuaternion(), CalVector(x, y, z)); } FIXTURE(BoneFixture) { SETUP(BoneFixture) : coreBone(testBone()) , bone(coreBone) {} static CalCoreBone testBone() { CalCoreBone cb("test"); // bind pose = 1.0f, 1.0f, 1.0f cb.relativeTransform = makeTranslation(1.0f, 1.0f, 1.0f); return cb; } CalCoreBone coreBone; CalBone bone; }; TEST_F(BoneFixture, bone_with_no_animation_returns_bind_position) { BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(1.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_zero_weight_is_replaced) { bone.blendPose(0.0f, makeTranslation(0, 0, 0), false, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(1.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_one_full_animation_returns_animation) { bone.blendPose(1.0f, makeTranslation(0, 0, 0), false, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(0.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_scaled_animation_returns_blend_of_bind_position_and_animation) { bone.blendPose(1.0f, makeTranslation(0, 0, 0), false, 0.5f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(0.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_two_replacements_uses_first_replacement) { bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 1.0f); bone.blendPose(1.0f, makeTranslation(0, 0, 0), true, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(2.0f, bt.rowx.w); } TEST_F(BoneFixture, bone_with_two_replacements_uses_first_replacement_partially_scaled) { bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 0.8f); bone.blendPose(1.0f, makeTranslation(10, 10, 10), true, 1.0f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(3.6f, bt.rowx.w); } inline float lerp(float a, float s, float t) { return a * t + (1.0f - a) * s; } TEST_F(BoneFixture, bone_with_two_replacements_and_one_nonreplacement_blends_more_to_the_first_replacement) { bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 0.5f); bone.blendPose(1.0f, makeTranslation(10, 10, 10), true, 0.5f); bone.blendPose(1.0f, makeTranslation(100, 100, 100), false, 0.5f); BoneTransform bt = bone.calculateAbsolutePose(&bone, true); CHECK_EQUAL(lerp(1.0f / 7.0f, lerp(1.0f / 3.0f, 2, 10), 100), bt.rowx.w); } //TEST_F(BoneFixture, can_ramp_in_at_zero) { // bone.blendPose(1.0f, makeTranslation(2, 2, 2), true, 0.0f); // BoneTransform bt = bone.calculateAbsolutePose(&bone, true); // CHECK_EQUAL(1.0f, bt.rowx.w); //} FIXTURE(MixerFixture) { static CalCoreSkeletonPtr fakeSkeleton() { CalCoreBonePtr coreRoot(new CalCoreBone("root")); coreRoot->relativeTransform.translation.x = 1; coreRoot->inverseBindPoseTransform.translation = CalVector(10, 10, 10); CalCoreBonePtr coreBone(new CalCoreBone("bone", 0)); coreBone->relativeTransform.translation.x = 2; coreBone->inverseBindPoseTransform.translation = CalVector(20, 20, 20); CalCoreSkeletonPtr cs(new CalCoreSkeleton); cs->addCoreBone(coreRoot); cs->addCoreBone(coreBone); return cs; } SETUP(MixerFixture) : skeleton(fakeSkeleton()) {} CalSkeleton skeleton; CalMixer mixer; }; TEST_F(MixerFixture, boneTransform_accumulates_transforms) { mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), std::vector<BoneScaleAdjustment>(), IncludeRootTransform); CHECK_EQUAL(11, skeleton.boneTransforms[0].rowx.w); CHECK_EQUAL(23, skeleton.boneTransforms[1].rowx.w); } inline CalVector transformPoint(const BoneTransform& bt, const CalVector& point) { return CalVector( bt.rowx.x * point.x + bt.rowx.y * point.y + bt.rowx.z * point.z + bt.rowx.w, bt.rowy.x * point.x + bt.rowy.y * point.y + bt.rowy.z * point.z + bt.rowy.w, bt.rowz.x * point.x + bt.rowz.y * point.y + bt.rowz.z * point.z + bt.rowz.w); } TEST_F(MixerFixture, boneTransform_accumulates_transforms_and_scales) { std::vector<BoneScaleAdjustment> boneScaleAdjustments; boneScaleAdjustments.push_back(BoneScaleAdjustment(0, CalVector(2, 2, 2))); boneScaleAdjustments.push_back(BoneScaleAdjustment(1, CalVector(0.5f, 0.5f, 0.5f))); mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), boneScaleAdjustments, IncludeRootTransform); CHECK_EQUAL(CalVector(25, 28, 36), transformPoint(skeleton.boneTransforms[0], CalVector(2, 4, 8))); CHECK_EQUAL(CalVector(27, 24, 28), transformPoint(skeleton.boneTransforms[1], CalVector(2, 4, 8))); } TEST(scale_is_in_bone_space) { CalQuaternion aboutZ; aboutZ.setAxisAngle(CalVector(0, 0, 1), 3.1415927410125732421875f / 2.0f); CHECK_EQUAL(CalVector(-4, 2, 8), aboutZ * CalVector(2, 4, 8)); CalCoreBonePtr root(new CalCoreBone("root")); root->inverseBindPoseTransform = cal3d::RotateTranslate(aboutZ, CalVector(2, 4, 8)); CalCoreSkeletonPtr coreSkeleton(new CalCoreSkeleton); coreSkeleton->addCoreBone(root); CalSkeleton skeleton(coreSkeleton); std::vector<BoneScaleAdjustment> boneScaleAdjustments; boneScaleAdjustments.push_back(BoneScaleAdjustment(0, CalVector(0.5f, 1, 2))); CalMixer mixer; mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), boneScaleAdjustments, IncludeRootTransform); CHECK_EQUAL(CalVector(-1, 6, 32), transformPoint(skeleton.boneTransforms[0], CalVector(2, 4, 8))); } TEST_F(MixerFixture, can_optionally_disregard_root_transform) { mixer.updateSkeleton(&skeleton, std::vector<BoneTransformAdjustment>(), std::vector<BoneScaleAdjustment>(), IgnoreRootTransform); CHECK_EQUAL(10, skeleton.boneTransforms[0].rowx.w); CHECK_EQUAL(22, skeleton.boneTransforms[1].rowx.w); }
Test coverage for multiple replace animations followed by a non-replace animation
Test coverage for multiple replace animations followed by a non-replace animation git-svn-id: febc42a3fd39fb08e5ae2b2182bc5ab0a583559c@121511 07c76cb3-cb09-0410-85de-c24d39f1912e
C++
lgpl-2.1
imvu/cal3d,imvu/cal3d,imvu/cal3d,imvu/cal3d
8479a2f914eb0a2f47c3b26a78fe908af91c699c
include/cybozu/random_generator.hpp
include/cybozu/random_generator.hpp
#pragma once /** @file @brief pseudrandom generator @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <cybozu/exception.hpp> #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <wincrypt.h> #pragma comment (lib, "advapi32.lib") #else #include <sys/types.h> #include <fcntl.h> #endif namespace cybozu { class RandomGenerator { RandomGenerator(const RandomGenerator&); void operator=(const RandomGenerator&); public: uint32_t operator()() { return get32(); } uint32_t get32() { uint32_t ret; read(&ret, 1); return ret; } uint64_t get64() { uint64_t ret; read(&ret, 1); return ret; } #ifdef _WIN32 RandomGenerator() : prov_(0) , pos_(bufSize) { DWORD flagTbl[] = { 0, CRYPT_NEWKEYSET }; for (int i = 0; i < 2; i++) { if (CryptAcquireContext(&prov_, NULL, NULL, PROV_RSA_FULL, flagTbl[i]) != 0) return; } throw cybozu::Exception("randomgenerator"); } void read_inner(void *buf, size_t byteSize) { if (CryptGenRandom(prov_, static_cast<DWORD>(byteSize), static_cast<BYTE*>(buf)) == 0) { throw cybozu::Exception("randomgenerator:read") << byteSize; } } ~RandomGenerator() { if (prov_) { CryptReleaseContext(prov_, 0); } } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(T *buf, size_t bufNum) { const size_t byteSize = sizeof(T) * bufNum; if (byteSize > bufSize) { read_inner(buf, byteSize); } else { if (pos_ + byteSize > bufSize) { read_inner(buf_, bufSize); pos_ = 0; } memcpy(buf, buf_ + pos_, byteSize); pos_ += byteSize; } } private: HCRYPTPROV prov_; static const size_t bufSize = 1024; char buf_[bufSize]; size_t pos_; #else RandomGenerator() : fp_(::fopen("/dev/urandom", "rb")) { if (!fp_) throw cybozu::Exception("randomgenerator"); } ~RandomGenerator() { if (fp_) ::fclose(fp_); } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(T *buf, size_t bufNum) { const size_t byteSize = sizeof(T) * bufNum; if (::fread(buf, 1, (int)byteSize, fp_) != byteSize) { throw cybozu::Exception("randomgenerator:read") << byteSize; } } #endif private: FILE *fp_; }; } // cybozu
#pragma once /** @file @brief pseudrandom generator @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <cybozu/exception.hpp> #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <wincrypt.h> #pragma comment (lib, "advapi32.lib") #else #include <sys/types.h> #include <fcntl.h> #endif namespace cybozu { class RandomGenerator { RandomGenerator(const RandomGenerator&); void operator=(const RandomGenerator&); public: uint32_t operator()() { return get32(); } uint32_t get32() { uint32_t ret; read(&ret, 1); return ret; } uint64_t get64() { uint64_t ret; read(&ret, 1); return ret; } #ifdef _WIN32 RandomGenerator() : prov_(0) , pos_(bufSize) { DWORD flagTbl[] = { 0, CRYPT_NEWKEYSET }; for (int i = 0; i < 2; i++) { if (CryptAcquireContext(&prov_, NULL, NULL, PROV_RSA_FULL, flagTbl[i]) != 0) return; } throw cybozu::Exception("randomgenerator"); } void read_inner(void *buf, size_t byteSize) { if (CryptGenRandom(prov_, static_cast<DWORD>(byteSize), static_cast<BYTE*>(buf)) == 0) { throw cybozu::Exception("randomgenerator:read") << byteSize; } } ~RandomGenerator() { if (prov_) { CryptReleaseContext(prov_, 0); } } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(T *buf, size_t bufNum) { const size_t byteSize = sizeof(T) * bufNum; if (byteSize > bufSize) { read_inner(buf, byteSize); } else { if (pos_ + byteSize > bufSize) { read_inner(buf_, bufSize); pos_ = 0; } memcpy(buf, buf_ + pos_, byteSize); pos_ += byteSize; } } private: HCRYPTPROV prov_; static const size_t bufSize = 1024; char buf_[bufSize]; size_t pos_; #else RandomGenerator() : fp_(::fopen("/dev/urandom", "rb")) { if (!fp_) throw cybozu::Exception("randomgenerator"); } ~RandomGenerator() { if (fp_) ::fclose(fp_); } /* fill buf[0..bufNum-1] with random data @note bufNum is not byte size */ template<class T> void read(T *buf, size_t bufNum) { const size_t byteSize = sizeof(T) * bufNum; if (::fread(buf, 1, (int)byteSize, fp_) != byteSize) { throw cybozu::Exception("randomgenerator:read") << byteSize; } } #endif private: FILE *fp_; }; template<class T, class RG> void shuffle(T* v, size_t n, RG& rg) { if (n <= 1) return; for (size_t i = 0; i < n - 1; i++) { size_t r = i + size_t(rg.get64() % (n - i)); using namespace std; swap(v[i], v[r]); } } template<class V, class RG> void shuffle(V& v, RG& rg) { shuffle(v.data(), v.size(), rg); } } // cybozu
add shuffle
add shuffle
C++
bsd-3-clause
herumi/cybozulib,herumi/cybozulib
ad913b93634335f653b285c07e13df3a1e23bf64
include/libtorrent/torrent_info.hpp
include/libtorrent/torrent_info.hpp
/* Copyright (c) 2003-2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_TORRENT_INFO_HPP_INCLUDED #define TORRENT_TORRENT_INFO_HPP_INCLUDED #include <string> #include <vector> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #include <boost/filesystem/path.hpp> #include <boost/shared_array.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/entry.hpp" #include "libtorrent/lazy_entry.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/file_storage.hpp" namespace libtorrent { namespace pt = boost::posix_time; namespace gr = boost::gregorian; namespace fs = boost::filesystem; enum { // wait 60 seconds before retrying a failed tracker tracker_retry_delay_min = 10 // when tracker_failed_max trackers // has failed, wait 60 minutes instead , tracker_retry_delay_max = 60 * 60 }; struct TORRENT_EXPORT announce_entry { announce_entry(std::string const& u) : url(u) , tier(0) , fail_limit(3) , fails(0) , source(0) , verified(false) , updating(false) , start_sent(false) , complete_sent(false) {} std::string url; // the time of next tracker announce ptime next_announce; boost::uint8_t tier; // the number of times this tracker can fail // in a row before it's removed. 0 means unlimited boost::uint8_t fail_limit; // the number of times in a row this tracker has failed boost::uint8_t fails; enum tracker_source { source_torrent = 1, source_client = 2, source_magnet_link = 4, source_tex = 8 }; // where did we get this tracker from boost::uint8_t source; // is set to true if we have ever received a response from // this tracker bool verified:1; // true if we're currently trying to announce with // this tracker bool updating:1; // this is true if event start has been sent to the tracker bool start_sent:1; // this is true if event completed has been sent to the tracker bool complete_sent:1; void reset() { start_sent = false; next_announce = min_time(); } void failed() { ++fails; int delay = (std::min)(tracker_retry_delay_min + int(fails) * int(fails) * tracker_retry_delay_min , int(tracker_retry_delay_max)); next_announce = time_now() + seconds(delay); updating = false; } bool can_announce(ptime now) const { return now >= next_announce && (fails < fail_limit || fail_limit == 0) && !updating; } bool is_working() const { return fails == 0; } }; #ifndef BOOST_NO_EXCEPTIONS struct TORRENT_EXPORT invalid_torrent_file: std::exception { virtual const char* what() const throw() { return "invalid torrent file"; } }; #endif int TORRENT_EXPORT load_file(fs::path const& filename, std::vector<char>& v); class TORRENT_EXPORT torrent_info : public intrusive_ptr_base<torrent_info> { public: torrent_info(sha1_hash const& info_hash); torrent_info(lazy_entry const& torrent_file); torrent_info(char const* buffer, int size); torrent_info(fs::path const& filename); torrent_info(fs::wpath const& filename); ~torrent_info(); file_storage const& files() const { return m_files; } file_storage const& orig_files() const { return m_orig_files ? *m_orig_files : m_files; } void rename_file(int index, std::string const& new_filename) { copy_on_write(); m_files.rename_file(index, new_filename); } void rename_file(int index, std::wstring const& new_filename) { copy_on_write(); m_files.rename_file(index, new_filename); } void add_tracker(std::string const& url, int tier = 0); std::vector<announce_entry> const& trackers() const { return m_urls; } std::vector<std::string> const& url_seeds() const { return m_url_seeds; } void add_url_seed(std::string const& url) { m_url_seeds.push_back(url); } std::vector<std::string> const& http_seeds() const { return m_http_seeds; } void add_http_seed(std::string const& url) { m_http_seeds.push_back(url); } size_type total_size() const { return m_files.total_size(); } int piece_length() const { return m_files.piece_length(); } int num_pieces() const { return m_files.num_pieces(); } const sha1_hash& info_hash() const { return m_info_hash; } const std::string& name() const { return m_files.name(); } typedef file_storage::iterator file_iterator; typedef file_storage::reverse_iterator reverse_file_iterator; file_iterator begin_files() const { return m_files.begin(); } file_iterator end_files() const { return m_files.end(); } reverse_file_iterator rbegin_files() const { return m_files.rbegin(); } reverse_file_iterator rend_files() const { return m_files.rend(); } int num_files() const { return m_files.num_files(); } file_entry const& file_at(int index) const { return m_files.at(index); } file_iterator file_at_offset(size_type offset) const { return m_files.file_at_offset(offset); } std::vector<file_slice> map_block(int piece, size_type offset, int size) const { return m_files.map_block(piece, offset, size); } peer_request map_file(int file, size_type offset, int size) const { return m_files.map_file(file, offset, size); } #ifndef TORRENT_NO_DEPRECATE // ------- start deprecation ------- // these functions will be removed in a future version torrent_info(entry const& torrent_file) TORRENT_DEPRECATED; void print(std::ostream& os) const TORRENT_DEPRECATED; file_storage& files() TORRENT_DEPRECATED { return m_files; } // ------- end deprecation ------- #endif bool is_valid() const { return m_files.is_valid(); } bool priv() const { return m_private; } int piece_size(int index) const { return m_files.piece_size(index); } sha1_hash hash_for_piece(int index) const { return sha1_hash(hash_for_piece_ptr(index)); } char const* hash_for_piece_ptr(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_files.num_pieces()); TORRENT_ASSERT(m_piece_hashes); TORRENT_ASSERT(m_piece_hashes >= m_info_section.get()); TORRENT_ASSERT(m_piece_hashes < m_info_section.get() + m_info_section_size); return &m_piece_hashes[index*20]; } boost::optional<pt::ptime> creation_date() const; const std::string& creator() const { return m_created_by; } const std::string& comment() const { return m_comment; } // dht nodes to add to the routing table/bootstrap from typedef std::vector<std::pair<std::string, int> > nodes_t; nodes_t const& nodes() const { return m_nodes; } void add_node(std::pair<std::string, int> const& node) { m_nodes.push_back(node); } bool parse_info_section(lazy_entry const& e, std::string& error); lazy_entry const* info(char const* key) const { if (m_info_dict.type() == lazy_entry::none_t) lazy_bdecode(m_info_section.get(), m_info_section.get() + m_info_section_size, m_info_dict); return m_info_dict.dict_find(key); } void swap(torrent_info& ti); boost::shared_array<char> metadata() const { return m_info_section; } int metadata_size() const { return m_info_section_size; } private: void copy_on_write(); bool parse_torrent_file(lazy_entry const& libtorrent, std::string& error); file_storage m_files; // if m_files is modified, it is first copied into // m_orig_files so that the original name and // filenames are preserved. boost::shared_ptr<const file_storage> m_orig_files; // the urls to the trackers std::vector<announce_entry> m_urls; std::vector<std::string> m_url_seeds; std::vector<std::string> m_http_seeds; nodes_t m_nodes; // the hash that identifies this torrent sha1_hash m_info_hash; // if a creation date is found in the torrent file // this will be set to that, otherwise it'll be // 1970, Jan 1 pt::ptime m_creation_date; // if a comment is found in the torrent file // this will be set to that comment std::string m_comment; // an optional string naming the software used // to create the torrent file std::string m_created_by; // this is used when creating a torrent. If there's // only one file there are cases where it's impossible // to know if it should be written as a multifile torrent // or not. e.g. test/test there's one file and one directory // and they have the same name. bool m_multifile; // this is true if the torrent is private. i.e., is should not // be announced on the dht bool m_private; // this is a copy of the info section from the torrent. // it use maintained in this flat format in order to // make it available through the metadata extension boost::shared_array<char> m_info_section; int m_info_section_size; // this is a pointer into the m_info_section buffer // pointing to the first byte of the first sha-1 hash char const* m_piece_hashes; // the info section parsed. points into m_info_section // parsed lazily mutable lazy_entry m_info_dict; }; } #endif // TORRENT_TORRENT_INFO_HPP_INCLUDED
/* Copyright (c) 2003-2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_TORRENT_INFO_HPP_INCLUDED #define TORRENT_TORRENT_INFO_HPP_INCLUDED #include <string> #include <vector> #include <iosfwd> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #include <boost/filesystem/path.hpp> #include <boost/shared_array.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/entry.hpp" #include "libtorrent/lazy_entry.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/time.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/file_storage.hpp" namespace libtorrent { namespace pt = boost::posix_time; namespace gr = boost::gregorian; namespace fs = boost::filesystem; enum { // wait 60 seconds before retrying a failed tracker tracker_retry_delay_min = 10 // when tracker_failed_max trackers // has failed, wait 60 minutes instead , tracker_retry_delay_max = 60 * 60 }; struct TORRENT_EXPORT announce_entry { announce_entry(std::string const& u) : url(u) , tier(0) , fail_limit(3) , fails(0) , source(0) , verified(false) , updating(false) , start_sent(false) , complete_sent(false) {} std::string url; // the time of next tracker announce ptime next_announce; boost::uint8_t tier; // the number of times this tracker can fail // in a row before it's removed. 0 means unlimited boost::uint8_t fail_limit; // the number of times in a row this tracker has failed boost::uint8_t fails; enum tracker_source { source_torrent = 1, source_client = 2, source_magnet_link = 4, source_tex = 8 }; // where did we get this tracker from boost::uint8_t source; // is set to true if we have ever received a response from // this tracker bool verified:1; // true if we're currently trying to announce with // this tracker bool updating:1; // this is true if event start has been sent to the tracker bool start_sent:1; // this is true if event completed has been sent to the tracker bool complete_sent:1; void reset() { start_sent = false; next_announce = min_time(); } void failed() { ++fails; int delay = (std::min)(tracker_retry_delay_min + int(fails) * int(fails) * tracker_retry_delay_min , int(tracker_retry_delay_max)); next_announce = time_now() + seconds(delay); updating = false; } bool can_announce(ptime now) const { return now >= next_announce && (fails < fail_limit || fail_limit == 0) && !updating; } bool is_working() const { return fails == 0; } }; #ifndef BOOST_NO_EXCEPTIONS struct TORRENT_EXPORT invalid_torrent_file: std::exception { virtual const char* what() const throw() { return "invalid torrent file"; } }; #endif int TORRENT_EXPORT load_file(fs::path const& filename, std::vector<char>& v); class TORRENT_EXPORT torrent_info : public intrusive_ptr_base<torrent_info> { public: torrent_info(sha1_hash const& info_hash); torrent_info(lazy_entry const& torrent_file); torrent_info(char const* buffer, int size); torrent_info(fs::path const& filename); torrent_info(fs::wpath const& filename); ~torrent_info(); file_storage const& files() const { return m_files; } file_storage const& orig_files() const { return m_orig_files ? *m_orig_files : m_files; } void rename_file(int index, std::string const& new_filename) { copy_on_write(); m_files.rename_file(index, new_filename); } void rename_file(int index, std::wstring const& new_filename) { copy_on_write(); m_files.rename_file(index, new_filename); } void add_tracker(std::string const& url, int tier = 0); std::vector<announce_entry> const& trackers() const { return m_urls; } std::vector<std::string> const& url_seeds() const { return m_url_seeds; } void add_url_seed(std::string const& url) { m_url_seeds.push_back(url); } std::vector<std::string> const& http_seeds() const { return m_http_seeds; } void add_http_seed(std::string const& url) { m_http_seeds.push_back(url); } size_type total_size() const { return m_files.total_size(); } int piece_length() const { return m_files.piece_length(); } int num_pieces() const { return m_files.num_pieces(); } const sha1_hash& info_hash() const { return m_info_hash; } const std::string& name() const { return m_files.name(); } typedef file_storage::iterator file_iterator; typedef file_storage::reverse_iterator reverse_file_iterator; file_iterator begin_files() const { return m_files.begin(); } file_iterator end_files() const { return m_files.end(); } reverse_file_iterator rbegin_files() const { return m_files.rbegin(); } reverse_file_iterator rend_files() const { return m_files.rend(); } int num_files() const { return m_files.num_files(); } file_entry const& file_at(int index) const { return m_files.at(index); } file_iterator file_at_offset(size_type offset) const { return m_files.file_at_offset(offset); } std::vector<file_slice> map_block(int piece, size_type offset, int size) const { return m_files.map_block(piece, offset, size); } peer_request map_file(int file, size_type offset, int size) const { return m_files.map_file(file, offset, size); } #ifndef TORRENT_NO_DEPRECATE // ------- start deprecation ------- // these functions will be removed in a future version torrent_info(entry const& torrent_file) TORRENT_DEPRECATED; void print(std::ostream& os) const TORRENT_DEPRECATED; // ------- end deprecation ------- #endif bool is_valid() const { return m_files.is_valid(); } bool priv() const { return m_private; } int piece_size(int index) const { return m_files.piece_size(index); } sha1_hash hash_for_piece(int index) const { return sha1_hash(hash_for_piece_ptr(index)); } char const* hash_for_piece_ptr(int index) const { TORRENT_ASSERT(index >= 0); TORRENT_ASSERT(index < m_files.num_pieces()); TORRENT_ASSERT(m_piece_hashes); TORRENT_ASSERT(m_piece_hashes >= m_info_section.get()); TORRENT_ASSERT(m_piece_hashes < m_info_section.get() + m_info_section_size); return &m_piece_hashes[index*20]; } boost::optional<pt::ptime> creation_date() const; const std::string& creator() const { return m_created_by; } const std::string& comment() const { return m_comment; } // dht nodes to add to the routing table/bootstrap from typedef std::vector<std::pair<std::string, int> > nodes_t; nodes_t const& nodes() const { return m_nodes; } void add_node(std::pair<std::string, int> const& node) { m_nodes.push_back(node); } bool parse_info_section(lazy_entry const& e, std::string& error); lazy_entry const* info(char const* key) const { if (m_info_dict.type() == lazy_entry::none_t) lazy_bdecode(m_info_section.get(), m_info_section.get() + m_info_section_size, m_info_dict); return m_info_dict.dict_find(key); } void swap(torrent_info& ti); boost::shared_array<char> metadata() const { return m_info_section; } int metadata_size() const { return m_info_section_size; } private: void copy_on_write(); bool parse_torrent_file(lazy_entry const& libtorrent, std::string& error); file_storage m_files; // if m_files is modified, it is first copied into // m_orig_files so that the original name and // filenames are preserved. boost::shared_ptr<const file_storage> m_orig_files; // the urls to the trackers std::vector<announce_entry> m_urls; std::vector<std::string> m_url_seeds; std::vector<std::string> m_http_seeds; nodes_t m_nodes; // the hash that identifies this torrent sha1_hash m_info_hash; // if a creation date is found in the torrent file // this will be set to that, otherwise it'll be // 1970, Jan 1 pt::ptime m_creation_date; // if a comment is found in the torrent file // this will be set to that comment std::string m_comment; // an optional string naming the software used // to create the torrent file std::string m_created_by; // this is used when creating a torrent. If there's // only one file there are cases where it's impossible // to know if it should be written as a multifile torrent // or not. e.g. test/test there's one file and one directory // and they have the same name. bool m_multifile; // this is true if the torrent is private. i.e., is should not // be announced on the dht bool m_private; // this is a copy of the info section from the torrent. // it use maintained in this flat format in order to // make it available through the metadata extension boost::shared_array<char> m_info_section; int m_info_section_size; // this is a pointer into the m_info_section buffer // pointing to the first byte of the first sha-1 hash char const* m_piece_hashes; // the info section parsed. points into m_info_section // parsed lazily mutable lazy_entry m_info_dict; }; } #endif // TORRENT_TORRENT_INFO_HPP_INCLUDED
remove (deprecated) non-const files() from torrent_info since it opens a loop-hole to modifying the filenames without preserving the original ones
remove (deprecated) non-const files() from torrent_info since it opens a loop-hole to modifying the filenames without preserving the original ones git-svn-id: c39a6fcb73c71bf990fd9353909696546eb40440@3113 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,mirror/libtorrent,mirror/libtorrent,mirror/libtorrent,mirror/libtorrent,john-peterson/libtorrent-old,john-peterson/libtorrent-old,mirror/libtorrent,mirror/libtorrent,john-peterson/libtorrent-old
fef75d556fa1242118e9daba4181bb9eba3bac91
test/optimisationAlgorithm/trajectoryBasedAlgorithm/testHillClimbing.cpp
test/optimisationAlgorithm/trajectoryBasedAlgorithm/testHillClimbing.cpp
// Catch #include <catch.hpp> // C++ Standard Library #include <memory> #include <iostream> // Armadillo #include <armadillo> // HOP #include <hop> class TestHillClimbing : public hop::HillClimbing { public: TestHillClimbing( const std::shared_ptr<hop::OptimisationProblem> optimisationProblem) : HillClimbing(optimisationProblem), velocityIndex_(0){ velocities_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testVel.mat"); } arma::Col<double> getVelocity() { return velocities_.col(velocityIndex_++); } protected: unsigned int velocityIndex_; arma::mat velocities_; }; class TestHillClimbingProblem : public hop::OptimisationProblem { public: TestHillClimbingProblem( const unsigned int numberOfDimensions) : OptimisationProblem(numberOfDimensions), objectiveValueIndex_(0) { objectiveValues_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testObj.mat"); } arma::Mat<double> getParameterHistory() const noexcept { return parameterHistory_; } protected: unsigned int objectiveValueIndex_; arma::Col<double> objectiveValues_; int n; arma::Mat<double> parameterHistory_; double getObjectiveValueImplementation( const arma::Col<double>& parameter) const override { //parameterHistory_.insert_cols(n, parameter); return objectiveValues_.at(objectiveValueIndex_); } std::string to_string() const noexcept { return "HillClimbing"; } }; TEST_CASE("Hill climbing", "") { std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(4)); TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setInitialParameter(arma::zeros<arma::Col<double>>(testHillClimbingProblem->getNumberOfDimensions())); testHillClimbing.setMaximalNumberOfIterations(4); testHillClimbing.optimise(); arma::Mat<double> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); actualParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat"); arma::Mat<double> expectedParameterHistory; expectedParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat"); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.col(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } }
// Catch #include <catch.hpp> // C++ Standard Library #include <memory> #include <iostream> // Armadillo #include <armadillo> // HOP #include <hop> class TestHillClimbing : public hop::HillClimbing { public: TestHillClimbing( const std::shared_ptr<hop::OptimisationProblem> optimisationProblem) : HillClimbing(optimisationProblem), velocityIndex_(0){ velocities_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testVel.mat"); } arma::Col<double> getVelocity() { return velocities_.col(velocityIndex_++); } protected: unsigned int velocityIndex_; arma::mat velocities_; }; class TestHillClimbingProblem : public hop::OptimisationProblem { public: TestHillClimbingProblem( const unsigned int numberOfDimensions) : OptimisationProblem(numberOfDimensions), objectiveValueIndex_(0) { objectiveValues_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testObj.mat"); } std::vector<arma::Col<double>> getParameterHistory() const noexcept { return parameterHistory_; } protected: unsigned int objectiveValueIndex_; arma::Col<double> objectiveValues_; static std::vector<arma::Col<double>> parameterHistory_; double getObjectiveValueImplementation( const arma::Col<double>& parameter) const override { parameterHistory_.push_back(parameter); return objectiveValues_.at(objectiveValueIndex_); } std::string to_string() const noexcept { return "TestHillClimbing"; } }; decltype(TestHillClimbingProblem::parameterHistory_) TestHillClimbingProblem::parameterHistory_; TEST_CASE("Hill climbing", "") { std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(4)); TestHillClimbing testHillClimbing(testHillClimbingProblem); testHillClimbing.setInitialParameter(arma::zeros<arma::Col<double>>(testHillClimbingProblem->getNumberOfDimensions())); testHillClimbing.setMaximalNumberOfIterations(4); testHillClimbing.optimise(); std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory(); arma::Mat<double> expectedParameterHistory; expectedParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat"); for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) { arma::Col<double> expectedParameter = expectedParameterHistory.col(n); arma::Col<double> actualParameter = actualParameterHistory.at(n); for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) { CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k))); } } }
Use std::vector<arma::Col<double>> for dynamic amounts of Columns
devel: Use std::vector<arma::Col<double>> for dynamic amounts of Columns
C++
mit
SebastianNiemann/Mantella,SebastianNiemann/Mantella,Mantella/Mantella,Mantella/Mantella,Mantella/Mantella,SebastianNiemann/Mantella
2c8733588d9195ae348f5238533481fd88c54de9
Modules/ImageStatistics/Testing/mitkImageStatisticsContainerTest.cpp
Modules/ImageStatistics/Testing/mitkImageStatisticsContainerTest.cpp
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" //MITK includes #include "mitkArbitraryTimeGeometry.h" #include "mitkImageStatisticsContainerNodeHelper.h" #include "mitkImageStatisticsContainerManager.h" #include "mitkImageStatisticsContainer.h" class mitkImageStatisticsContainerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkImageStatisticsContainerTestSuite); MITK_TEST(StatisticNamesIO); MITK_TEST(InvalidKey); MITK_TEST(TimeSteps); MITK_TEST(PrintSelf); MITK_TEST(InternalClone); MITK_TEST(StatisticNames); MITK_TEST(OverwriteStatistic); MITK_TEST(Reset); CPPUNIT_TEST_SUITE_END(); private: mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer; mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer2; mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer3; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject2; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject3; mitk::ArbitraryTimeGeometry::Pointer m_TimeGeometry; mitk::Geometry3D::Pointer m_Geometry1; mitk::Geometry3D::Pointer m_Geometry2; mitk::Geometry3D::Pointer m_Geometry3; mitk::Geometry3D::Pointer m_Geometry3_5; mitk::Geometry3D::Pointer m_Geometry4; mitk::Geometry3D::Pointer m_Geometry5; mitk::TimePointType m_Geometry1MinTP; mitk::TimePointType m_Geometry2MinTP; mitk::TimePointType m_Geometry3MinTP; mitk::TimePointType m_Geometry3_5MinTP; mitk::TimePointType m_Geometry4MinTP; mitk::TimePointType m_Geometry5MinTP; mitk::TimePointType m_Geometry1MaxTP; mitk::TimePointType m_Geometry2MaxTP; mitk::TimePointType m_Geometry3MaxTP; mitk::TimePointType m_Geometry3_5MaxTP; mitk::TimePointType m_Geometry4MaxTP; mitk::TimePointType m_Geometry5MaxTP; std::vector<std::string> estimatedDefaultStatisticNames { "Mean", "Median", "StandardDeviation", "RMS", "Max", "MaxPosition", "Min", "MinPosition", "#Voxel", "Volume [mm^3]", "Skewness", "Kurtosis", "Uniformity", "Entropy", "MPP", "UPP" }; public: void setUp() override { m_StatisticsContainer = mitk::ImageStatisticsContainer::New(); m_StatisticsContainer2 = mitk::ImageStatisticsContainer::New(); m_StatisticsContainer3 = mitk::ImageStatisticsContainer::New(); m_Geometry1 = mitk::Geometry3D::New(); m_Geometry2 = mitk::Geometry3D::New(); m_Geometry3 = mitk::Geometry3D::New(); m_Geometry3_5 = mitk::Geometry3D::New(); m_Geometry4 = mitk::Geometry3D::New(); m_Geometry5 = mitk::Geometry3D::New(); m_Geometry1MinTP = 1; m_Geometry2MinTP = 2; m_Geometry3MinTP = 3; m_Geometry3_5MinTP = 3.5; m_Geometry4MinTP = 4; m_Geometry5MinTP = 5; m_Geometry1MaxTP = 1.9; m_Geometry2MaxTP = 2.9; m_Geometry3MaxTP = 3.9; m_Geometry3_5MaxTP = 3.9; m_Geometry4MaxTP = 4.9; m_Geometry5MaxTP = 5.9; m_TimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_TimeGeometry->ClearAllGeometries(); m_TimeGeometry->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MinTP, m_Geometry4MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry5, m_Geometry5MinTP, m_Geometry5MaxTP); } void tearDown() override { m_StatisticsContainer->Reset(); m_StatisticsContainer2->Reset(); m_StatisticsContainer3->Reset(); m_StatisticsObject.Reset(); m_StatisticsObject2.Reset(); m_StatisticsObject3.Reset(); m_TimeGeometry->ClearAllGeometries(); } void StatisticNamesIO() { auto defaultStatisticNames = mitk::ImageStatisticsContainer::ImageStatisticsObject::GetDefaultStatisticNames(); for (size_t i = 0; i < estimatedDefaultStatisticNames.size(); i++) { CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated default statistics names are not correct.", defaultStatisticNames.at(i), estimatedDefaultStatisticNames.at(i)); } std::string testName = "testName"; double realTypeTest = 3.14; m_StatisticsObject.AddStatistic(testName, realTypeTest); auto customStatisticNames = m_StatisticsObject.GetCustomStatisticNames(); size_t one = 1; CPPUNIT_ASSERT_EQUAL_MESSAGE("Amount of estimated custom statistics names is not correct.", customStatisticNames.size(), one); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated custom statistics names are not correct.", customStatisticNames.front(), testName); auto allStatisticNames = m_StatisticsObject.GetAllStatisticNames(); estimatedDefaultStatisticNames.push_back(testName); for (size_t i = 0; i < estimatedDefaultStatisticNames.size(); i++) { CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", allStatisticNames.at(i), estimatedDefaultStatisticNames.at(i)); } auto existingStatisticNames = m_StatisticsObject.GetExistingStatisticNames(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Amount of estimated existing statistics names is not correct.", existingStatisticNames.size(), one); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated existing statistics names are not correct.", existingStatisticNames.front(), testName); m_StatisticsObject.Reset(); CPPUNIT_ASSERT_MESSAGE("Custom statistics names were not removed correctly.", m_StatisticsObject.GetCustomStatisticNames().empty()); } void InvalidKey() { CPPUNIT_ASSERT_THROW_MESSAGE("Exception should have been thrown because key does not exists.", m_StatisticsObject.GetValueNonConverted("Test"), mitk::Exception); } void TimeSteps() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(0), true); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(1), true); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(2), true); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(3), true); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(4), true); CPPUNIT_ASSERT_THROW_MESSAGE("Out of timeStep geometry bounds timeStep was added but no exception was thrown.", m_StatisticsContainer->SetStatisticsForTimeStep(42, m_StatisticsObject), mitk::Exception); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistics container does not contain the right amount of timeSteps.", static_cast<int> (m_StatisticsContainer->GetNumberOfTimeSteps()), 5); } void PrintSelf() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); std::stringstream print; CPPUNIT_ASSERT_NO_THROW_MESSAGE("Print function throws an exception.", m_StatisticsContainer->Print(print)); } void InternalClone() { auto clone = m_StatisticsContainer->Clone(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Internal clone was not cloned correctly.", m_StatisticsContainer->GetGeometry(), clone->GetGeometry()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Internal clone was not cloned correctly.", m_StatisticsContainer->GetNumberOfTimeSteps(), clone->GetNumberOfTimeSteps()); } void StatisticNames() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsObject2.AddStatistic("Test2", 4.2); m_StatisticsObject3.AddStatistic("Test3", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject2); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject2); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject2); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject2); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject3); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject3); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject3); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject3); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", mitk::GetAllStatisticNames(m_StatisticsContainer).size(), estimatedDefaultStatisticNames.size() + 1); void OverwriteStatistic() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was not correctly added to StatisticsObject.", boost::get<double> (m_StatisticsContainer->GetStatisticsForTimeStep(0).GetValueNonConverted("Test")), 4.2); // An existing statistic won't be updated by adding another statistic with same name to that object. m_StatisticsObject.AddStatistic("Test", 42.0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was overwritten.", boost::get<double>(m_StatisticsContainer->GetStatisticsForTimeStep(0).GetValueNonConverted("Test")), 4.2); } std::vector<mitk::ImageStatisticsContainer::ConstPointer> containers; containers.push_back(m_StatisticsContainer.GetPointer()); containers.push_back(m_StatisticsContainer2.GetPointer()); containers.push_back(m_StatisticsContainer3.GetPointer()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", mitk::GetAllStatisticNames(containers).size(), estimatedDefaultStatisticNames.size() + 1); } void Reset() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); m_StatisticsContainer->Reset(); m_StatisticsObject.Reset(); m_TimeGeometry->ClearAllGeometries(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(0).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(0).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(1).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(1).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(2).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(2).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(3).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(3).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(4).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(4).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was not deleted correctly.", m_StatisticsObject.HasStatistic("Test"), false); CPPUNIT_ASSERT_EQUAL_MESSAGE("Time geometry was not cleared correctly.", m_TimeGeometry->IsValid(), false); } }; MITK_TEST_SUITE_REGISTRATION(mitkImageStatisticsContainer)
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" //MITK includes #include "mitkArbitraryTimeGeometry.h" #include "mitkImageStatisticsContainerNodeHelper.h" #include "mitkImageStatisticsContainerManager.h" #include "mitkImageStatisticsContainer.h" class mitkImageStatisticsContainerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkImageStatisticsContainerTestSuite); MITK_TEST(StatisticNamesIO); MITK_TEST(InvalidKey); MITK_TEST(TimeSteps); MITK_TEST(PrintSelf); MITK_TEST(InternalClone); MITK_TEST(StatisticNames); MITK_TEST(OverwriteStatistic); MITK_TEST(Reset); CPPUNIT_TEST_SUITE_END(); private: mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer; mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer2; mitk::ImageStatisticsContainer::Pointer m_StatisticsContainer3; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject2; mitk::ImageStatisticsContainer::ImageStatisticsObject m_StatisticsObject3; mitk::ArbitraryTimeGeometry::Pointer m_TimeGeometry; mitk::Geometry3D::Pointer m_Geometry1; mitk::Geometry3D::Pointer m_Geometry2; mitk::Geometry3D::Pointer m_Geometry3; mitk::Geometry3D::Pointer m_Geometry3_5; mitk::Geometry3D::Pointer m_Geometry4; mitk::Geometry3D::Pointer m_Geometry5; mitk::TimePointType m_Geometry1MinTP; mitk::TimePointType m_Geometry2MinTP; mitk::TimePointType m_Geometry3MinTP; mitk::TimePointType m_Geometry3_5MinTP; mitk::TimePointType m_Geometry4MinTP; mitk::TimePointType m_Geometry5MinTP; mitk::TimePointType m_Geometry1MaxTP; mitk::TimePointType m_Geometry2MaxTP; mitk::TimePointType m_Geometry3MaxTP; mitk::TimePointType m_Geometry3_5MaxTP; mitk::TimePointType m_Geometry4MaxTP; mitk::TimePointType m_Geometry5MaxTP; std::vector<std::string> estimatedDefaultStatisticNames { "Mean", "Median", "StandardDeviation", "RMS", "Max", "MaxPosition", "Min", "MinPosition", "#Voxel", "Volume [mm^3]", "Skewness", "Kurtosis", "Uniformity", "Entropy", "MPP", "UPP" }; public: void setUp() override { m_StatisticsContainer = mitk::ImageStatisticsContainer::New(); m_StatisticsContainer2 = mitk::ImageStatisticsContainer::New(); m_StatisticsContainer3 = mitk::ImageStatisticsContainer::New(); m_Geometry1 = mitk::Geometry3D::New(); m_Geometry2 = mitk::Geometry3D::New(); m_Geometry3 = mitk::Geometry3D::New(); m_Geometry3_5 = mitk::Geometry3D::New(); m_Geometry4 = mitk::Geometry3D::New(); m_Geometry5 = mitk::Geometry3D::New(); m_Geometry1MinTP = 1; m_Geometry2MinTP = 2; m_Geometry3MinTP = 3; m_Geometry3_5MinTP = 3.5; m_Geometry4MinTP = 4; m_Geometry5MinTP = 5; m_Geometry1MaxTP = 1.9; m_Geometry2MaxTP = 2.9; m_Geometry3MaxTP = 3.9; m_Geometry3_5MaxTP = 3.9; m_Geometry4MaxTP = 4.9; m_Geometry5MaxTP = 5.9; m_TimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_TimeGeometry->ClearAllGeometries(); m_TimeGeometry->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MinTP, m_Geometry4MaxTP); m_TimeGeometry->AppendNewTimeStep(m_Geometry5, m_Geometry5MinTP, m_Geometry5MaxTP); } void tearDown() override { m_StatisticsContainer->Reset(); m_StatisticsContainer2->Reset(); m_StatisticsContainer3->Reset(); m_StatisticsObject.Reset(); m_StatisticsObject2.Reset(); m_StatisticsObject3.Reset(); m_TimeGeometry->ClearAllGeometries(); } void StatisticNamesIO() { auto defaultStatisticNames = mitk::ImageStatisticsContainer::ImageStatisticsObject::GetDefaultStatisticNames(); for (size_t i = 0; i < estimatedDefaultStatisticNames.size(); i++) { CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated default statistics names are not correct.", defaultStatisticNames.at(i), estimatedDefaultStatisticNames.at(i)); } std::string testName = "testName"; double realTypeTest = 3.14; m_StatisticsObject.AddStatistic(testName, realTypeTest); auto customStatisticNames = m_StatisticsObject.GetCustomStatisticNames(); size_t one = 1; CPPUNIT_ASSERT_EQUAL_MESSAGE("Amount of estimated custom statistics names is not correct.", customStatisticNames.size(), one); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated custom statistics names are not correct.", customStatisticNames.front(), testName); auto allStatisticNames = m_StatisticsObject.GetAllStatisticNames(); estimatedDefaultStatisticNames.push_back(testName); for (size_t i = 0; i < estimatedDefaultStatisticNames.size(); i++) { CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", allStatisticNames.at(i), estimatedDefaultStatisticNames.at(i)); } auto existingStatisticNames = m_StatisticsObject.GetExistingStatisticNames(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Amount of estimated existing statistics names is not correct.", existingStatisticNames.size(), one); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated existing statistics names are not correct.", existingStatisticNames.front(), testName); m_StatisticsObject.Reset(); CPPUNIT_ASSERT_MESSAGE("Custom statistics names were not removed correctly.", m_StatisticsObject.GetCustomStatisticNames().empty()); } void InvalidKey() { CPPUNIT_ASSERT_THROW_MESSAGE("Exception should have been thrown because key does not exists.", m_StatisticsObject.GetValueNonConverted("Test"), mitk::Exception); } void TimeSteps() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(0), true); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(1), true); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(2), true); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(3), true); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Previous added time step was not saved correctly.", m_StatisticsContainer->TimeStepExists(4), true); CPPUNIT_ASSERT_THROW_MESSAGE("Out of timeStep geometry bounds timeStep was added but no exception was thrown.", m_StatisticsContainer->SetStatisticsForTimeStep(42, m_StatisticsObject), mitk::Exception); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistics container does not contain the right amount of timeSteps.", static_cast<int> (m_StatisticsContainer->GetNumberOfTimeSteps()), 5); } void PrintSelf() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); std::stringstream print; CPPUNIT_ASSERT_NO_THROW_MESSAGE("Print function throws an exception.", m_StatisticsContainer->Print(print)); } void InternalClone() { auto clone = m_StatisticsContainer->Clone(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Internal clone was not cloned correctly.", m_StatisticsContainer->GetGeometry(), clone->GetGeometry()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Internal clone was not cloned correctly.", m_StatisticsContainer->GetNumberOfTimeSteps(), clone->GetNumberOfTimeSteps()); } void StatisticNames() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsContainer2->SetTimeGeometry(m_TimeGeometry); m_StatisticsContainer3->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsObject2.AddStatistic("Test2", 4.2); m_StatisticsObject3.AddStatistic("Test3", 4.2); // Setting the same statistics for different time steps will only add the statistics name once. m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); // Setting the same statistics for different time steps will only add the statistics name once. m_StatisticsContainer2->SetStatisticsForTimeStep(0, m_StatisticsObject2); m_StatisticsContainer2->SetStatisticsForTimeStep(1, m_StatisticsObject2); m_StatisticsContainer2->SetStatisticsForTimeStep(2, m_StatisticsObject2); m_StatisticsContainer2->SetStatisticsForTimeStep(3, m_StatisticsObject2); m_StatisticsContainer2->SetStatisticsForTimeStep(4, m_StatisticsObject2); // Setting the same statistics for different time steps will only add the statistics name once. m_StatisticsContainer3->SetStatisticsForTimeStep(0, m_StatisticsObject3); m_StatisticsContainer3->SetStatisticsForTimeStep(1, m_StatisticsObject3); m_StatisticsContainer3->SetStatisticsForTimeStep(2, m_StatisticsObject3); m_StatisticsContainer3->SetStatisticsForTimeStep(3, m_StatisticsObject3); m_StatisticsContainer3->SetStatisticsForTimeStep(4, m_StatisticsObject3); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", mitk::GetAllStatisticNames(m_StatisticsContainer).size(), estimatedDefaultStatisticNames.size() + 1); CPPUNIT_ASSERT_EQUAL_MESSAGE("Custom statistic name was not saved correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(0).HasStatistic("Test"), true); std::vector<mitk::ImageStatisticsContainer::ConstPointer> containers; containers.push_back(m_StatisticsContainer2.GetPointer()); containers.push_back(m_StatisticsContainer3.GetPointer()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", mitk::GetAllStatisticNames(containers).size(), estimatedDefaultStatisticNames.size() + 2); CPPUNIT_ASSERT_EQUAL_MESSAGE("Custom statistic name was not saved correctly.", m_StatisticsContainer2->GetStatisticsForTimeStep(0).HasStatistic("Test2"), true); CPPUNIT_ASSERT_EQUAL_MESSAGE("Custom statistic name was not saved correctly.", m_StatisticsContainer3->GetStatisticsForTimeStep(0).HasStatistic("Test3"), true); void OverwriteStatistic() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was not correctly added to StatisticsObject.", boost::get<double> (m_StatisticsContainer->GetStatisticsForTimeStep(0).GetValueNonConverted("Test")), 4.2); // An existing statistic won't be updated by adding another statistic with same name to that object. m_StatisticsObject.AddStatistic("Test", 42.0); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was overwritten.", boost::get<double>(m_StatisticsContainer->GetStatisticsForTimeStep(0).GetValueNonConverted("Test")), 4.2); } std::vector<mitk::ImageStatisticsContainer::ConstPointer> containers; containers.push_back(m_StatisticsContainer.GetPointer()); containers.push_back(m_StatisticsContainer2.GetPointer()); containers.push_back(m_StatisticsContainer3.GetPointer()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Estimated statistics names are not correct.", mitk::GetAllStatisticNames(containers).size(), estimatedDefaultStatisticNames.size() + 1); } void Reset() { m_StatisticsContainer->SetTimeGeometry(m_TimeGeometry); m_StatisticsObject.AddStatistic("Test", 4.2); m_StatisticsContainer->SetStatisticsForTimeStep(0, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(1, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(2, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(3, m_StatisticsObject); m_StatisticsContainer->SetStatisticsForTimeStep(4, m_StatisticsObject); m_StatisticsContainer->Reset(); m_StatisticsObject.Reset(); m_TimeGeometry->ClearAllGeometries(); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(0).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(0).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(1).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(1).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(2).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(2).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(3).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(3).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(4).GetExistingStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic object for time step was not deleted correctly.", m_StatisticsContainer->GetStatisticsForTimeStep(4).GetCustomStatisticNames().size(), size_t()); CPPUNIT_ASSERT_EQUAL_MESSAGE("Statistic was not deleted correctly.", m_StatisticsObject.HasStatistic("Test"), false); CPPUNIT_ASSERT_EQUAL_MESSAGE("Time geometry was not cleared correctly.", m_TimeGeometry->IsValid(), false); } }; MITK_TEST_SUITE_REGISTRATION(mitkImageStatisticsContainer)
Correct StatisticNamesTest
Correct StatisticNamesTest
C++
bsd-3-clause
MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK
60ae42493dd777e39067647f5a5fbffb7547b667
modules/common/adapters/adapter_manager.cc
modules/common/adapters/adapter_manager.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config); break; case AdapterConfig::RAW_IMU: EnableRawImu(FLAGS_raw_imu_topic, config); case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config); break; case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config); break; case AdapterConfig::INS_STATUS: EnableInsStatus(FLAGS_ins_status_topic, config); break; case AdapterConfig::GNSS_STATUS: EnableGnssStatus(FLAGS_gnss_status_topic, config); break; case AdapterConfig::SYSTEM_STATUS: EnableSystemStatus(FLAGS_system_status_topic, config); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config); break; case AdapterConfig::CONTI_RADAR: EnableContiRadar(FLAGS_conti_radar_topic, config); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config); break; case AdapterConfig::IMAGE_SHORT: EnableImageShort(FLAGS_image_short_topic, config); break; case AdapterConfig::IMAGE_LONG: EnableImageLong(FLAGS_image_long_topic, config); break; case AdapterConfig::DRIVE_EVENT: EnableImageLong(FLAGS_drive_event_topic, config); break; case AdapterConfig::GNSS_RTK_OBS: EnableGnssRtkObs(FLAGS_gnss_rtk_obs_topic, config); break; case AdapterConfig::GNSS_RTK_EPH: EnableGnssRtkEph(FLAGS_gnss_rtk_eph_topic, config); break; case AdapterConfig::GNSS_BEST_POSE: EnableGnssBestPose(FLAGS_gnss_best_pose_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_GNSS: EnableLocalizationMsfGnss(FLAGS_localization_gnss_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_LIDAR: EnableLocalizationMsfLidar(FLAGS_localization_lidar_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_SINS_PVA: EnableLocalizationMsfSinsPva(FLAGS_localization_sins_pva_topic, config); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/adapters/adapter_manager.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/util.h" namespace apollo { namespace common { namespace adapter { AdapterManager::AdapterManager() {} void AdapterManager::Observe() { for (const auto observe : instance()->observers_) { observe(); } } bool AdapterManager::Initialized() { return instance()->initialized_; } void AdapterManager::Reset() { instance()->initialized_ = false; instance()->observers_.clear(); } void AdapterManager::Init(const std::string &adapter_config_filename) { // Parse config file AdapterManagerConfig configs; CHECK(util::GetProtoFromFile(adapter_config_filename, &configs)) << "Unable to parse adapter config file " << adapter_config_filename; AINFO << "Init AdapterManger config:" << configs.DebugString(); Init(configs); } void AdapterManager::Init(const AdapterManagerConfig &configs) { if (Initialized()) { return; } instance()->initialized_ = true; if (configs.is_ros()) { instance()->node_handle_.reset(new ros::NodeHandle()); } for (const auto &config : configs.config()) { switch (config.type()) { case AdapterConfig::POINT_CLOUD: EnablePointCloud(FLAGS_pointcloud_topic, config); break; case AdapterConfig::GPS: EnableGps(FLAGS_gps_topic, config); break; case AdapterConfig::IMU: EnableImu(FLAGS_imu_topic, config); break; case AdapterConfig::RAW_IMU: EnableRawImu(FLAGS_raw_imu_topic, config); break; case AdapterConfig::CHASSIS: EnableChassis(FLAGS_chassis_topic, config); break; case AdapterConfig::LOCALIZATION: EnableLocalization(FLAGS_localization_topic, config); break; case AdapterConfig::PERCEPTION_OBSTACLES: EnablePerceptionObstacles(FLAGS_perception_obstacle_topic, config); break; case AdapterConfig::TRAFFIC_LIGHT_DETECTION: EnableTrafficLightDetection(FLAGS_traffic_light_detection_topic, config); break; case AdapterConfig::PAD: EnablePad(FLAGS_pad_topic, config); break; case AdapterConfig::CONTROL_COMMAND: EnableControlCommand(FLAGS_control_command_topic, config); break; case AdapterConfig::ROUTING_REQUEST: EnableRoutingRequest(FLAGS_routing_request_topic, config); break; case AdapterConfig::ROUTING_RESPONSE: EnableRoutingResponse(FLAGS_routing_response_topic, config); break; case AdapterConfig::PLANNING_TRAJECTORY: EnablePlanning(FLAGS_planning_trajectory_topic, config); break; case AdapterConfig::PREDICTION: EnablePrediction(FLAGS_prediction_topic, config); break; case AdapterConfig::MONITOR: EnableMonitor(FLAGS_monitor_topic, config); break; case AdapterConfig::CHASSIS_DETAIL: EnableChassisDetail(FLAGS_chassis_detail_topic, config); break; case AdapterConfig::RELATIVE_ODOMETRY: EnableRelativeOdometry(FLAGS_relative_odometry_topic, config); break; case AdapterConfig::INS_STAT: EnableInsStat(FLAGS_ins_stat_topic, config); break; case AdapterConfig::INS_STATUS: EnableInsStatus(FLAGS_ins_status_topic, config); break; case AdapterConfig::GNSS_STATUS: EnableGnssStatus(FLAGS_gnss_status_topic, config); break; case AdapterConfig::SYSTEM_STATUS: EnableSystemStatus(FLAGS_system_status_topic, config); break; case AdapterConfig::MOBILEYE: EnableMobileye(FLAGS_mobileye_topic, config); break; case AdapterConfig::DELPHIESR: EnableDelphiESR(FLAGS_delphi_esr_topic, config); break; case AdapterConfig::CONTI_RADAR: EnableContiRadar(FLAGS_conti_radar_topic, config); break; case AdapterConfig::COMPRESSED_IMAGE: EnableCompressedImage(FLAGS_compressed_image_topic, config); break; case AdapterConfig::IMAGE_SHORT: EnableImageShort(FLAGS_image_short_topic, config); break; case AdapterConfig::IMAGE_LONG: EnableImageLong(FLAGS_image_long_topic, config); break; case AdapterConfig::DRIVE_EVENT: EnableImageLong(FLAGS_drive_event_topic, config); break; case AdapterConfig::GNSS_RTK_OBS: EnableGnssRtkObs(FLAGS_gnss_rtk_obs_topic, config); break; case AdapterConfig::GNSS_RTK_EPH: EnableGnssRtkEph(FLAGS_gnss_rtk_eph_topic, config); break; case AdapterConfig::GNSS_BEST_POSE: EnableGnssBestPose(FLAGS_gnss_best_pose_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_GNSS: EnableLocalizationMsfGnss(FLAGS_localization_gnss_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_LIDAR: EnableLocalizationMsfLidar(FLAGS_localization_lidar_topic, config); break; case AdapterConfig::LOCALIZATION_MSF_SINS_PVA: EnableLocalizationMsfSinsPva(FLAGS_localization_sins_pva_topic, config); break; default: AERROR << "Unknown adapter config type!"; break; } } } } // namespace adapter } // namespace common } // namespace apollo
Fix switch case fall-through.
Common: Fix switch case fall-through.
C++
apache-2.0
wanglei828/apollo,ApolloAuto/apollo,wanglei828/apollo,xiaoxq/apollo,ycool/apollo,wanglei828/apollo,ycool/apollo,jinghaomiao/apollo,ycool/apollo,ApolloAuto/apollo,wanglei828/apollo,ycool/apollo,ApolloAuto/apollo,jinghaomiao/apollo,xiaoxq/apollo,ApolloAuto/apollo,wanglei828/apollo,xiaoxq/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,jinghaomiao/apollo,ycool/apollo,ApolloAuto/apollo,jinghaomiao/apollo,xiaoxq/apollo,xiaoxq/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo
a3f16016e52f8bdce88c63e99be23323d188bf78
demo2/src/demo/object/transform.cpp
demo2/src/demo/object/transform.cpp
// transform.cpp #include "transform.h" #include <glm/gtc/matrix_transform.hpp> namespace demo { namespace obj { // CONSTANTS const glm::vec3 Transform::FORWARD( glm::vec3( 0, 0, -1 ) ); const glm::vec3 Transform::UP( glm::vec3( 0, 1, 0 ) ); const glm::vec3 Transform::RIGHT( glm::vec3( -1, 0, 0 ) ); const glm::vec3 Transform::ZERO( glm::vec3( 0, 0, 0 ) ); // MUTATOR FUNCTIONS void Transform::setEulerRotation( const glm::vec3& rotation ) { glm::quat yaw = glm::rotate( glm::quat(), rotation.z, glm::vec3( 0.0f, 0.0f, 1.0f ) ); glm::quat pitch = glm::rotate( glm::quat(), rotation.x, glm::vec3( 1.0f, 0.0f, 0.0f ) ); glm::quat roll = glm::rotate( glm::quat(), rotation.y, glm::vec3( 0.0f, 1.0f, 0.0f ) ); _rotation = yaw * pitch * roll; recomputeMatrix(); } // MEMBER FUNCTIONS void Transform::rotateEuler( const glm::vec3& rotation ) { glm::quat rot = glm::rotate( _rotation, rotation.z, glm::vec3( 0.0f, 0.0f, 1.0f ) ); rot = glm::rotate( rot, rotation.x, glm::vec3( 1.0f, 0.0f, 0.0f ) ); rot = glm::rotate( rot, rotation.y, glm::vec3( 0.0f, 1.0f, 0.0f ) ); _rotation = rot; recomputeMatrix(); } void Transform::rotateAround( const glm::vec3& point, const glm::quat& rotation ) { glm::vec4 pos = rotation * glm::vec4( _position - point, 1.0f ); _position = glm::vec3( pos.x / pos.w, pos.y / pos.w, pos.z / pos.w ) + point; _rotation *= rotation; recomputeMatrix(); } void Transform::lookAt( const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up ) { assert( eye != center ); glm::vec3 forwardDir = glm::normalize( center - eye ); glm::vec3 upDir = glm::normalize( up ); glm::vec3 lookAxis = glm::cross( FORWARD, forwardDir ); glm::vec3 upAxis = glm::cross( UP, upDir ); // prevent zero axis if ( lookAxis == ZERO ) { lookAxis = glm::vec3( 0, 0, 1 ); } if ( upAxis == ZERO ) { upAxis = glm::vec3( 0, 0, 1 ); } lookAxis = glm::normalize( lookAxis ); upAxis = glm::normalize( upAxis ); float lookDot = glm::dot( FORWARD, forwardDir ); float lookAngle = acosf( lookDot ); float upDot = glm::dot( UP, upDir ); float upAngle = acosf( upDot ); glm::quat lookQuat = glm::angleAxis( lookAngle, lookAxis ); glm::quat upQuat = glm::normalize( glm::quat( upAxis * upAngle ) ); _rotation = glm::quat_cast( glm::mat4_cast( lookQuat ) * glm::mat4_cast( upQuat ) ); _position = eye; recomputeMatrix(); } // HELPER FUNCTIONS void Transform::recomputeMatrix() { glm::mat4 trans; trans[3][0] = _position.x; trans[3][1] = _position.y; trans[3][2] = _position.z; glm::mat4 rot( glm::mat4_cast( _rotation ) ); glm::mat4 scale( _scale.x, 0, 0, 0, 0, _scale.y, 0, 0, 0, 0, _scale.z, 0, 0, 0, 0, 1 ); _matrix = trans * rot * scale; _hasChanged = true; } } // End nspc obj } // End nspc demo
// transform.cpp #include "transform.h" #include <glm/gtc/matrix_transform.hpp> namespace demo { namespace obj { // CONSTANTS const glm::vec3 Transform::FORWARD( glm::vec3( 0, 0, -1 ) ); const glm::vec3 Transform::UP( glm::vec3( 0, 1, 0 ) ); const glm::vec3 Transform::RIGHT( glm::vec3( -1, 0, 0 ) ); const glm::vec3 Transform::ZERO( glm::vec3( 0, 0, 0 ) ); // MUTATOR FUNCTIONS void Transform::setEulerRotation( const glm::vec3& rotation ) { // todo: figure out why rotations are not being done in degrees glm::quat yaw = glm::rotate( glm::quat(), glm::radians( rotation.z ), glm::vec3( 0.0f, 0.0f, 1.0f ) ); glm::quat pitch = glm::rotate( glm::quat(), glm::radians( rotation.x ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); glm::quat roll = glm::rotate( glm::quat(), glm::radians( rotation.y ), glm::vec3( 0.0f, 1.0f, 0.0f ) ); _rotation = yaw * pitch * roll; recomputeMatrix(); } // MEMBER FUNCTIONS void Transform::rotateEuler( const glm::vec3& rotation ) { // todo: figure out why rotations are not being done in degrees glm::quat rot = glm::rotate( _rotation, glm::radians( rotation.z ), glm::vec3( 0.0f, 0.0f, 1.0f ) ); rot = glm::rotate( rot, glm::radians( rotation.x ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); rot = glm::rotate( rot, glm::radians( rotation.y ), glm::vec3( 0.0f, 1.0f, 0.0f ) ); _rotation = rot; recomputeMatrix(); } void Transform::rotateAround( const glm::vec3& point, const glm::quat& rotation ) { glm::vec4 pos = rotation * glm::vec4( _position - point, 1.0f ); _position = glm::vec3( pos.x / pos.w, pos.y / pos.w, pos.z / pos.w ) + point; _rotation *= rotation; recomputeMatrix(); } void Transform::lookAt( const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up ) { assert( eye != center ); glm::vec3 forwardDir = glm::normalize( center - eye ); glm::vec3 upDir = glm::normalize( up ); glm::vec3 lookAxis = glm::cross( FORWARD, forwardDir ); glm::vec3 upAxis = glm::cross( UP, upDir ); // prevent zero axis if ( lookAxis == ZERO ) { lookAxis = glm::vec3( 0, 0, 1 ); } if ( upAxis == ZERO ) { upAxis = glm::vec3( 0, 0, 1 ); } lookAxis = glm::normalize( lookAxis ); upAxis = glm::normalize( upAxis ); float lookDot = glm::dot( FORWARD, forwardDir ); float lookAngle = acosf( lookDot ); float upDot = glm::dot( UP, upDir ); float upAngle = acosf( upDot ); glm::quat lookQuat = glm::angleAxis( lookAngle, lookAxis ); glm::quat upQuat = glm::normalize( glm::quat( upAxis * upAngle ) ); _rotation = glm::quat_cast( glm::mat4_cast( lookQuat ) * glm::mat4_cast( upQuat ) ); _position = eye; recomputeMatrix(); } // HELPER FUNCTIONS void Transform::recomputeMatrix() { glm::mat4 trans; trans[3][0] = _position.x; trans[3][1] = _position.y; trans[3][2] = _position.z; glm::mat4 rot( glm::mat4_cast( _rotation ) ); glm::mat4 scale( _scale.x, 0, 0, 0, 0, _scale.y, 0, 0, 0, 0, _scale.z, 0, 0, 0, 0, 1 ); _matrix = trans * rot * scale; _hasChanged = true; } } // End nspc obj } // End nspc demo
Fix bug where rotations were being performed in radians instead of degrees.
Fix bug where rotations were being performed in radians instead of degrees.
C++
mit
invaderjon/demo,invaderjon/demo
33ee301f8bd8e83abf6dea43b3a7d17173c913f1
src/Bull/Core/Image/ImageLoader.cpp
src/Bull/Core/Image/ImageLoader.cpp
#include <stb_image/stb_image.h> #include <Bull/Core/Image/ImageLoader.hpp> #include <Bull/Core/IO/OutStringStream.hpp> #include <Bull/Core/Log/Log.hpp> #include <Bull/Core/Utility/CleanupCallback.hpp> namespace Bull { int ImageLoader::read(void* user, char* data, int size) { InStream* stream = reinterpret_cast<InStream*>(user); return stream->read(data, size); } void ImageLoader::skip(void* user, int n) { ByteVector buffer(n); InStream* stream = reinterpret_cast<InStream*>(user); stream->read(&buffer[0], buffer.getCapacity()); } int ImageLoader::eof(void* user) { InStream* stream = reinterpret_cast<InStream*>(user); return stream->isAtEnd() ? 1 : 0; } bool ImageLoader::getInfo(ImageInfo& info, const Path& path) { return createTask([&info, path]() -> bool{ return stbi_info(path.toString().getBuffer(), reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::getInfo(ImageInfo& info, InStream& stream) { return createTask([&info, &stream]() -> bool{ stbi_io_callbacks callbacks; callbacks.read = &ImageLoader::read; callbacks.skip = &ImageLoader::skip; callbacks.eof = &ImageLoader::eof; return stbi_info_from_callbacks(&callbacks, &stream, reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::getInfo(ImageInfo& info, const void* data, std::size_t length) { return createTask([&info, data, length]() -> bool{ return stbi_info_from_memory(reinterpret_cast<stbi_uc*>(data), length, reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::loadFromPath(AbstractImage& image, const Path& path) { return createTask([&image, path, this]() -> bool{ int width, height, channels; stbi_uc* buffer = stbi_load(path.toString().getBuffer(), &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from path " << path.toString() << " : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } bool ImageLoader::loadFromStream(AbstractImage& image, InStream& stream) { return createTask([&image, &stream, this]() -> bool{ stbi_io_callbacks callbacks; int width, height, channels; callbacks.read = &ImageLoader::read; callbacks.skip = &ImageLoader::skip; callbacks.eof = &ImageLoader::eof; stbi_uc* buffer = stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from stream : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } bool ImageLoader::loadFromMemory(AbstractImage& image, const void* data, std::size_t length) { return createTask([&image, data, length, this]() -> bool{ int width, height, channels; stbi_uc* buffer = stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(data), length, &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from memory : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } String ImageLoader::getErrorMessage() const { m_mutex.lock(); String message(stbi_failure_reason()); m_mutex.unlock(); return message; } bool ImageLoader::createImage(AbstractImage& image, const void* buffer, int width, int height, int channels) { if(buffer && width && height) { ByteVector pixels; if(pixels.fill(buffer, width * height * channels)) { Vector2UI size(width, height); return image.create(pixels, size); } } return false; } }
#include <stb_image/stb_image.h> #include <Bull/Core/Image/ImageLoader.hpp> #include <Bull/Core/IO/OutStringStream.hpp> #include <Bull/Core/Log/Log.hpp> #include <Bull/Core/Utility/CleanupCallback.hpp> namespace Bull { int ImageLoader::read(void* user, char* data, int size) { InStream* stream = reinterpret_cast<InStream*>(user); return stream->read(data, size); } void ImageLoader::skip(void* user, int n) { ByteVector buffer(n); InStream* stream = reinterpret_cast<InStream*>(user); stream->read(&buffer[0], buffer.getCapacity()); } int ImageLoader::eof(void* user) { InStream* stream = reinterpret_cast<InStream*>(user); return stream->isAtEnd() ? 1 : 0; } bool ImageLoader::getInfo(ImageInfo& info, const Path& path) { return createTask([&info, path]() -> bool{ return stbi_info(path.toString().getBuffer(), reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::getInfo(ImageInfo& info, InStream& stream) { return createTask([&info, &stream]() -> bool{ stbi_io_callbacks callbacks; callbacks.read = &ImageLoader::read; callbacks.skip = &ImageLoader::skip; callbacks.eof = &ImageLoader::eof; return stbi_info_from_callbacks(&callbacks, &stream, reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::getInfo(ImageInfo& info, const void* data, std::size_t length) { return createTask([&info, data, length]() -> bool{ return stbi_info_from_memory(reinterpret_cast<const stbi_uc*>(data), length, reinterpret_cast<int*>(&info.size.x()), reinterpret_cast<int*>(&info.size.y()), reinterpret_cast<int*>(&info.channels)) == 0; }); } bool ImageLoader::loadFromPath(AbstractImage& image, const Path& path) { return createTask([&image, path, this]() -> bool{ int width, height, channels; stbi_uc* buffer = stbi_load(path.toString().getBuffer(), &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from path " << path.toString() << " : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } bool ImageLoader::loadFromStream(AbstractImage& image, InStream& stream) { return createTask([&image, &stream, this]() -> bool{ stbi_io_callbacks callbacks; int width, height, channels; callbacks.read = &ImageLoader::read; callbacks.skip = &ImageLoader::skip; callbacks.eof = &ImageLoader::eof; stbi_uc* buffer = stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from stream : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } bool ImageLoader::loadFromMemory(AbstractImage& image, const void* data, std::size_t length) { return createTask([&image, data, length, this]() -> bool{ int width, height, channels; stbi_uc* buffer = stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(data), length, &width, &height, &channels, STBI_rgb_alpha); CleanupCallback cleanupCallback([buffer](){ stbi_image_free(buffer); }); if(!createImage(image, buffer, width, height, channels)) { OutStringStream oss; oss << "Failed to load image from memory : " << getErrorMessage(); Log::get()->write(oss.toString(), LogLevel_Error); return false; } return true; }); } String ImageLoader::getErrorMessage() const { m_mutex.lock(); String message(stbi_failure_reason()); m_mutex.unlock(); return message; } bool ImageLoader::createImage(AbstractImage& image, const void* buffer, int width, int height, int channels) { if(buffer && width && height) { ByteVector pixels; if(pixels.fill(buffer, width * height * channels)) { Vector2UI size(width, height); return image.create(pixels, size); } } return false; } }
Fix build
[Core/ImageLoader] Fix build
C++
mit
siliace/Bull
aedc861f7b20a2df374ac2265400690b15e57d71
opencog/reasoning/RuleEngine/rule-engine-src/pln/ForwardChainPatternMatchCB.cc
opencog/reasoning/RuleEngine/rule-engine-src/pln/ForwardChainPatternMatchCB.cc
/* * ForwardChainPatternMatchCB.cc * * Copyright (C) 2014 Misgana Bayetta * * Author: Misgana Bayetta <[email protected]> Sept 2014 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "ForwardChainPatternMatchCB.h" ForwardChainPatternMatchCB::ForwardChainPatternMatchCB(AtomSpace * as) : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), _as(as) { _fcmem = nullptr; } ForwardChainPatternMatchCB::~ForwardChainPatternMatchCB() { } bool ForwardChainPatternMatchCB::node_match(Handle& node1, Handle& node2) { //constrain search within premise list if (_fcmem->is_search_in_af()) return (_fcmem->isin_premise_list(node2) and AttentionalFocusCB::node_match( node1, node2)); else return (_fcmem->isin_premise_list(node2) and DefaultPatternMatchCB::node_match( node1, node2)); } bool ForwardChainPatternMatchCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) { //constrain search within premise list if (_fcmem->is_search_in_af()) return (_fcmem->isin_premise_list(Handle(lsoln)) and AttentionalFocusCB::link_match( lpat, lsoln)); else return (_fcmem->isin_premise_list(Handle(lsoln)) and DefaultPatternMatchCB::link_match( lpat, lsoln)); } bool ForwardChainPatternMatchCB::grounding( const std::map<Handle, Handle> &var_soln, const std::map<Handle, Handle> &pred_soln) { Handle h = inst.instantiate(implicand, var_soln); if (Handle::UNDEFINED != h) { result_list.push_back(h); } return false; } void ForwardChainPatternMatchCB::set_fcmem(FCMemory *fcmem) { _fcmem = fcmem; } HandleSeq ForwardChainPatternMatchCB::get_products() { auto product = result_list; result_list.clear(); return product; }
/* * ForwardChainPatternMatchCB.cc * * Copyright (C) 2014 Misgana Bayetta * * Author: Misgana Bayetta <[email protected]> Sept 2014 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "ForwardChainPatternMatchCB.h" ForwardChainPatternMatchCB::ForwardChainPatternMatchCB(AtomSpace * as) : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), _as(as) { _fcmem = nullptr; } ForwardChainPatternMatchCB::~ForwardChainPatternMatchCB() { } bool ForwardChainPatternMatchCB::node_match(Handle& node1, Handle& node2) { //constrain search within premise list return _fcmem->isin_premise_list(node2) and (_fcmem->is_search_in_af() ? AttentionalFocusCB::node_match(node1, node2) : DefaultPatternMatchCB::node_match(node1, node2)); } bool ForwardChainPatternMatchCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) { //constrain search within premise list return _fcmem->isin_premise_list(Handle(lsoln)) and (_fcmem->is_search_in_af() ? AttentionalFocusCB::link_match(lpat, lsoln) : DefaultPatternMatchCB::link_match(lpat, lsoln)); } bool ForwardChainPatternMatchCB::grounding( const std::map<Handle, Handle> &var_soln, const std::map<Handle, Handle> &pred_soln) { Handle h = inst.instantiate(implicand, var_soln); if (Handle::UNDEFINED != h) { result_list.push_back(h); } return false; } void ForwardChainPatternMatchCB::set_fcmem(FCMemory *fcmem) { _fcmem = fcmem; } HandleSeq ForwardChainPatternMatchCB::get_products() { auto product = result_list; result_list.clear(); return product; }
Simplify ForwardChainPatternMatchCB::{node_match,link_match}
Simplify ForwardChainPatternMatchCB::{node_match,link_match}
C++
agpl-3.0
cosmoharrigan/opencog,andre-senna/opencog,roselleebarle04/opencog,rodsol/opencog,ceefour/opencog,shujingke/opencog,kinoc/opencog,inflector/atomspace,cosmoharrigan/atomspace,sanuj/opencog,eddiemonroe/atomspace,eddiemonroe/opencog,TheNameIsNigel/opencog,ceefour/opencog,printedheart/opencog,gavrieltal/opencog,jswiergo/atomspace,MarcosPividori/atomspace,gavrieltal/opencog,ArvinPan/opencog,eddiemonroe/atomspace,virneo/atomspace,rohit12/opencog,misgeatgit/atomspace,ArvinPan/atomspace,printedheart/atomspace,anitzkin/opencog,printedheart/atomspace,printedheart/opencog,rohit12/atomspace,eddiemonroe/opencog,MarcosPividori/atomspace,eddiemonroe/opencog,Tiggels/opencog,Selameab/opencog,rohit12/opencog,ceefour/atomspace,Tiggels/opencog,shujingke/opencog,gavrieltal/opencog,yantrabuddhi/atomspace,gavrieltal/opencog,prateeksaxena2809/opencog,AmeBel/atomspace,eddiemonroe/atomspace,virneo/opencog,tim777z/opencog,Tiggels/opencog,yantrabuddhi/opencog,rohit12/opencog,yantrabuddhi/opencog,rodsol/atomspace,eddiemonroe/atomspace,Selameab/opencog,ArvinPan/opencog,kinoc/opencog,tim777z/opencog,eddiemonroe/opencog,anitzkin/opencog,Selameab/atomspace,Tiggels/opencog,andre-senna/opencog,rTreutlein/atomspace,shujingke/opencog,williampma/atomspace,printedheart/opencog,ceefour/opencog,rohit12/atomspace,kinoc/opencog,virneo/atomspace,AmeBel/opencog,ArvinPan/opencog,AmeBel/opencog,yantrabuddhi/atomspace,ruiting/opencog,jlegendary/opencog,TheNameIsNigel/opencog,jlegendary/opencog,printedheart/atomspace,ArvinPan/opencog,roselleebarle04/opencog,Selameab/opencog,misgeatgit/opencog,andre-senna/opencog,AmeBel/atomspace,misgeatgit/atomspace,inflector/opencog,inflector/opencog,AmeBel/opencog,jlegendary/opencog,yantrabuddhi/atomspace,yantrabuddhi/opencog,cosmoharrigan/atomspace,virneo/opencog,inflector/opencog,anitzkin/opencog,AmeBel/atomspace,iAMr00t/opencog,virneo/opencog,prateeksaxena2809/opencog,rohit12/opencog,kinoc/opencog,rohit12/atomspace,cosmoharrigan/opencog,gavrieltal/opencog,eddiemonroe/atomspace,roselleebarle04/opencog,kinoc/opencog,jlegendary/opencog,kinoc/opencog,TheNameIsNigel/opencog,virneo/atomspace,AmeBel/opencog,anitzkin/opencog,Tiggels/opencog,TheNameIsNigel/opencog,tim777z/opencog,ArvinPan/atomspace,Allend575/opencog,ruiting/opencog,ArvinPan/atomspace,MarcosPividori/atomspace,williampma/atomspace,tim777z/opencog,yantrabuddhi/opencog,misgeatgit/opencog,prateeksaxena2809/opencog,williampma/opencog,inflector/opencog,kim135797531/opencog,williampma/opencog,misgeatgit/opencog,AmeBel/atomspace,williampma/opencog,inflector/opencog,Selameab/atomspace,ceefour/opencog,ArvinPan/opencog,roselleebarle04/opencog,rTreutlein/atomspace,TheNameIsNigel/opencog,williampma/atomspace,andre-senna/opencog,jswiergo/atomspace,kim135797531/opencog,ceefour/atomspace,misgeatgit/opencog,ruiting/opencog,MarcosPividori/atomspace,eddiemonroe/opencog,inflector/opencog,AmeBel/opencog,ruiting/opencog,Selameab/opencog,rodsol/opencog,rodsol/atomspace,printedheart/opencog,shujingke/opencog,UIKit0/atomspace,kinoc/opencog,shujingke/opencog,anitzkin/opencog,yantrabuddhi/atomspace,rodsol/opencog,Selameab/opencog,jlegendary/opencog,cosmoharrigan/opencog,rohit12/opencog,inflector/opencog,rTreutlein/atomspace,gavrieltal/opencog,jlegendary/opencog,virneo/opencog,Allend575/opencog,inflector/atomspace,andre-senna/opencog,ceefour/atomspace,misgeatgit/opencog,roselleebarle04/opencog,virneo/atomspace,kim135797531/opencog,kim135797531/opencog,Selameab/atomspace,cosmoharrigan/opencog,rodsol/opencog,ceefour/atomspace,Allend575/opencog,printedheart/opencog,AmeBel/opencog,virneo/opencog,yantrabuddhi/opencog,printedheart/opencog,Tiggels/opencog,Selameab/atomspace,misgeatgit/atomspace,tim777z/opencog,shujingke/opencog,roselleebarle04/opencog,anitzkin/opencog,yantrabuddhi/opencog,eddiemonroe/opencog,ruiting/opencog,rodsol/atomspace,Allend575/opencog,jlegendary/opencog,sanuj/opencog,iAMr00t/opencog,printedheart/atomspace,cosmoharrigan/opencog,misgeatgit/atomspace,inflector/atomspace,ceefour/opencog,rodsol/atomspace,UIKit0/atomspace,AmeBel/atomspace,UIKit0/atomspace,kim135797531/opencog,ArvinPan/opencog,Selameab/opencog,andre-senna/opencog,gavrieltal/opencog,iAMr00t/opencog,williampma/opencog,misgeatgit/atomspace,virneo/opencog,sanuj/opencog,AmeBel/opencog,jswiergo/atomspace,jswiergo/atomspace,williampma/opencog,tim777z/opencog,ruiting/opencog,prateeksaxena2809/opencog,inflector/atomspace,yantrabuddhi/atomspace,prateeksaxena2809/opencog,kim135797531/opencog,prateeksaxena2809/opencog,iAMr00t/opencog,inflector/atomspace,cosmoharrigan/opencog,roselleebarle04/opencog,TheNameIsNigel/opencog,rohit12/atomspace,shujingke/opencog,williampma/atomspace,eddiemonroe/opencog,yantrabuddhi/opencog,rodsol/opencog,kim135797531/opencog,cosmoharrigan/atomspace,Allend575/opencog,misgeatgit/opencog,ceefour/opencog,andre-senna/opencog,cosmoharrigan/atomspace,iAMr00t/opencog,sanuj/opencog,iAMr00t/opencog,ArvinPan/atomspace,prateeksaxena2809/opencog,misgeatgit/opencog,virneo/opencog,anitzkin/opencog,misgeatgit/opencog,rTreutlein/atomspace,Allend575/opencog,williampma/opencog,rTreutlein/atomspace,sanuj/opencog,ruiting/opencog,rohit12/opencog,UIKit0/atomspace,ceefour/opencog,Allend575/opencog,misgeatgit/opencog,sanuj/opencog,rodsol/opencog,inflector/opencog
a6136b7156fb8ed9b5ed3fc27296096ea0d5c99e
lib/Target/ARM/ARMTargetMachine.cpp
lib/Target/ARM/ARMTargetMachine.cpp
//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static MCAsmInfo *createMCAsmInfo(const Target &T, StringRef TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } // This is duplicated code. Refactor this. static MCStreamer *createMCStreamer(const Target &T, const std::string &TT, MCContext &Ctx, TargetAsmBackend &TAB, raw_ostream &_OS, MCCodeEmitter *_Emitter, bool RelaxAll) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return createMachOStreamer(Ctx, TAB, _OS, _Emitter, RelaxAll); case Triple::MinGW32: case Triple::MinGW64: case Triple::Cygwin: case Triple::Win32: assert(0 && "ARM does not support Windows COFF format"); break; default: return createELFStreamer(Ctx, TAB, _OS, _Emitter, RelaxAll); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); // Register the MC Code Emitter TargetRegistry::RegisterCodeEmitter(TheARMTarget, createARMMCCodeEmitter); TargetRegistry::RegisterCodeEmitter(TheThumbTarget, createARMMCCodeEmitter); // Register the object streamer. TargetRegistry::RegisterObjectStreamer(TheARMTarget, createMCStreamer); TargetRegistry::RegisterObjectStreamer(TheThumbTarget, createMCStreamer); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()), DataLayout(Subtarget.getDataLayout()), ELFWriterInfo(*this) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), TLInfo(*this), TSInfo(*this) { if (!Subtarget.hasARMOps()) report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not " "support ARM mode execution!"); } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), TLInfo(*this), TSInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addPreISel(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (OptLevel != CodeGenOpt::None) PM.add(createARMGlobalMergePass(getTargetLowering())); return false; } bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this, OptLevel)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass(true)); return true; } bool ARMBaseTargetMachine::addPreSched2(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (Subtarget.hasNEON()) PM.add(createNEONMoveFixPass()); } // Expand some pseudo instructions into multiple instructions to allow // proper scheduling. PM.add(createARMExpandPseudoPass()); if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); } if (Subtarget.isThumb2()) PM.add(createThumb2ITBlockPass()); return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.isThumb2() && !Subtarget.prefers32BitThumb()) PM.add(createThumb2SizeReductionPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; }
//===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // //===----------------------------------------------------------------------===// #include "ARMTargetMachine.h" #include "ARMMCAsmInfo.h" #include "ARMFrameInfo.h" #include "ARM.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; static MCAsmInfo *createMCAsmInfo(const Target &T, StringRef TT) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return new ARMMCAsmInfoDarwin(); default: return new ARMELFMCAsmInfo(); } } // This is duplicated code. Refactor this. static MCStreamer *createMCStreamer(const Target &T, const std::string &TT, MCContext &Ctx, TargetAsmBackend &TAB, raw_ostream &_OS, MCCodeEmitter *_Emitter, bool RelaxAll) { Triple TheTriple(TT); switch (TheTriple.getOS()) { case Triple::Darwin: return createMachOStreamer(Ctx, TAB, _OS, _Emitter, RelaxAll); case Triple::MinGW32: case Triple::MinGW64: case Triple::Cygwin: case Triple::Win32: llvm_unreachable("ARM does not support Windows COFF format"); return NULL; default: return createELFStreamer(Ctx, TAB, _OS, _Emitter, RelaxAll); } } extern "C" void LLVMInitializeARMTarget() { // Register the target. RegisterTargetMachine<ARMTargetMachine> X(TheARMTarget); RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget); // Register the target asm info. RegisterAsmInfoFn A(TheARMTarget, createMCAsmInfo); RegisterAsmInfoFn B(TheThumbTarget, createMCAsmInfo); // Register the MC Code Emitter TargetRegistry::RegisterCodeEmitter(TheARMTarget, createARMMCCodeEmitter); TargetRegistry::RegisterCodeEmitter(TheThumbTarget, createARMMCCodeEmitter); // Register the object streamer. TargetRegistry::RegisterObjectStreamer(TheARMTarget, createMCStreamer); TargetRegistry::RegisterObjectStreamer(TheThumbTarget, createMCStreamer); } /// TargetMachine ctor - Create an ARM architecture model. /// ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const std::string &TT, const std::string &FS, bool isThumb) : LLVMTargetMachine(T, TT), Subtarget(TT, FS, isThumb), FrameInfo(Subtarget), JITInfo(), InstrItins(Subtarget.getInstrItineraryData()), DataLayout(Subtarget.getDataLayout()), ELFWriterInfo(*this) { DefRelocModel = getRelocationModel(); } ARMTargetMachine::ARMTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, false), InstrInfo(Subtarget), TLInfo(*this), TSInfo(*this) { if (!Subtarget.hasARMOps()) report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not " "support ARM mode execution!"); } ThumbTargetMachine::ThumbTargetMachine(const Target &T, const std::string &TT, const std::string &FS) : ARMBaseTargetMachine(T, TT, FS, true), InstrInfo(Subtarget.hasThumb2() ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget)) : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))), TLInfo(*this), TSInfo(*this) { } // Pass Pipeline Configuration bool ARMBaseTargetMachine::addPreISel(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (OptLevel != CodeGenOpt::None) PM.add(createARMGlobalMergePass(getTargetLowering())); return false; } bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { PM.add(createARMISelDag(*this, OptLevel)); return false; } bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None && !Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass(true)); return true; } bool ARMBaseTargetMachine::addPreSched2(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { // FIXME: temporarily disabling load / store optimization pass for Thumb1. if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createARMLoadStoreOptimizationPass()); if (Subtarget.hasNEON()) PM.add(createNEONMoveFixPass()); } // Expand some pseudo instructions into multiple instructions to allow // proper scheduling. PM.add(createARMExpandPseudoPass()); if (OptLevel != CodeGenOpt::None) { if (!Subtarget.isThumb1Only()) PM.add(createIfConverterPass()); } if (Subtarget.isThumb2()) PM.add(createThumb2ITBlockPass()); return true; } bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) { if (Subtarget.isThumb2() && !Subtarget.prefers32BitThumb()) PM.add(createThumb2SizeReductionPass()); PM.add(createARMConstantIslandPass()); return true; } bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLevel, JITCodeEmitter &JCE) { // FIXME: Move this to TargetJITInfo! if (DefRelocModel == Reloc::Default) setRelocationModel(Reloc::Static); // Machine code emitter pass for ARM. PM.add(createARMJITCodeEmitterPass(*this, JCE)); return false; }
Resolve this GCC warning: ARMTargetMachine.cpp:53: error: control reaches end of non-void function
Resolve this GCC warning: ARMTargetMachine.cpp:53: error: control reaches end of non-void function git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@114992 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm
cf72b8e0f6fdc945978b3a7ce47949e0b30ab45c
Source/Core/Module/CrossScript.cpp
Source/Core/Module/CrossScript.cpp
#include "CrossScript.h" #include "../Driver/Profiler/Optick/optick.h" #include <utility> using namespace PaintsNow; CrossRoutine::CrossRoutine(IScript::RequestPool* p, IScript::Request::Ref r) : pool(p), ref(r) {} CrossRoutine::~CrossRoutine() { Clear(); } void CrossRoutine::Clear() { if (ref) { IScript::Request& req = pool->GetScript().GetDefaultRequest(); req.DoLock(); req.Dereference(ref); ref.value = 0; req.UnLock(); } } void CrossRoutine::ScriptUninitialize(IScript::Request& request) { request.UnLock(); SharedTiny::ScriptUninitialize(request); request.DoLock(); } static void SysCall(IScript::Request& request, IScript::Delegate<CrossRoutine> routine, IScript::Request::Arguments& args) { CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->Call(request, routine.Get(), args); } static void SysCallAsync(IScript::Request& request, IScript::Request::Ref callback, IScript::Delegate<CrossRoutine> routine, IScript::Request::Arguments& args) { CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->CallAsync(request, callback, routine.Get(), args); } CrossScript::CrossScript(ThreadPool& e, IScript& script) : RequestPool(script, e.GetThreadCount()), threadPool(e) { script.DoLock(); IScript::Request& request = script.GetDefaultRequest(); request << global << key("SysCall") << request.Adapt(Wrap(SysCall)); request << global << key("SysCallAsync") << request.Adapt(Wrap(SysCallAsync)); script.SetErrorHandler(Wrap(this, &CrossScript::ErrorHandler)); script.UnLock(); } void CrossScript::ErrorHandler(IScript::Request& request, const String& err) { fprintf(stderr, "[CrossScript] subscript error: %s\n", err.c_str()); } CrossScript::~CrossScript() { requestPool.Clear(); script.ReleaseDevice(); } void CrossScript::ScriptUninitialize(IScript::Request& request) { // in case of recursive locking request.UnLock(); BaseClass::ScriptUninitialize(request); request.DoLock(); } TObject<IReflect>& CrossScript::operator () (IReflect& reflect) { BaseClass::operator () (reflect); if (reflect.IsReflectMethod()) {} return *this; } class RoutineWrapper { public: RoutineWrapper(rvalue<TShared<CrossRoutine> > r) : routine(std::move(r)) {} ~RoutineWrapper() {} void operator () (IScript::Request& request, IScript::Request::Arguments& args) { // always use sync call CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->Call(request, routine(), args); } TShared<CrossRoutine> routine; }; TShared<CrossRoutine> CrossScript::Get(const String& name) { IScript::Request& request = script.GetDefaultRequest(); request.DoLock(); IScript::Request::Ref ref; request << global; request << key(name) >> ref; request << endtable; request.UnLock(); if (ref.value != 0) { return TShared<CrossRoutine>::From(new CrossRoutine(this, ref)); } else { return nullptr; } } TShared<CrossRoutine> CrossScript::Load(const String& code) { IScript::Request& request = script.GetDefaultRequest(); request.DoLock(); IScript::Request::Ref ref = request.Load(code, "CrossScript"); request.UnLock(); if (ref.value != 0) { return TShared<CrossRoutine>::From(new CrossRoutine(this, ref)); } else { return nullptr; } } static void CopyTable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest); static void CopyArray(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest); static void CopyVariable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest, IScript::Request::TYPE type) { switch (type) { case IScript::Request::NIL: request << nil; break; case IScript::Request::BOOLEAN: { bool value; fromRequest >> value; request << value; break; } case IScript::Request::NUMBER: { double value; fromRequest >> value; request << value; break; } case IScript::Request::INTEGER: { int64_t value; fromRequest >> value; request << value; break; } case IScript::Request::STRING: { String value; fromRequest >> value; request << value; break; } case IScript::Request::TABLE: { CopyTable(flag, request, fromRequest); break; } case IScript::Request::ARRAY: { CopyArray(flag, request, fromRequest); break; } case IScript::Request::FUNCTION: { // convert to reference IScript::Request::Ref ref; fromRequest >> ref; IScript::Request::AutoWrapperBase* wrapper = fromRequest.GetWrapper(ref); if (wrapper != nullptr) { // Native function request << *wrapper; fromRequest.Dereference(ref); } else { // managed by remote routine TShared<CrossRoutine> remoteRoutine = TShared<CrossRoutine>::From(new CrossRoutine(fromRequest.GetRequestPool(), ref)); if (flag & CrossScript::CROSSSCRIPT_TRANSPARENT) { // create wrapper RoutineWrapper routineWrapper(std::move(remoteRoutine)); request << request.Adapt(WrapClosure(std::move(routineWrapper), &RoutineWrapper::operator ())); } else { request << remoteRoutine; } } break; } case IScript::Request::OBJECT: { IScript::BaseDelegate d; fromRequest >> d; IScript::Object* object = d.Get(); if (flag & CrossScript::CROSSSCRIPT_TRANSPARENT) { CrossRoutine* routine = object->QueryInterface(UniqueType<CrossRoutine>()); if (routine != nullptr) { if (&routine->pool->GetScript() == request.GetScript()) { request << routine->ref; } else { TShared<CrossRoutine> r(routine); RoutineWrapper routineWrapper(std::move(r)); request << request.Adapt(WrapClosure(std::move(routineWrapper), &RoutineWrapper::operator ())); } } else { request << object; } } else { request << object; } break; } case IScript::Request::ANY: { // omitted. break; } } } static void CopyArray(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest) { IScript::Request::ArrayStart ts; ts.count = 0; fromRequest >> ts; request << beginarray; for (size_t j = 0; j < ts.count; j++) { CopyVariable(flag, request, fromRequest, fromRequest.GetCurrentType()); } IScript::Request::Iterator it; while (true) { fromRequest >> it; if (!it) break; request << key; CopyVariable(flag, request, fromRequest, it.keyType); CopyVariable(flag, request, fromRequest, it.valueType); } request << endarray; fromRequest << endarray; } static void CopyTable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest) { IScript::Request::TableStart ts; ts.count = 0; fromRequest >> ts; request << begintable; for (size_t j = 0; j < ts.count; j++) { CopyVariable(flag, request, fromRequest, fromRequest.GetCurrentType()); } IScript::Request::Iterator it; while (true) { fromRequest >> it; if (!it) break; request << key; CopyVariable(flag, request, fromRequest, it.keyType); CopyVariable(flag, request, fromRequest, it.valueType); } request << endtable; fromRequest << endtable; } void CrossScript::Call(IScript::Request& fromRequest, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { // self call fromRequest.DoLock(); bool selfCall = fromRequest.GetRequestPool() == remoteRoutine->pool; fromRequest.UnLock(); if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); toRequest.DoLock(); if (!selfCall) fromRequest.DoLock(); toRequest.Push(); uint32_t flag = Flag().load(std::memory_order_relaxed); // read remaining parameters for (size_t i = 0; i < args.count; i++) { CopyVariable(flag, toRequest, fromRequest, fromRequest.GetCurrentType()); } if (!selfCall) fromRequest.UnLock(); toRequest.Call(remoteRoutine->ref); if (!selfCall) fromRequest.DoLock(); for (int k = 0; k < toRequest.GetCount(); k++) { CopyVariable(flag, fromRequest, toRequest, toRequest.GetCurrentType()); } toRequest.Pop(); if (!selfCall) fromRequest.UnLock(); toRequest.UnLock(); requestPool.ReleaseSafe(&toRequest); } else { fromRequest.Error("Invalid ref."); } } void CrossScript::ExecuteCall(IScript::RequestPool* returnPool, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine) { OPTICK_EVENT(); toRequest.DoLock(); toRequest.Call(remoteRoutine->ref); IScript::RequestPool* pool = toRequest.GetRequestPool(); toRequest.UnLock(); Dispatch(pool, returnPool, CreateTaskContextFree(Wrap(this, &CrossScript::CompleteCall), returnPool, std::ref(toRequest), callback, remoteRoutine)); } void CrossScript::CompleteCall(IScript::RequestPool* returnPool, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine) { OPTICK_EVENT(); IScript::Request& returnRequest = *returnPool->requestPool.AcquireSafe(); returnRequest.DoLock(); returnRequest.Push(); uint32_t flag = Flag().load(std::memory_order_relaxed); toRequest.DoLock(); for (int i = 0; i < toRequest.GetCount(); i++) { CopyVariable(flag, returnRequest, toRequest, toRequest.GetCurrentType()); } toRequest.Pop(); toRequest.UnLock(); returnRequest.Call(callback); returnRequest.Dereference(callback); returnRequest.Pop(); returnRequest.UnLock(); requestPool.ReleaseSafe(&toRequest); returnPool->requestPool.ReleaseSafe(&returnRequest); } void CrossScript::PrepareCall(IScript::Request& fromRequest, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { toRequest.Push(); // read remaining parameters uint32_t flag = Flag().load(std::memory_order_relaxed); for (size_t i = 0; i < args.count; i++) { CopyVariable(flag, toRequest, fromRequest, fromRequest.GetCurrentType()); } IScript::RequestPool* targetPool = toRequest.GetRequestPool(); toRequest.UnLock(); IScript::RequestPool* pool = fromRequest.GetRequestPool(); assert(&pool->GetScript() == fromRequest.GetScript()); fromRequest.UnLock(); Dispatch(pool, targetPool, CreateTaskContextFree(Wrap(this, &CrossScript::ExecuteCall), pool, std::ref(toRequest), callback, remoteRoutine)); } bool CrossScript::IsLocked() const { return script.IsLocked(); } void CrossScript::Dispatch(IScript::RequestPool* fromPool, IScript::RequestPool* toPool, ITask* task) { if (&toPool->GetScript() == &script) { threadPool.Dispatch(task); } else { task->Execute(nullptr); } } bool CrossScript::TryCallAsync(IScript::Request& fromRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); fromRequest.DoLock(); if (toRequest.TryLock()) { PrepareCall(fromRequest, toRequest, callback, remoteRoutine, args); return true; } else { fromRequest.UnLock(); return false; } } else { fromRequest.Error("Invalid ref."); return false; } } void CrossScript::CallAsync(IScript::Request& fromRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); fromRequest.DoLock(); toRequest.DoLock(); PrepareCall(fromRequest, toRequest, callback, remoteRoutine, args); } else { fromRequest.Error("Invalid ref."); } }
#include "CrossScript.h" #include "../Driver/Profiler/Optick/optick.h" #include <utility> using namespace PaintsNow; CrossRoutine::CrossRoutine(IScript::RequestPool* p, IScript::Request::Ref r) : pool(p), ref(r) {} CrossRoutine::~CrossRoutine() { Clear(); } void CrossRoutine::Clear() { if (ref) { IScript::Request& req = pool->GetScript().GetDefaultRequest(); req.DoLock(); req.Dereference(ref); ref.value = 0; req.UnLock(); } } void CrossRoutine::ScriptUninitialize(IScript::Request& request) { request.UnLock(); SharedTiny::ScriptUninitialize(request); request.DoLock(); } static void SysCall(IScript::Request& request, IScript::Delegate<CrossRoutine> routine, IScript::Request::Arguments& args) { CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->Call(request, routine.Get(), args); } static void SysCallAsync(IScript::Request& request, IScript::Request::Ref callback, IScript::Delegate<CrossRoutine> routine, IScript::Request::Arguments& args) { CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->CallAsync(request, callback, routine.Get(), args); } CrossScript::CrossScript(ThreadPool& e, IScript& script) : RequestPool(script, e.GetThreadCount()), threadPool(e) { script.DoLock(); IScript::Request& request = script.GetDefaultRequest(); request << global << key("SysCall") << request.Adapt(Wrap(SysCall)); request << global << key("SysCallAsync") << request.Adapt(Wrap(SysCallAsync)); script.SetErrorHandler(Wrap(this, &CrossScript::ErrorHandler)); script.UnLock(); } void CrossScript::ErrorHandler(IScript::Request& request, const String& err) { fprintf(stderr, "[CrossScript] subscript error: %s\n", err.c_str()); } CrossScript::~CrossScript() { requestPool.Clear(); script.ReleaseDevice(); } void CrossScript::ScriptUninitialize(IScript::Request& request) { // in case of recursive locking request.UnLock(); BaseClass::ScriptUninitialize(request); request.DoLock(); } TObject<IReflect>& CrossScript::operator () (IReflect& reflect) { BaseClass::operator () (reflect); if (reflect.IsReflectMethod()) {} return *this; } class RoutineWrapper { public: RoutineWrapper(rvalue<TShared<CrossRoutine> > r) : routine(std::move(r)) {} ~RoutineWrapper() {} void operator () (IScript::Request& request, IScript::Request::Arguments& args) { // always use sync call CrossScript* crossComponent = static_cast<CrossScript*>(routine->pool); assert(crossComponent != nullptr); crossComponent->Call(request, routine(), args); } TShared<CrossRoutine> routine; }; TShared<CrossRoutine> CrossScript::Get(const String& name) { IScript::Request& request = script.GetDefaultRequest(); request.DoLock(); IScript::Request::Ref ref; request << global; request << key(name) >> ref; request << endtable; request.UnLock(); if (ref.value != 0) { return TShared<CrossRoutine>::From(new CrossRoutine(this, ref)); } else { return nullptr; } } TShared<CrossRoutine> CrossScript::Load(const String& code) { IScript::Request& request = script.GetDefaultRequest(); request.DoLock(); IScript::Request::Ref ref = request.Load(code, "CrossScript"); request.UnLock(); if (ref.value != 0) { return TShared<CrossRoutine>::From(new CrossRoutine(this, ref)); } else { return nullptr; } } static void CopyTable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest); static void CopyArray(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest); static void CopyVariable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest, IScript::Request::TYPE type) { switch (type) { case IScript::Request::NIL: request << nil; break; case IScript::Request::BOOLEAN: { bool value; fromRequest >> value; request << value; break; } case IScript::Request::NUMBER: { double value; fromRequest >> value; request << value; break; } case IScript::Request::INTEGER: { int64_t value; fromRequest >> value; request << value; break; } case IScript::Request::STRING: { String value; fromRequest >> value; request << value; break; } case IScript::Request::TABLE: { CopyTable(flag, request, fromRequest); break; } case IScript::Request::ARRAY: { CopyArray(flag, request, fromRequest); break; } case IScript::Request::FUNCTION: { // convert to reference IScript::Request::Ref ref; fromRequest >> ref; IScript::Request::AutoWrapperBase* wrapper = fromRequest.GetWrapper(ref); if (wrapper != nullptr) { // Native function request << *wrapper; fromRequest.Dereference(ref); } else { // managed by remote routine TShared<CrossRoutine> remoteRoutine = TShared<CrossRoutine>::From(new CrossRoutine(fromRequest.GetRequestPool(), ref)); if (flag & CrossScript::CROSSSCRIPT_TRANSPARENT) { // create wrapper RoutineWrapper routineWrapper(std::move(remoteRoutine)); request << request.Adapt(WrapClosure(std::move(routineWrapper), &RoutineWrapper::operator ())); } else { request << remoteRoutine; } } break; } case IScript::Request::OBJECT: { IScript::BaseDelegate d; fromRequest >> d; IScript::Object* object = d.Get(); if (flag & CrossScript::CROSSSCRIPT_TRANSPARENT) { CrossRoutine* routine = object->QueryInterface(UniqueType<CrossRoutine>()); if (routine != nullptr) { if (&routine->pool->GetScript() == request.GetScript()) { request << routine->ref; } else { TShared<CrossRoutine> r(routine); RoutineWrapper routineWrapper(std::move(r)); request << request.Adapt(WrapClosure(std::move(routineWrapper), &RoutineWrapper::operator ())); } } else { request << object; } } else { request << object; } break; } case IScript::Request::ANY: { // omitted. break; } } } static void CopyArray(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest) { IScript::Request::ArrayStart ts; ts.count = 0; fromRequest >> ts; request << beginarray; for (size_t j = 0; j < ts.count; j++) { CopyVariable(flag, request, fromRequest, fromRequest.GetCurrentType()); } IScript::Request::Iterator it; while (true) { fromRequest >> it; if (!it) break; request << key; CopyVariable(flag, request, fromRequest, it.keyType); CopyVariable(flag, request, fromRequest, it.valueType); } request << endarray; fromRequest << endarray; } static void CopyTable(uint32_t flag, IScript::Request& request, IScript::Request& fromRequest) { IScript::Request::TableStart ts; ts.count = 0; fromRequest >> ts; request << begintable; for (size_t j = 0; j < ts.count; j++) { CopyVariable(flag, request, fromRequest, fromRequest.GetCurrentType()); } IScript::Request::Iterator it; while (true) { fromRequest >> it; if (!it) break; request << key; CopyVariable(flag, request, fromRequest, it.keyType); CopyVariable(flag, request, fromRequest, it.valueType); } request << endtable; fromRequest << endtable; } void CrossScript::Call(IScript::Request& fromRequest, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { // self call fromRequest.DoLock(); bool selfCall = fromRequest.GetRequestPool() == remoteRoutine->pool; fromRequest.UnLock(); if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); toRequest.DoLock(); if (!selfCall) fromRequest.DoLock(); toRequest.Push(); uint32_t flag = Flag().load(std::memory_order_relaxed); // read remaining parameters for (size_t i = 0; i < args.count; i++) { CopyVariable(flag, toRequest, fromRequest, fromRequest.GetCurrentType()); } if (!selfCall) fromRequest.UnLock(); toRequest.Call(remoteRoutine->ref); if (!selfCall) fromRequest.DoLock(); for (int k = 0; k < toRequest.GetCount(); k++) { CopyVariable(flag, fromRequest, toRequest, toRequest.GetCurrentType()); } toRequest.Pop(); if (!selfCall) fromRequest.UnLock(); toRequest.UnLock(); requestPool.ReleaseSafe(&toRequest); } else { fromRequest.Error("Invalid ref."); } } void CrossScript::ExecuteCall(IScript::RequestPool* returnPool, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine) { OPTICK_EVENT(); toRequest.DoLock(); toRequest.Call(remoteRoutine->ref); IScript::RequestPool* pool = toRequest.GetRequestPool(); toRequest.UnLock(); Dispatch(pool, returnPool, CreateTaskContextFree(Wrap(this, &CrossScript::CompleteCall), returnPool, std::ref(toRequest), callback, remoteRoutine)); } void CrossScript::CompleteCall(IScript::RequestPool* returnPool, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine) { OPTICK_EVENT(); IScript::Request& returnRequest = *returnPool->requestPool.AcquireSafe(); returnRequest.DoLock(); returnRequest.Push(); uint32_t flag = Flag().load(std::memory_order_relaxed); toRequest.DoLock(); for (int i = 0; i < toRequest.GetCount(); i++) { CopyVariable(flag, returnRequest, toRequest, toRequest.GetCurrentType()); } toRequest.Pop(); toRequest.UnLock(); returnRequest.Call(callback); returnRequest.Dereference(callback); returnRequest.Pop(); returnRequest.UnLock(); requestPool.ReleaseSafe(&toRequest); returnPool->requestPool.ReleaseSafe(&returnRequest); } void CrossScript::PrepareCall(IScript::Request& fromRequest, IScript::Request& toRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { toRequest.Push(); // read remaining parameters uint32_t flag = Flag().load(std::memory_order_relaxed); for (size_t i = 0; i < args.count; i++) { CopyVariable(flag, toRequest, fromRequest, fromRequest.GetCurrentType()); } IScript::RequestPool* targetPool = toRequest.GetRequestPool(); toRequest.UnLock(); IScript::RequestPool* pool = fromRequest.GetRequestPool(); assert(&pool->GetScript() == fromRequest.GetScript()); fromRequest.UnLock(); Dispatch(pool, targetPool, CreateTaskContextFree(Wrap(this, &CrossScript::ExecuteCall), pool, std::ref(toRequest), callback, remoteRoutine)); } bool CrossScript::IsLocked() const { return script.IsLocked(); } void CrossScript::Dispatch(IScript::RequestPool* fromPool, IScript::RequestPool* toPool, ITask* task) { if (&toPool->GetScript() == &script) { threadPool.Dispatch(task); } else { task->Execute(nullptr); } } bool CrossScript::TryCallAsync(IScript::Request& fromRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); fromRequest.DoLock(); if (toRequest.TryLock()) { PrepareCall(fromRequest, toRequest, callback, remoteRoutine, args); return true; } else { fromRequest.UnLock(); requestPool.ReleaseSafe(&toRequest); return false; } } else { fromRequest.Error("Invalid ref."); return false; } } void CrossScript::CallAsync(IScript::Request& fromRequest, IScript::Request::Ref callback, const TShared<CrossRoutine>& remoteRoutine, IScript::Request::Arguments& args) { if (remoteRoutine->pool == this && remoteRoutine->ref) { IScript::Request& toRequest = *requestPool.AcquireSafe(); fromRequest.DoLock(); toRequest.DoLock(); PrepareCall(fromRequest, toRequest, callback, remoteRoutine, args); } else { fromRequest.Error("Invalid ref."); } }
Fix request leak on CrossScript.
Fix request leak on CrossScript.
C++
mit
paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow,paintdream/PaintsNow
869c785c7128b55450a26694eb63f3c254ae9b1d
xplat/Sonar/SonarWebSocketImpl.cpp
xplat/Sonar/SonarWebSocketImpl.cpp
/* * Copyright (c) 2018-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "SonarWebSocketImpl.h" #include "SonarStep.h" #include "ConnectionContextStore.h" #include "Log.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <thread> #include <folly/io/async/AsyncSocketException.h> #include <stdexcept> #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting sonar initialization because it's not running in the sonar thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; namespace facebook { namespace sonar { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: SonarWebSocketImpl* websocket_; public: ConnectionEvents(SonarWebSocketImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: SonarWebSocketImpl* websocket_; public: Responder(SonarWebSocketImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; SonarWebSocketImpl::SonarWebSocketImpl(SonarInitConfig config, std::shared_ptr<SonarState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), sonarState_(state), sonarEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } SonarWebSocketImpl::~SonarWebSocketImpl() { stop(); } void SonarWebSocketImpl::start() { auto step = sonarState_->start("Start connection thread"); folly::makeFuture() .via(sonarEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&){ step->complete(); startSync(); }); } void SonarWebSocketImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } auto connect = sonarState_->start("Connect to desktop"); try { if (isCertificateExchangeNeeded()) { doCertificateExchange(); return; } connectSecurely(); connect->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. connect->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; connect->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); connect->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void SonarWebSocketImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = sonarState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromSonar(); } void SonarWebSocketImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = sonarState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = sonarState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void SonarWebSocketImpl::reconnect() { folly::makeFuture() .via(sonarEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&){ startSync(); }); } void SonarWebSocketImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool SonarWebSocketImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void SonarWebSocketImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void SonarWebSocketImpl::sendMessage(const folly::dynamic& message) { sonarEventBase_->add([this, message]() { if (client_) { client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([]() {}); } }); } bool SonarWebSocketImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = sonarState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void SonarWebSocketImpl::requestSignedCertFromSonar() { auto generatingCSR = sonarState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")( "csr", csr.c_str())("destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = sonarState_->start("Getting cert from desktop"); sonarEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe([this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from sonar desktop:\n" + errorMessage); } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()).c_str()); } ); }); }); failedConnectionAttempts_ = 0; } void SonarWebSocketImpl::sendLegacyCertificateRequest(folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = sonarState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); client_ = nullptr; }); } bool SonarWebSocketImpl::isRunningInOwnThread() { return sonarEventBase_->isInEventBaseThread(); } } // namespace sonar } // namespace facebook
/* * Copyright (c) 2018-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. * */ #include "SonarWebSocketImpl.h" #include "SonarStep.h" #include "ConnectionContextStore.h" #include "Log.h" #include <folly/String.h> #include <folly/futures/Future.h> #include <folly/io/async/SSLContext.h> #include <folly/json.h> #include <rsocket/Payload.h> #include <rsocket/RSocket.h> #include <rsocket/transports/tcp/TcpConnectionFactory.h> #include <thread> #include <folly/io/async/AsyncSocketException.h> #include <stdexcept> #define WRONG_THREAD_EXIT_MSG \ "ERROR: Aborting sonar initialization because it's not running in the sonar thread." static constexpr int reconnectIntervalSeconds = 2; static constexpr int connectionKeepaliveSeconds = 10; static constexpr int securePort = 8088; static constexpr int insecurePort = 8089; namespace facebook { namespace sonar { class ConnectionEvents : public rsocket::RSocketConnectionEvents { private: SonarWebSocketImpl* websocket_; public: ConnectionEvents(SonarWebSocketImpl* websocket) : websocket_(websocket) {} void onConnected() { websocket_->isOpen_ = true; if (websocket_->connectionIsTrusted_) { websocket_->callbacks_->onConnected(); } } void onDisconnected(const folly::exception_wrapper&) { if (!websocket_->isOpen_) return; websocket_->isOpen_ = false; if (websocket_->connectionIsTrusted_) { websocket_->connectionIsTrusted_ = false; websocket_->callbacks_->onDisconnected(); } websocket_->reconnect(); } void onClosed(const folly::exception_wrapper& e) { onDisconnected(e); } }; class Responder : public rsocket::RSocketResponder { private: SonarWebSocketImpl* websocket_; public: Responder(SonarWebSocketImpl* websocket) : websocket_(websocket) {} void handleFireAndForget( rsocket::Payload request, rsocket::StreamId streamId) { const auto payload = request.moveDataToString(); websocket_->callbacks_->onMessageReceived(folly::parseJson(payload)); } }; SonarWebSocketImpl::SonarWebSocketImpl(SonarInitConfig config, std::shared_ptr<SonarState> state, std::shared_ptr<ConnectionContextStore> contextStore) : deviceData_(config.deviceData), sonarState_(state), sonarEventBase_(config.callbackWorker), connectionEventBase_(config.connectionWorker), contextStore_(contextStore) { CHECK_THROW(config.callbackWorker, std::invalid_argument); CHECK_THROW(config.connectionWorker, std::invalid_argument); } SonarWebSocketImpl::~SonarWebSocketImpl() { stop(); } void SonarWebSocketImpl::start() { auto step = sonarState_->start("Start connection thread"); folly::makeFuture() .via(sonarEventBase_->getEventBase()) .delayed(std::chrono::milliseconds(0)) .thenValue([this, step](auto&&){ step->complete(); startSync(); }); } void SonarWebSocketImpl::startSync() { if (!isRunningInOwnThread()) { log(WRONG_THREAD_EXIT_MSG); return; } if (isOpen()) { log("Already connected"); return; } auto connect = sonarState_->start("Connect to desktop"); try { if (isCertificateExchangeNeeded()) { doCertificateExchange(); return; } connectSecurely(); connect->complete(); } catch (const folly::AsyncSocketException& e) { if (e.getType() == folly::AsyncSocketException::NOT_OPEN) { // The expected code path when flipper desktop is not running. // Don't count as a failed attempt. connect->fail("Port not open"); } else { log(e.what()); failedConnectionAttempts_++; connect->fail(e.what()); } reconnect(); } catch (const std::exception& e) { log(e.what()); connect->fail(e.what()); failedConnectionAttempts_++; reconnect(); } } void SonarWebSocketImpl::doCertificateExchange() { rsocket::SetupParameters parameters; folly::SocketAddress address; parameters.payload = rsocket::Payload( folly::toJson(folly::dynamic::object("os", deviceData_.os)( "device", deviceData_.device)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, insecurePort); auto connectingInsecurely = sonarState_->start("Connect insecurely"); connectionIsTrusted_ = false; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address)), std::move(parameters), nullptr, std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingInsecurely->complete(); requestSignedCertFromSonar(); } void SonarWebSocketImpl::connectSecurely() { rsocket::SetupParameters parameters; folly::SocketAddress address; auto loadingDeviceId = sonarState_->start("Load Device Id"); auto deviceId = contextStore_->getDeviceId(); if (deviceId.compare("unknown")) { loadingDeviceId->complete(); } parameters.payload = rsocket::Payload(folly::toJson(folly::dynamic::object( "os", deviceData_.os)("device", deviceData_.device)( "device_id", deviceId)("app", deviceData_.app))); address.setFromHostPort(deviceData_.host, securePort); std::shared_ptr<folly::SSLContext> sslContext = contextStore_->getSSLContext(); auto connectingSecurely = sonarState_->start("Connect securely"); connectionIsTrusted_ = true; client_ = rsocket::RSocket::createConnectedClient( std::make_unique<rsocket::TcpConnectionFactory>( *connectionEventBase_->getEventBase(), std::move(address), std::move(sslContext)), std::move(parameters), std::make_shared<Responder>(this), std::chrono::seconds(connectionKeepaliveSeconds), // keepaliveInterval nullptr, // stats std::make_shared<ConnectionEvents>(this)) .get(); connectingSecurely->complete(); failedConnectionAttempts_ = 0; } void SonarWebSocketImpl::reconnect() { folly::makeFuture() .via(sonarEventBase_->getEventBase()) .delayed(std::chrono::seconds(reconnectIntervalSeconds)) .thenValue([this](auto&&){ startSync(); }); } void SonarWebSocketImpl::stop() { if (client_) { client_->disconnect(); } client_ = nullptr; } bool SonarWebSocketImpl::isOpen() const { return isOpen_ && connectionIsTrusted_; } void SonarWebSocketImpl::setCallbacks(Callbacks* callbacks) { callbacks_ = callbacks; } void SonarWebSocketImpl::sendMessage(const folly::dynamic& message) { sonarEventBase_->add([this, message]() { if (client_) { client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([]() {}); } }); } bool SonarWebSocketImpl::isCertificateExchangeNeeded() { if (failedConnectionAttempts_ >= 2) { return true; } auto step = sonarState_->start("Check required certificates are present"); bool hasRequiredFiles = contextStore_->hasRequiredFiles(); if (hasRequiredFiles) { step->complete(); } return !hasRequiredFiles; } void SonarWebSocketImpl::requestSignedCertFromSonar() { auto generatingCSR = sonarState_->start("Generate CSR"); std::string csr = contextStore_->createCertificateSigningRequest(); generatingCSR->complete(); folly::dynamic message = folly::dynamic::object("method", "signCertificate")( "csr", csr.c_str())("destination", contextStore_->getCertificateDirectoryPath().c_str()); auto gettingCert = sonarState_->start("Getting cert from desktop"); sonarEventBase_->add([this, message, gettingCert]() { client_->getRequester() ->requestResponse(rsocket::Payload(folly::toJson(message))) ->subscribe([this, gettingCert](rsocket::Payload p) { auto response = p.moveDataToString(); if (!response.empty()) { folly::dynamic config = folly::parseJson(response); contextStore_->storeConnectionConfig(config); } gettingCert->complete(); log("Certificate exchange complete."); // Disconnect after message sending is complete. // This will trigger a reconnect which should use the secure channel. // TODO: Connect immediately, without waiting for reconnect client_ = nullptr; }, [this, message](folly::exception_wrapper e) { e.handle( [&](rsocket::ErrorWithPayload& errorWithPayload) { std::string errorMessage = errorWithPayload.payload.moveDataToString(); if (errorMessage.compare("not implemented")) { log("Desktop failed to provide certificates. Error from sonar desktop:\n" + errorMessage); } else { sendLegacyCertificateRequest(message); } }, [e](...) { log(("Error during certificate exchange:" + e.what()).c_str()); } ); }); }); failedConnectionAttempts_ = 0; } void SonarWebSocketImpl::sendLegacyCertificateRequest(folly::dynamic message) { // Desktop is using an old version of Flipper. // Fall back to fireAndForget, instead of requestResponse. auto sendingRequest = sonarState_->start("Sending fallback certificate request"); client_->getRequester() ->fireAndForget(rsocket::Payload(folly::toJson(message))) ->subscribe([this, sendingRequest]() { sendingRequest->complete(); folly::dynamic config = folly::dynamic::object(); contextStore_->storeConnectionConfig(config); client_ = nullptr; }); } bool SonarWebSocketImpl::isRunningInOwnThread() { return sonarEventBase_->isInEventBaseThread(); } } // namespace sonar } // namespace facebook
Store empty connection_config in legacy CSR requests
Store empty connection_config in legacy CSR requests Summary: Versions of flipper from before 7th August 2018 don't return any response, so we don't store any connection_config.json file. To keep the functionality the same as with up-to-date app versions, when this happens, store an empty config file ("{}"). Reviewed By: danielbuechele Differential Revision: D9682885 fbshipit-source-id: fd580f6bba6b6b20135aa2c076be10e1eea0f8bc
C++
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
7fd83937a27ac717321ecea02522072e91e55a9d
src/accessible/accessibleobject.cpp
src/accessible/accessibleobject.cpp
/* Copyright 2012 Frederik Gladhorn <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "accessibleobject.h" #include <qstring.h> #include <qdebug.h> #include "accessibleobject_p.h" #include "atspi/atspidbus.h" using namespace KAccessibleClient; AccessibleObject::AccessibleObject(AtSpiDBus *bus, const QString &service, const QString &path) :d(new AccessibleObjectPrivate(bus, service, path)) { } AccessibleObject::AccessibleObject(const AccessibleObject &other) { d = new AccessibleObjectPrivate(other.d->bus, other.d->service, other.d->path); } AccessibleObject::~AccessibleObject() { } bool AccessibleObject::isValid() const { return d->bus && (!d->service.isEmpty()) && (!d->path.isEmpty()) && (d->path != QLatin1String("/org/a11y/atspi/null")); } AccessibleObject &AccessibleObject::operator=(const AccessibleObject &other) { d = other.d; return *this; } bool AccessibleObject::operator==(const AccessibleObject &other) const { return (d == other.d) || *d == *other.d; } AccessibleObject AccessibleObject::parent() const { return d->bus->parent(*this); } QList<AccessibleObject> AccessibleObject::children() const { return d->bus->children(*this); } int AccessibleObject::childCount() const { return d->bus->childCount(*this); } AccessibleObject AccessibleObject::child(int index) const { return d->bus->child(*this, index); } //int AccessibleObject::indexInParent() const //{ //} //int AccessibleObject::childCount() const //{ //} //AccessibleObject AccessibleObject::getChild(int index) const //{ //} QString AccessibleObject::name() const { return d->name(); } //QString AccessibleObject::localizedName() const //{ //} //QString AccessibleObject::description() const //{ //} //int AccessibleObject::role() const //{ //} //QString AccessibleObject::roleName() const //{ //} //QString AccessibleObject::localizedRoleName() const //{ //}
/* Copyright 2012 Frederik Gladhorn <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "accessibleobject.h" #include <qstring.h> #include <qdebug.h> #include "accessibleobject_p.h" #include "atspi/atspidbus.h" using namespace KAccessibleClient; AccessibleObject::AccessibleObject(AtSpiDBus *bus, const QString &service, const QString &path) :d(new AccessibleObjectPrivate(bus, service, path)) { } AccessibleObject::AccessibleObject(const AccessibleObject &other) :d(other.d) { } AccessibleObject::~AccessibleObject() { } bool AccessibleObject::isValid() const { return d->bus && (!d->service.isEmpty()) && (!d->path.isEmpty()) && (d->path != QLatin1String("/org/a11y/atspi/null")); } AccessibleObject &AccessibleObject::operator=(const AccessibleObject &other) { d = other.d; return *this; } bool AccessibleObject::operator==(const AccessibleObject &other) const { return (d == other.d) || *d == *other.d; } AccessibleObject AccessibleObject::parent() const { return d->bus->parent(*this); } QList<AccessibleObject> AccessibleObject::children() const { return d->bus->children(*this); } int AccessibleObject::childCount() const { return d->bus->childCount(*this); } AccessibleObject AccessibleObject::child(int index) const { return d->bus->child(*this, index); } //int AccessibleObject::indexInParent() const //{ //} //int AccessibleObject::childCount() const //{ //} //AccessibleObject AccessibleObject::getChild(int index) const //{ //} QString AccessibleObject::name() const { return d->name(); } //QString AccessibleObject::localizedName() const //{ //} //QString AccessibleObject::description() const //{ //} //int AccessibleObject::role() const //{ //} //QString AccessibleObject::roleName() const //{ //} //QString AccessibleObject::localizedRoleName() const //{ //}
Make use of shared data pointer.
Make use of shared data pointer.
C++
lgpl-2.1
KDE/libkdeaccessibilityclient,KDE/libkdeaccessibilityclient
9f43820076845c023813920cda41069e5549b842
vm/free_list_allocator.hpp
vm/free_list_allocator.hpp
namespace factor { struct allocator_room { cell size; cell occupied_space; cell total_free; cell contiguous_free; cell free_block_count; }; template <typename Block> struct free_list_allocator { cell size; cell start; cell end; free_list free_blocks; mark_bits state; free_list_allocator(cell size, cell start); void initial_free_list(cell occupied); bool contains_p(Block* block); bool can_allot_p(cell size); Block* allot(cell size); void free(Block* block); cell occupied_space(); cell free_space(); cell largest_free_block(); cell free_block_count(); void sweep(); template <typename Iterator> void sweep(Iterator& iter); template <typename Iterator, typename Fixup> void compact(Iterator& iter, Fixup fixup, const Block** finger); template <typename Iterator, typename Fixup> void iterate(Iterator& iter, Fixup fixup); template <typename Iterator> void iterate(Iterator& iter); allocator_room as_allocator_room(); }; template <typename Block> free_list_allocator<Block>::free_list_allocator(cell size, cell start) : size(size), start(start), end(start + size), state(mark_bits(size, start)) { initial_free_list(0); } template <typename Block> void free_list_allocator<Block>::initial_free_list(cell occupied) { free_blocks.initial_free_list(start, end, occupied); } template <typename Block> bool free_list_allocator<Block>::contains_p(Block* block) { return ((cell)block - start) < size; } template <typename Block> bool free_list_allocator<Block>::can_allot_p(cell size) { return free_blocks.can_allot_p(size); } template <typename Block> Block* free_list_allocator<Block>::allot(cell size) { size = align(size, data_alignment); free_heap_block* block = free_blocks.find_free_block(size); if (block) { block = free_blocks.split_free_block(block, size); return (Block*)block; } else return NULL; } template <typename Block> void free_list_allocator<Block>::free(Block* block) { free_heap_block* free_block = (free_heap_block*)block; free_block->make_free(block->size()); free_blocks.add_to_free_list(free_block); } template <typename Block> cell free_list_allocator<Block>::free_space() { return free_blocks.free_space; } template <typename Block> cell free_list_allocator<Block>::occupied_space() { return size - free_blocks.free_space; } template <typename Block> cell free_list_allocator<Block>::largest_free_block() { return free_blocks.largest_free_block(); } template <typename Block> cell free_list_allocator<Block>::free_block_count() { return free_blocks.free_block_count; } template <typename Block> template <typename Iterator> void free_list_allocator<Block>::sweep(Iterator& iter) { free_blocks.clear_free_list(); cell start = this->start; cell end = this->end; while (start != end) { /* find next unmarked block */ start = state.next_unmarked_block_after(start); if (start != end) { /* find size */ cell size = state.unmarked_block_size(start); FACTOR_ASSERT(size > 0); free_heap_block* free_block = (free_heap_block*)start; free_block->make_free(size); free_blocks.add_to_free_list(free_block); iter((Block*)start, size); start = start + size; } } } template <typename Block> void free_list_allocator<Block>::sweep() { auto null_sweep = [](Block* free_block, cell size) { }; sweep(null_sweep); } /* The forwarding map must be computed first by calling state.compute_forwarding(). */ template <typename Block> template <typename Iterator, typename Fixup> void free_list_allocator<Block>::compact(Iterator& iter, Fixup fixup, const Block** finger) { cell dest_addr = start; auto compact_block_func = [&](Block* block, cell size) { cell block_addr = (cell)block; if (!this->state.marked_p(block_addr)) return; *finger = (Block*)(block_addr + size); memmove((Block*)dest_addr, block, size); iter(block, (Block*)dest_addr, size); dest_addr += size; }; iterate(compact_block_func, fixup); /* Now update the free list; there will be a single free block at the end */ free_blocks.initial_free_list(start, end, dest_addr - start); } /* During compaction we have to be careful and measure object sizes differently */ template <typename Block> template <typename Iterator, typename Fixup> void free_list_allocator<Block>::iterate(Iterator& iter, Fixup fixup) { cell scan = this->start; while (scan != this->end) { Block* block = (Block*)scan; cell size = fixup.size(block); if (!block->free_p()) iter(block, size); scan += size; } } template <typename Block> template <typename Iterator> void free_list_allocator<Block>::iterate(Iterator& iter) { iterate(iter, no_fixup()); } template <typename Block> allocator_room free_list_allocator<Block>::as_allocator_room() { allocator_room room; room.size = size; room.occupied_space = occupied_space(); room.total_free = free_space(); room.contiguous_free = largest_free_block(); room.free_block_count = free_block_count(); return room; } }
namespace factor { struct allocator_room { cell size; cell occupied_space; cell total_free; cell contiguous_free; cell free_block_count; }; template <typename Block> struct free_list_allocator { cell size; cell start; cell end; free_list free_blocks; mark_bits state; free_list_allocator(cell size, cell start); void initial_free_list(cell occupied); bool contains_p(Block* block); bool can_allot_p(cell size); Block* allot(cell size); void free(Block* block); cell occupied_space(); cell free_space(); cell largest_free_block(); cell free_block_count(); void sweep(); template <typename Iterator> void sweep(Iterator& iter); template <typename Iterator, typename Fixup> void compact(Iterator& iter, Fixup fixup, const Block** finger); template <typename Iterator, typename Fixup> void iterate(Iterator& iter, Fixup fixup); template <typename Iterator> void iterate(Iterator& iter); allocator_room as_allocator_room(); }; template <typename Block> free_list_allocator<Block>::free_list_allocator(cell size, cell start) : size(size), start(start), end(start + size), state(mark_bits(size, start)) { initial_free_list(0); } template <typename Block> void free_list_allocator<Block>::initial_free_list(cell occupied) { free_blocks.initial_free_list(start, end, occupied); } template <typename Block> bool free_list_allocator<Block>::contains_p(Block* block) { return ((cell)block - start) < size; } template <typename Block> bool free_list_allocator<Block>::can_allot_p(cell size) { return free_blocks.can_allot_p(size); } template <typename Block> Block* free_list_allocator<Block>::allot(cell size) { size = align(size, data_alignment); free_heap_block* block = free_blocks.find_free_block(size); if (block) { block = free_blocks.split_free_block(block, size); return (Block*)block; } else return NULL; } template <typename Block> void free_list_allocator<Block>::free(Block* block) { free_heap_block* free_block = (free_heap_block*)block; free_block->make_free(block->size()); free_blocks.add_to_free_list(free_block); } template <typename Block> cell free_list_allocator<Block>::free_space() { return free_blocks.free_space; } template <typename Block> cell free_list_allocator<Block>::occupied_space() { return size - free_blocks.free_space; } template <typename Block> cell free_list_allocator<Block>::largest_free_block() { return free_blocks.largest_free_block(); } template <typename Block> cell free_list_allocator<Block>::free_block_count() { return free_blocks.free_block_count; } template <typename Block> template <typename Iterator> void free_list_allocator<Block>::sweep(Iterator& iter) { free_blocks.clear_free_list(); cell start = this->start; cell end = this->end; while (start != end) { /* find next unmarked block */ start = state.next_unmarked_block_after(start); if (start != end) { /* find size */ cell size = state.unmarked_block_size(start); FACTOR_ASSERT(size > 0); free_heap_block* free_block = (free_heap_block*)start; free_block->make_free(size); free_blocks.add_to_free_list(free_block); iter((Block*)start, size); start = start + size; } } } template <typename Block> void free_list_allocator<Block>::sweep() { auto null_sweep = [](Block* free_block, cell size) { }; sweep(null_sweep); } /* The forwarding map must be computed first by calling state.compute_forwarding(). */ template <typename Block> template <typename Iterator, typename Fixup> void free_list_allocator<Block>::compact(Iterator& iter, Fixup fixup, const Block** finger) { cell dest_addr = start; auto compact_block_func = [&](Block* block, cell size) { cell block_addr = (cell)block; if (!state.marked_p(block_addr)) return; *finger = (Block*)(block_addr + size); memmove((Block*)dest_addr, block, size); iter(block, (Block*)dest_addr, size); dest_addr += size; }; iterate(compact_block_func, fixup); /* Now update the free list; there will be a single free block at the end */ free_blocks.initial_free_list(start, end, dest_addr - start); } /* During compaction we have to be careful and measure object sizes differently */ template <typename Block> template <typename Iterator, typename Fixup> void free_list_allocator<Block>::iterate(Iterator& iter, Fixup fixup) { cell scan = this->start; while (scan != this->end) { Block* block = (Block*)scan; cell size = fixup.size(block); if (!block->free_p()) iter(block, size); scan += size; } } template <typename Block> template <typename Iterator> void free_list_allocator<Block>::iterate(Iterator& iter) { iterate(iter, no_fixup()); } template <typename Block> allocator_room free_list_allocator<Block>::as_allocator_room() { allocator_room room; room.size = size; room.occupied_space = occupied_space(); room.total_free = free_space(); room.contiguous_free = largest_free_block(); room.free_block_count = free_block_count(); return room; } }
Revert "vm: don't use implicit this. thanks to Jon Harper for the report."
Revert "vm: don't use implicit this. thanks to Jon Harper for the report." My bad. A buggy compiler is a buggy compiler. Not a good workaround. This reverts commit 1602e5094c836e6081cc5f0139c0cab6b740debb.
C++
bsd-2-clause
factor/factor,tgunr/factor,bpollack/factor,mrjbq7/factor,nicolas-p/factor,mrjbq7/factor,bjourne/factor,slavapestov/factor,nicolas-p/factor,bpollack/factor,AlexIljin/factor,slavapestov/factor,factor/factor,slavapestov/factor,nicolas-p/factor,bpollack/factor,nicolas-p/factor,slavapestov/factor,bjourne/factor,factor/factor,nicolas-p/factor,tgunr/factor,tgunr/factor,factor/factor,mrjbq7/factor,bjourne/factor,bjourne/factor,AlexIljin/factor,mrjbq7/factor,factor/factor,factor/factor,slavapestov/factor,bjourne/factor,bjourne/factor,bpollack/factor,slavapestov/factor,mrjbq7/factor,bpollack/factor,tgunr/factor,AlexIljin/factor,tgunr/factor,nicolas-p/factor,AlexIljin/factor,AlexIljin/factor,mrjbq7/factor,bjourne/factor,AlexIljin/factor,bpollack/factor,tgunr/factor,AlexIljin/factor,slavapestov/factor,bpollack/factor,nicolas-p/factor
fefd2c2497086408d4a81d09594055a35ca81ac6
ArcGISRuntimeSDKQt_CppSamples/EditData/AddFeaturesFeatureService/AddFeaturesFeatureService.cpp
ArcGISRuntimeSDKQt_CppSamples/EditData/AddFeaturesFeatureService/AddFeaturesFeatureService.cpp
// [WriteFile Name=AddFeaturesFeatureService, Category=EditData] // [Legal] // Copyright 2016 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [Legal] #include "AddFeaturesFeatureService.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "Viewpoint.h" #include "Point.h" #include "SpatialReference.h" #include "ServiceFeatureTable.h" #include "FeatureLayer.h" #include "Feature.h" #include "FeatureEditResult.h" #include <QUrl> #include <QMap> #include <QUuid> #include <QSharedPointer> #include <QVariant> #include <QMouseEvent> using namespace Esri::ArcGISRuntime; AddFeaturesFeatureService::AddFeaturesFeatureService(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_featureLayer(nullptr), m_featureTable(nullptr) { } AddFeaturesFeatureService::~AddFeaturesFeatureService() { } void AddFeaturesFeatureService::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // create a Map by passing in the Basemap m_map = new Map(Basemap::streets(this), this); m_map->setInitialViewpoint(Viewpoint(Point(-10800000, 4500000, SpatialReference(102100)), 3e7)); // set map on the map view m_mapView->setMap(m_map); // create the ServiceFeatureTable m_featureTable = new ServiceFeatureTable(QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0"), this); // create the FeatureLayer with the ServiceFeatureTable and add it to the Map m_featureLayer = new FeatureLayer(m_featureTable, this); m_featureLayer->setSelectionWidth(3); m_map->operationalLayers()->append(m_featureLayer); connectSignals(); } void AddFeaturesFeatureService::connectSignals() { // connect to the mouse clicked signal on the MapQuickView connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // obtain the map point Point newPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y()); // create the feature attributes QMap<QString, QVariant> featureAttributes; featureAttributes.insert("typdamage", "Minor"); featureAttributes.insert("primcause", "Earthquake"); // create a new feature and add it to the feature table Feature* feature = m_featureTable->createFeature(featureAttributes,newPoint,this); m_featureTable->addFeature(feature); }); // connect to the addFeatureCompleted signal from the ServiceFeatureTable connect(m_featureTable, &ServiceFeatureTable::addFeatureCompleted, this, [this](QUuid, bool success) { // if add feature was successful, call apply edits if (success) m_featureTable->applyEdits(); }); // connect to the applyEditsCompleted signal from the ServiceFeatureTable connect(m_featureTable, &ServiceFeatureTable::applyEditsCompleted, this, [this](QUuid, QList<QSharedPointer<FeatureEditResult>> featureEditResults) { if (featureEditResults.isEmpty()) return; // obtain the first item in the list QSharedPointer<FeatureEditResult> featureEditResult = featureEditResults.first(); // check if there were errors, and if not, log the new object ID if (!featureEditResult->isCompletedWithErrors()) qDebug() << "New Object ID is:" << featureEditResult->objectId(); else qDebug() << "Apply edits error."; }); }
// [WriteFile Name=AddFeaturesFeatureService, Category=EditData] // [Legal] // Copyright 2016 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [Legal] #include "AddFeaturesFeatureService.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "Viewpoint.h" #include "Point.h" #include "SpatialReference.h" #include "ServiceFeatureTable.h" #include "FeatureLayer.h" #include "Feature.h" #include "FeatureEditResult.h" #include <QUrl> #include <QMap> #include <QUuid> #include <QSharedPointer> #include <QVariant> #include <QMouseEvent> using namespace Esri::ArcGISRuntime; AddFeaturesFeatureService::AddFeaturesFeatureService(QQuickItem* parent) : QQuickItem(parent), m_map(nullptr), m_mapView(nullptr), m_featureLayer(nullptr), m_featureTable(nullptr) { } AddFeaturesFeatureService::~AddFeaturesFeatureService() { } void AddFeaturesFeatureService::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // create a Map by passing in the Basemap m_map = new Map(Basemap::streets(this), this); m_map->setInitialViewpoint(Viewpoint(Point(-10800000, 4500000, SpatialReference(102100)), 3e7)); // set map on the map view m_mapView->setMap(m_map); // create the ServiceFeatureTable m_featureTable = new ServiceFeatureTable(QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0"), this); // create the FeatureLayer with the ServiceFeatureTable and add it to the Map m_featureLayer = new FeatureLayer(m_featureTable, this); m_featureLayer->setSelectionWidth(3); m_map->operationalLayers()->append(m_featureLayer); connectSignals(); } void AddFeaturesFeatureService::connectSignals() { //! [AddFeaturesFeatureService add at mouse click] // connect to the mouse clicked signal on the MapQuickView connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // obtain the map point Point newPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y()); // create the feature attributes QMap<QString, QVariant> featureAttributes; featureAttributes.insert("typdamage", "Minor"); featureAttributes.insert("primcause", "Earthquake"); // create a new feature and add it to the feature table Feature* feature = m_featureTable->createFeature(featureAttributes,newPoint,this); m_featureTable->addFeature(feature); }); //! [AddFeaturesFeatureService add at mouse click] // connect to the addFeatureCompleted signal from the ServiceFeatureTable connect(m_featureTable, &ServiceFeatureTable::addFeatureCompleted, this, [this](QUuid, bool success) { // if add feature was successful, call apply edits if (success) m_featureTable->applyEdits(); }); // connect to the applyEditsCompleted signal from the ServiceFeatureTable connect(m_featureTable, &ServiceFeatureTable::applyEditsCompleted, this, [this](QUuid, QList<QSharedPointer<FeatureEditResult>> featureEditResults) { if (featureEditResults.isEmpty()) return; // obtain the first item in the list QSharedPointer<FeatureEditResult> featureEditResult = featureEditResults.first(); // check if there were errors, and if not, log the new object ID if (!featureEditResult->isCompletedWithErrors()) qDebug() << "New Object ID is:" << featureEditResult->objectId(); else qDebug() << "Apply edits error."; }); }
Tag code as snippet.
Tag code as snippet.
C++
apache-2.0
Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt,Esri/arcgis-runtime-samples-qt
b3e3be31b68375e09d66e1e1358028a6599360cf
QActiveResource.cpp
QActiveResource.cpp
/* * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL */ #include "QActiveResource.h" #include <QXmlStreamReader> #include <QStringList> #include <QDateTime> #include <QDebug> #include <curl/curl.h> using namespace QActiveResource; static size_t writer(void *ptr, size_t size, size_t nmemb, void *stream) { reinterpret_cast<QByteArray *>(stream)->append(QByteArray((const char *)(ptr), size * nmemb)); return size * nmemb; } namespace HTTP { QByteArray get(const QUrl &url, bool followRedirects = false) { QByteArray data; CURL *curl = curl_easy_init(); static const int maxRetry = 1; int retry = 0; if(curl) { do { curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); if(followRedirects) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2); } } while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry); curl_easy_cleanup(curl); } return data; } } static QVariant::Type lookupType(const QString &name) { static QHash<QString, QVariant::Type> types; if(types.isEmpty()) { types["integer"] = QVariant::Int; types["decimal"] = QVariant::Double; types["datetime"] = QVariant::DateTime; types["boolean"] = QVariant::Bool; } return types.contains(name) ? types[name] : QVariant::String; } static void assign(Record *record, QString name, const QVariant &value) { (*record)[name.replace('-', '_')] = value; } static QDateTime toDateTime(const QString &s) { QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate); time.setTimeSpec(Qt::UTC); int zoneHours = s.mid(s.length() - 6, 3).toInt(); int zoneMinutes = s.right(2).toInt(); return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60); } static QString toClassName(QString name) { if(name.isEmpty()) { return name; } name[0] = name[0].toUpper(); QRegExp re("-([a-z])"); while(name.indexOf(re) >= 0) { name.replace(re.cap(0), re.cap(1).toUpper()); } return name; } static QVariant reader(QXmlStreamReader &xml, bool advance = true) { Record record; QString elementName; while(!xml.atEnd()) { if(advance) { xml.readNext(); } if(xml.tokenType() == QXmlStreamReader::StartElement) { if(elementName.isNull()) { elementName = xml.name().toString(); } QString type = xml.attributes().value("type").toString(); if(type == "array") { QString name = xml.name().toString(); QList<QVariant> array; while(xml.readNext() == QXmlStreamReader::StartElement || (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace())) { if(!xml.isWhitespace()) { array.append(reader(xml, false)); } } assign(&record, name, array); } else if(xml.attributes().value("nil") == "true") { assign(&record, xml.name().toString(), QVariant()); } else if(advance && xml.name() != elementName) { QVariant value; QString text = xml.readElementText(); switch(lookupType(type)) { case QVariant::Int: value = text.toInt(); break; case QVariant::Double: value = text.toDouble(); break; case QVariant::DateTime: value = toDateTime(text); break; case QVariant::Bool: value = bool(text == "true"); break; default: value = text; } assign(&record, xml.name().toString(), value); } } if(xml.tokenType() == QXmlStreamReader::EndElement && !elementName.isNull() && elementName == xml.name()) { record.setClassName(toClassName(elementName)); return record; } advance = true; } return QVariant(); } static RecordList fetch(QUrl url, bool followRedirects = false) { if(!url.path().endsWith(".xml")) { url.setPath(url.path() + ".xml"); } QByteArray data = HTTP::get(url, followRedirects); QXmlStreamReader xml(data); QVariant value = reader(xml); RecordList records; if(value.type() == QVariant::List) { foreach(QVariant v, value.toList()) { records.append(v.toHash()); } } else if(value.type() == QVariant::Hash && value.toHash().size() == 2) { foreach(QVariant v, value.toHash().begin()->toList()) { records.append(v.toHash()); } } else if(value.isValid()) { records.append(value.toHash()); } return records; } /* * Record */ static const QString QActiveResourceClassKey = "QActiveResource Class"; Record::Record(const QVariantHash &hash) : d(new Data) { d->hash = hash; d->className = d->hash.take(QActiveResourceClassKey).toString(); } Record::Record(const QVariant &v) : d(new Data) { d->hash = v.toHash(); d->className = d->hash.take(QActiveResourceClassKey).toString(); } QVariant &Record::operator[](const QString &key) { return d->hash[key]; } QVariant Record::operator[](const QString &key) const { return d->hash[key]; } bool Record::isEmpty() const { return d->hash.isEmpty(); } QString Record::className() const { return d->className; } void Record::setClassName(const QString &name) { d->className = name; } Record::operator QVariant() const { QVariantHash hash = d->hash; hash[QActiveResourceClassKey] = d->className; return hash; } Record::ConstIterator Record::begin() const { return d->hash.begin(); } Record::ConstIterator Record::end() const { return d->hash.end(); } /* * Param::Data */ Param::Data::Data(const QString &k, const QString &v) : key(k), value(v) { } /* * Param */ Param::Param() : d(0) { } Param::Param(const QString &key, const QString &value) : d(new Data(key, value)) { } bool Param::isNull() const { return d == 0; } QString Param::key() const { return isNull() ? QString() : d->key; } QString Param::value() const { return isNull() ? QString() : d->value; } /* * Resource::Data */ Resource::Data::Data(const QUrl &b, const QString &r) : base(b), resource(r), url(base), followRedirects(false) { setUrl(); } void Resource::Data::setUrl() { url = base; url.setPath(base.path() + (base.path().endsWith("/") ? "" : "/") + resource); } /* * Resource */ Resource::Resource(const QUrl &base, const QString &resource) : d(new Data(base, resource)) { } void Resource::setBase(const QUrl &base) { d->base = base; d->setUrl(); } void Resource::setResource(const QString &resource) { d->resource = resource; d->setUrl(); } Record Resource::find(const QVariant &id) const { return find(FindOne, id.toString()); } RecordList Resource::find(FindMulti style, const QString &from, const ParamList &params) const { Q_UNUSED(style); QUrl url = d->url; foreach(Param param, params) { if(!param.isNull()) { url.addQueryItem(param.key(), param.value()); } } if(!from.isEmpty()) { url.setPath(url.path() + "/" + from); } return fetch(url, d->followRedirects); } Record Resource::find(FindSingle style, const QString &from, const ParamList &params) const { QUrl url = d->url; foreach(Param param, params) { if(!param.isNull()) { url.addQueryItem(param.key(), param.value()); } } if(!from.isEmpty()) { url.setPath(url.path() + "/" + from); } switch(style) { case FindOne: case FindFirst: { RecordList results = find(FindAll, from, params); return results.isEmpty() ? Record() : results.front(); } case FindLast: { RecordList results = find(FindAll, from, params); return results.isEmpty() ? Record() : results.back(); } } return Record(); } Record Resource::find(FindSingle style, const QString &from, const Param &first, const Param &second, const Param &third, const Param &fourth) const { return find(style, from, ParamList() << first << second << third << fourth); } RecordList Resource::find(FindMulti style, const QString &from, const Param &first, const Param &second, const Param &third, const Param &fourth) const { return find(style, from, ParamList() << first << second << third << fourth); } void Resource::setFollowRedirects(bool followRedirects) { d->followRedirects = followRedirects; }
/* * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL */ #include "QActiveResource.h" #include <QXmlStreamReader> #include <QStringList> #include <QDateTime> #include <QDebug> #include <curl/curl.h> using namespace QActiveResource; static const QString QActiveResourceClassKey = "QActiveResource Class"; static size_t writer(void *ptr, size_t size, size_t nmemb, void *stream) { reinterpret_cast<QByteArray *>(stream)->append(QByteArray((const char *)(ptr), size * nmemb)); return size * nmemb; } namespace HTTP { QByteArray get(const QUrl &url, bool followRedirects = false) { QByteArray data; CURL *curl = curl_easy_init(); static const int maxRetry = 1; int retry = 0; if(curl) { do { curl_easy_setopt(curl, CURLOPT_URL, url.toEncoded().data()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &data); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 25); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); if(followRedirects) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2); } } while(curl_easy_perform(curl) != 0 && ++retry <= maxRetry); curl_easy_cleanup(curl); } return data; } } static QVariant::Type lookupType(const QString &name) { static QHash<QString, QVariant::Type> types; if(types.isEmpty()) { types["integer"] = QVariant::Int; types["decimal"] = QVariant::Double; types["datetime"] = QVariant::DateTime; types["boolean"] = QVariant::Bool; } return types.contains(name) ? types[name] : QVariant::String; } static void assign(Record *record, QString name, const QVariant &value) { (*record)[name.replace('-', '_')] = value; } static QDateTime toDateTime(const QString &s) { QDateTime time = QDateTime::fromString(s.left(s.length() - 6), Qt::ISODate); time.setTimeSpec(Qt::UTC); int zoneHours = s.mid(s.length() - 6, 3).toInt(); int zoneMinutes = s.right(2).toInt(); return time.addSecs(-1 * (60 * zoneHours + zoneMinutes) * 60); } static QString toClassName(QString name) { if(name.isEmpty()) { return name; } name[0] = name[0].toUpper(); QRegExp re("-([a-z])"); while(name.indexOf(re) >= 0) { name.replace(re.cap(0), re.cap(1).toUpper()); } return name; } static QVariant reader(QXmlStreamReader &xml, bool advance = true) { Record record; QString elementName; while(!xml.atEnd()) { if(advance) { xml.readNext(); } if(xml.tokenType() == QXmlStreamReader::StartElement) { if(elementName.isNull()) { elementName = xml.name().toString(); } QString type = xml.attributes().value("type").toString(); if(type == "array") { QString name = xml.name().toString(); QList<QVariant> array; while(xml.readNext() == QXmlStreamReader::StartElement || (xml.tokenType() == QXmlStreamReader::Characters && xml.isWhitespace())) { if(!xml.isWhitespace()) { array.append(reader(xml, false)); } } assign(&record, name, array); } else if(xml.attributes().value("nil") == "true") { assign(&record, xml.name().toString(), QVariant()); } else if(advance && xml.name() != elementName) { QVariant value; QString text = xml.readElementText(); switch(lookupType(type)) { case QVariant::Int: value = text.toInt(); break; case QVariant::Double: value = text.toDouble(); break; case QVariant::DateTime: value = toDateTime(text); break; case QVariant::Bool: value = bool(text == "true"); break; default: value = text; } assign(&record, xml.name().toString(), value); } } if(xml.tokenType() == QXmlStreamReader::EndElement && !elementName.isNull() && elementName == xml.name()) { record.setClassName(toClassName(elementName)); return record; } advance = true; } return QVariant(); } static RecordList fetch(QUrl url, bool followRedirects = false) { if(!url.path().endsWith(".xml")) { url.setPath(url.path() + ".xml"); } QByteArray data = HTTP::get(url, followRedirects); QXmlStreamReader xml(data); QVariant value = reader(xml); RecordList records; if(value.type() == QVariant::List) { foreach(QVariant v, value.toList()) { records.append(v.toHash()); } } else if(value.type() == QVariant::Hash && value.toHash().size() == 2) { QVariantHash hash = value.toHash(); QStringList keys = hash.keys(); keys.removeOne(QActiveResourceClassKey); foreach(QVariant v, hash[keys.front()].toList()) { records.append(v.toHash()); } } else if(value.isValid()) { records.append(value.toHash()); } return records; } /* * Record */ Record::Record(const QVariantHash &hash) : d(new Data) { d->hash = hash; d->className = d->hash.take(QActiveResourceClassKey).toString(); } Record::Record(const QVariant &v) : d(new Data) { d->hash = v.toHash(); d->className = d->hash.take(QActiveResourceClassKey).toString(); } QVariant &Record::operator[](const QString &key) { return d->hash[key]; } QVariant Record::operator[](const QString &key) const { return d->hash[key]; } bool Record::isEmpty() const { return d->hash.isEmpty(); } QString Record::className() const { return d->className; } void Record::setClassName(const QString &name) { d->className = name; } Record::operator QVariant() const { QVariantHash hash = d->hash; hash[QActiveResourceClassKey] = d->className; return hash; } Record::ConstIterator Record::begin() const { return d->hash.begin(); } Record::ConstIterator Record::end() const { return d->hash.end(); } /* * Param::Data */ Param::Data::Data(const QString &k, const QString &v) : key(k), value(v) { } /* * Param */ Param::Param() : d(0) { } Param::Param(const QString &key, const QString &value) : d(new Data(key, value)) { } bool Param::isNull() const { return d == 0; } QString Param::key() const { return isNull() ? QString() : d->key; } QString Param::value() const { return isNull() ? QString() : d->value; } /* * Resource::Data */ Resource::Data::Data(const QUrl &b, const QString &r) : base(b), resource(r), url(base), followRedirects(false) { setUrl(); } void Resource::Data::setUrl() { url = base; url.setPath(base.path() + (base.path().endsWith("/") ? "" : "/") + resource); } /* * Resource */ Resource::Resource(const QUrl &base, const QString &resource) : d(new Data(base, resource)) { } void Resource::setBase(const QUrl &base) { d->base = base; d->setUrl(); } void Resource::setResource(const QString &resource) { d->resource = resource; d->setUrl(); } Record Resource::find(const QVariant &id) const { return find(FindOne, id.toString()); } RecordList Resource::find(FindMulti style, const QString &from, const ParamList &params) const { Q_UNUSED(style); QUrl url = d->url; foreach(Param param, params) { if(!param.isNull()) { url.addQueryItem(param.key(), param.value()); } } if(!from.isEmpty()) { url.setPath(url.path() + "/" + from); } return fetch(url, d->followRedirects); } Record Resource::find(FindSingle style, const QString &from, const ParamList &params) const { QUrl url = d->url; foreach(Param param, params) { if(!param.isNull()) { url.addQueryItem(param.key(), param.value()); } } if(!from.isEmpty()) { url.setPath(url.path() + "/" + from); } switch(style) { case FindOne: case FindFirst: { RecordList results = find(FindAll, from, params); return results.isEmpty() ? Record() : results.front(); } case FindLast: { RecordList results = find(FindAll, from, params); return results.isEmpty() ? Record() : results.back(); } } return Record(); } Record Resource::find(FindSingle style, const QString &from, const Param &first, const Param &second, const Param &third, const Param &fourth) const { return find(style, from, ParamList() << first << second << third << fourth); } RecordList Resource::find(FindMulti style, const QString &from, const Param &first, const Param &second, const Param &third, const Param &fourth) const { return find(style, from, ParamList() << first << second << third << fourth); } void Resource::setFollowRedirects(bool followRedirects) { d->followRedirects = followRedirects; }
Adjust for the fact that we stick an extra key in
Adjust for the fact that we stick an extra key in
C++
lgpl-2.1
directededge/QActiveResource,directededge/QActiveResource,directededge/QActiveResource
aa74fa359665e705eef0f7ff7d1de7c1075f6b79
chrome/browser/ui/views/find_bar_host_aura.cc
chrome/browser/ui/views/find_bar_host_aura.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "base/logging.h" #include "ui/base/events/event.h" void FindBarHost::AudibleAlert() { #if defined(OS_WIN) MessageBeep(MB_OK); #else // TODO(mukai): NOTIMPLEMENTED(); #endif } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const ui::KeyEvent& key_event) { return true; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "base/logging.h" #include "ui/base/events/event.h" void FindBarHost::AudibleAlert() { #if defined(OS_WIN) MessageBeep(MB_OK); #endif } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const ui::KeyEvent& key_event) { return true; }
Remove NOTIMPLEMENTED() in FindBarHost::AudibleAlert() for ChromeOS.
Remove NOTIMPLEMENTED() in FindBarHost::AudibleAlert() for ChromeOS. BUG=None TEST=None R=jennyz,jamescook TBR=sky Review URL: https://chromiumcodereview.appspot.com/23819045 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@222422 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,anirudhSK/chromium,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,Just-D/chromium-1,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dednal/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,dushu1203/chromium.src,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,littlstar/chromium.src,dednal/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,Just-D/chromium-1,jaruba/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,M4sse/chromium.src,Just-D/chromium-1,dednal/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,markYoungH/chromium.src,jaruba/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,patrickm/chromium.src,mogoweb/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,anirudhSK/chromium,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,patrickm/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk
a45c394f050c6c276a418bad1faf466ec7a072ed
WebCore/kwq/KWQRenderTreeDebug.cpp
WebCore/kwq/KWQRenderTreeDebug.cpp
/* * Copyright (C) 2003 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "KWQRenderTreeDebug.h" #include "htmltags.h" #include "khtmlview.h" #include "render_replaced.h" #include "render_table.h" #include "render_text.h" #include "KWQKHTMLPart.h" #include "KWQTextStream.h" using khtml::RenderLayer; using khtml::RenderObject; using khtml::RenderTableCell; using khtml::RenderWidget; using khtml::RenderText; using khtml::TextRun; using khtml::TextRunArray; static void writeLayers(QTextStream &ts, const RenderLayer* rootLayer, RenderLayer* l, const QRect& paintDirtyRect, int indent=0); static QTextStream &operator<<(QTextStream &ts, const QRect &r) { return ts << "at (" << r.x() << "," << r.y() << ") size " << r.width() << "x" << r.height(); } static void writeIndent(QTextStream &ts, int indent) { for (int i = 0; i != indent; ++i) { ts << " "; } } static QTextStream &operator<<(QTextStream &ts, const RenderObject &o) { ts << o.renderName(); if (o.style() && o.style()->zIndex()) { ts << " zI: " << o.style()->zIndex(); } if (o.element()) { QString tagName(getTagName(o.element()->id()).string()); if (!tagName.isEmpty()) { ts << " {" << tagName << "}"; } } QRect r(o.xPos(), o.yPos(), o.width(), o.height()); ts << " " << r; if (o.parent() && (o.parent()->style()->color() != o.style()->color())) ts << " [color=" << o.style()->color().name() << "]"; if (o.parent() && (o.parent()->style()->backgroundColor() != o.style()->backgroundColor())) ts << " [bgcolor=" << o.style()->backgroundColor().name() << "]"; if (o.isTableCell()) { const RenderTableCell &c = static_cast<const RenderTableCell &>(o); ts << " [r=" << c.row() << " c=" << c.col() << " rs=" << c.rowSpan() << " cs=" << c.colSpan() << "]"; } return ts; } static QString quoteAndEscapeNonPrintables(const QString &s) { QString result; result += '"'; for (uint i = 0; i != s.length(); ++i) { QChar c = s.at(i); if (c == '\\') { result += "\\\\"; } else if (c == '"') { result += "\\\""; } else { ushort u = c.unicode(); if (u >= 0x20 && u < 0x7F) { result += c; } else { QString hex; hex.sprintf("\\x{%X}", u); result += hex; } } } result += '"'; return result; } static void writeTextRun(QTextStream &ts, const RenderText &o, const TextRun &run) { ts << "text run at (" << run.m_x << "," << run.m_y << ") width " << run.m_width << ": " << quoteAndEscapeNonPrintables(o.data().string().mid(run.m_start, run.m_len)) << "\n"; } static void write(QTextStream &ts, const RenderObject &o, int indent = 0) { writeIndent(ts, indent); ts << o << "\n"; if (o.isText()) { const RenderText &text = static_cast<const RenderText &>(o); TextRunArray runs = text.textRuns(); for (unsigned int i = 0; i < runs.count(); i++) { writeIndent(ts, indent+1); writeTextRun(ts, text, *runs[i]); } } for (RenderObject *child = o.firstChild(); child; child = child->nextSibling()) { if (child->layer()) { continue; } write(ts, *child, indent + 1); } if (o.isWidget()) { KHTMLView *view = dynamic_cast<KHTMLView *>(static_cast<const RenderWidget &>(o).widget()); if (view) { RenderObject *root = KWQ(view->part())->renderer(); if (root) { RenderLayer* l = root->layer(); if (l) writeLayers(ts, l, l, QRect(l->xPos(), l->yPos(), l->width(), l->height()), indent+1); } } } } static void write(QTextStream &ts, const RenderLayer &l, const QRect& layerBounds, const QRect& backgroundClipRect, const QRect& clipRect, int layerType = 0, int indent = 0) { writeIndent(ts, indent); ts << "layer"; QRect r(e.absBounds); ts << " " << r; if (layerBounds != layerBounds.intersect(backgroundClipRect)) { ts << " backgroundClip " << backgroundClipRect; } if (layerBounds != layerBounds.intersect(clipRect)) { ts << " clip " << clipRect; } if (layerType == -1) ts << " layerType: background only"; else if (layerType == 1) ts << " layerType: foreground only"; ts << "\n"; if (layerType != -1) write(ts, *l.renderer(), indent + 1); } static void writeLayers(QTextStream &ts, const RenderLayer* rootLayer, RenderLayer* l, const QRect& paintDirtyRect, int indent) { // Calculate the clip rects we should use. QRect layerBounds, damageRect, clipRectToApply; l->calculateRects(rootLayer, paintDirtyRect, layerBounds, damageRect, clipRectToApply); // Ensure our z-order lists are up-to-date. l->updateZOrderLists(); bool shouldPaint = l->intersectsDamageRect(layerBounds, damageRect); QPtrVector<RenderLayer>* negList = l->negZOrderList(); if (shouldPaint && negList && negList->count() > 0) write(ts, *l, layerBounds, damageRect, clipRectToApply, -1, indent); if (negList) { for (unsigned i = 0; i != negList->count(); ++i) writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, indent); } if (shouldPaint) write(ts, *l, layerBounds, damageRect, clipRectToApply, negList && negList->count() > 0, indent); QPtrVector<RenderLayer>* posList = l->posZOrderList(); if (posList) { for (unsigned i = 0; i != posList->count(); ++i) writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, indent); } } QString externalRepresentation(const RenderObject *o) { QString s; { QTextStream ts(&s); if (o) { RenderLayer* l = o->layer(); if (l) writeLayers(ts, l, l, QRect(l->xPos(), l->yPos(), l->width(), l->height())); } } return s; }
/* * Copyright (C) 2003 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "KWQRenderTreeDebug.h" #include "htmltags.h" #include "khtmlview.h" #include "render_replaced.h" #include "render_table.h" #include "render_text.h" #include "KWQKHTMLPart.h" #include "KWQTextStream.h" using khtml::RenderLayer; using khtml::RenderObject; using khtml::RenderTableCell; using khtml::RenderWidget; using khtml::RenderText; using khtml::TextRun; using khtml::TextRunArray; static void writeLayers(QTextStream &ts, const RenderLayer* rootLayer, RenderLayer* l, const QRect& paintDirtyRect, int indent=0); static QTextStream &operator<<(QTextStream &ts, const QRect &r) { return ts << "at (" << r.x() << "," << r.y() << ") size " << r.width() << "x" << r.height(); } static void writeIndent(QTextStream &ts, int indent) { for (int i = 0; i != indent; ++i) { ts << " "; } } static QTextStream &operator<<(QTextStream &ts, const RenderObject &o) { ts << o.renderName(); if (o.style() && o.style()->zIndex()) { ts << " zI: " << o.style()->zIndex(); } if (o.element()) { QString tagName(getTagName(o.element()->id()).string()); if (!tagName.isEmpty()) { ts << " {" << tagName << "}"; } } QRect r(o.xPos(), o.yPos(), o.width(), o.height()); ts << " " << r; if (o.parent() && (o.parent()->style()->color() != o.style()->color())) ts << " [color=" << o.style()->color().name() << "]"; if (o.parent() && (o.parent()->style()->backgroundColor() != o.style()->backgroundColor())) ts << " [bgcolor=" << o.style()->backgroundColor().name() << "]"; if (o.isTableCell()) { const RenderTableCell &c = static_cast<const RenderTableCell &>(o); ts << " [r=" << c.row() << " c=" << c.col() << " rs=" << c.rowSpan() << " cs=" << c.colSpan() << "]"; } return ts; } static QString quoteAndEscapeNonPrintables(const QString &s) { QString result; result += '"'; for (uint i = 0; i != s.length(); ++i) { QChar c = s.at(i); if (c == '\\') { result += "\\\\"; } else if (c == '"') { result += "\\\""; } else { ushort u = c.unicode(); if (u >= 0x20 && u < 0x7F) { result += c; } else { QString hex; hex.sprintf("\\x{%X}", u); result += hex; } } } result += '"'; return result; } static void writeTextRun(QTextStream &ts, const RenderText &o, const TextRun &run) { ts << "text run at (" << run.m_x << "," << run.m_y << ") width " << run.m_width << ": " << quoteAndEscapeNonPrintables(o.data().string().mid(run.m_start, run.m_len)) << "\n"; } static void write(QTextStream &ts, const RenderObject &o, int indent = 0) { writeIndent(ts, indent); ts << o << "\n"; if (o.isText()) { const RenderText &text = static_cast<const RenderText &>(o); TextRunArray runs = text.textRuns(); for (unsigned int i = 0; i < runs.count(); i++) { writeIndent(ts, indent+1); writeTextRun(ts, text, *runs[i]); } } for (RenderObject *child = o.firstChild(); child; child = child->nextSibling()) { if (child->layer()) { continue; } write(ts, *child, indent + 1); } if (o.isWidget()) { KHTMLView *view = dynamic_cast<KHTMLView *>(static_cast<const RenderWidget &>(o).widget()); if (view) { RenderObject *root = KWQ(view->part())->renderer(); if (root) { RenderLayer* l = root->layer(); if (l) writeLayers(ts, l, l, QRect(l->xPos(), l->yPos(), l->width(), l->height()), indent+1); } } } } static void write(QTextStream &ts, const RenderLayer &l, const QRect& layerBounds, const QRect& backgroundClipRect, const QRect& clipRect, int layerType = 0, int indent = 0) { writeIndent(ts, indent); ts << "layer"; ts << " " << layerBounds; if (layerBounds != layerBounds.intersect(backgroundClipRect)) ts << " backgroundClip " << backgroundClipRect; if (layerBounds != layerBounds.intersect(clipRect)) ts << " clip " << clipRect; if (layerType == -1) ts << " layerType: background only"; else if (layerType == 1) ts << " layerType: foreground only"; ts << "\n"; if (layerType != -1) write(ts, *l.renderer(), indent + 1); } static void writeLayers(QTextStream &ts, const RenderLayer* rootLayer, RenderLayer* l, const QRect& paintDirtyRect, int indent) { // Calculate the clip rects we should use. QRect layerBounds, damageRect, clipRectToApply; l->calculateRects(rootLayer, paintDirtyRect, layerBounds, damageRect, clipRectToApply); // Ensure our z-order lists are up-to-date. l->updateZOrderLists(); bool shouldPaint = l->intersectsDamageRect(layerBounds, damageRect); QPtrVector<RenderLayer>* negList = l->negZOrderList(); if (shouldPaint && negList && negList->count() > 0) write(ts, *l, layerBounds, damageRect, clipRectToApply, -1, indent); if (negList) { for (unsigned i = 0; i != negList->count(); ++i) writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, indent); } if (shouldPaint) write(ts, *l, layerBounds, damageRect, clipRectToApply, negList && negList->count() > 0, indent); QPtrVector<RenderLayer>* posList = l->posZOrderList(); if (posList) { for (unsigned i = 0; i != posList->count(); ++i) writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, indent); } } QString externalRepresentation(const RenderObject *o) { QString s; { QTextStream ts(&s); if (o) { RenderLayer* l = o->layer(); if (l) writeLayers(ts, l, l, QRect(l->xPos(), l->yPos(), l->width(), l->height())); } } return s; }
Fix build error.
Fix build error. git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@5010 bbb929c8-8fbe-4397-9dbb-9b2b20218538
C++
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
cb817931a01446268f912fcee0890ff3ed9082a0
workbench/src/counters.cpp
workbench/src/counters.cpp
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <chrono> #include <random> #define ETL_COUNTERS //#define ETL_COUNTERS_VERBOSE #define IF_DEBUG if(false) #include "etl/etl.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; float fake = 0; /* * * Current values are (alloc/gpu_to_cpu/cpu_to_gpu): * Simple: 3 / 0 / 2 (Optimal!) * Basic: 15 / 0 / 3 (Optimal!) * Sub: 163 / 160 / 480 * ML: 69 / 10 / 19 (without activations) * ML: 129 / 80 / 49 (with activations) */ void simple(){ etl::dyn_matrix<float, 2> A(4096, 4096); etl::dyn_matrix<float, 2> B(4096, 4096); etl::dyn_matrix<float, 2> C(4096, 4096); A = 1e-4 >> etl::sequence_generator<float>(1.0); B = 1e-4 >> etl::sequence_generator<float>(1.0); C = 1e-4 >> etl::sequence_generator<float>(1.0); etl::reset_counters(); std::cout << "Simple" << std::endl; for (size_t i = 0; i < 10; ++i) { C = A * B; fake += etl::mean(C); } etl::dump_counters(); std::cout << " Result: " << fake << std::endl; std::cout << "Should be: 2.8826e+10" << std::endl; } void basic(){ etl::dyn_matrix<float, 2> A(4096, 4096); etl::dyn_matrix<float, 2> B(4096, 4096); etl::dyn_matrix<float, 2> C(4096, 4096); etl::dyn_matrix<float, 2> D(4096, 4096); etl::dyn_matrix<float, 2> E(4096, 4096); A = 1e-4 >> etl::sequence_generator<float>(1.0); B = 1e-4 >> etl::sequence_generator<float>(1.0); C = 1e-4 >> etl::sequence_generator<float>(1.0); D = 1e-4 >> etl::sequence_generator<float>(1.0); E = 1e-4 >> etl::sequence_generator<float>(1.0); etl::reset_counters(); std::cout << "Basic" << std::endl; for (size_t i = 0; i < 10; ++i) { IF_DEBUG std::cout << i << ":0 C = A * B * E" << std::endl; C = A * B * E; IF_DEBUG std::cout << i << ":1 D = A * trans(A)" << std::endl; D = A * trans(A); IF_DEBUG std::cout << i << ":2 D *= 1.1" << std::endl; D *= 1.1; IF_DEBUG std::cout << i << ":3 E = D" << std::endl; E = D; IF_DEBUG std::cout << i << ":4 D += C" << std::endl; D += C; IF_DEBUG std::cout << i << ":5 fake += etl::mean(D)" << std::endl; fake += etl::mean(D); IF_DEBUG std::cout << i << ":6 end" << std::endl; } etl::dump_counters(); std::cout << " Result: " << fake << std::endl; std::cout << "Should be: 3.36933e+23" << std::endl; } void sub(){ etl::dyn_matrix<float, 3> A(16, 2048, 2048); etl::dyn_matrix<float, 3> B(16, 2048, 2048); etl::dyn_matrix<float, 3> C(16, 2048, 2048); etl::dyn_matrix<float, 3> D(16, 2048, 2048); A = etl::normal_generator<float>(1.0, 0.0); B = etl::normal_generator<float>(1.0, 0.0); C = etl::normal_generator<float>(1.0, 0.0); D = etl::normal_generator<float>(1.0, 0.0); etl::reset_counters(); std::cout << "Sub" << std::endl; for (size_t i = 0; i < 10; ++i) { for (size_t k = 0; k < 16; ++k) { C(k) = A(k) * B(k) * B(k); D(k) += C(k); D(k) *= 1.1; fake += etl::mean(D(k)); } } etl::dump_counters(); } // Simulate forward propagation in a neural network (with some ops as DLL) void ml(){ etl::dyn_matrix<float, 4> I(32, 3, 28, 28); etl::dyn_matrix<float, 2> L(32, 10); etl::dyn_matrix<float, 4> C1_W(16, 3, 3, 3); etl::dyn_matrix<float, 1> C1_B(16); etl::dyn_matrix<float, 4> C1_W_G(16, 3, 3, 3); etl::dyn_matrix<float, 1> C1_B_G(16); etl::dyn_matrix<float, 4> C1_O(32, 16, 28, 28); etl::dyn_matrix<float, 4> C1_E(32, 16, 28, 28); etl::dyn_matrix<float, 4> P1_O(32, 16, 14, 14); etl::dyn_matrix<float, 4> P1_E(32, 16, 14, 14); etl::dyn_matrix<float, 4> C2_W(16, 16, 3, 3); etl::dyn_matrix<float, 1> C2_B(16); etl::dyn_matrix<float, 4> C2_W_G(16, 16, 3, 3); etl::dyn_matrix<float, 1> C2_B_G(16); etl::dyn_matrix<float, 4> C2_O(32, 16, 14, 14); etl::dyn_matrix<float, 4> C2_E(32, 16, 14, 14); etl::dyn_matrix<float, 4> P2_O(32, 16, 7, 7); etl::dyn_matrix<float, 4> P2_E(32, 16, 7, 7); etl::dyn_matrix<float, 2> FC1_W(16 * 7 * 7, 500); etl::dyn_matrix<float, 1> FC1_B(500); etl::dyn_matrix<float, 2> FC1_W_G(16 * 7 * 7, 500); etl::dyn_matrix<float, 1> FC1_B_G(500); etl::dyn_matrix<float, 2> FC1_O(32, 500); etl::dyn_matrix<float, 2> FC1_E(32, 500); etl::dyn_matrix<float, 2> FC2_W(500, 10); etl::dyn_matrix<float, 1> FC2_B(10); etl::dyn_matrix<float, 2> FC2_W_G(500, 10); etl::dyn_matrix<float, 1> FC2_B_G(10); etl::dyn_matrix<float, 2> FC2_O(32, 10); etl::dyn_matrix<float, 2> FC2_E(32, 10); etl::reset_counters(); std::cout << "ML" << std::endl; for (size_t i = 0; i < 10; ++i) { // Forward Propagation C1_O = relu(bias_add_4d(etl::ml::convolution_forward<1, 1, 1, 1>(I, C1_W), C1_B)); P1_O = etl::max_pool_2d<2, 2>(C1_O); C2_O = relu(bias_add_4d(etl::ml::convolution_forward<1, 1, 1, 1>(P1_O, C2_W), C2_B)); P2_O = etl::max_pool_2d<2, 2>(C2_O); FC1_O = sigmoid(bias_add_2d(etl::reshape<32, 16 * 7 * 7>(P2_O) * FC1_W, FC1_B)); FC2_O = sigmoid(bias_add_2d(FC1_O * FC2_W, FC2_B)); // Backward propagation of the errors FC2_E = L - FC2_O; // Errors of last layer (!GPU) FC1_E = FC2_E * trans(FC2_W); // Backpropagate FC2 -> FC1 FC1_E = sigmoid_derivative(FC1_O) >> FC1_E; // Adapt errors of FC1 etl::reshape<32, 16 * 7 * 7>(P2_E) = FC1_E * trans(FC1_W); // FC1 -> MP2 C2_E = etl::max_pool_upsample_2d<2, 2>(C2_O, P2_O, P2_E); // MP2 -> C2 C2_E = relu_derivative(C2_O) >> C2_E; // Adapt errors of C2 P1_E = etl::ml::convolution_backward<1, 1, 1, 1>(C2_E, C2_W); // C2 -> MP1 C1_E = etl::max_pool_upsample_2d<2, 2>(C1_O, P1_O, P1_E); // MP1 -> C1 C1_E = relu_derivative(C1_O) >> C1_E; // Adapt errors of C1 // Compute the gradients C1_W_G = etl::ml::convolution_backward_filter<1, 1, 1, 1>(I, C1_E); C1_B_G = bias_batch_sum_4d(C1_E); C2_W_G = etl::ml::convolution_backward_filter<1, 1, 1, 1>(P1_O, C2_E); C2_B_G = bias_batch_sum_4d(C2_E); FC1_W_G = batch_outer(etl::reshape<32, 16 * 7 * 7>(P2_O), FC1_E); FC1_B_G = bias_batch_sum_2d(FC1_E); FC2_W_G = batch_outer(FC1_O, FC2_E); FC2_B_G = bias_batch_sum_2d(FC2_E); //TODO Apply the gradients } etl::dump_counters(); } int main(){ auto start_time = timer_clock::now(); simple(); basic(); sub(); ml(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<milliseconds>(end_time - start_time); std::cout << "duration: " << duration.count() << "ms" << std::endl; return (int) fake; }
//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <chrono> #include <random> #define ETL_COUNTERS //#define ETL_COUNTERS_VERBOSE #define IF_DEBUG if(false) #include "etl/etl.hpp" typedef std::chrono::high_resolution_clock timer_clock; typedef std::chrono::milliseconds milliseconds; float fake = 0; /* * * Current values are (alloc/gpu_to_cpu/cpu_to_gpu): * Simple: 3 / 0 / 2 (Optimal!) * Basic: 15 / 0 / 3 (Optimal!) * Sub: 163 / 160 / 480 * ML: 69 / 10 / 19 (without activations) * ML: 109 / 80 / 49 (with activations) */ void simple(){ etl::dyn_matrix<float, 2> A(4096, 4096); etl::dyn_matrix<float, 2> B(4096, 4096); etl::dyn_matrix<float, 2> C(4096, 4096); A = 1e-4 >> etl::sequence_generator<float>(1.0); B = 1e-4 >> etl::sequence_generator<float>(1.0); C = 1e-4 >> etl::sequence_generator<float>(1.0); etl::reset_counters(); std::cout << "Simple" << std::endl; for (size_t i = 0; i < 10; ++i) { C = A * B; fake += etl::mean(C); } etl::dump_counters(); std::cout << " Result: " << fake << std::endl; std::cout << "Should be: 2.8826e+10" << std::endl; } void basic(){ etl::dyn_matrix<float, 2> A(4096, 4096); etl::dyn_matrix<float, 2> B(4096, 4096); etl::dyn_matrix<float, 2> C(4096, 4096); etl::dyn_matrix<float, 2> D(4096, 4096); etl::dyn_matrix<float, 2> E(4096, 4096); A = 1e-4 >> etl::sequence_generator<float>(1.0); B = 1e-4 >> etl::sequence_generator<float>(1.0); C = 1e-4 >> etl::sequence_generator<float>(1.0); D = 1e-4 >> etl::sequence_generator<float>(1.0); E = 1e-4 >> etl::sequence_generator<float>(1.0); etl::reset_counters(); std::cout << "Basic" << std::endl; for (size_t i = 0; i < 10; ++i) { IF_DEBUG std::cout << i << ":0 C = A * B * E" << std::endl; C = A * B * E; IF_DEBUG std::cout << i << ":1 D = A * trans(A)" << std::endl; D = A * trans(A); IF_DEBUG std::cout << i << ":2 D *= 1.1" << std::endl; D *= 1.1; IF_DEBUG std::cout << i << ":3 E = D" << std::endl; E = D; IF_DEBUG std::cout << i << ":4 D += C" << std::endl; D += C; IF_DEBUG std::cout << i << ":5 fake += etl::mean(D)" << std::endl; fake += etl::mean(D); IF_DEBUG std::cout << i << ":6 end" << std::endl; } etl::dump_counters(); std::cout << " Result: " << fake << std::endl; std::cout << "Should be: 3.36933e+23" << std::endl; } void sub(){ etl::dyn_matrix<float, 3> A(16, 2048, 2048); etl::dyn_matrix<float, 3> B(16, 2048, 2048); etl::dyn_matrix<float, 3> C(16, 2048, 2048); etl::dyn_matrix<float, 3> D(16, 2048, 2048); A = etl::normal_generator<float>(1.0, 0.0); B = etl::normal_generator<float>(1.0, 0.0); C = etl::normal_generator<float>(1.0, 0.0); D = etl::normal_generator<float>(1.0, 0.0); etl::reset_counters(); std::cout << "Sub" << std::endl; for (size_t i = 0; i < 10; ++i) { for (size_t k = 0; k < 16; ++k) { C(k) = A(k) * B(k) * B(k); D(k) += C(k); D(k) *= 1.1; fake += etl::mean(D(k)); } } etl::dump_counters(); } // Simulate forward propagation in a neural network (with some ops as DLL) void ml(){ etl::dyn_matrix<float, 4> I(32, 3, 28, 28); etl::dyn_matrix<float, 2> L(32, 10); etl::dyn_matrix<float, 4> C1_W(16, 3, 3, 3); etl::dyn_matrix<float, 1> C1_B(16); etl::dyn_matrix<float, 4> C1_W_G(16, 3, 3, 3); etl::dyn_matrix<float, 1> C1_B_G(16); etl::dyn_matrix<float, 4> C1_O(32, 16, 28, 28); etl::dyn_matrix<float, 4> C1_E(32, 16, 28, 28); etl::dyn_matrix<float, 4> P1_O(32, 16, 14, 14); etl::dyn_matrix<float, 4> P1_E(32, 16, 14, 14); etl::dyn_matrix<float, 4> C2_W(16, 16, 3, 3); etl::dyn_matrix<float, 1> C2_B(16); etl::dyn_matrix<float, 4> C2_W_G(16, 16, 3, 3); etl::dyn_matrix<float, 1> C2_B_G(16); etl::dyn_matrix<float, 4> C2_O(32, 16, 14, 14); etl::dyn_matrix<float, 4> C2_E(32, 16, 14, 14); etl::dyn_matrix<float, 4> P2_O(32, 16, 7, 7); etl::dyn_matrix<float, 4> P2_E(32, 16, 7, 7); etl::dyn_matrix<float, 2> FC1_W(16 * 7 * 7, 500); etl::dyn_matrix<float, 1> FC1_B(500); etl::dyn_matrix<float, 2> FC1_W_G(16 * 7 * 7, 500); etl::dyn_matrix<float, 1> FC1_B_G(500); etl::dyn_matrix<float, 2> FC1_O(32, 500); etl::dyn_matrix<float, 2> FC1_E(32, 500); etl::dyn_matrix<float, 2> FC2_W(500, 10); etl::dyn_matrix<float, 1> FC2_B(10); etl::dyn_matrix<float, 2> FC2_W_G(500, 10); etl::dyn_matrix<float, 1> FC2_B_G(10); etl::dyn_matrix<float, 2> FC2_O(32, 10); etl::dyn_matrix<float, 2> FC2_E(32, 10); etl::reset_counters(); std::cout << "ML" << std::endl; for (size_t i = 0; i < 10; ++i) { // Forward Propagation C1_O = relu(bias_add_4d(etl::ml::convolution_forward<1, 1, 1, 1>(I, C1_W), C1_B)); P1_O = etl::max_pool_2d<2, 2>(C1_O); C2_O = relu(bias_add_4d(etl::ml::convolution_forward<1, 1, 1, 1>(P1_O, C2_W), C2_B)); P2_O = etl::max_pool_2d<2, 2>(C2_O); FC1_O = sigmoid(bias_add_2d(etl::reshape<32, 16 * 7 * 7>(P2_O) * FC1_W, FC1_B)); FC2_O = sigmoid(bias_add_2d(FC1_O * FC2_W, FC2_B)); // Backward propagation of the errors FC2_E = L - FC2_O; // Errors of last layer (!GPU) FC1_E = FC2_E * trans(FC2_W); // Backpropagate FC2 -> FC1 FC1_E = etl::ml::sigmoid_backward(FC1_O, FC1_E); // Adapt errors of FC1 etl::reshape<32, 16 * 7 * 7>(P2_E) = FC1_E * trans(FC1_W); // FC1 -> MP2 C2_E = etl::max_pool_upsample_2d<2, 2>(C2_O, P2_O, P2_E); // MP2 -> C2 C2_E = etl::ml::relu_backward(C2_O, C2_E); // Adapt errors of C2 P1_E = etl::ml::convolution_backward<1, 1, 1, 1>(C2_E, C2_W); // C2 -> MP1 C1_E = etl::max_pool_upsample_2d<2, 2>(C1_O, P1_O, P1_E); // MP1 -> C1 C1_E = etl::ml::relu_backward(C1_O, C1_E); // Adapt errors of C1 // Compute the gradients C1_W_G = etl::ml::convolution_backward_filter<1, 1, 1, 1>(I, C1_E); C1_B_G = bias_batch_sum_4d(C1_E); C2_W_G = etl::ml::convolution_backward_filter<1, 1, 1, 1>(P1_O, C2_E); C2_B_G = bias_batch_sum_4d(C2_E); FC1_W_G = batch_outer(etl::reshape<32, 16 * 7 * 7>(P2_O), FC1_E); FC1_B_G = bias_batch_sum_2d(FC1_E); FC2_W_G = batch_outer(FC1_O, FC2_E); FC2_B_G = bias_batch_sum_2d(FC2_E); //TODO Apply the gradients } etl::dump_counters(); } int main(){ auto start_time = timer_clock::now(); simple(); basic(); sub(); ml(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<milliseconds>(end_time - start_time); std::cout << "duration: " << duration.count() << "ms" << std::endl; return (int) fake; }
Use the new helpers
Use the new helpers
C++
mit
wichtounet/etl,wichtounet/etl
7b1c973884a93d95d5bf6e4df7d34eecacb20b8b
api/api.hh
api/api.hh
/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (!res.count._set) { res = val; return res; } if (val.count == 0) { return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } inline int64_t min_int64(int64_t a, int64_t b) { return std::min(a,b); } inline int64_t max_int64(int64_t a, int64_t b) { return std::max(a,b); } /** * A helper struct for ratio calculation * It combine total and the sub set for the ratio and its * to_json method return the ration sub/total */ struct ratio_holder : public json::jsonable { double total = 0; double sub = 0; virtual std::string to_json() const { if (total == 0) { return "0"; } return std::to_string(sub/total); } ratio_holder() = default; ratio_holder& add(double _total, double _sub) { total += _total; sub += _sub; return *this; } ratio_holder(double _total, double _sub) { total = _total; sub = _sub; } ratio_holder& operator+=(const ratio_holder& a) { return add(a.total, a.sub); } friend ratio_holder operator+(ratio_holder a, const ratio_holder& b) { return a += b; } }; }
/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; sstring api_doc; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (!res.count._set) { res = val; return res; } if (val.count == 0) { return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } inline int64_t min_int64(int64_t a, int64_t b) { return std::min(a,b); } inline int64_t max_int64(int64_t a, int64_t b) { return std::max(a,b); } /** * A helper struct for ratio calculation * It combine total and the sub set for the ratio and its * to_json method return the ration sub/total */ struct ratio_holder : public json::jsonable { double total = 0; double sub = 0; virtual std::string to_json() const { if (total == 0) { return "0"; } return std::to_string(sub/total); } ratio_holder() = default; ratio_holder& add(double _total, double _sub) { total += _total; sub += _sub; return *this; } ratio_holder(double _total, double _sub) { total = _total; sub = _sub; } ratio_holder& operator+=(const ratio_holder& a) { return add(a.total, a.sub); } friend ratio_holder operator+(ratio_holder a, const ratio_holder& b) { return a += b; } }; }
Add doc directory parameter to the http context
API: Add doc directory parameter to the http context Adding a parameter to the http context so it will not be hard coded and could be configured. Signed-off-by: Amnon Heiman <[email protected]>
C++
agpl-3.0
guiquanz/scylla,glommer/scylla,phonkee/scylla,victorbriz/scylla,shaunstanislaus/scylla,guiquanz/scylla,kangkot/scylla,duarten/scylla,capturePointer/scylla,acbellini/scylla,shaunstanislaus/scylla,asias/scylla,avikivity/scylla,tempbottle/scylla,capturePointer/scylla,raphaelsc/scylla,senseb/scylla,wildinto/scylla,scylladb/scylla,tempbottle/scylla,phonkee/scylla,eklitzke/scylla,kangkot/scylla,dwdm/scylla,victorbriz/scylla,scylladb/scylla,justintung/scylla,wildinto/scylla,glommer/scylla,dwdm/scylla,justintung/scylla,justintung/scylla,kjniemi/scylla,guiquanz/scylla,acbellini/scylla,senseb/scylla,rentongzhang/scylla,stamhe/scylla,respu/scylla,asias/scylla,gwicke/scylla,avikivity/scylla,capturePointer/scylla,scylladb/scylla,rentongzhang/scylla,stamhe/scylla,acbellini/scylla,phonkee/scylla,duarten/scylla,kjniemi/scylla,scylladb/scylla,tempbottle/scylla,linearregression/scylla,gwicke/scylla,stamhe/scylla,dwdm/scylla,linearregression/scylla,bowlofstew/scylla,victorbriz/scylla,linearregression/scylla,shaunstanislaus/scylla,aruanruan/scylla,senseb/scylla,avikivity/scylla,rentongzhang/scylla,bowlofstew/scylla,glommer/scylla,eklitzke/scylla,aruanruan/scylla,wildinto/scylla,aruanruan/scylla,rluta/scylla,rluta/scylla,asias/scylla,bowlofstew/scylla,raphaelsc/scylla,respu/scylla,raphaelsc/scylla,duarten/scylla,kangkot/scylla,gwicke/scylla,kjniemi/scylla,eklitzke/scylla,respu/scylla,rluta/scylla
9104ed99e542e291a6484c6d451e73286b6225c6
rrd/src/output.cc
rrd/src/output.cc
/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <iomanip> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/rrd/cached.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" #include "com/centreon/broker/rrd/lib.hh" #include "com/centreon/broker/rrd/output.hh" #include "com/centreon/broker/storage/events.hh" #include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; /************************************** * * * Public Methods * * * **************************************/ /** * Standard constructor. * * @param[in] metrics_path Path in which metrics RRD files should be * written. * @param[in] status_path Path in which status RRD files should be * written. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, bool write_metrics, bool write_status) : _backend(new lib), _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) {} /** * Local socket constructor. * * @param[in] metrics_path See standard constructor. * @param[in] status_path See standard constructor. * @param[in] local Local socket connection parameters. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, QString const& local, bool write_metrics, bool write_status) : _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) { #if QT_VERSION >= 0x040400 std::auto_ptr<cached> rrdcached(new cached); rrdcached->connect_local(local); _backend.reset(rrdcached.release()); #else throw (broker::exceptions::msg() << "RRD: local connection is not supported on Qt " << QT_VERSION_STR); #endif // Qt version } /** * Network socket constructor. * * @param[in] metrics_path See standard constructor. * @param[in] status_path See standard constructor. * @param[in] port rrdcached listening port. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, unsigned short port, bool write_metrics, bool write_status) : _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) { std::auto_ptr<cached> rrdcached(new cached); rrdcached->connect_remote("localhost", port); _backend.reset(rrdcached.release()); } /** * Destructor. */ output::~output() {} /** * Set if output should be processed or not. * * @param[in] in Unused. * @param[in] out Set to true to process output events. */ void output::process(bool in, bool out) { (void)in; _process_out = out; return ; } /** * Read data. * * @param[out] d Cleared. */ void output::read(misc::shared_ptr<io::data>& d) { d.clear(); throw (broker::exceptions::msg() << "RRD: attempt to read from endpoint (not supported yet)"); return ; } /** * Write an event. * * @param[in] d Data to write. */ void output::write(misc::shared_ptr<io::data> const& d) { // Check that data exists and should be processed. if (!_process_out) throw (io::exceptions::shutdown(true, true) << "RRD output is shutdown"); if (d.isNull()) return ; if (d->type() == "com::centreon::broker::storage::metric") { if (_write_metrics) { // Debug message. misc::shared_ptr<storage::metric> e(d.staticCast<storage::metric>()); logging::debug(logging::medium) << "RRD: new data for metric " << e->metric_id << " (time " << e->ctime << ") " << (e->is_for_rebuild ? "for rebuild" : ""); // Metric path. QString metric_path; { std::ostringstream oss; oss << _metrics_path.toStdString() << "/" << e->metric_id << ".rrd"; metric_path = oss.str().c_str(); } // Check that metric is not being rebuild. rebuild_cache::iterator it(_metrics_rebuild.find(metric_path)); if (e->is_for_rebuild || it == _metrics_rebuild.end()) { // Write metrics RRD. try { _backend->open(metric_path, e->name); } catch (exceptions::open const& b) { _backend->open( metric_path, e->name, e->rrd_len / (e->interval ? e->interval : 60) + 1, 0, e->interval, e->value_type); } std::ostringstream oss; if (e->value_type != storage::perfdata::gauge) oss << static_cast<long long>(e->value); else oss << std::fixed << e->value; _backend->update(e->ctime, oss.str().c_str()); } else // Cache value. it->push_back(d); } } else if (d->type() == "com::centreon::broker::storage::status") { if (_write_status) { // Debug message. misc::shared_ptr<storage::status> e(d.staticCast<storage::status>()); logging::debug(logging::medium) << "RRD: new status data for index " << e->index_id << " (" << e->state << ") " << (e->is_for_rebuild ? "for rebuild" : ""); // Status path. QString status_path; { std::ostringstream oss; oss << _status_path.toStdString() << "/" << e->index_id << ".rrd"; status_path = oss.str().c_str(); } // Check that status is not begin rebuild. rebuild_cache::iterator it(_status_rebuild.find(status_path)); if (e->is_for_rebuild || it == _status_rebuild.end()) { // Write status RRD. try { _backend->open(status_path, "status"); } catch (exceptions::open const& b) { _backend->open( status_path, "status", e->rrd_len / (e->interval ? e->interval : 60), 0, e->interval); } std::ostringstream oss; if (e->state == 0) oss << 100; else if (e->state == 1) oss << 75; else if (e->state == 2) oss << 0; _backend->update(e->ctime, oss.str().c_str()); } else // Cache value. it->push_back(d); } } else if (d->type() == "com::centreon::broker::storage::rebuild") { // Debug message. misc::shared_ptr<storage::rebuild> e(d.staticCast<storage::rebuild>()); logging::debug(logging::medium) << "RRD: rebuild request for " << (e->is_index ? "index " : "metric ") << e->id << (e->end ? "(end)" : "(start)"); // Generate path. QString path; { std::ostringstream oss; oss << (e->is_index ? _status_path : _metrics_path).toStdString() << "/" << e->id << ".rrd"; path = oss.str().c_str(); } // Rebuild is starting. if (!e->end) { if (e->is_index) _status_rebuild[path]; else _metrics_rebuild[path]; _backend->remove(path); } // Rebuild is ending. else { // Find cache. std::list<misc::shared_ptr<io::data> > l; { rebuild_cache::iterator it; if (e->is_index) { it = _status_rebuild.find(path); if (it != _status_rebuild.end()) { l = *it; _status_rebuild.erase(it); } } else { it = _metrics_rebuild.find(path); if (it != _metrics_rebuild.end()) { l = *it; _metrics_rebuild.erase(it); } } } // Resend cache data. while (!l.empty()) { write(l.front()); l.pop_front(); } } } else if (d->type() == "com::centreon::broker::storage::remove_graph") { // Debug message. misc::shared_ptr<storage::remove_graph> e(d.staticCast<storage::remove_graph>()); logging::debug(logging::medium) << "RRD: remove graph request for " << (e->is_index ? "index " : "metric ") << e->id; // Generate path. QString path; { std::ostringstream oss; oss << (e->is_index ? _status_path : _metrics_path).toStdString() << "/" << e->id << ".rrd"; path = oss.str().c_str(); } // Remove data from cache. rebuild_cache& cache(e->is_index ? _status_rebuild : _metrics_rebuild); rebuild_cache::iterator it(cache.find(path)); if (it != cache.end()) cache.erase(it); // Remove file. _backend->remove(path); } return ; }
/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <iomanip> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/rrd/cached.hh" #include "com/centreon/broker/rrd/exceptions/open.hh" #include "com/centreon/broker/rrd/exceptions/update.hh" #include "com/centreon/broker/rrd/lib.hh" #include "com/centreon/broker/rrd/output.hh" #include "com/centreon/broker/storage/events.hh" #include "com/centreon/broker/storage/perfdata.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; /************************************** * * * Public Methods * * * **************************************/ /** * Standard constructor. * * @param[in] metrics_path Path in which metrics RRD files should be * written. * @param[in] status_path Path in which status RRD files should be * written. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, bool write_metrics, bool write_status) : _backend(new lib), _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) {} /** * Local socket constructor. * * @param[in] metrics_path See standard constructor. * @param[in] status_path See standard constructor. * @param[in] local Local socket connection parameters. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, QString const& local, bool write_metrics, bool write_status) : _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) { #if QT_VERSION >= 0x040400 std::auto_ptr<cached> rrdcached(new cached); rrdcached->connect_local(local); _backend.reset(rrdcached.release()); #else throw (broker::exceptions::msg() << "RRD: local connection is not supported on Qt " << QT_VERSION_STR); #endif // Qt version } /** * Network socket constructor. * * @param[in] metrics_path See standard constructor. * @param[in] status_path See standard constructor. * @param[in] port rrdcached listening port. * @param[in] write_metrics Set to true if metrics graph must be * written. * @param[in] write_status Set to true if status graph must be * written. */ output::output( QString const& metrics_path, QString const& status_path, unsigned short port, bool write_metrics, bool write_status) : _metrics_path(metrics_path), _process_out(true), _status_path(status_path), _write_metrics(write_metrics), _write_status(write_status) { std::auto_ptr<cached> rrdcached(new cached); rrdcached->connect_remote("localhost", port); _backend.reset(rrdcached.release()); } /** * Destructor. */ output::~output() {} /** * Set if output should be processed or not. * * @param[in] in Unused. * @param[in] out Set to true to process output events. */ void output::process(bool in, bool out) { (void)in; _process_out = out; return ; } /** * Read data. * * @param[out] d Cleared. */ void output::read(misc::shared_ptr<io::data>& d) { d.clear(); throw (broker::exceptions::msg() << "RRD: attempt to read from endpoint (not supported yet)"); return ; } /** * Write an event. * * @param[in] d Data to write. */ void output::write(misc::shared_ptr<io::data> const& d) { // Check that data exists and should be processed. if (!_process_out) throw (io::exceptions::shutdown(true, true) << "RRD output is shutdown"); if (d.isNull()) return ; if (d->type() == "com::centreon::broker::storage::metric") { if (_write_metrics) { // Debug message. misc::shared_ptr<storage::metric> e(d.staticCast<storage::metric>()); logging::debug(logging::medium) << "RRD: new data for metric " << e->metric_id << " (time " << e->ctime << ") " << (e->is_for_rebuild ? "for rebuild" : ""); // Metric path. QString metric_path; { std::ostringstream oss; oss << _metrics_path.toStdString() << e->metric_id << ".rrd"; metric_path = oss.str().c_str(); } // Check that metric is not being rebuild. rebuild_cache::iterator it(_metrics_rebuild.find(metric_path)); if (e->is_for_rebuild || it == _metrics_rebuild.end()) { // Write metrics RRD. try { _backend->open(metric_path, e->name); } catch (exceptions::open const& b) { _backend->open( metric_path, e->name, e->rrd_len / (e->interval ? e->interval : 60) + 1, 0, e->interval, e->value_type); } std::ostringstream oss; if (e->value_type != storage::perfdata::gauge) oss << static_cast<long long>(e->value); else oss << std::fixed << e->value; _backend->update(e->ctime, oss.str().c_str()); } else // Cache value. it->push_back(d); } } else if (d->type() == "com::centreon::broker::storage::status") { if (_write_status) { // Debug message. misc::shared_ptr<storage::status> e(d.staticCast<storage::status>()); logging::debug(logging::medium) << "RRD: new status data for index " << e->index_id << " (" << e->state << ") " << (e->is_for_rebuild ? "for rebuild" : ""); // Status path. QString status_path; { std::ostringstream oss; oss << _status_path.toStdString() << e->index_id << ".rrd"; status_path = oss.str().c_str(); } // Check that status is not begin rebuild. rebuild_cache::iterator it(_status_rebuild.find(status_path)); if (e->is_for_rebuild || it == _status_rebuild.end()) { // Write status RRD. try { _backend->open(status_path, "status"); } catch (exceptions::open const& b) { _backend->open( status_path, "status", e->rrd_len / (e->interval ? e->interval : 60), 0, e->interval); } std::ostringstream oss; if (e->state == 0) oss << 100; else if (e->state == 1) oss << 75; else if (e->state == 2) oss << 0; _backend->update(e->ctime, oss.str().c_str()); } else // Cache value. it->push_back(d); } } else if (d->type() == "com::centreon::broker::storage::rebuild") { // Debug message. misc::shared_ptr<storage::rebuild> e(d.staticCast<storage::rebuild>()); logging::debug(logging::medium) << "RRD: rebuild request for " << (e->is_index ? "index " : "metric ") << e->id << (e->end ? "(end)" : "(start)"); // Generate path. QString path; { std::ostringstream oss; oss << (e->is_index ? _status_path : _metrics_path).toStdString() << e->id << ".rrd"; path = oss.str().c_str(); } // Rebuild is starting. if (!e->end) { if (e->is_index) _status_rebuild[path]; else _metrics_rebuild[path]; _backend->remove(path); } // Rebuild is ending. else { // Find cache. std::list<misc::shared_ptr<io::data> > l; { rebuild_cache::iterator it; if (e->is_index) { it = _status_rebuild.find(path); if (it != _status_rebuild.end()) { l = *it; _status_rebuild.erase(it); } } else { it = _metrics_rebuild.find(path); if (it != _metrics_rebuild.end()) { l = *it; _metrics_rebuild.erase(it); } } } // Resend cache data. while (!l.empty()) { write(l.front()); l.pop_front(); } } } else if (d->type() == "com::centreon::broker::storage::remove_graph") { // Debug message. misc::shared_ptr<storage::remove_graph> e(d.staticCast<storage::remove_graph>()); logging::debug(logging::medium) << "RRD: remove graph request for " << (e->is_index ? "index " : "metric ") << e->id; // Generate path. QString path; { std::ostringstream oss; oss << (e->is_index ? _status_path : _metrics_path).toStdString() << e->id << ".rrd"; path = oss.str().c_str(); } // Remove data from cache. rebuild_cache& cache(e->is_index ? _status_rebuild : _metrics_rebuild); rebuild_cache::iterator it(cache.find(path)); if (it != cache.end()) cache.erase(it); // Remove file. _backend->remove(path); } return ; }
fix the double slash issue. This refs #4126.
RRD: fix the double slash issue. This refs #4126.
C++
apache-2.0
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker