text
stringlengths
54
60.6k
<commit_before>/* * Copyright (C) 2007 Apple 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 "config.h" #include "LocalizedStrings.h" #include "PlatformString.h" #include "IntSize.h" #undef LOG #include "webkit/glue/glue_util.h" #include "webkit/glue/webkit_glue.h" #include "base/logging.h" #include "base/file_util.h" #include "base/string_util.h" #include "build/build_config.h" #include "webkit/glue/glue_util.h" #if defined(OS_WIN) #include "webkit_strings.h" #else // TODO:(pinkerton): only windows has the GRIT machinery, so we've created a // temporary generated header until we can figure out the l10n strategy. #include "bogus_webkit_strings.h" #endif using namespace WebCore; inline String GetLocalizedString(int message_id) { const std::wstring& str(webkit_glue::GetLocalizedString(message_id)); return webkit_glue::StdWStringToString(str); } String WebCore::searchableIndexIntroduction() { return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO); } String WebCore::submitButtonDefaultLabel() { return GetLocalizedString(IDS_FORM_SUBMIT_LABEL); } String WebCore::inputElementAltText() { return GetLocalizedString(IDS_FORM_INPUT_ALT); } String WebCore::resetButtonDefaultLabel() { return GetLocalizedString(IDS_FORM_RESET_LABEL); } String WebCore::fileButtonChooseFileLabel() { return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL); } String WebCore::fileButtonNoFileSelectedLabel() { return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL); } String WebCore::searchMenuNoRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES_NONE); } String WebCore::searchMenuRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES); } String WebCore::searchMenuClearRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR); } // A11y strings. String WebCore::AXWebAreaText() { return GetLocalizedString(IDS_AX_ROLE_WEB_AREA); } String WebCore::AXLinkText() { return GetLocalizedString(IDS_AX_ROLE_LINK); } String WebCore::AXListMarkerText() { return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER); } String WebCore::AXImageMapText() { return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP); } String WebCore::AXHeadingText() { return GetLocalizedString(IDS_AX_ROLE_HEADING); } String WebCore::AXButtonActionVerb() { return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB); } String WebCore::AXRadioButtonActionVerb() { return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB); } String WebCore::AXTextFieldActionVerb() { return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB); } String WebCore::AXCheckedCheckBoxActionVerb() { return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB); } String WebCore::AXUncheckedCheckBoxActionVerb() { return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB); } String WebCore::AXLinkActionVerb() { return GetLocalizedString(IDS_AX_LINK_ACTION_VERB); } // Used in FTPDirectoryDocument.cpp String WebCore::unknownFileSizeText() { return String(); } // These two are used in FileChooserWin.cpp. #if PLATFORM(WIN) String WebCore::uploadFileText() { return String(); } String WebCore::allFilesText() { return String(); } #endif // The following two functions are not declared in LocalizedStrings.h. // They are used by the menu for the HTML keygen tag. namespace WebCore { String keygenMenuHighGradeKeySize() { return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY); } String keygenMenuMediumGradeKeySize() { return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY); } // Used in ImageDocument.cpp as the title for pages when that page is an image. String imageTitle(const String& filename, const IntSize& size) { // C3 97 is UTF-8 for U+00D7 (multiplication sign). std::string size_str = StringPrintf(" (%d\xC3\x97%d)", size.width(), size.height()); return filename + webkit_glue::StdStringToString(size_str); } } //namespace WebCore // We don't use these strings, so they return an empty String. We can't just // make them asserts because webcore still calls them. String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); } String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); } String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); } String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); } String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); } String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); } String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); } String WebCore::contextMenuItemTagCopy() { return String(); } String WebCore::contextMenuItemTagGoBack() { return String(); } String WebCore::contextMenuItemTagGoForward() { return String(); } String WebCore::contextMenuItemTagStop() { return String(); } String WebCore::contextMenuItemTagReload() { return String(); } String WebCore::contextMenuItemTagCut() { return String(); } String WebCore::contextMenuItemTagPaste() { return String(); } String WebCore::contextMenuItemTagNoGuessesFound() { return String(); } String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); } String WebCore::contextMenuItemTagLearnSpelling() { return String(); } String WebCore::contextMenuItemTagSearchWeb() { return String(); } String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); } String WebCore::contextMenuItemTagOpenLink() { return String(); } String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); } String WebCore::contextMenuItemTagSpellingMenu() { return String(); } String WebCore::contextMenuItemTagCheckSpelling() { return String(); } String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); } String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); } String WebCore::contextMenuItemTagFontMenu() { return String(); } String WebCore::contextMenuItemTagBold() { return String(); } String WebCore::contextMenuItemTagItalic() { return String(); } String WebCore::contextMenuItemTagUnderline() { return String(); } String WebCore::contextMenuItemTagOutline() { return String(); } String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); } String WebCore::contextMenuItemTagDefaultDirection() { return String(); } String WebCore::contextMenuItemTagLeftToRight() { return String(); } String WebCore::contextMenuItemTagRightToLeft() { return String(); } String WebCore::contextMenuItemTagInspectElement() { return String(); } String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); } <commit_msg>Revert r3564, "We want these symbols on all platforms."<commit_after>/* * Copyright (C) 2007 Apple 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 "config.h" #include "LocalizedStrings.h" #include "PlatformString.h" #include "IntSize.h" #undef LOG #include "webkit/glue/glue_util.h" #include "webkit/glue/webkit_glue.h" #include "base/logging.h" #include "base/file_util.h" #include "base/string_util.h" #include "build/build_config.h" #include "webkit/glue/glue_util.h" #if defined(OS_WIN) #include "webkit_strings.h" #else // TODO:(pinkerton): only windows has the GRIT machinery, so we've created a // temporary generated header until we can figure out the l10n strategy. #include "bogus_webkit_strings.h" #endif using namespace WebCore; inline String GetLocalizedString(int message_id) { const std::wstring& str(webkit_glue::GetLocalizedString(message_id)); return webkit_glue::StdWStringToString(str); } #if defined(OS_WIN) String WebCore::searchableIndexIntroduction() { return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO); } String WebCore::submitButtonDefaultLabel() { return GetLocalizedString(IDS_FORM_SUBMIT_LABEL); } String WebCore::inputElementAltText() { return GetLocalizedString(IDS_FORM_INPUT_ALT); } String WebCore::resetButtonDefaultLabel() { return GetLocalizedString(IDS_FORM_RESET_LABEL); } String WebCore::fileButtonChooseFileLabel() { return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL); } String WebCore::fileButtonNoFileSelectedLabel() { return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL); } String WebCore::searchMenuNoRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES_NONE); } String WebCore::searchMenuRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES); } String WebCore::searchMenuClearRecentSearchesText() { return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR); } // A11y strings. String WebCore::AXWebAreaText() { return GetLocalizedString(IDS_AX_ROLE_WEB_AREA); } String WebCore::AXLinkText() { return GetLocalizedString(IDS_AX_ROLE_LINK); } String WebCore::AXListMarkerText() { return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER); } String WebCore::AXImageMapText() { return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP); } String WebCore::AXHeadingText() { return GetLocalizedString(IDS_AX_ROLE_HEADING); } #endif // OS_WIN String WebCore::AXButtonActionVerb() { return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB); } String WebCore::AXRadioButtonActionVerb() { return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB); } String WebCore::AXTextFieldActionVerb() { return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB); } String WebCore::AXCheckedCheckBoxActionVerb() { return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB); } String WebCore::AXUncheckedCheckBoxActionVerb() { return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB); } String WebCore::AXLinkActionVerb() { return GetLocalizedString(IDS_AX_LINK_ACTION_VERB); } // Used in FTPDirectoryDocument.cpp String WebCore::unknownFileSizeText() { return String(); } // These two are used in FileChooserWin.cpp. #if PLATFORM(WIN) String WebCore::uploadFileText() { return String(); } String WebCore::allFilesText() { return String(); } #endif // The following two functions are not declared in LocalizedStrings.h. // They are used by the menu for the HTML keygen tag. namespace WebCore { String keygenMenuHighGradeKeySize() { return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY); } String keygenMenuMediumGradeKeySize() { return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY); } // Used in ImageDocument.cpp as the title for pages when that page is an image. String imageTitle(const String& filename, const IntSize& size) { // C3 97 is UTF-8 for U+00D7 (multiplication sign). std::string size_str = StringPrintf(" (%d\xC3\x97%d)", size.width(), size.height()); return filename + webkit_glue::StdStringToString(size_str); } } //namespace WebCore #if defined(OS_WIN) // We don't use these strings, so they return an empty String. We can't just // make them asserts because webcore still calls them. String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); } String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); } String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); } String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); } String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); } String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); } String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); } String WebCore::contextMenuItemTagCopy() { return String(); } String WebCore::contextMenuItemTagGoBack() { return String(); } String WebCore::contextMenuItemTagGoForward() { return String(); } String WebCore::contextMenuItemTagStop() { return String(); } String WebCore::contextMenuItemTagReload() { return String(); } String WebCore::contextMenuItemTagCut() { return String(); } String WebCore::contextMenuItemTagPaste() { return String(); } String WebCore::contextMenuItemTagNoGuessesFound() { return String(); } String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); } String WebCore::contextMenuItemTagLearnSpelling() { return String(); } String WebCore::contextMenuItemTagSearchWeb() { return String(); } String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); } String WebCore::contextMenuItemTagOpenLink() { return String(); } String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); } String WebCore::contextMenuItemTagSpellingMenu() { return String(); } String WebCore::contextMenuItemTagCheckSpelling() { return String(); } String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); } String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); } String WebCore::contextMenuItemTagFontMenu() { return String(); } String WebCore::contextMenuItemTagBold() { return String(); } String WebCore::contextMenuItemTagItalic() { return String(); } String WebCore::contextMenuItemTagUnderline() { return String(); } String WebCore::contextMenuItemTagOutline() { return String(); } String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); } String WebCore::contextMenuItemTagDefaultDirection() { return String(); } String WebCore::contextMenuItemTagLeftToRight() { return String(); } String WebCore::contextMenuItemTagRightToLeft() { return String(); } String WebCore::contextMenuItemTagInspectElement() { return String(); } String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); } #endif // OS_WIN <|endoftext|>
<commit_before>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkBrokenLineWidget.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkDataSetMapper.h" #include "vtkExtractSelection.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProgrammableFilter.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTextActor.h" #include "vtkTextProperty.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" #include "vtkTestUtilities.h" #include <vtksys/ios/sstream> // Callback for the broken line widget interaction class vtkBLWCallback : public vtkCommand { public: static vtkBLWCallback *New() { return new vtkBLWCallback; } virtual void Execute( vtkObject *caller, unsigned long, void* ) { // Retrieve polydata line vtkBrokenLineWidget *line = reinterpret_cast<vtkBrokenLineWidget*>( caller ); line->GetPolyData( Poly ); // Update linear extractor with current points this->Selector->SetPoints( Poly->GetPoints() ); // Update selection from mesh this->Extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( this->Extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); this->Mapper->SetInput( selection ); // Update cardinality of selection vtksys_ios::ostringstream txt; txt << "Number of selected elements:" << ( selection ? selection->GetNumberOfCells() : 0 ); this->Text->SetInput( txt.str().c_str() ); } vtkBLWCallback():Poly(0),Selector(0),Extractor(0),Mapper(0),Text(0) {}; vtkPolyData* Poly; vtkLinearExtractor* Selector; vtkExtractSelection* Extractor; vtkDataSetMapper* Mapper; vtkTextActor* Text; }; int TestBrokenLineWidget( int argc, char *argv[] ) { // Create render window and interactor vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New(); win->SetMultiSamples( 0 ); win->SetSize( 600, 300 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( win ); iren->Initialize(); // Create 2 viewports in window vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .4, .4, .4 ); ren1->SetBackground2( .8, .8, .8 ); ren1->GradientBackgroundOn(); ren1->SetViewport( 0., 0., .5, 1. ); win->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderer> ren2 = vtkSmartPointer<vtkRenderer>::New(); ren2->SetBackground( 1., 1., 1. ); ren2->SetViewport( .5, 0., 1., 1. ); win->AddRenderer( ren2 ); // Create a good view angle vtkCamera* camera = ren1->GetActiveCamera(); camera->SetFocalPoint( .12, 0., 0. ); camera->SetPosition( .38, .3, .15 ); camera->SetViewUp( 0., 0., 1. ); ren2->SetActiveCamera( camera ); // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); delete [] fileName; reader->Update(); // Create mesh actor to be rendered in viewport 1 vtkSmartPointer<vtkDataSetMapper> meshMapper = vtkSmartPointer<vtkDataSetMapper>::New(); meshMapper->SetInputConnection( reader->GetOutputPort() ); vtkSmartPointer<vtkActor> meshActor = vtkSmartPointer<vtkActor>::New(); meshActor->SetMapper( meshMapper ); meshActor->GetProperty()->SetColor( .23, .37, .17 ); meshActor->GetProperty()->SetRepresentationToWireframe(); ren1->AddActor( meshActor ); // Create multi-block mesh for linear extractor reader->Update(); vtkUnstructuredGrid* mesh = reader->GetOutput(); vtkSmartPointer<vtkMultiBlockDataSet> meshMB = vtkSmartPointer<vtkMultiBlockDataSet>::New(); meshMB->SetNumberOfBlocks( 1 ); meshMB->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); meshMB->SetBlock( 0, mesh ); // Create broken line widget, attach it to input mesh vtkSmartPointer<vtkBrokenLineWidget> line = vtkSmartPointer<vtkBrokenLineWidget>::New(); line->SetInteractor( iren ); line->SetInput( mesh ); line->SetPriority( 1. ); line->KeyPressActivationOff(); line->PlaceWidget(); line->ProjectToPlaneOff(); line->On(); line->SetHandleSizeFactor( 1.2 ); // Create list of points to define broken line vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint( .23, .0, .0 ); points->InsertNextPoint( .0, .0, .0 ); points->InsertNextPoint( .23, .04, .04 ); line->InitializeHandles( points ); // Extract polygonal line and then its points vtkSmartPointer<vtkPolyData> linePD = vtkSmartPointer<vtkPolyData>::New(); line->GetPolyData( linePD ); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lineMapper->SetInput( linePD ); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); lineActor->SetMapper( lineMapper ); lineActor->GetProperty()->SetColor( 1., 0., 0. ); lineActor->GetProperty()->SetLineWidth( 2. ); ren2->AddActor( lineActor ); // Create selection along broken line defined by list of points vtkSmartPointer<vtkLinearExtractor> selector = vtkSmartPointer<vtkLinearExtractor>::New(); selector->SetInput( meshMB ); selector->SetPoints( points ); selector->IncludeVerticesOff(); selector->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New(); extractor->SetInput( 0, meshMB ); extractor->SetInputConnection( 1, selector->GetOutputPort() ); extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); // Create selection actor vtkSmartPointer<vtkDataSetMapper> selMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selMapper->SetInput( selection ); vtkSmartPointer<vtkActor> selActor = vtkSmartPointer<vtkActor>::New(); selActor->SetMapper( selMapper ); selActor->GetProperty()->SetColor( 0., 0., 0. ); selActor->GetProperty()->SetRepresentationToWireframe(); ren2->AddActor( selActor ); // Annotate with number of elements vtkSmartPointer<vtkTextActor> txtActor = vtkSmartPointer<vtkTextActor>::New(); vtksys_ios::ostringstream txt; txt << "Number of selected elements:" << ( selection ? selection->GetNumberOfCells() : 0 ); txtActor->SetInput( txt.str().c_str() ); txtActor->SetTextScaleModeToViewport(); txtActor->SetNonLinearFontScale( .2, 18 ); txtActor->GetTextProperty()->SetColor( 0., 0., 1. ); txtActor->GetTextProperty()->SetFontSize( 18 ); ren2->AddActor( txtActor ); // Invoke callback on polygonal line to interactively select elements vtkSmartPointer<vtkBLWCallback> cb = vtkSmartPointer<vtkBLWCallback>::New(); cb->Poly = linePD; cb->Selector = selector; cb->Extractor = extractor; cb->Mapper = selMapper; cb->Text = txtActor; line->AddObserver( vtkCommand::InteractionEvent, cb ); // Render and test win->Render(); int retVal = vtkRegressionTestImage( win ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } return !retVal; } <commit_msg>Add space in selection application text<commit_after>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkBrokenLineWidget.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkDataSetMapper.h" #include "vtkExtractSelection.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProgrammableFilter.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTextActor.h" #include "vtkTextProperty.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" #include "vtkTestUtilities.h" #include <vtksys/ios/sstream> // Callback for the broken line widget interaction class vtkBLWCallback : public vtkCommand { public: static vtkBLWCallback *New() { return new vtkBLWCallback; } virtual void Execute( vtkObject *caller, unsigned long, void* ) { // Retrieve polydata line vtkBrokenLineWidget *line = reinterpret_cast<vtkBrokenLineWidget*>( caller ); line->GetPolyData( Poly ); // Update linear extractor with current points this->Selector->SetPoints( Poly->GetPoints() ); // Update selection from mesh this->Extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( this->Extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); this->Mapper->SetInput( selection ); // Update cardinality of selection vtksys_ios::ostringstream txt; txt << "Number of selected elements: " << ( selection ? selection->GetNumberOfCells() : 0 ); this->Text->SetInput( txt.str().c_str() ); } vtkBLWCallback():Poly(0),Selector(0),Extractor(0),Mapper(0),Text(0) {}; vtkPolyData* Poly; vtkLinearExtractor* Selector; vtkExtractSelection* Extractor; vtkDataSetMapper* Mapper; vtkTextActor* Text; }; int TestBrokenLineWidget( int argc, char *argv[] ) { // Create render window and interactor vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New(); win->SetMultiSamples( 0 ); win->SetSize( 600, 300 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( win ); iren->Initialize(); // Create 2 viewports in window vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .4, .4, .4 ); ren1->SetBackground2( .8, .8, .8 ); ren1->GradientBackgroundOn(); ren1->SetViewport( 0., 0., .5, 1. ); win->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderer> ren2 = vtkSmartPointer<vtkRenderer>::New(); ren2->SetBackground( 1., 1., 1. ); ren2->SetViewport( .5, 0., 1., 1. ); win->AddRenderer( ren2 ); // Create a good view angle vtkCamera* camera = ren1->GetActiveCamera(); camera->SetFocalPoint( .12, 0., 0. ); camera->SetPosition( .38, .3, .15 ); camera->SetViewUp( 0., 0., 1. ); ren2->SetActiveCamera( camera ); // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); delete [] fileName; reader->Update(); // Create mesh actor to be rendered in viewport 1 vtkSmartPointer<vtkDataSetMapper> meshMapper = vtkSmartPointer<vtkDataSetMapper>::New(); meshMapper->SetInputConnection( reader->GetOutputPort() ); vtkSmartPointer<vtkActor> meshActor = vtkSmartPointer<vtkActor>::New(); meshActor->SetMapper( meshMapper ); meshActor->GetProperty()->SetColor( .23, .37, .17 ); meshActor->GetProperty()->SetRepresentationToWireframe(); ren1->AddActor( meshActor ); // Create multi-block mesh for linear extractor reader->Update(); vtkUnstructuredGrid* mesh = reader->GetOutput(); vtkSmartPointer<vtkMultiBlockDataSet> meshMB = vtkSmartPointer<vtkMultiBlockDataSet>::New(); meshMB->SetNumberOfBlocks( 1 ); meshMB->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); meshMB->SetBlock( 0, mesh ); // Create broken line widget, attach it to input mesh vtkSmartPointer<vtkBrokenLineWidget> line = vtkSmartPointer<vtkBrokenLineWidget>::New(); line->SetInteractor( iren ); line->SetInput( mesh ); line->SetPriority( 1. ); line->KeyPressActivationOff(); line->PlaceWidget(); line->ProjectToPlaneOff(); line->On(); line->SetHandleSizeFactor( 1.2 ); // Create list of points to define broken line vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint( .23, .0, .0 ); points->InsertNextPoint( .0, .0, .0 ); points->InsertNextPoint( .23, .04, .04 ); line->InitializeHandles( points ); // Extract polygonal line and then its points vtkSmartPointer<vtkPolyData> linePD = vtkSmartPointer<vtkPolyData>::New(); line->GetPolyData( linePD ); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lineMapper->SetInput( linePD ); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); lineActor->SetMapper( lineMapper ); lineActor->GetProperty()->SetColor( 1., 0., 0. ); lineActor->GetProperty()->SetLineWidth( 2. ); ren2->AddActor( lineActor ); // Create selection along broken line defined by list of points vtkSmartPointer<vtkLinearExtractor> selector = vtkSmartPointer<vtkLinearExtractor>::New(); selector->SetInput( meshMB ); selector->SetPoints( points ); selector->IncludeVerticesOff(); selector->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New(); extractor->SetInput( 0, meshMB ); extractor->SetInputConnection( 1, selector->GetOutputPort() ); extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); // Create selection actor vtkSmartPointer<vtkDataSetMapper> selMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selMapper->SetInput( selection ); vtkSmartPointer<vtkActor> selActor = vtkSmartPointer<vtkActor>::New(); selActor->SetMapper( selMapper ); selActor->GetProperty()->SetColor( 0., 0., 0. ); selActor->GetProperty()->SetRepresentationToWireframe(); ren2->AddActor( selActor ); // Annotate with number of elements vtkSmartPointer<vtkTextActor> txtActor = vtkSmartPointer<vtkTextActor>::New(); vtksys_ios::ostringstream txt; txt << "Number of selected elements: " << ( selection ? selection->GetNumberOfCells() : 0 ); txtActor->SetInput( txt.str().c_str() ); txtActor->SetTextScaleModeToViewport(); txtActor->SetNonLinearFontScale( .2, 18 ); txtActor->GetTextProperty()->SetColor( 0., 0., 1. ); txtActor->GetTextProperty()->SetFontSize( 18 ); ren2->AddActor( txtActor ); // Invoke callback on polygonal line to interactively select elements vtkSmartPointer<vtkBLWCallback> cb = vtkSmartPointer<vtkBLWCallback>::New(); cb->Poly = linePD; cb->Selector = selector; cb->Extractor = extractor; cb->Mapper = selMapper; cb->Text = txtActor; line->AddObserver( vtkCommand::InteractionEvent, cb ); // Render and test win->Render(); int retVal = vtkRegressionTestImage( win ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>//@author A0112054Y #include "stdafx.h" #include "../state.h" #include "../controller.h" #include "get_task.h" namespace You { namespace QueryEngine { namespace Internal { namespace Action { const std::wstring GetTask::logCategory = Query::logCategory + L"[GetTask]"; std::unordered_map<Task::ID, Task> GetTask::getFilteredTasks(const State& state) const { std::unordered_map<Task::ID, Task> filtered; std::vector<Task> all = state.graph().asTaskList(); for (const auto& task : all) { if (filter(task)) { filtered.insert({ task.getID(), task }); } } return filtered; } std::vector<Task> GetTask::removeTaskIfParentIsShown( std::unordered_map<Task::ID, Task>& filtered) const { std::vector<Task> result; for (const auto& r : filtered) { // Always show toplevel task. if (r.second.isTopLevel()) { result.push_back(r.second); } else { // Show child task iff the parent is not filtered. auto parent = r.second.getParent(); bool parentIsAlreadyFiltered = filtered.find(parent) != filtered.end(); if (!parentIsAlreadyFiltered) { result.push_back(r.second); } } } return result; } void GetTask::sortTheResultIfRequested(std::vector<Task>& result) const { if (!comparator.isDefault()) { std::remove_if(begin(result), end(result), Filter::completed()); std::sort(begin(result), end(result), comparator); } else { std::sort(begin(result), end(result), Comparator::byTimeCreated()); } } void GetTask::updateActiveFilterAndSorter(State& state) const { state.setActiveComparator(comparator); state.setActiveFilter(filter); } Response GetTask::execute(State& state) { std::unordered_map<Task::ID, Task> filtered = getFilteredTasks(state); std::vector<Task> result = removeTaskIfParentIsShown(filtered); sortTheResultIfRequested(result); updateActiveFilterAndSorter(state); return result; } } // namespace Action } // namespace Internal } // namespace QueryEngine } // namespace You <commit_msg>Fixes #378<commit_after>//@author A0112054Y #include "stdafx.h" #include "../state.h" #include "../controller.h" #include "get_task.h" namespace You { namespace QueryEngine { namespace Internal { namespace Action { const std::wstring GetTask::logCategory = Query::logCategory + L"[GetTask]"; std::unordered_map<Task::ID, Task> GetTask::getFilteredTasks(const State& state) const { std::unordered_map<Task::ID, Task> filtered; std::vector<Task> all = state.graph().asTaskList(); for (const auto& task : all) { if (filter(task)) { filtered.insert({ task.getID(), task }); } } return filtered; } std::vector<Task> GetTask::removeTaskIfParentIsShown( std::unordered_map<Task::ID, Task>& filtered) const { std::vector<Task> result; for (const auto& r : filtered) { // Always show toplevel task. if (r.second.isTopLevel()) { result.push_back(r.second); } else { // Show child task iff the parent is not filtered. auto parent = r.second.getParent(); bool parentIsAlreadyFiltered = filtered.find(parent) != filtered.end(); if (!parentIsAlreadyFiltered) { result.push_back(r.second); } } } return result; } void GetTask::sortTheResultIfRequested(std::vector<Task>& result) const { if (!comparator.isDefault()) { std::sort(begin(result), end(result), comparator); } else { std::sort(begin(result), end(result), Comparator::byTimeCreated()); } } void GetTask::updateActiveFilterAndSorter(State& state) const { state.setActiveComparator(comparator); state.setActiveFilter(filter); } Response GetTask::execute(State& state) { std::unordered_map<Task::ID, Task> filtered = getFilteredTasks(state); std::vector<Task> result = removeTaskIfParentIsShown(filtered); sortTheResultIfRequested(result); updateActiveFilterAndSorter(state); return result; } } // namespace Action } // namespace Internal } // namespace QueryEngine } // namespace You <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "mtac/dominators.hpp" using namespace eddic; void mtac::compute_dominators(std::shared_ptr<Function> function){ } <commit_msg>Compute the immediate dominators of each basic blocks using Lengauer and Tarjan algorithm<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <vector> #include <unordered_map> #include "mtac/dominators.hpp" using namespace eddic; struct dominators { unsigned int* parent; unsigned int* semi; unsigned int* vertex; unsigned int* dom; unsigned int* size; unsigned int* child; unsigned int* label; unsigned int* ancestor; std::vector<unsigned int>* pred; std::vector<unsigned int>* succ; std::vector<unsigned int>* bucket; const std::size_t cn; std::shared_ptr<mtac::Function> function; std::unordered_map<std::shared_ptr<mtac::BasicBlock>, unsigned int> numbers; dominators(std::size_t cn, std::shared_ptr<mtac::Function>) : cn(cn), function(function) { parent = new unsigned int[cn+1]; semi = new unsigned int[cn+1]; vertex = new unsigned int[cn+1]; dom = new unsigned int[cn+1]; size = new unsigned int[cn+1]; child = new unsigned int[cn+1]; label = new unsigned int[cn+1]; ancestor = new unsigned int[cn+1]; succ = new std::vector<unsigned int>[cn+1]; pred = new std::vector<unsigned int>[cn+1]; bucket = new std::vector<unsigned int>[cn+1]; } ~dominators(){ delete[] parent; delete[] semi; delete[] vertex; delete[] dom; delete[] size; delete[] child; delete[] label; delete[] ancestor; delete[] bucket; delete[] pred; delete[] succ; } unsigned int n = 0; void dfs(unsigned int v){ semi[v] = ++n; vertex[n] = label[v] = v; ancestor[v] = child[v] =0; size[v] = 1; for(auto w : succ[v]){ if(semi[w] == 0){ parent[w] = v; dfs(w); } pred[w].push_back(v); } } void compress(unsigned int v){ if(ancestor[ancestor[v]] != 0){ compress(ancestor[v]); if(semi[label[ancestor[v]]] < semi[label[v]]){ label[v] = label[ancestor[v]]; } ancestor[v] = ancestor[ancestor[v]]; } } unsigned int eval(unsigned int v){ if(ancestor[v] == 0){ return label[v]; } else { compress(v); if(semi[label[ancestor[v]]] > semi[label[v]]){ return label[v]; } else { return label[ancestor[v]]; } } } void link(unsigned int v, unsigned int w){ unsigned int s = w; while(semi[label[w]] < semi[label[child[s]]]){ if(size[s] + size[child[child[s]]] >= 2 * size[child[s]]){ ancestor[child[s]] = s; child[s] = child[child[s]]; } else { size[child[s]] = size[s]; s = ancestor[s] = child[s]; } } label[s] = label[w]; size[v] = size[v] + size[w]; if(size[v] < 2 * size[w]){ auto t = s; s = child[v]; child[v] = t; } while(s != 0){ ancestor[s] = v; s = child[s]; } } void compute_dominators(){ /* Step 0. Translate basic blocks to numbers */ unsigned int number = 0; for(auto& block : function){ numbers[block] = ++number; } number = 0; for(auto& block : function){ ++number; for(auto& s : block->successors){ succ[number].push_back(numbers[s]); } } /* Step 1. */ for(unsigned int v = 1; v <= n; ++v){ semi[v] = 0; } unsigned int n = 0; dfs(1); size[0] = label[0] = semi[0] = 0; for(unsigned int i = n; i >= 2; --i){ auto w = vertex[i]; /* Step 2 */ for(auto v : pred[w]){ auto u = eval(v); if(semi[u] < semi[w]){ semi[w] = semi[u]; } } bucket[vertex[semi[w]]].push_back(w); link(parent[w], w); /* Step 3 */ for(auto v : bucket[parent[w]]){ //remove v from bucket[parent[w]] auto u = eval(v); if(semi[u] < semi[v]){ dom[v] = u; } else { dom[v] = parent[w]; } } } /* Step 4 */ for(unsigned int i = 2; i <= n; ++i){ unsigned w = vertex[i]; if(dom[w] != vertex[semi[w]]){ dom[w] = dom[dom[w]]; } } dom[1] = 0; } }; void mtac::compute_dominators(std::shared_ptr<Function> function){ auto n = function->bb_count(); dominators dom(n, function); } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <net/http/client.hpp> namespace http { const Client::timeout_duration Client::DEFAULT_TIMEOUT{std::chrono::seconds(5)}; Client::Client(TCP& tcp, Request_handler on_send) : tcp_(tcp), on_send_{std::move(on_send)}, conns_{} { } Request_ptr Client::create_request(Method method) const { auto req = std::make_unique<Request>(); req->set_method(method); auto& header = req->header(); header.set_field(header::User_Agent, "IncludeOS/0.10"); set_connection_header(*req); return req; } void Client::send(Request_ptr req, Host host, Response_handler cb, Options options) { Expects(cb != nullptr); using namespace std; auto& conn = get_connection(host); auto&& header = req->header(); // Set Host if not already set if(! header.has_field(header::Host)) header.set_field(header::Host, host.to_string()); // Set Origin if not already set if(! header.has_field(header::Origin)) header.set_field(header::Origin, origin()); debug("<http::Client> Sending Request:\n%s\n", req->to_string().c_str()); if(on_send_) on_send_(*req, options, host); conn.send(move(req), move(cb), options.bufsize, options.timeout); } void Client::request(Method method, URI url, Header_set hfields, Response_handler cb, Options options) { Expects(cb != nullptr); using namespace std; if (url.host_is_ip4()) { std::string host = url.host().to_string(); auto ip = net::ip4::Addr(host); // setup request with method and headers auto req = create_request(method); *req << hfields; // Set Host and URI path populate_from_url(*req, url); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; send(move(req), {ip, port}, move(cb), move(options)); } else { tcp_.stack().resolve(url.host().to_string(), ResolveCallback::make_packed( [ this, method, url{move(url)}, hfields{move(hfields)}, cb{move(cb)}, opt{move(options)} ] (net::ip4::Addr ip, net::Error&) { // Host resolved if (ip != 0) { // setup request with method and headers auto req = create_request(method); *req << hfields; // Set Host and URI path populate_from_url(*req, url); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; send(move(req), {ip, port}, move(cb), move(opt)); } else { cb({Error::RESOLVE_HOST}, nullptr, Connection::empty()); } })); } } void Client::request(Method method, Host host, std::string path, Header_set hfields, Response_handler cb, Options options) { using namespace std; // setup request with method and headers auto req = create_request(method); *req << hfields; //set uri (default "/") req->set_uri((!path.empty()) ? URI{move(path)} : URI{"/"}); send(move(req), move(host), move(cb), move(options)); } void Client::request(Method method, URI url, Header_set hfields, std::string data, Response_handler cb, Options options) { using namespace std; tcp_.stack().resolve( url.host().to_string(), ResolveCallback::make_packed( [ this, method, url{move(url)}, hfields{move(hfields)}, data{move(data)}, cb{move(cb)}, opt{move(options)} ] (auto ip, net::Error&) { // Host resolved if(ip != 0) { // setup request with method and headers auto req = this->create_request(method); *req << hfields; // Set Host & path from url this->populate_from_url(*req, url); // Add data and content length this->add_data(*req, data); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; this->send(move(req), {ip, port}, move(cb), move(opt)); } else { cb({Error::RESOLVE_HOST}, nullptr, Connection::empty()); } }) ); } void Client::request(Method method, Host host, std::string path, Header_set hfields, const std::string& data, Response_handler cb, Options options) { using namespace std; // setup request with method and headers auto req = create_request(method); *req << hfields; // set uri (default "/") req->set_uri((!path.empty()) ? URI{move(path)} : URI{"/"}); // Add data and content length add_data(*req, data); send(move(req), move(host), move(cb), move(options)); } void Client::add_data(Request& req, const std::string& data) { auto& header = req.header(); if(!header.has_field(header::Content_Type)) header.set_field(header::Content_Type, "text/plain"); // Set Content-Length to be equal data length req.header().set_field(header::Content_Length, std::to_string(data.size())); // Add data req.add_body(data); } void Client::populate_from_url(Request& req, const URI& url) { // Set uri path (default "/") req.set_uri((!url.path().empty()) ? URI{url.path()} : URI{"/"}); // Set Host: host(:port) const auto port = url.port(); req.header().set_field(header::Host, (port != 0xFFFF and port != 80) ? url.host().to_string() + ":" + std::to_string(port) : url.host().to_string()); // to_string madness } void Client::resolve(const std::string& host, ResolveCallback cb) { static auto&& stack = tcp_.stack(); stack.resolve(host, cb); } Client_connection& Client::get_connection(const Host host) { // return/create a set for the given host auto& cset = conns_[host]; // iterate all the connection and return the first free one for(auto& conn : cset) { if(!conn->occupied()) return *conn; } // no non-occupied connections, emplace a new one cset.push_back(std::make_unique<Client_connection>(*this, std::make_unique<Connection::Stream>(tcp_.connect(host)))); return *cset.back(); } void Client::close(Client_connection& c) { debug("<http::Client> Closing %u:%s %p\n", c.local_port(), c.peer().to_string().c_str(), &c); auto& cset = conns_.at(c.peer()); cset.erase(std::remove_if(cset.begin(), cset.end(), [port = c.local_port()] (const std::unique_ptr<Client_connection>& conn)->bool { return conn->local_port() == port; })); } } <commit_msg>http: Fixed Client not support IP in URL when payload<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2016-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 <net/http/client.hpp> namespace http { const Client::timeout_duration Client::DEFAULT_TIMEOUT{std::chrono::seconds(5)}; Client::Client(TCP& tcp, Request_handler on_send) : tcp_(tcp), on_send_{std::move(on_send)}, conns_{} { } Request_ptr Client::create_request(Method method) const { auto req = std::make_unique<Request>(); req->set_method(method); auto& header = req->header(); header.set_field(header::User_Agent, "IncludeOS/0.10"); set_connection_header(*req); return req; } void Client::send(Request_ptr req, Host host, Response_handler cb, Options options) { Expects(cb != nullptr); using namespace std; auto& conn = get_connection(host); auto&& header = req->header(); // Set Host if not already set if(! header.has_field(header::Host)) header.set_field(header::Host, host.to_string()); // Set Origin if not already set if(! header.has_field(header::Origin)) header.set_field(header::Origin, origin()); debug("<http::Client> Sending Request:\n%s\n", req->to_string().c_str()); if(on_send_) on_send_(*req, options, host); conn.send(move(req), move(cb), options.bufsize, options.timeout); } void Client::request(Method method, URI url, Header_set hfields, Response_handler cb, Options options) { Expects(cb != nullptr); using namespace std; if (url.host_is_ip4()) { std::string host = url.host().to_string(); auto ip = net::ip4::Addr(host); // setup request with method and headers auto req = create_request(method); *req << hfields; // Set Host and URI path populate_from_url(*req, url); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; send(move(req), {ip, port}, move(cb), move(options)); } else { tcp_.stack().resolve(url.host().to_string(), ResolveCallback::make_packed( [ this, method, url{move(url)}, hfields{move(hfields)}, cb{move(cb)}, opt{move(options)} ] (net::ip4::Addr ip, net::Error&) { // Host resolved if (ip != 0) { // setup request with method and headers auto req = create_request(method); *req << hfields; // Set Host and URI path populate_from_url(*req, url); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; send(move(req), {ip, port}, move(cb), move(opt)); } else { cb({Error::RESOLVE_HOST}, nullptr, Connection::empty()); } })); } } void Client::request(Method method, Host host, std::string path, Header_set hfields, Response_handler cb, Options options) { using namespace std; // setup request with method and headers auto req = create_request(method); *req << hfields; //set uri (default "/") req->set_uri((!path.empty()) ? URI{move(path)} : URI{"/"}); send(move(req), move(host), move(cb), move(options)); } void Client::request(Method method, URI url, Header_set hfields, std::string data, Response_handler cb, Options options) { using namespace std; if (url.host_is_ip4()) { std::string host = url.host().to_string(); auto ip = net::ip4::Addr(host); // setup request with method and headers auto req = create_request(method); *req << hfields; // Set Host and URI path populate_from_url(*req, url); // Add data and content length this->add_data(*req, data); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; send(move(req), {ip, port}, move(cb), move(options)); } else { tcp_.stack().resolve( url.host().to_string(), ResolveCallback::make_packed( [ this, method, url{move(url)}, hfields{move(hfields)}, data{move(data)}, cb{move(cb)}, opt{move(options)} ] (auto ip, net::Error&) { // Host resolved if(ip != 0) { // setup request with method and headers auto req = this->create_request(method); *req << hfields; // Set Host & path from url this->populate_from_url(*req, url); // Add data and content length this->add_data(*req, data); // Default to port 80 if non given const uint16_t port = (url.port() != 0xFFFF) ? url.port() : 80; this->send(move(req), {ip, port}, move(cb), move(opt)); } else { cb({Error::RESOLVE_HOST}, nullptr, Connection::empty()); } }) ); } } void Client::request(Method method, Host host, std::string path, Header_set hfields, const std::string& data, Response_handler cb, Options options) { using namespace std; // setup request with method and headers auto req = create_request(method); *req << hfields; // set uri (default "/") req->set_uri((!path.empty()) ? URI{move(path)} : URI{"/"}); // Add data and content length add_data(*req, data); send(move(req), move(host), move(cb), move(options)); } void Client::add_data(Request& req, const std::string& data) { auto& header = req.header(); if(!header.has_field(header::Content_Type)) header.set_field(header::Content_Type, "text/plain"); // Set Content-Length to be equal data length req.header().set_field(header::Content_Length, std::to_string(data.size())); // Add data req.add_body(data); } void Client::populate_from_url(Request& req, const URI& url) { // Set uri path (default "/") req.set_uri((!url.path().empty()) ? URI{url.path()} : URI{"/"}); // Set Host: host(:port) const auto port = url.port(); req.header().set_field(header::Host, (port != 0xFFFF and port != 80) ? url.host().to_string() + ":" + std::to_string(port) : url.host().to_string()); // to_string madness } void Client::resolve(const std::string& host, ResolveCallback cb) { static auto&& stack = tcp_.stack(); stack.resolve(host, cb); } Client_connection& Client::get_connection(const Host host) { // return/create a set for the given host auto& cset = conns_[host]; // iterate all the connection and return the first free one for(auto& conn : cset) { if(!conn->occupied()) return *conn; } // no non-occupied connections, emplace a new one cset.push_back(std::make_unique<Client_connection>(*this, std::make_unique<Connection::Stream>(tcp_.connect(host)))); return *cset.back(); } void Client::close(Client_connection& c) { debug("<http::Client> Closing %u:%s %p\n", c.local_port(), c.peer().to_string().c_str(), &c); auto& cset = conns_.at(c.peer()); cset.erase(std::remove_if(cset.begin(), cset.end(), [port = c.local_port()] (const std::unique_ptr<Client_connection>& conn)->bool { return conn->local_port() == port; })); } } <|endoftext|>
<commit_before>#include <numpy_eigen/boost_python_headers.hpp> #include <sm/timing/TimestampCorrector.hpp> #include <boost/cstdint.hpp> template<typename TIME_T> void exportTimestampCorrector(const std::string & className) { using namespace boost::python; using namespace sm::timing; class_< TimestampCorrector<TIME_T> >( className.c_str(), init<>() ) .def("correctTimestamp", &TimestampCorrector<TIME_T>::correctTimestamp) .def("getLocalTime", &TimestampCorrector<TIME_T>::getLocalTime) .def("convexHullSize", &TimestampCorrector<TIME_T>::convexHullSize) .def("printHullPoints", &TimestampCorrector<TIME_T>::printHullPoints) ; } void exportTimestampCorrectors() { exportTimestampCorrector<double>("DoubleTimestampCorrector"); exportTimestampCorrector<boost::int64_t>("LongTimestampCorrector"); } <commit_msg>Added some documentation for the timestamp corrector<commit_after>#include <numpy_eigen/boost_python_headers.hpp> #include <sm/timing/TimestampCorrector.hpp> #include <boost/cstdint.hpp> template<typename TIME_T> void exportTimestampCorrector(const std::string & className) { using namespace boost::python; using namespace sm::timing; class_< TimestampCorrector<TIME_T> >( className.c_str(), init<>() ) .def("correctTimestamp", &TimestampCorrector<TIME_T>::correctTimestamp, "correctedEventLocalTime = correctTimestamp(eventRemoteTime, eventLocalTimes).\nNote: This function must be called with monotonically increasing remote timestamps.") .def("getLocalTime", &TimestampCorrector<TIME_T>::getLocalTime, "eventLocalTime = getLocalTime(eventRemoteTime)") .def("convexHullSize", &TimestampCorrector<TIME_T>::convexHullSize) .def("printHullPoints", &TimestampCorrector<TIME_T>::printHullPoints) ; } void exportTimestampCorrectors() { exportTimestampCorrector<double>("DoubleTimestampCorrector"); exportTimestampCorrector<boost::int64_t>("LongTimestampCorrector"); } <|endoftext|>
<commit_before>#include <iomanip> #include <iostream> #include <stdint.h> #include <cstdlib> #include <string> #include <sstream> #include <vector> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stropts.h> #include <cstring> #include <sys/tihdr.h> #include <inet/mib2.h> class buffer_t { public: char buffer[512]; strbuf buf; buffer_t() { memset(buffer,0,512); buf.buf=(char*)buffer; buf.len=512; } }; struct request_t { public: request_t() { req_header.PRIM_type=T_SVR4_OPTMGMT_REQ; req_header.OPT_length=sizeof(opt_header); req_header.OPT_offset=offsetof(request_t,opt_header); req_header.MGMT_flags=T_CURRENT; opt_header.level=MIB2_IP; opt_header.name=0; opt_header.len=0; } T_optmgmt_req req_header; opthdr opt_header; }; struct reply_t { T_optmgmt_ack ack_header; opthdr opt_header; }; std::string uint32_t_to_ipv4(const uint32_t address) { std::ostringstream ostr; ostr<<(uint32_t)((uint8_t*)&address)[0]<<"."<< (uint32_t)((uint8_t*)&address)[1]<<"."<< (uint32_t)((uint8_t*)&address)[2]<<"."<< (uint32_t)((uint8_t*)&address)[3]; return ostr.str(); } std::string uint8_t_16_to_ipv6(const uint8_t address[16]) { std::ostringstream ostr; for(int ii=0;ii<16;ii+=2) { ostr<<std::hex<<std::setw(2)<<std::setfill('0')<<(unsigned int)(unsigned char)address[ii+0]; ostr<<std::hex<<std::setw(2)<<std::setfill('0')<<(unsigned int)(unsigned char)address[ii+1]; if(ii<14) ostr<<":"; } return ostr.str(); } std::string dword_to_port(const uint32_t port) { std::ostringstream ostr; ostr<<((((uint32_t)((uint8_t*)&port)[0])<<8)+((uint8_t*)&port)[1]); return ostr.str(); } std::string to_string(const uint32_t val) { std::ostringstream ostr; ostr<<val; return ostr.str(); } std::string state_int_to_string(const uint32_t state) { if(state==MIB2_TCP_established) return "ESTABLISHED"; if(state==MIB2_TCP_synSent) return "SYN_SENT"; if(state==MIB2_TCP_synReceived) return "SYN_RECV"; if(state==MIB2_TCP_finWait1) return "FIN_WAIT1"; if(state==MIB2_TCP_finWait2) return "FIN_WAIT2"; if(state==MIB2_TCP_timeWait) return "TIME_WAIT"; if(state==MIB2_TCP_closed) return "CLOSE"; if(state==MIB2_TCP_closeWait) return "CLOSE_WAIT"; if(state==MIB2_TCP_lastAck) return "LAST_ACK"; if(state==MIB2_TCP_listen) return "LISTEN"; if(state==MIB2_TCP_closing||state==MIB2_TCP_deleteTCB) return "CLOSING"; return "UNKNOWN"; } struct netstat_t { std::string proto; std::string local_address; std::string foreign_address; std::string local_port; std::string foreign_port; std::string state; std::string inode; std::string pid; }; typedef std::vector<netstat_t> netstat_list_t; void netstat_print(const netstat_t& netstat) { std::cout<< std::setw(4)<<netstat.proto<<" "<< std::setw(64)<<netstat.local_address+":"+netstat.local_port<<" "<< std::setw(64)<<netstat.foreign_address+":"+netstat.foreign_port<<" "<< std::setw(16)<<netstat.state<<" "<< std::setw(8)<<netstat.pid<<" "<< std::endl; } void netstat_list_print(const netstat_list_t& netstats) { std::cout<< std::setw(4)<<"proto "<< std::setw(64)<<"local_address "<< std::setw(64)<<"foreign_address "<< std::setw(16)<<"state "<< std::setw(8)<<"pid "<< std::endl; for(size_t ii=0;ii<netstats.size();++ii) netstat_print(netstats[ii]); } int main() { int fd=open("/dev/arp",O_RDWR); if(fd==-1) return 1; if(ioctl(fd,I_PUSH,"tcp")==-1) return 1; if(ioctl(fd,I_PUSH,"udp")==-1) return 1; request_t request; strbuf buf; buf.len=sizeof(request); buf.buf=(char*)&request; if(putmsg(fd,&buf,NULL,0)<0) return 1; netstat_list_t tcp4; netstat_list_t tcp6; netstat_list_t udp4; netstat_list_t udp6; while(true) { strbuf buf2; int flags=0; reply_t reply; buf2.maxlen=sizeof(reply); buf2.buf=(char*)&reply; int ret=getmsg(fd,&buf2,NULL,&flags); if(ret<0) { std::cout<<"ret<0"<<std::endl; return 1; } if(ret!=MOREDATA) break; if(reply.ack_header.PRIM_type!=T_OPTMGMT_ACK) { std::cout<<"primtype"<<std::endl; return 1; } if((unsigned int)buf2.len<sizeof(reply.ack_header)) { std::cout<<"buf2len"<<std::endl; return 1; } if((unsigned int)reply.ack_header.OPT_length<sizeof(reply.opt_header)) { std::cout<<"optlength"<<std::endl; return 1; } void* data=malloc(reply.opt_header.len); if(data==NULL) return 1; buf2.maxlen=reply.opt_header.len; buf2.buf=(char*)data; flags=0; if(getmsg(fd,NULL,&buf2,&flags)>=0) { if(reply.opt_header.level==MIB2_TCP&&reply.opt_header.name==MIB2_TCP_CONN) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcpConnEntry_t)) { mib2_tcpConnEntry_t* entry=(mib2_tcpConnEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="tcp4"; netstat.local_address=uint32_t_to_ipv4(entry->tcpConnLocalAddress); netstat.foreign_address=uint32_t_to_ipv4(entry->tcpConnRemAddress); netstat.local_port=dword_to_port(htons(entry->tcpConnLocalPort)); netstat.foreign_port=dword_to_port(htons(entry->tcpConnRemPort)); netstat.state=state_int_to_string(entry->tcpConnState); netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->tcpConnCreationProcess); #endif tcp4.push_back(netstat); } } #if(defined(MIB2_TCP6)) if(reply.opt_header.level==MIB2_TCP6&&reply.opt_header.name==MIB2_TCP6_CONN) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcp6ConnEntry_t)) { mib2_tcp6ConnEntry_t* entry=(mib2_tcp6ConnEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="tcp6"; netstat.local_address=uint8_t_16_to_ipv6(entry->tcp6ConnLocalAddress.s6_addr); netstat.foreign_address=uint8_t_16_to_ipv6(entry->tcp6ConnRemAddress.s6_addr); netstat.local_port=dword_to_port(htons(entry->tcp6ConnLocalPort)); netstat.foreign_port=dword_to_port(htons(entry->tcp6ConnRemPort)); netstat.state=state_int_to_string(entry->tcp6ConnState); netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->tcp6ConnCreationProcess); #endif tcp6.push_back(netstat); } } #endif if(reply.opt_header.level==MIB2_UDP&&reply.opt_header.name==MIB2_UDP_ENTRY) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udpEntry_t)) { mib2_udpEntry_t* entry=(mib2_udpEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="udp4"; netstat.local_address=uint32_t_to_ipv4(entry->udpLocalAddress); netstat.foreign_address="0.0.0.0"; netstat.local_port=dword_to_port(htons(entry->udpLocalPort)); netstat.foreign_port="0"; netstat.state="-"; netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->udpCreationProcess); #endif udp4.push_back(netstat); } } #if(defined(MIB2_UDP6)) if(reply.opt_header.level==MIB2_UDP6&&reply.opt_header.name==MIB2_UDP6_ENTRY) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udp6Entry_t)) { mib2_udp6Entry_t* entry=(mib2_udp6Entry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="udp6"; netstat.local_address=uint8_t_16_to_ipv6(entry->udp6LocalAddress.s6_addr); netstat.foreign_address="0000:0000:0000:0000:0000:0000:0000:0000"; netstat.local_port=dword_to_port(htons(entry->udp6LocalPort)); netstat.foreign_port="0"; netstat.state="-"; netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->udp6CreationProcess); #endif udp6.push_back(netstat); } } #endif } free(data); } netstat_list_t netstats; for(size_t ii=0;ii<tcp4.size();++ii) netstats.push_back(tcp4[ii]); for(size_t ii=0;ii<tcp6.size();++ii) netstats.push_back(tcp6[ii]); for(size_t ii=0;ii<udp4.size();++ii) netstats.push_back(udp4[ii]); for(size_t ii=0;ii<udp6.size();++ii) netstats.push_back(udp6[ii]); netstat_list_print(netstats); return 0; } <commit_msg>Added testing systems.<commit_after>//Tested on: // solaris 10 (g++) // solaris 11 (g++) #include <iomanip> #include <iostream> #include <stdint.h> #include <cstdlib> #include <string> #include <sstream> #include <vector> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stropts.h> #include <cstring> #include <sys/tihdr.h> #include <inet/mib2.h> class buffer_t { public: char buffer[512]; strbuf buf; buffer_t() { memset(buffer,0,512); buf.buf=(char*)buffer; buf.len=512; } }; struct request_t { public: request_t() { req_header.PRIM_type=T_SVR4_OPTMGMT_REQ; req_header.OPT_length=sizeof(opt_header); req_header.OPT_offset=offsetof(request_t,opt_header); req_header.MGMT_flags=T_CURRENT; opt_header.level=MIB2_IP; opt_header.name=0; opt_header.len=0; } T_optmgmt_req req_header; opthdr opt_header; }; struct reply_t { T_optmgmt_ack ack_header; opthdr opt_header; }; std::string uint32_t_to_ipv4(const uint32_t address) { std::ostringstream ostr; ostr<<(uint32_t)((uint8_t*)&address)[0]<<"."<< (uint32_t)((uint8_t*)&address)[1]<<"."<< (uint32_t)((uint8_t*)&address)[2]<<"."<< (uint32_t)((uint8_t*)&address)[3]; return ostr.str(); } std::string uint8_t_16_to_ipv6(const uint8_t address[16]) { std::ostringstream ostr; for(int ii=0;ii<16;ii+=2) { ostr<<std::hex<<std::setw(2)<<std::setfill('0')<<(unsigned int)(unsigned char)address[ii+0]; ostr<<std::hex<<std::setw(2)<<std::setfill('0')<<(unsigned int)(unsigned char)address[ii+1]; if(ii<14) ostr<<":"; } return ostr.str(); } std::string dword_to_port(const uint32_t port) { std::ostringstream ostr; ostr<<((((uint32_t)((uint8_t*)&port)[0])<<8)+((uint8_t*)&port)[1]); return ostr.str(); } std::string to_string(const uint32_t val) { std::ostringstream ostr; ostr<<val; return ostr.str(); } std::string state_int_to_string(const uint32_t state) { if(state==MIB2_TCP_established) return "ESTABLISHED"; if(state==MIB2_TCP_synSent) return "SYN_SENT"; if(state==MIB2_TCP_synReceived) return "SYN_RECV"; if(state==MIB2_TCP_finWait1) return "FIN_WAIT1"; if(state==MIB2_TCP_finWait2) return "FIN_WAIT2"; if(state==MIB2_TCP_timeWait) return "TIME_WAIT"; if(state==MIB2_TCP_closed) return "CLOSE"; if(state==MIB2_TCP_closeWait) return "CLOSE_WAIT"; if(state==MIB2_TCP_lastAck) return "LAST_ACK"; if(state==MIB2_TCP_listen) return "LISTEN"; if(state==MIB2_TCP_closing||state==MIB2_TCP_deleteTCB) return "CLOSING"; return "UNKNOWN"; } struct netstat_t { std::string proto; std::string local_address; std::string foreign_address; std::string local_port; std::string foreign_port; std::string state; std::string inode; std::string pid; }; typedef std::vector<netstat_t> netstat_list_t; void netstat_print(const netstat_t& netstat) { std::cout<< std::setw(4)<<netstat.proto<<" "<< std::setw(64)<<netstat.local_address+":"+netstat.local_port<<" "<< std::setw(64)<<netstat.foreign_address+":"+netstat.foreign_port<<" "<< std::setw(16)<<netstat.state<<" "<< std::setw(8)<<netstat.pid<<" "<< std::endl; } void netstat_list_print(const netstat_list_t& netstats) { std::cout<< std::setw(4)<<"proto "<< std::setw(64)<<"local_address "<< std::setw(64)<<"foreign_address "<< std::setw(16)<<"state "<< std::setw(8)<<"pid "<< std::endl; for(size_t ii=0;ii<netstats.size();++ii) netstat_print(netstats[ii]); } int main() { int fd=open("/dev/arp",O_RDWR); if(fd==-1) return 1; if(ioctl(fd,I_PUSH,"tcp")==-1) return 1; if(ioctl(fd,I_PUSH,"udp")==-1) return 1; request_t request; strbuf buf; buf.len=sizeof(request); buf.buf=(char*)&request; if(putmsg(fd,&buf,NULL,0)<0) return 1; netstat_list_t tcp4; netstat_list_t tcp6; netstat_list_t udp4; netstat_list_t udp6; while(true) { strbuf buf2; int flags=0; reply_t reply; buf2.maxlen=sizeof(reply); buf2.buf=(char*)&reply; int ret=getmsg(fd,&buf2,NULL,&flags); if(ret<0) { std::cout<<"ret<0"<<std::endl; return 1; } if(ret!=MOREDATA) break; if(reply.ack_header.PRIM_type!=T_OPTMGMT_ACK) { std::cout<<"primtype"<<std::endl; return 1; } if((unsigned int)buf2.len<sizeof(reply.ack_header)) { std::cout<<"buf2len"<<std::endl; return 1; } if((unsigned int)reply.ack_header.OPT_length<sizeof(reply.opt_header)) { std::cout<<"optlength"<<std::endl; return 1; } void* data=malloc(reply.opt_header.len); if(data==NULL) return 1; buf2.maxlen=reply.opt_header.len; buf2.buf=(char*)data; flags=0; if(getmsg(fd,NULL,&buf2,&flags)>=0) { if(reply.opt_header.level==MIB2_TCP&&reply.opt_header.name==MIB2_TCP_CONN) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcpConnEntry_t)) { mib2_tcpConnEntry_t* entry=(mib2_tcpConnEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="tcp4"; netstat.local_address=uint32_t_to_ipv4(entry->tcpConnLocalAddress); netstat.foreign_address=uint32_t_to_ipv4(entry->tcpConnRemAddress); netstat.local_port=dword_to_port(htons(entry->tcpConnLocalPort)); netstat.foreign_port=dword_to_port(htons(entry->tcpConnRemPort)); netstat.state=state_int_to_string(entry->tcpConnState); netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->tcpConnCreationProcess); #endif tcp4.push_back(netstat); } } #if(defined(MIB2_TCP6)) if(reply.opt_header.level==MIB2_TCP6&&reply.opt_header.name==MIB2_TCP6_CONN) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcp6ConnEntry_t)) { mib2_tcp6ConnEntry_t* entry=(mib2_tcp6ConnEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="tcp6"; netstat.local_address=uint8_t_16_to_ipv6(entry->tcp6ConnLocalAddress.s6_addr); netstat.foreign_address=uint8_t_16_to_ipv6(entry->tcp6ConnRemAddress.s6_addr); netstat.local_port=dword_to_port(htons(entry->tcp6ConnLocalPort)); netstat.foreign_port=dword_to_port(htons(entry->tcp6ConnRemPort)); netstat.state=state_int_to_string(entry->tcp6ConnState); netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->tcp6ConnCreationProcess); #endif tcp6.push_back(netstat); } } #endif if(reply.opt_header.level==MIB2_UDP&&reply.opt_header.name==MIB2_UDP_ENTRY) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udpEntry_t)) { mib2_udpEntry_t* entry=(mib2_udpEntry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="udp4"; netstat.local_address=uint32_t_to_ipv4(entry->udpLocalAddress); netstat.foreign_address="0.0.0.0"; netstat.local_port=dword_to_port(htons(entry->udpLocalPort)); netstat.foreign_port="0"; netstat.state="-"; netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->udpCreationProcess); #endif udp4.push_back(netstat); } } #if(defined(MIB2_UDP6)) if(reply.opt_header.level==MIB2_UDP6&&reply.opt_header.name==MIB2_UDP6_ENTRY) { for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udp6Entry_t)) { mib2_udp6Entry_t* entry=(mib2_udp6Entry_t*)((char*)data+ii); netstat_t netstat; netstat.proto="udp6"; netstat.local_address=uint8_t_16_to_ipv6(entry->udp6LocalAddress.s6_addr); netstat.foreign_address="0000:0000:0000:0000:0000:0000:0000:0000"; netstat.local_port=dword_to_port(htons(entry->udp6LocalPort)); netstat.foreign_port="0"; netstat.state="-"; netstat.pid="-"; #if(defined(SOLARIS_112)) netstat.pid=to_string(entry->udp6CreationProcess); #endif udp6.push_back(netstat); } } #endif } free(data); } netstat_list_t netstats; for(size_t ii=0;ii<tcp4.size();++ii) netstats.push_back(tcp4[ii]); for(size_t ii=0;ii<tcp6.size();++ii) netstats.push_back(tcp6[ii]); for(size_t ii=0;ii<udp4.size();++ii) netstats.push_back(udp4[ii]); for(size_t ii=0;ii<udp6.size();++ii) netstats.push_back(udp6[ii]); netstat_list_print(netstats); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/network/network.hpp> #include <functional> #include <algorithm> #include <iostream> #include <bitcoin/utility/logger.hpp> namespace libbitcoin { using std::placeholders::_1; using std::placeholders::_2; acceptor::acceptor(threadpool& pool, tcp_acceptor_ptr tcp_accept) : pool_(pool), tcp_accept_(tcp_accept) { } void acceptor::accept(accept_handler handle_accept) { socket_ptr socket = std::make_shared<tcp::socket>(pool_.service()); tcp_accept_->async_accept(*socket, std::bind(&acceptor::call_handle_accept, shared_from_this(), _1, socket, handle_accept)); } void acceptor::call_handle_accept(const boost::system::error_code& ec, socket_ptr socket, accept_handler handle_accept) { if (ec) { handle_accept(error::accept_failed, nullptr); return; } auto proxy = std::make_shared<channel_proxy>(pool_, socket); proxy->start(); channel_ptr channel_object = std::make_shared<channel>(proxy); handle_accept(std::error_code(), channel_object); } class perform_connect_with_timeout : public std::enable_shared_from_this<perform_connect_with_timeout> { public: perform_connect_with_timeout(threadpool& pool) : timer_(pool.service()) { socket_ = std::make_shared<tcp::socket>(pool.service()); proxy_ = std::make_shared<channel_proxy>(pool, socket_); } void start(tcp::resolver::iterator endpoint_iterator, size_t timeout, network::connect_handler handle_connect) { timer_.expires_from_now(boost::posix_time::seconds(timeout)); timer_.async_wait(std::bind( &perform_connect_with_timeout::close, shared_from_this(), _1)); boost::asio::async_connect(*socket_, endpoint_iterator, std::bind(&perform_connect_with_timeout::call_connect_handler, shared_from_this(), _1, _2, handle_connect)); } private: void call_connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator, network::connect_handler handle_connect) { if (ec) { handle_connect(error::network_unreachable, nullptr); return; } timer_.cancel(); proxy_->start(); channel_ptr channel_object = std::make_shared<channel>(proxy_); handle_connect(std::error_code(), channel_object); } void close(const boost::system::error_code& ec) { // ec should be boost::asio::error::operation_aborted or nothing. if (!ec) proxy_->stop(); } socket_ptr socket_; channel::channel_proxy_ptr proxy_; boost::asio::deadline_timer timer_; }; network::network(threadpool& pool) : pool_(pool) { } void network::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator endpoint_iterator, connect_handler handle_connect, resolver_ptr, query_ptr) { if (ec) { handle_connect(error::resolve_failed, nullptr); return; } auto connect = std::make_shared<perform_connect_with_timeout>(pool_); connect->start(endpoint_iterator, 5, handle_connect); } void network::connect(const std::string& hostname, uint16_t port, connect_handler handle_connect) { resolver_ptr resolver = std::make_shared<tcp::resolver>(pool_.service()); query_ptr query = std::make_shared<tcp::resolver::query>(hostname, std::to_string(port)); resolver->async_resolve(*query, std::bind(&network::resolve_handler, this, _1, _2, handle_connect, resolver, query)); } // I personally don't like how exceptions mess with the program flow bool listen_error(const boost::system::error_code& ec, network::listen_handler handle_listen) { if (ec == boost::system::errc::address_in_use) { handle_listen(error::address_in_use, nullptr); return true; } else if (ec) { handle_listen(error::listen_failed, nullptr); return true; } return false; } void network::listen(uint16_t port, listen_handler handle_listen) { tcp::endpoint endpoint(tcp::v4(), port); acceptor::tcp_acceptor_ptr tcp_accept = std::make_shared<tcp::acceptor>(pool_.service()); // Need to check error codes for functions boost::system::error_code ec; tcp_accept->open(endpoint.protocol(), ec); if (listen_error(ec, handle_listen)) return; tcp_accept->set_option(tcp::acceptor::reuse_address(true), ec); if (listen_error(ec, handle_listen)) return; tcp_accept->bind(endpoint, ec); if (listen_error(ec, handle_listen)) return; tcp_accept->listen(boost::asio::socket_base::max_connections, ec); if (listen_error(ec, handle_listen)) return; acceptor_ptr accept = std::make_shared<acceptor>(pool_, tcp_accept); handle_listen(std::error_code(), accept); } } // namespace libbitcoin <commit_msg>assert in network connect timeout section.<commit_after>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/network/network.hpp> #include <functional> #include <algorithm> #include <iostream> #include <bitcoin/utility/logger.hpp> namespace libbitcoin { using std::placeholders::_1; using std::placeholders::_2; acceptor::acceptor(threadpool& pool, tcp_acceptor_ptr tcp_accept) : pool_(pool), tcp_accept_(tcp_accept) { } void acceptor::accept(accept_handler handle_accept) { socket_ptr socket = std::make_shared<tcp::socket>(pool_.service()); tcp_accept_->async_accept(*socket, std::bind(&acceptor::call_handle_accept, shared_from_this(), _1, socket, handle_accept)); } void acceptor::call_handle_accept(const boost::system::error_code& ec, socket_ptr socket, accept_handler handle_accept) { if (ec) { handle_accept(error::accept_failed, nullptr); return; } auto proxy = std::make_shared<channel_proxy>(pool_, socket); proxy->start(); channel_ptr channel_object = std::make_shared<channel>(proxy); handle_accept(std::error_code(), channel_object); } class perform_connect_with_timeout : public std::enable_shared_from_this<perform_connect_with_timeout> { public: perform_connect_with_timeout(threadpool& pool) : timer_(pool.service()) { socket_ = std::make_shared<tcp::socket>(pool.service()); proxy_ = std::make_shared<channel_proxy>(pool, socket_); } void start(tcp::resolver::iterator endpoint_iterator, size_t timeout, network::connect_handler handle_connect) { timer_.expires_from_now(boost::posix_time::seconds(timeout)); timer_.async_wait(std::bind( &perform_connect_with_timeout::close, shared_from_this(), _1)); boost::asio::async_connect(*socket_, endpoint_iterator, std::bind(&perform_connect_with_timeout::call_connect_handler, shared_from_this(), _1, _2, handle_connect)); } private: void call_connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator, network::connect_handler handle_connect) { if (ec) { handle_connect(error::network_unreachable, nullptr); return; } timer_.cancel(); proxy_->start(); channel_ptr channel_object = std::make_shared<channel>(proxy_); handle_connect(std::error_code(), channel_object); } void close(const boost::system::error_code& ec) { // ec should be boost::asio::error::operation_aborted or nothing. BITCOIN_ASSERT(!ec || ec == boost::asio::error::operation_aborted); if (!ec) proxy_->stop(); } socket_ptr socket_; channel::channel_proxy_ptr proxy_; boost::asio::deadline_timer timer_; }; network::network(threadpool& pool) : pool_(pool) { } void network::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator endpoint_iterator, connect_handler handle_connect, resolver_ptr, query_ptr) { if (ec) { handle_connect(error::resolve_failed, nullptr); return; } auto connect = std::make_shared<perform_connect_with_timeout>(pool_); connect->start(endpoint_iterator, 5, handle_connect); } void network::connect(const std::string& hostname, uint16_t port, connect_handler handle_connect) { resolver_ptr resolver = std::make_shared<tcp::resolver>(pool_.service()); query_ptr query = std::make_shared<tcp::resolver::query>(hostname, std::to_string(port)); resolver->async_resolve(*query, std::bind(&network::resolve_handler, this, _1, _2, handle_connect, resolver, query)); } // I personally don't like how exceptions mess with the program flow bool listen_error(const boost::system::error_code& ec, network::listen_handler handle_listen) { if (ec == boost::system::errc::address_in_use) { handle_listen(error::address_in_use, nullptr); return true; } else if (ec) { handle_listen(error::listen_failed, nullptr); return true; } return false; } void network::listen(uint16_t port, listen_handler handle_listen) { tcp::endpoint endpoint(tcp::v4(), port); acceptor::tcp_acceptor_ptr tcp_accept = std::make_shared<tcp::acceptor>(pool_.service()); // Need to check error codes for functions boost::system::error_code ec; tcp_accept->open(endpoint.protocol(), ec); if (listen_error(ec, handle_listen)) return; tcp_accept->set_option(tcp::acceptor::reuse_address(true), ec); if (listen_error(ec, handle_listen)) return; tcp_accept->bind(endpoint, ec); if (listen_error(ec, handle_listen)) return; tcp_accept->listen(boost::asio::socket_base::max_connections, ec); if (listen_error(ec, handle_listen)) return; acceptor_ptr accept = std::make_shared<acceptor>(pool_, tcp_accept); handle_listen(std::error_code(), accept); } } // namespace libbitcoin <|endoftext|>
<commit_before>//===-- llvm/CodeGen/GlobalISel/Legalizer.cpp -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file implements the LegalizerHelper class to legalize individual /// instructions and the LegalizePass wrapper pass for the primary /// legalization. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/Legalizer.h" #include "llvm/ADT/SetVector.h" #include "llvm/CodeGen/GlobalISel/LegalizerCombiner.h" #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h" #include "llvm/CodeGen/GlobalISel/Utils.h" #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include <iterator> #define DEBUG_TYPE "legalizer" using namespace llvm; char Legalizer::ID = 0; INITIALIZE_PASS_BEGIN(Legalizer, DEBUG_TYPE, "Legalize the Machine IR a function's Machine IR", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(Legalizer, DEBUG_TYPE, "Legalize the Machine IR a function's Machine IR", false, false) Legalizer::Legalizer() : MachineFunctionPass(ID) { initializeLegalizerPass(*PassRegistry::getPassRegistry()); } void Legalizer::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } void Legalizer::init(MachineFunction &MF) { } bool Legalizer::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Legalize Machine IR for: " << MF.getName() << '\n'); init(MF); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr); LegalizerHelper Helper(MF); // FIXME: an instruction may need more than one pass before it is legal. For // example on most architectures <3 x i3> is doubly-illegal. It would // typically proceed along a path like: <3 x i3> -> <3 x i8> -> <8 x i8>. We // probably want a worklist of instructions rather than naive iterate until // convergence for performance reasons. bool Changed = false; MachineBasicBlock::iterator NextMI; using VecType = SetVector<MachineInstr *, SmallVector<MachineInstr *, 8>>; VecType WorkList; VecType CombineList; for (auto &MBB : MF) { for (auto MI = MBB.begin(); MI != MBB.end(); MI = NextMI) { // Get the next Instruction before we try to legalize, because there's a // good chance MI will be deleted. NextMI = std::next(MI); // Only legalize pre-isel generic instructions: others don't have types // and are assumed to be legal. if (!isPreISelGenericOpcode(MI->getOpcode())) continue; unsigned NumNewInsns = 0; WorkList.clear(); CombineList.clear(); Helper.MIRBuilder.recordInsertions([&](MachineInstr *MI) { // Only legalize pre-isel generic instructions. // Legalization process could generate Target specific pseudo // instructions with generic types. Don't record them if (isPreISelGenericOpcode(MI->getOpcode())) { ++NumNewInsns; WorkList.insert(MI); CombineList.insert(MI); } }); WorkList.insert(&*MI); LegalizerCombiner C(Helper.MIRBuilder, MF.getRegInfo()); bool Changed = false; LegalizerHelper::LegalizeResult Res; do { assert(!WorkList.empty() && "Expecting illegal ops"); while (!WorkList.empty()) { NumNewInsns = 0; MachineInstr *CurrInst = WorkList.pop_back_val(); Res = Helper.legalizeInstrStep(*CurrInst); // Error out if we couldn't legalize this instruction. We may want to // fall back to DAG ISel instead in the future. if (Res == LegalizerHelper::UnableToLegalize) { Helper.MIRBuilder.stopRecordingInsertions(); if (Res == LegalizerHelper::UnableToLegalize) { reportGISelFailure(MF, TPC, MORE, "gisel-legalize", "unable to legalize instruction", *CurrInst); return false; } } Changed |= Res == LegalizerHelper::Legalized; // If CurrInst was legalized, there's a good chance that it might have // been erased. So remove it from the Combine List. if (Res == LegalizerHelper::Legalized) CombineList.remove(CurrInst); #ifndef NDEBUG if (NumNewInsns) for (unsigned I = WorkList.size() - NumNewInsns, E = WorkList.size(); I != E; ++I) DEBUG(dbgs() << ".. .. New MI: " << *WorkList[I];); #endif } // Do the combines. while (!CombineList.empty()) { NumNewInsns = 0; MachineInstr *CurrInst = CombineList.pop_back_val(); SmallVector<MachineInstr *, 4> DeadInstructions; Changed |= C.tryCombineInstruction(*CurrInst, DeadInstructions); for (auto *DeadMI : DeadInstructions) { DEBUG(dbgs() << ".. Erasing Dead Instruction " << *DeadMI); CombineList.remove(DeadMI); WorkList.remove(DeadMI); DeadMI->eraseFromParent(); } #ifndef NDEBUG if (NumNewInsns) for (unsigned I = CombineList.size() - NumNewInsns, E = CombineList.size(); I != E; ++I) DEBUG(dbgs() << ".. .. Combine New MI: " << *CombineList[I];); #endif } } while (!WorkList.empty()); Helper.MIRBuilder.stopRecordingInsertions(); } } MachineRegisterInfo &MRI = MF.getRegInfo(); MachineIRBuilder MIRBuilder(MF); LegalizerCombiner C(MIRBuilder, MRI); for (auto &MBB : MF) { for (auto MI = MBB.begin(); MI != MBB.end(); MI = NextMI) { // Get the next Instruction before we try to legalize, because there's a // good chance MI will be deleted. // TOOD: Perhaps move this to a combiner pass later?. NextMI = std::next(MI); SmallVector<MachineInstr *, 4> DeadInsts; Changed |= C.tryCombineMerges(*MI, DeadInsts); for (auto *DeadMI : DeadInsts) DeadMI->eraseFromParent(); } } return Changed; } <commit_msg>[Legalizer] Use SmallSetVector instead of SetVector.<commit_after>//===-- llvm/CodeGen/GlobalISel/Legalizer.cpp -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file implements the LegalizerHelper class to legalize individual /// instructions and the LegalizePass wrapper pass for the primary /// legalization. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/Legalizer.h" #include "llvm/ADT/SetVector.h" #include "llvm/CodeGen/GlobalISel/LegalizerCombiner.h" #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h" #include "llvm/CodeGen/GlobalISel/Utils.h" #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include <iterator> #define DEBUG_TYPE "legalizer" using namespace llvm; char Legalizer::ID = 0; INITIALIZE_PASS_BEGIN(Legalizer, DEBUG_TYPE, "Legalize the Machine IR a function's Machine IR", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(Legalizer, DEBUG_TYPE, "Legalize the Machine IR a function's Machine IR", false, false) Legalizer::Legalizer() : MachineFunctionPass(ID) { initializeLegalizerPass(*PassRegistry::getPassRegistry()); } void Legalizer::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } void Legalizer::init(MachineFunction &MF) { } bool Legalizer::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Legalize Machine IR for: " << MF.getName() << '\n'); init(MF); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); MachineOptimizationRemarkEmitter MORE(MF, /*MBFI=*/nullptr); LegalizerHelper Helper(MF); // FIXME: an instruction may need more than one pass before it is legal. For // example on most architectures <3 x i3> is doubly-illegal. It would // typically proceed along a path like: <3 x i3> -> <3 x i8> -> <8 x i8>. We // probably want a worklist of instructions rather than naive iterate until // convergence for performance reasons. bool Changed = false; MachineBasicBlock::iterator NextMI; using VecType = SmallSetVector<MachineInstr *, 8>; VecType WorkList; VecType CombineList; for (auto &MBB : MF) { for (auto MI = MBB.begin(); MI != MBB.end(); MI = NextMI) { // Get the next Instruction before we try to legalize, because there's a // good chance MI will be deleted. NextMI = std::next(MI); // Only legalize pre-isel generic instructions: others don't have types // and are assumed to be legal. if (!isPreISelGenericOpcode(MI->getOpcode())) continue; unsigned NumNewInsns = 0; WorkList.clear(); CombineList.clear(); Helper.MIRBuilder.recordInsertions([&](MachineInstr *MI) { // Only legalize pre-isel generic instructions. // Legalization process could generate Target specific pseudo // instructions with generic types. Don't record them if (isPreISelGenericOpcode(MI->getOpcode())) { ++NumNewInsns; WorkList.insert(MI); CombineList.insert(MI); } }); WorkList.insert(&*MI); LegalizerCombiner C(Helper.MIRBuilder, MF.getRegInfo()); bool Changed = false; LegalizerHelper::LegalizeResult Res; do { assert(!WorkList.empty() && "Expecting illegal ops"); while (!WorkList.empty()) { NumNewInsns = 0; MachineInstr *CurrInst = WorkList.pop_back_val(); Res = Helper.legalizeInstrStep(*CurrInst); // Error out if we couldn't legalize this instruction. We may want to // fall back to DAG ISel instead in the future. if (Res == LegalizerHelper::UnableToLegalize) { Helper.MIRBuilder.stopRecordingInsertions(); if (Res == LegalizerHelper::UnableToLegalize) { reportGISelFailure(MF, TPC, MORE, "gisel-legalize", "unable to legalize instruction", *CurrInst); return false; } } Changed |= Res == LegalizerHelper::Legalized; // If CurrInst was legalized, there's a good chance that it might have // been erased. So remove it from the Combine List. if (Res == LegalizerHelper::Legalized) CombineList.remove(CurrInst); #ifndef NDEBUG if (NumNewInsns) for (unsigned I = WorkList.size() - NumNewInsns, E = WorkList.size(); I != E; ++I) DEBUG(dbgs() << ".. .. New MI: " << *WorkList[I];); #endif } // Do the combines. while (!CombineList.empty()) { NumNewInsns = 0; MachineInstr *CurrInst = CombineList.pop_back_val(); SmallVector<MachineInstr *, 4> DeadInstructions; Changed |= C.tryCombineInstruction(*CurrInst, DeadInstructions); for (auto *DeadMI : DeadInstructions) { DEBUG(dbgs() << ".. Erasing Dead Instruction " << *DeadMI); CombineList.remove(DeadMI); WorkList.remove(DeadMI); DeadMI->eraseFromParent(); } #ifndef NDEBUG if (NumNewInsns) for (unsigned I = CombineList.size() - NumNewInsns, E = CombineList.size(); I != E; ++I) DEBUG(dbgs() << ".. .. Combine New MI: " << *CombineList[I];); #endif } } while (!WorkList.empty()); Helper.MIRBuilder.stopRecordingInsertions(); } } MachineRegisterInfo &MRI = MF.getRegInfo(); MachineIRBuilder MIRBuilder(MF); LegalizerCombiner C(MIRBuilder, MRI); for (auto &MBB : MF) { for (auto MI = MBB.begin(); MI != MBB.end(); MI = NextMI) { // Get the next Instruction before we try to legalize, because there's a // good chance MI will be deleted. // TOOD: Perhaps move this to a combiner pass later?. NextMI = std::next(MI); SmallVector<MachineInstr *, 4> DeadInsts; Changed |= C.tryCombineMerges(*MI, DeadInsts); for (auto *DeadMI : DeadInsts) DeadMI->eraseFromParent(); } } return Changed; } <|endoftext|>
<commit_before>/* * NNAdjust.cc * * Bumps up the strength of the edges connecting two nouns in a * noun-modifier (nn) relationship. Basically, if there is a * noun-modifier phrase, then make a stronger tie to make sure * that the two word senses corellate with each other. * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #include <stdio.h> #include "ForeachWord.h" #include "NNAdjust.h" #include "SimpleTruthValue.h" #define DEBUG using namespace opencog; NNAdjust::NNAdjust(void) { } NNAdjust::~NNAdjust() { } /** Loop over all parses for this sentence. */ void NNAdjust::adjust_sentence(Handle h) { foreach_parse(h, &NNAdjust::adjust_parse, this); } /** * For each parse, loop over all word-instances */ bool NNAdjust::adjust_parse(Handle h) { foreach_word_instance(h, &NNAdjust::adjust_word, this); return false; } /** * For each word-instance loop over all syntactic relationships. * (i.e. _subj, _obj, _nn, _amod, and so on). Discard all but the _nn. */ bool NNAdjust::adjust_word(Handle h) { foreach_relex_relation(h, &NNAdjust::adjust_relation, this); return false; } /** * This routine is called for every relation between word-instances in * a parse. */ bool NNAdjust::adjust_relation(const std::string &relname, Handle first, Handle second) { if (relname.compare("_nn")) return false; xxx return false; } /** * Create edges between all senses of a pair of words. * * This routine implements a doubley-nested foreach loop, iterating * over all senses of each word, and creating an edge between them. * * All of the current word-sense similarity algorithms report zero * similarity when the two words are different parts of speech. * Therefore, in order to improve performance, this routine does not * create any edges between words of differing parts-of-speech. */ bool NNAdjust::annotate_word_pair(Handle first, Handle second) { #ifdef DEBUG Node *f = dynamic_cast<Node *>(TLB::getAtom(first)); Node *s = dynamic_cast<Node *>(TLB::getAtom(second)); const std::string &fn = f->getName(); const std::string &sn = s->getName(); printf("(%s, %s)\n", fn.c_str(), sn.c_str()); #endif // Don't bother linking words with different parts-of-speech; // the similarity measures don't support these. std::string first_pos = get_pos_of_word_instance(first); std::string second_pos = get_pos_of_word_instance(second); if (0 != first_pos.compare(second_pos)) { return false; } second_word_inst = second; foreach_word_sense_of_inst(first, &NNAdjust::sense_of_first_inst, this); return false; } /** * Called for every pair (word-instance,word-sense) of the first * word-instance of a relex relationship. This, in turn iterates * over the second word-instance of the relex relationship. */ bool NNAdjust::sense_of_first_inst(Handle first_word_sense_h, Handle first_sense_link_h) { first_word_sense = first_word_sense_h; // Rule out relations that aren't actual word-senses. Node *sense = dynamic_cast<Node *>(TLB::getAtom(first_word_sense_h)); if (!sense || sense->getType() != WORD_SENSE_NODE) return false; // printf("first sense %s\n", sense->getName().c_str()); // Get the handle of the link itself .. first_sense_link = first_sense_link_h; foreach_word_sense_of_inst(second_word_inst, &NNAdjust::sense_of_second_inst, this); return false; } /** * Called for every pair (word-instance,word-sense) of the second * word-instance of a relex relationship. This routine is the last, * most deeply nested loop of all of this set of nested loops. This * routine now has possession of both pairs, and can now create a * Mihalcea-graph edge between these pairs. * * As discussed in the README file, the resulting structure is: * * <!-- the word "tree" occured in the sentence --> * <CosenseLink strength=0.49 confidence=0.3> * <InheritanceLink strength=0.9 confidence=0.6> * <ConceptNode name="tree_99" /> * <WordSenseNode name="tree_sense_12" /> * </InheritanceLink> * * <InheritanceLink strength=0.9 confidence=0.1> * <ConceptNode name="bark_144" /> * <WordSenseNode name="bark_sense_23" /> * </InheritanceLink> * </CosenseLink> */ bool NNAdjust::sense_of_second_inst(Handle second_word_sense_h, Handle second_sense_link) { // Rule out relations that aren't actual word-senses. Node *sense = dynamic_cast<Node *>(TLB::getAtom(second_word_sense_h)); if (!sense || sense->getType() != WORD_SENSE_NODE) return false; // printf("second sense %s!\n", sense->getName().c_str()); // Create a link connecting the first pair to the second pair. std::vector<Handle> out; out.push_back(first_sense_link); out.push_back(second_sense_link); // Use a word-sense similarity/relationship measure to assign an // initial truth value to the edge. SenseSimilarity *ss = new SenseSimilarity(); SimpleTruthValue stv = ss->lch_similarity(first_word_sense, second_word_sense_h); atom_space->addLink(COSENSE_LINK, out, stv); return false; } <commit_msg>more stuff<commit_after>/* * NNAdjust.cc * * Bumps up the strength of the edges connecting two nouns in a * noun-modifier (nn) relationship. Basically, if there is a * noun-modifier phrase, then make a stronger tie to make sure * that the two word senses corellate with each other. * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #include <stdio.h> #include "ForeachWord.h" #include "NNAdjust.h" #include "SimpleTruthValue.h" #define DEBUG using namespace opencog; NNAdjust::NNAdjust(void) { } NNAdjust::~NNAdjust() { } /** Loop over all parses for this sentence. */ void NNAdjust::adjust_sentence(Handle h) { foreach_parse(h, &NNAdjust::adjust_parse, this); } /** * For each parse, loop over all word-instances */ bool NNAdjust::adjust_parse(Handle h) { foreach_word_instance(h, &NNAdjust::adjust_word, this); return false; } /** * For each word-instance loop over all syntactic relationships. * (i.e. _subj, _obj, _nn, _amod, and so on). Discard all but the _nn. */ bool NNAdjust::adjust_word(Handle h) { foreach_relex_relation(h, &NNAdjust::adjust_relation, this); return false; } /** * This routine is called for every relation between word-instances in * a parse. */ bool NNAdjust::adjust_relation(const std::string &relname, Handle first, Handle second) { if (relname.compare("_nn")) return false; #ifdef DEBUG Node *f = dynamic_cast<Node *>(TLB::getAtom(first)); Node *s = dynamic_cast<Node *>(TLB::getAtom(second)); const std::string &fn = f->getName(); const std::string &sn = s->getName(); printf("_nn(%s, %s)\n", fn.c_str(), sn.c_str()); #endif second_word_inst = second; foreach_word_sense_of_inst(first, &NNAdjust::sense_of_first_inst, this); return false; } /** * Called for every pair (word-instance,word-sense) of the first * word-instance of a relex relationship. This, in turn iterates * over the second word-instance of the relex relationship. */ bool NNAdjust::sense_of_first_inst(Handle first_word_sense_h, Handle first_sense_link_h) { first_word_sense = first_word_sense_h; // Rule out relations that aren't actual word-senses. Node *sense = dynamic_cast<Node *>(TLB::getAtom(first_word_sense_h)); if (!sense || sense->getType() != WORD_SENSE_NODE) return false; // printf("first sense %s\n", sense->getName().c_str()); // Get the handle of the link itself .. first_sense_link = first_sense_link_h; foreach_word_sense_of_inst(second_word_inst, &NNAdjust::sense_of_second_inst, this); return false; } /** * Called for every pair (word-instance,word-sense) of the second * word-instance of a relex relationship. This routine is the last, * most deeply nested loop of all of this set of nested loops. This * routine now has possession of both pairs, and can now create a * Mihalcea-graph edge between these pairs. * * As discussed in the README file, the resulting structure is: * * <!-- the word "tree" occured in the sentence --> * <CosenseLink strength=0.49 confidence=0.3> * <InheritanceLink strength=0.9 confidence=0.6> * <ConceptNode name="tree_99" /> * <WordSenseNode name="tree_sense_12" /> * </InheritanceLink> * * <InheritanceLink strength=0.9 confidence=0.1> * <ConceptNode name="bark_144" /> * <WordSenseNode name="bark_sense_23" /> * </InheritanceLink> * </CosenseLink> */ bool NNAdjust::sense_of_second_inst(Handle second_word_sense_h, Handle second_sense_link) { // Rule out relations that aren't actual word-senses. Node *sense = dynamic_cast<Node *>(TLB::getAtom(second_word_sense_h)); if (!sense || sense->getType() != WORD_SENSE_NODE) return false; // printf("second sense %s!\n", sense->getName().c_str()); // Create a link connecting the first pair to the second pair. std::vector<Handle> out; out.push_back(first_sense_link); out.push_back(second_sense_link); // Use a word-sense similarity/relationship measure to assign an // initial truth value to the edge. SenseSimilarity *ss = new SenseSimilarity(); SimpleTruthValue stv = ss->lch_similarity(first_word_sense, second_word_sense_h); atom_space->addLink(COSENSE_LINK, out, stv); return false; } <|endoftext|>
<commit_before><commit_msg>give more tolerance to DirectML runs (#5564)<commit_after><|endoftext|>
<commit_before>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a printer that converts from our internal representation // of machine-dependent LLVM code to GAS-format Alpha assembly language. // //===----------------------------------------------------------------------===// #include "Alpha.h" #include "AlphaInstrInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/Writer.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Mangler.h" #include "llvm/ADT/Statistic.h" using namespace llvm; namespace { Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); struct AlphaAsmPrinter : public AsmPrinter { /// Unique incrementer for label values for referencing Global values. /// unsigned LabelNumber; AlphaAsmPrinter(std::ostream &o, TargetMachine &tm) : AsmPrinter(o, tm), LabelNumber(0) { } /// We name each basic block in a Function with a unique number, so /// that we can consistently refer to them later. This is cleared /// at the beginning of each call to runOnMachineFunction(). /// typedef std::map<const Value *, unsigned> ValueMapTy; ValueMapTy NumberForBB; virtual const char *getPassName() const { return "Alpha Assembly Printer"; } bool printInstruction(const MachineInstr *MI); void printOp(const MachineOperand &MO, bool IsCallOp = false); void printConstantPool(MachineConstantPool *MCP); void printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT); void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true); void printMachineInstruction(const MachineInstr *MI); bool runOnMachineFunction(MachineFunction &F); bool doInitialization(Module &M); bool doFinalization(Module &M); }; } // end of anonymous namespace /// createAlphaCodePrinterPass - Returns a pass that prints the Alpha /// assembly code for a MachineFunction to the given output stream, /// using the given target machine description. This should work /// regardless of whether the function is in SSA form. /// FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o, TargetMachine &tm) { return new AlphaAsmPrinter(o, tm); } #include "AlphaGenAsmWriter.inc" void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT) { const MachineOperand &MO = MI->getOperand(opNum); if (MO.getType() == MachineOperand::MO_MachineRegister) { assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??"); O << TM.getRegisterInfo()->get(MO.getReg()).Name; } else if (MO.isImmediate()) { O << MO.getImmedValue(); } else { printOp(MO); } } void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) { const MRegisterInfo &RI = *TM.getRegisterInfo(); int new_symbol; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (Value *V = MO.getVRegValueOrNull()) { O << "<" << V->getName() << ">"; return; } // FALLTHROUGH case MachineOperand::MO_MachineRegister: case MachineOperand::MO_CCRegister: O << RI.get(MO.getReg()).Name; return; case MachineOperand::MO_SignExtendedImmed: case MachineOperand::MO_UnextendedImmed: std::cerr << "printOp() does not handle immediate values\n"; abort(); return; case MachineOperand::MO_PCRelativeDisp: std::cerr << "Shouldn't use addPCDisp() when building Alpha MachineInstrs"; abort(); return; case MachineOperand::MO_MachineBasicBlock: { MachineBasicBlock *MBBOp = MO.getMachineBasicBlock(); O << "$LBB" << Mang->getValueName(MBBOp->getParent()->getFunction()) << "_" << MBBOp->getNumber() << "\t" << CommentString << " " << MBBOp->getBasicBlock()->getName(); return; } case MachineOperand::MO_ConstantPoolIndex: O << "$CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex(); return; case MachineOperand::MO_ExternalSymbol: O << MO.getSymbolName(); return; case MachineOperand::MO_GlobalAddress: O << Mang->getValueName(MO.getGlobal()); return; default: O << "<unknown operand type: " << MO.getType() << ">"; return; } } /// printMachineInstruction -- Print out a single Alpha MI to /// the current output stream. /// void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) { ++EmittedInsts; if (printInstruction(MI)) return; // Printer was automatically generated assert(0 && "Unhandled instruction in asm writer!"); abort(); return; } /// runOnMachineFunction - This uses the printMachineInstruction() /// method to print assembly for each instruction. /// bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) { setupMachineFunction(MF); O << "\n\n"; if (CurrentFnName.compare("main") == 0) { // O << "\n\n#HACK\n\t.text\n\t.ent __main\n__main:\n\tret $31,($26),1\n\t.end __main\n#ENDHACK\n\n"; } // Print out constants referenced by the function printConstantPool(MF.getConstantPool()); // Print out labels for the function. O << "\t.text\n"; emitAlignment(2); O << "\t.globl\t" << CurrentFnName << "\n"; O << "\t.ent\t" << CurrentFnName << "\n"; O << CurrentFnName << ":\n"; // Print out code for the function. for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E; ++I) { // Print a label for the basic block. O << "$LBB" << CurrentFnName << "_" << I->getNumber() << ":\t" << CommentString << " " << I->getBasicBlock()->getName() << "\n"; for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end(); II != E; ++II) { // Print the assembly for the instruction. O << "\t"; printMachineInstruction(II); } } ++LabelNumber; O << "\t.end\t" << CurrentFnName << "\n"; // We didn't modify anything. return false; } /// printConstantPool - Print to the current output stream assembly /// representations of the constants in the constant pool MCP. This is /// used to print out constants which have been "spilled to memory" by /// the code generator. /// void AlphaAsmPrinter::printConstantPool(MachineConstantPool *MCP) { const std::vector<Constant*> &CP = MCP->getConstants(); const TargetData &TD = TM.getTargetData(); if (CP.empty()) return; abort(); // for (unsigned i = 0, e = CP.size(); i != e; ++i) { // O << "\t.section\t.rodata\n"; // emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType())); // O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString // << *CP[i] << "\n"; // //emitGlobalConstant(CP[i]); // } } bool AlphaAsmPrinter::doInitialization(Module &M) { AsmPrinter::doInitialization(M); O << "\t.arch ev56\n"; return false; } // SwitchSection - Switch to the specified section of the executable if we are // not already in it! // static void SwitchSection(std::ostream &OS, std::string &CurSection, const char *NewSection) { if (CurSection != NewSection) { CurSection = NewSection; if (!CurSection.empty()) OS << "\t" << NewSection << "\n"; } } bool AlphaAsmPrinter::doFinalization(Module &M) { const TargetData &TD = TM.getTargetData(); std::string CurSection; for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) if (I->hasInitializer()) { // External global require no code O << "\n\n"; std::string name = Mang->getValueName(I); Constant *C = I->getInitializer(); unsigned Size = TD.getTypeSize(C->getType()); unsigned Align = TD.getTypeAlignmentShift(C->getType()); if (C->isNullValue() && (I->hasLinkOnceLinkage() || I->hasInternalLinkage() || I->hasWeakLinkage() /* FIXME: Verify correct */)) { SwitchSection(O, CurSection, ".data"); if (I->hasInternalLinkage()) O << "\t.local " << name << "\n"; O << "\t.comm " << name << "," << TD.getTypeSize(C->getType()) << "," << (1 << Align); O << "\t\t# "; WriteAsOperand(O, I, true, true, &M); O << "\n"; } else { switch (I->getLinkage()) { case GlobalValue::LinkOnceLinkage: case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak. // Nonnull linkonce -> weak O << "\t.weak " << name << "\n"; SwitchSection(O, CurSection, ""); O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"; break; case GlobalValue::AppendingLinkage: // FIXME: appending linkage variables should go into a section of // their name or something. For now, just emit them as external. case GlobalValue::ExternalLinkage: // If external or appending, declare as a global symbol O << "\t.globl " << name << "\n"; // FALL THROUGH case GlobalValue::InternalLinkage: if (C->isNullValue()) SwitchSection(O, CurSection, ".bss"); else SwitchSection(O, CurSection, ".data"); break; case GlobalValue::GhostLinkage: std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n"; abort(); } emitAlignment(Align); O << "\t.type " << name << ",@object\n"; O << "\t.size " << name << "," << Size << "\n"; O << name << ":\t\t\t\t# "; WriteAsOperand(O, I, true, true, &M); O << " = "; WriteAsOperand(O, C, false, false, &M); O << "\n"; emitGlobalConstant(C); } } AsmPrinter::doFinalization(M); return false; } <commit_msg>Print the Constant pool<commit_after>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a printer that converts from our internal representation // of machine-dependent LLVM code to GAS-format Alpha assembly language. // //===----------------------------------------------------------------------===// #include "Alpha.h" #include "AlphaInstrInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/Writer.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Mangler.h" #include "llvm/ADT/Statistic.h" using namespace llvm; namespace { Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); struct AlphaAsmPrinter : public AsmPrinter { /// Unique incrementer for label values for referencing Global values. /// unsigned LabelNumber; AlphaAsmPrinter(std::ostream &o, TargetMachine &tm) : AsmPrinter(o, tm), LabelNumber(0) { } /// We name each basic block in a Function with a unique number, so /// that we can consistently refer to them later. This is cleared /// at the beginning of each call to runOnMachineFunction(). /// typedef std::map<const Value *, unsigned> ValueMapTy; ValueMapTy NumberForBB; virtual const char *getPassName() const { return "Alpha Assembly Printer"; } bool printInstruction(const MachineInstr *MI); void printOp(const MachineOperand &MO, bool IsCallOp = false); void printConstantPool(MachineConstantPool *MCP); void printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT); void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true); void printMachineInstruction(const MachineInstr *MI); bool runOnMachineFunction(MachineFunction &F); bool doInitialization(Module &M); bool doFinalization(Module &M); }; } // end of anonymous namespace /// createAlphaCodePrinterPass - Returns a pass that prints the Alpha /// assembly code for a MachineFunction to the given output stream, /// using the given target machine description. This should work /// regardless of whether the function is in SSA form. /// FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o, TargetMachine &tm) { return new AlphaAsmPrinter(o, tm); } #include "AlphaGenAsmWriter.inc" void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT) { const MachineOperand &MO = MI->getOperand(opNum); if (MO.getType() == MachineOperand::MO_MachineRegister) { assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??"); O << TM.getRegisterInfo()->get(MO.getReg()).Name; } else if (MO.isImmediate()) { O << MO.getImmedValue(); } else { printOp(MO); } } void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) { const MRegisterInfo &RI = *TM.getRegisterInfo(); int new_symbol; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (Value *V = MO.getVRegValueOrNull()) { O << "<" << V->getName() << ">"; return; } // FALLTHROUGH case MachineOperand::MO_MachineRegister: case MachineOperand::MO_CCRegister: O << RI.get(MO.getReg()).Name; return; case MachineOperand::MO_SignExtendedImmed: case MachineOperand::MO_UnextendedImmed: std::cerr << "printOp() does not handle immediate values\n"; abort(); return; case MachineOperand::MO_PCRelativeDisp: std::cerr << "Shouldn't use addPCDisp() when building Alpha MachineInstrs"; abort(); return; case MachineOperand::MO_MachineBasicBlock: { MachineBasicBlock *MBBOp = MO.getMachineBasicBlock(); O << "$LBB" << Mang->getValueName(MBBOp->getParent()->getFunction()) << "_" << MBBOp->getNumber() << "\t" << CommentString << " " << MBBOp->getBasicBlock()->getName(); return; } case MachineOperand::MO_ConstantPoolIndex: O << "$CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex(); return; case MachineOperand::MO_ExternalSymbol: O << MO.getSymbolName(); return; case MachineOperand::MO_GlobalAddress: O << Mang->getValueName(MO.getGlobal()); return; default: O << "<unknown operand type: " << MO.getType() << ">"; return; } } /// printMachineInstruction -- Print out a single Alpha MI to /// the current output stream. /// void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) { ++EmittedInsts; if (printInstruction(MI)) return; // Printer was automatically generated assert(0 && "Unhandled instruction in asm writer!"); abort(); return; } /// runOnMachineFunction - This uses the printMachineInstruction() /// method to print assembly for each instruction. /// bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) { setupMachineFunction(MF); O << "\n\n"; if (CurrentFnName.compare("main") == 0) { // O << "\n\n#HACK\n\t.text\n\t.ent __main\n__main:\n\tret $31,($26),1\n\t.end __main\n#ENDHACK\n\n"; } // Print out constants referenced by the function printConstantPool(MF.getConstantPool()); // Print out labels for the function. O << "\t.text\n"; emitAlignment(2); O << "\t.globl\t" << CurrentFnName << "\n"; O << "\t.ent\t" << CurrentFnName << "\n"; O << CurrentFnName << ":\n"; // Print out code for the function. for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E; ++I) { // Print a label for the basic block. O << "$LBB" << CurrentFnName << "_" << I->getNumber() << ":\t" << CommentString << " " << I->getBasicBlock()->getName() << "\n"; for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end(); II != E; ++II) { // Print the assembly for the instruction. O << "\t"; printMachineInstruction(II); } } ++LabelNumber; O << "\t.end\t" << CurrentFnName << "\n"; // We didn't modify anything. return false; } /// printConstantPool - Print to the current output stream assembly /// representations of the constants in the constant pool MCP. This is /// used to print out constants which have been "spilled to memory" by /// the code generator. /// void AlphaAsmPrinter::printConstantPool(MachineConstantPool *MCP) { const std::vector<Constant*> &CP = MCP->getConstants(); const TargetData &TD = TM.getTargetData(); if (CP.empty()) return; for (unsigned i = 0, e = CP.size(); i != e; ++i) { O << "\t.section\t.rodata\n"; emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType())); O << "$CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString << *CP[i] << "\n"; emitGlobalConstant(CP[i]); } } bool AlphaAsmPrinter::doInitialization(Module &M) { AsmPrinter::doInitialization(M); O << "\t.arch ev56\n"; return false; } // SwitchSection - Switch to the specified section of the executable if we are // not already in it! // static void SwitchSection(std::ostream &OS, std::string &CurSection, const char *NewSection) { if (CurSection != NewSection) { CurSection = NewSection; if (!CurSection.empty()) OS << "\t" << NewSection << "\n"; } } bool AlphaAsmPrinter::doFinalization(Module &M) { const TargetData &TD = TM.getTargetData(); std::string CurSection; for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) if (I->hasInitializer()) { // External global require no code O << "\n\n"; std::string name = Mang->getValueName(I); Constant *C = I->getInitializer(); unsigned Size = TD.getTypeSize(C->getType()); unsigned Align = TD.getTypeAlignmentShift(C->getType()); if (C->isNullValue() && (I->hasLinkOnceLinkage() || I->hasInternalLinkage() || I->hasWeakLinkage() /* FIXME: Verify correct */)) { SwitchSection(O, CurSection, ".data"); if (I->hasInternalLinkage()) O << "\t.local " << name << "\n"; O << "\t.comm " << name << "," << TD.getTypeSize(C->getType()) << "," << (1 << Align); O << "\t\t# "; WriteAsOperand(O, I, true, true, &M); O << "\n"; } else { switch (I->getLinkage()) { case GlobalValue::LinkOnceLinkage: case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak. // Nonnull linkonce -> weak O << "\t.weak " << name << "\n"; SwitchSection(O, CurSection, ""); O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"; break; case GlobalValue::AppendingLinkage: // FIXME: appending linkage variables should go into a section of // their name or something. For now, just emit them as external. case GlobalValue::ExternalLinkage: // If external or appending, declare as a global symbol O << "\t.globl " << name << "\n"; // FALL THROUGH case GlobalValue::InternalLinkage: if (C->isNullValue()) SwitchSection(O, CurSection, ".bss"); else SwitchSection(O, CurSection, ".data"); break; case GlobalValue::GhostLinkage: std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n"; abort(); } emitAlignment(Align); O << "\t.type " << name << ",@object\n"; O << "\t.size " << name << "," << Size << "\n"; O << name << ":\t\t\t\t# "; WriteAsOperand(O, I, true, true, &M); O << " = "; WriteAsOperand(O, C, false, false, &M); O << "\n"; emitGlobalConstant(C); } } AsmPrinter::doFinalization(M); return false; } <|endoftext|>
<commit_before>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Bruno Cardoso Lopes and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MIPS implementation of the MRegisterInfo class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "mips-reg-info" #include "Mips.h" #include "MipsRegisterInfo.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/Function.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/STLExtras.h" //#include "MipsSubtarget.h" using namespace llvm; // TODO: add subtarget support MipsRegisterInfo::MipsRegisterInfo(const TargetInstrInfo &tii) : MipsGenRegisterInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP), TII(tii) {} void MipsRegisterInfo:: storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, int FI, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::SW)).addFrameIndex(FI) .addImm(0).addReg(SrcReg, false, false, true); else assert(0 && "Can't store this register to stack slot"); } void MipsRegisterInfo:: loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, int FI, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::LW), DestReg).addImm(0).addFrameIndex(FI); else assert(0 && "Can't load this register from stack slot"); } void MipsRegisterInfo:: copyRegToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, unsigned SrcReg, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::ADDu), DestReg).addReg(Mips::ZERO) .addReg(SrcReg); else assert (0 && "Can't copy this register"); } void MipsRegisterInfo::reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, const MachineInstr *Orig) const { MachineInstr *MI = Orig->clone(); MI->getOperand(0).setReg(DestReg); MBB.insert(I, MI); } MachineInstr *MipsRegisterInfo:: foldMemoryOperand(MachineInstr* MI, unsigned OpNum, int FI) const { MachineInstr *NewMI = NULL; switch (MI->getOpcode()) { case Mips::ADDu: if ((MI->getOperand(0).isRegister()) && (MI->getOperand(1).isRegister()) && (MI->getOperand(1).getReg() == Mips::ZERO) && (MI->getOperand(2).isRegister())) { if (OpNum == 0) // COPY -> STORE NewMI = BuildMI(TII.get(Mips::SW)).addFrameIndex(FI) .addImm(0).addReg(MI->getOperand(2).getReg()); else // COPY -> LOAD NewMI = BuildMI(TII.get(Mips::LW), MI->getOperand(0) .getReg()).addImm(0).addFrameIndex(FI); } break; } if (NewMI) NewMI->copyKillDeadInfo(MI); return NewMI; } /// Mips Callee Saved Registers const unsigned* MipsRegisterInfo:: getCalleeSavedRegs() const { // Mips calle-save register range is $16-$26(s0-s7) static const unsigned CalleeSavedRegs[] = { Mips::S0, Mips::S1, Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 0 }; return CalleeSavedRegs; } /// Mips Callee Saved Register Classes const TargetRegisterClass* const* MipsRegisterInfo::getCalleeSavedRegClasses() const { static const TargetRegisterClass * const CalleeSavedRegClasses[] = { &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, 0 }; return CalleeSavedRegClasses; } BitVector MipsRegisterInfo:: getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); Reserved.set(Mips::ZERO); Reserved.set(Mips::AT); Reserved.set(Mips::K0); Reserved.set(Mips::K1); Reserved.set(Mips::GP); Reserved.set(Mips::SP); Reserved.set(Mips::FP); Reserved.set(Mips::RA); return Reserved; } //===----------------------------------------------------------------------===// // Stack Frame Processing methods //===----------------------------------------------------------------------===// // True if target has frame pointer bool MipsRegisterInfo:: hasFP(const MachineFunction &MF) const { return false; } // This function eliminate ADJCALLSTACKDOWN, // ADJCALLSTACKUP pseudo instructions void MipsRegisterInfo:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions. MBB.erase(I); } // FrameIndex represent objects inside a abstract stack. // We must replace FrameIndex with an stack/frame pointer // direct reference. void MipsRegisterInfo:: eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, RegScavenger *RS) const { unsigned i = 0; MachineInstr &MI = *II; MachineFunction &MF = *MI.getParent()->getParent(); while (!MI.getOperand(i).isFrameIndex()) { ++i; assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!"); } // FrameInfo addressable stack objects are accessed // using neg. offsets, so we must add with the stack // size to obtain $sp relative address. int FrameIndex = MI.getOperand(i).getFrameIndex(); int stackSize = MF.getFrameInfo()->getStackSize(); int spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex); #ifndef NDEBUG DOUT << "\n<--------->\n"; MI.print(DOUT); DOUT << "FrameIndex : " << FrameIndex << "\n"; DOUT << "spOffset : " << spOffset << "\n"; DOUT << "stackSize : " << stackSize << "\n"; #endif // If the FrameIndex points to a positive SPOffset this // means we are inside the callee and getting the arguments // from the caller stack int Offset = (-(stackSize)) + spOffset; #ifndef NDEBUG DOUT << "Offset : " << Offset << "\n"; DOUT << "<--------->\n"; #endif MI.getOperand(i-1).ChangeToImmediate(Offset); MI.getOperand(i).ChangeToRegister(Mips::SP,false); } void MipsRegisterInfo:: emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); MachineFrameInfo *MFI = MF.getFrameInfo(); // Get the number of bytes to allocate from the FrameInfo int NumBytes = (int) MFI->getStackSize(); // Do we need to allocate space on the stack? if (NumBytes == 0) return; // FIXME: is Stack Align needed here ?? (maybe it's done before...) unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment(); NumBytes = -((NumBytes+Align-1)/Align*Align); // Update frame info to pretend that this is part of the stack... MFI->setStackSize(NumBytes); // adjust stack : addi sp, sp, (-imm) BuildMI(MBB, MBB.begin(), TII.get(Mips::ADDi), Mips::SP) .addReg(Mips::SP).addImm(NumBytes); } void MipsRegisterInfo:: emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = prior(MBB.end()); MachineFrameInfo *MFI = MF.getFrameInfo(); // Get the number of bytes from FrameInfo int NumBytes = (int) MFI->getStackSize(); // adjust stack : insert addi sp, sp, (imm) if (NumBytes) { BuildMI(MBB, MBBI, TII.get(Mips::ADDi), Mips::SP) .addReg(Mips::SP).addImm(-NumBytes); } } void MipsRegisterInfo:: processFunctionBeforeFrameFinalized(MachineFunction &MF) const {} unsigned MipsRegisterInfo:: getRARegister() const { return Mips::RA; } unsigned MipsRegisterInfo:: getFrameRegister(MachineFunction &MF) const { assert(0 && "What is the frame register"); return Mips::FP; } unsigned MipsRegisterInfo:: getEHExceptionRegister() const { assert(0 && "What is the exception register"); return 0; } unsigned MipsRegisterInfo:: getEHHandlerRegister() const { assert(0 && "What is the exception handler register"); return 0; } #include "MipsGenRegisterInfo.inc" <commit_msg>Added support for framepointer Prologue/Epilogue support fp,ra save/restore and use the stack frame the right way!<commit_after>//===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Bruno Cardoso Lopes and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MIPS implementation of the MRegisterInfo class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "mips-reg-info" #include "Mips.h" #include "MipsRegisterInfo.h" #include "MipsMachineFunction.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/Function.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/BitVector.h" #include "llvm/ADT/STLExtras.h" //#include "MipsSubtarget.h" using namespace llvm; // TODO: add subtarget support MipsRegisterInfo::MipsRegisterInfo(const TargetInstrInfo &tii) : MipsGenRegisterInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP), TII(tii) {} void MipsRegisterInfo:: storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, int FI, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::SW)).addReg(SrcReg, false, false, true) .addImm(0).addFrameIndex(FI); else assert(0 && "Can't store this register to stack slot"); } void MipsRegisterInfo:: loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, int FI, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::LW), DestReg).addImm(0).addFrameIndex(FI); else assert(0 && "Can't load this register from stack slot"); } void MipsRegisterInfo:: copyRegToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, unsigned SrcReg, const TargetRegisterClass *RC) const { if (RC == Mips::CPURegsRegisterClass) BuildMI(MBB, I, TII.get(Mips::ADDu), DestReg).addReg(Mips::ZERO) .addReg(SrcReg); else assert (0 && "Can't copy this register"); } void MipsRegisterInfo::reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, const MachineInstr *Orig) const { MachineInstr *MI = Orig->clone(); MI->getOperand(0).setReg(DestReg); MBB.insert(I, MI); } MachineInstr *MipsRegisterInfo:: foldMemoryOperand(MachineInstr* MI, unsigned OpNum, int FI) const { MachineInstr *NewMI = NULL; switch (MI->getOpcode()) { case Mips::ADDu: if ((MI->getOperand(0).isRegister()) && (MI->getOperand(1).isRegister()) && (MI->getOperand(1).getReg() == Mips::ZERO) && (MI->getOperand(2).isRegister())) { if (OpNum == 0) // COPY -> STORE NewMI = BuildMI(TII.get(Mips::SW)).addFrameIndex(FI) .addImm(0).addReg(MI->getOperand(2).getReg()); else // COPY -> LOAD NewMI = BuildMI(TII.get(Mips::LW), MI->getOperand(0) .getReg()).addImm(0).addFrameIndex(FI); } break; } if (NewMI) NewMI->copyKillDeadInfo(MI); return NewMI; } /// Mips Callee Saved Registers const unsigned* MipsRegisterInfo:: getCalleeSavedRegs() const { // Mips calle-save register range is $16-$26(s0-s7) static const unsigned CalleeSavedRegs[] = { Mips::S0, Mips::S1, Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7, 0 }; return CalleeSavedRegs; } /// Mips Callee Saved Register Classes const TargetRegisterClass* const* MipsRegisterInfo::getCalleeSavedRegClasses() const { static const TargetRegisterClass * const CalleeSavedRegClasses[] = { &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, 0 }; return CalleeSavedRegClasses; } BitVector MipsRegisterInfo:: getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); Reserved.set(Mips::ZERO); Reserved.set(Mips::AT); Reserved.set(Mips::K0); Reserved.set(Mips::K1); Reserved.set(Mips::GP); Reserved.set(Mips::SP); Reserved.set(Mips::FP); Reserved.set(Mips::RA); return Reserved; } //===----------------------------------------------------------------------===// // // Stack Frame Processing methods // +----------------------------+ // // Too meet ABI, we construct the frame on the reverse // of natural order. // // The LLVM Frame will look like this: // // As the stack grows down, we start at 0, and the reference // is decrement. // // 0 ---------- // -4 Args to pass // . saved "Callee Saved" Registers // . Local Area // . saved FP // . saved RA // -StackSize ----------- // // On the EliminateFrameIndex we just negate the address above // and we get the stack frame required by the ABI, which is: // // sp + stacksize ------------- // saved $RA (only on non-leaf functions) // saved $FP (only with frame pointer) // saved "Callee Saved" Registers // Local Area // saved $GP (used in PIC - not supported yet) // Args to pass area // sp ------------- // // The sp is the stack pointer subtracted/added from the stack size // at the Prologue/Epilogue // // References to the previous stack (to obtain arguments) are done // with fixed location stack frames using positive stack offsets. // // Examples: // - reference to the actual stack frame // for any local area var there is smt like : FI >= 0, StackOffset: -4 // sw REGX, 4(REGY) // // - reference to previous stack frame // suppose there's a store to the 5th arguments : FI < 0, StackOffset: 16. // The emitted instruction will be something like: // sw REGX, 16+StackSize (REGY) // //===----------------------------------------------------------------------===// // hasFP - Return true if the specified function should have a dedicated frame // pointer register. This is true if the function has variable sized allocas or // if frame pointer elimination is disabled. bool MipsRegisterInfo:: hasFP(const MachineFunction &MF) const { return (NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects()); } // This function eliminate ADJCALLSTACKDOWN, // ADJCALLSTACKUP pseudo instructions void MipsRegisterInfo:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions. MBB.erase(I); } // FrameIndex represent objects inside a abstract stack. // We must replace FrameIndex with an stack/frame pointer // direct reference. void MipsRegisterInfo:: eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, RegScavenger *RS) const { MachineInstr &MI = *II; MachineFunction &MF = *MI.getParent()->getParent(); unsigned i = 0; while (!MI.getOperand(i).isFrameIndex()) { ++i; assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!"); } int FrameIndex = MI.getOperand(i).getFrameIndex(); int stackSize = MF.getFrameInfo()->getStackSize(); int spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex); #ifndef NDEBUG DOUT << "\nFunction : " << MF.getFunction()->getName() << "\n"; DOUT << "<--------->\n"; MI.print(DOUT); DOUT << "FrameIndex : " << FrameIndex << "\n"; DOUT << "spOffset : " << spOffset << "\n"; DOUT << "stackSize : " << stackSize << "\n"; #endif int Offset = ( (spOffset >= 0) ? (stackSize + spOffset) : (-spOffset)); #ifndef NDEBUG DOUT << "Offset : " << Offset << "\n"; DOUT << "<--------->\n"; #endif MI.getOperand(i-1).ChangeToImmediate(Offset); MI.getOperand(i).ChangeToRegister(getFrameRegister(MF),false); } void MipsRegisterInfo:: emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); MachineBasicBlock::iterator MBBI = MBB.begin(); // Get the number of bytes to allocate from the FrameInfo int NumBytes = (int) MFI->getStackSize(); #ifndef NDEBUG DOUT << "\n<--- EMIT PROLOGUE --->"; DOUT << "Stack size :" << NumBytes << "\n"; #endif // Do we need to allocate space on the stack? if (NumBytes == 0) return; int FPOffset, RAOffset; // Always allocate space for saved RA and FP, // even if FramePointer is not used. When not // using FP, the last stack slot becomes empty // and RA is saved before it. if ((hasFP(MF)) && (MFI->hasCalls())) { FPOffset = NumBytes; RAOffset = (NumBytes+4); } else if ((!hasFP(MF)) && (MFI->hasCalls())) { FPOffset = 0; RAOffset = NumBytes; } else if ((hasFP(MF)) && (!MFI->hasCalls())) { FPOffset = NumBytes; RAOffset = 0; } MFI->setObjectOffset(MFI->CreateStackObject(4,4), -FPOffset); MFI->setObjectOffset(MFI->CreateStackObject(4,4), -RAOffset); MipsFI->setFPStackOffset(FPOffset); MipsFI->setRAStackOffset(RAOffset); #ifndef NDEBUG DOUT << "FPOffset :" << FPOffset << "\n"; DOUT << "RAOffset :" << RAOffset << "\n"; #endif // Align stack. NumBytes += 8; unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment(); NumBytes = ((NumBytes+Align-1)/Align*Align); #ifndef NDEBUG DOUT << "New stack size :" << NumBytes << "\n\n"; #endif // Update frame info MFI->setStackSize(NumBytes); // Adjust stack : addi sp, sp, (-imm) BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP) .addReg(Mips::SP).addImm(-NumBytes); // Save the return address only if the function isnt a leaf one. // sw $ra, stack_loc($sp) if (MFI->hasCalls()) { BuildMI(MBB, MBBI, TII.get(Mips::SW)) .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP); } // if framepointer enabled, save it and set it // to point to the stack pointer if (hasFP(MF)) { // sw $fp,stack_loc($sp) BuildMI(MBB, MBBI, TII.get(Mips::SW)) .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP); // move $fp, $sp BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::FP) .addReg(Mips::SP).addReg(Mips::ZERO); } } void MipsRegisterInfo:: emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = prior(MBB.end()); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); // Get the number of bytes from FrameInfo int NumBytes = (int) MFI->getStackSize(); // Get the FI's where RA and FP are saved. int FPOffset = MipsFI->getFPStackOffset(); int RAOffset = MipsFI->getRAStackOffset(); #ifndef NDEBUG DOUT << "\n<--- EMIT EPILOGUE --->" << "\n"; DOUT << "Stack size :" << NumBytes << "\n"; DOUT << "FPOffset :" << FPOffset << "\n"; DOUT << "RAOffset :" << RAOffset << "\n\n"; #endif // if framepointer enabled, restore it and restore the // stack pointer if (hasFP(MF)) { // move $sp, $fp BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::SP) .addReg(Mips::FP).addReg(Mips::ZERO); // lw $fp,stack_loc($sp) BuildMI(MBB, MBBI, TII.get(Mips::LW)) .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP); } // Restore the return address only if the function isnt a leaf one. // lw $ra, stack_loc($sp) if (MFI->hasCalls()) { BuildMI(MBB, MBBI, TII.get(Mips::LW)) .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP); } // adjust stack : insert addi sp, sp, (imm) if (NumBytes) { BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP) .addReg(Mips::SP).addImm(NumBytes); } } void MipsRegisterInfo:: processFunctionBeforeFrameFinalized(MachineFunction &MF) const { } unsigned MipsRegisterInfo:: getRARegister() const { return Mips::RA; } unsigned MipsRegisterInfo:: getFrameRegister(MachineFunction &MF) const { return hasFP(MF) ? Mips::FP : Mips::SP; } unsigned MipsRegisterInfo:: getEHExceptionRegister() const { assert(0 && "What is the exception register"); return 0; } unsigned MipsRegisterInfo:: getEHHandlerRegister() const { assert(0 && "What is the exception handler register"); return 0; } #include "MipsGenRegisterInfo.inc" <|endoftext|>
<commit_before>//===- LoopExtractor.cpp - Extract each loop into a new function ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // A pass wrapper around the ExtractLoop() scalar transformation to extract each // top-level loop into its own new function. If the loop is the ONLY loop in a // given function, it is not touched. This is a pass most useful for debugging // via bugpoint. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/iTerminators.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/FunctionUtils.h" using namespace llvm; namespace { // FIXME: This is not a function pass, but the PassManager doesn't allow // Module passes to require FunctionPasses, so we can't get loop info if we're // not a function pass. struct LoopExtractor : public FunctionPass { unsigned NumLoops; LoopExtractor(unsigned numLoops = ~0) : NumLoops(numLoops) {} virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequiredID(BreakCriticalEdgesID); AU.addRequiredID(LoopSimplifyID); AU.addRequired<DominatorSet>(); AU.addRequired<LoopInfo>(); } }; RegisterOpt<LoopExtractor> X("loop-extract", "Extract loops into new functions"); /// SingleLoopExtractor - For bugpoint. struct SingleLoopExtractor : public LoopExtractor { SingleLoopExtractor() : LoopExtractor(1) {} }; RegisterOpt<SingleLoopExtractor> Y("loop-extract-single", "Extract at most one loop into a new function"); } // End anonymous namespace bool LoopExtractor::runOnFunction(Function &F) { LoopInfo &LI = getAnalysis<LoopInfo>(); // If this function has no loops, there is nothing to do. if (LI.begin() == LI.end()) return false; DominatorSet &DS = getAnalysis<DominatorSet>(); // If there is more than one top-level loop in this function, extract all of // the loops. bool Changed = false; if (LI.end()-LI.begin() > 1) { for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, *i) != 0; } } else { // Otherwise there is exactly one top-level loop. If this function is more // than a minimal wrapper around the loop, extract the loop. Loop *TLL = *LI.begin(); bool ShouldExtractLoop = false; // Extract the loop if the entry block doesn't branch to the loop header. TerminatorInst *EntryTI = F.getEntryBlock().getTerminator(); if (!isa<BranchInst>(EntryTI) || !cast<BranchInst>(EntryTI)->isUnconditional() || EntryTI->getSuccessor(0) != TLL->getHeader()) ShouldExtractLoop = true; else { // Check to see if any exits from the loop are more than just return // blocks. for (unsigned i = 0, e = TLL->getExitBlocks().size(); i != e; ++i) if (!isa<ReturnInst>(TLL->getExitBlocks()[i]->getTerminator())) { ShouldExtractLoop = true; break; } } if (ShouldExtractLoop) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, TLL) != 0; } else { // Okay, this function is a minimal container around the specified loop. // If we extract the loop, we will continue to just keep extracting it // infinitely... so don't extract it. However, if the loop contains any // subloops, extract them. for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, *i) != 0; } } } return Changed; } // createSingleLoopExtractorPass - This pass extracts one natural loop from the // program into a function if it can. This is used by bugpoint. // Pass *llvm::createSingleLoopExtractorPass() { return new SingleLoopExtractor(); } <commit_msg>Add statistics to the loop extractor. The loop extractor has successfully extracted all 63 loops for Olden/bh without crashing and without miscompiling the program!!!<commit_after>//===- LoopExtractor.cpp - Extract each loop into a new function ----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // A pass wrapper around the ExtractLoop() scalar transformation to extract each // top-level loop into its own new function. If the loop is the ONLY loop in a // given function, it is not touched. This is a pass most useful for debugging // via bugpoint. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/iTerminators.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/FunctionUtils.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumExtracted("loop-extract", "Number of loops extracted"); // FIXME: This is not a function pass, but the PassManager doesn't allow // Module passes to require FunctionPasses, so we can't get loop info if we're // not a function pass. struct LoopExtractor : public FunctionPass { unsigned NumLoops; LoopExtractor(unsigned numLoops = ~0) : NumLoops(numLoops) {} virtual bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequiredID(BreakCriticalEdgesID); AU.addRequiredID(LoopSimplifyID); AU.addRequired<DominatorSet>(); AU.addRequired<LoopInfo>(); } }; RegisterOpt<LoopExtractor> X("loop-extract", "Extract loops into new functions"); /// SingleLoopExtractor - For bugpoint. struct SingleLoopExtractor : public LoopExtractor { SingleLoopExtractor() : LoopExtractor(1) {} }; RegisterOpt<SingleLoopExtractor> Y("loop-extract-single", "Extract at most one loop into a new function"); } // End anonymous namespace bool LoopExtractor::runOnFunction(Function &F) { LoopInfo &LI = getAnalysis<LoopInfo>(); // If this function has no loops, there is nothing to do. if (LI.begin() == LI.end()) return false; DominatorSet &DS = getAnalysis<DominatorSet>(); // If there is more than one top-level loop in this function, extract all of // the loops. bool Changed = false; if (LI.end()-LI.begin() > 1) { for (LoopInfo::iterator i = LI.begin(), e = LI.end(); i != e; ++i) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, *i) != 0; ++NumExtracted; } } else { // Otherwise there is exactly one top-level loop. If this function is more // than a minimal wrapper around the loop, extract the loop. Loop *TLL = *LI.begin(); bool ShouldExtractLoop = false; // Extract the loop if the entry block doesn't branch to the loop header. TerminatorInst *EntryTI = F.getEntryBlock().getTerminator(); if (!isa<BranchInst>(EntryTI) || !cast<BranchInst>(EntryTI)->isUnconditional() || EntryTI->getSuccessor(0) != TLL->getHeader()) ShouldExtractLoop = true; else { // Check to see if any exits from the loop are more than just return // blocks. for (unsigned i = 0, e = TLL->getExitBlocks().size(); i != e; ++i) if (!isa<ReturnInst>(TLL->getExitBlocks()[i]->getTerminator())) { ShouldExtractLoop = true; break; } } if (ShouldExtractLoop) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, TLL) != 0; ++NumExtracted; } else { // Okay, this function is a minimal container around the specified loop. // If we extract the loop, we will continue to just keep extracting it // infinitely... so don't extract it. However, if the loop contains any // subloops, extract them. for (Loop::iterator i = TLL->begin(), e = TLL->end(); i != e; ++i) { if (NumLoops == 0) return Changed; --NumLoops; Changed |= ExtractLoop(DS, *i) != 0; ++NumExtracted; } } } return Changed; } // createSingleLoopExtractorPass - This pass extracts one natural loop from the // program into a function if it can. This is used by bugpoint. // Pass *llvm::createSingleLoopExtractorPass() { return new SingleLoopExtractor(); } <|endoftext|>
<commit_before>#include "headers/mainwindow.h" #include "headers/cryptogame.h" #include "ui_mainwindow.h" #include "QPushButton" #include <QLayoutItem> #include <QMessageBox> #include "headers/buttonarray.h" #include "headers/labelarray.h" #include "iostream" //for debugging MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { connect(&threadCrack, SIGNAL(finished()), this, SLOT(update_crack_result())); connect(&threadFactor, SIGNAL(finished()), this, SLOT(update_factor_result())); ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; threadCrack.quit(); threadFactor.quit(); //delete hashAlg; } void MainWindow::on_pushButton_clicked() { std::cout<<"Start the game."<<std::endl; std::cout<<"Rows: " << ui->gameGrid->rowCount()<<std::endl; std::cout<<"Columns: " << ui->gameGrid->columnCount()<<std::endl; /*if(buttonPtrs){ delete buttonPtrs; } */ //QLayoutItem *nullLayout = NULL; //Delete all buttons in the and labels in the gameGrid for(int i=0; i<ui->gameGrid->columnCount(); i++){ QLayoutItem *button = ui->gameGrid->itemAtPosition(1,i); if(button){ delete button->widget(); //delete button; //QLayoutItem::~QLayoutItem(); std::cout<<"Deleting button number: " << i<<std::endl; } QLayoutItem *label = ui->gameGrid->itemAtPosition(0,i); if(label){ delete label->widget(); } /* delete label->widget(); delete label;*/ } agame = new cryptogame(); QString q = QString::fromStdString(agame->getEncryptedMessage()); //ui->label->setText(q); LabelArray *lptr = new LabelArray(q, ui->tabWidget); ButtonArray *buttonPtrs = new ButtonArray(q, ui->tabWidget, agame); for(int i=0; i<q.size(); i++){ ui->gameGrid->addWidget(lptr->get(i), 0, i); ui->gameGrid->addWidget(buttonPtrs->get(i), 1, i); } guessedWord.clear(); guessedWord = buttonPtrs->checkGuess(); } void MainWindow::on_pushButton_2_clicked(){} void MainWindow::on_pushButton_3_clicked() { //Somehow give a hint to the player. QMessageBox winningMessage; //Note: there are tabs in the QString in the next sentence winningMessage.setText("Here's a hint: There are no hints "); winningMessage.exec(); // ui->textEdit->setText("Here's a hint: There are no hints"); } void MainWindow::on_factorPrimesButton_clicked() { //reset label text ui->resultLabel->setText(QString::fromStdString("Result:")); ui->timeLabel->setText(QString::fromStdString("Time: ")); ui->resultLabel->repaint(); ui->timeLabel->repaint(); //set algorithm int algChoice = ui->factorAlgChooser->currentIndex(); Factor* pf; switch(algChoice) { case 0: pf = new BruteForceFactor(); break; case 1: //Quadratic sieve here std::cout<<"Quadratic sieve feature is in progress!"<<std::endl; return; break; } mpz_class composite; string s = ui->compositeTextField->text().toStdString(); composite.set_str(s, 10); threadFactor.setFactor(pf, composite); threadFactor.work(); } void MainWindow::on_random_composite_clicked() { mpz_class composite, p, q; GeneratePrimes gp = GeneratePrimes(); p = gp.readRandomPrime((char*)"primes.txt"); q = gp.readRandomPrime((char*)"primes.txt"); composite = p * q; string s = composite.get_str(10); ui->compositeTextField->setText(QString::fromStdString(s)); } void MainWindow::on_hashButton_clicked() { switch(ui->hashComboBox->currentIndex()) { case 0: hashAlg = new Md5(); break; case 1: hashAlg = new Sha512(); break; case 2: hashAlg = new Pbkdf2(); break; } hashAlg->setPlaintext(ui->plaintextField->text()); if(ui->saltField->text() != "") { //if not empty hashAlg->setSalt(ui->saltField->text()); } hashAlg->compute(); digest = hashAlg->getDigest(); ui->digestField->setText(digest); //Perhaps make this an option? //hashAlg->salt = ""; } void MainWindow::on_randomSaltButton_clicked() { Hash h; h.generateSalt(16); ui->saltField->setText(h.getSalt()); } void MainWindow::on_crackButton_clicked() { //reset label text ui->crackTimeLabel->setText("Time: "); ui->crackTimeLabel->repaint(); ui->crackedField->setText(""); ui->crackedField->repaint(); Crack* c; if(hashAlg == NULL) { return; } switch(ui->crackComboBox->currentIndex()) { case 0: {int maxLength = ui->charCountSpinBox->text().toInt(); c = new BruteForceCrack(hashAlg,bruteForceAlphabet(), maxLength); break;} case 1: {c = new DictionaryCrack(hashAlg, "../dictionary.txt"); dictionaryOptions(c); break;} } c->digest = digest.toStdString(); threadCrack.setCrackType(c); threadCrack.work(); } void MainWindow::update_crack_result() { long elapsed; bool success; elapsed = threadCrack.getResult(); Crack* c = threadCrack.getCrack(); success = c->getPlaintext().length(); if(success) { ui->crackedField->setText(c->getPlaintext()); } else { ui->crackedField->setText("\"Uncrackable!!\""); } string s = "Time: " + std::to_string(elapsed) + " ms"; ui->crackTimeLabel->setText(QString::fromStdString(s)); } void MainWindow::update_factor_result() { long elapsed = threadFactor.getResult(); Factor* pf = threadFactor.getFactor(); string s = "Time: " + std::to_string(elapsed) + " ms"; ui->timeLabel->setText(QString::fromStdString(s)); s = "Result: " + pf->p1.get_str(10) + " * " + pf->p2.get_str(10); ui->resultLabel->setText(QString::fromStdString(s)); } std::string MainWindow::bruteForceAlphabet() { std::string alph = " ";//weird bug "fix" if(ui->customCheckBox->isChecked()) { return ui->alphabetField->text().toStdString(); } if(ui->lettersCheckBox->isChecked()) { alph += "abcdefghijklmnopqrstuvwxyz"; } if(ui->upCaseCheckBox->isChecked()) { alph += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } if(ui->numbersCheckBox->isChecked()) { alph += "1234567890"; } if(ui->symbolsCheckBox->isChecked()) { alph += "`~!@#$%^&*()_+-=,.<>/?'[]{}"; } return alph; } void MainWindow::dictionaryOptions(Crack* d) { unsigned int numWords = ui->wordCountSpinBox->text().toInt(); unsigned int appendedDigits = 0; if(ui->appendCheckBox->isChecked()) { appendedDigits = ui->digitCountSpinBox->text().toInt(); } unsigned int prependedDigits = 0; if(ui->prependCheckBox->isChecked()) { prependedDigits = ui->digitCountSpinBox->text().toInt(); } bool cap = ui->capCheckBox->isChecked(); bool symbols = ui->dictSymbolsCheckBox->isChecked(); d->setOptions(numWords,appendedDigits,prependedDigits,symbols,cap); } void MainWindow::on_drawFactoring_clicked() { //generate data int beginDigits = ui->startDigitsSpinBox->text().toInt(); int count = ui->dataPointsSpinBox->text().toInt(); std::vector<mpz_class> comps = GenerateData::composites(beginDigits, count); factorDataPoints = GenerateData::factor(comps, new BruteForceFactor); //draw points fg = new GraphWindow(ui->factoringGraphicsView, factorDataPoints); fg->vSize = 600; fg->hSize = 600; if(ui->factorLogScaleCheckBox->isChecked()) { fg->logScaleDraw(); } else { fg->draw(); } fg->addLabels("Milliseconds", "Number of digits"); fg->view->show(); } void MainWindow::on_plotCrackButton_clicked() { //grab hashing and cracking algorithms switch(ui->hashComboBox->currentIndex()) { case 0: hashAlg = new Md5(); break; case 1: hashAlg = new Sha512(); break; case 2: hashAlg = new Pbkdf2(); break; } Crack* c; if(hashAlg == NULL) { return; } switch(ui->crackComboBox->currentIndex()) { case 0: {int maxLength = ui->charCountSpinBox->text().toInt(); c = new BruteForceCrack(hashAlg,bruteForceAlphabet(), maxLength); break;} case 1: {c = new DictionaryCrack(hashAlg, "../dictionary.txt"); break;} } //generate data int beginChars = ui->charCountSpinBox_2->text().toInt(); int count = ui->crackPointCountSpinBox->text().toInt(); std::vector<std::string> strings = GenerateData::plaintexts(beginChars, count); std::vector<std::string> digests = GenerateData::getHashes(strings, hashAlg); crackDataPoints = GenerateData::crack(digests, c); //begin graphing cg = new GraphWindow(ui->crackGraphicsView, crackDataPoints); cg->vSize = 600; cg->hSize = 600; if(ui->hashLogScaleCheckBox->isChecked()) { cg->logScaleDraw(); } else { cg->draw(); } cg->addLabels("Milliseconds", "Number of characters"); cg->view->show(); } void MainWindow::on_hashLogScaleCheckBox_clicked() { if(cg == NULL) { std::cout << "graphwindow object not initialized. No action to take." << std::endl; return; } if(crackDataPoints.size() == 0) { std::cout << "No points to graph." << std::endl; return; } cg = new GraphWindow(ui->crackGraphicsView, crackDataPoints); cg->vSize = 600; cg->hSize = 600; if(ui->hashLogScaleCheckBox->isChecked()) { cg->logScaleDraw(); } else { cg->draw(); } cg->addLabels("Milliseconds", "Number of characters"); cg->view->show(); } void MainWindow::on_factorLogScaleCheckBox_clicked() { if(fg == NULL) { std::cout << "graphwindow object not initialized. No action to take." << std::endl; return; } if(factorDataPoints.size() == 0) { std::cout << "No points to graph." << std::endl; return; } fg = new GraphWindow(ui->factoringGraphicsView, factorDataPoints); fg->vSize = 600; fg->hSize = 600; if(ui->factorLogScaleCheckBox->isChecked()) { fg->logScaleDraw(); } else { fg->draw(); } fg->addLabels("Milliseconds", "Number of characters"); fg->view->show(); } <commit_msg>commented out some debugging print out statements<commit_after>#include "headers/mainwindow.h" #include "headers/cryptogame.h" #include "ui_mainwindow.h" #include "QPushButton" #include <QLayoutItem> #include <QMessageBox> #include "headers/buttonarray.h" #include "headers/labelarray.h" #include "iostream" //for debugging MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { connect(&threadCrack, SIGNAL(finished()), this, SLOT(update_crack_result())); connect(&threadFactor, SIGNAL(finished()), this, SLOT(update_factor_result())); ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; threadCrack.quit(); threadFactor.quit(); //delete hashAlg; } void MainWindow::on_pushButton_clicked() { // std::cout<<"Start the game."<<std::endl; // std::cout<<"Rows: " << ui->gameGrid->rowCount()<<std::endl; //std::cout<<"Columns: " << ui->gameGrid->columnCount()<<std::endl; /*if(buttonPtrs){ delete buttonPtrs; } */ //QLayoutItem *nullLayout = NULL; //Delete all buttons in the and labels in the gameGrid for(int i=0; i<ui->gameGrid->columnCount(); i++){ QLayoutItem *button = ui->gameGrid->itemAtPosition(1,i); if(button){ delete button->widget(); //delete button; //QLayoutItem::~QLayoutItem(); //std::cout<<"Deleting button number: " << i<<std::endl; } QLayoutItem *label = ui->gameGrid->itemAtPosition(0,i); if(label){ delete label->widget(); } /* delete label->widget(); delete label;*/ } agame = new cryptogame(); QString q = QString::fromStdString(agame->getEncryptedMessage()); //ui->label->setText(q); LabelArray *lptr = new LabelArray(q, ui->tabWidget); ButtonArray *buttonPtrs = new ButtonArray(q, ui->tabWidget, agame); for(int i=0; i<q.size(); i++){ ui->gameGrid->addWidget(lptr->get(i), 0, i); ui->gameGrid->addWidget(buttonPtrs->get(i), 1, i); } guessedWord.clear(); guessedWord = buttonPtrs->checkGuess(); } void MainWindow::on_pushButton_2_clicked(){} void MainWindow::on_pushButton_3_clicked() { //Somehow give a hint to the player. QMessageBox winningMessage; //Note: there are tabs in the QString in the next sentence winningMessage.setText("Here's a hint: There are no hints "); winningMessage.exec(); // ui->textEdit->setText("Here's a hint: There are no hints"); } void MainWindow::on_factorPrimesButton_clicked() { //reset label text ui->resultLabel->setText(QString::fromStdString("Result:")); ui->timeLabel->setText(QString::fromStdString("Time: ")); ui->resultLabel->repaint(); ui->timeLabel->repaint(); //set algorithm int algChoice = ui->factorAlgChooser->currentIndex(); Factor* pf; switch(algChoice) { case 0: pf = new BruteForceFactor(); break; case 1: //Quadratic sieve here std::cout<<"Quadratic sieve feature is in progress!"<<std::endl; return; break; } mpz_class composite; string s = ui->compositeTextField->text().toStdString(); composite.set_str(s, 10); threadFactor.setFactor(pf, composite); threadFactor.work(); } void MainWindow::on_random_composite_clicked() { mpz_class composite, p, q; GeneratePrimes gp = GeneratePrimes(); p = gp.readRandomPrime((char*)"primes.txt"); q = gp.readRandomPrime((char*)"primes.txt"); composite = p * q; string s = composite.get_str(10); ui->compositeTextField->setText(QString::fromStdString(s)); } void MainWindow::on_hashButton_clicked() { switch(ui->hashComboBox->currentIndex()) { case 0: hashAlg = new Md5(); break; case 1: hashAlg = new Sha512(); break; case 2: hashAlg = new Pbkdf2(); break; } hashAlg->setPlaintext(ui->plaintextField->text()); if(ui->saltField->text() != "") { //if not empty hashAlg->setSalt(ui->saltField->text()); } hashAlg->compute(); digest = hashAlg->getDigest(); ui->digestField->setText(digest); //Perhaps make this an option? //hashAlg->salt = ""; } void MainWindow::on_randomSaltButton_clicked() { Hash h; h.generateSalt(16); ui->saltField->setText(h.getSalt()); } void MainWindow::on_crackButton_clicked() { //reset label text ui->crackTimeLabel->setText("Time: "); ui->crackTimeLabel->repaint(); ui->crackedField->setText(""); ui->crackedField->repaint(); Crack* c; if(hashAlg == NULL) { return; } switch(ui->crackComboBox->currentIndex()) { case 0: {int maxLength = ui->charCountSpinBox->text().toInt(); c = new BruteForceCrack(hashAlg,bruteForceAlphabet(), maxLength); break;} case 1: {c = new DictionaryCrack(hashAlg, "../dictionary.txt"); dictionaryOptions(c); break;} } c->digest = digest.toStdString(); threadCrack.setCrackType(c); threadCrack.work(); } void MainWindow::update_crack_result() { long elapsed; bool success; elapsed = threadCrack.getResult(); Crack* c = threadCrack.getCrack(); success = c->getPlaintext().length(); if(success) { ui->crackedField->setText(c->getPlaintext()); } else { ui->crackedField->setText("\"Uncrackable!!\""); } string s = "Time: " + std::to_string(elapsed) + " ms"; ui->crackTimeLabel->setText(QString::fromStdString(s)); } void MainWindow::update_factor_result() { long elapsed = threadFactor.getResult(); Factor* pf = threadFactor.getFactor(); string s = "Time: " + std::to_string(elapsed) + " ms"; ui->timeLabel->setText(QString::fromStdString(s)); s = "Result: " + pf->p1.get_str(10) + " * " + pf->p2.get_str(10); ui->resultLabel->setText(QString::fromStdString(s)); } std::string MainWindow::bruteForceAlphabet() { std::string alph = " ";//weird bug "fix" if(ui->customCheckBox->isChecked()) { return ui->alphabetField->text().toStdString(); } if(ui->lettersCheckBox->isChecked()) { alph += "abcdefghijklmnopqrstuvwxyz"; } if(ui->upCaseCheckBox->isChecked()) { alph += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } if(ui->numbersCheckBox->isChecked()) { alph += "1234567890"; } if(ui->symbolsCheckBox->isChecked()) { alph += "`~!@#$%^&*()_+-=,.<>/?'[]{}"; } return alph; } void MainWindow::dictionaryOptions(Crack* d) { unsigned int numWords = ui->wordCountSpinBox->text().toInt(); unsigned int appendedDigits = 0; if(ui->appendCheckBox->isChecked()) { appendedDigits = ui->digitCountSpinBox->text().toInt(); } unsigned int prependedDigits = 0; if(ui->prependCheckBox->isChecked()) { prependedDigits = ui->digitCountSpinBox->text().toInt(); } bool cap = ui->capCheckBox->isChecked(); bool symbols = ui->dictSymbolsCheckBox->isChecked(); d->setOptions(numWords,appendedDigits,prependedDigits,symbols,cap); } void MainWindow::on_drawFactoring_clicked() { //generate data int beginDigits = ui->startDigitsSpinBox->text().toInt(); int count = ui->dataPointsSpinBox->text().toInt(); std::vector<mpz_class> comps = GenerateData::composites(beginDigits, count); factorDataPoints = GenerateData::factor(comps, new BruteForceFactor); //draw points fg = new GraphWindow(ui->factoringGraphicsView, factorDataPoints); fg->vSize = 600; fg->hSize = 600; if(ui->factorLogScaleCheckBox->isChecked()) { fg->logScaleDraw(); } else { fg->draw(); } fg->addLabels("Milliseconds", "Number of digits"); fg->view->show(); } void MainWindow::on_plotCrackButton_clicked() { //grab hashing and cracking algorithms switch(ui->hashComboBox->currentIndex()) { case 0: hashAlg = new Md5(); break; case 1: hashAlg = new Sha512(); break; case 2: hashAlg = new Pbkdf2(); break; } Crack* c; if(hashAlg == NULL) { return; } switch(ui->crackComboBox->currentIndex()) { case 0: {int maxLength = ui->charCountSpinBox->text().toInt(); c = new BruteForceCrack(hashAlg,bruteForceAlphabet(), maxLength); break;} case 1: {c = new DictionaryCrack(hashAlg, "../dictionary.txt"); break;} } //generate data int beginChars = ui->charCountSpinBox_2->text().toInt(); int count = ui->crackPointCountSpinBox->text().toInt(); std::vector<std::string> strings = GenerateData::plaintexts(beginChars, count); std::vector<std::string> digests = GenerateData::getHashes(strings, hashAlg); crackDataPoints = GenerateData::crack(digests, c); //begin graphing cg = new GraphWindow(ui->crackGraphicsView, crackDataPoints); cg->vSize = 600; cg->hSize = 600; if(ui->hashLogScaleCheckBox->isChecked()) { cg->logScaleDraw(); } else { cg->draw(); } cg->addLabels("Milliseconds", "Number of characters"); cg->view->show(); } void MainWindow::on_hashLogScaleCheckBox_clicked() { if(cg == NULL) { std::cout << "graphwindow object not initialized. No action to take." << std::endl; return; } if(crackDataPoints.size() == 0) { std::cout << "No points to graph." << std::endl; return; } cg = new GraphWindow(ui->crackGraphicsView, crackDataPoints); cg->vSize = 600; cg->hSize = 600; if(ui->hashLogScaleCheckBox->isChecked()) { cg->logScaleDraw(); } else { cg->draw(); } cg->addLabels("Milliseconds", "Number of characters"); cg->view->show(); } void MainWindow::on_factorLogScaleCheckBox_clicked() { if(fg == NULL) { std::cout << "graphwindow object not initialized. No action to take." << std::endl; return; } if(factorDataPoints.size() == 0) { std::cout << "No points to graph." << std::endl; return; } fg = new GraphWindow(ui->factoringGraphicsView, factorDataPoints); fg->vSize = 600; fg->hSize = 600; if(ui->factorLogScaleCheckBox->isChecked()) { fg->logScaleDraw(); } else { fg->draw(); } fg->addLabels("Milliseconds", "Number of characters"); fg->view->show(); } <|endoftext|>
<commit_before>// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test reinit() #include "../tests.h" #include <deal.II/lac/generic_linear_algebra.h> #include <deal.II/base/index_set.h> #include <deal.II/lac/constraint_matrix.h> #include <fstream> #include <iostream> #include <iomanip> #include <vector> #include "gla.h" template <class LA> void test () { unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); unsigned int numproc = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD); if (myid==0) deallog << "numproc=" << numproc << std::endl; // each processor owns 2 indices and all // are ghosting Element 1 (the second) IndexSet local_active(numproc*2); local_active.add_range(myid*2,myid*2+2); IndexSet local_relevant(numproc*2); local_relevant.add_range(1,2); typename LA::MPI::Vector v(local_active, MPI_COMM_WORLD); typename LA::MPI::Vector g(local_active, local_relevant, MPI_COMM_WORLD); // set local values v(myid*2)=myid*2.0; v(myid*2+1)=myid*2.0+1.0; v.compress(VectorOperation::insert); g=v; IndexSet local_active_big(numproc*3); local_active_big.add_range(myid*3,myid*3+3); typename LA::MPI::Vector big(local_active_big, MPI_COMM_WORLD); typename LA::MPI::Vector x; Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==0, ExcInternalError()); x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); x.reinit(big); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==big.size(), ExcInternalError()); x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); x.reinit(g); Assert(x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==g.size(), ExcInternalError()); deallog << x(1) << std::endl; x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); // done if (myid==0) deallog << "OK" << std::endl; } int main (int argc, char **argv) { Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); MPILogInitAll log; { deallog.push("PETSc"); test<LA_PETSc>(); deallog.pop(); deallog.push("Trilinos"); test<LA_Trilinos>(); deallog.pop(); } } <commit_msg>extend gla/vec_05 to complex-valued PETSc<commit_after>// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test reinit() #include "../tests.h" #include <deal.II/lac/generic_linear_algebra.h> #include <deal.II/base/index_set.h> #include <deal.II/lac/constraint_matrix.h> #include <fstream> #include <iostream> #include <iomanip> #include <vector> #include "gla.h" template <class LA> void test () { unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD); unsigned int numproc = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD); if (myid==0) deallog << "numproc=" << numproc << std::endl; // each processor owns 2 indices and all // are ghosting Element 1 (the second) IndexSet local_active(numproc*2); local_active.add_range(myid*2,myid*2+2); IndexSet local_relevant(numproc*2); local_relevant.add_range(1,2); typename LA::MPI::Vector v(local_active, MPI_COMM_WORLD); typename LA::MPI::Vector g(local_active, local_relevant, MPI_COMM_WORLD); // set local values v(myid*2)=myid*2.0; v(myid*2+1)=myid*2.0+1.0; v.compress(VectorOperation::insert); g=v; IndexSet local_active_big(numproc*3); local_active_big.add_range(myid*3,myid*3+3); typename LA::MPI::Vector big(local_active_big, MPI_COMM_WORLD); typename LA::MPI::Vector x; Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==0, ExcInternalError()); x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); x.reinit(big); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==big.size(), ExcInternalError()); x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); x.reinit(g); Assert(x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==g.size(), ExcInternalError()); deallog << get_real_assert_zero_imag(x(1)) << std::endl; x.reinit(v); Assert(!x.has_ghost_elements(), ExcInternalError()); Assert(x.size()==v.size(), ExcInternalError()); // done if (myid==0) deallog << "OK" << std::endl; } int main (int argc, char **argv) { Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); MPILogInitAll log; { deallog.push("PETSc"); test<LA_PETSc>(); deallog.pop(); deallog.push("Trilinos"); test<LA_Trilinos>(); deallog.pop(); } } <|endoftext|>
<commit_before>#include "xchainer/python/backprop_mode.h" #include <memory> #include <utility> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/backprop_mode.h" #include "xchainer/context.h" #include "xchainer/graph.h" #include "xchainer/python/common.h" #include "xchainer/python/context.h" namespace xchainer { namespace python { namespace internal { namespace { namespace py = pybind11; // standard convention template <class BackpropModeScope> class PyBackpropModeScope { public: explicit PyBackpropModeScope() {} explicit PyBackpropModeScope(std::vector<GraphId> graph_ids) : graph_ids_{std::move(graph_ids)} {} void Enter() { scope_ = graph_ids_.has_value() ? std::make_unique<BackpropModeScope>(*graph_ids_) : std::make_unique<BackpropModeScope>(); } void Exit(py::args args) { (void)args; // unused scope_.reset(); } private: // optional requires having copy ctor, so use unique_ptr instead std::unique_ptr<BackpropModeScope> scope_; nonstd::optional<std::vector<GraphId>> graph_ids_{}; }; using PyNoBackpropModeScope = PyBackpropModeScope<NoBackpropModeScope>; using PyForceBackpropModeScope = PyBackpropModeScope<ForceBackpropModeScope>; template <class PyBackpropModeScope> void InitXchainerBackpropModeScope(pybind11::module& m, const std::string& class_name, const std::string& function_name) { py::class_<PyBackpropModeScope> c{m, class_name.c_str()}; c.def("__enter__", &PyBackpropModeScope::Enter); c.def("__exit__", &PyBackpropModeScope::Exit); m.def(function_name.c_str(), []() { return PyBackpropModeScope{}; }); m.def(function_name.c_str(), [](GraphId graph_id) { return PyBackpropModeScope{{std::move(graph_id)}}; }); m.def(function_name.c_str(), [](const std::vector<GraphId>& graph_ids) { return PyBackpropModeScope{graph_ids}; }); } } // namespace void InitXchainerBackpropMode(pybind11::module& m) { InitXchainerBackpropModeScope<PyNoBackpropModeScope>(m, "NoBackpropMode", "no_backprop_mode"); InitXchainerBackpropModeScope<PyForceBackpropModeScope>(m, "ForceBackpropMode", "force_backprop_mode"); m.def("is_backprop_required", [](const GraphId& graph_id, py::handle context) { return IsBackpropRequired(graph_id, GetContext(context)); }, py::arg("graph_id") = kDefaultGraphId, py::arg("context") = py::none()); } } // namespace internal } // namespace python } // namespace xchainer <commit_msg>cpplint<commit_after>#include "xchainer/python/backprop_mode.h" #include <memory> #include <string> #include <utility> #include <vector> #include <nonstd/optional.hpp> #include "xchainer/backprop_mode.h" #include "xchainer/context.h" #include "xchainer/graph.h" #include "xchainer/python/common.h" #include "xchainer/python/context.h" namespace xchainer { namespace python { namespace internal { namespace { namespace py = pybind11; // standard convention template <class BackpropModeScope> class PyBackpropModeScope { public: PyBackpropModeScope() {} explicit PyBackpropModeScope(std::vector<GraphId> graph_ids) : graph_ids_{std::move(graph_ids)} {} void Enter() { scope_ = graph_ids_.has_value() ? std::make_unique<BackpropModeScope>(*graph_ids_) : std::make_unique<BackpropModeScope>(); } void Exit(py::args args) { (void)args; // unused scope_.reset(); } private: // optional requires having copy ctor, so use unique_ptr instead std::unique_ptr<BackpropModeScope> scope_; nonstd::optional<std::vector<GraphId>> graph_ids_{}; }; using PyNoBackpropModeScope = PyBackpropModeScope<NoBackpropModeScope>; using PyForceBackpropModeScope = PyBackpropModeScope<ForceBackpropModeScope>; template <class PyBackpropModeScope> void InitXchainerBackpropModeScope(pybind11::module& m, const std::string& class_name, const std::string& function_name) { py::class_<PyBackpropModeScope> c{m, class_name.c_str()}; c.def("__enter__", &PyBackpropModeScope::Enter); c.def("__exit__", &PyBackpropModeScope::Exit); m.def(function_name.c_str(), []() { return PyBackpropModeScope{}; }); m.def(function_name.c_str(), [](GraphId graph_id) { return PyBackpropModeScope{{std::move(graph_id)}}; }); m.def(function_name.c_str(), [](const std::vector<GraphId>& graph_ids) { return PyBackpropModeScope{graph_ids}; }); } } // namespace void InitXchainerBackpropMode(pybind11::module& m) { InitXchainerBackpropModeScope<PyNoBackpropModeScope>(m, "NoBackpropMode", "no_backprop_mode"); InitXchainerBackpropModeScope<PyForceBackpropModeScope>(m, "ForceBackpropMode", "force_backprop_mode"); m.def("is_backprop_required", [](const GraphId& graph_id, py::handle context) { return IsBackpropRequired(graph_id, GetContext(context)); }, py::arg("graph_id") = kDefaultGraphId, py::arg("context") = py::none()); } } // namespace internal } // namespace python } // namespace xchainer <|endoftext|>
<commit_before><commit_msg>Fixed compilation warning<commit_after><|endoftext|>
<commit_before>#include "datalayer.h" #include "persons.h" #include "sortings.h" #include <string> #include <vector> #include <fstream> #include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; const string FILENAME = "science.txt"; DataLayer::DataLayer() { // loadFromFile(); } vector<Persons> DataLayer::getVector() { saveToFile(); return people; } void DataLayer::loadFromFile() { Persons p; ifstream inStream; inStream.open(FILENAME); while(inStream >> p) { addPerson(p); } inStream.close(); } void DataLayer::saveToFile() { fstream out; out.open(FILENAME); for (size_t i = 0; i < people.size(); i++) { out << people[i] << endl; } out.close(); } void DataLayer::addPerson(const Persons& p) { people.push_back(p); saveToFile(); } bool sortByName2(const Persons &lhs, const Persons &rhs) { return lhs.getName() < rhs.getName(); } //reyndi að nota klasaföll, en það vill þýðandinn ekki. bool sortByGender2(const Persons &lhs, const Persons &rhs) { return lhs.getGender() < rhs.getGender(); } bool sortByBirthYear2(const Persons &lhs, const Persons &rhs) { return lhs.getBirthYear() < rhs.getBirthYear(); } bool sortByDeathYear2(const Persons &lhs, const Persons &rhs) { return lhs.getDeathYear() < rhs.getDeathYear(); } void DataLayer::sortByName() { sort(people.begin(), people.end(), sortByName2); } void DataLayer::sortByBirthYear() { sort(people.begin(), people.end(), sortByBirthYear2); } void DataLayer::sortByDeathYear() { sort(people.begin(), people.end(), sortByDeathYear2); } void DataLayer::sortByGender() { sort(people.begin(), people.end(), sortByGender2); } <commit_msg>laga bil<commit_after>#include "datalayer.h" #include "persons.h" #include "sortings.h" #include <string> #include <vector> #include <fstream> #include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; const string FILENAME = "science.txt"; DataLayer::DataLayer() { // loadFromFile(); } vector<Persons> DataLayer::getVector() { saveToFile(); return people; } void DataLayer::loadFromFile() { Persons p; ifstream inStream; inStream.open(FILENAME); while(inStream >> p) { addPerson(p); } inStream.close(); } void DataLayer::saveToFile() { fstream out; out.open(FILENAME); for (size_t i = 0; i < people.size(); i++) { out << people[i]; } out.close(); } void DataLayer::addPerson(const Persons& p) { people.push_back(p); saveToFile(); } bool sortByName2(const Persons &lhs, const Persons &rhs) { return lhs.getName() < rhs.getName(); } //reyndi að nota klasaföll, en það vill þýðandinn ekki. bool sortByGender2(const Persons &lhs, const Persons &rhs) { return lhs.getGender() < rhs.getGender(); } bool sortByBirthYear2(const Persons &lhs, const Persons &rhs) { return lhs.getBirthYear() < rhs.getBirthYear(); } bool sortByDeathYear2(const Persons &lhs, const Persons &rhs) { return lhs.getDeathYear() < rhs.getDeathYear(); } void DataLayer::sortByName() { sort(people.begin(), people.end(), sortByName2); } void DataLayer::sortByBirthYear() { sort(people.begin(), people.end(), sortByBirthYear2); } void DataLayer::sortByDeathYear() { sort(people.begin(), people.end(), sortByDeathYear2); } void DataLayer::sortByGender() { sort(people.begin(), people.end(), sortByGender2); } <|endoftext|>
<commit_before><commit_msg>dependencies: Update JSON library to 3.7.0<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: weighhdl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:50:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_PROPERTYHANDLER_FONTWEIGHTTYPES_HXX #include <weighhdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _VCL_VCLENUM_HXX #include <vcl/vclenum.hxx> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _INC_LIMITS #include <limits.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #include <toolkit/unohlp.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::xmloff::token; struct FontWeightMapper { FontWeight eWeight; USHORT nValue; }; FontWeightMapper const aFontWeightMap[] = { { WEIGHT_DONTKNOW, 0 }, { WEIGHT_THIN, 100 }, { WEIGHT_ULTRALIGHT, 150 }, { WEIGHT_LIGHT, 250 }, { WEIGHT_SEMILIGHT, 350 }, { WEIGHT_NORMAL, 400 }, { WEIGHT_MEDIUM, 450 }, { WEIGHT_SEMIBOLD, 600 }, { WEIGHT_BOLD, 700 }, { WEIGHT_ULTRABOLD, 800 }, { WEIGHT_BLACK, 900 }, { (FontWeight)USHRT_MAX, 1000 } }; /////////////////////////////////////////////////////////////////////////////// // // class XMLFmtBreakBeforePropHdl // XMLFontWeightPropHdl::~XMLFontWeightPropHdl() { // Nothing to do } sal_Bool XMLFontWeightPropHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { sal_Bool bRet = sal_False; sal_uInt16 nWeight = 0; if( IsXMLToken( rStrImpValue, XML_WEIGHT_NORMAL ) ) { nWeight = 400; bRet = sal_True; } else if( IsXMLToken( rStrImpValue, XML_WEIGHT_BOLD ) ) { nWeight = 700; bRet = sal_True; } else { sal_Int32 nTemp; if( ( bRet = rUnitConverter.convertNumber( nTemp, rStrImpValue, 100, 900 ) ) ) nWeight = nTemp; } if( bRet ) { bRet = sal_False; for( int i = 0; aFontWeightMap[i].eWeight != USHRT_MAX; i++ ) { if( (nWeight >= aFontWeightMap[i].nValue) && (nWeight <= aFontWeightMap[i+1].nValue) ) { sal_uInt16 nDiff1 = nWeight - aFontWeightMap[i].nValue; sal_uInt16 nDiff2 = aFontWeightMap[i+1].nValue - nWeight; if( nDiff1 < nDiff2 ) rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i].eWeight ) ); else rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i+1].eWeight ) ); bRet = sal_True; break; } } } return bRet; } sal_Bool XMLFontWeightPropHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { sal_Bool bRet = sal_False; FontWeight eWeight; float fValue; if( !( rValue >>= fValue ) ) { sal_Int32 nValue; if( rValue >>= nValue ) { fValue = (float)nValue; bRet = sal_True; } } else bRet = sal_True; eWeight = VCLUnoHelper::ConvertFontWeight( fValue ); if( bRet ) { sal_uInt16 nWeight = 0; for( int i = 0; aFontWeightMap[i].eWeight != -1; i++ ) { if( aFontWeightMap[i].eWeight == eWeight ) { nWeight = aFontWeightMap[i].nValue; break; } } OUStringBuffer aOut; if( 400 == nWeight ) aOut.append( GetXMLToken(XML_WEIGHT_NORMAL) ); else if( 700 == nWeight ) aOut.append( GetXMLToken(XML_WEIGHT_BOLD) ); else rUnitConverter.convertNumber( aOut, (sal_Int32)nWeight ); rStrExpValue = aOut.makeStringAndClear(); } return bRet; } <commit_msg>INTEGRATION: CWS warnings01 (1.3.34); FILE MERGED 2005/11/02 14:57:56 cl 1.3.34.1: warning free code changes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: weighhdl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 18:35:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_PROPERTYHANDLER_FONTWEIGHTTYPES_HXX #include <weighhdl.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _VCL_VCLENUM_HXX #include <vcl/vclenum.hxx> #endif #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _INC_LIMITS #include <limits.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #include <toolkit/unohlp.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::xmloff::token; struct FontWeightMapper { FontWeight eWeight; USHORT nValue; }; FontWeightMapper const aFontWeightMap[] = { { WEIGHT_DONTKNOW, 0 }, { WEIGHT_THIN, 100 }, { WEIGHT_ULTRALIGHT, 150 }, { WEIGHT_LIGHT, 250 }, { WEIGHT_SEMILIGHT, 350 }, { WEIGHT_NORMAL, 400 }, { WEIGHT_MEDIUM, 450 }, { WEIGHT_SEMIBOLD, 600 }, { WEIGHT_BOLD, 700 }, { WEIGHT_ULTRABOLD, 800 }, { WEIGHT_BLACK, 900 }, { (FontWeight)USHRT_MAX, 1000 } }; /////////////////////////////////////////////////////////////////////////////// // // class XMLFmtBreakBeforePropHdl // XMLFontWeightPropHdl::~XMLFontWeightPropHdl() { // Nothing to do } sal_Bool XMLFontWeightPropHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { sal_Bool bRet = sal_False; sal_uInt16 nWeight = 0; if( IsXMLToken( rStrImpValue, XML_WEIGHT_NORMAL ) ) { nWeight = 400; bRet = sal_True; } else if( IsXMLToken( rStrImpValue, XML_WEIGHT_BOLD ) ) { nWeight = 700; bRet = sal_True; } else { sal_Int32 nTemp; if( ( bRet = rUnitConverter.convertNumber( nTemp, rStrImpValue, 100, 900 ) ) ) nWeight = nTemp; } if( bRet ) { bRet = sal_False; for( int i = 0; aFontWeightMap[i].eWeight != USHRT_MAX; i++ ) { if( (nWeight >= aFontWeightMap[i].nValue) && (nWeight <= aFontWeightMap[i+1].nValue) ) { sal_uInt16 nDiff1 = nWeight - aFontWeightMap[i].nValue; sal_uInt16 nDiff2 = aFontWeightMap[i+1].nValue - nWeight; if( nDiff1 < nDiff2 ) rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i].eWeight ) ); else rValue <<= (float)( VCLUnoHelper::ConvertFontWeight( aFontWeightMap[i+1].eWeight ) ); bRet = sal_True; break; } } } return bRet; } sal_Bool XMLFontWeightPropHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { sal_Bool bRet = sal_False; FontWeight eWeight; float fValue; if( !( rValue >>= fValue ) ) { sal_Int32 nValue; if( rValue >>= nValue ) { fValue = (float)nValue; bRet = sal_True; } } else bRet = sal_True; eWeight = VCLUnoHelper::ConvertFontWeight( fValue ); if( bRet ) { sal_uInt16 nWeight = 0; for( int i = 0; aFontWeightMap[i].eWeight != -1; i++ ) { if( aFontWeightMap[i].eWeight == eWeight ) { nWeight = aFontWeightMap[i].nValue; break; } } OUStringBuffer aOut; if( 400 == nWeight ) aOut.append( GetXMLToken(XML_WEIGHT_NORMAL) ); else if( 700 == nWeight ) aOut.append( GetXMLToken(XML_WEIGHT_BOLD) ); else rUnitConverter.convertNumber( aOut, (sal_Int32)nWeight ); rStrExpValue = aOut.makeStringAndClear(); } return bRet; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlaustp.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: mib $ $Date: 2000-11-20 10:15:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLASTPL_IMPL_HXX #include "impastpl.hxx" #endif #ifndef _XMLOFF_XMLASTPLP_HXX #include "xmlaustp.hxx" #endif #ifndef _XMLOFF_FAMILIES_HXX_ #include "families.hxx" #endif #ifndef _XMLOFF_ATTRLIST_HXX #include "attrlist.hxx" #endif #ifndef _XMLOFF_XMLKYWD_HXX #include "xmlkywd.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include "PageMasterStyleMap.hxx" #endif #ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX #include "PageMasterExportPropMapper.hxx" #endif #ifndef _XMLBACKGROUNDIMAGEEXPORT_HXX #include "XMLBackgroundImageExport.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif using namespace ::std; using namespace ::rtl; using namespace ::com::sun::star; void SvXMLAutoStylePoolP::exportStyleAttributes( SvXMLAttributeList& rAttrList, sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties, const SvXMLExportPropertyMapper& rPropExp, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const { if( nFamily == XML_STYLE_FAMILY_PAGE_MASTER ) { for( vector< XMLPropertyState >::const_iterator pProp = rProperties.begin(); pProp != rProperties.end(); pProp++ ) { UniReference< XMLPropertySetMapper > aPropMapper = rPropExp.getPropertySetMapper(); sal_Int32 nIndex = pProp->mnIndex; sal_Int16 nContextID = aPropMapper->GetEntryContextId( nIndex ); switch( nContextID ) { case CTF_PM_PAGEUSAGE: { OUString sAttrName( rNamespaceMap.GetQNameByKey( aPropMapper->GetEntryNameSpace( nIndex ), aPropMapper->GetEntryXMLName( nIndex ) ) ); OUString sCDATA( RTL_CONSTASCII_USTRINGPARAM( sXML_CDATA ) ); OUString sValue; const XMLPropertyHandler* pPropHdl = aPropMapper->GetPropertyHandler( nIndex ); if( pPropHdl && pPropHdl->exportXML( sValue, pProp->maValue, rUnitConverter ) && (sValue.compareToAscii( sXML_all ) != 0) ) rAttrList.AddAttribute( sAttrName, sCDATA, sValue ); } break; } } } } void SvXMLAutoStylePoolP::exportStyleContent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler, sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties, const SvXMLExportPropertyMapper& rPropExp, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const { if( nFamily == XML_STYLE_FAMILY_PAGE_MASTER ) { OUString sType( RTL_CONSTASCII_USTRINGPARAM( sXML_CDATA ) ); OUString sWS( RTL_CONSTASCII_USTRINGPARAM( sXML_WS ) ); sal_Int32 nHeaderStartIndex(-1); sal_Int32 nHeaderEndIndex(-1); sal_Int32 nFooterStartIndex(-1); sal_Int32 nFooterEndIndex(-1); sal_Bool bHeaderStartIndex(sal_False); sal_Bool bHeaderEndIndex(sal_False); sal_Bool bFooterStartIndex(sal_False); sal_Bool bFooterEndIndex(sal_False); UniReference< XMLPropertySetMapper > aPropMapper = rPropExp.getPropertySetMapper(); sal_Int32 nIndex(0); while(nIndex < aPropMapper->GetEntryCount()) { switch( aPropMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK ) { case CTF_PM_HEADERFLAG: { if (!bHeaderStartIndex) { nHeaderStartIndex = nIndex; bHeaderStartIndex = sal_True; } if (bFooterStartIndex && !bFooterEndIndex) { nFooterEndIndex = nIndex; bFooterEndIndex = sal_True; } } break; case CTF_PM_FOOTERFLAG: { if (!bFooterStartIndex) { nFooterStartIndex = nIndex; bFooterStartIndex = sal_True; } if (bHeaderStartIndex && !bHeaderEndIndex) { nHeaderEndIndex = nIndex; bHeaderEndIndex = sal_True; } } break; } nIndex++; } if (!bHeaderEndIndex) nHeaderEndIndex = nIndex; if (!bFooterEndIndex) nFooterEndIndex = nIndex; uno::Reference< xml::sax::XAttributeList > xEmptyList; OUString sNameHeader( rNamespaceMap.GetQNameByKey( XML_NAMESPACE_STYLE, OUString::createFromAscii( sXML_header_style ) ) ); rHandler->ignorableWhitespace( sWS ); rHandler->startElement( sNameHeader, xEmptyList ); rPropExp.exportXML(rHandler, rProperties, rUnitConverter, rNamespaceMap, nHeaderStartIndex, nHeaderEndIndex, XML_EXPORT_FLAG_IGN_WS); rHandler->ignorableWhitespace( sWS ); rHandler->endElement( sNameHeader ); OUString sNameFooter( rNamespaceMap.GetQNameByKey( XML_NAMESPACE_STYLE, OUString::createFromAscii( sXML_footer_style ) ) ); rHandler->ignorableWhitespace( sWS ); rHandler->startElement( sNameFooter, xEmptyList ); rPropExp.exportXML(rHandler, rProperties, rUnitConverter, rNamespaceMap, nFooterStartIndex, nFooterEndIndex, XML_EXPORT_FLAG_IGN_WS); rHandler->ignorableWhitespace( sWS ); rHandler->endElement( sNameFooter ); } } SvXMLAutoStylePoolP::SvXMLAutoStylePoolP() { pImpl = new SvXMLAutoStylePoolP_Impl; } SvXMLAutoStylePoolP::~SvXMLAutoStylePoolP() { delete pImpl; } // TODO: romove this void SvXMLAutoStylePoolP::AddFamily( sal_Int32 nFamily, const OUString& rStrName, SvXMLExportPropertyMapper* pMapper, OUString aStrPrefix, sal_Bool bAsFamily ) { UniReference <SvXMLExportPropertyMapper> xTmp = pMapper; AddFamily( nFamily, rStrName, xTmp, aStrPrefix, bAsFamily ); } void SvXMLAutoStylePoolP::AddFamily( sal_Int32 nFamily, const OUString& rStrName, const UniReference < SvXMLExportPropertyMapper > & rMapper, const OUString& rStrPrefix, sal_Bool bAsFamily ) { pImpl->AddFamily( nFamily, rStrName, rMapper, rStrPrefix, bAsFamily ); } void SvXMLAutoStylePoolP::RegisterName( sal_Int32 nFamily, const OUString& rName ) { pImpl->RegisterName( nFamily, rName ); } OUString SvXMLAutoStylePoolP::Add( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) { OUString sEmpty; return pImpl->Add( nFamily, sEmpty, rProperties ); } OUString SvXMLAutoStylePoolP::Add( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) { return pImpl->Add( nFamily, rParent, rProperties ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) { OUString sEmpty; return pImpl->Add( nFamily, sEmpty, rProperties, sal_True ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) { return pImpl->Add( nFamily, rParent, rProperties, sal_True ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const OUString& rParent ) { return pImpl->AddToCache( nFamily, rParent ); } OUString SvXMLAutoStylePoolP::Find( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) const { OUString sEmpty; return pImpl->Find( nFamily, sEmpty, rProperties ); } OUString SvXMLAutoStylePoolP::Find( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) const { return pImpl->Find( nFamily, rParent, rProperties ); } OUString SvXMLAutoStylePoolP::FindAndRemoveCached( sal_Int32 nFamily ) const { return pImpl->FindAndRemoveCached( nFamily ); } void SvXMLAutoStylePoolP::exportXML( sal_Int32 nFamily, const uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap) const { pImpl->exportXML( nFamily, rHandler, rUnitConverter, rNamespaceMap, this); } void SvXMLAutoStylePoolP::ClearEntries() { pImpl->ClearEntries(); } <commit_msg>#81065#; get only the entry if the index is higher than -1<commit_after>/************************************************************************* * * $RCSfile: xmlaustp.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: sab $ $Date: 2000-12-01 10:56:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLASTPL_IMPL_HXX #include "impastpl.hxx" #endif #ifndef _XMLOFF_XMLASTPLP_HXX #include "xmlaustp.hxx" #endif #ifndef _XMLOFF_FAMILIES_HXX_ #include "families.hxx" #endif #ifndef _XMLOFF_ATTRLIST_HXX #include "attrlist.hxx" #endif #ifndef _XMLOFF_XMLKYWD_HXX #include "xmlkywd.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include "PageMasterStyleMap.hxx" #endif #ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX #include "PageMasterExportPropMapper.hxx" #endif #ifndef _XMLBACKGROUNDIMAGEEXPORT_HXX #include "XMLBackgroundImageExport.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif using namespace ::std; using namespace ::rtl; using namespace ::com::sun::star; void SvXMLAutoStylePoolP::exportStyleAttributes( SvXMLAttributeList& rAttrList, sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties, const SvXMLExportPropertyMapper& rPropExp, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const { if( nFamily == XML_STYLE_FAMILY_PAGE_MASTER ) { for( vector< XMLPropertyState >::const_iterator pProp = rProperties.begin(); pProp != rProperties.end(); pProp++ ) { if (pProp->mnIndex > -1) { UniReference< XMLPropertySetMapper > aPropMapper = rPropExp.getPropertySetMapper(); sal_Int32 nIndex = pProp->mnIndex; sal_Int16 nContextID = aPropMapper->GetEntryContextId( nIndex ); switch( nContextID ) { case CTF_PM_PAGEUSAGE: { OUString sAttrName( rNamespaceMap.GetQNameByKey( aPropMapper->GetEntryNameSpace( nIndex ), aPropMapper->GetEntryXMLName( nIndex ) ) ); OUString sCDATA( RTL_CONSTASCII_USTRINGPARAM( sXML_CDATA ) ); OUString sValue; const XMLPropertyHandler* pPropHdl = aPropMapper->GetPropertyHandler( nIndex ); if( pPropHdl && pPropHdl->exportXML( sValue, pProp->maValue, rUnitConverter ) && (sValue.compareToAscii( sXML_all ) != 0) ) rAttrList.AddAttribute( sAttrName, sCDATA, sValue ); } break; } } } } } void SvXMLAutoStylePoolP::exportStyleContent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler, sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties, const SvXMLExportPropertyMapper& rPropExp, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap ) const { if( nFamily == XML_STYLE_FAMILY_PAGE_MASTER ) { OUString sType( RTL_CONSTASCII_USTRINGPARAM( sXML_CDATA ) ); OUString sWS( RTL_CONSTASCII_USTRINGPARAM( sXML_WS ) ); sal_Int32 nHeaderStartIndex(-1); sal_Int32 nHeaderEndIndex(-1); sal_Int32 nFooterStartIndex(-1); sal_Int32 nFooterEndIndex(-1); sal_Bool bHeaderStartIndex(sal_False); sal_Bool bHeaderEndIndex(sal_False); sal_Bool bFooterStartIndex(sal_False); sal_Bool bFooterEndIndex(sal_False); UniReference< XMLPropertySetMapper > aPropMapper = rPropExp.getPropertySetMapper(); sal_Int32 nIndex(0); while(nIndex < aPropMapper->GetEntryCount()) { switch( aPropMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK ) { case CTF_PM_HEADERFLAG: { if (!bHeaderStartIndex) { nHeaderStartIndex = nIndex; bHeaderStartIndex = sal_True; } if (bFooterStartIndex && !bFooterEndIndex) { nFooterEndIndex = nIndex; bFooterEndIndex = sal_True; } } break; case CTF_PM_FOOTERFLAG: { if (!bFooterStartIndex) { nFooterStartIndex = nIndex; bFooterStartIndex = sal_True; } if (bHeaderStartIndex && !bHeaderEndIndex) { nHeaderEndIndex = nIndex; bHeaderEndIndex = sal_True; } } break; } nIndex++; } if (!bHeaderEndIndex) nHeaderEndIndex = nIndex; if (!bFooterEndIndex) nFooterEndIndex = nIndex; uno::Reference< xml::sax::XAttributeList > xEmptyList; OUString sNameHeader( rNamespaceMap.GetQNameByKey( XML_NAMESPACE_STYLE, OUString::createFromAscii( sXML_header_style ) ) ); rHandler->ignorableWhitespace( sWS ); rHandler->startElement( sNameHeader, xEmptyList ); rPropExp.exportXML(rHandler, rProperties, rUnitConverter, rNamespaceMap, nHeaderStartIndex, nHeaderEndIndex, XML_EXPORT_FLAG_IGN_WS); rHandler->ignorableWhitespace( sWS ); rHandler->endElement( sNameHeader ); OUString sNameFooter( rNamespaceMap.GetQNameByKey( XML_NAMESPACE_STYLE, OUString::createFromAscii( sXML_footer_style ) ) ); rHandler->ignorableWhitespace( sWS ); rHandler->startElement( sNameFooter, xEmptyList ); rPropExp.exportXML(rHandler, rProperties, rUnitConverter, rNamespaceMap, nFooterStartIndex, nFooterEndIndex, XML_EXPORT_FLAG_IGN_WS); rHandler->ignorableWhitespace( sWS ); rHandler->endElement( sNameFooter ); } } SvXMLAutoStylePoolP::SvXMLAutoStylePoolP() { pImpl = new SvXMLAutoStylePoolP_Impl; } SvXMLAutoStylePoolP::~SvXMLAutoStylePoolP() { delete pImpl; } // TODO: romove this void SvXMLAutoStylePoolP::AddFamily( sal_Int32 nFamily, const OUString& rStrName, SvXMLExportPropertyMapper* pMapper, OUString aStrPrefix, sal_Bool bAsFamily ) { UniReference <SvXMLExportPropertyMapper> xTmp = pMapper; AddFamily( nFamily, rStrName, xTmp, aStrPrefix, bAsFamily ); } void SvXMLAutoStylePoolP::AddFamily( sal_Int32 nFamily, const OUString& rStrName, const UniReference < SvXMLExportPropertyMapper > & rMapper, const OUString& rStrPrefix, sal_Bool bAsFamily ) { pImpl->AddFamily( nFamily, rStrName, rMapper, rStrPrefix, bAsFamily ); } void SvXMLAutoStylePoolP::RegisterName( sal_Int32 nFamily, const OUString& rName ) { pImpl->RegisterName( nFamily, rName ); } OUString SvXMLAutoStylePoolP::Add( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) { OUString sEmpty; return pImpl->Add( nFamily, sEmpty, rProperties ); } OUString SvXMLAutoStylePoolP::Add( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) { return pImpl->Add( nFamily, rParent, rProperties ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) { OUString sEmpty; return pImpl->Add( nFamily, sEmpty, rProperties, sal_True ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) { return pImpl->Add( nFamily, rParent, rProperties, sal_True ); } OUString SvXMLAutoStylePoolP::AddAndCache( sal_Int32 nFamily, const OUString& rParent ) { return pImpl->AddToCache( nFamily, rParent ); } OUString SvXMLAutoStylePoolP::Find( sal_Int32 nFamily, const vector< XMLPropertyState >& rProperties ) const { OUString sEmpty; return pImpl->Find( nFamily, sEmpty, rProperties ); } OUString SvXMLAutoStylePoolP::Find( sal_Int32 nFamily, const OUString& rParent, const vector< XMLPropertyState >& rProperties ) const { return pImpl->Find( nFamily, rParent, rProperties ); } OUString SvXMLAutoStylePoolP::FindAndRemoveCached( sal_Int32 nFamily ) const { return pImpl->FindAndRemoveCached( nFamily ); } void SvXMLAutoStylePoolP::exportXML( sal_Int32 nFamily, const uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > & rHandler, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap) const { pImpl->exportXML( nFamily, rHandler, rUnitConverter, rNamespaceMap, this); } void SvXMLAutoStylePoolP::ClearEntries() { pImpl->ClearEntries(); } <|endoftext|>
<commit_before>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkDataSetMapper.h" #include "vtkExtractSelection.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkPlaneSource.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProgrammableFilter.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkBrokenLineWidget.h" #include "vtkTextProperty.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" #include "vtkTestUtilities.h" // Callback for the broken line widget interaction class vtkBLWCallback : public vtkCommand { public: static vtkBLWCallback *New() { return new vtkBLWCallback; } virtual void Execute(vtkObject *caller, unsigned long, void* ) { // Retrieve polydata line vtkBrokenLineWidget *line = reinterpret_cast<vtkBrokenLineWidget*>( caller ); line->GetPolyData( Poly ); // Update linear extractor with current points this->Selector->SetPoints( Poly->GetPoints() ); // Update selection from mesh this->Extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( this->Extractor->GetOutput() ); this->Selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); this->Mapper->SetInput( this->Selection ); } vtkBLWCallback():Poly(0),Selector(0),Extractor(0),Selection(0) {}; vtkPolyData* Poly; vtkLinearExtractor* Selector; vtkExtractSelection* Extractor; vtkUnstructuredGrid* Selection; vtkDataSetMapper* Mapper; }; int TestBrokenLineWidget( int argc, char *argv[] ) { // Initialize test value int testIntValue = 0; // Create render window and interactor vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New(); win->SetMultiSamples( 0 ); win->SetSize( 600, 300 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( win ); iren->Initialize(); // Create 2 viewports in window vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .4, .4, .4 ); ren1->SetBackground2( .8, .8, .8 ); ren1->GradientBackgroundOn(); ren1->SetViewport( 0., 0., .5, 1. ); win->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderer> ren2 = vtkSmartPointer<vtkRenderer>::New(); ren2->SetBackground( 1., 1., 1. ); ren2->SetViewport( .5, 0., 1., 1. ); win->AddRenderer( ren2 ); // Create a good view angle vtkCamera* camera1 = ren1->GetActiveCamera(); camera1->SetFocalPoint( .12, 0., 0. ); camera1->SetPosition( .35, .3, .3 ); camera1->SetViewUp( 0., 0., 1. ); ren2->SetActiveCamera( camera1 ); // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); delete [] fileName; reader->Update(); // Create mesh actor from reader output vtkSmartPointer<vtkDataSetMapper> meshMapper = vtkSmartPointer<vtkDataSetMapper>::New(); meshMapper->SetInputConnection( reader->GetOutputPort() ); vtkSmartPointer<vtkActor> meshActor = vtkSmartPointer<vtkActor>::New(); meshActor->SetMapper( meshMapper ); meshActor->GetProperty()->SetColor( .23, .37, .17 ); meshActor->GetProperty()->SetRepresentationToWireframe(); ren1->AddActor( meshActor ); // Create multi-block mesh for linear extractor reader->Update(); vtkUnstructuredGrid* mesh = reader->GetOutput(); vtkSmartPointer<vtkMultiBlockDataSet> meshMB = vtkSmartPointer<vtkMultiBlockDataSet>::New(); meshMB->SetNumberOfBlocks( 1 ); meshMB->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); meshMB->SetBlock( 0, mesh ); // Create broken line widget, attach it to input mesh vtkSmartPointer<vtkBrokenLineWidget> line = vtkSmartPointer<vtkBrokenLineWidget>::New(); line->SetInteractor( iren ); line->SetInput( mesh ); line->SetPriority( 1. ); line->KeyPressActivationOff(); line->PlaceWidget(); line->ProjectToPlaneOff(); line->On(); line->SetResolution( 6 ); line->SetHandleSizeFactor( 1. ); // Create list of points to define broken line vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint( .23, .0, .0 ); points->InsertNextPoint( .0, .0, .0 ); points->InsertNextPoint( .23, .04, .04 ); line->InitializeHandles( points ); // Extract polygonal line and then its points vtkSmartPointer<vtkPolyData> linePD = vtkSmartPointer<vtkPolyData>::New(); line->GetPolyData( linePD ); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lineMapper->SetInput( linePD ); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); lineActor->SetMapper( lineMapper ); lineActor->GetProperty()->SetColor( 1., 0., 0. ); lineActor->GetProperty()->SetLineWidth( 2. ); ren2->AddActor( lineActor ); // Create selection along broken line defined by list of points vtkSmartPointer<vtkLinearExtractor> selector = vtkSmartPointer<vtkLinearExtractor>::New(); selector->SetInput( meshMB ); selector->SetPoints( points ); selector->IncludeVerticesOff(); selector->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New(); extractor->SetInput( 0, meshMB ); extractor->SetInputConnection( 1, selector->GetOutputPort() ); extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); // Create selection actor vtkSmartPointer<vtkDataSetMapper> selMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selMapper->SetInput( selection ); vtkSmartPointer<vtkActor> selActor = vtkSmartPointer<vtkActor>::New(); selActor->SetMapper( selMapper ); selActor->GetProperty()->SetColor( 0., 0., 0. ); selActor->GetProperty()->SetRepresentationToWireframe(); ren2->AddActor( selActor ); // Invoke callback on polygonal line to interactively select elements vtkSmartPointer<vtkBLWCallback> cb = vtkSmartPointer<vtkBLWCallback>::New(); cb->Poly = linePD; cb->Selector = selector; cb->Extractor = extractor; cb->Selection = selection; cb->Mapper = selMapper; line->AddObserver( vtkCommand::InteractionEvent, cb ); // Render and interact win->Render(); iren->Start(); return testIntValue; } <commit_msg>A simplified version<commit_after>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkCommand.h" #include "vtkDataSetMapper.h" #include "vtkExtractSelection.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkPlaneSource.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProgrammableFilter.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkBrokenLineWidget.h" #include "vtkTextProperty.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" #include "vtkTestUtilities.h" // Callback for the broken line widget interaction class vtkBLWCallback : public vtkCommand { public: static vtkBLWCallback *New() { return new vtkBLWCallback; } virtual void Execute( vtkObject *caller, unsigned long, void* ) { // Retrieve polydata line vtkBrokenLineWidget *line = reinterpret_cast<vtkBrokenLineWidget*>( caller ); line->GetPolyData( Poly ); // Update linear extractor with current points this->Selector->SetPoints( Poly->GetPoints() ); // Update selection from mesh this->Extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( this->Extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); this->Mapper->SetInput( selection ); } vtkBLWCallback():Poly(0),Selector(0),Extractor(0),Mapper(0) {}; vtkPolyData* Poly; vtkLinearExtractor* Selector; vtkExtractSelection* Extractor; vtkDataSetMapper* Mapper; }; int TestBrokenLineWidget( int argc, char *argv[] ) { // Initialize test value int testIntValue = 0; // Create render window and interactor vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New(); win->SetMultiSamples( 0 ); win->SetSize( 600, 300 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( win ); iren->Initialize(); // Create 2 viewports in window vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .4, .4, .4 ); ren1->SetBackground2( .8, .8, .8 ); ren1->GradientBackgroundOn(); ren1->SetViewport( 0., 0., .5, 1. ); win->AddRenderer( ren1 ); vtkSmartPointer<vtkRenderer> ren2 = vtkSmartPointer<vtkRenderer>::New(); ren2->SetBackground( 1., 1., 1. ); ren2->SetViewport( .5, 0., 1., 1. ); win->AddRenderer( ren2 ); // Create a good view angle vtkCamera* camera1 = ren1->GetActiveCamera(); camera1->SetFocalPoint( .12, 0., 0. ); camera1->SetPosition( .35, .3, .3 ); camera1->SetViewUp( 0., 0., 1. ); ren2->SetActiveCamera( camera1 ); // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); delete [] fileName; reader->Update(); // Create mesh actor from reader output vtkSmartPointer<vtkDataSetMapper> meshMapper = vtkSmartPointer<vtkDataSetMapper>::New(); meshMapper->SetInputConnection( reader->GetOutputPort() ); vtkSmartPointer<vtkActor> meshActor = vtkSmartPointer<vtkActor>::New(); meshActor->SetMapper( meshMapper ); meshActor->GetProperty()->SetColor( .23, .37, .17 ); meshActor->GetProperty()->SetRepresentationToWireframe(); ren1->AddActor( meshActor ); // Create multi-block mesh for linear extractor reader->Update(); vtkUnstructuredGrid* mesh = reader->GetOutput(); vtkSmartPointer<vtkMultiBlockDataSet> meshMB = vtkSmartPointer<vtkMultiBlockDataSet>::New(); meshMB->SetNumberOfBlocks( 1 ); meshMB->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); meshMB->SetBlock( 0, mesh ); // Create broken line widget, attach it to input mesh vtkSmartPointer<vtkBrokenLineWidget> line = vtkSmartPointer<vtkBrokenLineWidget>::New(); line->SetInteractor( iren ); line->SetInput( mesh ); line->SetPriority( 1. ); line->KeyPressActivationOff(); line->PlaceWidget(); line->ProjectToPlaneOff(); line->On(); line->SetResolution( 6 ); line->SetHandleSizeFactor( 1.5 ); // Create list of points to define broken line vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint( .23, .0, .0 ); points->InsertNextPoint( .0, .0, .0 ); points->InsertNextPoint( .23, .04, .04 ); line->InitializeHandles( points ); // Extract polygonal line and then its points vtkSmartPointer<vtkPolyData> linePD = vtkSmartPointer<vtkPolyData>::New(); line->GetPolyData( linePD ); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lineMapper->SetInput( linePD ); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); lineActor->SetMapper( lineMapper ); lineActor->GetProperty()->SetColor( 1., 0., 0. ); lineActor->GetProperty()->SetLineWidth( 2. ); ren2->AddActor( lineActor ); // Create selection along broken line defined by list of points vtkSmartPointer<vtkLinearExtractor> selector = vtkSmartPointer<vtkLinearExtractor>::New(); selector->SetInput( meshMB ); selector->SetPoints( points ); selector->IncludeVerticesOff(); selector->SetVertexEliminationTolerance( 1.e-12 ); // Extract selection from mesh vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New(); extractor->SetInput( 0, meshMB ); extractor->SetInputConnection( 1, selector->GetOutputPort() ); extractor->Update(); vtkMultiBlockDataSet* outMB = vtkMultiBlockDataSet::SafeDownCast( extractor->GetOutput() ); vtkUnstructuredGrid* selection = vtkUnstructuredGrid::SafeDownCast( outMB->GetBlock( 0 ) ); // Create selection actor vtkSmartPointer<vtkDataSetMapper> selMapper = vtkSmartPointer<vtkDataSetMapper>::New(); selMapper->SetInput( selection ); vtkSmartPointer<vtkActor> selActor = vtkSmartPointer<vtkActor>::New(); selActor->SetMapper( selMapper ); selActor->GetProperty()->SetColor( 0., 0., 0. ); selActor->GetProperty()->SetRepresentationToWireframe(); ren2->AddActor( selActor ); // Invoke callback on polygonal line to interactively select elements vtkSmartPointer<vtkBLWCallback> cb = vtkSmartPointer<vtkBLWCallback>::New(); cb->Poly = linePD; cb->Selector = selector; cb->Extractor = extractor; cb->Mapper = selMapper; line->AddObserver( vtkCommand::InteractionEvent, cb ); // Render and interact win->Render(); iren->Start(); return testIntValue; } <|endoftext|>
<commit_before>#pragma once #include <tuple> #include <utility> #include <core/function_traits.hpp> #include <core/traits.hpp> #include <core/tuple_meta.hpp> namespace fc { template <class... ports> struct mux_port; template <class op> struct unloaded_merge_port; template <class op, class... ports> struct loaded_merge_port; struct default_tag {}; struct merge_tag {}; struct mux_tag {}; template <typename T> struct port_traits { using mux_category = default_tag; }; template <class... ports> struct port_traits<mux_port<ports...>> { using mux_category = mux_tag; }; template <class op> struct port_traits<unloaded_merge_port<op>> { using mux_category = merge_tag; }; namespace detail { template <bool... vals> constexpr bool any() { bool values[] = {vals...}; for (auto value : values) if (value) return true; return false; } } // namespace detail template <class base> struct node_aware; template <class... port_ts> struct mux_port { std::tuple<port_ts...> ports; template <class T> auto connect(T t, merge_tag) { static_assert( detail::has_result_of_type<decltype(t.merge), decltype(std::declval<port_ts>()())...>(), "The muxed ports can not be merged using the provided merge function."); static_assert(!detail::any<detail::is_derived_from<node_aware, port_ts>::value...>(), "Merge port can not be used with node aware ports. See merge_node."); return loaded_merge_port<decltype(t.merge), port_ts...>{t.merge, std::move(ports)}; } template <class... other_ports> auto connect(mux_port<other_ports...> other, mux_tag) { constexpr size_t N = sizeof...(port_ts); constexpr size_t M = sizeof...(other_ports); static_assert(N == M, "Mux ports need to have the same number of subports."); auto pairwise_connect = [](auto&& l, auto&& r) { return std::forward<decltype(l)>(l) >> std::forward<decltype(r)>(r); }; return fc::tuple::transform(std::move(ports), std::move(other.ports), pairwise_connect); } template <class T> auto connect(T&& t, default_tag) { auto connect_to_copy = [&t](auto&& elem) { // t needs to be copied if it's not an lvalue ref, forward won't work because can't move // from smth multiple times. return std::forward<decltype(elem)>(elem) >> static_cast<T>(t); }; return mux_from_tuple(fc::tuple::transform(std::move(ports), connect_to_copy)); } template <class T> auto operator>>(T&& t) { using decayed = std::decay_t<T>; using tag = typename fc::port_traits<decayed>::mux_category; return this->connect(std::forward<T>(t), tag{}); } }; template <class... port_ts> auto mux(port_ts&... ports) { return mux_port<std::remove_const_t<port_ts>&...>{std::tie(ports...)}; } template <class... conn_ts> mux_port<conn_ts...> mux_from_tuple(std::tuple<conn_ts...> tuple_) { return mux_port<conn_ts...>{std::move(tuple_)}; } template <class merge_op> struct unloaded_merge_port { merge_op merge; }; template <class merge_op, class... port_ts> struct loaded_merge_port { merge_op op; std::tuple<port_ts...> ports; auto operator()() { auto op = this->op; auto call_and_apply = [op](auto&&... src) { return op(std::forward<decltype(src)>(src)()...); }; return tuple::invoke_function(call_and_apply, ports, std::make_index_sequence<sizeof...(port_ts)>{}); } }; template <class merge_op> auto merge(merge_op op) { return unloaded_merge_port<merge_op>{op}; } } // namespace fc <commit_msg>ports: mux: use tag dispatch for mux->mux connections.<commit_after>#pragma once #include <tuple> #include <utility> #include <core/function_traits.hpp> #include <core/traits.hpp> #include <core/tuple_meta.hpp> namespace fc { template <class... ports> struct mux_port; template <class op> struct unloaded_merge_port; template <class op, class... ports> struct loaded_merge_port; struct default_tag {}; struct merge_tag {}; struct mux_tag {}; template <typename T> struct port_traits { using mux_category = default_tag; }; template <class... ports> struct port_traits<mux_port<ports...>> { using mux_category = mux_tag; }; template <class op> struct port_traits<unloaded_merge_port<op>> { using mux_category = merge_tag; }; namespace detail { template <bool... vals> constexpr bool any() { bool values[] = {vals...}; for (auto value : values) if (value) return true; return false; } template <typename... T> constexpr bool always_false_fun(T...) { return false; } } // namespace detail template <class base> struct node_aware; struct many_to_many_tag {}; template <size_t left_ports, size_t right_ports> struct mux_traits { static_assert( detail::always_false_fun(left_ports, right_ports), "Only N->N, 1->N and N->1 connections possible between muxed ports. PS: don't try 1->1."); }; template <size_t ports> struct mux_traits<ports, ports> { using connection_category = many_to_many_tag; }; template <class... port_ts> struct mux_port { std::tuple<port_ts...> ports; template <class T> auto connect(T t, merge_tag) { static_assert( detail::has_result_of_type<decltype(t.merge), decltype(std::declval<port_ts>()())...>(), "The muxed ports can not be merged using the provided merge function."); static_assert(!detail::any<detail::is_derived_from<node_aware, port_ts>::value...>(), "Merge port can not be used with node aware ports. See merge_node."); return loaded_merge_port<decltype(t.merge), port_ts...>{t.merge, std::move(ports)}; } template <class other_mux> auto connect(other_mux&& other, mux_tag) { constexpr size_t this_ports = sizeof...(port_ts); constexpr size_t other_ports = std::tuple_size<decltype(other.ports)>::value; using connection_tag = typename mux_traits<this_ports, other_ports>::connection_category; return connect_mux(std::forward<other_mux>(other), connection_tag{}); } template <class other_mux_port> auto connect_mux(other_mux_port&& other, many_to_many_tag) { auto pairwise_connect = [](auto&& l, auto&& r) { return std::forward<decltype(l)>(l) >> std::forward<decltype(r)>(r); }; return fc::tuple::transform(std::move(ports), std::forward<other_mux_port>(other).ports, pairwise_connect); } template <class T> auto connect(T&& t, default_tag) { auto connect_to_copy = [&t](auto&& elem) { // t needs to be copied if it's not an lvalue ref, forward won't work because can't move // from smth multiple times. return std::forward<decltype(elem)>(elem) >> static_cast<T>(t); }; return mux_from_tuple(fc::tuple::transform(std::move(ports), connect_to_copy)); } template <class T> auto operator>>(T&& t) { using decayed = std::decay_t<T>; using tag = typename fc::port_traits<decayed>::mux_category; return this->connect(std::forward<T>(t), tag{}); } }; template <class... port_ts> auto mux(port_ts&... ports) { return mux_port<std::remove_const_t<port_ts>&...>{std::tie(ports...)}; } template <class... conn_ts> mux_port<conn_ts...> mux_from_tuple(std::tuple<conn_ts...> tuple_) { return mux_port<conn_ts...>{std::move(tuple_)}; } template <class merge_op> struct unloaded_merge_port { merge_op merge; }; template <class merge_op, class... port_ts> struct loaded_merge_port { merge_op op; std::tuple<port_ts...> ports; auto operator()() { auto op = this->op; auto call_and_apply = [op](auto&&... src) { return op(std::forward<decltype(src)>(src)()...); }; return tuple::invoke_function(call_and_apply, ports, std::make_index_sequence<sizeof...(port_ts)>{}); } }; template <class merge_op> auto merge(merge_op op) { return unloaded_merge_port<merge_op>{op}; } } // namespace fc <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <stddef.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <assert.h> #include <onyx/spinlock.h> #include <onyx/page.h> #include <onyx/vm.h> #include <onyx/panic.h> #include <onyx/copy.h> #include <onyx/utils.h> #include <onyx/atomic.hpp> size_t page_memory_size; size_t nr_global_pages; atomic<size_t> used_pages = 0; static inline unsigned long pow2(int exp) { return (1UL << (unsigned long) exp); } struct page_list { struct page *page; struct list_head list_node; }; struct page_arena { void *start_arena; void *end_arena; struct list_head arena_list_node; struct page *alloc_contiguous(size_t nr_pgs, unsigned long flags); }; class page_node { private: struct spinlock node_lock; struct list_head arena_list; struct list_head cpu_list_node; struct list_head page_list; unsigned long used_pages; unsigned long total_pages; int page_add(struct page_arena *arena, void *__page, struct bootmodule *modules); public: constexpr page_node() : node_lock{}, arena_list{}, cpu_list_node{}, page_list{}, used_pages{}, total_pages{} { } ~page_node() {} void init() { INIT_LIST_HEAD(&arena_list); INIT_LIST_HEAD(&cpu_list_node); INIT_LIST_HEAD(&page_list); } void add_region(unsigned long base, size_t size, struct bootmodule *module); struct page *allocate_pages(unsigned long nr_pages, unsigned long flags); struct page *alloc_page(unsigned long flags); struct page *alloc_contiguous(unsigned long nr_pages, unsigned long flags); void free_page(struct page *p); }; static bool page_is_initialized = false; static constexpr size_t arena_default_size = 0x200000; page_node main_node; #include <onyx/clock.h> #define ADDRESS_4GB_MARK 0x100000000 extern "C" bool page_is_used(void *__page, struct bootmodule *modules); extern struct serial_port com1; extern "C" void serial_write(const char *s, size_t size, struct serial_port *port); int page_node::page_add(struct page_arena *arena, void *__page, struct bootmodule *modules) { if(page_is_used(__page, modules)) { struct page *p = page_add_page(__page); p->ref = 1; return -1; } nr_global_pages++; struct page_list *page = (struct page_list *) PHYS_TO_VIRT(__page); page->page = page_add_page(__page); page->page->flags |= PAGE_FLAG_FREE; list_add(&page->list_node, &page_list); total_pages++; return 0; } void page_node::add_region(uintptr_t base, size_t size, struct bootmodule *module) { while(size) { size_t area_size = min(size, arena_default_size); struct page_arena *arena = (struct page_arena *) __ksbrk(sizeof(struct page_arena)); assert(arena != NULL); memset_s(arena, 0, sizeof(struct page_arena)); arena->start_arena = (void*) base; arena->end_arena = (void*) (base + area_size); for(size_t i = 0; i < area_size; i += PAGE_SIZE) { /* If the page is being used, decrement the free_pages counter */ if(page_add(arena, (void*) (base + i), module) < 0) { used_pages++; ::used_pages++; } } list_add_tail(&arena->arena_list_node, &arena_list); size -= area_size; base += area_size; } } void page_init(size_t memory_size, unsigned long maxpfn, void *(*get_phys_mem_region)(uintptr_t *base, uintptr_t *size, void *context), struct bootmodule *modules) { uintptr_t region_base; uintptr_t region_size; void *context_cookie = NULL; main_node.init(); printf("page: Memory size: %lu\n", memory_size); page_memory_size = memory_size; //nr_global_pages = vm_align_size_to_pages(memory_size); size_t nr_arenas = page_memory_size / arena_default_size; if(page_memory_size % arena_default_size) nr_arenas++; size_t needed_memory = nr_arenas * sizeof(struct page_arena) + maxpfn * sizeof(struct page); void *ptr = alloc_boot_page(vm_size_to_pages(needed_memory), 0); if(!ptr) { halt(); } __kbrk(PHYS_TO_VIRT(ptr), (void *)((unsigned long) PHYS_TO_VIRT(ptr) + needed_memory)); page_allocate_pagemap(maxpfn); /* The context cookie is supposed to be used as a way for the * get_phys_mem_region implementation to keep track of where it's at, * without needing ugly global variables. */ /* Loop this call until the context cookie is NULL * (we must have reached the end) */ while((context_cookie = get_phys_mem_region(&region_base, &region_size, context_cookie)) != NULL) { /* page_add_region can't return an error value since it halts * on failure */ main_node.add_region(region_base, region_size, modules); } page_is_initialized = true; } #include <onyx/pagecache.h> #include <onyx/heap.h> void page_get_stats(struct memstat *m) { m->total_pages = nr_global_pages; m->allocated_pages = used_pages; m->page_cache_pages = pagecache_get_used_pages(); m->kernel_heap_pages = heap_get_used_pages(); } extern unsigned char kernel_end; void *kernel_break = &kernel_end; static void *kernel_break_limit = NULL; __attribute__((malloc)) void *__ksbrk(long inc) { void *ret = kernel_break; kernel_break = (char*) kernel_break + inc; assert((unsigned long) kernel_break <= (unsigned long) kernel_break_limit); return ret; } void __kbrk(void *break_, void *kbrk_limit) { kernel_break = break_; kernel_break_limit = kbrk_limit; } void free_pages(struct page *pages) { assert(pages != NULL); struct page *next = NULL; for(struct page *p = pages; p != NULL; p = next) { next = p->next_un.next_allocation; free_page(p); } } void free_page(struct page *p) { assert(p != NULL); assert(p->ref != 0); if(__page_unref(p) == 0) { p->next_un.next_allocation = NULL; main_node.free_page(p); //printf("free pages %p, %p\n", page_to_phys(p), __builtin_return_address(0)); } #if 0 else { printf("unref pages %p(refs %lu), %p\n", page_to_phys(p), p->ref, __builtin_return_address(0)); } #endif } struct page *page_node::alloc_page(unsigned long flags) { struct page *ret = nullptr; struct page_list *p = nullptr; /* The slow, alloc_contiguous function is the one that handles those requests */ if(flags & PAGE_ALLOC_4GB_LIMIT) return alloc_contiguous(1, flags); unsigned long cpu_flags = spin_lock_irqsave(&node_lock); if(list_is_empty(&page_list)) { assert(used_pages == total_pages); goto out; } p = container_of(list_first_element(&page_list), struct page_list, list_node); list_remove(&p->list_node); p->page->ref = 1; assert(p->page->flags & PAGE_FLAG_FREE); p->page->flags &= ~PAGE_FLAG_FREE; ret = p->page; used_pages++; ::used_pages++; out: spin_unlock_irqrestore(&node_lock, cpu_flags); return ret; } struct page *page_node::allocate_pages(size_t nr_pgs, unsigned long flags) { struct page *plist = NULL; struct page *ptail = NULL; for(size_t i = 0; i < nr_pgs; i++) { struct page *p = alloc_page(flags); if(!p) { if(plist) free_pages(plist); return NULL; } if(page_should_zero(flags)) { set_non_temporal(PAGE_TO_VIRT(p), 0, PAGE_SIZE); } if(!plist) { plist = ptail = p; } else { ptail->next_un.next_allocation = p; ptail = p; } } //printf("alloc pages %lu = %p, %p\n", nr_pgs, page_to_phys(plist), __builtin_return_address(0)); return plist; } struct page *page_arena::alloc_contiguous(size_t nr_pgs, unsigned long flags) { unsigned long start = (unsigned long) start_arena; unsigned long end = (unsigned long) end_arena & -(PAGE_SIZE - 1); auto current = start; struct page *first_page = nullptr; unsigned long contig_in_row = 0; while(current != end) { struct page *p = phys_to_page(current); if(flags & PAGE_ALLOC_4GB_LIMIT && current >= ADDRESS_4GB_MARK) return nullptr; if(!(p->flags & PAGE_FLAG_FREE)) { contig_in_row = 0; first_page = nullptr; } else { contig_in_row++; if(!first_page) first_page = p; assert(p->ref == 0); } if(contig_in_row == nr_pgs) break; current += PAGE_SIZE; } if(contig_in_row != nr_pgs) return nullptr; struct page *before = nullptr; for(size_t i = 0; i < nr_pgs; i++) { auto page = first_page + i; auto page_list_struct = (page_list *) PAGE_TO_VIRT(page); list_remove(&page_list_struct->list_node); page->flags &= ~PAGE_FLAG_FREE; page_ref(page); if(before) before->next_un.next_allocation = page; before = page; } used_pages += nr_pgs; ::used_pages += nr_pgs; if(page_should_zero(flags)) { set_non_temporal(PAGE_TO_VIRT(first_page), 0, nr_pgs << PAGE_SHIFT); } return first_page; } struct page *page_node::alloc_contiguous(size_t nr_pgs, unsigned long flags) { struct page *pages = nullptr; unsigned long cpu_flags = spin_lock_irqsave(&node_lock); list_for_every(&arena_list) { page_arena *arena = container_of(l, page_arena, arena_list_node); if(flags & PAGE_ALLOC_4GB_LIMIT && (unsigned long) arena->start_arena >= ADDRESS_4GB_MARK) goto out; pages = arena->alloc_contiguous(nr_pgs, flags); if(pages) goto out; } out: spin_unlock_irqrestore(&node_lock, cpu_flags); return pages; } extern "C" struct page *alloc_pages(size_t nr_pgs, unsigned long flags) { auto &node = main_node; /* Optimise for the possibility that someone's looking to allocate '1' contiguous page */ if(unlikely(flags & PAGE_ALLOC_CONTIGUOUS && nr_pgs > 1)) return node.alloc_contiguous(nr_pgs, flags); else return node.allocate_pages(nr_pgs, flags); } void __reclaim_page(struct page *new_page) { __sync_add_and_fetch(&nr_global_pages, 1); /* We need to set new_page->ref to 1 as free_page will decrement the ref as to * free it */ new_page->ref = 1; free_page(new_page); } void page_node::free_page(struct page *p) { unsigned long cpu_flags = spin_lock_irqsave(&node_lock); /* Reset the page */ p->flags = 0; p->cache = nullptr; p->next_un.next_allocation = nullptr; p->ref = 0; p->flags |= PAGE_FLAG_FREE; auto page_list_node = (struct page_list *) PAGE_TO_VIRT(p); page_list_node->page = p; /* Add it at the beginning since it might be fresh in the cache */ list_add(&page_list_node->list_node, &page_list); used_pages--; ::used_pages--; spin_unlock_irqrestore(&node_lock, cpu_flags); } <commit_msg>pagealloc: Fix used_pages.<commit_after>/* * Copyright (c) 2017 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <stddef.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <assert.h> #include <onyx/spinlock.h> #include <onyx/page.h> #include <onyx/vm.h> #include <onyx/panic.h> #include <onyx/copy.h> #include <onyx/utils.h> #include <onyx/atomic.hpp> size_t page_memory_size; size_t nr_global_pages; atomic<size_t> used_pages = 0; static inline unsigned long pow2(int exp) { return (1UL << (unsigned long) exp); } struct page_list { struct page *page; struct list_head list_node; }; struct page_arena { void *start_arena; void *end_arena; struct list_head arena_list_node; struct page *alloc_contiguous(size_t nr_pgs, unsigned long flags); }; class page_node { private: struct spinlock node_lock; struct list_head arena_list; struct list_head cpu_list_node; struct list_head page_list; unsigned long used_pages; unsigned long total_pages; int page_add(struct page_arena *arena, void *__page, struct bootmodule *modules); public: constexpr page_node() : node_lock{}, arena_list{}, cpu_list_node{}, page_list{}, used_pages{}, total_pages{} { } ~page_node() {} void init() { INIT_LIST_HEAD(&arena_list); INIT_LIST_HEAD(&cpu_list_node); INIT_LIST_HEAD(&page_list); } void add_region(unsigned long base, size_t size, struct bootmodule *module); struct page *allocate_pages(unsigned long nr_pages, unsigned long flags); struct page *alloc_page(unsigned long flags); struct page *alloc_contiguous(unsigned long nr_pages, unsigned long flags); void free_page(struct page *p); }; static bool page_is_initialized = false; static constexpr size_t arena_default_size = 0x200000; page_node main_node; #include <onyx/clock.h> #define ADDRESS_4GB_MARK 0x100000000 extern "C" bool page_is_used(void *__page, struct bootmodule *modules); extern struct serial_port com1; extern "C" void serial_write(const char *s, size_t size, struct serial_port *port); int page_node::page_add(struct page_arena *arena, void *__page, struct bootmodule *modules) { nr_global_pages++; total_pages++; if(page_is_used(__page, modules)) { struct page *p = page_add_page(__page); p->ref = 1; return -1; } struct page_list *page = (struct page_list *) PHYS_TO_VIRT(__page); page->page = page_add_page(__page); page->page->flags |= PAGE_FLAG_FREE; list_add(&page->list_node, &page_list); return 0; } void page_node::add_region(uintptr_t base, size_t size, struct bootmodule *module) { while(size) { size_t area_size = min(size, arena_default_size); struct page_arena *arena = (struct page_arena *) __ksbrk(sizeof(struct page_arena)); assert(arena != NULL); memset_s(arena, 0, sizeof(struct page_arena)); arena->start_arena = (void*) base; arena->end_arena = (void*) (base + area_size); for(size_t i = 0; i < area_size; i += PAGE_SIZE) { /* If the page is being used, decrement the free_pages counter */ if(page_add(arena, (void*) (base + i), module) < 0) { used_pages++; ::used_pages++; } } list_add_tail(&arena->arena_list_node, &arena_list); size -= area_size; base += area_size; } } void page_init(size_t memory_size, unsigned long maxpfn, void *(*get_phys_mem_region)(uintptr_t *base, uintptr_t *size, void *context), struct bootmodule *modules) { uintptr_t region_base; uintptr_t region_size; void *context_cookie = NULL; main_node.init(); printf("page: Memory size: %lu\n", memory_size); page_memory_size = memory_size; //nr_global_pages = vm_align_size_to_pages(memory_size); size_t nr_arenas = page_memory_size / arena_default_size; if(page_memory_size % arena_default_size) nr_arenas++; size_t needed_memory = nr_arenas * sizeof(struct page_arena) + maxpfn * sizeof(struct page); void *ptr = alloc_boot_page(vm_size_to_pages(needed_memory), 0); if(!ptr) { halt(); } __kbrk(PHYS_TO_VIRT(ptr), (void *)((unsigned long) PHYS_TO_VIRT(ptr) + needed_memory)); page_allocate_pagemap(maxpfn); /* The context cookie is supposed to be used as a way for the * get_phys_mem_region implementation to keep track of where it's at, * without needing ugly global variables. */ /* Loop this call until the context cookie is NULL * (we must have reached the end) */ while((context_cookie = get_phys_mem_region(&region_base, &region_size, context_cookie)) != NULL) { /* page_add_region can't return an error value since it halts * on failure */ main_node.add_region(region_base, region_size, modules); } page_is_initialized = true; } #include <onyx/pagecache.h> #include <onyx/heap.h> void page_get_stats(struct memstat *m) { m->total_pages = nr_global_pages; m->allocated_pages = used_pages; m->page_cache_pages = pagecache_get_used_pages(); m->kernel_heap_pages = heap_get_used_pages(); } extern unsigned char kernel_end; void *kernel_break = &kernel_end; static void *kernel_break_limit = NULL; __attribute__((malloc)) void *__ksbrk(long inc) { void *ret = kernel_break; kernel_break = (char*) kernel_break + inc; assert((unsigned long) kernel_break <= (unsigned long) kernel_break_limit); return ret; } void __kbrk(void *break_, void *kbrk_limit) { kernel_break = break_; kernel_break_limit = kbrk_limit; } void free_pages(struct page *pages) { assert(pages != NULL); struct page *next = NULL; for(struct page *p = pages; p != NULL; p = next) { next = p->next_un.next_allocation; free_page(p); } } void free_page(struct page *p) { assert(p != NULL); assert(p->ref != 0); if(__page_unref(p) == 0) { p->next_un.next_allocation = NULL; main_node.free_page(p); //printf("free pages %p, %p\n", page_to_phys(p), __builtin_return_address(0)); } #if 0 else { printf("unref pages %p(refs %lu), %p\n", page_to_phys(p), p->ref, __builtin_return_address(0)); } #endif } struct page *page_node::alloc_page(unsigned long flags) { struct page *ret = nullptr; struct page_list *p = nullptr; /* The slow, alloc_contiguous function is the one that handles those requests */ if(flags & PAGE_ALLOC_4GB_LIMIT) return alloc_contiguous(1, flags); unsigned long cpu_flags = spin_lock_irqsave(&node_lock); if(list_is_empty(&page_list)) { assert(used_pages == total_pages); goto out; } p = container_of(list_first_element(&page_list), struct page_list, list_node); list_remove(&p->list_node); p->page->ref = 1; assert(p->page->flags & PAGE_FLAG_FREE); p->page->flags &= ~PAGE_FLAG_FREE; ret = p->page; used_pages++; ::used_pages++; out: spin_unlock_irqrestore(&node_lock, cpu_flags); return ret; } struct page *page_node::allocate_pages(size_t nr_pgs, unsigned long flags) { struct page *plist = NULL; struct page *ptail = NULL; for(size_t i = 0; i < nr_pgs; i++) { struct page *p = alloc_page(flags); if(!p) { if(plist) free_pages(plist); return NULL; } if(page_should_zero(flags)) { set_non_temporal(PAGE_TO_VIRT(p), 0, PAGE_SIZE); } if(!plist) { plist = ptail = p; } else { ptail->next_un.next_allocation = p; ptail = p; } } //printf("alloc pages %lu = %p, %p\n", nr_pgs, page_to_phys(plist), __builtin_return_address(0)); return plist; } struct page *page_arena::alloc_contiguous(size_t nr_pgs, unsigned long flags) { unsigned long start = (unsigned long) start_arena; unsigned long end = (unsigned long) end_arena & -(PAGE_SIZE - 1); auto current = start; struct page *first_page = nullptr; unsigned long contig_in_row = 0; while(current != end) { struct page *p = phys_to_page(current); if(flags & PAGE_ALLOC_4GB_LIMIT && current >= ADDRESS_4GB_MARK) return nullptr; if(!(p->flags & PAGE_FLAG_FREE)) { contig_in_row = 0; first_page = nullptr; } else { contig_in_row++; if(!first_page) first_page = p; assert(p->ref == 0); } if(contig_in_row == nr_pgs) break; current += PAGE_SIZE; } if(contig_in_row != nr_pgs) return nullptr; struct page *before = nullptr; for(size_t i = 0; i < nr_pgs; i++) { auto page = first_page + i; auto page_list_struct = (page_list *) PAGE_TO_VIRT(page); list_remove(&page_list_struct->list_node); page->flags &= ~PAGE_FLAG_FREE; page_ref(page); if(before) before->next_un.next_allocation = page; before = page; } used_pages += nr_pgs; ::used_pages += nr_pgs; if(page_should_zero(flags)) { set_non_temporal(PAGE_TO_VIRT(first_page), 0, nr_pgs << PAGE_SHIFT); } return first_page; } struct page *page_node::alloc_contiguous(size_t nr_pgs, unsigned long flags) { struct page *pages = nullptr; unsigned long cpu_flags = spin_lock_irqsave(&node_lock); list_for_every(&arena_list) { page_arena *arena = container_of(l, page_arena, arena_list_node); if(flags & PAGE_ALLOC_4GB_LIMIT && (unsigned long) arena->start_arena >= ADDRESS_4GB_MARK) goto out; pages = arena->alloc_contiguous(nr_pgs, flags); if(pages) goto out; } out: spin_unlock_irqrestore(&node_lock, cpu_flags); return pages; } extern "C" struct page *alloc_pages(size_t nr_pgs, unsigned long flags) { auto &node = main_node; /* Optimise for the possibility that someone's looking to allocate '1' contiguous page */ if(unlikely(flags & PAGE_ALLOC_CONTIGUOUS && nr_pgs > 1)) return node.alloc_contiguous(nr_pgs, flags); else return node.allocate_pages(nr_pgs, flags); } void __reclaim_page(struct page *new_page) { __sync_add_and_fetch(&nr_global_pages, 1); /* We need to set new_page->ref to 1 as free_page will decrement the ref as to * free it */ new_page->ref = 1; free_page(new_page); } void page_node::free_page(struct page *p) { unsigned long cpu_flags = spin_lock_irqsave(&node_lock); /* Reset the page */ p->flags = 0; p->cache = nullptr; p->next_un.next_allocation = nullptr; p->ref = 0; p->flags |= PAGE_FLAG_FREE; auto page_list_node = (struct page_list *) PAGE_TO_VIRT(p); page_list_node->page = p; /* Add it at the beginning since it might be fresh in the cache */ list_add(&page_list_node->list_node, &page_list); used_pages--; ::used_pages--; spin_unlock_irqrestore(&node_lock, cpu_flags); } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <bse/testing.hh> #include <bse/bsemain.hh> #include <bse/bse.hh> #include <bse/bseserver.hh> #include "ipc.hh" #include "testresampler.hh" #include "bse/internal.hh" // for Bse::Test::IntegrityCheck integration #define DEBUG(...) do { break; Bse::printerr (__VA_ARGS__); } while (0) static int jobserver (const char *const argv0, Bse::StringVector &tests); static int jobclient (int jobfd); static void print_int_ring (SfiRing *ring) { SfiRing *node; TNOTE ("{"); for (node = ring; node; node = sfi_ring_walk (node, ring)) TNOTE ("%c", char (size_t (node->data))); TNOTE ("}"); } static gint ints_cmp (gconstpointer d1, gconstpointer d2, gpointer data) { size_t i1 = size_t (d1); size_t i2 = size_t (d2); return i1 < i2 ? -1 : i1 > i2; } static void test_sfi_ring (void) { gint data_array[][64] = { { 0, }, { 1, 'a', }, { 2, 'a', 'a', }, { 2, 'a', 'b', }, { 2, 'z', 'a', }, { 3, 'a', 'c', 'z' }, { 3, 'a', 'z', 'c' }, { 3, 'c', 'a', 'z' }, { 3, 'z', 'c', 'a' }, { 3, 'a', 'a', 'a' }, { 3, 'a', 'a', 'z' }, { 3, 'a', 'z', 'a' }, { 3, 'z', 'a', 'a' }, { 10, 'g', 's', 't', 'y', 'x', 'q', 'i', 'n', 'j', 'a' }, { 15, 'w', 'k', 't', 'o', 'c', 's', 'j', 'd', 'd', 'q', 'p', 'v', 'q', 'r', 'a' }, { 26, 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm' , 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a', }, }; for (uint n = 0; n < G_N_ELEMENTS (data_array); n++) { uint l = data_array[n][0]; SfiRing *ring = NULL; for (uint i = 1; i <= l; i++) ring = sfi_ring_append (ring, (void*) size_t (data_array[n][i])); TNOTE ("source: "); print_int_ring (ring); ring = sfi_ring_sort (ring, ints_cmp, NULL); TNOTE (" sorted: "); print_int_ring (ring); TNOTE ("\n"); sfi_ring_free (ring); } } TEST_ADD (test_sfi_ring); static void bench_aida() { using namespace Bse; double calls = 0, slowest = 0, fastest = 9e+9; for (uint j = 0; j < 37; j++) { Bse::jobs += [] () { BSE_SERVER.test_counter_set (0); }; const int count = 2999; const uint64_t ts0 = timestamp_benchmark(); for (int i = 0; i < count; i++) Bse::jobs += [] () { BSE_SERVER.test_counter_inc_fetch(); }; const uint64 ts1 = timestamp_benchmark(); TASSERT (count == (Bse::jobs += [] () { return BSE_SERVER.test_counter_get(); })); double t0 = ts0 / 1000000000.; double t1 = ts1 / 1000000000.; double call1 = (t1 - t0) / count; slowest = MAX (slowest, call1 * 1000000.); fastest = MIN (fastest, call1 * 1000000.); double this_calls = 1 / call1; calls = MAX (calls, this_calls); } double err = (slowest - fastest) / slowest; printout (" BENCH Aida: %g calls/s; fastest: %.2fus; slowest: %.2fus; err: %.2f%%\n", calls, fastest, slowest, err * 100); } // Override weak symbol to enable integrity tests namespace Bse::Test { /* NOT __weak__: */ const bool IntegrityCheck::enable_testing = true; // see internal.hh } // Bse::Test static int test_main (int argc, char *argv[]) { // Parse args Bse::Test::TestEntries test_entries; int64 jobs = 0; int jobfd = -1; int64 testflags = 0; for (ssize_t i = 1; i < argc; i++) if (argv[i]) { if (std::string ("--broken") == argv[i]) { testflags |= Bse::Test::BROKEN; } else if (std::string ("--slow") == argv[i]) { testflags |= Bse::Test::SLOW; } else if (std::string ("--bench") == argv[i]) { testflags |= Bse::Test::BENCH; } else if (std::string ("--jobfd") == argv[i] && i + 1 < argc) { jobfd = Bse::string_to_int (argv[++i]); } else if (std::string ("-j") == argv[i]) { jobs = 1; } else if ('-' == argv[i][0]) { Bse::printerr ("%s: unknown option: %s\n", argv[0], argv[i]); return 7; } else test_entries.push_back (Bse::Test::TestEntry (argv[i])); } // Process test list fetched via IPC if (jobfd != -1) return jobclient (jobfd); // Fallback to run *all* tests if (test_entries.size() == 0) test_entries = Bse::Test::list_tests(); int serverstatus = 0; if (jobs) { Bse::StringVector tests; for (const Bse::Test::TestEntry &entry : test_entries) if (0 == (entry.flags & ~testflags) || (testflags == 0 && (entry.flags & Bse::Test::INTEGRITY))) tests.push_back (entry.ident); serverstatus = jobserver (argv[0], tests); } else for (Bse::Test::TestEntry entry : test_entries) if (0 == (entry.flags & ~testflags) || (testflags == 0 && (entry.flags & Bse::Test::INTEGRITY))) { const int result = Bse::Test::run_test (entry.ident); if (result < 0) { Bse::printout (" RUN… %s\n", entry.ident); Bse::printout (" FAIL %s - test missing\n", entry.ident); serverstatus = -1; break; } } Bse::printout (" EXIT %d - %s\n", serverstatus, serverstatus ? "FAIL" : "OK"); return serverstatus; } int main (int argc, char *argv[]) { Bse::StringVector args = Bse::init_args (&argc, argv); args.push_back ("stand-alone=1"); Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); assert_return (Bse::Test::IntegrityCheck::enable_testing == true, -1); // special case aida-bench if (argc >= 2 && argv[1] && std::string ("--aida-bench") == argv[1]) { Bse::init_async (argv[0], args); bench_aida(); return 0; } if (argc >= 2 && argv[1] && std::string ("--resampler") == argv[1]) { Bse::init_async (argv[0], args); return test_resampler (argc, argv); } // run tests return Bse::init_and_test (args, [&]() { // check-assertions if (argc >= 2 && String ("--assert_return1") == argv[1]) { assert_return (1, 0); return 0; } else if (argc >= 2 && String ("--assert_return0") == argv[1]) { assert_return (0, 0); return 0; } else if (argc >= 2 && String ("--assert_return_unreached") == argv[1]) { assert_return_unreached (0); return 0; } else if (argc >= 2 && String ("--fatal_error") == argv[1]) { Bse::fatal_error ("got argument --fatal_error"); return 0; } else if (argc >= 2 && String ("--return_unless0") == argv[1]) { return_unless (0, 7); return 0; } else if (argc >= 2 && String ("--return_unless1") == argv[1]) { return_unless (1, 8); return 0; } // run tests return test_main (argc, argv); }); } static int jobclient (int jobfd) { IpcSharedMem *sm = IpcSharedMem::acquire_shared (jobfd); Bse::StringVector tests; const std::string testlist = sm->get_string(); for (const auto &line : Bse::string_split (testlist, "\n")) if (!line.empty()) tests.push_back (line); for (int64 v = sm->counter.fetch_add (-1); v > 0; v = sm->counter.fetch_add (-1)) { const size_t test_index = v - 1; TASSERT (test_index < tests.size()); const int result = Bse::Test::run_test (tests[test_index]); if (result < 0) { Bse::printout (" RUN… %s\n", tests[test_index]); Bse::printout (" FAIL %s - test missing\n", tests[test_index]); return -1; } } IpcSharedMem::release_shared (sm, jobfd); DEBUG ("JOBDONE (%u)\n", Bse::this_thread_getpid()); return 0; } #include <unistd.h> // fork exec #include <sys/wait.h> // waitpid static int jobserver (const char *const argv0, Bse::StringVector &tests) { std::reverse (tests.begin(), tests.end()); // the IpcSharedMem counter is decremented const std::string testlist = Bse::string_join ("\n", tests); int fd = -1; IpcSharedMem *sm = IpcSharedMem::create_shared (testlist, &fd, tests.size()); if (fd < 0 || !sm) die ("failed to create shared memory segment: %s", Bse::strerror (errno)); DEBUG ("jobserver: pid=%u\n", Bse::this_thread_getpid()); const size_t n_jobs = std::max (1, Bse::this_thread_online_cpus()); std::vector<pid_t> jobs; for (size_t i = 0; i < n_jobs; i++) if (sm->counter > 0) // avoid spawning jobs if there's no work { const pid_t child = fork(); if (child == 0) { execl (argv0, argv0, "--jobfd", Bse::string_from_int (fd).c_str(), NULL); die ("failed to execl(\"%s\"): %s", argv0, Bse::strerror (errno)); } else if (child < 0) { DEBUG ("%s: failed to fork: %s\n", argv0, Bse::strerror (errno)); } else jobs.push_back (child); } int serverstatus = 0; while (jobs.size()) { int wstatus = 0; const int pid = waitpid (-1, &wstatus, 0); if (pid < 0) { DEBUG ("%s: waitpid(%d) failed: %s\n", argv0, pid, Bse::strerror (errno)); if (errno == ECHILD) abort(); // lost track of jobs continue; } const int exitstatus = WIFEXITED (wstatus) ? WEXITSTATUS (wstatus) : WIFSIGNALED (wstatus) ? -WTERMSIG (wstatus) : -128; auto it = std::find (jobs.begin(), jobs.end(), pid); if (it == jobs.end()) DEBUG ("%s: orphan (%d) exited: %d\n", argv0, pid, exitstatus); else { jobs.erase (it); if (!serverstatus) serverstatus = exitstatus; DEBUG ("%s: child (%d) exited: %d\n", argv0, pid, exitstatus); } } const ssize_t remaining_tests = sm->counter; TASSERT (remaining_tests <= 0); IpcSharedMem::destroy_shared (sm, fd); return serverstatus; } <commit_msg>TESTS: suite-main.cc: trigger clean shutdown via Bse::shutdown_async()<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include <bse/testing.hh> #include <bse/bsemain.hh> #include <bse/bse.hh> #include <bse/bseserver.hh> #include "ipc.hh" #include "testresampler.hh" #include "bse/internal.hh" // for Bse::Test::IntegrityCheck integration #define DEBUG(...) do { break; Bse::printerr (__VA_ARGS__); } while (0) static int jobserver (const char *const argv0, Bse::StringVector &tests); static int jobclient (int jobfd); static void print_int_ring (SfiRing *ring) { SfiRing *node; TNOTE ("{"); for (node = ring; node; node = sfi_ring_walk (node, ring)) TNOTE ("%c", char (size_t (node->data))); TNOTE ("}"); } static gint ints_cmp (gconstpointer d1, gconstpointer d2, gpointer data) { size_t i1 = size_t (d1); size_t i2 = size_t (d2); return i1 < i2 ? -1 : i1 > i2; } static void test_sfi_ring (void) { gint data_array[][64] = { { 0, }, { 1, 'a', }, { 2, 'a', 'a', }, { 2, 'a', 'b', }, { 2, 'z', 'a', }, { 3, 'a', 'c', 'z' }, { 3, 'a', 'z', 'c' }, { 3, 'c', 'a', 'z' }, { 3, 'z', 'c', 'a' }, { 3, 'a', 'a', 'a' }, { 3, 'a', 'a', 'z' }, { 3, 'a', 'z', 'a' }, { 3, 'z', 'a', 'a' }, { 10, 'g', 's', 't', 'y', 'x', 'q', 'i', 'n', 'j', 'a' }, { 15, 'w', 'k', 't', 'o', 'c', 's', 'j', 'd', 'd', 'q', 'p', 'v', 'q', 'r', 'a' }, { 26, 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm' , 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a', }, }; for (uint n = 0; n < G_N_ELEMENTS (data_array); n++) { uint l = data_array[n][0]; SfiRing *ring = NULL; for (uint i = 1; i <= l; i++) ring = sfi_ring_append (ring, (void*) size_t (data_array[n][i])); TNOTE ("source: "); print_int_ring (ring); ring = sfi_ring_sort (ring, ints_cmp, NULL); TNOTE (" sorted: "); print_int_ring (ring); TNOTE ("\n"); sfi_ring_free (ring); } } TEST_ADD (test_sfi_ring); static void bench_aida() { using namespace Bse; double calls = 0, slowest = 0, fastest = 9e+9; for (uint j = 0; j < 37; j++) { Bse::jobs += [] () { BSE_SERVER.test_counter_set (0); }; const int count = 2999; const uint64_t ts0 = timestamp_benchmark(); for (int i = 0; i < count; i++) Bse::jobs += [] () { BSE_SERVER.test_counter_inc_fetch(); }; const uint64 ts1 = timestamp_benchmark(); TASSERT (count == (Bse::jobs += [] () { return BSE_SERVER.test_counter_get(); })); double t0 = ts0 / 1000000000.; double t1 = ts1 / 1000000000.; double call1 = (t1 - t0) / count; slowest = MAX (slowest, call1 * 1000000.); fastest = MIN (fastest, call1 * 1000000.); double this_calls = 1 / call1; calls = MAX (calls, this_calls); } double err = (slowest - fastest) / slowest; printout (" BENCH Aida: %g calls/s; fastest: %.2fus; slowest: %.2fus; err: %.2f%%\n", calls, fastest, slowest, err * 100); } // Override weak symbol to enable integrity tests namespace Bse::Test { /* NOT __weak__: */ const bool IntegrityCheck::enable_testing = true; // see internal.hh } // Bse::Test static int test_main (int argc, char *argv[]) { // Parse args Bse::Test::TestEntries test_entries; int64 jobs = 0; int jobfd = -1; int64 testflags = 0; for (ssize_t i = 1; i < argc; i++) if (argv[i]) { if (std::string ("--broken") == argv[i]) { testflags |= Bse::Test::BROKEN; } else if (std::string ("--slow") == argv[i]) { testflags |= Bse::Test::SLOW; } else if (std::string ("--bench") == argv[i]) { testflags |= Bse::Test::BENCH; } else if (std::string ("--jobfd") == argv[i] && i + 1 < argc) { jobfd = Bse::string_to_int (argv[++i]); } else if (std::string ("-j") == argv[i]) { jobs = 1; } else if ('-' == argv[i][0]) { Bse::printerr ("%s: unknown option: %s\n", argv[0], argv[i]); return 7; } else test_entries.push_back (Bse::Test::TestEntry (argv[i])); } // Process test list fetched via IPC if (jobfd != -1) return jobclient (jobfd); // Fallback to run *all* tests if (test_entries.size() == 0) test_entries = Bse::Test::list_tests(); int serverstatus = 0; if (jobs) { Bse::StringVector tests; for (const Bse::Test::TestEntry &entry : test_entries) if (0 == (entry.flags & ~testflags) || (testflags == 0 && (entry.flags & Bse::Test::INTEGRITY))) tests.push_back (entry.ident); serverstatus = jobserver (argv[0], tests); } else for (Bse::Test::TestEntry entry : test_entries) if (0 == (entry.flags & ~testflags) || (testflags == 0 && (entry.flags & Bse::Test::INTEGRITY))) { const int result = Bse::Test::run_test (entry.ident); if (result < 0) { Bse::printout (" RUN… %s\n", entry.ident); Bse::printout (" FAIL %s - test missing\n", entry.ident); serverstatus = -1; break; } } Bse::printout (" EXIT %d - %s\n", serverstatus, serverstatus ? "FAIL" : "OK"); return serverstatus; } int main (int argc, char *argv[]) { Bse::StringVector args = Bse::init_args (&argc, argv); args.push_back ("stand-alone=1"); Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT); assert_return (Bse::Test::IntegrityCheck::enable_testing == true, -1); // special case aida-bench if (argc >= 2 && argv[1] && std::string ("--aida-bench") == argv[1]) { Bse::init_async (argv[0], args); bench_aida(); return 0; } if (argc >= 2 && argv[1] && std::string ("--resampler") == argv[1]) { Bse::init_async (argv[0], args); return test_resampler (argc, argv); } // initialize BSE and continue in BSE thread const int status = Bse::init_and_test (args, [&]() { // check-assertions if (argc >= 2 && String ("--assert_return1") == argv[1]) { assert_return (1, 0); return 0; } else if (argc >= 2 && String ("--assert_return0") == argv[1]) { assert_return (0, 0); return 0; } else if (argc >= 2 && String ("--assert_return_unreached") == argv[1]) { assert_return_unreached (0); return 0; } else if (argc >= 2 && String ("--fatal_error") == argv[1]) { Bse::fatal_error ("got argument --fatal_error"); return 0; } else if (argc >= 2 && String ("--return_unless0") == argv[1]) { return_unless (0, 7); return 0; } else if (argc >= 2 && String ("--return_unless1") == argv[1]) { return_unless (1, 8); return 0; } // run tests return test_main (argc, argv); }); // clean shutdown if (status == 0) Bse::shutdown_async(); return status; } static int jobclient (int jobfd) { IpcSharedMem *sm = IpcSharedMem::acquire_shared (jobfd); Bse::StringVector tests; const std::string testlist = sm->get_string(); for (const auto &line : Bse::string_split (testlist, "\n")) if (!line.empty()) tests.push_back (line); for (int64 v = sm->counter.fetch_add (-1); v > 0; v = sm->counter.fetch_add (-1)) { const size_t test_index = v - 1; TASSERT (test_index < tests.size()); const int result = Bse::Test::run_test (tests[test_index]); if (result < 0) { Bse::printout (" RUN… %s\n", tests[test_index]); Bse::printout (" FAIL %s - test missing\n", tests[test_index]); return -1; } } IpcSharedMem::release_shared (sm, jobfd); DEBUG ("JOBDONE (%u)\n", Bse::this_thread_getpid()); return 0; } #include <unistd.h> // fork exec #include <sys/wait.h> // waitpid static int jobserver (const char *const argv0, Bse::StringVector &tests) { std::reverse (tests.begin(), tests.end()); // the IpcSharedMem counter is decremented const std::string testlist = Bse::string_join ("\n", tests); int fd = -1; IpcSharedMem *sm = IpcSharedMem::create_shared (testlist, &fd, tests.size()); if (fd < 0 || !sm) die ("failed to create shared memory segment: %s", Bse::strerror (errno)); DEBUG ("jobserver: pid=%u\n", Bse::this_thread_getpid()); const size_t n_jobs = std::max (1, Bse::this_thread_online_cpus()); std::vector<pid_t> jobs; for (size_t i = 0; i < n_jobs; i++) if (sm->counter > 0) // avoid spawning jobs if there's no work { const pid_t child = fork(); if (child == 0) { execl (argv0, argv0, "--jobfd", Bse::string_from_int (fd).c_str(), NULL); die ("failed to execl(\"%s\"): %s", argv0, Bse::strerror (errno)); } else if (child < 0) { DEBUG ("%s: failed to fork: %s\n", argv0, Bse::strerror (errno)); } else jobs.push_back (child); } int serverstatus = 0; while (jobs.size()) { int wstatus = 0; const int pid = waitpid (-1, &wstatus, 0); if (pid < 0) { DEBUG ("%s: waitpid(%d) failed: %s\n", argv0, pid, Bse::strerror (errno)); if (errno == ECHILD) abort(); // lost track of jobs continue; } const int exitstatus = WIFEXITED (wstatus) ? WEXITSTATUS (wstatus) : WIFSIGNALED (wstatus) ? -WTERMSIG (wstatus) : -128; auto it = std::find (jobs.begin(), jobs.end(), pid); if (it == jobs.end()) DEBUG ("%s: orphan (%d) exited: %d\n", argv0, pid, exitstatus); else { jobs.erase (it); if (!serverstatus) serverstatus = exitstatus; DEBUG ("%s: child (%d) exited: %d\n", argv0, pid, exitstatus); } } const ssize_t remaining_tests = sm->counter; TASSERT (remaining_tests <= 0); IpcSharedMem::destroy_shared (sm, fd); return serverstatus; } <|endoftext|>
<commit_before>// // Created by fanyang on 16-7-24. // #include "../graph.h" #include "../utils.h" #include <fstream> using namespace std; int main(int argc, char** argv) { auto path = getDataPath(); /* { string N = "1000000"; auto pG1 = Graph::fromFile(path + "/data/er_" + N + "_0.0001.txt"); auto pG2 = Graph::fromFile(path + "/data/er_" + N + "_0.0002.txt"); auto pG3 = Graph::fromFile(path + "/data/er_" + N + "_0.0003.txt"); auto maxD1 = pG1->maxDegree(), maxD2 = pG2->maxDegree(), maxD3 = pG3->maxDegree(); ofstream outFile((path + "/result/er_" + N + ".txt").c_str()); cout << "Will up to " << maxD3 << endl; for (size_t i = 1; i <= 1000000; ++i) { if (i - 1 > maxD3 + 2) break; if (i % 200 == 0) cout << i << endl; auto result1 = pG1->getSubgraphNumber_Star(i).get_str(10); auto result2 = pG2->getSubgraphNumber_Star(i).get_str(10); auto result3 = pG3->getSubgraphNumber_Star(i).get_str(10); outFile << result1.substr(0, 3) << " " << result1.size() << " "; outFile << result2.substr(0, 3) << " " << result1.size() << " "; outFile << result3.substr(0, 3) << " " << result1.size() << " "; outFile << endl; } outFile.close(); } */ { auto pGA = Graph::fromFileByNamedVertices(path + "/data/Arxiv-CondMat.txt"); auto pGY = Graph::fromFileByNamedVertices(path + "/data/YouTube.txt"); auto pGL = Graph::fromFileByNamedVertices(path + "/data/LiveJournal.txt"); auto pGD = Graph::fromFileByNamedVertices(path + "/data/DBLP.txt"); auto pGF = Graph::fromFileByNamedVertices(path + "/data/Facebook.txt"); auto maxD = pGA->maxDegree(); if (pGY->maxDegree() > maxD) maxD = pGY->maxDegree(); if (pGL->maxDegree() > maxD) maxD = pGL->maxDegree(); if (pGD->maxDegree() > maxD) maxD = pGD->maxDegree(); if (pGF->maxDegree() > maxD) maxD = pGF->maxDegree(); auto minN = pGA->size(); if (pGY->size() < minN) minN = pGY->size(); if (pGL->size() < minN) minN = pGL->size(); if (pGD->size() < minN) minN = pGD->size(); if (pGF->size() < minN) minN = pGF->size(); ofstream outFile((path + "/result/real.txt").c_str()); cout << "Will up to " << maxD << endl; for (size_t i = 1; i < minN; ++i) { if (i - 1 > maxD + 2) break; if (i % 200 == 0) cout << i << endl; auto resultA = pGA->getSubgraphNumber_Star(i).get_str(10); auto resultY = pGY->getSubgraphNumber_Star(i).get_str(10); auto resultL = pGL->getSubgraphNumber_Star(i).get_str(10); auto resultD = pGD->getSubgraphNumber_Star(i).get_str(10); auto resultF = pGF->getSubgraphNumber_Star(i).get_str(10); outFile << resultA.substr(0, 3) << " " << resultA.size() << " "; outFile << resultY.substr(0, 3) << " " << resultY.size() << " "; outFile << resultL.substr(0, 3) << " " << resultL.size() << " "; outFile << resultD.substr(0, 3) << " " << resultD.size() << " "; outFile << resultF.substr(0, 3) << " " << resultF.size() << " "; outFile << endl; } outFile.close(); } return 0; } <commit_msg>Some small changes in tempTest2.cpp<commit_after>// // Created by fanyang on 16-7-24. // #include "../graph.h" #include "../utils.h" #include <fstream> using namespace std; int main(int argc, char** argv) { auto path = getDataPath(); /* { string N = "1000000"; auto pG1 = Graph::fromFile(path + "/data/er_" + N + "_0.0001.txt"); auto pG2 = Graph::fromFile(path + "/data/er_" + N + "_0.0002.txt"); auto pG3 = Graph::fromFile(path + "/data/er_" + N + "_0.0003.txt"); auto maxD1 = pG1->maxDegree(), maxD2 = pG2->maxDegree(), maxD3 = pG3->maxDegree(); ofstream outFile((path + "/result/er_" + N + ".txt").c_str()); cout << "Will up to " << maxD3 << endl; for (size_t i = 1; i <= 1000000; ++i) { if (i - 1 > maxD3 + 2) break; if (i % 200 == 0) cout << i << endl; auto result1 = pG1->getSubgraphNumber_Star(i).get_str(10); auto result2 = pG2->getSubgraphNumber_Star(i).get_str(10); auto result3 = pG3->getSubgraphNumber_Star(i).get_str(10); outFile << result1.substr(0, 3) << " " << result1.size() << " "; outFile << result2.substr(0, 3) << " " << result1.size() << " "; outFile << result3.substr(0, 3) << " " << result1.size() << " "; outFile << endl; } outFile.close(); } */ { auto pGA = Graph::fromFileByNamedVertices(path + "/data/Arxiv-CondMat.txt"); auto pGY = Graph::fromFileByNamedVertices(path + "/data/YouTube.txt"); auto pGL = Graph::fromFileByNamedVertices(path + "/data/LiveJournal.txt"); auto pGD = Graph::fromFileByNamedVertices(path + "/data/DBLP.txt"); auto pGF = Graph::fromFileByNamedVertices(path + "/data/Facebook.txt"); auto maxD = pGA->maxDegree(); if (pGY->maxDegree() > maxD) maxD = pGY->maxDegree(); if (pGL->maxDegree() > maxD) maxD = pGL->maxDegree(); if (pGD->maxDegree() > maxD) maxD = pGD->maxDegree(); if (pGF->maxDegree() > maxD) maxD = pGF->maxDegree(); auto minN = pGA->size(); if (pGY->size() < minN) minN = pGY->size(); if (pGL->size() < minN) minN = pGL->size(); if (pGD->size() < minN) minN = pGD->size(); if (pGF->size() < minN) minN = pGF->size(); ofstream outFile((path + "/result/real.txt").c_str()); cout << "Will up to " << maxD << endl; cout << "MinN = " << minN << endl; for (size_t i = 1; i < maxD + 10; ++i) { if (i - 1 > maxD + 2) break; if (i % 200 == 0) cout << i << endl; auto resultA = pGA->getSubgraphNumber_Star(i).get_str(10); auto resultY = pGY->getSubgraphNumber_Star(i).get_str(10); auto resultL = pGL->getSubgraphNumber_Star(i).get_str(10); auto resultD = pGD->getSubgraphNumber_Star(i).get_str(10); auto resultF = pGF->getSubgraphNumber_Star(i).get_str(10); outFile << resultA.substr(0, 3) << " " << resultA.size() << " "; outFile << resultY.substr(0, 3) << " " << resultY.size() << " "; outFile << resultL.substr(0, 3) << " " << resultL.size() << " "; outFile << resultD.substr(0, 3) << " " << resultD.size() << " "; outFile << resultF.substr(0, 3) << " " << resultF.size() << " "; outFile << endl; } outFile.close(); } return 0; } <|endoftext|>
<commit_before>#include <cthun-client/connector/connector.hpp> #include <cthun-client/connector/uuid.hpp> #include <cthun-client/protocol/message.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector" #include <leatherman/logging/logging.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <cstdio> #include <chrono> namespace CthunClient { // // Constants // static const uint CONNECTION_CHECK_S { 15 }; // [s] static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s] // // Utility functions // // TODO(ale): move this to leatherman std::string getISO8601Time(unsigned int modifier_in_seconds) { boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time() + boost::posix_time::seconds(modifier_in_seconds); return boost::posix_time::to_iso_extended_string(t) + "Z"; } // TODO(ale): move plural from the common StringUtils in leatherman template<typename T> std::string plural(std::vector<T> things); std::string plural(int num_of_things) { return num_of_things > 1 ? "s" : ""; } // // Public api // Connector::Connector(const std::string& server_url, const std::string& type, const std::string& ca_crt_path, const std::string& client_crt_path, const std::string& client_key_path) : server_url_ { server_url }, client_metadata_ { type, ca_crt_path, client_crt_path, client_key_path }, connection_ptr_ { nullptr }, validator_ {}, schema_callback_pairs_ {}, mutex_ {}, cond_var_ {}, is_destructing_ { false }, is_monitoring_ { false } { addEnvelopeSchemaToValidator(); } Connector::~Connector() { if (connection_ptr_ != nullptr) { // reset callbacks to avoid breaking the Connection instance // due to callbacks having an invalid reference context LOG_INFO("Resetting the WebSocket event callbacks"); connection_ptr_->resetCallbacks(); } { std::lock_guard<std::mutex> the_lock { mutex_ }; is_destructing_ = true; cond_var_.notify_one(); } } // Register schemas and onMessage callbacks void Connector::registerMessageCallback(const Schema schema, MessageCallback callback) { validator_.registerSchema(schema); auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback); schema_callback_pairs_.insert(p); } // Manage the connection state void Connector::connect(int max_connect_attempts) { if (connection_ptr_ == nullptr) { // Initialize the WebSocket connection connection_ptr_.reset(new Connection(server_url_, client_metadata_)); connection_ptr_->setOnMessageCallback( [this](std::string message) { processMessage(message); }); connection_ptr_->setOnOpenCallback( [this]() { sendLogin(); }); } try { // Open the WebSocket connection connection_ptr_->connect(max_connect_attempts); } catch (connection_processing_error& e) { // NB: connection_fatal_errors are propagated whereas // connection_processing_errors are converted to // connection_config_errors (they can be thrown after // websocketpp::Endpoint::connect() or ::send() failures) LOG_ERROR("Failed to connect: %1%", e.what()); throw connection_config_error { e.what() }; } } bool Connector::isConnected() const { // TODO(ale): make this consistent with the login transaction as // specified in the protocol specs (perhaps with a logged-in flag) return connection_ptr_ != nullptr && connection_ptr_->getConnectionState() == ConnectionStateValues::open; } void Connector::monitorConnection(int max_connect_attempts) { checkConnectionInitialization(); if (!is_monitoring_) { is_monitoring_ = true; startMonitorTask(max_connect_attempts); } else { LOG_WARNING("The monitorConnection has already been called"); } } // Send messages void Connector::send(const Message& msg) { checkConnectionInitialization(); auto serialized_msg = msg.getSerialized(); LOG_DEBUG("Sending message of %1% bytes:\n%2%", serialized_msg.size(), msg.toString()); connection_ptr_->send(&serialized_msg[0], serialized_msg.size()); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, const DataContainer& data_json, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, false, data_json.toString(), debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, const std::string& data_binary, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, false, data_binary, debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const DataContainer& data_json, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, destination_report, data_json.toString(), debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const std::string& data_binary, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, destination_report, data_binary, debug); } // // Private interface // // Utility functions void Connector::checkConnectionInitialization() { if (connection_ptr_ == nullptr) { throw connection_not_init_error { "connection not initialized" }; } } void Connector::addEnvelopeSchemaToValidator() { Schema schema { ENVELOPE_SCHEMA_NAME, ContentType::Json }; schema.addConstraint("id", TypeConstraint::String, true); schema.addConstraint("expires", TypeConstraint::String, true); schema.addConstraint("sender", TypeConstraint::String, true); schema.addConstraint("endpoints", TypeConstraint::Array, true); schema.addConstraint("data_schema", TypeConstraint::String, true); schema.addConstraint("destination_report", TypeConstraint::Bool, false); validator_.registerSchema(schema); } MessageChunk Connector::createEnvelope(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report) { auto msg_id = UUID::getUUID(); auto expires = getISO8601Time(timeout); LOG_INFO("Creating message with id %1% for %2% receiver%3%", msg_id, endpoints.size(), plural(endpoints.size())); DataContainer envelope_content {}; envelope_content.set<std::string>("id", msg_id); envelope_content.set<std::string>("expires", expires); envelope_content.set<std::string>("sender", client_metadata_.id); envelope_content.set<std::string>("data_schema", data_schema); envelope_content.set<std::vector<std::string>>("endpoints", endpoints); if (destination_report) { envelope_content.set<bool>("destination_report", true); } return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() }; } void Connector::sendMessage(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const std::string& data_txt, const std::vector<DataContainer>& debug) { auto envelope_chunk = createEnvelope(endpoints, data_schema, timeout, destination_report); MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt }; Message msg { envelope_chunk, data_chunk }; for (auto debug_content : debug) { MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() }; msg.addDebugChunk(d_c); } send(msg); } // Login void Connector::sendLogin() { // Envelope // TODO(ale): use the complete server URI once we apply the specs auto envelope = createEnvelope(std::vector<std::string> { "cth://server" }, CTHUN_LOGIN_SCHEMA_NAME, DEFAULT_MSG_TIMEOUT, false); // Data DataContainer data_entries {}; data_entries.set<std::string>("type", client_metadata_.type); MessageChunk data { ChunkDescriptor::DATA, data_entries.toString() }; // Create and send message Message msg { envelope, data }; LOG_INFO("Sending login message"); LOG_DEBUG("Login message data: %1%", data.content); send(msg); } // WebSocket onMessage callback void Connector::processMessage(const std::string& msg_txt) { LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt); // Deserialize the incoming message std::unique_ptr<Message> msg_ptr; try { msg_ptr.reset(new Message(msg_txt)); } catch (message_error& e) { LOG_ERROR("Failed to deserialize message: %1%", e.what()); return; } // Parse message chunks ParsedChunks parsed_chunks; try { parsed_chunks = msg_ptr->getParsedChunks(validator_); } catch (validator_error& e) { LOG_ERROR("Invalid message: %1%", e.what()); return; } // Execute the callback associated with the data schema auto schema_name = parsed_chunks.envelope.get<std::string>("data_schema"); if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) { auto c_b = schema_callback_pairs_.at(schema_name); LOG_TRACE("Executing callback for a message with '%1%' schema", schema_name); c_b(parsed_chunks); } else { LOG_WARNING("No message callback has be registered for '%1%' schema", schema_name); } } // Monitor task void Connector::startMonitorTask(int max_connect_attempts) { assert(connection_ptr_ != nullptr); while (true) { std::unique_lock<std::mutex> the_lock { mutex_ }; auto now = std::chrono::system_clock::now(); cond_var_.wait_until(the_lock, now + std::chrono::seconds(CONNECTION_CHECK_S)); if (is_destructing_) { // The dtor has been invoked LOG_INFO("Stopping the monitor task"); is_monitoring_ = false; the_lock.unlock(); return; } try { if (!isConnected()) { LOG_WARNING("Connection to Cthun server lost; retrying"); connection_ptr_->connect(max_connect_attempts); } else { LOG_DEBUG("Sending heartbeat ping"); connection_ptr_->ping(); } } catch (connection_processing_error& e) { // Connection::connect() or ping() failure - keep trying LOG_ERROR("Connection monitor failure: %1%", e.what()); } catch (connection_fatal_error& e) { // Failed to reconnect after max_connect_attempts - stop LOG_ERROR("The connection monitor task will stop - failure: %1%", e.what()); is_monitoring_ = false; the_lock.unlock(); throw; } the_lock.unlock(); } } } // namespace CthunClient <commit_msg>(CTH-217) Use protocol/schemas.hpp in Connector<commit_after>#include <cthun-client/connector/connector.hpp> #include <cthun-client/connector/uuid.hpp> #include <cthun-client/protocol/message.hpp> #include <cthun-client/protocol/schemas.hpp> #define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector" #include <leatherman/logging/logging.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <cstdio> #include <chrono> namespace CthunClient { // // Constants // static const uint CONNECTION_CHECK_S { 15 }; // [s] static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s] // // Utility functions // // TODO(ale): move this to leatherman std::string getISO8601Time(unsigned int modifier_in_seconds) { boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time() + boost::posix_time::seconds(modifier_in_seconds); return boost::posix_time::to_iso_extended_string(t) + "Z"; } // TODO(ale): move plural from the common StringUtils in leatherman template<typename T> std::string plural(std::vector<T> things); std::string plural(int num_of_things) { return num_of_things > 1 ? "s" : ""; } // // Public api // Connector::Connector(const std::string& server_url, const std::string& type, const std::string& ca_crt_path, const std::string& client_crt_path, const std::string& client_key_path) : server_url_ { server_url }, client_metadata_ { type, ca_crt_path, client_crt_path, client_key_path }, connection_ptr_ { nullptr }, validator_ {}, schema_callback_pairs_ {}, mutex_ {}, cond_var_ {}, is_destructing_ { false }, is_monitoring_ { false } { addEnvelopeSchemaToValidator(); } Connector::~Connector() { if (connection_ptr_ != nullptr) { // reset callbacks to avoid breaking the Connection instance // due to callbacks having an invalid reference context LOG_INFO("Resetting the WebSocket event callbacks"); connection_ptr_->resetCallbacks(); } { std::lock_guard<std::mutex> the_lock { mutex_ }; is_destructing_ = true; cond_var_.notify_one(); } } // Register schemas and onMessage callbacks void Connector::registerMessageCallback(const Schema schema, MessageCallback callback) { validator_.registerSchema(schema); auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback); schema_callback_pairs_.insert(p); } // Manage the connection state void Connector::connect(int max_connect_attempts) { if (connection_ptr_ == nullptr) { // Initialize the WebSocket connection connection_ptr_.reset(new Connection(server_url_, client_metadata_)); connection_ptr_->setOnMessageCallback( [this](std::string message) { processMessage(message); }); connection_ptr_->setOnOpenCallback( [this]() { sendLogin(); }); } try { // Open the WebSocket connection connection_ptr_->connect(max_connect_attempts); } catch (connection_processing_error& e) { // NB: connection_fatal_errors are propagated whereas // connection_processing_errors are converted to // connection_config_errors (they can be thrown after // websocketpp::Endpoint::connect() or ::send() failures) LOG_ERROR("Failed to connect: %1%", e.what()); throw connection_config_error { e.what() }; } } bool Connector::isConnected() const { // TODO(ale): make this consistent with the login transaction as // specified in the protocol specs (perhaps with a logged-in flag) return connection_ptr_ != nullptr && connection_ptr_->getConnectionState() == ConnectionStateValues::open; } void Connector::monitorConnection(int max_connect_attempts) { checkConnectionInitialization(); if (!is_monitoring_) { is_monitoring_ = true; startMonitorTask(max_connect_attempts); } else { LOG_WARNING("The monitorConnection has already been called"); } } // Send messages void Connector::send(const Message& msg) { checkConnectionInitialization(); auto serialized_msg = msg.getSerialized(); LOG_DEBUG("Sending message of %1% bytes:\n%2%", serialized_msg.size(), msg.toString()); connection_ptr_->send(&serialized_msg[0], serialized_msg.size()); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, const DataContainer& data_json, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, false, data_json.toString(), debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, const std::string& data_binary, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, false, data_binary, debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const DataContainer& data_json, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, destination_report, data_json.toString(), debug); } void Connector::send(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const std::string& data_binary, const std::vector<DataContainer>& debug) { sendMessage(endpoints, data_schema, timeout, destination_report, data_binary, debug); } // // Private interface // // Utility functions void Connector::checkConnectionInitialization() { if (connection_ptr_ == nullptr) { throw connection_not_init_error { "connection not initialized" }; } } void Connector::addEnvelopeSchemaToValidator() { auto schema = Protocol::getEnvelopeSchema(); validator_.registerSchema(schema); } MessageChunk Connector::createEnvelope(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report) { auto msg_id = UUID::getUUID(); auto expires = getISO8601Time(timeout); LOG_INFO("Creating message with id %1% for %2% receiver%3%", msg_id, endpoints.size(), plural(endpoints.size())); DataContainer envelope_content {}; envelope_content.set<std::string>("id", msg_id); envelope_content.set<std::string>("expires", expires); envelope_content.set<std::string>("sender", client_metadata_.id); envelope_content.set<std::string>("data_schema", data_schema); envelope_content.set<std::vector<std::string>>("endpoints", endpoints); if (destination_report) { envelope_content.set<bool>("destination_report", true); } return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() }; } void Connector::sendMessage(const std::vector<std::string>& endpoints, const std::string& data_schema, unsigned int timeout, bool destination_report, const std::string& data_txt, const std::vector<DataContainer>& debug) { auto envelope_chunk = createEnvelope(endpoints, data_schema, timeout, destination_report); MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt }; Message msg { envelope_chunk, data_chunk }; for (auto debug_content : debug) { MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() }; msg.addDebugChunk(d_c); } send(msg); } // Login void Connector::sendLogin() { // Envelope // TODO(ale): use the complete server URI once we apply the specs auto envelope = createEnvelope(std::vector<std::string> { "cth://server" }, CTHUN_LOGIN_SCHEMA_NAME, DEFAULT_MSG_TIMEOUT, false); // Data DataContainer data_entries {}; data_entries.set<std::string>("type", client_metadata_.type); MessageChunk data { ChunkDescriptor::DATA, data_entries.toString() }; // Create and send message Message msg { envelope, data }; LOG_INFO("Sending login message"); LOG_DEBUG("Login message data: %1%", data.content); send(msg); } // WebSocket onMessage callback void Connector::processMessage(const std::string& msg_txt) { LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt); // Deserialize the incoming message std::unique_ptr<Message> msg_ptr; try { msg_ptr.reset(new Message(msg_txt)); } catch (message_error& e) { LOG_ERROR("Failed to deserialize message: %1%", e.what()); return; } // Parse message chunks ParsedChunks parsed_chunks; try { parsed_chunks = msg_ptr->getParsedChunks(validator_); } catch (validator_error& e) { LOG_ERROR("Invalid message: %1%", e.what()); return; } // Execute the callback associated with the data schema auto schema_name = parsed_chunks.envelope.get<std::string>("data_schema"); if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) { auto c_b = schema_callback_pairs_.at(schema_name); LOG_TRACE("Executing callback for a message with '%1%' schema", schema_name); c_b(parsed_chunks); } else { LOG_WARNING("No message callback has be registered for '%1%' schema", schema_name); } } // Monitor task void Connector::startMonitorTask(int max_connect_attempts) { assert(connection_ptr_ != nullptr); while (true) { std::unique_lock<std::mutex> the_lock { mutex_ }; auto now = std::chrono::system_clock::now(); cond_var_.wait_until(the_lock, now + std::chrono::seconds(CONNECTION_CHECK_S)); if (is_destructing_) { // The dtor has been invoked LOG_INFO("Stopping the monitor task"); is_monitoring_ = false; the_lock.unlock(); return; } try { if (!isConnected()) { LOG_WARNING("Connection to Cthun server lost; retrying"); connection_ptr_->connect(max_connect_attempts); } else { LOG_DEBUG("Sending heartbeat ping"); connection_ptr_->ping(); } } catch (connection_processing_error& e) { // Connection::connect() or ping() failure - keep trying LOG_ERROR("Connection monitor failure: %1%", e.what()); } catch (connection_fatal_error& e) { // Failed to reconnect after max_connect_attempts - stop LOG_ERROR("The connection monitor task will stop - failure: %1%", e.what()); is_monitoring_ = false; the_lock.unlock(); throw; } the_lock.unlock(); } } } // namespace CthunClient <|endoftext|>
<commit_before>#include "blockbrowser.h" #include "ui_blockbrowser.h" #include "main.h" #include "wallet.h" #include "base58.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "transactionrecord.h" #include "txdb.h" #include <sstream> #include <string> using namespace std; double getBlockHardness(int64 height) { const CBlockIndex* blockindex = getBlockIndex(height); int64 nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64 getBlockHashrate(int64 height) { // Tranz: Need to change between Hash rate and NetStakeWeight int64 lookup = height; double timeDiff = getBlockTime(height) - getBlockTime(1); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)getBlockHardness(height) * pow(2.0, 32)) / timePerBlock); } const CBlockIndex* getBlockIndex(int64 height) { std::string hex = getBlockHash(height); uint256 hash(hex); return mapBlockIndex[hash]; } std::string getBlockHash(int64 Height) { if(Height > pindexBest->nHeight) { return ""; } if(Height < 0) { return ""; } int64 desiredheight; desiredheight = Height; if (desiredheight < 0 || desiredheight > nBestHeight) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > desiredheight) pblockindex = pblockindex->pprev; return pblockindex->GetBlockHash().GetHex(); // pblockindex->phashBlock->GetHex(); } int64 getBlockTime(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nTime; } std::string getBlockMerkle(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->hashMerkleRoot.ToString();//.substr(0,10).c_str(); } int64 getBlocknBits(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nBits; } int64 getBlockNonce(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nNonce; } std::string getBlockDebug(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->ToString(); } int64 blocksInPastHours(int64 hours) { int64 wayback = hours * 3600; bool check = true; int64 height = pindexBest->nHeight; int64 heightHour = pindexBest->nHeight; int64 utime = (int64)time(NULL); int64 target = utime - wayback; while(check) { if(getBlockTime(heightHour) < target) { check = false; return height - heightHour; } else { heightHour = heightHour - 1; } } return 0; } double getTxTotalValue(std::string txid) { uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return 0; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; double value = 0; double buffer = 0; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; buffer = value + convertCoins(txout.nValue); value = buffer; } return value; } double convertCoins(int64 amount) { // Tranz needs to use options model. return (double)amount / (double)COIN; } std::string getOutputs(std::string txid) { //Tranz This needs major work. uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return "N/A"; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; std::string str = ""; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; CTxDestination source; ExtractDestination(txout.scriptPubKey, source); CBitcoinAddress addressSource(source); std::string lol7 = addressSource.ToString(); double buffer = convertCoins(txout.nValue); std::string amount = boost::to_string(buffer); str.append(lol7); str.append(": "); str.append(amount); str.append(" HBN"); str.append("\n"); } return str; } std::string getInputs(std::string txid) { //Tranz this needs major work. uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return "N/A"; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; std::string str = ""; for (unsigned int i = 0; i < tx.vin.size(); i++) { uint256 hash; const CTxIn& vin = tx.vin[i]; hash.SetHex(vin.prevout.hash.ToString()); CTransaction wtxPrev; uint256 hashBlock = 0; if (!GetTransaction(hash, wtxPrev, hashBlock)) return "N/A"; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << wtxPrev; CTxDestination source; ExtractDestination(wtxPrev.vout[vin.prevout.n].scriptPubKey, source); CBitcoinAddress addressSource(source); std::string lol6 = addressSource.ToString(); const CScript target = wtxPrev.vout[vin.prevout.n].scriptPubKey; double buffer = convertCoins(getInputValue(wtxPrev, target)); std::string amount = boost::to_string(buffer); str.append(lol6); str.append(": "); str.append(amount); str.append(" HBN"); str.append("\n"); } return str; } int64 getInputValue(CTransaction tx, CScript target) { //Tranz needs work for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& txout = tx.vout[i]; if(txout.scriptPubKey == target) { return txout.nValue; } } //return 0; } double BlockBrowser::getTxFees(std::string txid) { uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; CTxDB txdb("r"); if (!GetTransaction(hash, tx, hashBlock)) return convertCoins(MIN_TX_FEE); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) return convertCoins(MIN_TX_FEE); int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if(tx.IsCoinStake() || tx.IsCoinBase()) { ui->feesLabel->setText(QString("Reward")); nTxFees *= -1; } else ui->feesLabel->setText(QString("Fees")); return convertCoins(nTxFees); } BlockBrowser::BlockBrowser(QWidget *parent) : QDialog(parent, (Qt::WindowMinMaxButtonsHint|Qt::WindowCloseButtonHint)), ui(new Ui::BlockBrowser) { ui->setupUi(this); setBaseSize(850, 500); connect(ui->blockButton, SIGNAL(pressed()), this, SLOT(blockClicked())); connect(ui->txButton, SIGNAL(pressed()), this, SLOT(txClicked())); } void BlockBrowser::updateExplorer(bool block) { if(block) { ui->heightLabelBE1->show(); ui->heightLabelBE1->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->heightLabelBE2->show(); ui->heightLabelBE1->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hashLabel->show(); ui->hashLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hashBox->show(); ui->hashBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->merkleLabel->show(); ui->merkleLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->merkleBox->show(); ui->merkleBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->nonceLabel->show(); ui->nonceLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->nonceBox->show(); ui->nonceBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->bitsLabel->show(); ui->bitsLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->bitsBox->show(); ui->bitsBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->timeLabel->show(); ui->timeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->timeBox->show(); ui->timeBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hardLabel->show(); ui->hardLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hardBox->show();; ui->hardBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->pawLabel->show(); ui->pawLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->pawBox->show(); ui->pawBox->setTextInteractionFlags(Qt::TextSelectableByMouse); int64 height = ui->heightBox->value(); if (height > pindexBest->nHeight) { ui->heightBox->setValue(pindexBest->nHeight); height = pindexBest->nHeight; } int64 Pawrate = getBlockHashrate(height); double Pawrate2 = 0.000; Pawrate2 = ((double)Pawrate / 1000000); std::string hash = getBlockHash(height); std::string merkle = getBlockMerkle(height); int64 nBits = getBlocknBits(height); int64 nNonce = getBlockNonce(height); int64 atime = getBlockTime(height); double hardness = getBlockHardness(height); QString QHeight = QString::number(height); QString QHash = QString::fromUtf8(hash.c_str()); QString QMerkle = QString::fromUtf8(merkle.c_str()); QString QBits = QString::number(nBits); QString QNonce = QString::number(nNonce); QString QTime = QString::number(atime); QString QHardness = QString::number(hardness, 'f', 6); QString QPawrate = QString::number(Pawrate2, 'f', 3); ui->heightLabelBE1->setText(QHeight); ui->hashBox->setText(QHash); ui->merkleBox->setText(QMerkle); ui->bitsBox->setText(QBits); ui->nonceBox->setText(QNonce); ui->timeBox->setText(QTime); ui->hardBox->setText(QHardness); ui->pawBox->setText(QPawrate + " MH/s"); } if(block == false) { ui->txID->show(); ui->txID->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->txLabel->show(); ui->txLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->valueLabel->show(); ui->valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->valueBox->show(); ui->valueBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->inputLabel->show(); ui->inputLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->inputBox->show(); ui->inputBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->outputLabel->show(); ui->outputLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->outputBox->show(); ui->outputBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->feesLabel->show(); ui->feesLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->feesBox->show(); ui->feesBox->setTextInteractionFlags(Qt::TextSelectableByMouse); std::string txid = ui->txBox->text().toUtf8().constData(); double value = getTxTotalValue(txid); double fees = getTxFees(txid); std::string outputs = getOutputs(txid); std::string inputs = getInputs(txid); QString QValue = QString::number(value, 'f', 6); QString QID = QString::fromUtf8(txid.c_str()); QString QOutputs = QString::fromUtf8(outputs.c_str()); QString QInputs = QString::fromUtf8(inputs.c_str()); QString QFees = QString::number(fees, 'f', 6); ui->valueBox->setText(QValue + " HBN"); ui->txID->setText(QID); ui->outputBox->setText(QOutputs); ui->inputBox->setText(QInputs); ui->feesBox->setText(QFees + " HBN"); } } void BlockBrowser::setTransactionId(const QString &transactionId) { ui->txBox->setText(transactionId); ui->txBox->setFocus(); updateExplorer(false); } void BlockBrowser::txClicked() { updateExplorer(false); } void BlockBrowser::blockClicked() { updateExplorer(true); } void BlockBrowser::setModel(ClientModel *model) { this->model = model; } BlockBrowser::~BlockBrowser() { delete ui; } <commit_msg>Block Browser Fix Outputs<commit_after>#include "blockbrowser.h" #include "ui_blockbrowser.h" #include "main.h" #include "wallet.h" #include "base58.h" #include "clientmodel.h" #include "transactionrecord.h" #include "txdb.h" #include <sstream> #include <string> using namespace std; double getBlockHardness(int64 height) { const CBlockIndex* blockindex = getBlockIndex(height); int64 nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64 getBlockHashrate(int64 height) { // Tranz: Need to change between Hash rate and NetStakeWeight int64 lookup = height; double timeDiff = getBlockTime(height) - getBlockTime(1); double timePerBlock = timeDiff / lookup; return (boost::int64_t)(((double)getBlockHardness(height) * pow(2.0, 32)) / timePerBlock); } const CBlockIndex* getBlockIndex(int64 height) { std::string hex = getBlockHash(height); uint256 hash(hex); return mapBlockIndex[hash]; } std::string getBlockHash(int64 Height) { if(Height > pindexBest->nHeight) { return ""; } if(Height < 0) { return ""; } int64 desiredheight; desiredheight = Height; if (desiredheight < 0 || desiredheight > nBestHeight) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > desiredheight) pblockindex = pblockindex->pprev; return pblockindex->GetBlockHash().GetHex(); // pblockindex->phashBlock->GetHex(); } int64 getBlockTime(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nTime; } std::string getBlockMerkle(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->hashMerkleRoot.ToString();//.substr(0,10).c_str(); } int64 getBlocknBits(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nBits; } int64 getBlockNonce(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->nNonce; } std::string getBlockDebug(int64 Height) { std::string strHash = getBlockHash(Height); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) return 0; CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; return pblockindex->ToString(); } int64 blocksInPastHours(int64 hours) { int64 wayback = hours * 3600; bool check = true; int64 height = pindexBest->nHeight; int64 heightHour = pindexBest->nHeight; int64 utime = (int64)time(NULL); int64 target = utime - wayback; while(check) { if(getBlockTime(heightHour) < target) { check = false; return height - heightHour; } else { heightHour = heightHour - 1; } } return 0; } double getTxTotalValue(std::string txid) { uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return 0; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; double value = 0; double buffer = 0; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; buffer = value + convertCoins(txout.nValue); value = buffer; } return value; } double convertCoins(int64 amount) { // Tranz needs to use options model. return (double)amount / (double)COIN; } std::string getOutputs(std::string txid) { uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return "N/A"; std::string str = ""; for (unsigned int i = (tx.IsCoinStake() ? 1 : 0); i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) ) address = CNoDestination(); double buffer = convertCoins(txout.nValue); std::string amount = boost::to_string(buffer); str.append(CBitcoinAddress(address).ToString()); str.append(": "); str.append(amount); str.append(" HBN"); str.append("\n"); } return str; } std::string getInputs(std::string txid) { //Tranz this needs major work. uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) return "N/A"; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; std::string str = ""; for (unsigned int i = 0; i < tx.vin.size(); i++) { uint256 hash; const CTxIn& vin = tx.vin[i]; hash.SetHex(vin.prevout.hash.ToString()); CTransaction wtxPrev; uint256 hashBlock = 0; if (!GetTransaction(hash, wtxPrev, hashBlock)) return "N/A"; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << wtxPrev; CTxDestination source; ExtractDestination(wtxPrev.vout[vin.prevout.n].scriptPubKey, source); CBitcoinAddress addressSource(source); std::string lol6 = addressSource.ToString(); const CScript target = wtxPrev.vout[vin.prevout.n].scriptPubKey; double buffer = convertCoins(getInputValue(wtxPrev, target)); std::string amount = boost::to_string(buffer); str.append(lol6); str.append(": "); str.append(amount); str.append(" HBN"); str.append("\n"); } return str; } int64 getInputValue(CTransaction tx, CScript target) { //Tranz needs work for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& txout = tx.vout[i]; if(txout.scriptPubKey == target) { return txout.nValue; } } //return 0; } double BlockBrowser::getTxFees(std::string txid) { uint256 hash; hash.SetHex(txid); CTransaction tx; uint256 hashBlock = 0; CTxDB txdb("r"); if (!GetTransaction(hash, tx, hashBlock)) return convertCoins(MIN_TX_FEE); MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) return convertCoins(MIN_TX_FEE); int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if(tx.IsCoinStake() || tx.IsCoinBase()) { ui->feesLabel->setText(QString("Reward")); nTxFees *= -1; } else ui->feesLabel->setText(QString("Fees")); return convertCoins(nTxFees); } BlockBrowser::BlockBrowser(QWidget *parent) : QDialog(parent, (Qt::WindowMinMaxButtonsHint|Qt::WindowCloseButtonHint)), ui(new Ui::BlockBrowser) { ui->setupUi(this); setBaseSize(850, 500); connect(ui->blockButton, SIGNAL(pressed()), this, SLOT(blockClicked())); connect(ui->txButton, SIGNAL(pressed()), this, SLOT(txClicked())); } void BlockBrowser::updateExplorer(bool block) { if(block) { ui->heightLabelBE1->show(); ui->heightLabelBE1->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->heightLabelBE2->show(); ui->heightLabelBE1->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hashLabel->show(); ui->hashLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hashBox->show(); ui->hashBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->merkleLabel->show(); ui->merkleLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->merkleBox->show(); ui->merkleBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->nonceLabel->show(); ui->nonceLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->nonceBox->show(); ui->nonceBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->bitsLabel->show(); ui->bitsLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->bitsBox->show(); ui->bitsBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->timeLabel->show(); ui->timeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->timeBox->show(); ui->timeBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hardLabel->show(); ui->hardLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->hardBox->show();; ui->hardBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->pawLabel->show(); ui->pawLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->pawBox->show(); ui->pawBox->setTextInteractionFlags(Qt::TextSelectableByMouse); int64 height = ui->heightBox->value(); if (height > pindexBest->nHeight) { ui->heightBox->setValue(pindexBest->nHeight); height = pindexBest->nHeight; } int64 Pawrate = getBlockHashrate(height); double Pawrate2 = 0.000; Pawrate2 = ((double)Pawrate / 1000000); std::string hash = getBlockHash(height); std::string merkle = getBlockMerkle(height); int64 nBits = getBlocknBits(height); int64 nNonce = getBlockNonce(height); int64 atime = getBlockTime(height); double hardness = getBlockHardness(height); QString QHeight = QString::number(height); QString QHash = QString::fromUtf8(hash.c_str()); QString QMerkle = QString::fromUtf8(merkle.c_str()); QString QBits = QString::number(nBits); QString QNonce = QString::number(nNonce); QString QTime = QString::number(atime); QString QHardness = QString::number(hardness, 'f', 6); QString QPawrate = QString::number(Pawrate2, 'f', 3); ui->heightLabelBE1->setText(QHeight); ui->hashBox->setText(QHash); ui->merkleBox->setText(QMerkle); ui->bitsBox->setText(QBits); ui->nonceBox->setText(QNonce); ui->timeBox->setText(QTime); ui->hardBox->setText(QHardness); ui->pawBox->setText(QPawrate + " MH/s"); } if(block == false) { ui->txID->show(); ui->txID->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->txLabel->show(); ui->txLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->valueLabel->show(); ui->valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->valueBox->show(); ui->valueBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->inputLabel->show(); ui->inputLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->inputBox->show(); ui->inputBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->outputLabel->show(); ui->outputLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->outputBox->show(); ui->outputBox->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->feesLabel->show(); ui->feesLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); ui->feesBox->show(); ui->feesBox->setTextInteractionFlags(Qt::TextSelectableByMouse); std::string txid = ui->txBox->text().toUtf8().constData(); double value = getTxTotalValue(txid); double fees = getTxFees(txid); std::string outputs = getOutputs(txid); std::string inputs = getInputs(txid); QString QValue = QString::number(value, 'f', 6); QString QID = QString::fromUtf8(txid.c_str()); QString QOutputs = QString::fromUtf8(outputs.c_str()); QString QInputs = QString::fromUtf8(inputs.c_str()); QString QFees = QString::number(fees, 'f', 6); ui->valueBox->setText(QValue + " HBN"); ui->txID->setText(QID); ui->outputBox->setText(QOutputs); ui->inputBox->setText(QInputs); ui->feesBox->setText(QFees + " HBN"); } } void BlockBrowser::setTransactionId(const QString &transactionId) { ui->txBox->setText(transactionId); ui->txBox->setFocus(); updateExplorer(false); } void BlockBrowser::txClicked() { updateExplorer(false); } void BlockBrowser::blockClicked() { updateExplorer(true); } void BlockBrowser::setModel(ClientModel *model) { this->model = model; } BlockBrowser::~BlockBrowser() { delete ui; } <|endoftext|>
<commit_before>// demo.cpp // // Here is an example on how to use the descriptor presented in the following paper: // A. Alahi, R. Ortiz, and P. Vandergheynst. FREAK: Fast Retina Keypoint. In IEEE Conference on Computer Vision and Pattern Recognition, 2012. // // // Copyright (C) 2011-2012 Signal processing laboratory 2, EPFL, // Raphael Ortiz (raphael.ortiz@a3.epfl.ch), // Kirell Benzi (kirell.benzi@epfl.ch) // Alexandre Alahi (alexandre.alahi@epfl.ch) // and Pierre Vandergheynst (pierre.vandergheynst@epfl.ch) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. #include <iostream> #include <string> #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/nonfree/features2d.hpp> #include <opencv2/legacy/legacy.hpp> #include "freak.h" #include "hammingseg.h" using namespace cv; static const std::string kResPath = "../../resources/"; int main( int argc, char** argv ) { // check http://opencv.itseez.com/doc/tutorials/features2d/table_of_content_features2d/table_of_content_features2d.html // for OpenCV general detection/matching framework details // Load images Mat imgA = imread(kResPath + "images/graf/img1.ppm", CV_LOAD_IMAGE_GRAYSCALE ); if( !imgA.data ) { std::cout<< " --(!) Error reading images " << std::endl; return -1; } Mat imgB = imread(kResPath + "images/graf/img3.ppm", CV_LOAD_IMAGE_GRAYSCALE ); if( !imgA.data ) { std::cout << " --(!) Error reading images " << std::endl; return -1; } std::vector<KeyPoint> keypointsA, keypointsB; Mat descriptorsA, descriptorsB; std::vector< DMatch> matches; // DETECTION // Any openCV detector such as SurfFeatureDetector detector(2000,4); // DESCRIPTOR // Our propose FREAK descriptor // (roation invariance, scale invariance, pattern radius corresponding to SMALLEST_KP_SIZE, number of octaves, file containing list of selected pairs) FreakDescriptorExtractor extractor(true,true,22,4, kResPath + "selected_pairs.bin"); // MATCHER // The standard Hamming distance can be used such as // BruteForceMatcher<Hamming> matcher; // or the proposed cascade of hamming distance #ifdef USE_SSE BruteForceMatcher< HammingSeg<30,4> > matcher; #else BruteForceMatcher<Hamming> matcher; #endif // detect double t = (double)getTickCount(); detector.detect( imgA, keypointsA ); detector.detect( imgB, keypointsB ); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "detection time [s]: " << t/1.0 << std::endl; // extract t = (double)getTickCount(); extractor.compute( imgA, keypointsA, descriptorsA ); extractor.compute( imgB, keypointsB, descriptorsB ); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "extraction time [s]: " << t << std::endl; // match t = (double)getTickCount(); matcher.match(descriptorsA, descriptorsB, matches); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "matching time [s]: " << t << std::endl; // Draw matches Mat imgMatch; drawMatches( imgA, keypointsA, imgB, keypointsB, matches, imgMatch); namedWindow("matches", CV_WINDOW_KEEPRATIO); imshow("matches", imgMatch); waitKey(0); ///////////////////////////////////////////////// // //PAIRS SELECTION //FREAK is available with a set of pairs learned off-line. Researchers can run a training process to learn their own set of pair. //For more details read section 4.2 in: //A. Alahi, R. Ortiz, and P. Vandergheynst. FREAK: Fast Retina Keypoint. In IEEE Conference on Computer Vision and Pattern Recognition, 2012. //We notice that for keypoint matching applications, image content has little effect on the selected pairs unless very specific //what does matter is the detector type (blobs, corners,...) and the options used (scale/rotation invariance,...) //reduce corrTresh if not enough pairs are selected (43 points --> 903 possible pairs) // Un-comment the following lines if you want to run the training process to learn the best pairs: /* std::vector<string> filenames; filenames.push_back(kResPath + "images/train/1.jpg"); filenames.push_back(kResPath + "images/train/2.jpg"); std::vector<Mat> images(filenames.size()); std::vector< std::vector<KeyPoint> > keypoints(filenames.size()); for( size_t i = 0; i < filenames.size(); ++i ) { images[i] = imread( filenames[i].c_str(), CV_LOAD_IMAGE_GRAYSCALE ); if( !images[i].data ) { std::cout<< " --(!) Error reading images " << std::endl; return -1; } detector.detect( images[i], keypoints[i] ); } extractor.selectPairs(images, keypoints, kResPath + "selected_pairs2", 0.7); */ } <commit_msg>fix whitespaces ..<commit_after>// demo.cpp // // Here is an example on how to use the descriptor presented in the following paper: // A. Alahi, R. Ortiz, and P. Vandergheynst. FREAK: Fast Retina Keypoint. In IEEE Conference on Computer Vision and Pattern Recognition, 2012. // // // Copyright (C) 2011-2012 Signal processing laboratory 2, EPFL, // Raphael Ortiz (raphael.ortiz@a3.epfl.ch), // Kirell Benzi (kirell.benzi@epfl.ch) // Alexandre Alahi (alexandre.alahi@epfl.ch) // and Pierre Vandergheynst (pierre.vandergheynst@epfl.ch) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. #include <iostream> #include <string> #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/nonfree/features2d.hpp> #include <opencv2/legacy/legacy.hpp> #include "freak.h" #include "hammingseg.h" using namespace cv; static const std::string kResPath = "../../resources/"; int main( int argc, char** argv ) { // check http://opencv.itseez.com/doc/tutorials/features2d/table_of_content_features2d/table_of_content_features2d.html // for OpenCV general detection/matching framework details // Load images Mat imgA = imread(kResPath + "images/graf/img1.ppm", CV_LOAD_IMAGE_GRAYSCALE ); if( !imgA.data ) { std::cout<< " --(!) Error reading images " << std::endl; return -1; } Mat imgB = imread(kResPath + "images/graf/img3.ppm", CV_LOAD_IMAGE_GRAYSCALE ); if( !imgA.data ) { std::cout << " --(!) Error reading images " << std::endl; return -1; } std::vector<KeyPoint> keypointsA, keypointsB; Mat descriptorsA, descriptorsB; std::vector< DMatch> matches; // DETECTION // Any openCV detector such as SurfFeatureDetector detector(2000,4); // DESCRIPTOR // Our propose FREAK descriptor // (roation invariance, scale invariance, pattern radius corresponding to SMALLEST_KP_SIZE, number of octaves, file containing list of selected pairs) FreakDescriptorExtractor extractor(true,true,22,4, kResPath + "selected_pairs.bin"); // MATCHER // The standard Hamming distance can be used such as // BruteForceMatcher<Hamming> matcher; // or the proposed cascade of hamming distance #ifdef USE_SSE BruteForceMatcher< HammingSeg<30,4> > matcher; #else BruteForceMatcher<Hamming> matcher; #endif // detect double t = (double)getTickCount(); detector.detect( imgA, keypointsA ); detector.detect( imgB, keypointsB ); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "detection time [s]: " << t/1.0 << std::endl; // extract t = (double)getTickCount(); extractor.compute( imgA, keypointsA, descriptorsA ); extractor.compute( imgB, keypointsB, descriptorsB ); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "extraction time [s]: " << t << std::endl; // match t = (double)getTickCount(); matcher.match(descriptorsA, descriptorsB, matches); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "matching time [s]: " << t << std::endl; // Draw matches Mat imgMatch; drawMatches( imgA, keypointsA, imgB, keypointsB, matches, imgMatch); namedWindow("matches", CV_WINDOW_KEEPRATIO); imshow("matches", imgMatch); waitKey(0); ///////////////////////////////////////////////// // //PAIRS SELECTION //FREAK is available with a set of pairs learned off-line. Researchers can run a training process to learn their own set of pair. //For more details read section 4.2 in: //A. Alahi, R. Ortiz, and P. Vandergheynst. FREAK: Fast Retina Keypoint. In IEEE Conference on Computer Vision and Pattern Recognition, 2012. //We notice that for keypoint matching applications, image content has little effect on the selected pairs unless very specific //what does matter is the detector type (blobs, corners,...) and the options used (scale/rotation invariance,...) //reduce corrTresh if not enough pairs are selected (43 points --> 903 possible pairs) // Un-comment the following lines if you want to run the training process to learn the best pairs: /* std::vector<string> filenames; filenames.push_back(kResPath + "images/train/1.jpg"); filenames.push_back(kResPath + "images/train/2.jpg"); std::vector<Mat> images(filenames.size()); std::vector< std::vector<KeyPoint> > keypoints(filenames.size()); for( size_t i = 0; i < filenames.size(); ++i ) { images[i] = imread( filenames[i].c_str(), CV_LOAD_IMAGE_GRAYSCALE ); if( !images[i].data ) { std::cout<< " --(!) Error reading images " << std::endl; return -1; } detector.detect( images[i], keypoints[i] ); } extractor.selectPairs(images, keypoints, kResPath + "selected_pairs2", 0.7); */ } <|endoftext|>
<commit_before>#include <stdexcept> #include "vtrc-stdint.h" #include "vtrc/common/sizepack-policy.h" #include "vtrc/common/data-queue.h" #include "vtrc/common/exception.h" namespace vtrc { namespace common { namespace data_queue { struct queue_base::impl { plain_data_type data_; std::deque<std::string> packed_; size_t max_valid_length_; impl( size_t max_valid_length ) :max_valid_length_(max_valid_length) { } void append( const char *data, size_t length ) { data_.insert( data_.end( ), data, data + length ); } size_t data_size( ) const { return data_.size( ); } size_t size( ) const { return packed_.size( ); } void grab_all( std::deque<std::string> &messages ) { std::deque<std::string> tmp; packed_.swap( tmp ); messages.swap( tmp ); } std::string &front( ) { return packed_.front( ); } void pop_front( ) { packed_.pop_front( ); } plain_data_type &plain_data( ) { return data_; } const plain_data_type &plain_data( ) const { return data_; } message_queue_type &messages( ) { return packed_; } const message_queue_type &messages( ) const { return packed_; } size_t get_maximum_length( ) const { return max_valid_length_; } void set_maximum_length(size_t new_value) { max_valid_length_ = new_value; } }; queue_base::queue_base( size_t max_valid_length ) :impl_(new impl(max_valid_length)) { } queue_base::~queue_base( ) { delete impl_; } void queue_base::append( const char *data, size_t length ) { impl_->append( data, length ); } plain_data_type &queue_base::plain_data( ) { return impl_->plain_data( ); } const plain_data_type &queue_base::plain_data( ) const { return impl_->plain_data( ); } message_queue_type &queue_base::messages( ) { return impl_->messages( ); } const message_queue_type &queue_base::messages( ) const { return impl_->messages( ); } size_t queue_base::get_maximum_length( ) const { return impl_->get_maximum_length( ); } void queue_base::set_maximum_length(size_t new_value) { impl_->set_maximum_length( new_value ); } namespace { template<typename SizePackPolicy> class serializer_impl: public queue_base { public: serializer_impl( size_t maximim_valid ) :queue_base(maximim_valid) { } std::string pack_size( size_t size ) const { return SizePackPolicy::pack( size ); } std::string *process_one( ) { process( ); return &messages( ).back( ); } void process( ) { typedef SizePackPolicy SSP; plain_data_type &data(plain_data( )); if( data.size( ) > get_maximum_length( ) ) { common::raise( std::length_error( "Message is too long" ) ); return; } std::string new_data( SSP::pack( data.size( ) ) ); new_data.insert( new_data.end( ), data.begin( ), data.end( )); messages( ).push_back( new_data ); data.clear( ); } }; template<typename SizePackPolicy> class parser_impl: public queue_base { public: parser_impl( size_t maximim_valid ) :queue_base(maximim_valid) { } std::string pack_size( size_t size ) const { return SizePackPolicy::pack( size ); } std::string *process_one( ) { std::string *result = VTRC_NULL; typedef SizePackPolicy SPP; plain_data_type &data(plain_data( )); size_t next(SPP::size_length(data.begin( ), data.end( ))); if( next > 0 ) { if( next > SPP::max_length ) { common::raise( std::length_error ( "The serialized data is invalid" ) ); return result; } size_t len = SPP::unpack(data.begin( ), data.end( )); if( len > get_maximum_length( ) ) { //std::cout << "Message is too long " << len << "\n"; common::raise( std::length_error( "Message is too long" ) ); return result; } if( (len + next) <= data.size( ) ) { plain_data_type::iterator b( data.begin( ) ); plain_data_type::iterator n( b ); plain_data_type::iterator e( b ); std::advance( n, next ); std::advance( e, len + next ); std::string mess( n, e ); messages( ).push_back( mess ); result = &messages( ).back( ); data.erase( b, e ); } } return result; } void process( ) { while( process_one( ) ); } }; } namespace varint { typedef vtrc::common::policies::varint_policy<uint32_t> policy_type; queue_base *create_parser( size_t max_valid_length ) { return new parser_impl<policy_type>(max_valid_length); } queue_base *create_serializer( size_t max_valid_length ) { return new serializer_impl<policy_type>(max_valid_length); } std::string pack_size(size_t size) { return policy_type::pack( size ); } size_t pack_size_to( size_t size, void *result ) { return policy_type::pack( size, result ); } } namespace fixint { typedef vtrc::common::policies::fixint_policy<uint32_t> policy_type; queue_base *create_parser( size_t max_valid_length ) { return new parser_impl<policy_type>(max_valid_length); } queue_base *create_serializer( size_t max_valid_length ) { return new serializer_impl<policy_type>(max_valid_length); } std::string pack_size(size_t size) { return policy_type::pack( size ); } size_t pack_size_to( size_t size, void *result ) { return policy_type::pack( size, result ); } } }}} <commit_msg>REFACTOR<commit_after>#include <stdexcept> #include "vtrc-stdint.h" #include "vtrc/common/sizepack-policy.h" #include "vtrc/common/data-queue.h" #include "vtrc/common/exception.h" namespace vtrc { namespace common { namespace data_queue { struct queue_base::impl { plain_data_type data_; std::deque<std::string> packed_; size_t max_valid_length_; impl( size_t max_valid_length ) :max_valid_length_(max_valid_length) { } void append( const char *data, size_t length ) { data_.insert( data_.end( ), data, data + length ); } size_t data_size( ) const { return data_.size( ); } size_t size( ) const { return packed_.size( ); } void grab_all( std::deque<std::string> &messages ) { std::deque<std::string> tmp; packed_.swap( tmp ); messages.swap( tmp ); } std::string &front( ) { return packed_.front( ); } void pop_front( ) { packed_.pop_front( ); } plain_data_type &plain_data( ) { return data_; } const plain_data_type &plain_data( ) const { return data_; } message_queue_type &messages( ) { return packed_; } const message_queue_type &messages( ) const { return packed_; } size_t get_maximum_length( ) const { return max_valid_length_; } void set_maximum_length(size_t new_value) { max_valid_length_ = new_value; } }; queue_base::queue_base( size_t max_valid_length ) :impl_(new impl(max_valid_length)) { } queue_base::~queue_base( ) { delete impl_; } void queue_base::append( const char *data, size_t length ) { impl_->append( data, length ); } plain_data_type &queue_base::plain_data( ) { return impl_->plain_data( ); } const plain_data_type &queue_base::plain_data( ) const { return impl_->plain_data( ); } message_queue_type &queue_base::messages( ) { return impl_->messages( ); } const message_queue_type &queue_base::messages( ) const { return impl_->messages( ); } size_t queue_base::get_maximum_length( ) const { return impl_->get_maximum_length( ); } void queue_base::set_maximum_length(size_t new_value) { impl_->set_maximum_length( new_value ); } namespace { template<typename SizePackPolicy> class serializer_impl: public queue_base { public: serializer_impl( size_t maximim_valid ) :queue_base(maximim_valid) { } std::string pack_size( size_t size ) const { return SizePackPolicy::pack( size ); } std::string *process_one( ) { process( ); return &messages( ).back( ); } void process( ) { typedef SizePackPolicy SSP; plain_data_type &data(plain_data( )); if( data.size( ) > get_maximum_length( ) ) { common::raise( std::length_error( "Message is too long" ) ); return; } std::string new_data( SSP::pack( data.size( ) ) ); new_data.insert( new_data.end( ), data.begin( ), data.end( )); messages( ).push_back( new_data ); data.clear( ); } }; template<typename SizePackPolicy> class parser_impl: public queue_base { public: parser_impl( size_t maximim_valid ) :queue_base(maximim_valid) { } std::string pack_size( size_t size ) const { return SizePackPolicy::pack( size ); } std::string *process_one( ) { std::string *result = VTRC_NULL; typedef SizePackPolicy SPP; plain_data_type &data(plain_data( )); size_t next(SPP::size_length(data.begin( ), data.end( ))); if( next > 0 ) { if( next > SPP::max_length ) { common::raise( std::length_error ( "The serialized data is invalid" ) ); return result; } size_t len = SPP::unpack(data.begin( ), data.end( )); if( len > get_maximum_length( ) ) { //std::cout << "Message is too long " << len << "\n"; common::raise( std::length_error( "Message is too long" ) ); return result; } if( (len + next) <= data.size( ) ) { plain_data_type::iterator b( data.begin( ) ); plain_data_type::iterator n( b ); plain_data_type::iterator e( b ); std::advance( n, next ); std::advance( e, len + next ); std::string mess( n, e ); messages( ).push_back( mess ); result = &messages( ).back( ); data.erase( b, e ); } } return result; } void process( ) { while( process_one( ) ); } }; } namespace varint { typedef vtrc::common::policies::varint_policy<size_t> policy_type; queue_base *create_parser( size_t max_valid_length ) { return new parser_impl<policy_type>(max_valid_length); } queue_base *create_serializer( size_t max_valid_length ) { return new serializer_impl<policy_type>(max_valid_length); } std::string pack_size(size_t size) { return policy_type::pack( size ); } size_t pack_size_to( size_t size, void *result ) { return policy_type::pack( size, result ); } } namespace fixint { typedef vtrc::common::policies::fixint_policy<size_t> policy_type; queue_base *create_parser( size_t max_valid_length ) { return new parser_impl<policy_type>(max_valid_length); } queue_base *create_serializer( size_t max_valid_length ) { return new serializer_impl<policy_type>(max_valid_length); } std::string pack_size(size_t size) { return policy_type::pack( size ); } size_t pack_size_to( size_t size, void *result ) { return policy_type::pack( size, result ); } } }}} <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sigcache.h" #include "memusage.h" #include "pubkey.h" #include "random.h" #include "uint256.h" #include "util.h" #include "cuckoocache.h" #include <boost/thread.hpp> namespace { /** * We're hashing a nonce into the entries themselves, so we don't need extra * blinding in the set hash computation. * * This may exhibit platform endian dependent behavior but because these are * nonced hashes (random) and this state is only ever used locally it is safe. * All that matters is local consistency. */ class SignatureCacheHasher { public: template <uint8_t hash_select> uint32_t operator()(const uint256& key) const { static_assert(hash_select <8, "SignatureCacheHasher only has 8 hashes available."); uint32_t u; std::memcpy(&u, key.begin()+4*hash_select, 4); return u; } }; /** * Valid signature cache, to avoid doing expensive ECDSA signature checking * twice for every transaction (once when accepted into memory pool, and * again when accepted into the block chain) */ class CSignatureCache { private: //! Entries are SHA256(nonce || signature hash || public key || signature || additional commit || CScript). They are used in various ways for different checks uint256 nonce; typedef CuckooCache::cache<uint256, SignatureCacheHasher> map_type; map_type setValid; boost::shared_mutex cs_sigcache; public: CSignatureCache() { GetRandBytes(nonce.begin(), 32); } void ComputeEntry(uint256& entry, const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const std::vector<unsigned char>& vchCommitment, const CScript& scriptPubKey) { CSHA256().Write(nonce.begin(), 32).Write(hash.begin(), 32).Write(&pubkey[0], pubkey.size()).Write(&vchSig[0], vchSig.size()).Write(&vchCommitment[0], vchCommitment.size()).Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(entry.begin()); } bool Get(const uint256& entry, const bool erase) { boost::shared_lock<boost::shared_mutex> lock(cs_sigcache); return setValid.contains(entry, erase); } void Set(uint256& entry) { boost::unique_lock<boost::shared_mutex> lock(cs_sigcache); setValid.insert(entry); } uint32_t setup_bytes(size_t n) { return setValid.setup_bytes(n); } }; /* In previous versions of this code, signatureCache was a local static variable * in CachingTransactionSignatureChecker::VerifySignature. We initialize * signatureCache outside of VerifySignature to avoid the atomic operation per * call overhead associated with local static variables even though * signatureCache could be made local to VerifySignature. */ static CSignatureCache signatureCache; static CSignatureCache rangeProofCache; static CSignatureCache surjectionProofCache; } // To be called once in AppInit2/TestingSetup to initialize the signatureCache void InitSignatureCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = signatureCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for signature cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } // To be called once in AppInit2/TestingSetup to initialize the rangeproof cache void InitRangeproofCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = rangeProofCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for rangeproof cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } // To be called once in AppInit2/TestingSetup to initialize the surjectionrproof cache void InitSurjectionproofCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = surjectionProofCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for surjectionproof cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } bool CachingTransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const { uint256 entry; signatureCache.ComputeEntry(entry, sighash, vchSig, pubkey, vchSig, CScript()); if (signatureCache.Get(entry, !store)) return true; if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash)) return false; if (store) signatureCache.Set(entry); return true; } bool CachingRangeProofChecker::VerifyRangeProof(const std::vector<unsigned char>& vchRangeProof, const std::vector<unsigned char>& vchValueCommitment, const std::vector<unsigned char>& vchAssetCommitment, const CScript& scriptPubKey, const secp256k1_context* secp256k1_ctx_verify_amounts) const { CPubKey pubkey(vchValueCommitment); uint256 entry; rangeProofCache.ComputeEntry(entry, uint256(), vchRangeProof, pubkey, vchAssetCommitment, scriptPubKey); if (rangeProofCache.Get(entry, !store)) { return true; } if (vchRangeProof.size() == 0) { return false; } uint64_t min_value, max_value; secp256k1_pedersen_commitment commit; if (secp256k1_pedersen_commitment_parse(secp256k1_ctx_verify_amounts, &commit, &vchValueCommitment[0]) != 1) return false; secp256k1_generator tag; if (secp256k1_generator_parse(secp256k1_ctx_verify_amounts, &tag, &vchAssetCommitment[0]) != 1) return false; if (!secp256k1_rangeproof_verify(secp256k1_ctx_verify_amounts, &min_value, &max_value, &commit, vchRangeProof.data(), vchRangeProof.size(), scriptPubKey.size() ? &scriptPubKey.front() : NULL, scriptPubKey.size(), &tag)) { return false; } // An rangeproof is not valid if the output is spendable but the minimum number // is 0. This is to prevent people passing 0-value tokens around, or conjuring // reissuance tokens from nothing then attempting to reissue an asset. // ie reissuance doesn't require revealing value of reissuance output // Issuances proofs are always "unspendable" as they commit to an empty script. if (min_value == 0 && !scriptPubKey.IsUnspendable()) { return false; } return true; } bool CachingSurjectionProofChecker::VerifySurjectionProof(secp256k1_surjectionproof& proof, std::vector<secp256k1_generator>& vTags, secp256k1_generator& gen, const secp256k1_context* secp256k1_ctx_verify_amounts) const { // Serialize objects std::vector<unsigned char> vchproof; size_t proof_len = 0; vchproof.resize(secp256k1_surjectionproof_serialized_size(secp256k1_ctx_verify_amounts, &proof)); secp256k1_surjectionproof_serialize(secp256k1_ctx_verify_amounts, &vchproof[0], &proof_len, &proof); std::vector<unsigned char> tagCommit; tagCommit.resize(33); CSHA256 sha2; for (unsigned int i = 0; i <vTags.size(); i++) { secp256k1_generator_serialize(secp256k1_ctx_verify_amounts, tagCommit.data(), &vTags[i]); sha2.Write(tagCommit.data(), tagCommit.size()); } tagCommit.resize(32); sha2.Finalize(tagCommit.data()); std::vector<unsigned char> vchGen; vchGen.resize(CConfidentialValue::nCommittedSize); secp256k1_generator_serialize(secp256k1_ctx_verify_amounts, &vchGen[0], &gen); CPubKey pubkey(vchGen); uint256 entry; surjectionProofCache.ComputeEntry(entry, uint256(tagCommit), vchproof, pubkey, vchGen, CScript()); if (surjectionProofCache.Get(entry, !store)) { return true; } if (secp256k1_surjectionproof_verify(secp256k1_ctx_verify_amounts, &proof, vTags.data(), vTags.size(), &gen) != 1) { return false; } return true; } <commit_msg>Actually cache range and surjection proofs<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sigcache.h" #include "memusage.h" #include "pubkey.h" #include "random.h" #include "uint256.h" #include "util.h" #include "cuckoocache.h" #include <boost/thread.hpp> namespace { /** * We're hashing a nonce into the entries themselves, so we don't need extra * blinding in the set hash computation. * * This may exhibit platform endian dependent behavior but because these are * nonced hashes (random) and this state is only ever used locally it is safe. * All that matters is local consistency. */ class SignatureCacheHasher { public: template <uint8_t hash_select> uint32_t operator()(const uint256& key) const { static_assert(hash_select <8, "SignatureCacheHasher only has 8 hashes available."); uint32_t u; std::memcpy(&u, key.begin()+4*hash_select, 4); return u; } }; /** * Valid signature cache, to avoid doing expensive ECDSA signature checking * twice for every transaction (once when accepted into memory pool, and * again when accepted into the block chain) */ class CSignatureCache { private: //! Entries are SHA256(nonce || signature hash || public key || signature || additional commit || CScript). They are used in various ways for different checks uint256 nonce; typedef CuckooCache::cache<uint256, SignatureCacheHasher> map_type; map_type setValid; boost::shared_mutex cs_sigcache; public: CSignatureCache() { GetRandBytes(nonce.begin(), 32); } void ComputeEntry(uint256& entry, const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const std::vector<unsigned char>& vchCommitment, const CScript& scriptPubKey) { CSHA256().Write(nonce.begin(), 32).Write(hash.begin(), 32).Write(&pubkey[0], pubkey.size()).Write(&vchSig[0], vchSig.size()).Write(&vchCommitment[0], vchCommitment.size()).Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(entry.begin()); } bool Get(const uint256& entry, const bool erase) { boost::shared_lock<boost::shared_mutex> lock(cs_sigcache); return setValid.contains(entry, erase); } void Set(uint256& entry) { boost::unique_lock<boost::shared_mutex> lock(cs_sigcache); setValid.insert(entry); } uint32_t setup_bytes(size_t n) { return setValid.setup_bytes(n); } }; /* In previous versions of this code, signatureCache was a local static variable * in CachingTransactionSignatureChecker::VerifySignature. We initialize * signatureCache outside of VerifySignature to avoid the atomic operation per * call overhead associated with local static variables even though * signatureCache could be made local to VerifySignature. */ static CSignatureCache signatureCache; static CSignatureCache rangeProofCache; static CSignatureCache surjectionProofCache; } // To be called once in AppInit2/TestingSetup to initialize the signatureCache void InitSignatureCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = signatureCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for signature cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } // To be called once in AppInit2/TestingSetup to initialize the rangeproof cache void InitRangeproofCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = rangeProofCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for rangeproof cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } // To be called once in AppInit2/TestingSetup to initialize the surjectionrproof cache void InitSurjectionproofCache() { // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero, // setup_bytes creates the minimum possible cache (2 elements). size_t nMaxCacheSize = std::min(std::max((int64_t)0, GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE)), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20); size_t nElems = surjectionProofCache.setup_bytes(nMaxCacheSize); LogPrintf("Using %zu MiB out of %zu requested for surjectionproof cache, able to store %zu elements\n", (nElems*sizeof(uint256)) >>20, nMaxCacheSize>>20, nElems); } bool CachingTransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const { uint256 entry; signatureCache.ComputeEntry(entry, sighash, vchSig, pubkey, vchSig, CScript()); if (signatureCache.Get(entry, !store)) return true; if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash)) return false; if (store) signatureCache.Set(entry); return true; } bool CachingRangeProofChecker::VerifyRangeProof(const std::vector<unsigned char>& vchRangeProof, const std::vector<unsigned char>& vchValueCommitment, const std::vector<unsigned char>& vchAssetCommitment, const CScript& scriptPubKey, const secp256k1_context* secp256k1_ctx_verify_amounts) const { CPubKey pubkey(vchValueCommitment); uint256 entry; rangeProofCache.ComputeEntry(entry, uint256(), vchRangeProof, pubkey, vchAssetCommitment, scriptPubKey); if (rangeProofCache.Get(entry, !store)) { return true; } if (vchRangeProof.size() == 0) { return false; } uint64_t min_value, max_value; secp256k1_pedersen_commitment commit; if (secp256k1_pedersen_commitment_parse(secp256k1_ctx_verify_amounts, &commit, &vchValueCommitment[0]) != 1) return false; secp256k1_generator tag; if (secp256k1_generator_parse(secp256k1_ctx_verify_amounts, &tag, &vchAssetCommitment[0]) != 1) return false; if (!secp256k1_rangeproof_verify(secp256k1_ctx_verify_amounts, &min_value, &max_value, &commit, vchRangeProof.data(), vchRangeProof.size(), scriptPubKey.size() ? &scriptPubKey.front() : NULL, scriptPubKey.size(), &tag)) { return false; } // An rangeproof is not valid if the output is spendable but the minimum number // is 0. This is to prevent people passing 0-value tokens around, or conjuring // reissuance tokens from nothing then attempting to reissue an asset. // ie reissuance doesn't require revealing value of reissuance output // Issuances proofs are always "unspendable" as they commit to an empty script. if (min_value == 0 && !scriptPubKey.IsUnspendable()) { return false; } if (store) { rangeProofCache.Set(entry); } return true; } bool CachingSurjectionProofChecker::VerifySurjectionProof(secp256k1_surjectionproof& proof, std::vector<secp256k1_generator>& vTags, secp256k1_generator& gen, const secp256k1_context* secp256k1_ctx_verify_amounts) const { // Serialize objects std::vector<unsigned char> vchproof; size_t proof_len = 0; vchproof.resize(secp256k1_surjectionproof_serialized_size(secp256k1_ctx_verify_amounts, &proof)); secp256k1_surjectionproof_serialize(secp256k1_ctx_verify_amounts, &vchproof[0], &proof_len, &proof); std::vector<unsigned char> tagCommit; tagCommit.resize(33); CSHA256 sha2; for (unsigned int i = 0; i <vTags.size(); i++) { secp256k1_generator_serialize(secp256k1_ctx_verify_amounts, tagCommit.data(), &vTags[i]); sha2.Write(tagCommit.data(), tagCommit.size()); } tagCommit.resize(32); sha2.Finalize(tagCommit.data()); std::vector<unsigned char> vchGen; vchGen.resize(CConfidentialValue::nCommittedSize); secp256k1_generator_serialize(secp256k1_ctx_verify_amounts, &vchGen[0], &gen); CPubKey pubkey(vchGen); uint256 entry; surjectionProofCache.ComputeEntry(entry, uint256(tagCommit), vchproof, pubkey, vchGen, CScript()); if (surjectionProofCache.Get(entry, !store)) { return true; } if (secp256k1_surjectionproof_verify(secp256k1_ctx_verify_amounts, &proof, vTags.data(), vTags.size(), &gen) != 1) { return false; } if (store) { surjectionProofCache.Set(entry); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "script/sign.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; typedef vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_CONTRIBUTION: return "cfund_contribution"; case TX_PROPOSALYESVOTE: return "proposal_yes_vote"; case TX_PAYMENTREQUESTYESVOTE: return "payment_request_yes_vote"; case TX_PROPOSALNOVOTE: return "proposal_no_vote"; case TX_PAYMENTREQUESTNOVOTE: return "payment_request_no_vote"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; } return NULL; } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet) { // Templates static multimap<txnouttype, CScript> mTemplates; if (mTemplates.empty()) { // Standard tx, sender provides pubkey, receiver adds signature mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG)); // NavCoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG)); // Sender provides N pubkeys, receivers provides M signatures mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG)); } vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Shortcut for cold stake, so we don't need to match a template if (scriptPubKey.IsColdStaking()) { typeRet = TX_COLDSTAKING; vector<unsigned char> stakingPubKey(scriptPubKey.begin()+4, scriptPubKey.begin()+24); vSolutionsRet.push_back(stakingPubKey); vector<unsigned char> spendingPubKey(scriptPubKey.begin()+30, scriptPubKey.begin()+50); vSolutionsRet.push_back(spendingPubKey); return true; } if (scriptPubKey.IsCommunityFundContribution()) { typeRet = TX_CONTRIBUTION; return true; } if(scriptPubKey.IsProposalVoteYes()) { typeRet = TX_PROPOSALYESVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsProposalVoteNo()) { typeRet = TX_PROPOSALNOVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsPaymentRequestVoteYes()) { typeRet = TX_PAYMENTREQUESTYESVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsPaymentRequestVoteNo()) { typeRet = TX_PAYMENTREQUESTNOVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == 20) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == 32) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } return false; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } // Scan templates const CScript& script1 = scriptPubKey; BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates) { const CScript& script2 = tplate.second; vSolutionsRet.clear(); opcodetype opcode1, opcode2; vector<unsigned char> vch1, vch2; // Compare CScript::const_iterator pc1 = script1.begin(); CScript::const_iterator pc2 = script2.begin(); while (true) { if (pc1 == script1.end() && pc2 == script2.end()) { // Found a match typeRet = tplate.first; if (typeRet == TX_MULTISIG) { // Additional checks for TX_MULTISIG: unsigned char m = vSolutionsRet.front()[0]; unsigned char n = vSolutionsRet.back()[0]; if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n) return false; } return true; } if (!script1.GetOp(pc1, opcode1, vch1)) break; if (!script2.GetOp(pc2, opcode2, vch2)) break; // Template matching opcodes: if (opcode2 == OP_PUBKEYS) { while (vch1.size() >= 33 && vch1.size() <= 65) { vSolutionsRet.push_back(vch1); if (!script1.GetOp(pc1, opcode1, vch1)) break; } if (!script2.GetOp(pc2, opcode2, vch2)) break; // Normal situation is to fall through // to other if/else statements } if (opcode2 == OP_PUBKEY) { if (vch1.size() < 33 || vch1.size() > 65) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_PUBKEYHASH) { if (vch1.size() != sizeof(uint160)) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_SMALLINTEGER) { // Single-byte small integer pushed onto vSolutions if (opcode1 == OP_0 || (opcode1 >= OP_1 && opcode1 <= OP_16)) { char n = (char)CScript::DecodeOP_N(opcode1); vSolutionsRet.push_back(valtype(1, n)); } else break; } else if (opcode1 != opcode2 || vch1 != vch2) { // Others must match exactly break; } } } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_CONTRIBUTION || typeRet == TX_PAYMENTREQUESTNOVOTE || typeRet == TX_PAYMENTREQUESTYESVOTE || typeRet == TX_PROPOSALNOVOTE || typeRet == TX_PROPOSALYESVOTE) { return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); BOOST_FOREACH(const CPubKey& key, keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { unsigned char h160[20]; CHash160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160); ret << OP_0 << std::vector<unsigned char>(&h160[0], &h160[20]); return ret; } else if (typ == TX_PUBKEYHASH) { ret << OP_0 << vSolutions[0]; return ret; } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); ret << OP_0 << ToByteVector(hash); return ret; } <commit_msg>stringify tx output<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "script/sign.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; typedef vector<unsigned char> valtype; bool fAcceptDatacarrier = DEFAULT_ACCEPT_DATACARRIER; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_NULL_DATA: return "nulldata"; case TX_CONTRIBUTION: return "cfund_contribution"; case TX_PROPOSALYESVOTE: return "proposal_yes_vote"; case TX_PAYMENTREQUESTYESVOTE: return "payment_request_yes_vote"; case TX_PROPOSALNOVOTE: return "proposal_no_vote"; case TX_PAYMENTREQUESTNOVOTE: return "payment_request_no_vote"; case TX_WITNESS_V0_KEYHASH: return "witness_v0_keyhash"; case TX_WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash"; case TX_COLDSTAKING: return "cold_staking"; } return NULL; } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet) { // Templates static multimap<txnouttype, CScript> mTemplates; if (mTemplates.empty()) { // Standard tx, sender provides pubkey, receiver adds signature mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG)); // NavCoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG)); // Sender provides N pubkeys, receivers provides M signatures mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG)); } vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Shortcut for cold stake, so we don't need to match a template if (scriptPubKey.IsColdStaking()) { typeRet = TX_COLDSTAKING; vector<unsigned char> stakingPubKey(scriptPubKey.begin()+4, scriptPubKey.begin()+24); vSolutionsRet.push_back(stakingPubKey); vector<unsigned char> spendingPubKey(scriptPubKey.begin()+30, scriptPubKey.begin()+50); vSolutionsRet.push_back(spendingPubKey); return true; } if (scriptPubKey.IsCommunityFundContribution()) { typeRet = TX_CONTRIBUTION; return true; } if(scriptPubKey.IsProposalVoteYes()) { typeRet = TX_PROPOSALYESVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsProposalVoteNo()) { typeRet = TX_PROPOSALNOVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsPaymentRequestVoteYes()) { typeRet = TX_PAYMENTREQUESTYESVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } if(scriptPubKey.IsPaymentRequestVoteNo()) { typeRet = TX_PAYMENTREQUESTNOVOTE; vector<unsigned char> hashBytes(scriptPubKey.begin()+4, scriptPubKey.begin()+36); vSolutionsRet.push_back(hashBytes); return true; } int witnessversion; std::vector<unsigned char> witnessprogram; if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) { if (witnessversion == 0 && witnessprogram.size() == 20) { typeRet = TX_WITNESS_V0_KEYHASH; vSolutionsRet.push_back(witnessprogram); return true; } if (witnessversion == 0 && witnessprogram.size() == 32) { typeRet = TX_WITNESS_V0_SCRIPTHASH; vSolutionsRet.push_back(witnessprogram); return true; } return false; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } // Scan templates const CScript& script1 = scriptPubKey; BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates) { const CScript& script2 = tplate.second; vSolutionsRet.clear(); opcodetype opcode1, opcode2; vector<unsigned char> vch1, vch2; // Compare CScript::const_iterator pc1 = script1.begin(); CScript::const_iterator pc2 = script2.begin(); while (true) { if (pc1 == script1.end() && pc2 == script2.end()) { // Found a match typeRet = tplate.first; if (typeRet == TX_MULTISIG) { // Additional checks for TX_MULTISIG: unsigned char m = vSolutionsRet.front()[0]; unsigned char n = vSolutionsRet.back()[0]; if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n) return false; } return true; } if (!script1.GetOp(pc1, opcode1, vch1)) break; if (!script2.GetOp(pc2, opcode2, vch2)) break; // Template matching opcodes: if (opcode2 == OP_PUBKEYS) { while (vch1.size() >= 33 && vch1.size() <= 65) { vSolutionsRet.push_back(vch1); if (!script1.GetOp(pc1, opcode1, vch1)) break; } if (!script2.GetOp(pc2, opcode2, vch2)) break; // Normal situation is to fall through // to other if/else statements } if (opcode2 == OP_PUBKEY) { if (vch1.size() < 33 || vch1.size() > 65) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_PUBKEYHASH) { if (vch1.size() != sizeof(uint160)) break; vSolutionsRet.push_back(vch1); } else if (opcode2 == OP_SMALLINTEGER) { // Single-byte small integer pushed onto vSolutions if (opcode1 == OP_0 || (opcode1 >= OP_1 && opcode1 <= OP_16)) { char n = (char)CScript::DecodeOP_N(opcode1); vSolutionsRet.push_back(valtype(1, n)); } else break; } else if (opcode1 != opcode2 || vch1 != vch2) { // Others must match exactly break; } } } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_CONTRIBUTION || typeRet == TX_PAYMENTREQUESTNOVOTE || typeRet == TX_PAYMENTREQUESTYESVOTE || typeRet == TX_PROPOSALNOVOTE || typeRet == TX_PROPOSALYESVOTE) { return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); BOOST_FOREACH(const CPubKey& key, keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { unsigned char h160[20]; CHash160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160); ret << OP_0 << std::vector<unsigned char>(&h160[0], &h160[20]); return ret; } else if (typ == TX_PUBKEYHASH) { ret << OP_0 << vSolutions[0]; return ret; } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); ret << OP_0 << ToByteVector(hash); return ret; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" typedef std::vector<unsigned char> valtype; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_COLDSTAKE: return "coldstake"; case TX_NULL_DATA: return "nulldata"; case TX_ZEROCOINMINT: return "zerocoinmint"; } return NULL; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } static bool MatchPayToColdStaking(const CScript& script, valtype& stakerPubKeyHash, valtype& ownerPubKeyHash) { if (script.IsPayToColdStaking()) { stakerPubKeyHash = valtype(script.begin () + 6, script.begin() + 26); ownerPubKeyHash = valtype(script.begin () + 28, script.begin() + 48); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Zerocoin if (scriptPubKey.IsZerocoinMint()) { typeRet = TX_ZEROCOINMINT; if(scriptPubKey.size() > 150) return false; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); vSolutionsRet.push_back(hashBytes); return true; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } std::vector<unsigned char> data1; if (MatchPayToColdStaking(scriptPubKey, data, data1)) { typeRet = TX_COLDSTAKE; vSolutionsRet.push_back(std::move(data)); vSolutionsRet.push_back(std::move(data1)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions) { switch (t) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: return -1; case TX_PUBKEY: return 1; case TX_PUBKEYHASH: return 2; case TX_COLDSTAKE: return 3; case TX_MULTISIG: if (vSolutions.size() < 1 || vSolutions[0].size() < 1) return -1; return vSolutions[0][0] + 1; case TX_SCRIPTHASH: return 1; // doesn't include args needed by the script } return -1; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet, bool fColdStake) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_COLDSTAKE) { addressRet = CKeyID(uint160(vSolutions[!fColdStake])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_COLDSTAKE) { if (vSolutions.size() < 2) return false; nRequiredRet = 2; addressRet.emplace_back(uint160(vSolutions[0])); addressRet.emplace_back(uint160(vSolutions[1])); return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForStakeDelegation(const CKeyID& stakingKey, const CKeyID& spendingKey) { CScript script; script << OP_DUP << OP_HASH160 << OP_ROT << OP_IF << OP_CHECKCOLDSTAKEVERIFY << ToByteVector(stakingKey) << OP_ELSE << ToByteVector(spendingKey) << OP_ENDIF << OP_EQUALVERIFY << OP_CHECKSIG; return script; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <commit_msg>[BUG] Fix regression with emplace_back on cold-staking scripts<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/standard.h" #include "pubkey.h" #include "script/script.h" #include "util.h" #include "utilstrencodings.h" typedef std::vector<unsigned char> valtype; unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY; CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {} const char* GetTxnOutputType(txnouttype t) { switch (t) { case TX_NONSTANDARD: return "nonstandard"; case TX_PUBKEY: return "pubkey"; case TX_PUBKEYHASH: return "pubkeyhash"; case TX_SCRIPTHASH: return "scripthash"; case TX_MULTISIG: return "multisig"; case TX_COLDSTAKE: return "coldstake"; case TX_NULL_DATA: return "nulldata"; case TX_ZEROCOINMINT: return "zerocoinmint"; } return NULL; } static bool MatchPayToPubkey(const CScript& script, valtype& pubkey) { if (script.size() == CPubKey::PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } if (script.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 2 && script[0] == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE && script.back() == OP_CHECKSIG) { pubkey = valtype(script.begin() + 1, script.begin() + CPubKey::COMPRESSED_PUBLIC_KEY_SIZE + 1); return CPubKey::ValidSize(pubkey); } return false; } static bool MatchPayToPubkeyHash(const CScript& script, valtype& pubkeyhash) { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { pubkeyhash = valtype(script.begin () + 3, script.begin() + 23); return true; } return false; } static bool MatchPayToColdStaking(const CScript& script, valtype& stakerPubKeyHash, valtype& ownerPubKeyHash) { if (script.IsPayToColdStaking()) { stakerPubKeyHash = valtype(script.begin () + 6, script.begin() + 26); ownerPubKeyHash = valtype(script.begin () + 28, script.begin() + 48); return true; } return false; } /** Test for "small positive integer" script opcodes - OP_1 through OP_16. */ static constexpr bool IsSmallInteger(opcodetype opcode) { return opcode >= OP_1 && opcode <= OP_16; } static bool MatchMultisig(const CScript& script, unsigned int& required, std::vector<valtype>& pubkeys) { opcodetype opcode; valtype data; CScript::const_iterator it = script.begin(); if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false; if (!script.GetOp(it, opcode, data) || !IsSmallInteger(opcode)) return false; required = CScript::DecodeOP_N(opcode); while (script.GetOp(it, opcode, data) && CPubKey::ValidSize(data)) { pubkeys.emplace_back(std::move(data)); } if (!IsSmallInteger(opcode)) return false; unsigned int keys = CScript::DecodeOP_N(opcode); if (pubkeys.size() != keys || keys < required) return false; return (it + 1 == script.end()); } /** * Return public keys or hashes from scriptPubKey, for 'standard' transaction types. */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet) { vSolutionsRet.clear(); // Shortcut for pay-to-script-hash, which are more constrained than the other types: // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL if (scriptPubKey.IsPayToScriptHash()) { typeRet = TX_SCRIPTHASH; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22); vSolutionsRet.push_back(hashBytes); return true; } // Zerocoin if (scriptPubKey.IsZerocoinMint()) { typeRet = TX_ZEROCOINMINT; if(scriptPubKey.size() > 150) return false; std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.end()); vSolutionsRet.push_back(hashBytes); return true; } // Provably prunable, data-carrying output // // So long as script passes the IsUnspendable() test and all but the first // byte passes the IsPushOnly() test we don't care what exactly is in the // script. if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) { typeRet = TX_NULL_DATA; return true; } std::vector<unsigned char> data; if (MatchPayToPubkey(scriptPubKey, data)) { typeRet = TX_PUBKEY; vSolutionsRet.push_back(std::move(data)); return true; } if (MatchPayToPubkeyHash(scriptPubKey, data)) { typeRet = TX_PUBKEYHASH; vSolutionsRet.push_back(std::move(data)); return true; } std::vector<unsigned char> data1; if (MatchPayToColdStaking(scriptPubKey, data, data1)) { typeRet = TX_COLDSTAKE; vSolutionsRet.push_back(std::move(data)); vSolutionsRet.push_back(std::move(data1)); return true; } unsigned int required; std::vector<std::vector<unsigned char>> keys; if (MatchMultisig(scriptPubKey, required, keys)) { typeRet = TX_MULTISIG; vSolutionsRet.push_back({static_cast<unsigned char>(required)}); // safe as required is in range 1..16 vSolutionsRet.insert(vSolutionsRet.end(), keys.begin(), keys.end()); vSolutionsRet.push_back({static_cast<unsigned char>(keys.size())}); // safe as size is in range 1..16 return true; } vSolutionsRet.clear(); typeRet = TX_NONSTANDARD; return false; } int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions) { switch (t) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_ZEROCOINMINT: return -1; case TX_PUBKEY: return 1; case TX_PUBKEYHASH: return 2; case TX_COLDSTAKE: return 3; case TX_MULTISIG: if (vSolutions.size() < 1 || vSolutions[0].size() < 1) return -1; return vSolutions[0][0] + 1; case TX_SCRIPTHASH: return 1; // doesn't include args needed by the script } return -1; } bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet, bool fColdStake) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_COLDSTAKE) { addressRet = CKeyID(uint160(vSolutions[!fColdStake])); return true; } // Multisig txns have more than one address... return false; } bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else if (typeRet == TX_COLDSTAKE) { if (vSolutions.size() < 2) return false; nRequiredRet = 2; addressRet.push_back(CKeyID(uint160(vSolutions[0]))); addressRet.push_back(CKeyID(uint160(vSolutions[1]))); return true; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; } namespace { class CScriptVisitor : public boost::static_visitor<bool> { private: CScript *script; public: CScriptVisitor(CScript *scriptin) { script = scriptin; } bool operator()(const CNoDestination &dest) const { script->clear(); return false; } bool operator()(const CKeyID &keyID) const { script->clear(); *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; return true; } bool operator()(const CScriptID &scriptID) const { script->clear(); *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL; return true; } }; } CScript GetScriptForDestination(const CTxDestination& dest) { CScript script; boost::apply_visitor(CScriptVisitor(&script), dest); return script; } CScript GetScriptForRawPubKey(const CPubKey& pubKey) { return CScript() << std::vector<unsigned char>(pubKey.begin(), pubKey.end()) << OP_CHECKSIG; } CScript GetScriptForStakeDelegation(const CKeyID& stakingKey, const CKeyID& spendingKey) { CScript script; script << OP_DUP << OP_HASH160 << OP_ROT << OP_IF << OP_CHECKCOLDSTAKEVERIFY << ToByteVector(stakingKey) << OP_ELSE << ToByteVector(spendingKey) << OP_ENDIF << OP_EQUALVERIFY << OP_CHECKSIG; return script; } CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys) { CScript script; script << CScript::EncodeOP_N(nRequired); for (const CPubKey& key : keys) script << ToByteVector(key); script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; return script; } bool IsValidDestination(const CTxDestination& dest) { return dest.which() != 0; } <|endoftext|>
<commit_before>#include <fc/exception/exception.hpp> #include <boost/exception/all.hpp> #include <fc/log/logger.hpp> #include <fc/io/json.hpp> #include <iostream> namespace fc { FC_REGISTER_EXCEPTIONS( (timeout_exception) (file_not_found_exception) (parse_error_exception) (invalid_arg_exception) (invalid_operation_exception) (key_not_found_exception) (bad_cast_exception) (out_of_range_exception) (canceled_exception) (assert_exception) (eof_exception) (unknown_host_exception) (null_optional) (udt_exception) (aes_exception) (overflow_exception) (underflow_exception) (divide_by_zero_exception) ) namespace detail { class exception_impl { public: std::string _name; std::string _what; int64_t _code; log_messages _elog; }; } exception::exception( log_messages&& msgs, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog = fc::move(msgs); } exception::exception( const log_messages& msgs, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog = msgs; } unhandled_exception::unhandled_exception( log_message&& m, std::exception_ptr e ) :exception( fc::move(m) ) { _inner = e; } unhandled_exception::unhandled_exception( const exception& r ) :exception(r) { } unhandled_exception::unhandled_exception( log_messages m ) :exception() { my->_elog = fc::move(m); } std::exception_ptr unhandled_exception::get_inner_exception()const { return _inner; } NO_RETURN void unhandled_exception::dynamic_rethrow_exception()const { if( !(_inner == std::exception_ptr()) ) std::rethrow_exception( _inner ); else { fc::exception::dynamic_rethrow_exception(); } } std::shared_ptr<exception> unhandled_exception::dynamic_copy_exception()const { auto e = std::make_shared<unhandled_exception>( *this ); e->_inner = _inner; return e; } exception::exception( int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; } exception::exception( log_message&& msg, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog.push_back( fc::move( msg ) ); } exception::exception( const exception& c ) :my( new detail::exception_impl(*c.my) ) { } exception::exception( exception&& c ) :my( fc::move(c.my) ){} const char* exception::name()const throw() { return my->_name.c_str(); } const char* exception::what()const throw() { return my->_what.c_str(); } int64_t exception::code()const throw() { return my->_code; } exception::~exception(){} void to_variant( const exception& e, variant& v ) { v = mutable_variant_object( "code", e.code() ) ( "name", e.name() ) ( "message", e.what() ) ( "stack", e.get_log() ); } void from_variant( const variant& v, exception& ll ) { auto obj = v.get_object(); if( obj.contains( "stack" ) ) ll.my->_elog = obj["stack"].as<log_messages>(); if( obj.contains( "code" ) ) ll.my->_code = obj["code"].as_int64(); if( obj.contains( "name" ) ) ll.my->_name = obj["name"].as_string(); if( obj.contains( "message" ) ) ll.my->_what = obj["message"].as_string(); } const log_messages& exception::get_log()const { return my->_elog; } void exception::append_log( log_message m ) { my->_elog.emplace_back( fc::move(m) ); } /** * Generates a detailed string including file, line, method, * and other information that is generally only useful for * developers. */ string exception::to_detail_string( log_level ll )const { std::stringstream ss; ss << variant(my->_code).as_string() <<" " << my->_name << ": " <<my->_what<<"\n"; for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ) { ss << itr->get_message() <<"\n"; //fc::format_string( itr->get_format(), itr->get_data() ) <<"\n"; ss << " " << json::to_string( itr->get_data() ) <<"\n"; ss << " " << itr->get_context().to_string(); ++itr; if( itr != my->_elog.end() ) ss<<"\n"; } return ss.str(); } /** * Generates a user-friendly error report. */ string exception::to_string( log_level ll )const { std::stringstream ss; ss << what() << " (" << variant(my->_code).as_string() <<")\n"; for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ++itr ) { ss << fc::format_string( itr->get_format(), itr->get_data() ) <<"\n"; // ss << " " << itr->get_context().to_string() <<"\n"; } return ss.str(); } /** * Generates a user-friendly error report. */ string exception::top_message( )const { for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ++itr ) { auto s = fc::format_string( itr->get_format(), itr->get_data() ); if (!s.empty()) { return s; } } return string(); } void NO_RETURN exception_factory::rethrow( const exception& e )const { auto itr = _registered_exceptions.find( e.code() ); if( itr != _registered_exceptions.end() ) itr->second->rethrow( e ); throw e; } /** * Rethrows the exception restoring the proper type based upon * the error code. This is used to propagate exception types * across conversions to/from JSON */ NO_RETURN void exception::dynamic_rethrow_exception()const { exception_factory::instance().rethrow( *this ); } exception_ptr exception::dynamic_copy_exception()const { return std::make_shared<exception>(*this); } fc::string except_str() { return boost::current_exception_diagnostic_information(); } void throw_bad_enum_cast( int64_t i, const char* e ) { FC_THROW_EXCEPTION( bad_cast_exception, "invalid index '${key}' in enum '${enum}'", ("key",i)("enum",e) ); } void throw_bad_enum_cast( const char* k, const char* e ) { FC_THROW_EXCEPTION( bad_cast_exception, "invalid name '${key}' in enum '${enum}'", ("key",k)("enum",e) ); } bool assert_optional(bool is_valid ) { if( !is_valid ) throw null_optional(); return true; } exception& exception::operator=( const exception& copy ) { *my = *copy.my; return *this; } exception& exception::operator=( exception&& copy ) { my = std::move(copy.my); return *this; } void record_assert_trip( const char* filename, uint32_t lineno, const char* expr ) { fc::mutable_variant_object assert_trip_info = fc::mutable_variant_object() ("source_file", filename) ("source_lineno", lineno) ("expr", expr) ; /* TODO: restore this later std::cout << "FC_ASSERT triggered: " << fc::json::to_string( assert_trip_info ) << "\n"; */ return; } bool enable_record_assert_trip = false; } // fc <commit_msg>Add exception handling to to_string and to_detail_string<commit_after>#include <fc/exception/exception.hpp> #include <boost/exception/all.hpp> #include <fc/log/logger.hpp> #include <fc/io/json.hpp> #include <iostream> namespace fc { FC_REGISTER_EXCEPTIONS( (timeout_exception) (file_not_found_exception) (parse_error_exception) (invalid_arg_exception) (invalid_operation_exception) (key_not_found_exception) (bad_cast_exception) (out_of_range_exception) (canceled_exception) (assert_exception) (eof_exception) (unknown_host_exception) (null_optional) (udt_exception) (aes_exception) (overflow_exception) (underflow_exception) (divide_by_zero_exception) ) namespace detail { class exception_impl { public: std::string _name; std::string _what; int64_t _code; log_messages _elog; }; } exception::exception( log_messages&& msgs, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog = fc::move(msgs); } exception::exception( const log_messages& msgs, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog = msgs; } unhandled_exception::unhandled_exception( log_message&& m, std::exception_ptr e ) :exception( fc::move(m) ) { _inner = e; } unhandled_exception::unhandled_exception( const exception& r ) :exception(r) { } unhandled_exception::unhandled_exception( log_messages m ) :exception() { my->_elog = fc::move(m); } std::exception_ptr unhandled_exception::get_inner_exception()const { return _inner; } NO_RETURN void unhandled_exception::dynamic_rethrow_exception()const { if( !(_inner == std::exception_ptr()) ) std::rethrow_exception( _inner ); else { fc::exception::dynamic_rethrow_exception(); } } std::shared_ptr<exception> unhandled_exception::dynamic_copy_exception()const { auto e = std::make_shared<unhandled_exception>( *this ); e->_inner = _inner; return e; } exception::exception( int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; } exception::exception( log_message&& msg, int64_t code, const std::string& name_value, const std::string& what_value ) :my( new detail::exception_impl() ) { my->_code = code; my->_what = what_value; my->_name = name_value; my->_elog.push_back( fc::move( msg ) ); } exception::exception( const exception& c ) :my( new detail::exception_impl(*c.my) ) { } exception::exception( exception&& c ) :my( fc::move(c.my) ){} const char* exception::name()const throw() { return my->_name.c_str(); } const char* exception::what()const throw() { return my->_what.c_str(); } int64_t exception::code()const throw() { return my->_code; } exception::~exception(){} void to_variant( const exception& e, variant& v ) { v = mutable_variant_object( "code", e.code() ) ( "name", e.name() ) ( "message", e.what() ) ( "stack", e.get_log() ); } void from_variant( const variant& v, exception& ll ) { auto obj = v.get_object(); if( obj.contains( "stack" ) ) ll.my->_elog = obj["stack"].as<log_messages>(); if( obj.contains( "code" ) ) ll.my->_code = obj["code"].as_int64(); if( obj.contains( "name" ) ) ll.my->_name = obj["name"].as_string(); if( obj.contains( "message" ) ) ll.my->_what = obj["message"].as_string(); } const log_messages& exception::get_log()const { return my->_elog; } void exception::append_log( log_message m ) { my->_elog.emplace_back( fc::move(m) ); } /** * Generates a detailed string including file, line, method, * and other information that is generally only useful for * developers. */ string exception::to_detail_string( log_level ll )const { std::stringstream ss; try { try { ss << variant( my->_code ).as_string(); } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_detail_string."; } ss << " " << my->_name << ": " << my->_what << "\n"; for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ) { try { ss << itr->get_message() << "\n"; //fc::format_string( itr->get_format(), itr->get_data() ) <<"\n"; ss << " " << json::to_string( itr->get_data()) << "\n"; ss << " " << itr->get_context().to_string(); ++itr; } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_detail_string."; } if( itr != my->_elog.end()) ss << "\n"; } } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_detail_string.\n"; } return ss.str(); } /** * Generates a user-friendly error report. */ string exception::to_string( log_level ll )const { std::stringstream ss; try { ss << my->_what; try { ss << " (" << variant( my->_code ).as_string() << ")\n"; } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_string.\n"; } for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ++itr ) { try { ss << fc::format_string( itr->get_format(), itr->get_data()) << "\n"; // ss << " " << itr->get_context().to_string() <<"\n"; } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_string.\n"; } } return ss.str(); } catch( std::bad_alloc& ) { throw; } catch( ... ) { ss << "<- exception in to_string.\n"; } } /** * Generates a user-friendly error report. */ string exception::top_message( )const { for( auto itr = my->_elog.begin(); itr != my->_elog.end(); ++itr ) { auto s = fc::format_string( itr->get_format(), itr->get_data() ); if (!s.empty()) { return s; } } return string(); } void NO_RETURN exception_factory::rethrow( const exception& e )const { auto itr = _registered_exceptions.find( e.code() ); if( itr != _registered_exceptions.end() ) itr->second->rethrow( e ); throw e; } /** * Rethrows the exception restoring the proper type based upon * the error code. This is used to propagate exception types * across conversions to/from JSON */ NO_RETURN void exception::dynamic_rethrow_exception()const { exception_factory::instance().rethrow( *this ); } exception_ptr exception::dynamic_copy_exception()const { return std::make_shared<exception>(*this); } fc::string except_str() { return boost::current_exception_diagnostic_information(); } void throw_bad_enum_cast( int64_t i, const char* e ) { FC_THROW_EXCEPTION( bad_cast_exception, "invalid index '${key}' in enum '${enum}'", ("key",i)("enum",e) ); } void throw_bad_enum_cast( const char* k, const char* e ) { FC_THROW_EXCEPTION( bad_cast_exception, "invalid name '${key}' in enum '${enum}'", ("key",k)("enum",e) ); } bool assert_optional(bool is_valid ) { if( !is_valid ) throw null_optional(); return true; } exception& exception::operator=( const exception& copy ) { *my = *copy.my; return *this; } exception& exception::operator=( exception&& copy ) { my = std::move(copy.my); return *this; } void record_assert_trip( const char* filename, uint32_t lineno, const char* expr ) { fc::mutable_variant_object assert_trip_info = fc::mutable_variant_object() ("source_file", filename) ("source_lineno", lineno) ("expr", expr) ; /* TODO: restore this later std::cout << "FC_ASSERT triggered: " << fc::json::to_string( assert_trip_info ) << "\n"; */ return; } bool enable_record_assert_trip = false; } // fc <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // audioio-jack.cpp: Interface to JACK audio framework // Copyright (C) 2001,2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi) // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <iostream> #include <jack/jack.h> #include <kvu_dbc.h> #include <kvu_numtostr.h> #include "audioio.h" #include "eca-version.h" #include "eca-logger.h" #include "audioio_jack.h" #include "audioio_jack_manager.h" #ifdef ECA_ENABLE_AUDIOIO_PLUGINS /* see eca-static-object-maps.cpp */ static const char* audio_io_keyword_const = "jack"; static const char* audio_io_keyword_regex_const = "(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)"; AUDIO_IO* audio_io_descriptor(void) { return(new AUDIO_IO_JACK()); } const char* audio_io_keyword(void){return(audio_io_keyword_const); } const char* audio_io_keyword_regex(void){return(audio_io_keyword_regex_const); } int audio_io_interface_version(void) { return(ecasound_library_version_current); } #endif AUDIO_IO_JACK::AUDIO_IO_JACK (void) { ECA_LOG_MSG(ECA_LOGGER::functions, "(audioio-jack) constructor"); jackmgr_rep = 0; myid_rep = 0; secondparam_rep = ""; } AUDIO_IO_JACK::~AUDIO_IO_JACK(void) { if (is_open() == true && is_running()) stop(); if (is_open() == true) { close(); } } AUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const { return(new AUDIO_IO_JACK_MANAGER()); } void AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id) { string mgrname = (mgr == 0 ? mgr->name() : "null"); ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) setting manager to " + mgr->name()); jackmgr_rep = mgr; myid_rep = id; } void AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) open"); set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le); toggle_interleaved_channels(false); if (jackmgr_rep != 0) { string my_in_portname ("in"), my_out_portname ("out"); if (label() == "jack_generic") { my_in_portname = my_out_portname = secondparam_rep; } // FIXME: required? // if (workstring.size() == 0) workstring = label(); jackmgr_rep->open(myid_rep); if (jackmgr_rep->is_open() != true) { /* unable to open connection to jackd, exit */ throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Unable to open JACK-client")); } if (samples_per_second() != jackmgr_rep->samples_per_second()) { jackmgr_rep->close(myid_rep); throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Cannot connect open connection! Samplerate " + kvu_numtostr(samples_per_second()) + " differs from JACK server's sample rate of " + kvu_numtostr(jackmgr_rep->samples_per_second()) + ".")); } if (buffersize() != jackmgr_rep->buffersize()) { long int jackd_bsize = jackmgr_rep->buffersize(); jackmgr_rep->close(myid_rep); throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Cannot connect open connection! Buffersize " + kvu_numtostr(buffersize()) + " differs from JACK server's buffersize of " + kvu_numtostr(jackd_bsize) + ".")); } if (io_mode() == AUDIO_IO::io_read) { jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname); } else { jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname); } if (label() != "jack_generic" && label() != "jack") { string in_aconn_portprefix, out_aconn_portprefix; if (label() == "jack_alsa") { in_aconn_portprefix = "alsa_pcm:capture_"; out_aconn_portprefix = "alsa_pcm:playback_"; } else if (label() == "jack_auto") { in_aconn_portprefix = secondparam_rep + ":out_"; out_aconn_portprefix = secondparam_rep + ":in_"; } for(int n = 0; n < channels(); n++) { if (io_mode() == AUDIO_IO::io_read) { jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1)); } else { jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1)); } } } } AUDIO_IO_DEVICE::open(); } void AUDIO_IO_JACK::close(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) close"); if (jackmgr_rep != 0) { jackmgr_rep->unregister_jack_ports(myid_rep); jackmgr_rep->close(myid_rep); } AUDIO_IO_DEVICE::close(); } bool AUDIO_IO_JACK::finished(void) const { if (is_open() != true || jackmgr_rep == 0 || jackmgr_rep->is_open() != true) return(true); return(false); } long int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples) { if (jackmgr_rep != 0) { long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples); return(res); } return(0); } void AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples) { /* FIXME: case where samples!=buffersize() not handled */ if (jackmgr_rep != 0) { DBC_CHECK(samples == jackmgr_rep->buffersize()); jackmgr_rep->write_samples(myid_rep, target_buffer, samples); } } void AUDIO_IO_JACK::prepare(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) prepare / " + label()); AUDIO_IO_DEVICE::prepare(); } void AUDIO_IO_JACK::start(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) start / " + label()); AUDIO_IO_DEVICE::start(); } void AUDIO_IO_JACK::stop(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) stop / " + label()); AUDIO_IO_DEVICE::stop(); } long int AUDIO_IO_JACK::latency(void) const { return(jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep)); } std::string AUDIO_IO_JACK::parameter_names(void) const { if (label() == "jack_generic") return("label,portname"); if (label() == "jack_auto") return("label,client"); /* jack, jack_alsa */ return("label"); } void AUDIO_IO_JACK::set_parameter(int param, std::string value) { switch(param) { case 1: { set_label(value); break; } case 2: { secondparam_rep = value; break; } } } std::string AUDIO_IO_JACK::get_parameter(int param) const { switch(param) { case 1: { return(label()); } case 2: { return(secondparam_rep); } } return(""); } <commit_msg>Copyright update.<commit_after>// ------------------------------------------------------------------------ // audioio-jack.cpp: Interface to JACK audio framework // Copyright (C) 2001-2003 Kai Vehmanen (kai.vehmanen@wakkanet.fi) // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ------------------------------------------------------------------------ #include <iostream> #include <jack/jack.h> #include <kvu_dbc.h> #include <kvu_numtostr.h> #include "audioio.h" #include "eca-version.h" #include "eca-logger.h" #include "audioio_jack.h" #include "audioio_jack_manager.h" #ifdef ECA_ENABLE_AUDIOIO_PLUGINS /* see eca-static-object-maps.cpp */ static const char* audio_io_keyword_const = "jack"; static const char* audio_io_keyword_regex_const = "(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)"; AUDIO_IO* audio_io_descriptor(void) { return(new AUDIO_IO_JACK()); } const char* audio_io_keyword(void){return(audio_io_keyword_const); } const char* audio_io_keyword_regex(void){return(audio_io_keyword_regex_const); } int audio_io_interface_version(void) { return(ecasound_library_version_current); } #endif AUDIO_IO_JACK::AUDIO_IO_JACK (void) { ECA_LOG_MSG(ECA_LOGGER::functions, "(audioio-jack) constructor"); jackmgr_rep = 0; myid_rep = 0; secondparam_rep = ""; } AUDIO_IO_JACK::~AUDIO_IO_JACK(void) { if (is_open() == true && is_running()) stop(); if (is_open() == true) { close(); } } AUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const { return(new AUDIO_IO_JACK_MANAGER()); } void AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id) { string mgrname = (mgr == 0 ? mgr->name() : "null"); ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) setting manager to " + mgr->name()); jackmgr_rep = mgr; myid_rep = id; } void AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) open"); set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le); toggle_interleaved_channels(false); if (jackmgr_rep != 0) { string my_in_portname ("in"), my_out_portname ("out"); if (label() == "jack_generic") { my_in_portname = my_out_portname = secondparam_rep; } // FIXME: required? // if (workstring.size() == 0) workstring = label(); jackmgr_rep->open(myid_rep); if (jackmgr_rep->is_open() != true) { /* unable to open connection to jackd, exit */ throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Unable to open JACK-client")); } if (samples_per_second() != jackmgr_rep->samples_per_second()) { jackmgr_rep->close(myid_rep); throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Cannot connect open connection! Samplerate " + kvu_numtostr(samples_per_second()) + " differs from JACK server's sample rate of " + kvu_numtostr(jackmgr_rep->samples_per_second()) + ".")); } if (buffersize() != jackmgr_rep->buffersize()) { long int jackd_bsize = jackmgr_rep->buffersize(); jackmgr_rep->close(myid_rep); throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Cannot connect open connection! Buffersize " + kvu_numtostr(buffersize()) + " differs from JACK server's buffersize of " + kvu_numtostr(jackd_bsize) + ".")); } if (io_mode() == AUDIO_IO::io_read) { jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname); } else { jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname); } if (label() != "jack_generic" && label() != "jack") { string in_aconn_portprefix, out_aconn_portprefix; if (label() == "jack_alsa") { in_aconn_portprefix = "alsa_pcm:capture_"; out_aconn_portprefix = "alsa_pcm:playback_"; } else if (label() == "jack_auto") { in_aconn_portprefix = secondparam_rep + ":out_"; out_aconn_portprefix = secondparam_rep + ":in_"; } for(int n = 0; n < channels(); n++) { if (io_mode() == AUDIO_IO::io_read) { jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1)); } else { jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1)); } } } } AUDIO_IO_DEVICE::open(); } void AUDIO_IO_JACK::close(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) close"); if (jackmgr_rep != 0) { jackmgr_rep->unregister_jack_ports(myid_rep); jackmgr_rep->close(myid_rep); } AUDIO_IO_DEVICE::close(); } bool AUDIO_IO_JACK::finished(void) const { if (is_open() != true || jackmgr_rep == 0 || jackmgr_rep->is_open() != true) return(true); return(false); } long int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples) { if (jackmgr_rep != 0) { long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples); return(res); } return(0); } void AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples) { /* FIXME: case where samples!=buffersize() not handled */ if (jackmgr_rep != 0) { DBC_CHECK(samples == jackmgr_rep->buffersize()); jackmgr_rep->write_samples(myid_rep, target_buffer, samples); } } void AUDIO_IO_JACK::prepare(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) prepare / " + label()); AUDIO_IO_DEVICE::prepare(); } void AUDIO_IO_JACK::start(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) start / " + label()); AUDIO_IO_DEVICE::start(); } void AUDIO_IO_JACK::stop(void) { ECA_LOG_MSG(ECA_LOGGER::system_objects, "(audioio-jack) stop / " + label()); AUDIO_IO_DEVICE::stop(); } long int AUDIO_IO_JACK::latency(void) const { return(jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep)); } std::string AUDIO_IO_JACK::parameter_names(void) const { if (label() == "jack_generic") return("label,portname"); if (label() == "jack_auto") return("label,client"); /* jack, jack_alsa */ return("label"); } void AUDIO_IO_JACK::set_parameter(int param, std::string value) { switch(param) { case 1: { set_label(value); break; } case 2: { secondparam_rep = value; break; } } } std::string AUDIO_IO_JACK::get_parameter(int param) const { switch(param) { case 1: { return(label()); } case 2: { return(secondparam_rep); } } return(""); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <stdio.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include "dbusgateway.h" #include "pelagicontain-common.h" DBusGateway::DBusGateway(ProxyType type, const std::string &gatewayDir, const std::string &name) : Gateway(ID), m_type(type), m_hasBeenConfigured(false), m_dbusProxyStarted(false) { m_socket = gatewayDir + (m_type == SessionProxy ? "/sess_" : "/sys_") + name + ".sock"; } DBusGateway::~DBusGateway() { if (m_pid != INVALID_PID) { log_debug() << "Killing dbus proxy with pid " << m_pid; kill(m_pid, SIGTERM); } // TODO : fix dbus-proxy to delete the socket files when terminating } static constexpr const char *SESSION_CONFIG = "dbus-gateway-config-session"; static constexpr const char *SYSTEM_CONFIG = "dbus-gateway-config-system"; ReturnCode DBusGateway::readConfigElement(const JSonElement &element) { auto sessionConfig = element[SESSION_CONFIG]; if (sessionConfig.isValid() && sessionConfig.isArray()) { for(unsigned int i = 0; i < sessionConfig.elementCount(); i++) { JSonElement child = sessionConfig.arrayElementAt(i); if (m_sessionBusConfig.size() != 0) { m_sessionBusConfig += ","; } m_sessionBusConfig += child.dump(); } } auto systemConfig = element[SYSTEM_CONFIG]; if (systemConfig.isValid() && systemConfig.isArray()) { for(unsigned int i = 0; i < systemConfig.elementCount(); i++) { JSonElement child = systemConfig.arrayElementAt(i); if (m_systemBusConfig.size() != 0) { m_systemBusConfig += ","; } m_systemBusConfig += child.dump(); } } m_hasBeenConfigured = true; return ReturnCode::SUCCESS; } bool DBusGateway::activate() { if (!m_hasBeenConfigured) { log_warning() << "'Activate' called on non-configured gateway " << id(); return false; } // set DBUS ENV var std::string variable = "DBUS_"; variable += m_type == SessionProxy ? "SESSION" : "SYSTEM"; variable += "_BUS_ADDRESS"; std::string value = "unix:path=/gateways/" + socketName(); setEnvironmentVariable(variable, value); // Open pipe std::string command = "dbus-proxy " + m_socket + " " + typeString(); log_debug() << command; auto code = makePopenCall(command, m_infp, m_pid); if (isError(code)) { log_error() << "Failed to launch " << command; return false; } else { log_debug() << "Started dbus-proxy: " << m_pid; m_dbusProxyStarted = true; } // Write configuration std::string config = (logging::StringBuilder() << "{\"" << SESSION_CONFIG << "\"" << ": [" << m_sessionBusConfig << "]" << " , \"" << SYSTEM_CONFIG << "\"" << ": [" << m_systemBusConfig << "]}"); log_debug() << "Sending config " << config; auto count = sizeof(char) * config.length(); auto written = write(m_infp, config.c_str(), count); // writing didn't work at all if (written == -1) { log_error() << "Failed to write to STDIN of dbus-proxy: " << strerror(errno); return false; } // writing has written exact amout of bytes if (written == (ssize_t)count) { close(m_infp); m_infp = INVALID_FD; // dbus-proxy might take some time to create the bus socket if (isSocketCreated()) { log_debug() << "Found D-Bus socket: " << m_socket; } else { log_error() << "Did not find any D-Bus socket: " << m_socket; return false; } return true; } // something went wrong during the write log_error() << "Failed to write to STDIN of dbus-proxy!"; return false; } bool DBusGateway::isSocketCreated() const { int maxCount = 1000; int count = 0; do { if (count >= maxCount) { return false; } count++; usleep(1000 * 10); } while (access(m_socket.c_str(), F_OK) == -1); return true; } bool DBusGateway::teardown() { bool success = true; if (m_dbusProxyStarted) { if (m_pid != INVALID_PID) { if (!makePcloseCall(m_pid, m_infp)) { log_error() << "makePcloseCall() returned error"; success = false; } } else { log_error() << "Failed to close connection to dbus-proxy!"; success = false; } if (unlink(m_socket.c_str()) == -1) { log_error() << "Could not remove " << m_socket << ": " << strerror(errno); success = false; } } return success; } const char *DBusGateway::typeString() { if (m_type == SessionProxy) { return "session"; } else { return "system"; } } std::string DBusGateway::socketName() { // Return the filename after stripping directory info std::string socket(m_socket.c_str()); return socket.substr(socket.rfind('/') + 1); } ReturnCode DBusGateway::makePopenCall(const std::string &command, int &infp, pid_t &pid) { static constexpr int READ = 0; static constexpr int WRITE = 1; int stdinfp[2]; if (pipe(stdinfp) != 0) { log_error() << "Failed to open STDIN to dbus-proxy"; return ReturnCode::FAILURE; } pid = fork(); if (pid < 0) { return ReturnCode::FAILURE; } else if (pid == 0) { close(stdinfp[WRITE]); dup2(stdinfp[READ], READ); dup2(open("/dev/null", O_WRONLY), WRITE); // Set group id to the same as pid, that way we can kill the shells children on close. setpgid(0, 0); execl("/bin/sh", "sh", "-c", command.c_str(), nullptr); log_error() << "execl : " << strerror(errno); exit(1); } infp = stdinfp[WRITE]; return ReturnCode::SUCCESS; } bool DBusGateway::makePcloseCall(pid_t pid, int infp) { if (infp > -1) { if (close(infp) == -1) { log_warning() << "Failed to close STDIN to dbus-proxy"; } } // the negative pid makes it kill the whole group, not only the shell int killed = kill(-pid, SIGKILL); return (killed == 0); } <commit_msg>dbusgateway.cpp: checks result from open() and removes stringbuilder dependency<commit_after>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <stdio.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <fcntl.h> #include "dbusgateway.h" #include "pelagicontain-common.h" DBusGateway::DBusGateway(ProxyType type, const std::string &gatewayDir, const std::string &name) : Gateway(ID), m_type(type), m_hasBeenConfigured(false), m_dbusProxyStarted(false) { m_socket = gatewayDir + (m_type == SessionProxy ? "/sess_" : "/sys_") + name + ".sock"; } DBusGateway::~DBusGateway() { if (m_pid != INVALID_PID) { log_debug() << "Killing dbus proxy with pid " << m_pid; kill(m_pid, SIGTERM); } // TODO : fix dbus-proxy to delete the socket files when terminating } static constexpr const char *SESSION_CONFIG = "dbus-gateway-config-session"; static constexpr const char *SYSTEM_CONFIG = "dbus-gateway-config-system"; ReturnCode DBusGateway::readConfigElement(const JSonElement &element) { auto sessionConfig = element[SESSION_CONFIG]; if (sessionConfig.isValid() && sessionConfig.isArray()) { for(unsigned int i = 0; i < sessionConfig.elementCount(); i++) { JSonElement child = sessionConfig.arrayElementAt(i); if (m_sessionBusConfig.size() != 0) { m_sessionBusConfig += ","; } m_sessionBusConfig += child.dump(); } } auto systemConfig = element[SYSTEM_CONFIG]; if (systemConfig.isValid() && systemConfig.isArray()) { for(unsigned int i = 0; i < systemConfig.elementCount(); i++) { JSonElement child = systemConfig.arrayElementAt(i); if (m_systemBusConfig.size() != 0) { m_systemBusConfig += ","; } m_systemBusConfig += child.dump(); } } m_hasBeenConfigured = true; return ReturnCode::SUCCESS; } bool DBusGateway::activate() { if (!m_hasBeenConfigured) { log_warning() << "'Activate' called on non-configured gateway " << id(); return false; } // set DBUS ENV var std::string variable = "DBUS_"; variable += m_type == SessionProxy ? "SESSION" : "SYSTEM"; variable += "_BUS_ADDRESS"; std::string value = "unix:path=/gateways/" + socketName(); setEnvironmentVariable(variable, value); // Open pipe std::string command = "dbus-proxy " + m_socket + " " + typeString(); log_debug() << command; auto code = makePopenCall(command, m_infp, m_pid); if (isError(code)) { log_error() << "Failed to launch " << command; return false; } else { log_debug() << "Started dbus-proxy: " << m_pid; m_dbusProxyStarted = true; } // Write configuration std::string config = "{\"" + std::string(SESSION_CONFIG) + "\": [" + m_sessionBusConfig + "]" + ", \"" + std::string(SYSTEM_CONFIG) + "\": [" + m_systemBusConfig + "]}"; log_debug() << "Sending config " << config; auto count = sizeof(char) * config.length(); auto written = write(m_infp, config.c_str(), count); // writing didn't work at all if (written == -1) { log_error() << "Failed to write to STDIN of dbus-proxy: " << strerror(errno); return false; } // writing has written exact amout of bytes if (written == (ssize_t)count) { close(m_infp); m_infp = INVALID_FD; // dbus-proxy might take some time to create the bus socket if (isSocketCreated()) { log_debug() << "Found D-Bus socket: " << m_socket; } else { log_error() << "Did not find any D-Bus socket: " << m_socket; return false; } return true; } // something went wrong during the write log_error() << "Failed to write to STDIN of dbus-proxy!"; return false; } bool DBusGateway::isSocketCreated() const { int maxCount = 1000; int count = 0; do { if (count >= maxCount) { return false; } count++; usleep(1000 * 10); } while (access(m_socket.c_str(), F_OK) == -1); return true; } bool DBusGateway::teardown() { bool success = true; if (m_dbusProxyStarted) { if (m_pid != INVALID_PID) { if (!makePcloseCall(m_pid, m_infp)) { log_error() << "makePcloseCall() returned error"; success = false; } } else { log_error() << "Failed to close connection to dbus-proxy!"; success = false; } if (unlink(m_socket.c_str()) == -1) { log_error() << "Could not remove " << m_socket << ": " << strerror(errno); success = false; } } return success; } const char *DBusGateway::typeString() { if (m_type == SessionProxy) { return "session"; } else { return "system"; } } std::string DBusGateway::socketName() { // Return the filename after stripping directory info std::string socket(m_socket.c_str()); return socket.substr(socket.rfind('/') + 1); } /* * Opens a channel to some command and captures the input file descriptor and * pid for future writing and control. Output from the call is directed * towards /dev/null */ ReturnCode DBusGateway::makePopenCall(const std::string &command, int &infp, pid_t &pid) { static constexpr int READ = 0; static constexpr int WRITE = 1; int stdinfp[2]; if (pipe(stdinfp) != 0) { log_error() << "Failed to open STDIN to dbus-proxy"; return ReturnCode::FAILURE; } pid = fork(); if (pid < 0) { return ReturnCode::FAILURE; } else if (pid == 0) { close(stdinfp[WRITE]); dup2(stdinfp[READ], READ); int nullfd = open("/dev/null", O_WRONLY); if (nullfd == INVALID_FD) { log_error() << "could not open /dev/null: " << strerror(errno); exit(1); } else { dup2(nullfd, WRITE); // Set group id to the same as pid, that way we can kill the shells children on close. setpgid(0, 0); execl("/bin/sh", "sh", "-c", command.c_str(), nullptr); log_error() << "execl : " << strerror(errno); close(nullfd); exit(1); } } infp = stdinfp[WRITE]; return ReturnCode::SUCCESS; } bool DBusGateway::makePcloseCall(pid_t pid, int infp) { if (infp > -1) { if (close(infp) == -1) { log_warning() << "Failed to close STDIN to dbus-proxy"; } } // the negative pid makes it kill the whole group, not only the shell int killed = kill(-pid, SIGKILL); return (killed == 0); } <|endoftext|>
<commit_before>/* Crystal Space Windowing System: Default listbox skin Copyright (C) 2001 Christopher Nelson This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csws/cslistbx.h" #include "csws/sdefault.h" /** * The following defines are duplicated from cslistbx.cpp * Any changes should be made in BOTH places. * */ // Amount of space at left and at right of each listbox item #define LISTBOXITEM_XSPACE 2 // Amount of space at top and at bottom of each listbox item #define LISTBOXITEM_YSPACE 2 // Mouse scroll time interval in milliseconds #define MOUSE_SCROLL_INTERVAL 100 // Horizontal large scrolling step #define LISTBOX_HORIZONTAL_PAGESTEP 8 void csDefaultListBoxItemSkin::Draw (csComponent &This) { #define This ((csListBoxItem &)This) bool enabled = !This.parent->GetState (CSS_DISABLED); bool selected = enabled && This.GetState (CSS_LISTBOXITEM_SELECTED); if (selected) { if (This.parent->GetState (CSS_FOCUSED) && enabled) This.Clear (CSPAL_LISTBOXITEM_SELECTION); else This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOXITEM_SELECTION, CSPAL_LISTBOXITEM_SELECTION); } int color; if (This.GetState (CSS_SELECTABLE) && enabled) { if (This.GetItemStyle() == cslisNormal) if (selected && This.parent->GetState (CSS_FOCUSED)) color = CSPAL_LISTBOXITEM_SNTEXT; else color = CSPAL_LISTBOXITEM_UNTEXT; else if (selected && This.parent->GetState (CSS_FOCUSED)) color = CSPAL_LISTBOXITEM_SETEXT; else color = CSPAL_LISTBOXITEM_UETEXT; } else color = CSPAL_LISTBOXITEM_DTEXT; int x = LISTBOXITEM_XSPACE - This.GetDeltaX() + This.GetHOffset(); csPixmap *ItemBitmap; if ((ItemBitmap=This.GetItemBitmap())) { This.Pixmap(ItemBitmap, x, (This.bound.Height()-ItemBitmap->Height()) / 2); x += ItemBitmap->Width () + LISTBOXITEM_XSPACE; } /* endif */ char *text; if ((text=This.GetText())) { int fh; This.GetTextSize (text, &fh); This.Text (x, (This.bound.Height () - fh + 1) / 2, color, -1, text); } /* endif */ #undef This } void csDefaultListBoxSkin::Draw (csComponent &This) { #define This ((csListBox &)This) int BorderWidth, BorderHeight; This.GetBorderSize(&BorderWidth, &BorderHeight); if (This.GetPlaceItemsFlag()) This.PlaceItems (); switch (This.GetFrameStyle()) { case cslfsNone: This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND); break; case cslfsThinRect: This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); This.Rect3D (1, 1, This.bound.Width () - 1, This.bound.Height () - 1, CSPAL_LISTBOX_DARK3D, CSPAL_LISTBOX_LIGHT3D); This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND); break; case cslfsThickRect: This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); This.Rect3D (1, 1, This.bound.Width () - 1, This.bound.Height () - 1, CSPAL_LISTBOX_2LIGHT3D, CSPAL_LISTBOX_2DARK3D); This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND2); break; case cslfsTextured: This.Pixmap(This.GetFrameBitmap(), 1, 1, This.bound.Width ()-BorderWidth, This.bound.Height ()-BorderHeight, 0, 0, This.GetAlpha()); This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (),CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); break; case cslfsTexturedNoFrame: This.Pixmap(This.GetFrameBitmap(), 1, 1, This.bound.Width ()-BorderWidth, This.bound.Height ()-BorderHeight, 0, 0, This.GetAlpha()); break; case cslfsBitmap: This.Pixmap(This.GetFrameBitmap(), 0, 0, This.GetAlpha()); break; default: break; } /* endswitch */ #undef This } void csDefaultListBoxSkin::SuggestSize (csListBox &This, int &w, int &h) { w = h = 0; if (This.GetHScroll()) h = This.GetHScroll()->bound.Height (); if (This.GetVScroll()) w = This.GetVScroll()->bound.Width (); h = MAX (This.bound.Height (), h); w = MAX (This.bound.Width (), w); }<commit_msg>Added missing newline at end of file.<commit_after>/* Crystal Space Windowing System: Default listbox skin Copyright (C) 2001 Christopher Nelson This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csws/cslistbx.h" #include "csws/sdefault.h" /** * The following defines are duplicated from cslistbx.cpp * Any changes should be made in BOTH places. * */ // Amount of space at left and at right of each listbox item #define LISTBOXITEM_XSPACE 2 // Amount of space at top and at bottom of each listbox item #define LISTBOXITEM_YSPACE 2 // Mouse scroll time interval in milliseconds #define MOUSE_SCROLL_INTERVAL 100 // Horizontal large scrolling step #define LISTBOX_HORIZONTAL_PAGESTEP 8 void csDefaultListBoxItemSkin::Draw (csComponent &This) { #define This ((csListBoxItem &)This) bool enabled = !This.parent->GetState (CSS_DISABLED); bool selected = enabled && This.GetState (CSS_LISTBOXITEM_SELECTED); if (selected) { if (This.parent->GetState (CSS_FOCUSED) && enabled) This.Clear (CSPAL_LISTBOXITEM_SELECTION); else This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOXITEM_SELECTION, CSPAL_LISTBOXITEM_SELECTION); } int color; if (This.GetState (CSS_SELECTABLE) && enabled) { if (This.GetItemStyle() == cslisNormal) if (selected && This.parent->GetState (CSS_FOCUSED)) color = CSPAL_LISTBOXITEM_SNTEXT; else color = CSPAL_LISTBOXITEM_UNTEXT; else if (selected && This.parent->GetState (CSS_FOCUSED)) color = CSPAL_LISTBOXITEM_SETEXT; else color = CSPAL_LISTBOXITEM_UETEXT; } else color = CSPAL_LISTBOXITEM_DTEXT; int x = LISTBOXITEM_XSPACE - This.GetDeltaX() + This.GetHOffset(); csPixmap *ItemBitmap; if ((ItemBitmap=This.GetItemBitmap())) { This.Pixmap(ItemBitmap, x, (This.bound.Height()-ItemBitmap->Height()) / 2); x += ItemBitmap->Width () + LISTBOXITEM_XSPACE; } /* endif */ char *text; if ((text=This.GetText())) { int fh; This.GetTextSize (text, &fh); This.Text (x, (This.bound.Height () - fh + 1) / 2, color, -1, text); } /* endif */ #undef This } void csDefaultListBoxSkin::Draw (csComponent &This) { #define This ((csListBox &)This) int BorderWidth, BorderHeight; This.GetBorderSize(&BorderWidth, &BorderHeight); if (This.GetPlaceItemsFlag()) This.PlaceItems (); switch (This.GetFrameStyle()) { case cslfsNone: This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND); break; case cslfsThinRect: This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); This.Rect3D (1, 1, This.bound.Width () - 1, This.bound.Height () - 1, CSPAL_LISTBOX_DARK3D, CSPAL_LISTBOX_LIGHT3D); This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND); break; case cslfsThickRect: This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (), CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); This.Rect3D (1, 1, This.bound.Width () - 1, This.bound.Height () - 1, CSPAL_LISTBOX_2LIGHT3D, CSPAL_LISTBOX_2DARK3D); This.Box (BorderWidth, BorderHeight, This.bound.Width () - BorderWidth, This.bound.Height () - BorderHeight, CSPAL_LISTBOX_BACKGROUND2); break; case cslfsTextured: This.Pixmap(This.GetFrameBitmap(), 1, 1, This.bound.Width ()-BorderWidth, This.bound.Height ()-BorderHeight, 0, 0, This.GetAlpha()); This.Rect3D (0, 0, This.bound.Width (), This.bound.Height (),CSPAL_LISTBOX_LIGHT3D, CSPAL_LISTBOX_DARK3D); break; case cslfsTexturedNoFrame: This.Pixmap(This.GetFrameBitmap(), 1, 1, This.bound.Width ()-BorderWidth, This.bound.Height ()-BorderHeight, 0, 0, This.GetAlpha()); break; case cslfsBitmap: This.Pixmap(This.GetFrameBitmap(), 0, 0, This.GetAlpha()); break; default: break; } /* endswitch */ #undef This } void csDefaultListBoxSkin::SuggestSize (csListBox &This, int &w, int &h) { w = h = 0; if (This.GetHScroll()) h = This.GetHScroll()->bound.Height (); if (This.GetVScroll()) w = This.GetVScroll()->bound.Width (); h = MAX (This.bound.Height (), h); w = MAX (This.bound.Width (), w); } <|endoftext|>
<commit_before>class Solution { public: /* 题意为求最长回文子串, 直接枚举子串首尾位置再判断是否会问,时间复杂度为O(N^3), 换个思路,枚举回文串的对称中心位置,向两侧扫描检测最长回文长度时间复杂度为O(N^2) 对于最长回文子串问题有对应O(N)算法--Manacher算法 笔者觉得面试中应当不会有这么高的要求,有兴趣可以自行了解该算法 */ string longestPalindrome(string s) { string str = "", ans = ""; int len = s.length(); int maxl = -1, cnt; for (int i = 0; i < len; i++) { str += '#'; str += s[i]; } str += '#'; // extend to #a#b# ; 2len+1 total length // don't care about the odd and even // O(n*n) Solution for (int i = 1; i < 2 * len; i++) { cnt = 0; while ((i - cnt >= 0) && (i + cnt <= 2 * len) && (str[i - cnt] == str[i + cnt])) cnt++; cnt--; if (cnt > maxl) { maxl = cnt; ans = s.substr((i - cnt) / 2, (i + cnt) / 2 - (i - cnt) / 2); } } return ans; } }; // Total Runtime: 39 ms<commit_msg>testing 200<commit_after>class Solution { public: /* 题意为求最长回文子串, 直接枚举子串首尾位置再判断是否会问,时间复杂度为O(N^3), 换个思路,枚举回文串的对称中心位置,向两侧扫描检测最长回文长度时间复杂度为O(N^2) 对于最长回文子串问题有对应O(N)算法--Manacher算法 笔者觉得面试中应当不会有这么高的要求,有兴趣可以自行了解该算法 */ string longestPalindrome(string s) { string str = "", ans = ""; int len = s.length(); int maxl = -1, cnt; for (int i = 0; i < len; i++) { str += '#'; str += s[i]; } str += '#'; // extend to #a#b# ; 2len+1 total length // don't care about the odd and even // O(n*n) Solution for (int i = 1; i < 2 * len; i++) { cnt = 0; while ((i - cnt >= 0) && (i + cnt <= 2 * len) && (str[i - cnt] == str[i + cnt])) cnt++; cnt--; // new (i-cnt)..(i+cnt) if (cnt > maxl) { maxl = cnt; ans = s.substr((i - cnt) / 2, cnt); } } return ans; } }; // Total Runtime: 39 ms<|endoftext|>
<commit_before>/* * Map.cpp * * Created on: Apr 22, 2014 * Author: user */ #include "Map.h" Map::Map(int rows, int columns, double resolution) { // TODO: input checks _resolution = resolution; float fixed_resolution = 1 / resolution; _rows = ceil(rows * fixed_resolution); _columns = ceil(columns * fixed_resolution); _matrix.init(_rows, _columns, MAP_STATE_UNKNOWN); } /* * X, Y may be nagative * * in our map, 0 is the middle * any negative value is relative to the left * and any positive value is relative to the right * * - - - - 0 + + + + *-4 -3 -2 -1 1 2 3 4 *------------------------------ * 0 1 2 3 4 5 6 7 8 * */ int Map::convertYToRow(double y) const { int value = (_rows / 2) - (y / _resolution); return value; } int Map::convertXToColumn(double x) const { int value = (_columns / 2) + (x / _resolution); return value; } int Map::get(double x, double y) const { // TODO: input checks // Convert x and y to row and column int row = convertYToRow(y); int column = convertXToColumn(x); return get(row, column); } void Map::set(double x, double y, int value) { // TODO: input checks // Convert x and y to row and column int row = convertYToRow(y); int column = convertXToColumn(x); set(row, column, value); } int Map::get(int row, int column) const { // TODO: input checks return _matrix(row, column); } void Map::set(int row, int column, int value) { int previews_value = get(row, column); switch (previews_value) { case (MAP_STATE_OBSTACLE): // Ignore this cell update break; default: _matrix(row, column) = value; break; } } void Map::set(const Point& point, int value) { int pointRow = convertYToRow(point.getY()); int pointColumn = convertXToColumn(point.getX()); set(pointRow, pointColumn, value); } bool Map::isMismatch(int row, int column, int value, bool & isUnknown) { int previews_value = get(row, column); // For unknown values we do not care what is the new value if (previews_value == MAP_STATE_UNKNOWN) { isUnknown = true; return false; } isUnknown = false; // If they are not equals then this is a mismatch bool mismatch = previews_value != value; return mismatch; } bool Map::isMismatch(const Point& point, int value, bool & isUnknown) { // Convert x and y to row and column int pointRow = convertYToRow(point.getY()); int pointColumn = convertXToColumn(point.getX()); return isMismatch(pointRow, pointColumn, value, isUnknown); } // Print operator std::ostream& operator<<(ostream &os, const Map& map) { for (int i = 0; i < map._rows; i++) { for (int j = 0; j < map._columns; j++) { int value = map.get(i, j); switch (value) { case (MAP_STATE_CLEAR): os << " "; break; case (MAP_STATE_OBSTACLE): os << "█"; break; case (MAP_STATE_UNKNOWN): os << "░"; break; } } os << endl; } return os; } Map& Map::operator =(const Map& m) { _columns = m._columns; _resolution = m._resolution; _rows = m._rows; _matrix = m._matrix; return *this; } double Map::handleObstacles(const Point& initalPoint, const vector<Point>& obstacles) { unsigned int mismatchCount = 0; unsigned int currectCounter = 0; ////////////////////////////////////////////////// // TODO: DELETE THIS LINE - ONLY FOR TESTING int num_of_obstacles = obstacles.size(); ////////////////////////////////////////////////// vector<Point> freePointsToFlush; set(initalPoint, MAP_STATE_CLEAR); for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it) { bool isNewPoint; const Point& obstaclePoint = *it; if (isMismatch(obstaclePoint, MAP_STATE_OBSTACLE, isNewPoint)) { mismatchCount++; } else if (!isNewPoint) { currectCounter++; } // Get intermediate points (the points between the robot and the obstacle) vector<Point> intermediatePoints; MathHelper::GetIntermediatePoints(initalPoint, obstaclePoint, MAP_INTERMEDIATE_POINT_DISTANCE, intermediatePoints); //////////////////////////////////////////////// // TODO: DELETE THIS LINE - ONLY FOR TESTING int num_of_intermediatePoints = intermediatePoints.size(); /////////////////////////////////////////////// // Enumerate Intermediate Points, // Set each intermediate Point to 'CLEAR' map state for (std::vector<Point>::const_iterator it2 = intermediatePoints.begin(); it2 != intermediatePoints.end(); ++it2) { const Point& intermediatePoint = *it2; if (isMismatch(intermediatePoint, MAP_STATE_CLEAR, isNewPoint)) { mismatchCount++; } else if (!isNewPoint) { currectCounter++; } freePointsToFlush.push_back(intermediatePoint); } } for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it) { set(*it, MAP_STATE_OBSTACLE); } for (std::vector<Point>::const_iterator it = freePointsToFlush.begin(); it != freePointsToFlush.end(); ++it) { set(*it, MAP_STATE_CLEAR); } if (mismatchCount == 0) return 1; return (double)currectCounter/(double)(currectCounter+mismatchCount); } double Map::handleObstacles(Robot& robot, const vector<Point>& obstacles) { double robotX = robot.getX(); double robotY = robot.getY(); Point initalPoint(robotX, robotY); double matchPercent = handleObstacles(initalPoint, obstacles); return matchPercent; } double Map::update(double x, double y, double yaw, const Laser& laser) { // Handle new Obstacles vector<Point> obstacles; laser.getObstacles(x, y, yaw, obstacles); Point initalPoint(x, y); double matchPercent = handleObstacles(initalPoint, obstacles); return matchPercent; } <commit_msg>add the robot's location<commit_after>/* * Map.cpp * * Created on: Apr 22, 2014 * Author: user */ #include "Map.h" Map::Map(int rows, int columns, double resolution) : _resolution(resolution), _prev() { float fixed_resolution = 1 / resolution; _rows = ceil(rows * fixed_resolution); _columns = ceil(columns * fixed_resolution); _matrix.init(_rows, _columns, MAP_STATE_UNKNOWN); } /* * X, Y may be nagative * * in our map, 0 is the middle * any negative value is relative to the left * and any positive value is relative to the right * * - - - - 0 + + + + *-4 -3 -2 -1 1 2 3 4 *------------------------------ * 0 1 2 3 4 5 6 7 8 * */ int Map::convertYToRow(double y) const { int value = (_rows / 2) - (y / _resolution); return value; } int Map::convertXToColumn(double x) const { int value = (_columns / 2) + (x / _resolution); return value; } int Map::get(double x, double y) const { // TODO: input checks // Convert x and y to row and column int row = convertYToRow(y); int column = convertXToColumn(x); return get(row, column); } void Map::set(double x, double y, int value) { // TODO: input checks // Convert x and y to row and column int row = convertYToRow(y); int column = convertXToColumn(x); set(row, column, value); } int Map::get(int row, int column) const { // TODO: input checks return _matrix(row, column); } void Map::set(int row, int column, int value) { int previews_value = get(row, column); switch (previews_value) { case (MAP_STATE_OBSTACLE): // Ignore this cell update break; default: _matrix(row, column) = value; break; } } void Map::set(const Point& point, int value) { int pointRow = convertYToRow(point.getY()); int pointColumn = convertXToColumn(point.getX()); set(pointRow, pointColumn, value); } bool Map::isMismatch(int row, int column, int value, bool & isUnknown) { int previews_value = get(row, column); // For unknown values we do not care what is the new value if (previews_value == MAP_STATE_UNKNOWN) { isUnknown = true; return false; } isUnknown = false; // If they are not equals then this is a mismatch bool mismatch = previews_value != value; return mismatch; } bool Map::isMismatch(const Point& point, int value, bool & isUnknown) { // Convert x and y to row and column int pointRow = convertYToRow(point.getY()); int pointColumn = convertXToColumn(point.getX()); return isMismatch(pointRow, pointColumn, value, isUnknown); } // Print operator std::ostream& operator<<(ostream &os, const Map& map) { for (int i = 0; i < map._rows; i++) { for (int j = 0; j < map._columns; j++) { int value = map.get(i, j); switch (value) { case (MAP_STATE_CLEAR): os << " "; break; case (MAP_STATE_OBSTACLE): os << "█"; break; case (MAP_STATE_UNKNOWN): os << "░"; break; case (MAP_STATE_ROBOT): os << "*"; break; } } os << endl; } return os; } Map& Map::operator =(const Map& m) { _columns = m._columns; _resolution = m._resolution; _rows = m._rows; _matrix = m._matrix; return *this; } double Map::handleObstacles(const Point& initalPoint, const vector<Point>& obstacles) { unsigned int mismatchCount = 0; unsigned int currectCounter = 0; vector<Point> freePointsToFlush; set(initalPoint, MAP_STATE_CLEAR); set(_prev, MAP_STATE_CLEAR); _prev = initalPoint; for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it) { bool isNewPoint; const Point& obstaclePoint = *it; if (isMismatch(obstaclePoint, MAP_STATE_OBSTACLE, isNewPoint)) { mismatchCount++; } else if (!isNewPoint) { currectCounter++; } // Get intermediate points (the points between the robot and the obstacle) vector<Point> intermediatePoints; MathHelper::GetIntermediatePoints(initalPoint, obstaclePoint, MAP_INTERMEDIATE_POINT_DISTANCE, intermediatePoints); // Enumerate Intermediate Points, // Set each intermediate Point to 'CLEAR' map state for (std::vector<Point>::const_iterator it2 = intermediatePoints.begin(); it2 != intermediatePoints.end(); ++it2) { const Point& intermediatePoint = *it2; if (isMismatch(intermediatePoint, MAP_STATE_CLEAR, isNewPoint)) { mismatchCount++; } else if (!isNewPoint) { currectCounter++; } freePointsToFlush.push_back(intermediatePoint); } } for (std::vector<Point>::const_iterator it = obstacles.begin(); it != obstacles.end(); ++it) { set(*it, MAP_STATE_OBSTACLE); } for (std::vector<Point>::const_iterator it = freePointsToFlush.begin(); it != freePointsToFlush.end(); ++it) { set(*it, MAP_STATE_CLEAR); } if (mismatchCount == 0) return 1; set(_prev, MAP_STATE_ROBOT); return (double)currectCounter/(double)(currectCounter+mismatchCount); } double Map::handleObstacles(Robot& robot, const vector<Point>& obstacles) { double robotX = robot.getX(); double robotY = robot.getY(); Point initalPoint(robotX, robotY); double matchPercent = handleObstacles(initalPoint, obstacles); return matchPercent; } double Map::update(double x, double y, double yaw, const Laser& laser) { // Handle new Obstacles vector<Point> obstacles; laser.getObstacles(x, y, yaw, obstacles); Point initalPoint(x, y); double matchPercent = handleObstacles(initalPoint, obstacles); return matchPercent; } <|endoftext|>
<commit_before>#include "metperson.h" using namespace std; METPerson::METPerson(){ first_name = ""; last_name = ""; middle_name = ""; age = 21; sex = OTHER; social_security_number = "000-00-0000"; } METPerson::~METPerson(){ } METPerson::METPerson(string f, string l, string m, int a, GENDER g, string s){ first_name = f; last_name = l; middle_name = m; age = a; sex = g; social_security_number = s; } void METPerson::setFirstName(string a){ first_name = a; } void METPerson::setLastName(string a){ last_name = a; } void METPerson::setMiddleName(string a){ middle_name = a; } void METPerson::setAge(int a){ age = a; } void METPerson::setSex(GENDER a){ sex = a; } void METPerson::setSocial(string a){ social_security_number = a; } string METPerson::getFirstName(){ return first_name; } string METPerson::getLastName(){ return last_name; } string METPerson::getMiddleName(){ return middle_name; } int METPerson::getAge(){ return age; } GENDER METPerson::getSex(){ return sex; } string METPerson::getSocial(){ return social_security_number; } <commit_msg>Changed to camel case<commit_after>#include "metperson.h" using namespace std; METPerson::METPerson(){ firstName = ""; lastName = ""; middleName = ""; age = 21; sex = OTHER; socialSecurityNumber = "000-00-0000"; } METPerson::~METPerson(){ } METPerson::METPerson(string f, string l, string m, int a, GENDER g, string s){ firstName = f; lastName = l; middleName = m; age = a; sex = g; socialSecurityNumber = s; } void METPerson::setFirstName(string a){ firstName = a; } void METPerson::setLastName(string a){ lastName = a; } void METPerson::setMiddleName(string a){ middleName = a; } void METPerson::setAge(int a){ age = a; } void METPerson::setSex(GENDER a){ sex = a; } void METPerson::setSocial(string a){ socialSecurityNumber = a; } string METPerson::getFirstName(){ return firstName; } string METPerson::getLastName(){ return lastName; } string METPerson::getMiddleName(){ return middleName; } int METPerson::getAge(){ return age; } GENDER METPerson::getSex(){ return sex; } string METPerson::getSocial(){ return socialSecurityNumber; } <|endoftext|>
<commit_before>#include "SMU.h" #include "libsmu/libsmu.hpp" #include "Plot/PhosphorRender.h" #include "Plot/FloatBuffer.h" void registerTypes() { qmlRegisterType<SessionItem>(); qmlRegisterType<DeviceItem>(); qmlRegisterType<ChannelItem>(); qmlRegisterType<SignalItem>(); qmlRegisterType<ModeItem>(); qmlRegisterType<SrcItem>(); qmlRegisterType<PhosphorRender>("Plot", 1, 0, "PhosphorRender"); qmlRegisterType<FloatBuffer>("Plot", 1, 0, "FloatBuffer"); qRegisterMetaType<sample_t>("sample_t"); } SessionItem::SessionItem(): m_session(new Session), m_active(false), m_continuous(false), m_sample_rate(0), m_sample_count(0) { connect(this, &SessionItem::progress, this, &SessionItem::onProgress, Qt::QueuedConnection); connect(this, &SessionItem::finished, this, &SessionItem::onFinished, Qt::QueuedConnection); connect(this, &SessionItem::attached, this, &SessionItem::onAttached, Qt::QueuedConnection); connect(this, &SessionItem::detached, this, &SessionItem::onDetached, Qt::QueuedConnection); m_session->m_completion_callback = [this](unsigned status){ emit finished(status); }; m_session->m_progress_callback = [this](sample_t n) { emit progress(n); }; m_session->m_hotplug_attach_callback = [this](Device* device){ emit attached(device); }; m_session->m_hotplug_detach_callback = [this](Device* device){ emit detached(device); }; } SessionItem::~SessionItem() { Q_ASSERT(m_devices.size() == 0); } void SessionItem::openAllDevices() { m_session->update_available_devices(); for (auto i: m_session->m_available_devices) { auto dev = m_session->add_device(&*i); m_devices.append(new DeviceItem(this, dev)); } devicesChanged(); } void SessionItem::closeAllDevices() { qDebug() << "Closing devices"; m_session->cancel(); m_session->end(); QList<DeviceItem *> devices; m_devices.swap(devices); devicesChanged(); for (auto i: devices) { m_session->remove_device(i->m_device); delete i; } } void SessionItem::start(bool continuous) { if (m_devices.size() == 0) return; if (m_active) return; if (m_sample_rate == 0) return; m_continuous = continuous; m_active = true; activeChanged(); m_session->configure(m_sample_rate); // Configure buffers for (auto dev: m_devices) { for (auto chan: dev->m_channels) { dev->m_device->set_mode(chan->m_index, chan->m_mode); for (auto sig: chan->m_signals) { sig->m_buffer->setRate(1.0/m_sample_rate); sig->m_buffer->allocate(m_sample_count); if (m_continuous) { sig->m_signal->measure_callback([=](float d){ sig->m_buffer->shift(d); }); connect(sig->m_src, &SrcItem::changed, [=] { dev->m_device->lock(); sig->m_src->update(); dev->m_device->unlock(); }); } else { sig->m_signal->measure_buffer(sig->m_buffer->data(), m_sample_count); } sig->m_src->update(); } } } m_session->start(continuous ? 0 : m_sample_count); } void SessionItem::onAttached(Device *device) { auto dev = m_session->add_device(device); Q_UNUSED(dev); m_devices.append(new DeviceItem(this, device)); devicesChanged(); } void SessionItem::onDetached(Device* device){ if (m_active) { this->cancel(); } // wait for completion m_session->end(); m_session->remove_device(device); if ((int) m_session->m_devices.size() < m_devices.size()) { for (auto dev: m_devices) { if (dev->m_device == device) m_devices.removeOne(dev); } } m_session->destroy_available(device); devicesChanged(); } void SessionItem::cancel() { if (!m_active) { return; } m_session->cancel(); } void SessionItem::onFinished() { m_session->end(); m_active = false; activeChanged(); for (auto dev: m_devices) { for (auto chan: dev->m_channels) { for (auto sig: chan->m_signals) { disconnect(sig->m_src, &SrcItem::changed, 0, 0); if (!m_continuous) { sig->updateMeasurement(); } } } } } void SessionItem::onProgress(sample_t sample) { for (auto dev: m_devices) { for (auto chan: dev->m_channels) { for (auto sig: chan->m_signals) { if (m_continuous) { sig->m_buffer->continuousProgress(sample); } else { sig->m_buffer->sweepProgress(sample); } } } } } DeviceItem::DeviceItem(SessionItem* parent, Device* dev): QObject(parent), m_device(dev) { auto dev_info = dev->info(); for (unsigned ch_i=0; ch_i < dev_info->channel_count; ch_i++) { m_channels.append(new ChannelItem(this, dev, ch_i)); } } ChannelItem::ChannelItem(DeviceItem* parent, Device* dev, unsigned ch_i): QObject(parent), m_device(dev), m_index(ch_i), m_mode(0) { auto ch_info = dev->channel_info(ch_i); for (unsigned sig_i=0; sig_i < ch_info->signal_count; sig_i++) { auto sig = dev->signal(ch_i, sig_i); m_signals.append(new SignalItem(this, ch_i, sig)); } } SignalItem::SignalItem(ChannelItem* parent, int index, Signal* sig): QObject(parent), m_index(index), m_channel(parent), m_signal(sig), m_buffer(new FloatBuffer(this)), m_src(new SrcItem(this)), m_measurement(0.0) { auto sig_info = sig->info(); Q_UNUSED(sig_info); connect(m_channel, &ChannelItem::modeChanged, this, &SignalItem::onParentModeChanged); } void SignalItem::onParentModeChanged(int) { isOutputChanged(getIsOutput()); isInputChanged(getIsInput()); } void SignalItem::updateMeasurement(){ m_measurement = m_buffer->mean(); measurementChanged(m_measurement); } SrcItem::SrcItem(SignalItem* parent): QObject(parent), m_src("constant"), m_v1(0), m_v2(0), m_period(0), m_phase(0), m_duty(0.5), m_parent(parent) { connect(this, &SrcItem::srcChanged, [=]{ changed(); }); connect(this, &SrcItem::v1Changed, [=]{ changed(); }); connect(this, &SrcItem::v2Changed, [=]{ changed(); }); connect(this, &SrcItem::periodChanged, [=]{ changed(); }); connect(this, &SrcItem::phaseChanged, [=]{ changed(); }); connect(this, &SrcItem::dutyChanged, [=]{ changed(); }); } void SrcItem::update() { Src v = SRC_CONSTANT; if (m_src == "constant") v = SRC_CONSTANT; else if (m_src == "buffer") v = SRC_BUFFER; else if (m_src == "callback") v = SRC_CALLBACK; else if (m_src == "square") v = SRC_SQUARE; else if (m_src == "sawtooth") v = SRC_SAWTOOTH; else if (m_src == "stairstep") v = SRC_STAIRSTEP; else if (m_src == "sine") v = SRC_SINE; else if (m_src == "triangle") v = SRC_TRIANGLE; else return; m_parent->m_signal->m_src = v; m_parent->m_signal->m_src_v1 = m_v1; m_parent->m_signal->m_src_v2 = m_v2; m_parent->m_signal->m_src_period = m_period; m_parent->m_signal->m_src_phase = m_phase; m_parent->m_signal->m_src_duty = m_duty; } ModeItem::ModeItem() { } <commit_msg>that doesn't go here.<commit_after>#include "SMU.h" #include "libsmu/libsmu.hpp" #include "Plot/PhosphorRender.h" #include "Plot/FloatBuffer.h" void registerTypes() { qmlRegisterType<SessionItem>(); qmlRegisterType<DeviceItem>(); qmlRegisterType<ChannelItem>(); qmlRegisterType<SignalItem>(); qmlRegisterType<ModeItem>(); qmlRegisterType<SrcItem>(); qmlRegisterType<PhosphorRender>("Plot", 1, 0, "PhosphorRender"); qmlRegisterType<FloatBuffer>("Plot", 1, 0, "FloatBuffer"); qRegisterMetaType<sample_t>("sample_t"); } SessionItem::SessionItem(): m_session(new Session), m_active(false), m_continuous(false), m_sample_rate(0), m_sample_count(0) { connect(this, &SessionItem::progress, this, &SessionItem::onProgress, Qt::QueuedConnection); connect(this, &SessionItem::finished, this, &SessionItem::onFinished, Qt::QueuedConnection); connect(this, &SessionItem::attached, this, &SessionItem::onAttached, Qt::QueuedConnection); connect(this, &SessionItem::detached, this, &SessionItem::onDetached, Qt::QueuedConnection); m_session->m_completion_callback = [this](unsigned status){ emit finished(status); }; m_session->m_progress_callback = [this](sample_t n) { emit progress(n); }; m_session->m_hotplug_attach_callback = [this](Device* device){ emit attached(device); }; m_session->m_hotplug_detach_callback = [this](Device* device){ emit detached(device); }; } SessionItem::~SessionItem() { Q_ASSERT(m_devices.size() == 0); } void SessionItem::openAllDevices() { m_session->update_available_devices(); for (auto i: m_session->m_available_devices) { auto dev = m_session->add_device(&*i); m_devices.append(new DeviceItem(this, dev)); } devicesChanged(); } void SessionItem::closeAllDevices() { qDebug() << "Closing devices"; m_session->cancel(); m_session->end(); QList<DeviceItem *> devices; m_devices.swap(devices); devicesChanged(); for (auto i: devices) { m_session->remove_device(i->m_device); delete i; } } void SessionItem::start(bool continuous) { if (m_devices.size() == 0) return; if (m_active) return; if (m_sample_rate == 0) return; m_continuous = continuous; m_active = true; activeChanged(); m_session->configure(m_sample_rate); // Configure buffers for (auto dev: m_devices) { for (auto chan: dev->m_channels) { dev->m_device->set_mode(chan->m_index, chan->m_mode); for (auto sig: chan->m_signals) { sig->m_buffer->setRate(1.0/m_sample_rate); sig->m_buffer->allocate(m_sample_count); if (m_continuous) { sig->m_signal->measure_callback([=](float d){ sig->m_buffer->shift(d); }); connect(sig->m_src, &SrcItem::changed, [=] { dev->m_device->lock(); sig->m_src->update(); dev->m_device->unlock(); }); } else { sig->m_signal->measure_buffer(sig->m_buffer->data(), m_sample_count); } sig->m_src->update(); } } } m_session->start(continuous ? 0 : m_sample_count); } void SessionItem::onAttached(Device *device) { auto dev = m_session->add_device(device); Q_UNUSED(dev); m_devices.append(new DeviceItem(this, device)); devicesChanged(); } void SessionItem::onDetached(Device* device){ if (m_active) { this->cancel(); } // wait for completion m_session->end(); m_session->remove_device(device); if ((int) m_session->m_devices.size() < m_devices.size()) { for (auto dev: m_devices) { if (dev->m_device == device) m_devices.removeOne(dev); } } devicesChanged(); } void SessionItem::cancel() { if (!m_active) { return; } m_session->cancel(); } void SessionItem::onFinished() { m_session->end(); m_active = false; activeChanged(); for (auto dev: m_devices) { for (auto chan: dev->m_channels) { for (auto sig: chan->m_signals) { disconnect(sig->m_src, &SrcItem::changed, 0, 0); if (!m_continuous) { sig->updateMeasurement(); } } } } } void SessionItem::onProgress(sample_t sample) { for (auto dev: m_devices) { for (auto chan: dev->m_channels) { for (auto sig: chan->m_signals) { if (m_continuous) { sig->m_buffer->continuousProgress(sample); } else { sig->m_buffer->sweepProgress(sample); } } } } } DeviceItem::DeviceItem(SessionItem* parent, Device* dev): QObject(parent), m_device(dev) { auto dev_info = dev->info(); for (unsigned ch_i=0; ch_i < dev_info->channel_count; ch_i++) { m_channels.append(new ChannelItem(this, dev, ch_i)); } } ChannelItem::ChannelItem(DeviceItem* parent, Device* dev, unsigned ch_i): QObject(parent), m_device(dev), m_index(ch_i), m_mode(0) { auto ch_info = dev->channel_info(ch_i); for (unsigned sig_i=0; sig_i < ch_info->signal_count; sig_i++) { auto sig = dev->signal(ch_i, sig_i); m_signals.append(new SignalItem(this, ch_i, sig)); } } SignalItem::SignalItem(ChannelItem* parent, int index, Signal* sig): QObject(parent), m_index(index), m_channel(parent), m_signal(sig), m_buffer(new FloatBuffer(this)), m_src(new SrcItem(this)), m_measurement(0.0) { auto sig_info = sig->info(); Q_UNUSED(sig_info); connect(m_channel, &ChannelItem::modeChanged, this, &SignalItem::onParentModeChanged); } void SignalItem::onParentModeChanged(int) { isOutputChanged(getIsOutput()); isInputChanged(getIsInput()); } void SignalItem::updateMeasurement(){ m_measurement = m_buffer->mean(); measurementChanged(m_measurement); } SrcItem::SrcItem(SignalItem* parent): QObject(parent), m_src("constant"), m_v1(0), m_v2(0), m_period(0), m_phase(0), m_duty(0.5), m_parent(parent) { connect(this, &SrcItem::srcChanged, [=]{ changed(); }); connect(this, &SrcItem::v1Changed, [=]{ changed(); }); connect(this, &SrcItem::v2Changed, [=]{ changed(); }); connect(this, &SrcItem::periodChanged, [=]{ changed(); }); connect(this, &SrcItem::phaseChanged, [=]{ changed(); }); connect(this, &SrcItem::dutyChanged, [=]{ changed(); }); } void SrcItem::update() { Src v = SRC_CONSTANT; if (m_src == "constant") v = SRC_CONSTANT; else if (m_src == "buffer") v = SRC_BUFFER; else if (m_src == "callback") v = SRC_CALLBACK; else if (m_src == "square") v = SRC_SQUARE; else if (m_src == "sawtooth") v = SRC_SAWTOOTH; else if (m_src == "stairstep") v = SRC_STAIRSTEP; else if (m_src == "sine") v = SRC_SINE; else if (m_src == "triangle") v = SRC_TRIANGLE; else return; m_parent->m_signal->m_src = v; m_parent->m_signal->m_src_v1 = m_v1; m_parent->m_signal->m_src_v2 = m_v2; m_parent->m_signal->m_src_period = m_period; m_parent->m_signal->m_src_phase = m_phase; m_parent->m_signal->m_src_duty = m_duty; } ModeItem::ModeItem() { } <|endoftext|>
<commit_before>// Adobe Leaked Email Checker // Date: December 2013 // Author: Jervis Muindi // Standard Lib Header #include <iostream> #include "common/strings/strutil.h" #include "common/log/log.h" #include "third_party/leveldb/leveldb.h" #include "alec.h" using namespace std; namespace alec { bool Credential::operator==(const Credential& other) const { return this->email == other.email && this->hash == other.hash && this->username == other.username && this->rec_id == other.rec_id && this->hint == other.hint; } string Credential::ToString() const { string result; result += "Email: '" + email + "'\n"; result += "Username: '" + username + "'\n"; result += "Record ID: " + rec_id + "\n"; result += "Password Hint: '" + hint + "'\n"; return result; } ostream& operator<<(ostream &out, const Credential& other) { string result = other.ToString(); out << result; return out; } CredentialReader::CredentialReader(const string& filename) : filename_(filename), file_reader_(filename) { LOG(INFO) << "Cred reader initd"; } bool CredentialReader::Done() { return file_reader_.Done(); } bool CredentialReader::NextCredential(Credential *output) { if (output == NULL) { LOG(ERROR) << "Given a NULL output pointer"; return false; } if (Done()) { return false; } Credential cred; // Find a non-empty credentials line bool line_empty; string line; do { line = file_reader_.line(); line_empty = line.empty(); if (line_empty) { file_reader_.Next(); } } while (line_empty); if (!ParseLine(line, &cred)) { LOG(ERROR) << "Failed to Parse Line: '" << line << "'"; return false; } else { *output = cred; if (!file_reader_.Done()) { file_reader_.Next(); } return true; } } // static class method bool CredentialReader::ParseLine(const string& line, Credential* result) { bool warnings_occurred = false; if (result == NULL) { LOG(ERROR) << "Given NULL result pointer"; return false; } // line mostly looks like: // 000000010-|--|-person10@dls.net-|-IMj2ZmZchtNM=-|-internet|-- // The format is : // <user_id> | <adobe_username> | <email address> | <password hash> | <password hint> // which was obtained from a SOPHOS analysis: http://goo.gl/xIEZSe vector<StringPiece> pieces = strings::Split(line, "|"); int i = 0; for (auto& piece : pieces) { VLOG(2) << "piece " << i << ": " << piece; ++i; } // Sanity check if expected fields are present static const int kExpectedPieces = 6; if (pieces.size() != kExpectedPieces) { LOG(WARNING) << "Expected line to have " << kExpectedPieces << " '|'-separates pieces but got " << pieces.size() << ". Credentials may be incorrectly parsed.\n" << "\nLine:" << line; warnings_occurred = true; } // Default expected indexes into the 'pieces' string vector int rec_id_idx = 0, username_idx = 1, email_idx = 2, hash_idx = 3, hint_idx = 4; // Find the max valid index value const int kMaxIdx = pieces.size() - 1; // There's a special case when 'line' is split into exactly // 7 pieces. In this scenario, the email is split into // separate username and domain parts. This looks like this: // 115985151-|--|-kadja_83|@yahoo.es-|-CWWWYFjjxa/ioxG6CatHBw==-|-dra|-- bool email_special_case = pieces.size() == 7; if (email_special_case) { // The hash/hint fields are one away from their normal/expected location ++hash_idx; ++hint_idx; } string rec_id = rec_id_idx <= kMaxIdx ? pieces[rec_id_idx].as_string() : "NA"; // record id has form "<rec_id>-", so chop off the trailing '-' character rec_id = rec_id.substr(0, rec_id.size() - 1); // username has form "-<username>-", so chop off the leading/trailing '-' character. string username = username_idx <= kMaxIdx ? pieces[username_idx].as_string() : "NA"; username = username.substr(1, username.size() - 2); string email = email_idx <= kMaxIdx ? pieces[email_idx].as_string() : "NA"; // email has form "-<email>-", so chop of the leading and trailing '-' character. email = email.substr(1, email.size() - 2); if (email_special_case) { string domain = pieces[email_idx+1].as_string(); // Domain looks like: '@yahoo.es-', so get rid of trailing '-' domain = domain.substr(0, domain.size() - 1); email += domain; } string hash = hash_idx <= kMaxIdx ? pieces[hash_idx].as_string() : "NA"; // hash has form "-<hash>-", so chop of the leading and trailing '-' character. hash = hash.substr(1, hash.size() - 2); string hint = hint_idx <= kMaxIdx ? pieces[hint_idx].as_string() : "NA"; // hint has form "-<hint>", so just chop of the leading '-' character hint = hint.substr(1); // Okay, save the parsed result result->email = email; result->username = username; result->rec_id = rec_id; result->hint = hint; result->hash = hash; // Print out the Parsed Credential object if warning occured if (warnings_occurred) { LOG(WARNING) << "Parsed Credential is\n" << *result << "\n---------"; } return true; } CredentialReader::~CredentialReader() { ; } static string NumberFormat(long n) { stringstream ss; locale l(""); ss.imbue(l); ss << fixed << n; return ss.str(); } bool CredentialProcessor::GenerateDiskHashTable(StringPiece filename) { // Open a LevelDB Database leveldb::DB* db; leveldb::Options options; leveldb::Status status; options.create_if_missing = true; const string& filename_string = filename.ToString(); status = leveldb::DB::Open(options, filename_string, &db); if (!status.ok()) { LOG(ERROR) << "Failed to Open LevelDB Database: " << filename_string ; return false; } // Read and save all credential records Credential cred; bool success_read; int count = 0, failed_reads = 0, failed_writes = 0; while (!cred_reader_->Done()) { LOG_EVERY_N(INFO, 100000) << "Processing Record #" << NumberFormat(count) << " ..."; success_read = cred_reader_->NextCredential(&cred); if (!success_read) { ++failed_reads; LOG(WARNING) << "Failed to obtain credential record # " << count << ". Total Read Failures now at: " << failed_reads; ++count; continue; } // Save the record to disk string key = strings::LowerString(cred.email); char *cred_data = reinterpret_cast<char*>(&cred); int cred_size = sizeof(cred); leveldb::Slice value(cred_data, cred_size); status = db->Put(leveldb::WriteOptions(), key, value); if (!status.ok()) { ++failed_writes; LOG(WARNING) << "Failed to save credential record # " << count << ". Total Write Failures now at: " << failed_writes; } ++count; } // Close the Database delete db; return true; } } // alec namespace <commit_msg>Fix 2 issues related to special_email_case. 1) it was possible that even with 7 pieces email was not divided into 2 parts. 2) The '@' sign could be in any one of the two pieces, so need to avoid chopping it off.<commit_after>// Adobe Leaked Email Checker // Date: December 2013 // Author: Jervis Muindi // Standard Lib Header #include <iostream> #include "common/strings/strutil.h" #include "common/log/log.h" #include "third_party/leveldb/leveldb.h" #include "alec.h" using namespace std; namespace alec { bool Credential::operator==(const Credential& other) const { return this->email == other.email && this->hash == other.hash && this->username == other.username && this->rec_id == other.rec_id && this->hint == other.hint; } string Credential::ToString() const { string result; result += "Email: '" + email + "'\n"; result += "Username: '" + username + "'\n"; result += "Record ID: " + rec_id + "\n"; result += "Password Hint: '" + hint + "'\n"; return result; } ostream& operator<<(ostream &out, const Credential& other) { string result = other.ToString(); out << result; return out; } CredentialReader::CredentialReader(const string& filename) : filename_(filename), file_reader_(filename) { LOG(INFO) << "Cred reader initd"; } bool CredentialReader::Done() { return file_reader_.Done(); } bool CredentialReader::NextCredential(Credential *output) { if (output == NULL) { LOG(ERROR) << "Given a NULL output pointer"; return false; } if (Done()) { return false; } Credential cred; // Find a non-empty credentials line bool line_empty; string line; do { line = file_reader_.line(); line_empty = line.empty(); if (line_empty) { file_reader_.Next(); } } while (line_empty); if (!ParseLine(line, &cred)) { LOG(ERROR) << "Failed to Parse Line: '" << line << "'"; return false; } else { *output = cred; if (!file_reader_.Done()) { file_reader_.Next(); } return true; } } // Returns a copy of the string 's' without the // leading and trailing '-' where applicable static string RemoveLeadingTrailingMinus(string s) { int first_idx = 0, last_idx = s.size() - 1; char minus = '-'; bool leading_minus = s[first_idx] == minus; bool trailing_minus = s[last_idx] == minus; if (leading_minus && trailing_minus) { return s.substr(1, s.size() - 2); } else if (leading_minus) { return s.substr(1, s.size() - 1 ); } else if (trailing_minus) { return s.substr(0, s.size() - 1); } else { return s; } } // static class method bool CredentialReader::ParseLine(const string& line, Credential* result) { bool warnings_occurred = false; if (result == NULL) { LOG(ERROR) << "Given NULL result pointer"; return false; } // line mostly looks like: // 000000010-|--|-person10@dls.net-|-IMj2ZmZchtNM=-|-internet|-- // The format is : // <user_id> | <adobe_username> | <email address> | <password hash> | <password hint> // which was obtained from a SOPHOS analysis: http://goo.gl/xIEZSe vector<StringPiece> pieces = strings::Split(line, "|"); int i = 0; for (auto& piece : pieces) { VLOG(2) << "piece " << i << ": " << piece; ++i; } // Sanity check if expected fields are present static const int kExpectedPieces = 6; if (pieces.size() != kExpectedPieces) { LOG(WARNING) << "Expected line to have " << kExpectedPieces << " '|'-separates pieces but got " << pieces.size() << ". Credentials may be incorrectly parsed.\n" << "\nLine:" << line; warnings_occurred = true; } // Default expected indexes into the 'pieces' string vector int rec_id_idx = 0, username_idx = 1, email_idx = 2, hash_idx = 3, hint_idx = 4; // Find the max valid index value const int kMaxIdx = pieces.size() - 1; // There's a special case when 'line' is split into exactly // 7 pieces. In this scenario, the email is split into // separate username and domain parts. This looks like this: // 115985151-|--|-kadja_83|@yahoo.es-|-CWWWYFjjxa/ioxG6CatHBw==-|-dra|-- bool email_special_case = pieces.size() == 7; // It's also possible that the email is not split, even when we have 7 pieces. E.g. // 103228954-|--|-augihol@yahoo.com|-|-0lWluyxrPejioxG6CatHBw==-|-|-- int domain_idx = email_idx + 1; if (domain_idx <= kMaxIdx) { string domain = pieces[domain_idx].as_string(); // A valid email domain is assumed to contain at least one "." character // If this is not the case, then we're not in our email special case mode. if (domain.find(".") == string::npos) { email_special_case = false; } } if (email_special_case) { // The hash/hint fields are one away from their normal/expected location ++hash_idx; ++hint_idx; } string rec_id = rec_id_idx <= kMaxIdx ? pieces[rec_id_idx].as_string() : "NA"; // record id has form "<rec_id>-", so chop off the trailing '-' character rec_id = RemoveLeadingTrailingMinus(rec_id); // username has form "-<username>-", so chop off the leading/trailing '-' character. string username = username_idx <= kMaxIdx ? pieces[username_idx].as_string() : "NA"; username = RemoveLeadingTrailingMinus(username); string email = email_idx <= kMaxIdx ? pieces[email_idx].as_string() : "NA"; // email has form "-<email>-", so chop of the leading and trailing '-' character. email = RemoveLeadingTrailingMinus(email); if (email_special_case) { string domain = pieces[email_idx+1].as_string(); // Domain looks like: '@yahoo.es-', so get rid of trailing '-' domain = RemoveLeadingTrailingMinus(domain); email += domain; } string hash = hash_idx <= kMaxIdx ? pieces[hash_idx].as_string() : "NA"; // hash has form "-<hash>-", so chop of the leading and trailing '-' character. hash = RemoveLeadingTrailingMinus(hash); string hint = hint_idx <= kMaxIdx ? pieces[hint_idx].as_string() : "NA"; // hint has form "-<hint>", so just chop of the leading '-' character hint = RemoveLeadingTrailingMinus(hint); // Okay, save the parsed result result->email = email; result->username = username; result->rec_id = rec_id; result->hint = hint; result->hash = hash; // Print out the Parsed Credential object if warning occured if (warnings_occurred) { LOG(WARNING) << "Parsed Credential is\n" << *result << "\n---------"; } return true; } CredentialReader::~CredentialReader() { ; } static string NumberFormat(long n) { stringstream ss; locale l(""); ss.imbue(l); ss << fixed << n; return ss.str(); } bool CredentialProcessor::GenerateDiskHashTable(StringPiece filename) { // Open a LevelDB Database leveldb::DB* db; leveldb::Options options; leveldb::Status status; options.create_if_missing = true; const string& filename_string = filename.ToString(); status = leveldb::DB::Open(options, filename_string, &db); if (!status.ok()) { LOG(ERROR) << "Failed to Open LevelDB Database: " << filename_string ; return false; } // Read and save all credential records Credential cred; bool success_read; int count = 0, failed_reads = 0, failed_writes = 0; while (!cred_reader_->Done()) { LOG_EVERY_N(INFO, 100000) << "Processing Record #" << NumberFormat(count) << " ..."; success_read = cred_reader_->NextCredential(&cred); if (!success_read) { ++failed_reads; LOG(WARNING) << "Failed to obtain credential record # " << count << ". Total Read Failures now at: " << failed_reads; ++count; continue; } // Save the record to disk string key = strings::LowerString(cred.email); char *cred_data = reinterpret_cast<char*>(&cred); int cred_size = sizeof(cred); leveldb::Slice value(cred_data, cred_size); status = db->Put(leveldb::WriteOptions(), key, value); if (!status.ok()) { ++failed_writes; LOG(WARNING) << "Failed to save credential record # " << count << ". Total Write Failures now at: " << failed_writes; } ++count; } // Close the Database delete db; return true; } } // alec namespace <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_SeriesToAxis.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2007-06-11 14:58:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "tp_SeriesToAxis.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "chartview/ChartSfxItemIds.hxx" #include "NoWarningThisInCTOR.hxx" // header for class SfxBoolItem #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif // header for SfxInt32Item #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif //............................................................................. namespace chart { //............................................................................. SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) : SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs), aGrpAxis(this, SchResId(GRP_OPT_AXIS)), aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)), aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)), aGrpBar(this, SchResId(GB_BAR)), aFTGap(this,SchResId(FT_GAP)), aMTGap(this,SchResId(MT_GAP)), aFTOverlap(this,SchResId(FT_OVERLAP)), aMTOverlap(this,SchResId(MT_OVERLAP)), aCBConnect(this,SchResId(CB_CONNECTOR)) { FreeResource(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SchOptionTabPage::~SchOptionTabPage() { } /************************************************************************* |* |* Erzeugung |* \*************************************************************************/ SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs) { return new SchOptionTabPage(pWindow, rOutAttrs); } /************************************************************************* |* |* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen |* \*************************************************************************/ BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs) { if(aRbtAxis2.IsChecked()) rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y)); else rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y)); if(aMTGap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,aMTGap.GetValue())); if(aMTOverlap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,aMTOverlap.GetValue())); if(aCBConnect.IsVisible()) rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked())); return TRUE; } /************************************************************************* |* |* Initialisierung |* \*************************************************************************/ void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs) { const SfxPoolItem *pPoolItem = NULL; aRbtAxis1.Check(TRUE); aRbtAxis2.Check(FALSE); if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET) { long nVal=((const SfxInt32Item*)pPoolItem)->GetValue(); if(nVal==CHART_AXIS_SECONDARY_Y) { aRbtAxis2.Check(TRUE); aRbtAxis1.Check(FALSE); } } long nTmp; if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTGap.SetValue(nTmp); } else { aMTGap.Show(FALSE); aFTGap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTOverlap.SetValue(nTmp); } else { aMTOverlap.Show(FALSE); aFTOverlap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET) { BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue(); aCBConnect.Check(bCheck); } else { aCBConnect.Show(FALSE); } } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS chart07 (1.7.8); FILE MERGED 2007/07/10 11:57:29 bm 1.7.8.1: #i69281# warnings removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tp_SeriesToAxis.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:38:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "tp_SeriesToAxis.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "chartview/ChartSfxItemIds.hxx" #include "NoWarningThisInCTOR.hxx" // header for class SfxBoolItem #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif // header for SfxInt32Item #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif //............................................................................. namespace chart { //............................................................................. SchOptionTabPage::SchOptionTabPage(Window* pWindow,const SfxItemSet& rInAttrs) : SfxTabPage(pWindow, SchResId(TP_OPTIONS), rInAttrs), aGrpAxis(this, SchResId(GRP_OPT_AXIS)), aRbtAxis1(this,SchResId(RBT_OPT_AXIS_1)), aRbtAxis2(this,SchResId(RBT_OPT_AXIS_2)), aGrpBar(this, SchResId(GB_BAR)), aFTGap(this,SchResId(FT_GAP)), aMTGap(this,SchResId(MT_GAP)), aFTOverlap(this,SchResId(FT_OVERLAP)), aMTOverlap(this,SchResId(MT_OVERLAP)), aCBConnect(this,SchResId(CB_CONNECTOR)) { FreeResource(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SchOptionTabPage::~SchOptionTabPage() { } /************************************************************************* |* |* Erzeugung |* \*************************************************************************/ SfxTabPage* SchOptionTabPage::Create(Window* pWindow,const SfxItemSet& rOutAttrs) { return new SchOptionTabPage(pWindow, rOutAttrs); } /************************************************************************* |* |* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen |* \*************************************************************************/ BOOL SchOptionTabPage::FillItemSet(SfxItemSet& rOutAttrs) { if(aRbtAxis2.IsChecked()) rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_SECONDARY_Y)); else rOutAttrs.Put(SfxInt32Item(SCHATTR_AXIS,CHART_AXIS_PRIMARY_Y)); if(aMTGap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_GAPWIDTH,static_cast< sal_Int32 >( aMTGap.GetValue()))); if(aMTOverlap.IsVisible()) rOutAttrs.Put(SfxInt32Item(SCHATTR_BAR_OVERLAP,static_cast< sal_Int32 >( aMTOverlap.GetValue()))); if(aCBConnect.IsVisible()) rOutAttrs.Put(SfxBoolItem(SCHATTR_BAR_CONNECT,aCBConnect.IsChecked())); return TRUE; } /************************************************************************* |* |* Initialisierung |* \*************************************************************************/ void SchOptionTabPage::Reset(const SfxItemSet& rInAttrs) { const SfxPoolItem *pPoolItem = NULL; aRbtAxis1.Check(TRUE); aRbtAxis2.Check(FALSE); if (rInAttrs.GetItemState(SCHATTR_AXIS,TRUE, &pPoolItem) == SFX_ITEM_SET) { long nVal=((const SfxInt32Item*)pPoolItem)->GetValue(); if(nVal==CHART_AXIS_SECONDARY_Y) { aRbtAxis2.Check(TRUE); aRbtAxis1.Check(FALSE); } } long nTmp; if (rInAttrs.GetItemState(SCHATTR_BAR_GAPWIDTH, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTGap.SetValue(nTmp); } else { aMTGap.Show(FALSE); aFTGap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_OVERLAP, TRUE, &pPoolItem) == SFX_ITEM_SET) { nTmp = (long)((const SfxInt32Item*)pPoolItem)->GetValue(); aMTOverlap.SetValue(nTmp); } else { aMTOverlap.Show(FALSE); aFTOverlap.Show(FALSE); } if (rInAttrs.GetItemState(SCHATTR_BAR_CONNECT, TRUE, &pPoolItem) == SFX_ITEM_SET) { BOOL bCheck = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue(); aCBConnect.Check(bCheck); } else { aCBConnect.Show(FALSE); } } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * 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/>. */ #pragma once #include "exceptions/exceptions.hh" #include "unimplemented.hh" #include "timestamp.hh" #include "db_clock.hh" #include "database.hh" #include "auth/authenticated_user.hh" #include "auth/authenticator.hh" #include "auth/permission.hh" #include "tracing/tracing.hh" #include "tracing/trace_state.hh" namespace service { /** * State related to a client connection. */ class client_state { private: sstring _keyspace; tracing::trace_state_ptr _trace_state_ptr; lw_shared_ptr<utils::UUID> _tracing_session_id; #if 0 private static final Logger logger = LoggerFactory.getLogger(ClientState.class); public static final SemanticVersion DEFAULT_CQL_VERSION = org.apache.cassandra.cql3.QueryProcessor.CQL_VERSION; private static final Set<IResource> READABLE_SYSTEM_RESOURCES = new HashSet<>(); private static final Set<IResource> PROTECTED_AUTH_RESOURCES = new HashSet<>(); static { // We want these system cfs to be always readable to authenticated users since many tools rely on them // (nodetool, cqlsh, bulkloader, etc.) for (String cf : Iterables.concat(Arrays.asList(SystemKeyspace.LOCAL, SystemKeyspace.PEERS), LegacySchemaTables.ALL)) READABLE_SYSTEM_RESOURCES.add(DataResource.columnFamily(SystemKeyspace.NAME, cf)); PROTECTED_AUTH_RESOURCES.addAll(DatabaseDescriptor.getAuthenticator().protectedResources()); PROTECTED_AUTH_RESOURCES.addAll(DatabaseDescriptor.getAuthorizer().protectedResources()); } // Current user for the session private volatile AuthenticatedUser user; private volatile String keyspace; #endif ::shared_ptr<auth::authenticated_user> _user; // isInternal is used to mark ClientState as used by some internal component // that should have an ability to modify system keyspace. bool _is_internal; bool _is_thrift; // The biggest timestamp that was returned by getTimestamp/assigned to a query api::timestamp_type _last_timestamp_micros = 0; bool _dirty = false; // Address of a client socket_address _remote_address; public: struct internal_tag {}; struct external_tag {}; void create_tracing_session(tracing::trace_type type, bool write_on_close) { _trace_state_ptr = tracing::tracing::get_local_tracing_instance().create_session(type, write_on_close); // store a session ID separately because its lifetime is not always // coupled with the trace_state because the trace_state may already be // destroyed when we need a session ID for a response to a client (e.g. // in case of errors). if (_trace_state_ptr) { _tracing_session_id = make_lw_shared<utils::UUID>(_trace_state_ptr->get_session_id()); } } tracing::trace_state_ptr& get_trace_state() { return _trace_state_ptr; } lw_shared_ptr<utils::UUID>& tracing_session_id_ptr() { return _tracing_session_id; } client_state(external_tag, const socket_address& remote_address = socket_address(), bool thrift = false) : _is_internal(false) , _is_thrift(thrift) , _remote_address(remote_address) { if (!auth::authenticator::get().require_authentication()) { _user = ::make_shared<auth::authenticated_user>(); } } gms::inet_address get_client_address() const { return gms::inet_address(_remote_address); } client_state(internal_tag) : _keyspace("system"), _is_internal(true), _is_thrift(false) {} void merge(const client_state& other); bool is_thrift() const { return _is_thrift; } bool is_internal() const { return _is_internal; } /** * @return a ClientState object for internal C* calls (not limited by any kind of auth). */ static client_state for_internal_calls() { return client_state(internal_tag()); } /** * @return a ClientState object for external clients (thrift/native protocol users). */ static client_state for_external_calls() { return client_state(external_tag()); } static client_state for_external_thrift_calls() { return client_state(external_tag(), socket_address(), true); } /** * This clock guarantees that updates for the same ClientState will be ordered * in the sequence seen, even if multiple updates happen in the same millisecond. */ api::timestamp_type get_timestamp() { auto current = api::new_timestamp(); auto last = _last_timestamp_micros; auto result = last >= current ? last + 1 : current; _last_timestamp_micros = result; return result; } #if 0 /** * Can be use when a timestamp has been assigned by a query, but that timestamp is * not directly one returned by getTimestamp() (see SP.beginAndRepairPaxos()). * This ensure following calls to getTimestamp() will return a timestamp strictly * greated than the one provided to this method. */ public void updateLastTimestamp(long tstampMicros) { while (true) { long last = lastTimestampMicros.get(); if (tstampMicros <= last || lastTimestampMicros.compareAndSet(last, tstampMicros)) return; } } public SocketAddress getRemoteAddress() { return remoteAddress; } #endif const sstring& get_raw_keyspace() const { return _keyspace; } public: void set_keyspace(seastar::sharded<database>& db, sstring keyspace) { // Skip keyspace validation for non-authenticated users. Apparently, some client libraries // call set_keyspace() before calling login(), and we have to handle that. if (_user && !db.local().has_keyspace(keyspace)) { throw exceptions::invalid_request_exception(sprint("Keyspace '%s' does not exist", keyspace)); } _keyspace = keyspace; _dirty = true; } const sstring& get_keyspace() const { if (_keyspace.empty()) { throw exceptions::invalid_request_exception("No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename"); } return _keyspace; } /** * Sets active user. Does _not_ validate anything */ void set_login(::shared_ptr<auth::authenticated_user>); /** * Attempts to validate login for the set user. */ future<> check_user_exists(); future<> has_all_keyspaces_access(auth::permission) const; future<> has_keyspace_access(const sstring&, auth::permission) const; future<> has_column_family_access(const sstring&, const sstring&, auth::permission) const; future<> has_schema_access(const schema& s, auth::permission p) const; private: future<> has_access(const sstring&, auth::permission, auth::data_resource) const; future<bool> check_has_permission(auth::permission, auth::data_resource) const; public: future<> ensure_has_permission(auth::permission, auth::data_resource) const; void validate_login() const; void ensure_not_anonymous() const throw(exceptions::unauthorized_exception); #if 0 public void ensureIsSuper(String message) throws UnauthorizedException { if (DatabaseDescriptor.getAuthenticator().requireAuthentication() && (user == null || !user.isSuper())) throw new UnauthorizedException(message); } private static void validateKeyspace(String keyspace) throws InvalidRequestException { if (keyspace == null) throw new InvalidRequestException("You have not set a keyspace for this session"); } #endif ::shared_ptr<auth::authenticated_user> user() const { return _user; } #if 0 public static SemanticVersion[] getCQLSupportedVersion() { return new SemanticVersion[]{ QueryProcessor.CQL_VERSION }; } private Set<Permission> authorize(IResource resource) { // AllowAllAuthorizer or manually disabled caching. if (Auth.permissionsCache == null) return DatabaseDescriptor.getAuthorizer().authorize(user, resource); try { return Auth.permissionsCache.get(Pair.create(user, resource)); } catch (ExecutionException e) { throw new RuntimeException(e); } } #endif }; } <commit_msg>service::client_state: add a const version of get_trace_state()<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * 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/>. */ #pragma once #include "exceptions/exceptions.hh" #include "unimplemented.hh" #include "timestamp.hh" #include "db_clock.hh" #include "database.hh" #include "auth/authenticated_user.hh" #include "auth/authenticator.hh" #include "auth/permission.hh" #include "tracing/tracing.hh" #include "tracing/trace_state.hh" namespace service { /** * State related to a client connection. */ class client_state { private: sstring _keyspace; tracing::trace_state_ptr _trace_state_ptr; lw_shared_ptr<utils::UUID> _tracing_session_id; #if 0 private static final Logger logger = LoggerFactory.getLogger(ClientState.class); public static final SemanticVersion DEFAULT_CQL_VERSION = org.apache.cassandra.cql3.QueryProcessor.CQL_VERSION; private static final Set<IResource> READABLE_SYSTEM_RESOURCES = new HashSet<>(); private static final Set<IResource> PROTECTED_AUTH_RESOURCES = new HashSet<>(); static { // We want these system cfs to be always readable to authenticated users since many tools rely on them // (nodetool, cqlsh, bulkloader, etc.) for (String cf : Iterables.concat(Arrays.asList(SystemKeyspace.LOCAL, SystemKeyspace.PEERS), LegacySchemaTables.ALL)) READABLE_SYSTEM_RESOURCES.add(DataResource.columnFamily(SystemKeyspace.NAME, cf)); PROTECTED_AUTH_RESOURCES.addAll(DatabaseDescriptor.getAuthenticator().protectedResources()); PROTECTED_AUTH_RESOURCES.addAll(DatabaseDescriptor.getAuthorizer().protectedResources()); } // Current user for the session private volatile AuthenticatedUser user; private volatile String keyspace; #endif ::shared_ptr<auth::authenticated_user> _user; // isInternal is used to mark ClientState as used by some internal component // that should have an ability to modify system keyspace. bool _is_internal; bool _is_thrift; // The biggest timestamp that was returned by getTimestamp/assigned to a query api::timestamp_type _last_timestamp_micros = 0; bool _dirty = false; // Address of a client socket_address _remote_address; public: struct internal_tag {}; struct external_tag {}; void create_tracing_session(tracing::trace_type type, bool write_on_close) { _trace_state_ptr = tracing::tracing::get_local_tracing_instance().create_session(type, write_on_close); // store a session ID separately because its lifetime is not always // coupled with the trace_state because the trace_state may already be // destroyed when we need a session ID for a response to a client (e.g. // in case of errors). if (_trace_state_ptr) { _tracing_session_id = make_lw_shared<utils::UUID>(_trace_state_ptr->get_session_id()); } } tracing::trace_state_ptr& get_trace_state() { return _trace_state_ptr; } const tracing::trace_state_ptr& get_trace_state() const { return _trace_state_ptr; } lw_shared_ptr<utils::UUID>& tracing_session_id_ptr() { return _tracing_session_id; } client_state(external_tag, const socket_address& remote_address = socket_address(), bool thrift = false) : _is_internal(false) , _is_thrift(thrift) , _remote_address(remote_address) { if (!auth::authenticator::get().require_authentication()) { _user = ::make_shared<auth::authenticated_user>(); } } gms::inet_address get_client_address() const { return gms::inet_address(_remote_address); } client_state(internal_tag) : _keyspace("system"), _is_internal(true), _is_thrift(false) {} void merge(const client_state& other); bool is_thrift() const { return _is_thrift; } bool is_internal() const { return _is_internal; } /** * @return a ClientState object for internal C* calls (not limited by any kind of auth). */ static client_state for_internal_calls() { return client_state(internal_tag()); } /** * @return a ClientState object for external clients (thrift/native protocol users). */ static client_state for_external_calls() { return client_state(external_tag()); } static client_state for_external_thrift_calls() { return client_state(external_tag(), socket_address(), true); } /** * This clock guarantees that updates for the same ClientState will be ordered * in the sequence seen, even if multiple updates happen in the same millisecond. */ api::timestamp_type get_timestamp() { auto current = api::new_timestamp(); auto last = _last_timestamp_micros; auto result = last >= current ? last + 1 : current; _last_timestamp_micros = result; return result; } #if 0 /** * Can be use when a timestamp has been assigned by a query, but that timestamp is * not directly one returned by getTimestamp() (see SP.beginAndRepairPaxos()). * This ensure following calls to getTimestamp() will return a timestamp strictly * greated than the one provided to this method. */ public void updateLastTimestamp(long tstampMicros) { while (true) { long last = lastTimestampMicros.get(); if (tstampMicros <= last || lastTimestampMicros.compareAndSet(last, tstampMicros)) return; } } public SocketAddress getRemoteAddress() { return remoteAddress; } #endif const sstring& get_raw_keyspace() const { return _keyspace; } public: void set_keyspace(seastar::sharded<database>& db, sstring keyspace) { // Skip keyspace validation for non-authenticated users. Apparently, some client libraries // call set_keyspace() before calling login(), and we have to handle that. if (_user && !db.local().has_keyspace(keyspace)) { throw exceptions::invalid_request_exception(sprint("Keyspace '%s' does not exist", keyspace)); } _keyspace = keyspace; _dirty = true; } const sstring& get_keyspace() const { if (_keyspace.empty()) { throw exceptions::invalid_request_exception("No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename"); } return _keyspace; } /** * Sets active user. Does _not_ validate anything */ void set_login(::shared_ptr<auth::authenticated_user>); /** * Attempts to validate login for the set user. */ future<> check_user_exists(); future<> has_all_keyspaces_access(auth::permission) const; future<> has_keyspace_access(const sstring&, auth::permission) const; future<> has_column_family_access(const sstring&, const sstring&, auth::permission) const; future<> has_schema_access(const schema& s, auth::permission p) const; private: future<> has_access(const sstring&, auth::permission, auth::data_resource) const; future<bool> check_has_permission(auth::permission, auth::data_resource) const; public: future<> ensure_has_permission(auth::permission, auth::data_resource) const; void validate_login() const; void ensure_not_anonymous() const throw(exceptions::unauthorized_exception); #if 0 public void ensureIsSuper(String message) throws UnauthorizedException { if (DatabaseDescriptor.getAuthenticator().requireAuthentication() && (user == null || !user.isSuper())) throw new UnauthorizedException(message); } private static void validateKeyspace(String keyspace) throws InvalidRequestException { if (keyspace == null) throw new InvalidRequestException("You have not set a keyspace for this session"); } #endif ::shared_ptr<auth::authenticated_user> user() const { return _user; } #if 0 public static SemanticVersion[] getCQLSupportedVersion() { return new SemanticVersion[]{ QueryProcessor.CQL_VERSION }; } private Set<Permission> authorize(IResource resource) { // AllowAllAuthorizer or manually disabled caching. if (Auth.permissionsCache == null) return DatabaseDescriptor.getAuthorizer().authorize(user, resource); try { return Auth.permissionsCache.get(Pair.create(user, resource)); } catch (ExecutionException e) { throw new RuntimeException(e); } } #endif }; } <|endoftext|>
<commit_before>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "Slate/AssetPicker/ArticyObjectFilterHelpers.h" #include "ArticyObject.h" #include "Interfaces/ArticyObjectWithDisplayName.h" #include "Interfaces/ArticyObjectWithText.h" #include "Interfaces/ArticyObjectWithSpeaker.h" #define LOCTEXT_NAMESPACE "ArticyObjectSearchBoxHelpers" /** Expression context to test the given asset data against the current text filter */ class FFrontendFilter_ArticyObjectFilterExpressionContext : public ITextFilterExpressionContext { public: typedef TRemoveReference<FAssetFilterType>::Type* FAssetFilterTypePtr; FFrontendFilter_ArticyObjectFilterExpressionContext() : AssetPtr(nullptr) , bIncludeClassName(true) , NameKeyName("Name") , PathKeyName("Path") , ClassKeyName("Class") , TypeKeyName("Type") , TagKeyName("Tag") { } void SetAsset(FAssetFilterTypePtr InAsset) { AssetPtr = InAsset; } void ClearAsset() { AssetPtr = nullptr; } void SetIncludeClassName(const bool InIncludeClassName) { bIncludeClassName = InIncludeClassName; } bool GetIncludeClassName() const { return bIncludeClassName; } virtual bool TestBasicStringExpression(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const override { UArticyObject* ArticyObject = Cast<UArticyObject>(AssetPtr->GetAsset()); if(CheckDisplayName(InValue, InTextComparisonMode)) { return true; } if (CheckTechnicalName(InValue, InTextComparisonMode)) { return true; } if (CheckTextOfArticyObject(InValue, InTextComparisonMode)) { return true; } if(CheckSpeakerDisplayName(InValue, InTextComparisonMode)) { return true; } const FTextFilterString AssetName(AssetPtr->AssetName); if (AssetName.CompareText(InValue, InTextComparisonMode)) { return true; } if (bIncludeClassName) { const FTextFilterString AssetClassFilter(AssetPtr->AssetClass); if (AssetClassFilter.CompareText(InValue, InTextComparisonMode)) { return true; } } return false; } virtual bool TestComplexExpression(const FName& InKey, const FTextFilterString& InValue, const ETextFilterComparisonOperation InComparisonOperation, const ETextFilterTextComparisonMode InTextComparisonMode) const override { // Special case for the asset name, as this isn't contained within the asset registry meta-data if (InKey == NameKeyName) { // Names can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } const bool bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->AssetName, InValue, InTextComparisonMode); return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Special case for the asset path, as this isn't contained within the asset registry meta-data if (InKey == PathKeyName) { // Paths can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } // If the comparison mode is partial, then we only need to test the ObjectPath as that contains the other two as sub-strings bool bIsMatch = false; if (InTextComparisonMode == ETextFilterTextComparisonMode::Partial) { bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->ObjectPath, InValue, InTextComparisonMode); } else { bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->ObjectPath, InValue, InTextComparisonMode) || TextFilterUtils::TestBasicStringExpression(AssetPtr->PackageName, InValue, InTextComparisonMode) || TextFilterUtils::TestBasicStringExpression(AssetPtr->PackagePath, InValue, InTextComparisonMode); } return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Special case for the asset type, as this isn't contained within the asset registry meta-data if (InKey == ClassKeyName || InKey == TypeKeyName) { // Class names can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } const bool bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->AssetClass, InValue, InTextComparisonMode); return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Generic handling for anything in the asset meta-data { auto GetMetaDataValue = [this, &InKey](FString & OutMetaDataValue) -> bool { // Check for a literal key if (AssetPtr->GetTagValue(InKey, OutMetaDataValue)) { return true; } return false; }; FString MetaDataValue; if (GetMetaDataValue(MetaDataValue)) { return TextFilterUtils::TestComplexExpression(MetaDataValue, InValue, InComparisonOperation, InTextComparisonMode); } } return false; } private: /** Pointer to the asset we're currently filtering */ FAssetFilterTypePtr AssetPtr; /** Are we supposed to include the class name in our basic string tests? */ bool bIncludeClassName; /** Keys used by TestComplexExpression */ const FName NameKeyName; const FName PathKeyName; const FName ClassKeyName; const FName TypeKeyName; const FName TagKeyName; bool CheckDisplayName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithDisplayName* ArticyObjectWithDisplayName = Cast<IArticyObjectWithDisplayName>(AssetPtr->GetAsset()); if(ArticyObjectWithDisplayName) { const FTextFilterString TextToCompare(ArticyObjectWithDisplayName->GetDisplayName().ToString()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } bool CheckTextOfArticyObject(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithText* ArticyObjectWithText = Cast<IArticyObjectWithText>(AssetPtr->GetAsset()); if(ArticyObjectWithText) { const FText Text = ArticyObjectWithText->GetText(); const FTextFilterString FilterString(Text.ToString()); const bool bTextIsEmptyOrWhitespace = Text.IsEmptyOrWhitespace(); if(!bTextIsEmptyOrWhitespace && FilterString.CompareText(InValue, InTextComparisonMode)) { return true; } } return false; } bool CheckTechnicalName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { UArticyObject* ArticyObject = Cast<UArticyObject>(AssetPtr->GetAsset()); if (ArticyObject) { const FTextFilterString TextToCompare(ArticyObject->GetTechnicalName()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } bool CheckSpeakerDisplayName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithSpeaker* ArticyObjectWithSpeaker = Cast<IArticyObjectWithSpeaker>(AssetPtr->GetAsset()); if(ArticyObjectWithSpeaker) { UArticyObject* SpeakerObject = UArticyObject::FindAsset(ArticyObjectWithSpeaker->GetSpeakerId()); if(!SpeakerObject) { UE_LOG(LogArticyEditor, Error, TEXT("Articy filter: Speaker object does not exist")); return false; } IArticyObjectWithDisplayName* SpeakerDisplayName = Cast<IArticyObjectWithDisplayName>(SpeakerObject); FText& SpeakerName = SpeakerDisplayName->GetDisplayName(); const FTextFilterString TextToCompare(SpeakerName.ToString()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } }; FFrontendFilter_ArticyObject::FFrontendFilter_ArticyObject() : FFrontendFilter(nullptr) , TextFilterExpressionContext(MakeShareable(new FFrontendFilter_ArticyObjectFilterExpressionContext())) , TextFilterExpressionEvaluator(ETextFilterExpressionEvaluatorMode::Complex) { } FFrontendFilter_ArticyObject::~FFrontendFilter_ArticyObject() { } bool FFrontendFilter_ArticyObject::PassesFilter(FAssetFilterType InItem) const { TextFilterExpressionContext->SetAsset(&InItem); const bool bMatched = TextFilterExpressionEvaluator.TestTextFilter(*TextFilterExpressionContext); TextFilterExpressionContext->ClearAsset(); return bMatched; } FText FFrontendFilter_ArticyObject::GetRawFilterText() const { return TextFilterExpressionEvaluator.GetFilterText(); } void FFrontendFilter_ArticyObject::SetRawFilterText(const FText& InFilterText) { if (TextFilterExpressionEvaluator.SetFilterText(InFilterText)) { // Will trigger a re-filter with the new text BroadcastChangedEvent(); } } FText FFrontendFilter_ArticyObject::GetFilterErrorText() const { return TextFilterExpressionEvaluator.GetFilterErrorText(); } void FFrontendFilter_ArticyObject::SetIncludeClassName(const bool InIncludeClassName) { if (TextFilterExpressionContext->GetIncludeClassName() != InIncludeClassName) { TextFilterExpressionContext->SetIncludeClassName(InIncludeClassName); // Will trigger a re-filter with the new setting BroadcastChangedEvent(); } } FArticyClassRestrictionFilter::FArticyClassRestrictionFilter() { } bool FArticyClassRestrictionFilter::PassesFilter(FAssetFilterType InItem) const { return InItem.GetAsset()->IsA(AllowedClass.Get()); } #undef LOCTEXT_NAMESPACE <commit_msg>Cleaned up asset picker search related code<commit_after>// // Copyright (c) articy Software GmbH & Co. KG. All rights reserved. // #include "Slate/AssetPicker/ArticyObjectFilterHelpers.h" #include "ArticyObject.h" #include "Interfaces/ArticyObjectWithDisplayName.h" #include "Interfaces/ArticyObjectWithText.h" #include "Interfaces/ArticyObjectWithSpeaker.h" #define LOCTEXT_NAMESPACE "ArticyObjectSearchBoxHelpers" /** Expression context to test the given asset data against the current text filter */ class FFrontendFilter_ArticyObjectFilterExpressionContext : public ITextFilterExpressionContext { public: typedef TRemoveReference<FAssetFilterType>::Type* FAssetFilterTypePtr; FFrontendFilter_ArticyObjectFilterExpressionContext() : AssetPtr(nullptr) , bIncludeClassName(true) , NameKeyName("Name") , PathKeyName("Path") , ClassKeyName("Class") , TypeKeyName("Type") , TagKeyName("Tag") { } void SetAsset(FAssetFilterTypePtr InAsset) { AssetPtr = InAsset; } void ClearAsset() { AssetPtr = nullptr; } void SetIncludeClassName(const bool InIncludeClassName) { bIncludeClassName = InIncludeClassName; } bool GetIncludeClassName() const { return bIncludeClassName; } virtual bool TestBasicStringExpression(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const override { UArticyObject* ArticyObject = Cast<UArticyObject>(AssetPtr->GetAsset()); if(CheckDisplayName(InValue, InTextComparisonMode)) { return true; } if (CheckTechnicalName(InValue, InTextComparisonMode)) { return true; } if (CheckTextOfArticyObject(InValue, InTextComparisonMode)) { return true; } if(CheckSpeakerDisplayName(InValue, InTextComparisonMode)) { return true; } const FTextFilterString AssetName(AssetPtr->AssetName); if (AssetName.CompareText(InValue, InTextComparisonMode)) { return true; } if (bIncludeClassName) { const FTextFilterString AssetClassFilter(AssetPtr->AssetClass); if (AssetClassFilter.CompareText(InValue, InTextComparisonMode)) { return true; } } return false; } virtual bool TestComplexExpression(const FName& InKey, const FTextFilterString& InValue, const ETextFilterComparisonOperation InComparisonOperation, const ETextFilterTextComparisonMode InTextComparisonMode) const override { // Special case for the asset name, as this isn't contained within the asset registry meta-data if (InKey == NameKeyName) { // Names can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } const bool bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->AssetName, InValue, InTextComparisonMode); return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Special case for the asset path, as this isn't contained within the asset registry meta-data if (InKey == PathKeyName) { // Paths can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } // If the comparison mode is partial, then we only need to test the ObjectPath as that contains the other two as sub-strings bool bIsMatch = false; if (InTextComparisonMode == ETextFilterTextComparisonMode::Partial) { bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->ObjectPath, InValue, InTextComparisonMode); } else { bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->ObjectPath, InValue, InTextComparisonMode) || TextFilterUtils::TestBasicStringExpression(AssetPtr->PackageName, InValue, InTextComparisonMode) || TextFilterUtils::TestBasicStringExpression(AssetPtr->PackagePath, InValue, InTextComparisonMode); } return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Special case for the asset type, as this isn't contained within the asset registry meta-data if (InKey == ClassKeyName || InKey == TypeKeyName) { // Class names can only work with Equal or NotEqual type tests if (InComparisonOperation != ETextFilterComparisonOperation::Equal && InComparisonOperation != ETextFilterComparisonOperation::NotEqual) { return false; } const bool bIsMatch = TextFilterUtils::TestBasicStringExpression(AssetPtr->AssetClass, InValue, InTextComparisonMode); return (InComparisonOperation == ETextFilterComparisonOperation::Equal) ? bIsMatch : !bIsMatch; } // Generic handling for anything in the asset meta-data { auto GetMetaDataValue = [this, &InKey](FString & OutMetaDataValue) -> bool { // Check for a literal key if (AssetPtr->GetTagValue(InKey, OutMetaDataValue)) { return true; } return false; }; FString MetaDataValue; if (GetMetaDataValue(MetaDataValue)) { return TextFilterUtils::TestComplexExpression(MetaDataValue, InValue, InComparisonOperation, InTextComparisonMode); } } return false; } private: /** Pointer to the asset we're currently filtering */ FAssetFilterTypePtr AssetPtr; /** Are we supposed to include the class name in our basic string tests? */ bool bIncludeClassName; /** Keys used by TestComplexExpression */ const FName NameKeyName; const FName PathKeyName; const FName ClassKeyName; const FName TypeKeyName; const FName TagKeyName; bool CheckDisplayName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithDisplayName* ArticyObjectWithDisplayName = Cast<IArticyObjectWithDisplayName>(AssetPtr->GetAsset()); if(ArticyObjectWithDisplayName) { const FTextFilterString TextToCompare(ArticyObjectWithDisplayName->GetDisplayName().ToString()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } bool CheckTextOfArticyObject(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithText* ArticyObjectWithText = Cast<IArticyObjectWithText>(AssetPtr->GetAsset()); if(ArticyObjectWithText) { const FText Text = ArticyObjectWithText->GetText(); const FTextFilterString FilterString(Text.ToString()); const bool bTextIsEmptyOrWhitespace = Text.IsEmptyOrWhitespace(); if(!bTextIsEmptyOrWhitespace && FilterString.CompareText(InValue, InTextComparisonMode)) { return true; } } return false; } bool CheckTechnicalName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { UArticyObject* ArticyObject = Cast<UArticyObject>(AssetPtr->GetAsset()); if (ArticyObject) { const FTextFilterString TextToCompare(ArticyObject->GetTechnicalName()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } bool CheckSpeakerDisplayName(const FTextFilterString& InValue, const ETextFilterTextComparisonMode InTextComparisonMode) const { IArticyObjectWithSpeaker* ArticyObjectWithSpeaker = Cast<IArticyObjectWithSpeaker>(AssetPtr->GetAsset()); if(ArticyObjectWithSpeaker) { IArticyObjectWithDisplayName* SpeakerDisplayName = Cast<IArticyObjectWithDisplayName>(UArticyObject::FindAsset(ArticyObjectWithSpeaker->GetSpeakerId())); if(!SpeakerDisplayName) { UE_LOG(LogArticyEditor, Error, TEXT("Articy filter: Speaker object does not exist")); return false; } FText& SpeakerName = SpeakerDisplayName->GetDisplayName(); const FTextFilterString TextToCompare(SpeakerName.ToString()); if (TextToCompare.IsEmpty()) { return false; } return TextToCompare.CompareText(InValue, InTextComparisonMode); } return false; } }; FFrontendFilter_ArticyObject::FFrontendFilter_ArticyObject() : FFrontendFilter(nullptr) , TextFilterExpressionContext(MakeShareable(new FFrontendFilter_ArticyObjectFilterExpressionContext())) , TextFilterExpressionEvaluator(ETextFilterExpressionEvaluatorMode::Complex) { } FFrontendFilter_ArticyObject::~FFrontendFilter_ArticyObject() { } bool FFrontendFilter_ArticyObject::PassesFilter(FAssetFilterType InItem) const { TextFilterExpressionContext->SetAsset(&InItem); const bool bMatched = TextFilterExpressionEvaluator.TestTextFilter(*TextFilterExpressionContext); TextFilterExpressionContext->ClearAsset(); return bMatched; } FText FFrontendFilter_ArticyObject::GetRawFilterText() const { return TextFilterExpressionEvaluator.GetFilterText(); } void FFrontendFilter_ArticyObject::SetRawFilterText(const FText& InFilterText) { if (TextFilterExpressionEvaluator.SetFilterText(InFilterText)) { // Will trigger a re-filter with the new text BroadcastChangedEvent(); } } FText FFrontendFilter_ArticyObject::GetFilterErrorText() const { return TextFilterExpressionEvaluator.GetFilterErrorText(); } void FFrontendFilter_ArticyObject::SetIncludeClassName(const bool InIncludeClassName) { if (TextFilterExpressionContext->GetIncludeClassName() != InIncludeClassName) { TextFilterExpressionContext->SetIncludeClassName(InIncludeClassName); // Will trigger a re-filter with the new setting BroadcastChangedEvent(); } } FArticyClassRestrictionFilter::FArticyClassRestrictionFilter() { } bool FArticyClassRestrictionFilter::PassesFilter(FAssetFilterType InItem) const { return InItem.GetAsset()->IsA(AllowedClass.Get()); } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include "MicroBit.h" /* The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ * If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL) * The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this * as a compatability option, but does not support the options used... */ #if !defined(__arm) #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include "ble.h" /* * Return to our predefined compiler settings. */ #if !defined(__arm) #pragma GCC diagnostic pop #endif #define MICROBIT_BLE_ENABLE_BONDING true #define MICROBIT_BLE_REQUIRE_MITM true #define MICROBIT_PAIRING_MODE_TIMEOUT 90 #define MICROBIT_PAIRING_FADE_SPEED 4 const char* MICROBIT_BLE_MANUFACTURER = "The Cast of W1A"; const char* MICROBIT_BLE_MODEL = "BBC micro:bit"; const char* MICROBIT_BLE_HARDWARE_VERSION = "1.0"; const char* MICROBIT_BLE_FIRMWARE_VERSION = MICROBIT_DAL_VERSION; const char* MICROBIT_BLE_SOFTWARE_VERSION = NULL; /* * Many of the mbed interfaces we need to use only support callbacks to plain C functions, rather than C++ methods. * So, we maintain a pointer to the MicroBitBLEManager that's in use. Ths way, we can still access resources on the micro:bit * whilst keeping the code modular. */ static MicroBitBLEManager *manager = NULL; /** * Callback when a BLE GATT disconnect occurs. */ static void bleDisconnectionCallback(const Gap::DisconnectionCallbackParams_t *reason) { (void) reason; /* -Wunused-param */ if (manager) manager->onDisconnectionCallback(); } static void passkeyDisplayCallback(Gap::Handle_t handle, const SecurityManager::Passkey_t passkey) { (void) handle; /* -Wunused-param */ ManagedString passKey((const char *)passkey, SecurityManager::PASSKEY_LEN); if (manager) manager->pairingRequested(passKey); } static void securitySetupCompletedCallback(Gap::Handle_t handle, SecurityManager::SecurityCompletionStatus_t status) { (void) handle; /* -Wunused-param */ if (manager) manager->pairingComplete(status == SecurityManager::SEC_STATUS_SUCCESS); } /** * Constructor. * * Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack. * Note that the BLE stack *cannot* be brought up in a static context. * (the software simply hangs or corrupts itself). * Hence, we bring it up in an explicit init() method, rather than in the constructor. */ MicroBitBLEManager::MicroBitBLEManager() { manager = this; this->ble = NULL; this->pairingStatus = 0; } /** * Method that is called whenever a BLE device disconnects from us. * The nordic stack stops dvertising whenever a device connects, so we use * this callback to restart advertising. */ void MicroBitBLEManager::onDisconnectionCallback() { if(ble) ble->startAdvertising(); } /** * Post constructor initialisation method. * After *MUCH* pain, it's noted that the BLE stack can't be brought up in a * static context, so we bring it up here rather than in the constructor. * n.b. This method *must* be called in main() or later, not before. * * Example: * @code * uBit.init(); * @endcode */ void MicroBitBLEManager::init(ManagedString deviceName, ManagedString serialNumber) { ManagedString BLEName("BBC micro:bit"); this->deviceName = deviceName; // Start the BLE stack. ble = new BLEDevice(); ble->init(); // automatically restart advertising after a device disconnects. ble->onDisconnection(bleDisconnectionCallback); // configure the stack to hold on to CPU during critical timing events. // mbed-classic performs __disabe_irq calls in its timers, which can cause MIC failures // on secure BLE channels. ble_common_opt_radio_cpu_mutex_t opt; opt.enable = 1; sd_ble_opt_set(BLE_COMMON_OPT_RADIO_CPU_MUTEX, (const ble_opt_t *)&opt); #if CONFIG_ENABLED(MICROBIT_BLE_PRIVATE_ADDRESSES) // Configure for private addresses, so kids' behaviour can't be easily tracked. ble->setAddress(Gap::ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE, NULL); #endif // Setup our security requirements. ble->securityManager().onPasskeyDisplay(passkeyDisplayCallback); ble->securityManager().onSecuritySetupCompleted(securitySetupCompletedCallback); ble->securityManager().init(MICROBIT_BLE_ENABLE_BONDING, MICROBIT_BLE_REQUIRE_MITM, SecurityManager::IO_CAPS_DISPLAY_ONLY); // Bring up any configured auxiliary services. #if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE) new MicroBitDFUService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) DeviceInformationService ble_device_information_service (*ble, MICROBIT_BLE_MANUFACTURER, MICROBIT_BLE_MODEL, serialNumber.toCharArray(), MICROBIT_BLE_HARDWARE_VERSION, MICROBIT_BLE_FIRMWARE_VERSION, MICROBIT_BLE_SOFTWARE_VERSION); #endif #if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE) new MicroBitEventService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_LED_SERVICE) new MicroBitLEDService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_ACCELEROMETER_SERVICE) new MicroBitAccelerometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_MAGNETOMETER_SERVICE) new MicroBitMagnetometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_BUTTON_SERVICE) new MicroBitButtonService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_IO_PIN_SERVICE) new MicroBitIOPinService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_TEMPERATURE_SERVICE) new MicroBitTemperatureService(*ble); #endif // Configure for high speed mode where possible. Gap::ConnectionParams_t fast; ble->getPreferredConnectionParams(&fast); fast.minConnectionInterval = 8; // 10 ms fast.maxConnectionInterval = 16; // 20 ms fast.slaveLatency = 0; ble->setPreferredConnectionParams(&fast); // Setup advertising. ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)BLEName.toCharArray(), BLEName.length()); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(200); ble->startAdvertising(); } /** * A request to pair has been received from a BLE device. * If we're in pairing mode, display the passkey to the user. */ void MicroBitBLEManager::pairingRequested(ManagedString passKey) { this->passKey = passKey; this->pairingStatus = MICROBIT_BLE_PAIR_REQUEST; } /** * A pairing request has been sucesfully completed. * If we're in pairing mode, display feedback to the user. */ void MicroBitBLEManager::pairingComplete(bool success) { this->pairingStatus = MICROBIT_BLE_PAIR_COMPLETE; if(success) this->pairingStatus |= MICROBIT_BLE_PAIR_SUCCESSFUL; } /** * Enter pairing mode. This is mode is called to initiate pairing, and to enable FOTA programming * of the micro:bit in cases where BLE is disabled during normal operation. */ void MicroBitBLEManager::pairingMode(MicroBitDisplay &display) { ManagedString namePrefix("BBC micro:bit ["); ManagedString namePostfix("]"); ManagedString BLEName = namePrefix + deviceName + namePostfix; ManagedString msg("PAIRING MODE!"); int timeInPairingMode = 0; int brightness = 255; int fadeDirection = 0; // Update the advertised name of this micro:bit to include the device name ble->clearAdvertisingPayload(); #if CONFIG_ENABLED(MICROBIT_BLE_PRIVATE_ADDRESSES) // Always configure for public addresses in pairing mode... ble->setAddress(Gap::ADDR_TYPE_PUBLIC, NULL); #endif ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)BLEName.toCharArray(), BLEName.length()); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(200); ble->startAdvertising(); // Stop any running animations on the display display.stopAnimation(); display.scroll(msg); // Display our name, visualised as a histogram in the display to aid identification. showNameHistogram(display); while(1) { if (pairingStatus & MICROBIT_BLE_PAIR_REQUEST) { timeInPairingMode = 0; MicroBitImage arrow("0,0,255,0,0\n0,255,0,0,0\n255,255,255,255,255\n0,255,0,0,0\n0,0,255,0,0\n"); display.print(arrow,0,0,0); if (fadeDirection == 0) brightness -= MICROBIT_PAIRING_FADE_SPEED; else brightness += MICROBIT_PAIRING_FADE_SPEED; if (brightness <= 40) display.clear(); if (brightness <= 0) fadeDirection = 1; if (brightness >= 255) fadeDirection = 0; if (uBit.buttonA.isPressed()) { pairingStatus &= ~MICROBIT_BLE_PAIR_REQUEST; pairingStatus |= MICROBIT_BLE_PAIR_PASSCODE; } } if (pairingStatus & MICROBIT_BLE_PAIR_PASSCODE) { timeInPairingMode = 0; display.setBrightness(255); for (int i=0; i<passKey.length(); i++) { display.image.print(passKey.charAt(i),0,0); uBit.sleep(800); display.clear(); uBit.sleep(200); if (pairingStatus & MICROBIT_BLE_PAIR_COMPLETE) break; } uBit.sleep(1000); } if (pairingStatus & MICROBIT_BLE_PAIR_COMPLETE) { if (pairingStatus & MICROBIT_BLE_PAIR_SUCCESSFUL) { MicroBitImage tick("0,0,0,0,0\n0,0,0,0,255\n0,0,0,255,0\n255,0,255,0,0\n0,255,0,0,0\n"); display.print(tick,0,0,0); } else { MicroBitImage cross("255,0,0,0,255\n0,255,0,255,0\n0,0,255,0,0\n0,255,0,255,0\n255,0,0,0,255\n"); display.print(cross,0,0,0); } } uBit.sleep(30); timeInPairingMode++; if (timeInPairingMode >= MICROBIT_PAIRING_MODE_TIMEOUT * 30) microbit_reset(); } } /** * Displays the device's ID code as a histogram on the LED matrix display. */ void MicroBitBLEManager::showNameHistogram(MicroBitDisplay &display) { uint32_t n = NRF_FICR->DEVICEID[1]; int ld = 1; int d = MICROBIT_DFU_HISTOGRAM_HEIGHT; int h; display.clear(); for (int i=0; i<MICROBIT_DFU_HISTOGRAM_WIDTH;i++) { h = (n % d) / ld; n -= h; d *= MICROBIT_DFU_HISTOGRAM_HEIGHT; ld *= MICROBIT_DFU_HISTOGRAM_HEIGHT; for (int j=0; j<h+1; j++) display.image.setPixelValue(MICROBIT_DFU_HISTOGRAM_WIDTH-i-1, MICROBIT_DFU_HISTOGRAM_HEIGHT-j-1, 255); } } <commit_msg>microbit: Revert explicit use of public addresses in pairing mode<commit_after>#include "MicroBit.h" /* The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ * If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL) * The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this * as a compatability option, but does not support the options used... */ #if !defined(__arm) #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include "ble.h" /* * Return to our predefined compiler settings. */ #if !defined(__arm) #pragma GCC diagnostic pop #endif #define MICROBIT_BLE_ENABLE_BONDING true #define MICROBIT_BLE_REQUIRE_MITM true #define MICROBIT_PAIRING_MODE_TIMEOUT 90 #define MICROBIT_PAIRING_FADE_SPEED 4 const char* MICROBIT_BLE_MANUFACTURER = "The Cast of W1A"; const char* MICROBIT_BLE_MODEL = "BBC micro:bit"; const char* MICROBIT_BLE_HARDWARE_VERSION = "1.0"; const char* MICROBIT_BLE_FIRMWARE_VERSION = MICROBIT_DAL_VERSION; const char* MICROBIT_BLE_SOFTWARE_VERSION = NULL; /* * Many of the mbed interfaces we need to use only support callbacks to plain C functions, rather than C++ methods. * So, we maintain a pointer to the MicroBitBLEManager that's in use. Ths way, we can still access resources on the micro:bit * whilst keeping the code modular. */ static MicroBitBLEManager *manager = NULL; /** * Callback when a BLE GATT disconnect occurs. */ static void bleDisconnectionCallback(const Gap::DisconnectionCallbackParams_t *reason) { (void) reason; /* -Wunused-param */ if (manager) manager->onDisconnectionCallback(); } static void passkeyDisplayCallback(Gap::Handle_t handle, const SecurityManager::Passkey_t passkey) { (void) handle; /* -Wunused-param */ ManagedString passKey((const char *)passkey, SecurityManager::PASSKEY_LEN); if (manager) manager->pairingRequested(passKey); } static void securitySetupCompletedCallback(Gap::Handle_t handle, SecurityManager::SecurityCompletionStatus_t status) { (void) handle; /* -Wunused-param */ if (manager) manager->pairingComplete(status == SecurityManager::SEC_STATUS_SUCCESS); } /** * Constructor. * * Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack. * Note that the BLE stack *cannot* be brought up in a static context. * (the software simply hangs or corrupts itself). * Hence, we bring it up in an explicit init() method, rather than in the constructor. */ MicroBitBLEManager::MicroBitBLEManager() { manager = this; this->ble = NULL; this->pairingStatus = 0; } /** * Method that is called whenever a BLE device disconnects from us. * The nordic stack stops dvertising whenever a device connects, so we use * this callback to restart advertising. */ void MicroBitBLEManager::onDisconnectionCallback() { if(ble) ble->startAdvertising(); } /** * Post constructor initialisation method. * After *MUCH* pain, it's noted that the BLE stack can't be brought up in a * static context, so we bring it up here rather than in the constructor. * n.b. This method *must* be called in main() or later, not before. * * Example: * @code * uBit.init(); * @endcode */ void MicroBitBLEManager::init(ManagedString deviceName, ManagedString serialNumber) { ManagedString BLEName("BBC micro:bit"); this->deviceName = deviceName; // Start the BLE stack. ble = new BLEDevice(); ble->init(); // automatically restart advertising after a device disconnects. ble->onDisconnection(bleDisconnectionCallback); // configure the stack to hold on to CPU during critical timing events. // mbed-classic performs __disabe_irq calls in its timers, which can cause MIC failures // on secure BLE channels. ble_common_opt_radio_cpu_mutex_t opt; opt.enable = 1; sd_ble_opt_set(BLE_COMMON_OPT_RADIO_CPU_MUTEX, (const ble_opt_t *)&opt); #if CONFIG_ENABLED(MICROBIT_BLE_PRIVATE_ADDRESSES) // Configure for private addresses, so kids' behaviour can't be easily tracked. ble->setAddress(Gap::ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE, NULL); #endif // Setup our security requirements. ble->securityManager().onPasskeyDisplay(passkeyDisplayCallback); ble->securityManager().onSecuritySetupCompleted(securitySetupCompletedCallback); ble->securityManager().init(MICROBIT_BLE_ENABLE_BONDING, MICROBIT_BLE_REQUIRE_MITM, SecurityManager::IO_CAPS_DISPLAY_ONLY); // Bring up any configured auxiliary services. #if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE) new MicroBitDFUService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE) DeviceInformationService ble_device_information_service (*ble, MICROBIT_BLE_MANUFACTURER, MICROBIT_BLE_MODEL, serialNumber.toCharArray(), MICROBIT_BLE_HARDWARE_VERSION, MICROBIT_BLE_FIRMWARE_VERSION, MICROBIT_BLE_SOFTWARE_VERSION); #endif #if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE) new MicroBitEventService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_LED_SERVICE) new MicroBitLEDService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_ACCELEROMETER_SERVICE) new MicroBitAccelerometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_MAGNETOMETER_SERVICE) new MicroBitMagnetometerService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_BUTTON_SERVICE) new MicroBitButtonService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_IO_PIN_SERVICE) new MicroBitIOPinService(*ble); #endif #if CONFIG_ENABLED(MICROBIT_BLE_TEMPERATURE_SERVICE) new MicroBitTemperatureService(*ble); #endif // Configure for high speed mode where possible. Gap::ConnectionParams_t fast; ble->getPreferredConnectionParams(&fast); fast.minConnectionInterval = 8; // 10 ms fast.maxConnectionInterval = 16; // 20 ms fast.slaveLatency = 0; ble->setPreferredConnectionParams(&fast); // Setup advertising. ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)BLEName.toCharArray(), BLEName.length()); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(200); ble->startAdvertising(); } /** * A request to pair has been received from a BLE device. * If we're in pairing mode, display the passkey to the user. */ void MicroBitBLEManager::pairingRequested(ManagedString passKey) { this->passKey = passKey; this->pairingStatus = MICROBIT_BLE_PAIR_REQUEST; } /** * A pairing request has been sucesfully completed. * If we're in pairing mode, display feedback to the user. */ void MicroBitBLEManager::pairingComplete(bool success) { this->pairingStatus = MICROBIT_BLE_PAIR_COMPLETE; if(success) this->pairingStatus |= MICROBIT_BLE_PAIR_SUCCESSFUL; } /** * Enter pairing mode. This is mode is called to initiate pairing, and to enable FOTA programming * of the micro:bit in cases where BLE is disabled during normal operation. */ void MicroBitBLEManager::pairingMode(MicroBitDisplay &display) { ManagedString namePrefix("BBC micro:bit ["); ManagedString namePostfix("]"); ManagedString BLEName = namePrefix + deviceName + namePostfix; ManagedString msg("PAIRING MODE!"); int timeInPairingMode = 0; int brightness = 255; int fadeDirection = 0; // Update the advertised name of this micro:bit to include the device name ble->clearAdvertisingPayload(); ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)BLEName.toCharArray(), BLEName.length()); ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble->setAdvertisingInterval(200); ble->startAdvertising(); // Stop any running animations on the display display.stopAnimation(); display.scroll(msg); // Display our name, visualised as a histogram in the display to aid identification. showNameHistogram(display); while(1) { if (pairingStatus & MICROBIT_BLE_PAIR_REQUEST) { timeInPairingMode = 0; MicroBitImage arrow("0,0,255,0,0\n0,255,0,0,0\n255,255,255,255,255\n0,255,0,0,0\n0,0,255,0,0\n"); display.print(arrow,0,0,0); if (fadeDirection == 0) brightness -= MICROBIT_PAIRING_FADE_SPEED; else brightness += MICROBIT_PAIRING_FADE_SPEED; if (brightness <= 40) display.clear(); if (brightness <= 0) fadeDirection = 1; if (brightness >= 255) fadeDirection = 0; if (uBit.buttonA.isPressed()) { pairingStatus &= ~MICROBIT_BLE_PAIR_REQUEST; pairingStatus |= MICROBIT_BLE_PAIR_PASSCODE; } } if (pairingStatus & MICROBIT_BLE_PAIR_PASSCODE) { timeInPairingMode = 0; display.setBrightness(255); for (int i=0; i<passKey.length(); i++) { display.image.print(passKey.charAt(i),0,0); uBit.sleep(800); display.clear(); uBit.sleep(200); if (pairingStatus & MICROBIT_BLE_PAIR_COMPLETE) break; } uBit.sleep(1000); } if (pairingStatus & MICROBIT_BLE_PAIR_COMPLETE) { if (pairingStatus & MICROBIT_BLE_PAIR_SUCCESSFUL) { MicroBitImage tick("0,0,0,0,0\n0,0,0,0,255\n0,0,0,255,0\n255,0,255,0,0\n0,255,0,0,0\n"); display.print(tick,0,0,0); } else { MicroBitImage cross("255,0,0,0,255\n0,255,0,255,0\n0,0,255,0,0\n0,255,0,255,0\n255,0,0,0,255\n"); display.print(cross,0,0,0); } } uBit.sleep(30); timeInPairingMode++; if (timeInPairingMode >= MICROBIT_PAIRING_MODE_TIMEOUT * 30) microbit_reset(); } } /** * Displays the device's ID code as a histogram on the LED matrix display. */ void MicroBitBLEManager::showNameHistogram(MicroBitDisplay &display) { uint32_t n = NRF_FICR->DEVICEID[1]; int ld = 1; int d = MICROBIT_DFU_HISTOGRAM_HEIGHT; int h; display.clear(); for (int i=0; i<MICROBIT_DFU_HISTOGRAM_WIDTH;i++) { h = (n % d) / ld; n -= h; d *= MICROBIT_DFU_HISTOGRAM_HEIGHT; ld *= MICROBIT_DFU_HISTOGRAM_HEIGHT; for (int j=0; j<h+1; j++) display.image.setPixelValue(MICROBIT_DFU_HISTOGRAM_WIDTH-i-1, MICROBIT_DFU_HISTOGRAM_HEIGHT-j-1, 255); } } <|endoftext|>
<commit_before>#include "generic.h" #include <algorithm> generic_manager::generic_manager(moltengamepad* mg, generic_driver_info& descr) : device_manager(mg) { this->name = descr.name.c_str(); this->devname = descr.devname.c_str(); mapprofile.name = name; this->descr = &descr; split = descr.split; flatten = descr.flatten; if (split > 1) { for (int i = 1; i <= split; i++) { splitevents.push_back(std::vector<gen_source_event>()); } for (auto gen_ev : descr.events) { if (gen_ev.split_id < 1 || gen_ev.split_id > split) continue; splitevents.at(gen_ev.split_id - 1).push_back(gen_ev); } } for (auto alias : descr.aliases) { mapprofile.set_alias(alias.first,alias.second); } descr.split_types.resize(split,input_source::GAMEPAD); for (auto type : descr.split_types) { if (type == input_source::GAMEPAD) { mapprofile.gamepad_defaults(); break; } } std::cout << name << " driver initialized." << std::endl; } generic_manager::~generic_manager() { for (auto file : openfiles) { delete file; } delete descr; } int generic_manager::accept_device(struct udev* udev, struct udev_device* dev) { const char* path = udev_device_get_syspath(dev); const char* subsystem = udev_device_get_subsystem(dev); const char* action = udev_device_get_action(dev); if (!action) action = "null"; if (!strcmp(action, "remove")) { if (!path) return -1; for (auto it = openfiles.begin(); it != openfiles.end(); it++) { (*it)->close_node(dev, true); if ((*it)->nodes.empty()) { std::cout << "Generic driver " << name << " lost a device." << std::endl; delete(*it); openfiles.erase(it); return 0; } } } if (!strcmp(action, "add") || !strcmp(action, "null")) { if (!strcmp(subsystem, "input")) { const char* sysname = udev_device_get_sysname(dev); const char* name = nullptr; if (!strncmp(sysname, "event", 3)) { struct udev_device* parent = udev_device_get_parent(dev); name = udev_device_get_sysattr_value(parent, "name"); if (!name) return -2; for (auto it = descr->matches.begin(); it != descr->matches.end(); it++) { if (!strcmp((*it).name.c_str(), name)) { return open_device(udev, dev); } } } } } return -2; } int generic_manager::open_device(struct udev* udev, struct udev_device* dev) { try { if (flatten) { if (openfiles.size() < 1) { openfiles.push_back(new generic_file(dev, descr->grab_ioctl, descr->grab_chmod)); openfiles.front()->mg = mg; create_inputs(openfiles.front(), openfiles.front()->fds.front(), false); } else { openfiles.front()->open_node(dev); } } else { openfiles.push_back(new generic_file(dev, descr->grab_ioctl, descr->grab_chmod)); openfiles.back()->mg = mg; create_inputs(openfiles.back(), openfiles.back()->fds.front(), false); } } catch (...) { return -1; //Something went wrong opening this device... } return 0; } void generic_manager::create_inputs(generic_file* opened_file, int fd, bool watch) { if (split == 1) { generic_device* gendev = new generic_device(descr->events, fd, watch, mg->slots, descr->split_types[0]); char* newdevname = nullptr; asprintf(&newdevname, "%s%d", devname.c_str(), ++dev_counter); gendev->nameptr = newdevname; gendev->name = newdevname; opened_file->add_dev(gendev); mg->add_device(gendev); gendev->start_thread(); gendev->load_profile(&mapprofile); } else { for (int i = 1; i <= split; i++) { generic_device* gendev = new generic_device(splitevents.at(i - 1), fd, watch, mg->slots, descr->split_types[i-1]); char* newdevname = nullptr; asprintf(&newdevname, "%s%d", devname.c_str(), ++dev_counter); gendev->nameptr = newdevname; gendev->name = newdevname; opened_file->add_dev(gendev); mg->add_device(gendev); gendev->start_thread(); gendev->load_profile(&mapprofile); } } } void generic_manager::update_maps(const char* evname, event_translator* trans) { auto type = entry_type(evname); mapprofile.set_mapping(evname, trans->clone(), type); for (auto file : openfiles) { for (auto dev : file->devices) { dev->update_map(evname, trans); } } } void generic_manager::update_option(const char* opname, const char* value) { //Generic devices currently have no options. }; void generic_manager::update_advanceds(const std::vector<std::string>& names, advanced_event_translator* trans) { if (trans) { mapprofile.set_advanced(names, trans->clone()); } else { mapprofile.set_advanced(names, nullptr); } for (auto file : openfiles) { for (auto dev : file->devices) { dev->update_advanced(names, trans); } } } input_source* generic_manager::find_device(const char* name) { for (auto file : openfiles) { for (auto dev : file->devices) { if (!strcmp(dev->name, name)) return dev; } } return nullptr; } enum entry_type generic_manager::entry_type(const char* name) { auto alias = mapprofile.get_alias(std::string(name)); if (!alias.empty()) name = alias.c_str(); for (auto ev : descr->events) { if (!strcmp(ev.name.c_str(), name)) return ev.type; } return NO_ENTRY; } <commit_msg>Remove some silly redundancy in generic_manager<commit_after>#include "generic.h" #include <algorithm> generic_manager::generic_manager(moltengamepad* mg, generic_driver_info& descr) : device_manager(mg) { this->name = descr.name.c_str(); this->devname = descr.devname.c_str(); mapprofile.name = name; this->descr = &descr; split = descr.split; flatten = descr.flatten; for (int i = 1; i <= split; i++) { splitevents.push_back(std::vector<gen_source_event>()); } for (auto gen_ev : descr.events) { if (gen_ev.split_id < 1 || gen_ev.split_id > split) continue; splitevents.at(gen_ev.split_id - 1).push_back(gen_ev); } for (auto alias : descr.aliases) { mapprofile.set_alias(alias.first,alias.second); } descr.split_types.resize(split,input_source::GAMEPAD); for (auto type : descr.split_types) { if (type == input_source::GAMEPAD) { mapprofile.gamepad_defaults(); break; } } std::cout << name << " driver initialized." << std::endl; } generic_manager::~generic_manager() { for (auto file : openfiles) { delete file; } delete descr; } int generic_manager::accept_device(struct udev* udev, struct udev_device* dev) { const char* path = udev_device_get_syspath(dev); const char* subsystem = udev_device_get_subsystem(dev); const char* action = udev_device_get_action(dev); if (!action) action = "null"; if (!strcmp(action, "remove")) { if (!path) return -1; for (auto it = openfiles.begin(); it != openfiles.end(); it++) { (*it)->close_node(dev, true); if ((*it)->nodes.empty()) { std::cout << "Generic driver " << name << " lost a device." << std::endl; delete(*it); openfiles.erase(it); return 0; } } } if (!strcmp(action, "add") || !strcmp(action, "null")) { if (!strcmp(subsystem, "input")) { const char* sysname = udev_device_get_sysname(dev); const char* name = nullptr; if (!strncmp(sysname, "event", 3)) { struct udev_device* parent = udev_device_get_parent(dev); name = udev_device_get_sysattr_value(parent, "name"); if (!name) return -2; for (auto it = descr->matches.begin(); it != descr->matches.end(); it++) { if (!strcmp((*it).name.c_str(), name)) { return open_device(udev, dev); } } } } } return -2; } int generic_manager::open_device(struct udev* udev, struct udev_device* dev) { try { if (flatten) { if (openfiles.size() < 1) { openfiles.push_back(new generic_file(dev, descr->grab_ioctl, descr->grab_chmod)); openfiles.front()->mg = mg; create_inputs(openfiles.front(), openfiles.front()->fds.front(), false); } else { openfiles.front()->open_node(dev); } } else { openfiles.push_back(new generic_file(dev, descr->grab_ioctl, descr->grab_chmod)); openfiles.back()->mg = mg; create_inputs(openfiles.back(), openfiles.back()->fds.front(), false); } } catch (...) { return -1; //Something went wrong opening this device... } return 0; } void generic_manager::create_inputs(generic_file* opened_file, int fd, bool watch) { for (int i = 1; i <= split; i++) { generic_device* gendev = new generic_device(splitevents.at(i - 1), fd, watch, mg->slots, descr->split_types[i-1]); char* newdevname = nullptr; asprintf(&newdevname, "%s%d", devname.c_str(), ++dev_counter); gendev->nameptr = newdevname; gendev->name = newdevname; opened_file->add_dev(gendev); mg->add_device(gendev); gendev->start_thread(); gendev->load_profile(&mapprofile); } } void generic_manager::update_maps(const char* evname, event_translator* trans) { auto type = entry_type(evname); mapprofile.set_mapping(evname, trans->clone(), type); for (auto file : openfiles) { for (auto dev : file->devices) { dev->update_map(evname, trans); } } } void generic_manager::update_option(const char* opname, const char* value) { //Generic devices currently have no options. }; void generic_manager::update_advanceds(const std::vector<std::string>& names, advanced_event_translator* trans) { if (trans) { mapprofile.set_advanced(names, trans->clone()); } else { mapprofile.set_advanced(names, nullptr); } for (auto file : openfiles) { for (auto dev : file->devices) { dev->update_advanced(names, trans); } } } input_source* generic_manager::find_device(const char* name) { for (auto file : openfiles) { for (auto dev : file->devices) { if (!strcmp(dev->name, name)) return dev; } } return nullptr; } enum entry_type generic_manager::entry_type(const char* name) { auto alias = mapprofile.get_alias(std::string(name)); if (!alias.empty()) name = alias.c_str(); for (auto ev : descr->events) { if (!strcmp(ev.name.c_str(), name)) return ev.type; } return NO_ENTRY; } <|endoftext|>
<commit_before>#include "type.hpp" #include <vector> #include <sstream> #include "ast.hpp" #include "tool.hpp" namespace type { static const bool debug = false; static const auto make_constant = [](const char* name, kind::any k=kind::term()) { return make_ref<constant>(constant{symbol(name), k}); }; static const auto make_variable = [](std::size_t level, kind::any k=kind::term()) { return make_ref<variable>(variable{level, k}); }; // constants const ref<constant> unit = make_constant("unit"); const ref<constant> boolean = make_constant("boolean"); const ref<constant> integer = make_constant("integer"); const ref<constant> real = make_constant("real"); const ref<constant> func = make_constant("->", kind::term() >>= kind::term() >>= kind::term()); const ref<constant> io = make_constant("io", kind::term() >>= kind::term()); const ref<constant> rec = make_constant("record", kind::row() >>= kind::term()); ref<constant> ext(symbol attr) { static const kind::any k = kind::term() >>= kind::row() >>= kind::row(); static std::map<symbol, ref<constant>> table; const std::string name = std::string("@") + attr.get(); auto it = table.emplace(attr, make_constant(name.c_str(), k)); return it.first->second; } state& state::operator()(std::string s, mono t) { locals.emplace(s, generalize(t)); return *this; } static mono instantiate(poly self, std::size_t depth); ref<application> apply(mono ctor, mono arg) { return make_ref<application>(ctor, arg); } mono operator>>=(mono from, mono to) { return apply(apply(func, from), to); } application::application(mono ctor, mono arg) : ctor(ctor), arg(arg) { const kind::any k = ctor.kind(); if(auto c = k.get<ref<kind::constructor>>()) { if((*c)->from != arg.kind()) { std::clog << poly{{}, ctor} << " :: " << ctor.kind() << " " << poly{{}, arg} << " :: " << arg.kind() << std::endl; throw kind::error("argument has not the expected kind"); } } else { throw kind::error("type constructor must have constructor kind"); } } struct kind_visitor { kind::any operator()(const ref<constant>& self) const { return self->kind; } kind::any operator()(const ref<variable>& self) const { return self->kind; } kind::any operator()(const ref<application>& self) const { const kind::any k = self->ctor.kind(); if(auto c = k.get<ref<kind::constructor>>()) { return (*c)->to; } else { throw std::logic_error("derp"); } } }; kind::any mono::kind() const { return visit<kind::any>(kind_visitor()); } struct infer_visitor { template<class T> mono operator()(const T& self, const ref<state>&) const { throw std::logic_error("infer unimplemented: " + tool::type_name(typeid(T))); } // var mono operator()(const ast::var& self, const ref<state>& s) const { try { return instantiate(s->find(self.name), s->level); } catch(std::out_of_range& e) { throw error("unbound variable " + tool::quote(self.name.get())); } } // abs mono operator()(const ast::abs& self, const ref<state>& s) const { std::vector<poly> vars; // construct function type const mono result = s->fresh(); const mono sig = foldr(result, self.args, [&](symbol name, mono t) { const mono alpha = s->fresh(); // note: alpha is monomorphic in sigma const poly sigma = {{}, alpha}; vars.emplace_back(sigma); return alpha >>= t; }); // infer lambda body with augmented environment auto scope = augment(s, self.args, vars.rbegin(), vars.rend()); s->unify(result, mono::infer(scope, *self.body)); return sig; } // app mono operator()(const ast::app& self, const ref<state>& s) const { const mono func = mono::infer(s, *self.func); const mono result = s->fresh(); const mono sig = foldr(result, self.args, [&](ast::expr e, mono t) { return mono::infer(s, e) >>= t; }); s->unify(sig, func); return result; } // let mono operator()(const ast::let& self, const ref<state>& s) const { auto sub = scope(s); for(ast::def def : self.defs) { auto it = sub->locals.emplace(def.name, s->generalize(mono::infer(s, def.value))).first; (void) it; // std::clog << it->first << " : " << it->second << std::endl; } return mono::infer(sub, *self.body); } // sel mono operator()(const ast::sel& self, const ref<state>& s) const { const mono tail = s->fresh(kind::row()); const mono head = s->fresh(kind::term()); const mono row = apply(apply(ext(self.name), head), tail); return apply(rec, row); } // lit mono operator()(const ast::lit<::unit>& self, const ref<state>&) const { return unit; } mono operator()(const ast::lit<::boolean>& self, const ref<state>&) const { return boolean; } mono operator()(const ast::lit<::integer>& self, const ref<state>&) const { return integer; } mono operator()(const ast::lit<::real>& self, const ref<state>&) const { return real; } }; // polytype instantiation struct instantiate_visitor { using map_type = std::map<ref<variable>, ref<variable>>; const map_type& map; mono operator()(const ref<constant>& self) const { return self; } mono operator()(const ref<variable>& self) const { auto it = map.find(self); if(it != map.end()) { return it->second; } else { return self; } } mono operator()(const ref<application>& self) const { return apply(self->ctor.visit<mono>(*this), self->arg.visit<mono>(*this)); } }; static mono instantiate(poly self, std::size_t level) { // associate quantified variables with fresh variables instantiate_visitor::map_type map; for(const ref<variable>& it : self.forall) { assert(it->level <= level); map.emplace(it, make_ref<variable>( variable{level, it->kind} )); } // instantiate return self.type.visit<mono>(instantiate_visitor{map}); } mono mono::infer(const ref<state>& s, const ast::expr& self) { return self.visit<mono>(infer_visitor(), s); } // type state state::state() : level(0), sub(make_ref<substitution>()) { } state::state(const ref<state>& parent) : environment<poly>(parent), level(parent->level + 1), sub(parent->sub) { } ref<variable> state::fresh(kind::any k) const { return make_variable(level, k); } // generalize struct generalize_visitor { const std::size_t level; template<class OutputIterator> void operator()(const ref<constant>&, OutputIterator) const { } template<class OutputIterator> void operator()(const ref<variable>& self, OutputIterator out) const { // generalize if variable is deeper than current level if(self->level >= level) { *out++ = self; } } template<class OutputIterator> void operator()(const ref<application>& self, OutputIterator out) const { self->ctor.visit(*this, out); self->arg.visit(*this, out); } }; poly state::generalize(const mono& t) const { poly::forall_type forall; const mono s = substitute(t); s.visit(generalize_visitor{level}, std::inserter(forall, forall.begin())); return poly{forall, s}; } struct ostream_visitor { using map_type = std::map<ref<variable>, std::size_t>; map_type& map; void operator()(const ref<constant>& self, std::ostream& out, const poly::forall_type& forall) const { out << self->name; } void operator()(const ref<variable>& self, std::ostream& out, const poly::forall_type& forall) const { auto it = map.emplace(self, map.size()).first; if(forall.find(self) != forall.end()) { out << "'"; } else { out << "!"; } out << char('a' + it->second); if(debug) { out << "(" << std::hex << (long(self.get()) & 0xffff) << ")"; } } void operator()(const ref<application>& self, std::ostream& out, const poly::forall_type& forall) const { if(self->ctor == func) { self->arg.visit(*this, out, forall); out << " "; self->ctor.visit(*this, out, forall); } else { // TODO parens self->ctor.visit(*this, out, forall); out << " "; self->arg.visit(*this, out, forall); } } }; std::ostream& operator<<(std::ostream& out, const poly& self) { ostream_visitor::map_type map; self.type.visit(ostream_visitor{map}, out, self.forall); return out; } struct substitute_visitor { mono operator()(const ref<variable>& self, const state& s) const { auto it = s.sub->find(self); if(it == s.sub->end()) return self; assert(it->second != self); return s.substitute(it->second); } mono operator()(const ref<application>& self, const state& s) const { return apply(s.substitute(self->ctor), s.substitute(self->arg)); } mono operator()(const ref<constant>& self, const state&) const { return self; } }; mono state::substitute(const mono& t) const { return t.visit<mono>(substitute_visitor(), *this); } static std::size_t indent = 0; struct lock { lock() { ++indent; } ~lock() { --indent; } }; struct show { ostream_visitor::map_type& map; const poly& p; friend std::ostream& operator<<(std::ostream& out, const show& self) { self.p.type.visit(ostream_visitor{self.map}, out, self.p.forall); return out; } }; void state::unify(mono from, mono to) { const lock instance; using var = ref<variable>; using app = ref<application>; if( debug ) { ostream_visitor::map_type map; std::clog << std::string(2 * indent, '.') << "unifying: " << show{map, generalize(from)} << " with: " << show{map, generalize(to)} << std::endl; } // resolve from = substitute(from); to = substitute(to); // var -> var if(from.get<var>() && to.get<var>()) { // var <- var if(from.cast<var>()->level < to.cast<var>()->level) { sub->emplace(from.cast<var>(), to); return; } } // var -> mono if(auto v = from.get<var>()) { sub->emplace(*v, to); return; } // mono <- var if(auto v = to.get<var>()) { sub->emplace(*v, from); return; } // app <-> app if(from.get<app>() && to.get<app>()) { unify(from.cast<app>()->ctor, to.cast<app>()->ctor); unify(from.cast<app>()->arg, to.cast<app>()->arg); return; } if(from != to) { std::stringstream ss; ss << "cannot unify types \"" << generalize(from) << "\" and \"" << generalize(to) << "\""; throw error(ss.str()); } } }; <commit_msg>make sure unifications are kind-preserving<commit_after>#include "type.hpp" #include <vector> #include <sstream> #include "ast.hpp" #include "tool.hpp" namespace type { static const bool debug = false; static const auto make_constant = [](const char* name, kind::any k=kind::term()) { return make_ref<constant>(constant{symbol(name), k}); }; static const auto make_variable = [](std::size_t level, kind::any k=kind::term()) { return make_ref<variable>(variable{level, k}); }; // constants const ref<constant> unit = make_constant("unit"); const ref<constant> boolean = make_constant("boolean"); const ref<constant> integer = make_constant("integer"); const ref<constant> real = make_constant("real"); const ref<constant> func = make_constant("->", kind::term() >>= kind::term() >>= kind::term()); const ref<constant> io = make_constant("io", kind::term() >>= kind::term()); const ref<constant> rec = make_constant("record", kind::row() >>= kind::term()); const ref<constant> empty = make_constant("{}", kind::row()); ref<constant> ext(symbol attr) { static const kind::any k = kind::term() >>= kind::row() >>= kind::row(); static std::map<symbol, ref<constant>> table; const std::string name = std::string("@") + attr.get(); auto it = table.emplace(attr, make_constant(name.c_str(), k)); return it.first->second; } state& state::operator()(std::string s, mono t) { locals.emplace(s, generalize(t)); return *this; } static mono instantiate(poly self, std::size_t depth); ref<application> apply(mono ctor, mono arg) { return make_ref<application>(ctor, arg); } mono operator>>=(mono from, mono to) { return apply(apply(func, from), to); } application::application(mono ctor, mono arg) : ctor(ctor), arg(arg) { const kind::any k = ctor.kind(); if(auto c = k.get<ref<kind::constructor>>()) { if((*c)->from != arg.kind()) { std::clog << poly{{}, ctor} << " :: " << ctor.kind() << " " << poly{{}, arg} << " :: " << arg.kind() << std::endl; throw kind::error("argument has not the expected kind"); } } else { throw kind::error("type constructor must have constructor kind"); } } struct kind_visitor { kind::any operator()(const ref<constant>& self) const { return self->kind; } kind::any operator()(const ref<variable>& self) const { return self->kind; } kind::any operator()(const ref<application>& self) const { const kind::any k = self->ctor.kind(); if(auto c = k.get<ref<kind::constructor>>()) { return (*c)->to; } else { throw std::logic_error("derp"); } } }; kind::any mono::kind() const { return visit<kind::any>(kind_visitor()); } struct infer_visitor { template<class T> mono operator()(const T& self, const ref<state>&) const { throw std::logic_error("infer unimplemented: " + tool::type_name(typeid(T))); } // var mono operator()(const ast::var& self, const ref<state>& s) const { try { return instantiate(s->find(self.name), s->level); } catch(std::out_of_range& e) { throw error("unbound variable " + tool::quote(self.name.get())); } } // abs mono operator()(const ast::abs& self, const ref<state>& s) const { std::vector<poly> vars; // construct function type const mono result = s->fresh(); const mono sig = foldr(result, self.args, [&](symbol name, mono t) { const mono alpha = s->fresh(); // note: alpha is monomorphic in sigma const poly sigma = {{}, alpha}; vars.emplace_back(sigma); return alpha >>= t; }); // infer lambda body with augmented environment auto scope = augment(s, self.args, vars.rbegin(), vars.rend()); s->unify(result, mono::infer(scope, *self.body)); return sig; } // app mono operator()(const ast::app& self, const ref<state>& s) const { const mono func = mono::infer(s, *self.func); const mono result = s->fresh(); const mono sig = foldr(result, self.args, [&](ast::expr e, mono t) { return mono::infer(s, e) >>= t; }); s->unify(sig, func); return result; } // let mono operator()(const ast::let& self, const ref<state>& s) const { auto sub = scope(s); for(ast::def def : self.defs) { auto it = sub->locals.emplace(def.name, s->generalize(mono::infer(s, def.value))).first; (void) it; // std::clog << it->first << " : " << it->second << std::endl; } return mono::infer(sub, *self.body); } // sel mono operator()(const ast::sel& self, const ref<state>& s) const { const mono tail = s->fresh(kind::row()); const mono head = s->fresh(kind::term()); const mono row = apply(apply(ext(self.name), head), tail); return apply(rec, row); } // lit mono operator()(const ast::lit<::unit>& self, const ref<state>&) const { return unit; } mono operator()(const ast::lit<::boolean>& self, const ref<state>&) const { return boolean; } mono operator()(const ast::lit<::integer>& self, const ref<state>&) const { return integer; } mono operator()(const ast::lit<::real>& self, const ref<state>&) const { return real; } }; // polytype instantiation struct instantiate_visitor { using map_type = std::map<ref<variable>, ref<variable>>; const map_type& map; mono operator()(const ref<constant>& self) const { return self; } mono operator()(const ref<variable>& self) const { auto it = map.find(self); if(it != map.end()) { return it->second; } else { return self; } } mono operator()(const ref<application>& self) const { return apply(self->ctor.visit<mono>(*this), self->arg.visit<mono>(*this)); } }; static mono instantiate(poly self, std::size_t level) { // associate quantified variables with fresh variables instantiate_visitor::map_type map; for(const ref<variable>& it : self.forall) { assert(it->level <= level); map.emplace(it, make_ref<variable>( variable{level, it->kind} )); } // instantiate return self.type.visit<mono>(instantiate_visitor{map}); } mono mono::infer(const ref<state>& s, const ast::expr& self) { return self.visit<mono>(infer_visitor(), s); } // type state state::state() : level(0), sub(make_ref<substitution>()) { } state::state(const ref<state>& parent) : environment<poly>(parent), level(parent->level + 1), sub(parent->sub) { } ref<variable> state::fresh(kind::any k) const { return make_variable(level, k); } // generalize struct generalize_visitor { const std::size_t level; template<class OutputIterator> void operator()(const ref<constant>&, OutputIterator) const { } template<class OutputIterator> void operator()(const ref<variable>& self, OutputIterator out) const { // generalize if variable is deeper than current level if(self->level >= level) { *out++ = self; } } template<class OutputIterator> void operator()(const ref<application>& self, OutputIterator out) const { self->ctor.visit(*this, out); self->arg.visit(*this, out); } }; poly state::generalize(const mono& t) const { poly::forall_type forall; const mono s = substitute(t); s.visit(generalize_visitor{level}, std::inserter(forall, forall.begin())); return poly{forall, s}; } struct ostream_visitor { using map_type = std::map<ref<variable>, std::size_t>; map_type& map; void operator()(const ref<constant>& self, std::ostream& out, const poly::forall_type& forall) const { out << self->name; } void operator()(const ref<variable>& self, std::ostream& out, const poly::forall_type& forall) const { auto it = map.emplace(self, map.size()).first; if(forall.find(self) != forall.end()) { out << "'"; } else { out << "!"; } out << char('a' + it->second); if(debug) { out << "(" << std::hex << (long(self.get()) & 0xffff) << ")"; } } void operator()(const ref<application>& self, std::ostream& out, const poly::forall_type& forall) const { if(self->ctor == func) { self->arg.visit(*this, out, forall); out << " "; self->ctor.visit(*this, out, forall); } else { // TODO parens self->ctor.visit(*this, out, forall); out << " "; self->arg.visit(*this, out, forall); } } }; std::ostream& operator<<(std::ostream& out, const poly& self) { ostream_visitor::map_type map; self.type.visit(ostream_visitor{map}, out, self.forall); return out; } struct substitute_visitor { mono operator()(const ref<variable>& self, const state& s) const { auto it = s.sub->find(self); if(it == s.sub->end()) return self; assert(it->second != self); return s.substitute(it->second); } mono operator()(const ref<application>& self, const state& s) const { return apply(s.substitute(self->ctor), s.substitute(self->arg)); } mono operator()(const ref<constant>& self, const state&) const { return self; } }; mono state::substitute(const mono& t) const { return t.visit<mono>(substitute_visitor(), *this); } static std::size_t indent = 0; struct lock { lock() { ++indent; } ~lock() { --indent; } }; struct show { ostream_visitor::map_type& map; const poly& p; friend std::ostream& operator<<(std::ostream& out, const show& self) { self.p.type.visit(ostream_visitor{self.map}, out, self.p.forall); return out; } }; static void link(state* self, const ref<variable>& from, const mono& to) { assert(from->kind == to.kind()); if(!self->sub->emplace(from, to).second) { assert(false); } } void state::unify(mono from, mono to) { const lock instance; using var = ref<variable>; using app = ref<application>; if( debug ) { ostream_visitor::map_type map; std::clog << std::string(2 * indent, '.') << "unifying: " << show{map, generalize(from)} << " with: " << show{map, generalize(to)} << std::endl; } // resolve from = substitute(from); to = substitute(to); // var -> var if(from.get<var>() && to.get<var>()) { // var <- var if(from.cast<var>()->level < to.cast<var>()->level) { link(this, from.cast<var>(), to); return; } } // var -> mono if(auto v = from.get<var>()) { link(this, *v, to); return; } // mono <- var if(auto v = to.get<var>()) { link(this, *v, from); return; } // app <-> app if(from.get<app>() && to.get<app>()) { unify(from.cast<app>()->ctor, to.cast<app>()->ctor); unify(from.cast<app>()->arg, to.cast<app>()->arg); return; } if(from != to) { std::stringstream ss; ss << "cannot unify types \"" << generalize(from) << "\" and \"" << generalize(to) << "\""; throw error(ss.str()); } } }; <|endoftext|>
<commit_before>#include "mainwindow.h" #include "pagefactory.h" #include "dcppage.h" #include "maintranslations.h" #include <duiscenemanager.h> #include <QtDebug> #include <duiaction.h> #include <duiapplication.h> #include "dcpappletdb.h" MainWindow::MainWindow() { Pages::Handle handle = {Pages::MAIN, ""}; // Pages::Handle handle = {Pages::APPLET, "DateTime"}; changePage(handle); } void MainWindow::backClicked() { PageFactory::instance()->back(); } MainWindow::~MainWindow() { DcpAppletDb::instance()->destroy(); } void MainWindow::changePage(Pages::Handle handle) { DcpPage *page = PageFactory::instance()->create(handle); connect (page, SIGNAL(openSubPage(Pages::Handle)), this, SLOT(changePage(Pages::Handle))); connect(page, SIGNAL(backButtonClicked()), this, SLOT(backClicked())); // --- temporary to test rotating the device --- DuiAction* rotateAction = new DuiAction("ROT", page); rotateAction->setLocation(DuiAction::ToolBar); connect (rotateAction, SIGNAL (triggered()), this, SLOT(onRotateClicked())); // --- // closeAction DuiAction *quitAction = new DuiAction(DcpMain::quitMenuItemText, this); quitAction->setLocation(DuiAction::ViewMenu); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); // Add actions to page if (handle.id != Pages::MAIN) page->addAction(quitAction); page->addAction(rotateAction); page->appear(DuiSceneWindow::DestroyWhenDone); //TODO -> Destroy } /* * only for testing the orientation changei without a device, * not meant to be in final app */ void MainWindow::onRotateClicked() { DuiSceneManager *manager = DuiSceneManager::instance(); Dui::OrientationAngle angle = manager->orientationAngle(); if (angle == Dui::Angle270) { angle = Dui::Angle0; } else if (angle == Dui::Angle0) { angle = Dui::Angle90; } else if (angle == Dui::Angle90) { angle = Dui::Angle180; } else if (angle == Dui::Angle180) { angle = Dui::Angle270; } manager->setOrientationAngle (angle); } <commit_msg>KeepWhenDone for pages as a temporary solution for the segfault<commit_after>#include "mainwindow.h" #include "pagefactory.h" #include "dcppage.h" #include "maintranslations.h" #include <duiscenemanager.h> #include <QtDebug> #include <duiaction.h> #include <duiapplication.h> #include "dcpappletdb.h" MainWindow::MainWindow() { Pages::Handle handle = {Pages::MAIN, ""}; // Pages::Handle handle = {Pages::APPLET, "DateTime"}; changePage(handle); } void MainWindow::backClicked() { PageFactory::instance()->back(); } MainWindow::~MainWindow() { DcpAppletDb::instance()->destroy(); } void MainWindow::changePage(Pages::Handle handle) { DcpPage *page = PageFactory::instance()->create(handle); connect (page, SIGNAL(openSubPage(Pages::Handle)), this, SLOT(changePage(Pages::Handle))); connect(page, SIGNAL(backButtonClicked()), this, SLOT(backClicked())); // --- temporary to test rotating the device --- DuiAction* rotateAction = new DuiAction("ROT", page); rotateAction->setLocation(DuiAction::ToolBar); connect (rotateAction, SIGNAL (triggered()), this, SLOT(onRotateClicked())); // --- // closeAction DuiAction *quitAction = new DuiAction(DcpMain::quitMenuItemText, this); quitAction->setLocation(DuiAction::ViewMenu); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); // Add actions to page if (handle.id != Pages::MAIN) page->addAction(quitAction); page->addAction(rotateAction); // page->appear(DuiSceneWindow::DestroyWhenDone); page->appear(DuiSceneWindow::KeepWhenDone); // FIXME } /* * only for testing the orientation changei without a device, * not meant to be in final app */ void MainWindow::onRotateClicked() { DuiSceneManager *manager = DuiSceneManager::instance(); Dui::OrientationAngle angle = manager->orientationAngle(); if (angle == Dui::Angle270) { angle = Dui::Angle0; } else if (angle == Dui::Angle0) { angle = Dui::Angle90; } else if (angle == Dui::Angle90) { angle = Dui::Angle180; } else if (angle == Dui::Angle180) { angle = Dui::Angle270; } manager->setOrientationAngle (angle); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andreas Streichardt <andreas@arangodb.com> //////////////////////////////////////////////////////////////////////////////// #include "AuthenticationFeature.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Auth/Common.h" #include "Auth/Handler.h" #include "Basics/FileUtils.h" #include "Basics/StringUtils.h" #include "Cluster/ServerState.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "Random/RandomGenerator.h" #include "RestServer/QueryRegistryFeature.h" #if USE_ENTERPRISE #include "Enterprise/Ldap/LdapAuthenticationHandler.h" #include "Enterprise/Ldap/LdapFeature.h" #endif using namespace arangodb::options; namespace arangodb { AuthenticationFeature* AuthenticationFeature::INSTANCE = nullptr; AuthenticationFeature::AuthenticationFeature(application_features::ApplicationServer& server) : ApplicationFeature(server, "Authentication"), _userManager(nullptr), _authCache(nullptr), _authenticationUnixSockets(true), _authenticationSystemOnly(true), _localAuthentication(true), _active(true), _authenticationTimeout(0.0), _jwtSecretProgramOption("") { setOptional(false); startsAfter("BasicsPhase"); #ifdef USE_ENTERPRISE startsAfter("Ldap"); #endif } void AuthenticationFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addSection("server", "Server features"); options->addOldOption("server.disable-authentication", "server.authentication"); options->addOldOption("server.disable-authentication-unix-sockets", "server.authentication-unix-sockets"); options->addOldOption("server.authenticate-system-only", "server.authentication-system-only"); options->addOldOption("server.allow-method-override", "http.allow-method-override"); options->addOldOption("server.hide-product-header", "http.hide-product-header"); options->addOldOption("server.keep-alive-timeout", "http.keep-alive-timeout"); options->addOldOption("server.default-api-compatibility", ""); options->addOldOption("no-server", "server.rest-server"); options->addOption("--server.authentication", "enable authentication for ALL client requests", new BooleanParameter(&_active)); options->addOption( "--server.authentication-timeout", "timeout for the authentication cache in seconds (0 = indefinitely)", new DoubleParameter(&_authenticationTimeout)); options->addOption("--server.local-authentication", "enable authentication using the local user database", new BooleanParameter(&_localAuthentication)); options->addOption( "--server.authentication-system-only", "use HTTP authentication only for requests to /_api and /_admin", new BooleanParameter(&_authenticationSystemOnly)); #ifdef ARANGODB_HAVE_DOMAIN_SOCKETS options->addOption("--server.authentication-unix-sockets", "authentication for requests via UNIX domain sockets", new BooleanParameter(&_authenticationUnixSockets)); #endif // Maybe deprecate this option in devel options->addOption("--server.jwt-secret", "secret to use when doing jwt authentication", new StringParameter(&_jwtSecretProgramOption)) .setDeprecatedIn(30322).setDeprecatedIn(30402); options->addOption( "--server.jwt-secret-keyfile", "file containing jwt secret to use when doing jwt authentication.", new StringParameter(&_jwtSecretKeyfileProgramOption)); } void AuthenticationFeature::validateOptions(std::shared_ptr<ProgramOptions>) { if (!_jwtSecretKeyfileProgramOption.empty()) { try { // Note that the secret is trimmed for whitespace, because whitespace // at the end of a file can easily happen. We do not base64-encode, // though, so the bytes count as given. Zero bytes might be a problem // here. _jwtSecretProgramOption = basics::StringUtils::trim(basics::FileUtils::slurp(_jwtSecretKeyfileProgramOption), " \t\n\r"); } catch (std::exception const& ex) { LOG_TOPIC(FATAL, Logger::STARTUP) << "unable to read content of jwt-secret file '" << _jwtSecretKeyfileProgramOption << "': " << ex.what() << ". please make sure the file/directory is readable for the " "arangod process and user"; FATAL_ERROR_EXIT(); } } else if (!_jwtSecretProgramOption.empty()) { LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "--server.jwt-secret is insecure. Use --server.jwt-secret-keyfile " "instead."; if (_jwtSecretProgramOption.length() > _maxSecretLength) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "Given JWT secret too long. Max length is " << _maxSecretLength; FATAL_ERROR_EXIT(); } } } void AuthenticationFeature::prepare() { TRI_ASSERT(isEnabled()); TRI_ASSERT(_userManager == nullptr); ServerState::RoleEnum role = ServerState::instance()->getRole(); TRI_ASSERT(role != ServerState::RoleEnum::ROLE_UNDEFINED); if (ServerState::isSingleServer(role) || ServerState::isCoordinator(role)) { #if USE_ENTERPRISE if (application_features::ApplicationServer::getFeature<LdapFeature>("Ldap")->isEnabled()) { _userManager.reset( new auth::UserManager(std::make_unique<LdapAuthenticationHandler>())); } else { _userManager.reset(new auth::UserManager()); } #else _userManager.reset(new auth::UserManager()); #endif } else { LOG_TOPIC(DEBUG, Logger::AUTHENTICATION) << "Not creating user manager"; } TRI_ASSERT(_authCache == nullptr); _authCache.reset(new auth::TokenCache(_userManager.get(), _authenticationTimeout)); std::string jwtSecret = _jwtSecretProgramOption; if (jwtSecret.empty()) { LOG_TOPIC(INFO, Logger::AUTHENTICATION) << "Jwt secret not specified, generating..."; uint16_t m = 254; for (size_t i = 0; i < _maxSecretLength; i++) { jwtSecret += (1 + RandomGenerator::interval(m)); } } _authCache->setJwtSecret(jwtSecret); INSTANCE = this; } void AuthenticationFeature::start() { TRI_ASSERT(isEnabled()); std::ostringstream out; out << "Authentication is turned " << (_active ? "on" : "off"); if (_userManager != nullptr) { auto queryRegistryFeature = application_features::ApplicationServer::getFeature<QueryRegistryFeature>( "QueryRegistry"); _userManager->setQueryRegistry(queryRegistryFeature->queryRegistry()); } if (_active && _authenticationSystemOnly) { out << " (system only)"; } #ifdef ARANGODB_HAVE_DOMAIN_SOCKETS out << ", authentication for unix sockets is turned " << (_authenticationUnixSockets ? "on" : "off"); #endif LOG_TOPIC(INFO, arangodb::Logger::AUTHENTICATION) << out.str(); } void AuthenticationFeature::unprepare() { INSTANCE = nullptr; } } // namespace arangodb <commit_msg>Bug fix/jwt secret file logging (#7976)<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andreas Streichardt <andreas@arangodb.com> //////////////////////////////////////////////////////////////////////////////// #include "AuthenticationFeature.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Auth/Common.h" #include "Auth/Handler.h" #include "Basics/FileUtils.h" #include "Basics/StringUtils.h" #include "Cluster/ServerState.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "Random/RandomGenerator.h" #include "RestServer/QueryRegistryFeature.h" #if USE_ENTERPRISE #include "Enterprise/Ldap/LdapAuthenticationHandler.h" #include "Enterprise/Ldap/LdapFeature.h" #endif using namespace arangodb::options; namespace arangodb { AuthenticationFeature* AuthenticationFeature::INSTANCE = nullptr; AuthenticationFeature::AuthenticationFeature(application_features::ApplicationServer& server) : ApplicationFeature(server, "Authentication"), _userManager(nullptr), _authCache(nullptr), _authenticationUnixSockets(true), _authenticationSystemOnly(true), _localAuthentication(true), _active(true), _authenticationTimeout(0.0), _jwtSecretProgramOption("") { setOptional(false); startsAfter("BasicsPhase"); #ifdef USE_ENTERPRISE startsAfter("Ldap"); #endif } void AuthenticationFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { options->addSection("server", "Server features"); options->addOldOption("server.disable-authentication", "server.authentication"); options->addOldOption("server.disable-authentication-unix-sockets", "server.authentication-unix-sockets"); options->addOldOption("server.authenticate-system-only", "server.authentication-system-only"); options->addOldOption("server.allow-method-override", "http.allow-method-override"); options->addOldOption("server.hide-product-header", "http.hide-product-header"); options->addOldOption("server.keep-alive-timeout", "http.keep-alive-timeout"); options->addOldOption("server.default-api-compatibility", ""); options->addOldOption("no-server", "server.rest-server"); options->addOption("--server.authentication", "enable authentication for ALL client requests", new BooleanParameter(&_active)); options->addOption( "--server.authentication-timeout", "timeout for the authentication cache in seconds (0 = indefinitely)", new DoubleParameter(&_authenticationTimeout)); options->addOption("--server.local-authentication", "enable authentication using the local user database", new BooleanParameter(&_localAuthentication)); options->addOption( "--server.authentication-system-only", "use HTTP authentication only for requests to /_api and /_admin", new BooleanParameter(&_authenticationSystemOnly)); #ifdef ARANGODB_HAVE_DOMAIN_SOCKETS options->addOption("--server.authentication-unix-sockets", "authentication for requests via UNIX domain sockets", new BooleanParameter(&_authenticationUnixSockets)); #endif // Maybe deprecate this option in devel options->addOption("--server.jwt-secret", "secret to use when doing jwt authentication", new StringParameter(&_jwtSecretProgramOption)) .setDeprecatedIn(30322).setDeprecatedIn(30402); options->addOption( "--server.jwt-secret-keyfile", "file containing jwt secret to use when doing jwt authentication.", new StringParameter(&_jwtSecretKeyfileProgramOption)); } void AuthenticationFeature::validateOptions(std::shared_ptr<ProgramOptions>) { if (!_jwtSecretKeyfileProgramOption.empty()) { try { // Note that the secret is trimmed for whitespace, because whitespace // at the end of a file can easily happen. We do not base64-encode, // though, so the bytes count as given. Zero bytes might be a problem // here. _jwtSecretProgramOption = basics::StringUtils::trim(basics::FileUtils::slurp(_jwtSecretKeyfileProgramOption), " \t\n\r"); } catch (std::exception const& ex) { LOG_TOPIC(FATAL, Logger::STARTUP) << "unable to read content of jwt-secret file '" << _jwtSecretKeyfileProgramOption << "': " << ex.what() << ". please make sure the file/directory is readable for the " "arangod process and user"; FATAL_ERROR_EXIT(); } } else if (!_jwtSecretProgramOption.empty()) { if (_jwtSecretProgramOption.length() > _maxSecretLength) { LOG_TOPIC(FATAL, arangodb::Logger::STARTUP) << "Given JWT secret too long. Max length is " << _maxSecretLength; FATAL_ERROR_EXIT(); } } } void AuthenticationFeature::prepare() { TRI_ASSERT(isEnabled()); TRI_ASSERT(_userManager == nullptr); ServerState::RoleEnum role = ServerState::instance()->getRole(); TRI_ASSERT(role != ServerState::RoleEnum::ROLE_UNDEFINED); if (ServerState::isSingleServer(role) || ServerState::isCoordinator(role)) { #if USE_ENTERPRISE if (application_features::ApplicationServer::getFeature<LdapFeature>("Ldap")->isEnabled()) { _userManager.reset( new auth::UserManager(std::make_unique<LdapAuthenticationHandler>())); } else { _userManager.reset(new auth::UserManager()); } #else _userManager.reset(new auth::UserManager()); #endif } else { LOG_TOPIC(DEBUG, Logger::AUTHENTICATION) << "Not creating user manager"; } TRI_ASSERT(_authCache == nullptr); _authCache.reset(new auth::TokenCache(_userManager.get(), _authenticationTimeout)); std::string jwtSecret = _jwtSecretProgramOption; if (jwtSecret.empty()) { LOG_TOPIC(INFO, Logger::AUTHENTICATION) << "Jwt secret not specified, generating..."; uint16_t m = 254; for (size_t i = 0; i < _maxSecretLength; i++) { jwtSecret += (1 + RandomGenerator::interval(m)); } } _authCache->setJwtSecret(jwtSecret); INSTANCE = this; } void AuthenticationFeature::start() { TRI_ASSERT(isEnabled()); // If this is empty here, --server.jwt-secret was used if (_jwtSecretKeyfileProgramOption.empty()) { LOG_TOPIC(WARN, arangodb::Logger::AUTHENTICATION) << "--server.jwt-secret is insecure. Use --server.jwt-secret-keyfile " "instead."; } std::ostringstream out; out << "Authentication is turned " << (_active ? "on" : "off"); if (_userManager != nullptr) { auto queryRegistryFeature = application_features::ApplicationServer::getFeature<QueryRegistryFeature>( "QueryRegistry"); _userManager->setQueryRegistry(queryRegistryFeature->queryRegistry()); } if (_active && _authenticationSystemOnly) { out << " (system only)"; } #ifdef ARANGODB_HAVE_DOMAIN_SOCKETS out << ", authentication for unix sockets is turned " << (_authenticationUnixSockets ? "on" : "off"); #endif LOG_TOPIC(INFO, arangodb::Logger::AUTHENTICATION) << out.str(); } void AuthenticationFeature::unprepare() { INSTANCE = nullptr; } } // namespace arangodb <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <list> #include <queue> #include <string> #include <ctime> #include "jsoncpp/json.h" using namespace std; const int MAX_N = 25; const int dx[4] = {-1, 0, 1, 0}; const int dy[4] = {0, 1, 0, -1}; bool invalid[MAX_N][MAX_N]; int n, m; struct Point { int x, y; Point(const int &_x, const int &_y) : x(_x), y(_y) {} }; list<Point> snake[2]; // 0ʾԼߣ1ʾԷ int possibleDire[10]; int posCount; bool whetherGrow(int num) //غǷ { if (num <= 9) return true; if ((num - 9) % 3 == 0) return true; return false; } void deleteEnd(int id) //ɾβ { snake[id].pop_back(); } void move(int id, int dire, int num) //Ϊid߳direƶһ { Point p = *(snake[id].begin()); int x = p.x + dx[dire]; int y = p.y + dy[dire]; snake[id].push_front(Point(x, y)); if (!whetherGrow(num)) deleteEnd(id); } void outputSnakeBody(int id) // { cout << "Snake No." << id << endl; for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) cout << iter->x << " " << iter->y << endl; cout << endl; } bool isInBody(int x, int y) //ж(x,y)λǷ { for (int id = 0; id <= 1; id++) for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) if (x == iter->x && y == iter->y) return true; return false; } bool validDirection(int id, int k) //жϵǰƶһǷϷ { Point p = *(snake[id].begin()); int x = p.x + dx[k]; int y = p.y + dy[k]; if (x > n || y > m || x < 1 || y < 1) return false; if (invalid[x][y]) return false; if (isInBody(x, y)) return false; return true; } int canPass[MAX_N][MAX_N] = {0}; void MaintainMap() { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (invalid[i][j]) { canPass[i][j] = 100000; } else { canPass[i][j] = 0; } } } for (int id = 0; id <= 1; id++) { int len = 1; for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) { canPass[iter->x][iter->y] = len++; } } } int BFS(const int &sX, const int &sY) { bool vis[MAX_N][MAX_N] = {0}; queue<Point> que; que.push(Point(sX, sY)); vis[sX][sY] = true; int cnt = 1; while (!que.empty()) { for (int i = 0; i < 4; ++i) { int tX = que.front().x + dx[i]; int tY = que.front().y + dy[i]; if (tX < 1 || tY < 1 || tX > n || tY > m || canPass[tX][tY] > 0) { continue; } if (!vis[tX][tY]) { vis[tX][tY] = true; ++cnt; que.push(Point(tX, tY)); } } que.pop(); } return cnt; } int CurHeadDirection(int id) { list<Point>::iterator iter = snake[id].begin(); Point head = *iter++; Point next = *iter; if (head.x == next.x) { if (head.y == next.y + 1) { return 1; } else { return 3; } } else { if (head.x == next.y + 1) { return 2; } else { return 0; } } } int MakeDecision(Json::Value &ret) { MaintainMap(); vector<int> consider; int bestCnt = 0; int headX = snake[0].begin()->x; int headY = snake[0].begin()->y; int cnt = 0; for (int dir = 0; dir < 4; ++dir) { if (validDirection(0, dir)) { int sX = headX + dx[dir]; int sY = headY + dy[dir]; int result = BFS(sX, sY); ostringstream oss; oss << "BFS at (" << sX << "," << sY << ") with empty unit " << result; ret["response"]["debug"][cnt++] = oss.str().c_str(); if (bestCnt < result) { consider.clear(); consider.push_back(dir); bestCnt = result; } else if (bestCnt == result) { consider.push_back(dir); } } } srand((unsigned)time(NULL)); return consider[rand() % consider.size()]; } int main() { memset(invalid, 0, sizeof(invalid)); string str; string temp; while (getline(cin, temp)) str += temp; Json::Reader reader; Json::Value input; reader.parse(str, input); n = input["requests"][(Json::Value::UInt) 0]["height"].asInt(); //̸߶ m = input["requests"][(Json::Value::UInt) 0]["width"].asInt(); //̿ int x = input["requests"][(Json::Value::UInt) 0]["x"].asInt(); //߳ʼϢ if (x == 1) { snake[0].push_front(Point(1, 1)); snake[1].push_front(Point(n, m)); } else { snake[1].push_front(Point(1, 1)); snake[0].push_front(Point(n, m)); } //ͼеϰ int obsCount = input["requests"][(Json::Value::UInt) 0]["obstacle"].size(); for (int i = 0; i < obsCount; i++) { int ox = input["requests"][(Json::Value::UInt) 0]["obstacle"][(Json::Value::UInt) i]["x"].asInt(); int oy = input["requests"][(Json::Value::UInt) 0]["obstacle"][(Json::Value::UInt) i]["y"].asInt(); invalid[ox][oy] = 1; } //ʷϢֳָ int total = input["responses"].size(); int dire; for (int i = 0; i < total; i++) { dire = input["responses"][i]["direction"].asInt(); move(0, dire, i); dire = input["requests"][i + 1]["direction"].asInt(); move(1, dire, i); } if (!whetherGrow(total)) // غ { deleteEnd(0); deleteEnd(1); } Json::Value ret; ret["response"]["direction"] = MakeDecision(ret); Json::FastWriter writer; cout << writer.write(ret) << endl; return 0; }<commit_msg>use a method named 'eat tail' to make decision<commit_after>#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <list> #include <queue> #include <string> #include <vector> #include <ctime> #include <climits> #include "jsoncpp/json.h" using namespace std; const int MAX_N = 25; const int dx[4] = {-1, 0, 1, 0}; const int dy[4] = {0, 1, 0, -1}; bool invalid[MAX_N][MAX_N]; int n, m; struct Point { int x, y; Point(const int &_x = 0, const int &_y = 0) : x(_x), y(_y) {} }; list<Point> snake[2]; // 0ʾԼߣ1ʾԷ int possibleDire[10]; int posCount; bool whetherGrow(int num) //غǷ { if (num <= 9) return true; if ((num - 9) % 3 == 0) return true; return false; } void deleteEnd(int id) //ɾβ { snake[id].pop_back(); } void move(int id, int dire, int num) //Ϊid߳direƶһ { Point p = *(snake[id].begin()); int x = p.x + dx[dire]; int y = p.y + dy[dire]; snake[id].push_front(Point(x, y)); if (!whetherGrow(num)) deleteEnd(id); } void outputSnakeBody(int id) // { cout << "Snake No." << id << endl; for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) cout << iter->x << " " << iter->y << endl; cout << endl; } bool isInBody(int x, int y) //ж(x,y)λǷ { for (int id = 0; id <= 1; id++) for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) if (x == iter->x && y == iter->y) return true; return false; } bool validDirection(int id, int k) //жϵǰƶһǷϷ { Point p = *(snake[id].begin()); int x = p.x + dx[k]; int y = p.y + dy[k]; if (x > n || y > m || x < 1 || y < 1) return false; if (invalid[x][y]) return false; if (isInBody(x, y)) return false; return true; } int MakeDecision(); int main() { memset(invalid, 0, sizeof(invalid)); string str; string temp; while (getline(cin, temp)) str += temp; Json::Reader reader; Json::Value input; reader.parse(str, input); n = input["requests"][(Json::Value::UInt) 0]["height"].asInt(); //̸߶ m = input["requests"][(Json::Value::UInt) 0]["width"].asInt(); //̿ int x = input["requests"][(Json::Value::UInt) 0]["x"].asInt(); //߳ʼϢ if (x == 1) { snake[0].push_front(Point(1, 1)); snake[1].push_front(Point(n, m)); } else { snake[1].push_front(Point(1, 1)); snake[0].push_front(Point(n, m)); } //ͼеϰ int obsCount = input["requests"][(Json::Value::UInt) 0]["obstacle"].size(); for (int i = 0; i < obsCount; i++) { int ox = input["requests"][(Json::Value::UInt) 0]["obstacle"][(Json::Value::UInt) i]["x"].asInt(); int oy = input["requests"][(Json::Value::UInt) 0]["obstacle"][(Json::Value::UInt) i]["y"].asInt(); invalid[ox][oy] = 1; } //ʷϢֳָ int total = input["responses"].size(); int dire; for (int i = 0; i < total; i++) { dire = input["responses"][i]["direction"].asInt(); move(0, dire, i); dire = input["requests"][i + 1]["direction"].asInt(); move(1, dire, i); } if (!whetherGrow(total)) // غ { deleteEnd(0); deleteEnd(1); } Json::Value ret; ret["response"]["direction"] = MakeDecision(); Json::FastWriter writer; cout << writer.write(ret) << endl; return 0; } int grid[MAX_N][MAX_N] = {0}; void MaintainGrid() { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (invalid[i][j]) { grid[i][j] = INT_MAX; } else { grid[i][j] = 0; } } } for (int id = 0; id <= 1; ++id) { for (list<Point>::iterator iter = snake[id].begin(); iter != snake[id].end(); ++iter) { grid[iter->x][iter->y] = id == 0 ? 1 : -1; } } } int dist[MAX_N][MAX_N] = {0}; void BFS(const Point &S) { memset(dist, 0x7f, sizeof(dist)); queue<Point> que; que.push(S); dist[S.x][S.y] = 0; while (!que.empty()) { for (int i = 0; i < 4; ++i) { int X = que.front().x + dx[i]; int Y = que.front().y + dy[i]; if (X < 1 || Y < 1 || X > n || Y > m || grid[X][Y] > 0) { continue; } if (dist[X][Y] > dist[que.front().x][que.front().y] + 1) { dist[X][Y] = dist[que.front().x][que.front().y] + 1; que.push(Point(X, Y)); } } que.pop(); } } inline Point GetHead(const int &id) { return snake[id].front(); } inline Point GetTail(const int &id) { return snake[id].back(); } int MakeDecision() { srand((unsigned)time(NULL)); MaintainGrid(); Point head = GetHead(0); Point tail = GetTail(0); //BFS from the tail of snake No.0 BFS(tail); if (dist[head.x][head.y] < 0x7f7f7f7f) { // Can reach the tail of snake No.0 deque<int> choice; int farthest = 0; for (int i = 0; i < 4; ++i) { int X = head.x + dx[i]; int Y = head.y + dy[i]; if (validDirection(0, i)) { if (dist[X][Y] < 0x7f7f7f7f && farthest <= dist[X][Y]) { farthest = dist[X][Y]; choice.push_front(i); } else if (dist[X][Y] < 0x7f7f7f7f) { choice.push_back(i); } } } return choice[choice.size() >> 1]; } else { // Cannot reach the tail of snake No.0 tail = GetTail(1); BFS(tail); // Try to reach the tail of snake No.1 if (dist[head.x][head.y] < 0x7f7f7f7f) { // Can reach the tail of snake No.1 deque<int> choice; int farthest = 0; for (int i = 0; i < 4; ++i) { int X = head.x + dx[i]; int Y = head.y + dy[i]; if (validDirection(0, i)) { if (dist[X][Y] < 0x7f7f7f7f && farthest <= dist[X][Y]) { farthest = dist[X][Y]; choice.push_front(i); } else if (dist[X][Y] < 0x7f7f7f7f) { choice.push_back(i); } } } return choice[choice.size() >> 1]; } else { // Cannot reach the tail of snake No.1 Point target; BFS(head); for (list<Point>::iterator iter1 = snake[0].begin(), iter2 = snake[1].begin(); iter1 != snake[0].end() && iter2 != snake[1].end(); iter1++, iter2++) { if (dist[iter2->x][iter2->y] < 0x7f7f7f7f) { target = *iter2; } if (dist[iter1->x][iter1->y] < 0x7f7f7f7f) { target = *iter1; } } if (target.x == 0 && target.y == 0) { goto RANDOM_DECISION; } BFS(target); deque<int> choice; int farthest = 0; for (int i = 0; i < 4; ++i) { int X = head.x + dx[i]; int Y = head.y + dy[i]; if (validDirection(0, i)) { if (dist[X][Y] < 0x7f7f7f7f && farthest <= dist[X][Y]) { farthest = dist[X][Y]; choice.push_front(i); } else if (dist[X][Y] < 0x7f7f7f7f) { choice.push_back(i); } } } return choice[choice.size() >> 1]; } } RANDOM_DECISION: vector<int> choice; for (int i = 0; i < 4; ++i) { if (validDirection(0, i)) { choice.push_back(i); } } return choice[rand() % choice.size()]; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: out_position.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-11-02 16:42:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <toolkit/out_position.hxx> // NOT FULLY DEFINED SERVICES namespace output { namespace { const int C_nAssumedMaxLinkLength = 500; void move_ToParent( Node * & io_node, intt i_levels = 1 ); void move_ToParent( Node * & io_node, intt i_levels ) { for ( intt n = 0; n < i_levels; ++n ) { csv_assert(io_node != 0); io_node = io_node->Parent(); } } } // namepace anonymous Position::Position() : sFile(), pDirectory(&Node::Null_()) { } Position::Position( Node & i_directory, const String & i_file ) : sFile(i_file), pDirectory(&i_directory) { } Position::Position( const Position & i_directory, const String & i_sDifferentFile ) : sFile(i_sDifferentFile), pDirectory(i_directory.pDirectory) { } Position::~Position() { } Position & Position::operator=( Node & i_node ) { pDirectory = &i_node; sFile.clear(); return *this; } Position & Position::operator+=( const String & i_nodeName ) { csv_assert(pDirectory != 0); pDirectory = &pDirectory->Provide_Child(i_nodeName); sFile.clear(); return *this; } Position & Position::operator-=( intt i_levels ) { csv_assert(pDirectory != 0); for ( intt i = i_levels; i > 0; --i ) { pDirectory = pDirectory->Parent(); if (pDirectory == 0) { pDirectory = &Node::Null_(); i = 0; } } sFile.clear(); return *this; } String Position::LinkTo( const Position & i_destination, const String & i_localLabel ) const { StreamLock aLink(C_nAssumedMaxLinkLength); StreamStr & rLink = aLink(); Get_LinkTo(rLink, i_destination, i_localLabel); return rLink.c_str(); } String Position::LinkToRoot( const String & ) const { StreamLock sl(C_nAssumedMaxLinkLength); return sl() << get_UpLink(Depth()) << c_str; } void Position::Get_LinkTo( StreamStr & o_result, const Position & i_destination, const String & i_localLabel ) const { Node * p1 = pDirectory; Node * p2 = i_destination.pDirectory; intt diff = Depth() - i_destination.Depth(); intt pathLength1 = 0; intt pathLength2 = 0; if ( diff > 0 ) { pathLength1 = diff; move_ToParent(p1,pathLength1); } else if ( diff < 0 ) { pathLength2 = -diff; move_ToParent(p2,pathLength2); } while ( p1 != p2 ) { move_ToParent(p1); move_ToParent(p2); ++pathLength1; ++pathLength2; } o_result << get_UpLink(pathLength1); i_destination.pDirectory->Get_Path(o_result, pathLength2); o_result << i_destination.sFile; if (i_localLabel.length()) o_result << "#" << i_localLabel; } void Position::Get_LinkToRoot( StreamStr & o_result, const String & ) const { o_result << get_UpLink(Depth()); } void Position::Set( Node & i_node, const String & i_file ) { sFile = i_file; pDirectory = &i_node; } const char * get_UpLink(uintt i_depth) { static const uintt C_nMaxDepth = 30; static const char C_sUpLinkArray[3*C_nMaxDepth+1] = "../../../../../../../../../../" "../../../../../../../../../../" "../../../../../../../../../../"; static const char * C_sUpLink = &C_sUpLinkArray[0]; if ( i_depth <= C_nMaxDepth ) { return C_sUpLink + 3*(C_nMaxDepth - i_depth); } else { // not THREAD fast static std::vector<char> aRet; uintt nNeededSize = i_depth * 3 + 1; if (aRet.size() < nNeededSize) { aRet.resize(nNeededSize); char * pEnd = &aRet[nNeededSize-1]; *pEnd = '\0'; for ( char * pFill = &(*aRet.begin()); pFill != pEnd; pFill += 3 ) { memcpy(pFill, C_sUpLink, 3); } } // end if return &aRet[aRet.size() - 1 - 3*i_depth]; } } } // namespace output <commit_msg>INTEGRATION: CWS changefileheader (1.8.22); FILE MERGED 2008/03/28 16:02:15 rt 1.8.22.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: out_position.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <precomp.h> #include <toolkit/out_position.hxx> // NOT FULLY DEFINED SERVICES namespace output { namespace { const int C_nAssumedMaxLinkLength = 500; void move_ToParent( Node * & io_node, intt i_levels = 1 ); void move_ToParent( Node * & io_node, intt i_levels ) { for ( intt n = 0; n < i_levels; ++n ) { csv_assert(io_node != 0); io_node = io_node->Parent(); } } } // namepace anonymous Position::Position() : sFile(), pDirectory(&Node::Null_()) { } Position::Position( Node & i_directory, const String & i_file ) : sFile(i_file), pDirectory(&i_directory) { } Position::Position( const Position & i_directory, const String & i_sDifferentFile ) : sFile(i_sDifferentFile), pDirectory(i_directory.pDirectory) { } Position::~Position() { } Position & Position::operator=( Node & i_node ) { pDirectory = &i_node; sFile.clear(); return *this; } Position & Position::operator+=( const String & i_nodeName ) { csv_assert(pDirectory != 0); pDirectory = &pDirectory->Provide_Child(i_nodeName); sFile.clear(); return *this; } Position & Position::operator-=( intt i_levels ) { csv_assert(pDirectory != 0); for ( intt i = i_levels; i > 0; --i ) { pDirectory = pDirectory->Parent(); if (pDirectory == 0) { pDirectory = &Node::Null_(); i = 0; } } sFile.clear(); return *this; } String Position::LinkTo( const Position & i_destination, const String & i_localLabel ) const { StreamLock aLink(C_nAssumedMaxLinkLength); StreamStr & rLink = aLink(); Get_LinkTo(rLink, i_destination, i_localLabel); return rLink.c_str(); } String Position::LinkToRoot( const String & ) const { StreamLock sl(C_nAssumedMaxLinkLength); return sl() << get_UpLink(Depth()) << c_str; } void Position::Get_LinkTo( StreamStr & o_result, const Position & i_destination, const String & i_localLabel ) const { Node * p1 = pDirectory; Node * p2 = i_destination.pDirectory; intt diff = Depth() - i_destination.Depth(); intt pathLength1 = 0; intt pathLength2 = 0; if ( diff > 0 ) { pathLength1 = diff; move_ToParent(p1,pathLength1); } else if ( diff < 0 ) { pathLength2 = -diff; move_ToParent(p2,pathLength2); } while ( p1 != p2 ) { move_ToParent(p1); move_ToParent(p2); ++pathLength1; ++pathLength2; } o_result << get_UpLink(pathLength1); i_destination.pDirectory->Get_Path(o_result, pathLength2); o_result << i_destination.sFile; if (i_localLabel.length()) o_result << "#" << i_localLabel; } void Position::Get_LinkToRoot( StreamStr & o_result, const String & ) const { o_result << get_UpLink(Depth()); } void Position::Set( Node & i_node, const String & i_file ) { sFile = i_file; pDirectory = &i_node; } const char * get_UpLink(uintt i_depth) { static const uintt C_nMaxDepth = 30; static const char C_sUpLinkArray[3*C_nMaxDepth+1] = "../../../../../../../../../../" "../../../../../../../../../../" "../../../../../../../../../../"; static const char * C_sUpLink = &C_sUpLinkArray[0]; if ( i_depth <= C_nMaxDepth ) { return C_sUpLink + 3*(C_nMaxDepth - i_depth); } else { // not THREAD fast static std::vector<char> aRet; uintt nNeededSize = i_depth * 3 + 1; if (aRet.size() < nNeededSize) { aRet.resize(nNeededSize); char * pEnd = &aRet[nNeededSize-1]; *pEnd = '\0'; for ( char * pFill = &(*aRet.begin()); pFill != pEnd; pFill += 3 ) { memcpy(pFill, C_sUpLink, 3); } } // end if return &aRet[aRet.size() - 1 - 3*i_depth]; } } } // namespace output <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: out_position.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 18:02:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <toolkit/out_position.hxx> // NOT FULLY DEFINED SERVICES namespace output { namespace { const int C_nAssumedMaxLinkLength = 500; void move_ToParent( Node * & io_node, intt i_levels = 1 ); void move_ToParent( Node * & io_node, intt i_levels ) { for ( intt n = 0; n < i_levels; ++n ) { csv_assert(io_node != 0); io_node = io_node->Parent(); } } } // namepace anonymous Position::Position() : sFile(), pDirectory(&Node::Null_()) { } Position::Position( Node & i_directory, const String & i_file ) : sFile(i_file), pDirectory(&i_directory) { } Position::Position( Position & i_directory, const String & i_sDifferentFile ) : sFile(i_sDifferentFile), pDirectory(i_directory.pDirectory) { } Position::~Position() { } Position & Position::operator=( Node & i_node ) { pDirectory = &i_node; sFile.clear(); return *this; } Position & Position::operator+=( const String & i_nodeName ) { csv_assert(pDirectory != 0); pDirectory = &pDirectory->Provide_Child(i_nodeName); sFile.clear(); return *this; } Position & Position::operator-=( intt i_levels ) { csv_assert(pDirectory != 0); pDirectory = pDirectory->Parent(); if (pDirectory == 0) pDirectory = &Node::Null_(); sFile.clear(); return *this; } String Position::LinkTo( Position & i_destination, const String & i_localLabel ) const { StreamLock aLink(C_nAssumedMaxLinkLength); StreamStr & rLink = aLink(); Get_LinkTo(rLink, i_destination, i_localLabel); return rLink.c_str(); } String Position::LinkToRoot( const String & i_localLabel ) const { return StreamLock(C_nAssumedMaxLinkLength)() << get_UpLink(Depth()) << c_str; } void Position::Get_LinkTo( StreamStr & o_result, Position & i_destination, const String & i_localLabel ) const { Node * p1 = pDirectory; Node * p2 = i_destination.pDirectory; intt diff = Depth() - i_destination.Depth(); intt pathLength1 = 0; intt pathLength2 = 0; if ( diff > 0 ) { pathLength1 = diff; move_ToParent(p1,pathLength1); } else if ( diff < 0 ) { pathLength2 = -diff; move_ToParent(p2,pathLength2); } while ( p1 != p2 ) { move_ToParent(p1); move_ToParent(p2); ++pathLength1; ++pathLength2; } o_result << get_UpLink(pathLength1); i_destination.pDirectory->Get_Path(o_result, pathLength2); o_result << i_destination.sFile; if (i_localLabel.length()) o_result << "#" << i_localLabel; } void Position::Get_LinkToRoot( StreamStr & o_result, const String & i_localLabel ) const { o_result << get_UpLink(Depth()); } void Position::Set( Node & i_node, const String & i_file ) { sFile = i_file; pDirectory = &i_node; } const char * get_UpLink(uintt i_depth) { static const uintt C_nMaxDepth = 30; static const char C_sUpLinkArray[3*C_nMaxDepth+1] = "../../../../../../../../../../" "../../../../../../../../../../" "../../../../../../../../../../"; static const char * C_sUpLink = &C_sUpLinkArray[0]; if ( i_depth <= C_nMaxDepth ) { return C_sUpLink + 3*(C_nMaxDepth - i_depth); } else { // not THREAD fast static std::vector<char> aRet; uintt nNeededSize = i_depth * 3 + 1; if (aRet.size() < nNeededSize) { aRet.resize(nNeededSize); char * pEnd = &aRet[nNeededSize-1]; *pEnd = '\0'; for ( char * pFill = &(*aRet.begin()); pFill != pEnd; pFill += 3 ) { memcpy(pFill, C_sUpLink, 3); } } // end if return &aRet[aRet.size() - 1 - 3*i_depth]; } } } // namespace output <commit_msg>INTEGRATION: CWS warnings01 (1.4.4); FILE MERGED 2005/10/19 09:29:01 np 1.4.4.2: #i53898# 2005/10/18 08:36:03 np 1.4.4.1: #i53898#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: out_position.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 12:01:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include <toolkit/out_position.hxx> // NOT FULLY DEFINED SERVICES namespace output { namespace { const int C_nAssumedMaxLinkLength = 500; void move_ToParent( Node * & io_node, intt i_levels = 1 ); void move_ToParent( Node * & io_node, intt i_levels ) { for ( intt n = 0; n < i_levels; ++n ) { csv_assert(io_node != 0); io_node = io_node->Parent(); } } } // namepace anonymous Position::Position() : sFile(), pDirectory(&Node::Null_()) { } Position::Position( Node & i_directory, const String & i_file ) : sFile(i_file), pDirectory(&i_directory) { } Position::Position( Position & i_directory, const String & i_sDifferentFile ) : sFile(i_sDifferentFile), pDirectory(i_directory.pDirectory) { } Position::~Position() { } Position & Position::operator=( Node & i_node ) { pDirectory = &i_node; sFile.clear(); return *this; } Position & Position::operator+=( const String & i_nodeName ) { csv_assert(pDirectory != 0); pDirectory = &pDirectory->Provide_Child(i_nodeName); sFile.clear(); return *this; } Position & Position::operator-=( intt i_levels ) { csv_assert(pDirectory != 0); for ( intt i = i_levels; i > 0; --i ) { pDirectory = pDirectory->Parent(); if (pDirectory == 0) { pDirectory = &Node::Null_(); i = 0; } } sFile.clear(); return *this; } String Position::LinkTo( Position & i_destination, const String & i_localLabel ) const { StreamLock aLink(C_nAssumedMaxLinkLength); StreamStr & rLink = aLink(); Get_LinkTo(rLink, i_destination, i_localLabel); return rLink.c_str(); } String Position::LinkToRoot( const String & ) const { StreamLock sl(C_nAssumedMaxLinkLength); return sl() << get_UpLink(Depth()) << c_str; } void Position::Get_LinkTo( StreamStr & o_result, Position & i_destination, const String & i_localLabel ) const { Node * p1 = pDirectory; Node * p2 = i_destination.pDirectory; intt diff = Depth() - i_destination.Depth(); intt pathLength1 = 0; intt pathLength2 = 0; if ( diff > 0 ) { pathLength1 = diff; move_ToParent(p1,pathLength1); } else if ( diff < 0 ) { pathLength2 = -diff; move_ToParent(p2,pathLength2); } while ( p1 != p2 ) { move_ToParent(p1); move_ToParent(p2); ++pathLength1; ++pathLength2; } o_result << get_UpLink(pathLength1); i_destination.pDirectory->Get_Path(o_result, pathLength2); o_result << i_destination.sFile; if (i_localLabel.length()) o_result << "#" << i_localLabel; } void Position::Get_LinkToRoot( StreamStr & o_result, const String & ) const { o_result << get_UpLink(Depth()); } void Position::Set( Node & i_node, const String & i_file ) { sFile = i_file; pDirectory = &i_node; } const char * get_UpLink(uintt i_depth) { static const uintt C_nMaxDepth = 30; static const char C_sUpLinkArray[3*C_nMaxDepth+1] = "../../../../../../../../../../" "../../../../../../../../../../" "../../../../../../../../../../"; static const char * C_sUpLink = &C_sUpLinkArray[0]; if ( i_depth <= C_nMaxDepth ) { return C_sUpLink + 3*(C_nMaxDepth - i_depth); } else { // not THREAD fast static std::vector<char> aRet; uintt nNeededSize = i_depth * 3 + 1; if (aRet.size() < nNeededSize) { aRet.resize(nNeededSize); char * pEnd = &aRet[nNeededSize-1]; *pEnd = '\0'; for ( char * pFill = &(*aRet.begin()); pFill != pEnd; pFill += 3 ) { memcpy(pFill, C_sUpLink, 3); } } // end if return &aRet[aRet.size() - 1 - 3*i_depth]; } } } // namespace output <|endoftext|>
<commit_before>#include "physics/Environment.hpp" #include "SimulatorWindow.hpp" #include "SimulatorGLUTThread.hpp" #include <QApplication> #include <QFile> #include <QThread> #include <stdio.h> #include <signal.h> using namespace std; void quit(int signal) { fprintf(stderr, "Exiting due to signal %d\n", signal); exit(0); } void usage(const char* prog) { fprintf(stderr, "usage: %s [-c <config file>] [--sv]\n", prog); fprintf(stderr, "\t--help Show usage message\n"); fprintf(stderr, "\t--sv Use shared vision multicast port\n"); fprintf(stderr, "\t--headless Run the simulator in headless mode (without a GUI)\n"); } int main(int argc, char* argv[]) { QApplication app(argc, argv); Field_Dimensions::Current_Dimensions = Field_Dimensions::Single_Field_Dimensions * scaling; QString configFile = "simulator.cfg"; bool sendShared = false; bool headless = false; //loop arguments and look for config file for (int i=1 ; i<argc ; ++i) { if (strcmp(argv[i], "--help") == 0) { usage(argv[0]); return 1; } else if (strcmp(argv[i], "--sv") == 0) { sendShared = true; } else if (strcmp(argv[i], "-c") == 0) { ++i; if (i < argc) { configFile = argv[i]; } else { printf ("Expected config file after -c parameter\n"); return 1; } } else if ((strcmp(argv[i], "--h") == 0) || (strcmp(argv[i], "--help") == 0)) { usage(argv[0]); return 0; } else if (strcmp(argv[i], "--headless") == 0) { headless = true; } else { printf("%s is not recognized as a valid flag\n", argv[i]); return 1; } } // create the thread for simulation SimulatorGLUTThread sim_thread(argc, argv, configFile, sendShared, !headless); struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = quit; sigaction(SIGINT, &act, 0); // Create and initialize GUI with environment information SimulatorWindow win(sim_thread.env()); if (!headless) { win.show(); } // initialize socket connections separately sim_thread.env()->connectSockets(); // start up threads sim_thread.start(); int ret = app.exec(); // shut down sim_thread sim_thread.stop(); sim_thread.wait(); return ret; } <commit_msg>sim defaults to large field, has --smallfield for single size<commit_after>#include "physics/Environment.hpp" #include "SimulatorWindow.hpp" #include "SimulatorGLUTThread.hpp" #include <QApplication> #include <QFile> #include <QThread> #include <stdio.h> #include <signal.h> using namespace std; void quit(int signal) { fprintf(stderr, "Exiting due to signal %d\n", signal); exit(0); } void usage(const char* prog) { fprintf(stderr, "usage: %s [-c <config file>] [--sv]\n", prog); fprintf(stderr, "\t--help Show usage message\n"); fprintf(stderr, "\t--sv Use shared vision multicast port\n"); fprintf(stderr, "\t--headless Run the simulator in headless mode (without a GUI)\n"); fprintf(stderr, "\t--smallfield Run the simulator with the small/single field.\n"); } int main(int argc, char* argv[]) { QApplication app(argc, argv); // Default to double size field, switch to single if flag is set. Field_Dimensions::Current_Dimensions = Field_Dimensions::Double_Field_Dimensions * scaling; QString configFile = "simulator.cfg"; bool sendShared = false; bool headless = false; //loop arguments and look for config file for (int i=1 ; i<argc ; ++i) { if (strcmp(argv[i], "--help") == 0) { usage(argv[0]); return 1; } else if (strcmp(argv[i], "--sv") == 0) { sendShared = true; } else if (strcmp(argv[i], "-c") == 0) { ++i; if (i < argc) { configFile = argv[i]; } else { printf ("Expected config file after -c parameter\n"); return 1; } } else if ((strcmp(argv[i], "--h") == 0) || (strcmp(argv[i], "--help") == 0)) { usage(argv[0]); return 0; } else if (strcmp(argv[i], "--headless") == 0) { headless = true; } else if (strcmp(argv[i], "--smallfield") == 0) { Field_Dimensions::Current_Dimensions = Field_Dimensions::Single_Field_Dimensions * scaling; } else { printf("%s is not recognized as a valid flag\n", argv[i]); return 1; } } // create the thread for simulation SimulatorGLUTThread sim_thread(argc, argv, configFile, sendShared, !headless); struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = quit; sigaction(SIGINT, &act, 0); // Create and initialize GUI with environment information SimulatorWindow win(sim_thread.env()); if (!headless) { win.show(); } // initialize socket connections separately sim_thread.env()->connectSockets(); // start up threads sim_thread.start(); int ret = app.exec(); // shut down sim_thread sim_thread.stop(); sim_thread.wait(); return ret; } <|endoftext|>
<commit_before>/* * simulator.cpp - interface for simulator * Copyright 2018 MIPT-MIPS */ // Configurations #include <infra/config/config.h> #include <infra/exception.h> // Simulators #include <func_sim/func_sim.h> #include <modules/core/perf_sim.h> // ISAs #include <mips/mips.h> #include <risc_v/risc_v.h> #include "simulator.h" namespace config { static AliasedValue<std::string> isa = { "I", "isa", "mars", "modeled ISA"}; static AliasedSwitch disassembly_on = { "d", "disassembly", "print disassembly"}; static AliasedSwitch functional_only = { "f", "functional-only", "run functional simulation only"}; } // namespace config class SimulatorFactory { struct Builder { virtual std::unique_ptr<Simulator> get_funcsim( bool log) = 0; virtual std::unique_ptr<CycleAccurateSimulator> get_perfsim() = 0; Builder() = default; virtual ~Builder() = default; Builder( const Builder&) = delete; Builder( Builder&&) = delete; Builder& operator=( const Builder&) = delete; Builder& operator=( Builder&&) = delete; }; template<typename T> struct TBuilder : public Builder { const std::string isa; const Endian e; std::unique_ptr<Simulator> get_funcsim( bool log) final { return std::make_unique<FuncSim<T>>( e, log, isa); } std::unique_ptr<CycleAccurateSimulator> get_perfsim() final { return std::make_unique<PerfSim<T>>( e, isa); } }; using Map = std::map<std::string, std::unique_ptr<Builder>>; Map map; template<typename T> void emplace( std::string_view name, Endian e) { map.emplace( name, std::make_unique<TBuilder<T>>( name, e)); } template<typename T> void emplace_all_endians( std::string name) { emplace<T>( name, Endian::little); emplace<T>( name + "le", Endian::little); if constexpr ( std::is_base_of_v<IsMIPS, T>) emplace<T>( name + "be", Endian::big); } auto get_factory( const std::string& name) const try { return map.at( name).get(); } catch ( const std::out_of_range& e) { std::cout << "Supported ISAs:" << std::endl; for ( const auto& map_name : map) std::cout << "\t" << map_name.first << std::endl; throw InvalidISA( name); } public: SimulatorFactory() { emplace_all_endians<MIPSI>( "mipsI"); emplace_all_endians<MIPSII>( "mipsII"); emplace_all_endians<MIPSIII>( "mipsIII"); emplace_all_endians<MIPSIV>( "mipsIV"); emplace_all_endians<MIPS32>( "mips32"); emplace_all_endians<MIPS64>( "mips64"); emplace_all_endians<MARS>( "mars"); emplace_all_endians<MARS64>( "mars64"); emplace_all_endians<RISCV32>( "riscv32"); emplace_all_endians<RISCV64>( "riscv64"); emplace_all_endians<RISCV128>( "riscv128"); } auto get_funcsim( const std::string& name, bool log) const { return get_factory( name)->get_funcsim( log); } auto get_perfsim( const std::string& name) const { return get_factory( name)->get_perfsim(); } static SimulatorFactory& get_instance() { static SimulatorFactory sf; return sf; } }; std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only, bool log) { if ( functional_only) return SimulatorFactory::get_instance().get_funcsim( isa, log); return CycleAccurateSimulator::create_simulator( isa); } std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only) { return create_simulator( isa, functional_only, false); } std::shared_ptr<Simulator> Simulator::create_configured_simulator() { return create_simulator( config::isa, config::functional_only, config::disassembly_on); } std::shared_ptr<Simulator> Simulator::create_configured_isa_simulator( const std::string& isa) { return create_simulator( isa, config::functional_only, config::disassembly_on); } std::shared_ptr<CycleAccurateSimulator> CycleAccurateSimulator::create_simulator( const std::string& isa) { return SimulatorFactory::get_instance().get_perfsim( isa); } <commit_msg>Update simulator.cpp<commit_after>/* * simulator.cpp - interface for simulator * Copyright 2018 MIPT-MIPS */ // Configurations #include <infra/config/config.h> #include <infra/exception.h> // Simulators #include <func_sim/func_sim.h> #include <modules/core/perf_sim.h> // ISAs #include <mips/mips.h> #include <risc_v/risc_v.h> #include "simulator.h" namespace config { static AliasedValue<std::string> isa = { "I", "isa", "mars", "modeled ISA"}; static AliasedSwitch disassembly_on = { "d", "disassembly", "print disassembly"}; static AliasedSwitch functional_only = { "f", "functional-only", "run functional simulation only"}; } // namespace config class SimulatorFactory { struct Builder { virtual std::unique_ptr<Simulator> get_funcsim( bool log) = 0; virtual std::unique_ptr<CycleAccurateSimulator> get_perfsim() = 0; Builder() = default; virtual ~Builder() = default; Builder( const Builder&) = delete; Builder( Builder&&) = delete; Builder& operator=( const Builder&) = delete; Builder& operator=( Builder&&) = delete; }; template<typename T> struct TBuilder : public Builder { const std::string isa; const Endian e; TBuilder( std::string_view isa, Endian e) : isa( isa), e( e) { } std::unique_ptr<Simulator> get_funcsim( bool log) final { return std::make_unique<FuncSim<T>>( e, log, isa); } std::unique_ptr<CycleAccurateSimulator> get_perfsim() final { return std::make_unique<PerfSim<T>>( e, isa); } }; std::map<std::string, std::unique_ptr<Builder>> map; template<typename T> void emplace( std::string_view name, Endian e) { map.emplace( name, std::make_unique<TBuilder<T>>( name, e)); } template<typename T> void emplace_all_endians( std::string name) { emplace<T>( name, Endian::little); emplace<T>( name + "le", Endian::little); if constexpr ( std::is_base_of_v<IsMIPS, T>) emplace<T>( name + "be", Endian::big); } auto get_factory( const std::string& name) const try { return map.at( name).get(); } catch ( const std::out_of_range&) { std::cout << "Supported ISAs:" << std::endl; for ( const auto& map_name : map) std::cout << "\t" << map_name.first << std::endl; throw InvalidISA( name); } public: SimulatorFactory() { emplace_all_endians<MIPSI>( "mipsI"); emplace_all_endians<MIPSII>( "mipsII"); emplace_all_endians<MIPSIII>( "mipsIII"); emplace_all_endians<MIPSIV>( "mipsIV"); emplace_all_endians<MIPS32>( "mips32"); emplace_all_endians<MIPS64>( "mips64"); emplace_all_endians<MARS>( "mars"); emplace_all_endians<MARS64>( "mars64"); emplace_all_endians<RISCV32>( "riscv32"); emplace_all_endians<RISCV64>( "riscv64"); emplace_all_endians<RISCV128>( "riscv128"); } auto get_funcsim( const std::string& name, bool log) const { return get_factory( name)->get_funcsim( log); } auto get_perfsim( const std::string& name) const { return get_factory( name)->get_perfsim(); } static SimulatorFactory& get_instance() { static SimulatorFactory sf; return sf; } }; std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only, bool log) { if ( functional_only) return SimulatorFactory::get_instance().get_funcsim( isa, log); return CycleAccurateSimulator::create_simulator( isa); } std::shared_ptr<Simulator> Simulator::create_simulator( const std::string& isa, bool functional_only) { return create_simulator( isa, functional_only, false); } std::shared_ptr<Simulator> Simulator::create_configured_simulator() { return create_simulator( config::isa, config::functional_only, config::disassembly_on); } std::shared_ptr<Simulator> Simulator::create_configured_isa_simulator( const std::string& isa) { return create_simulator( isa, config::functional_only, config::disassembly_on); } std::shared_ptr<CycleAccurateSimulator> CycleAccurateSimulator::create_simulator( const std::string& isa) { return SimulatorFactory::get_instance().get_perfsim( isa); } <|endoftext|>
<commit_before> // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file TypeSupport.cpp */ #include <fastdds/dds/topic/TypeSupport.hpp> #include <fastdds/dds/domain/DomainParticipant.hpp> using namespace eprosima::fastdds::dds; ReturnCode_t TypeSupport::register_type( DomainParticipant* participant, std::string type_name) const { return participant->register_type(*this, type_name == "" ? get_type_name() : type_name); } ReturnCode_t TypeSupport::register_type( DomainParticipant* participant) const { return participant->register_type(*this, get_type_name()); } <commit_msg>Check for an empty string using empty() (#1289)<commit_after> // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file TypeSupport.cpp */ #include <fastdds/dds/topic/TypeSupport.hpp> #include <fastdds/dds/domain/DomainParticipant.hpp> using namespace eprosima::fastdds::dds; ReturnCode_t TypeSupport::register_type( DomainParticipant* participant, std::string type_name) const { return participant->register_type(*this, type_name.empty() ? get_type_name() : type_name); } ReturnCode_t TypeSupport::register_type( DomainParticipant* participant) const { return participant->register_type(*this, get_type_name()); } <|endoftext|>
<commit_before>#include <Windows.h> #include <debugger/client/run.h> #include <debugger/client/stdinput.h> #include <base/util/format.h> #include <base/path/self.h> #include <base/hook/replacedll.h> std::string create_install_script(vscode::rprotocol& req, const fs::path& dbg_path, const std::wstring& port) { auto& args = req["arguments"]; bool isUtf8 = false; std::string sourceCoding = "ansi"; if (args.HasMember("sourceCoding") && args["sourceCoding"].IsString()) { isUtf8 = "utf8" == args["sourceCoding"].Get<std::string>(); } std::string res; if (args.HasMember("path")) { if (args["path"].IsString()) { res += base::format("package.path=[[%s]];", isUtf8 ? args["path"].Get<std::string>() : base::u2a(args["path"])); } else if (args["path"].IsArray()) { std::string path; for (auto& v : args["path"].GetArray()) { if (v.IsString()) { if (!path.empty()) path += ";"; path += isUtf8 ? v.Get<std::string>() : base::u2a(v); } } res += base::format("package.path=[[%s]];", path); } } if (args.HasMember("cpath")) { if (args["cpath"].IsString()) { res += base::format("package.cpath=[[%s]];", isUtf8 ? args["cpath"].Get<std::string>() : base::u2a(args["cpath"])); } else if (args["cpath"].IsArray()) { std::string path; for (auto& v : args["cpath"].GetArray()) { if (v.IsString()) { if (!path.empty()) path += ";"; path += isUtf8 ? v.Get<std::string>() : base::u2a(v); } } res += base::format("package.cpath=[[%s]];", path); } } res += base::format("local dbg=package.loadlib([[%s]], 'luaopen_debugger')();package.loaded[ [[%s]] ]=dbg;dbg:io([[pipe:%s]])" , isUtf8 ? base::w2u((dbg_path / L"debugger.dll").wstring()) : base::w2a((dbg_path / L"debugger.dll").wstring()) , args.HasMember("internalModule") && args["internalModule"].IsString() ? args["internalModule"].Get<std::string>() : "debugger" , base::w2u(port) ); if (args.HasMember("outputCapture") && args["outputCapture"].IsArray()) { for (auto& v : args["outputCapture"].GetArray()) { if (v.IsString()) { std::string item = v.Get<std::string>(); if (item == "print" || item == "stdout" || item == "stderr") { res += ":redirect('" + item + "')"; } } } } res += ":guard():wait():start()"; return res; } int getLuaRuntime(const rapidjson::Value& args) { if (args.HasMember("luaRuntime") && args["luaRuntime"].IsString()) { std::string luaRuntime = args["luaRuntime"].Get<std::string>(); if (luaRuntime == "5.4 64bit") { return 54064; } else if (luaRuntime == "5.4 32bit") { return 54032; } else if (luaRuntime == "5.3 64bit") { return 53064; } else if (luaRuntime == "5.3 32bit") { return 53032; } } return 53032; } bool is64Exe(const wchar_t* exe) { HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hExe == INVALID_HANDLE_VALUE) { return false; } DWORD read; char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER]; SetFilePointer(hExe, 0, NULL, FILE_BEGIN); if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) { CloseHandle(hExe); return false; } SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN); if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) { CloseHandle(hExe); return false; } CloseHandle(hExe); return !(((PIMAGE_NT_HEADERS)data)->FileHeader.Characteristics & IMAGE_FILE_32BIT_MACHINE); } process_opt create_luaexe_with_debugger(stdinput& io, vscode::rprotocol& req, const std::wstring& port) { auto& args = req["arguments"]; fs::path dbgPath = base::path::self().parent_path().parent_path(); std::wstring luaexe; std::pair<std::string, std::string> replacedll; if (args.HasMember("luaexe") && args["luaexe"].IsString()) { luaexe = base::u2w(args["luaexe"].Get<std::string>()); if (is64Exe(luaexe.c_str())) { dbgPath /= "x64"; } else { dbgPath /= "x86"; } } else { if (54064 == getLuaRuntime(args)) { dbgPath /= "x64"; luaexe = dbgPath / "lua54.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua54.dll" }; } } else if (54032 == getLuaRuntime(args)) { dbgPath /= "x86"; luaexe = dbgPath / "lua54.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua54.dll" }; } } else if (53064 == getLuaRuntime(args)) { dbgPath /= "x64"; luaexe = dbgPath / "lua53.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua53.dll" }; } } else { dbgPath /= "x86"; luaexe = dbgPath / "lua53.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua53.dll" }; } } } std::wstring wcwd; std::vector<std::wstring> wargs; wargs.push_back(luaexe); if (args.HasMember("cwd") && args["cwd"].IsString()) { wcwd = base::u2w(args["cwd"].Get<std::string>()); } else { wcwd = fs::path(luaexe).parent_path(); } std::string script = create_install_script(req, dbgPath, port); wargs.push_back(L"-e"); wargs.push_back(base::u2w(script)); if (args.HasMember("arg0")) { if (args["arg0"].IsString()) { auto& v = args["arg0"]; wargs.push_back(base::u2w(v)); } else if (args["arg0"].IsArray()) { for (auto& v : args["arg0"].GetArray()) { if (v.IsString()) { wargs.push_back(base::u2w(v)); } } } } std::wstring program = L".lua"; if (args.HasMember("program") && args["program"].IsString()) { program = base::u2w(args["program"]); } wargs.push_back(program); if (args.HasMember("arg") && args["arg"].IsArray()) { for (auto& v : args["arg"].GetArray()) { if (v.IsString()) { wargs.push_back(base::u2w(v)); } } } base::subprocess::spawn spawn; spawn.set_console(base::subprocess::console::eDisable); if (args.HasMember("env")) { if (args["env"].IsObject()) { for (auto& v : args["env"].GetObject()) { if (v.name.IsString()) { if (v.value.IsString()) { spawn.env_set(base::u2w(v.name.Get<std::string>()), base::u2w(v.value.Get<std::string>())); } else if (v.value.IsNull()) { spawn.env_del(base::u2w(v.name.Get<std::string>())); } } } } req.RemoveMember("env"); } if (!replacedll.first.empty()) { spawn.suspended(); } if (!spawn.exec(wargs, wcwd.c_str())) { return process_opt(); } if (replacedll.first.empty()) { return base::subprocess::process(spawn); } auto process = base::subprocess::process(spawn); base::hook::replacedll(process, replacedll.first.c_str(), replacedll.second.c_str()); process.resume(); return process; } <commit_msg>修正一个错误<commit_after>#include <Windows.h> #include <debugger/client/run.h> #include <debugger/client/stdinput.h> #include <base/util/format.h> #include <base/path/self.h> #include <base/hook/replacedll.h> std::string create_install_script(vscode::rprotocol& req, const fs::path& dbg_path, const std::wstring& port) { auto& args = req["arguments"]; bool isUtf8 = false; std::string sourceCoding = "ansi"; if (args.HasMember("sourceCoding") && args["sourceCoding"].IsString()) { isUtf8 = "utf8" == args["sourceCoding"].Get<std::string>(); } std::string res; if (args.HasMember("path")) { if (args["path"].IsString()) { res += base::format("package.path=[[%s]];", isUtf8 ? args["path"].Get<std::string>() : base::u2a(args["path"])); } else if (args["path"].IsArray()) { std::string path; for (auto& v : args["path"].GetArray()) { if (v.IsString()) { if (!path.empty()) path += ";"; path += isUtf8 ? v.Get<std::string>() : base::u2a(v); } } res += base::format("package.path=[[%s]];", path); } } if (args.HasMember("cpath")) { if (args["cpath"].IsString()) { res += base::format("package.cpath=[[%s]];", isUtf8 ? args["cpath"].Get<std::string>() : base::u2a(args["cpath"])); } else if (args["cpath"].IsArray()) { std::string path; for (auto& v : args["cpath"].GetArray()) { if (v.IsString()) { if (!path.empty()) path += ";"; path += isUtf8 ? v.Get<std::string>() : base::u2a(v); } } res += base::format("package.cpath=[[%s]];", path); } } res += base::format("local dbg=package.loadlib([[%s]], 'luaopen_debugger')();package.loaded[ [[%s]] ]=dbg;dbg:io([[pipe:%s]])" , isUtf8 ? base::w2u((dbg_path / L"debugger.dll").wstring()) : base::w2a((dbg_path / L"debugger.dll").wstring()) , args.HasMember("internalModule") && args["internalModule"].IsString() ? args["internalModule"].Get<std::string>() : "debugger" , base::w2u(port) ); if (args.HasMember("outputCapture") && args["outputCapture"].IsArray()) { for (auto& v : args["outputCapture"].GetArray()) { if (v.IsString()) { std::string item = v.Get<std::string>(); if (item == "print" || item == "stdout" || item == "stderr") { res += ":redirect('" + item + "')"; } } } } res += ":guard():wait():start()"; return res; } int getLuaRuntime(const rapidjson::Value& args) { if (args.HasMember("luaRuntime") && args["luaRuntime"].IsString()) { std::string luaRuntime = args["luaRuntime"].Get<std::string>(); if (luaRuntime == "5.4 64bit") { return 54064; } else if (luaRuntime == "5.4 32bit") { return 54032; } else if (luaRuntime == "5.3 64bit") { return 53064; } else if (luaRuntime == "5.3 32bit") { return 53032; } } return 53032; } bool is64Exe(const wchar_t* exe) { HANDLE hExe = CreateFileW(exe, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hExe == INVALID_HANDLE_VALUE) { return false; } DWORD read; char data[sizeof IMAGE_NT_HEADERS + sizeof IMAGE_DOS_HEADER]; SetFilePointer(hExe, 0, NULL, FILE_BEGIN); if (!ReadFile(hExe, data, sizeof IMAGE_DOS_HEADER, &read, NULL)) { CloseHandle(hExe); return false; } SetFilePointer(hExe, ((PIMAGE_DOS_HEADER)data)->e_lfanew, NULL, FILE_BEGIN); if (!ReadFile(hExe, data, sizeof IMAGE_NT_HEADERS, &read, NULL)) { CloseHandle(hExe); return false; } CloseHandle(hExe); return !(((PIMAGE_NT_HEADERS)data)->FileHeader.Characteristics & IMAGE_FILE_32BIT_MACHINE); } process_opt create_luaexe_with_debugger(stdinput& io, vscode::rprotocol& req, const std::wstring& port) { auto& args = req["arguments"]; fs::path dbgPath = base::path::self().parent_path().parent_path(); std::wstring luaexe; std::pair<std::string, std::string> replacedll; if (args.HasMember("luaexe") && args["luaexe"].IsString()) { luaexe = base::u2w(args["luaexe"].Get<std::string>()); if (is64Exe(luaexe.c_str())) { dbgPath /= "x64"; } else { dbgPath /= "x86"; } } else { if (54064 == getLuaRuntime(args)) { dbgPath /= "x64"; luaexe = dbgPath / "lua54.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua54.dll" }; } } else if (54032 == getLuaRuntime(args)) { dbgPath /= "x86"; luaexe = dbgPath / "lua54.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua54.dll" }; } } else if (53064 == getLuaRuntime(args)) { dbgPath /= "x64"; luaexe = dbgPath / "lua53.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua53.dll" }; } } else { dbgPath /= "x86"; luaexe = dbgPath / "lua53.exe"; if (args.HasMember("luadll") && args["luadll"].IsString()) { replacedll = { base::u2a(args["luadll"].Get<std::string>()), "lua53.dll" }; } } } std::wstring wcwd; std::vector<std::wstring> wargs; wargs.push_back(luaexe); if (args.HasMember("cwd") && args["cwd"].IsString()) { wcwd = base::u2w(args["cwd"].Get<std::string>()); } else { wcwd = fs::path(luaexe).parent_path(); } std::string script = create_install_script(req, dbgPath, port); wargs.push_back(L"-e"); wargs.push_back(base::u2w(script)); if (args.HasMember("arg0")) { if (args["arg0"].IsString()) { auto& v = args["arg0"]; wargs.push_back(base::u2w(v)); } else if (args["arg0"].IsArray()) { for (auto& v : args["arg0"].GetArray()) { if (v.IsString()) { wargs.push_back(base::u2w(v)); } } } } std::wstring program = L".lua"; if (args.HasMember("program") && args["program"].IsString()) { program = base::u2w(args["program"]); } wargs.push_back(program); if (args.HasMember("arg") && args["arg"].IsArray()) { for (auto& v : args["arg"].GetArray()) { if (v.IsString()) { wargs.push_back(base::u2w(v)); } } } base::subprocess::spawn spawn; spawn.set_console(base::subprocess::console::eNew); spawn.hide_window(); if (args.HasMember("env")) { if (args["env"].IsObject()) { for (auto& v : args["env"].GetObject()) { if (v.name.IsString()) { if (v.value.IsString()) { spawn.env_set(base::u2w(v.name.Get<std::string>()), base::u2w(v.value.Get<std::string>())); } else if (v.value.IsNull()) { spawn.env_del(base::u2w(v.name.Get<std::string>())); } } } } req.RemoveMember("env"); } if (!replacedll.first.empty()) { spawn.suspended(); } if (!spawn.exec(wargs, wcwd.c_str())) { return process_opt(); } if (replacedll.first.empty()) { return base::subprocess::process(spawn); } auto process = base::subprocess::process(spawn); base::hook::replacedll(process, replacedll.first.c_str(), replacedll.second.c_str()); process.resume(); return process; } <|endoftext|>
<commit_before>#include "RigidBodyEditor.hpp" #include <Engine/Component/RigidBody.hpp> #include <Engine/Component/Shape.hpp> #include <Engine/Entity/Entity.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/PhysicsManager.hpp> #include <imgui.h> namespace GUI { void RigidBodyEditor::Show(Component::RigidBody* comp) { GetData(comp); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { ImGui::Indent(); if (ImGui::InputFloat("Mass", &mass)) Managers().physicsManager->SetMass(comp, mass); ImGui::Unindent(); } else { ImGui::Indent(); ImGui::TextWrapped("A rigid body is only valid with a complementary shape component. Please add one to allow editing this component."); ImGui::Unindent(); } } void RigidBodyEditor::GetData(Component::RigidBody* comp) { mass = Managers().physicsManager->GetMass(comp); } } <commit_msg>Editor support to make rigid bodies kinematic.<commit_after>#include "RigidBodyEditor.hpp" #include <Engine/Component/RigidBody.hpp> #include <Engine/Component/Shape.hpp> #include <Engine/Entity/Entity.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/PhysicsManager.hpp> #include <imgui.h> namespace GUI { void RigidBodyEditor::Show(Component::RigidBody* comp) { GetData(comp); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { ImGui::Indent(); if (ImGui::InputFloat("Mass", &mass)) Managers().physicsManager->SetMass(comp, mass); bool kinematic = comp->IsKinematic(); if (ImGui::Checkbox("Kinematic", &kinematic)) { if (kinematic) Managers().physicsManager->MakeKinematic(comp); else Managers().physicsManager->MakeDynamic(comp); } ImGui::Unindent(); } else { ImGui::Indent(); ImGui::TextWrapped("A rigid body is only valid with a complementary shape component. Please add one to allow editing this component."); ImGui::Unindent(); } } void RigidBodyEditor::GetData(Component::RigidBody* comp) { mass = Managers().physicsManager->GetMass(comp); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/python.hpp> #include "IECore/ImageWriter.h" #include "IECore/VectorTypedData.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/RunTimeTypedBinding.h" using std::string; using namespace boost; using namespace boost::python; namespace IECore { void bindImageWriter() { typedef class_< ImageWriter , ImageWriterPtr, boost::noncopyable, bases<Writer> > ImageWriterPyClass; ImageWriterPyClass("ImageWriter", no_init) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS(ImageWriter) ; INTRUSIVE_PTR_PATCH( ImageWriter, ImageWriterPyClass ); implicitly_convertible<ImageWriterPtr, WriterPtr>(); } } // namespace IECore <commit_msg>Added canWrite() binding<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/python.hpp> #include "IECore/ImageWriter.h" #include "IECore/VectorTypedData.h" #include "IECore/bindings/IntrusivePtrPatch.h" #include "IECore/bindings/RunTimeTypedBinding.h" using std::string; using namespace boost; using namespace boost::python; namespace IECore { void bindImageWriter() { typedef class_< ImageWriter , ImageWriterPtr, boost::noncopyable, bases<Writer> > ImageWriterPyClass; ImageWriterPyClass("ImageWriter", no_init) .def( "canWrite", &ImageWriter::canWrite ).staticmethod( "canWrite" ) .IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS(ImageWriter) ; INTRUSIVE_PTR_PATCH( ImageWriter, ImageWriterPyClass ); implicitly_convertible<ImageWriterPtr, WriterPtr>(); } } // namespace IECore <|endoftext|>
<commit_before>#include <type_traits> #include <algorithm> #include <sstream> #include <mipp.h> #include "Tools/Exception/exception.hpp" #include "Tools/general_utils.h" #include "Modem_optical.hpp" using namespace aff3ct; using namespace aff3ct::module; //std::vector<std::vector<float>> llrs; //size_t llr_idx; template <typename B, typename R, typename Q> Modem_optical<B,R,Q> ::Modem_optical(const int N, const tools::Distributions<R>& dist, const tools::Noise<R>& noise, const int n_frames) : Modem<B,R,Q>(N, noise, n_frames), dist(dist) { const std::string name = "Modem_optical"; this->set_name(name); // std::ifstream file("/media/ohartmann/DATA/Documents/Projets/CNES_AIRBUS/vectorTestIMS/TestVec ROP -31_3970/AFF3CT/LLR.txt"); // // if (!file.is_open()) // throw tools::runtime_error(); // // unsigned length, n_llrs; // file >> n_llrs >> length; // // llrs.resize(n_llrs, std::vector<float>(length)); // // for (unsigned i = 0; i < n_llrs; i++) // { // for (unsigned j = 0; j < length; j++) // file >> llrs[i][j]; // } // llr_idx = 0; } template <typename B, typename R, typename Q> Modem_optical<B,R,Q> ::~Modem_optical() { } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::set_noise(const tools::Noise<R>& noise) { Modem<B,R,Q>::set_noise(noise); this->n->is_of_type_throw(tools::Noise_type::ROP); this->current_dist = dist.get_distribution(this->n->get_noise()); if (this->current_dist == nullptr) { std::stringstream message; message << "Undefined noise power 'this->n->get_noise()' in the given distributions" " ('this->n->get_noise()' = " << this->n->get_noise() << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::_modulate(const B *X_N1, R *X_N2, const int frame_id) { for (int i = 0; i < this->N; i++) X_N2[i] = X_N1[i] ? (R)1 : (R)0; } namespace aff3ct { namespace module { template <> void Modem_optical<int,float,float> ::_modulate(const int *X_N1, float *X_N2, const int frame_id) { using B = int; using R = float; unsigned size = (unsigned int)(this->N); const auto vec_loop_size = (size / mipp::nElReg<B>()) * mipp::nElReg<B>(); const mipp::Reg<R> Rone = (R)1.0; const mipp::Reg<R> Rzero = (R)0.0; const mipp::Reg<B> Bzero = (B)0; for (unsigned i = 0; i < vec_loop_size; i += mipp::nElReg<B>()) { const auto x1b = mipp::Reg<B>(&X_N1[i]); const auto x2r = mipp::blend(Rone, Rzero, x1b != Bzero); x2r.store(&X_N2[i]); } for (unsigned i = vec_loop_size; i < size; i++) X_N2[i] = X_N1[i] ? (R)1 : (R)0; } } } template <typename B,typename R, typename Q> void Modem_optical<B,R,Q> ::_filter(const R *Y_N1, R *Y_N2, const int frame_id) { std::copy(Y_N1, Y_N1 + this->N_fil, Y_N2); } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id) { if (!std::is_same<R,Q>::value) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'R' and 'Q' have to be the same."); if (!std::is_floating_point<Q>::value) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'Q' has to be float or double."); const Q min_value = 1e-10; // when prob_1 ou prob_0 = 0; if (current_dist == nullptr) throw tools::runtime_error(__FILE__, __LINE__, __func__, "No valid noise has been set."); const auto& pdf_x = current_dist->get_pdf_x(); const auto& pdf_y0 = current_dist->get_pdf_y()[0]; const auto& pdf_y1 = current_dist->get_pdf_y()[1]; unsigned x_pos; for (auto i = 0; i < this->N_fil; i++) { // find the position of the first x that is above the receiver val auto x_above = std::lower_bound(pdf_x.begin(), pdf_x.end(), Y_N1[i]); if (x_above == pdf_x.end()) // if last x_pos = pdf_x.size() - 1; else if (x_above == pdf_x.begin()) // if first x_pos = 0; else { x_pos = std::distance(pdf_x.begin(), x_above); auto x_below = x_above - 1; // find which between x_below and x_above is the nearest of Y_N1[i] x_pos = (Y_N1[i] - *x_below) < (*x_above - Y_N1[i]) ? x_pos - 1 : x_pos; } // then get the matching probabilities auto prob_0 = pdf_y0[x_pos] == (Q)0 ? min_value : pdf_y0[x_pos]; auto prob_1 = pdf_y1[x_pos] == (Q)0 ? min_value : pdf_y1[x_pos]; Y_N2[i] = std::log(prob_0/prob_1); } } //template <typename B, typename R, typename Q> //void Modem_optical<B,R,Q> //::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id) //{ // std::copy(llrs[llr_idx].begin(), llrs[llr_idx].end(), Y_N2); // llr_idx = (llr_idx + 1) % llrs.size(); //}; // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::module::Modem_optical<B_8,R_8,R_8>; template class aff3ct::module::Modem_optical<B_8,R_8,Q_8>; template class aff3ct::module::Modem_optical<B_16,R_16,R_16>; template class aff3ct::module::Modem_optical<B_16,R_16,Q_16>; template class aff3ct::module::Modem_optical<B_32,R_32,R_32>; template class aff3ct::module::Modem_optical<B_64,R_64,R_64>; #else template class aff3ct::module::Modem_optical<B,R,Q>; #if !defined(PREC_32_BIT) && !defined(PREC_64_BIT) template class aff3ct::module::Modem_optical<B,R,R>; #endif #endif // ==================================================================================== explicit template instantiation <commit_msg>Change modem optical debug path<commit_after>#include <type_traits> #include <algorithm> #include <sstream> #include <mipp.h> #include "Tools/Exception/exception.hpp" #include "Tools/general_utils.h" #include "Modem_optical.hpp" using namespace aff3ct; using namespace aff3ct::module; // //std::vector<std::vector<float>> llrs; //size_t llr_idx; template <typename B, typename R, typename Q> Modem_optical<B,R,Q> ::Modem_optical(const int N, const tools::Distributions<R>& dist, const tools::Noise<R>& noise, const int n_frames) : Modem<B,R,Q>(N, noise, n_frames), dist(dist) { const std::string name = "Modem_optical"; this->set_name(name); // std::ifstream file("/media/ohartmann/DATA/Documents/Projets/CNES_AIRBUS/matrices/2018_05_03/vectorTestIMS/TestVec ROP -32/AFF3CT/LLR.txt"); // // if (!file.is_open()) // throw tools::runtime_error(); // // unsigned length, n_llrs; // file >> n_llrs >> length; // // llrs.resize(n_llrs, std::vector<float>(length)); // // for (unsigned i = 0; i < n_llrs; i++) // { // for (unsigned j = 0; j < length; j++) // file >> llrs[i][j]; // } // llr_idx = 0; } template <typename B, typename R, typename Q> Modem_optical<B,R,Q> ::~Modem_optical() { } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::set_noise(const tools::Noise<R>& noise) { Modem<B,R,Q>::set_noise(noise); this->n->is_of_type_throw(tools::Noise_type::ROP); this->current_dist = dist.get_distribution(this->n->get_noise()); if (this->current_dist == nullptr) { std::stringstream message; message << "Undefined noise power 'this->n->get_noise()' in the given distributions" " ('this->n->get_noise()' = " << this->n->get_noise() << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::_modulate(const B *X_N1, R *X_N2, const int frame_id) { for (int i = 0; i < this->N; i++) X_N2[i] = X_N1[i] ? (R)1 : (R)0; } namespace aff3ct { namespace module { template <> void Modem_optical<int,float,float> ::_modulate(const int *X_N1, float *X_N2, const int frame_id) { using B = int; using R = float; unsigned size = (unsigned int)(this->N); const auto vec_loop_size = (size / mipp::nElReg<B>()) * mipp::nElReg<B>(); const mipp::Reg<R> Rone = (R)1.0; const mipp::Reg<R> Rzero = (R)0.0; const mipp::Reg<B> Bzero = (B)0; for (unsigned i = 0; i < vec_loop_size; i += mipp::nElReg<B>()) { const auto x1b = mipp::Reg<B>(&X_N1[i]); const auto x2r = mipp::blend(Rone, Rzero, x1b != Bzero); x2r.store(&X_N2[i]); } for (unsigned i = vec_loop_size; i < size; i++) X_N2[i] = X_N1[i] ? (R)1 : (R)0; } } } template <typename B,typename R, typename Q> void Modem_optical<B,R,Q> ::_filter(const R *Y_N1, R *Y_N2, const int frame_id) { std::copy(Y_N1, Y_N1 + this->N_fil, Y_N2); } template <typename B, typename R, typename Q> void Modem_optical<B,R,Q> ::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id) { if (!std::is_same<R,Q>::value) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'R' and 'Q' have to be the same."); if (!std::is_floating_point<Q>::value) throw tools::invalid_argument(__FILE__, __LINE__, __func__, "Type 'Q' has to be float or double."); const Q min_value = 1e-10; // when prob_1 ou prob_0 = 0; if (current_dist == nullptr) throw tools::runtime_error(__FILE__, __LINE__, __func__, "No valid noise has been set."); const auto& pdf_x = current_dist->get_pdf_x(); const auto& pdf_y0 = current_dist->get_pdf_y()[0]; const auto& pdf_y1 = current_dist->get_pdf_y()[1]; unsigned x_pos; for (auto i = 0; i < this->N_fil; i++) { // find the position of the first x that is above the receiver val auto x_above = std::lower_bound(pdf_x.begin(), pdf_x.end(), Y_N1[i]); if (x_above == pdf_x.end()) // if last x_pos = pdf_x.size() - 1; else if (x_above == pdf_x.begin()) // if first x_pos = 0; else { x_pos = std::distance(pdf_x.begin(), x_above); auto x_below = x_above - 1; // find which between x_below and x_above is the nearest of Y_N1[i] x_pos = (Y_N1[i] - *x_below) < (*x_above - Y_N1[i]) ? x_pos - 1 : x_pos; } // then get the matching probabilities auto prob_0 = pdf_y0[x_pos] == (Q)0 ? min_value : pdf_y0[x_pos]; auto prob_1 = pdf_y1[x_pos] == (Q)0 ? min_value : pdf_y1[x_pos]; Y_N2[i] = std::log(prob_0/prob_1); } } //template <typename B, typename R, typename Q> //void Modem_optical<B,R,Q> //::_demodulate(const Q *Y_N1, Q *Y_N2, const int frame_id) //{ // std::copy(llrs[llr_idx].begin(), llrs[llr_idx].end(), Y_N2); // llr_idx = (llr_idx + 1) % llrs.size(); //}; // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::module::Modem_optical<B_8,R_8,R_8>; template class aff3ct::module::Modem_optical<B_8,R_8,Q_8>; template class aff3ct::module::Modem_optical<B_16,R_16,R_16>; template class aff3ct::module::Modem_optical<B_16,R_16,Q_16>; template class aff3ct::module::Modem_optical<B_32,R_32,R_32>; template class aff3ct::module::Modem_optical<B_64,R_64,R_64>; #else template class aff3ct::module::Modem_optical<B,R,Q>; #if !defined(PREC_32_BIT) && !defined(PREC_64_BIT) template class aff3ct::module::Modem_optical<B,R,R>; #endif #endif // ==================================================================================== explicit template instantiation <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Network/Posix/IpAddressImpl.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Network/Posix/SocketImpl.hpp> #include <cstring> #include <Nazara/Network/Debug.hpp> namespace Nz { namespace Detail { using addrinfoImpl = addrinfo; int GetAddressInfo(const String& hostname, const String& service, const addrinfoImpl* hints, addrinfoImpl** results) { return getaddrinfo(hostname.GetConstBuffer(), service.GetConstBuffer(), hints, results); } int GetHostnameInfo(sockaddr* socketAddress, socklen_t socketLen, String* hostname, String* service, int flags) { std::array<char, NI_MAXHOST> hostnameBuffer; std::array<char, NI_MAXSERV> serviceBuffer; int result = getnameinfo(socketAddress, socketLen, hostnameBuffer.data(), hostnameBuffer.size(), serviceBuffer.data(), serviceBuffer.size(), flags); if (result == 0) { if (hostname) hostname->Set(hostnameBuffer.data()); if (service) service->Set(serviceBuffer.data()); } return result; } void FreeAddressInfo(addrinfoImpl* results) { freeaddrinfo(results); } IpAddress::IPv4 convertSockaddrToIPv4(const in_addr& addr) { union byteToInt { UInt8 b[sizeof(uint32_t)]; uint32_t i; }; byteToInt hostOrder; hostOrder.i = ntohl(addr.s_addr); return { {hostOrder.b[3], hostOrder.b[2], hostOrder.b[1], hostOrder.b[0]} }; } IpAddress::IPv6 convertSockaddr6ToIPv6(const in6_addr& addr) { auto& rawIpV6 = addr.s6_addr; IpAddress::IPv6 ipv6; for (unsigned int i = 0; i < 8; ++i) ipv6[i] = rawIpV6[i * 2] << 8 | rawIpV6[i * 2 + 1]; return ipv6; } } IpAddress IpAddressImpl::FromAddrinfo(const addrinfo* info) { switch (info->ai_family) { case AF_INET: { sockaddr_in* ipv4 = reinterpret_cast<sockaddr_in*>(info->ai_addr); return FromSockAddr(ipv4); } case AF_INET6: { sockaddr_in6* ipv6 = reinterpret_cast<sockaddr_in6*>(info->ai_addr); return FromSockAddr(ipv6); } } return IpAddress::Invalid; } IpAddress IpAddressImpl::FromSockAddr(const sockaddr* address) { switch (address->sa_family) { case AF_INET: return FromSockAddr(reinterpret_cast<const sockaddr_in*>(address)); case AF_INET6: return FromSockAddr(reinterpret_cast<const sockaddr_in6*>(address)); } return IpAddress::Invalid; } IpAddress IpAddressImpl::FromSockAddr(const sockaddr_in* addressv4) { IpAddress::IPv4 ip4Address = Detail::convertSockaddrToIPv4(addressv4->sin_addr); return IpAddress(ip4Address, ntohs(addressv4->sin_port)); } IpAddress IpAddressImpl::FromSockAddr(const sockaddr_in6* addressv6) { IpAddress::IPv6 ip6Address = Detail::convertSockaddr6ToIPv6(addressv6->sin6_addr); return IpAddress(ip6Address, ntohs(addressv6->sin6_port)); } bool IpAddressImpl::ResolveAddress(const IpAddress& ipAddress, String* hostname, String* service, ResolveError* error) { SockAddrBuffer socketAddress; socklen_t socketAddressLen = ToSockAddr(ipAddress, socketAddress.data()); if (Detail::GetHostnameInfo(reinterpret_cast<sockaddr*>(socketAddress.data()), socketAddressLen, hostname, service, NI_NUMERICSERV) != 0) { if (error) *error = TranslateEAIErrorToResolveError(errno); return false; } if (error) *error = ResolveError_NoError; return true; } std::vector<HostnameInfo> IpAddressImpl::ResolveHostname(NetProtocol procol, const String& hostname, const String& service, ResolveError* error) { std::vector<HostnameInfo> results; Detail::addrinfoImpl hints; std::memset(&hints, 0, sizeof(Detail::addrinfoImpl)); hints.ai_family = SocketImpl::TranslateNetProtocolToAF(procol); hints.ai_flags = AI_CANONNAME; hints.ai_socktype = SOCK_STREAM; Detail::addrinfoImpl* servinfo; if (Detail::GetAddressInfo(hostname, service, &hints, &servinfo) != 0) { if (error) *error = TranslateEAIErrorToResolveError(errno); return results; } CallOnExit onExit([servinfo]() { Detail::FreeAddressInfo(servinfo); }); // loop through all the results and connect to the first we can for (Detail::addrinfoImpl* p = servinfo; p != nullptr; p = p->ai_next) { HostnameInfo result; result.address = FromAddrinfo(p); result.canonicalName = String::Unicode(p->ai_canonname); result.protocol = TranslatePFToNetProtocol(p->ai_family); result.socketType = TranslateSockToNetProtocol(p->ai_socktype); results.push_back(result); } if (error) *error = ResolveError_NoError; return results; } socklen_t IpAddressImpl::ToSockAddr(const IpAddress& ipAddress, void* buffer) { if (ipAddress.IsValid()) { switch (ipAddress.GetProtocol()) { case NetProtocol_IPv4: { sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer); std::memset(socketAddress, 0, sizeof(sockaddr_in)); socketAddress->sin_family = AF_INET; socketAddress->sin_port = htons(ipAddress.GetPort()); socketAddress->sin_addr.s_addr = htonl(ipAddress.ToUInt32()); return sizeof(sockaddr_in); } case NetProtocol_IPv6: { sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer); std::memset(socketAddress, 0, sizeof(sockaddr_in6)); socketAddress->sin6_family = AF_INET6; socketAddress->sin6_port = htons(ipAddress.GetPort()); IpAddress::IPv6 address = ipAddress.ToIPv6(); for (unsigned int i = 0; i < 8; ++i) { u_short addressPart = htons(address[i]); socketAddress->sin6_addr.s6_addr[i * 2 + 0] = addressPart >> 0; socketAddress->sin6_addr.s6_addr[i * 2 + 1] = addressPart >> 8; } return sizeof(sockaddr_in6); } default: NazaraInternalError("Unhandled ip protocol (0x" + String::Number(ipAddress.GetProtocol()) + ')'); break; } } NazaraError("Invalid ip address"); return 0; } NetProtocol IpAddressImpl::TranslatePFToNetProtocol(int family) { switch (family) { case PF_INET: return NetProtocol_IPv4; case PF_INET6: return NetProtocol_IPv6; default: return NetProtocol_Unknown; } } SocketType IpAddressImpl::TranslateSockToNetProtocol(int socketType) { switch (socketType) { case SOCK_STREAM: return SocketType_TCP; case SOCK_DGRAM: return SocketType_UDP; case SOCK_RAW: return SocketType_Raw; default: return SocketType_Unknown; } } ResolveError IpAddressImpl::TranslateEAIErrorToResolveError(int error) { // http://man7.org/linux/man-pages/man3/gai_strerror.3.html switch (error) { case 0: return ResolveError_NoError; // Engine error case EAI_BADFLAGS: case EAI_SYSTEM: return ResolveError_Internal; case EAI_FAMILY: case EAI_SERVICE: case EAI_SOCKTYPE: return ResolveError_ProtocolNotSupported; case EAI_NONAME: return ResolveError_NotFound; case EAI_FAIL: return ResolveError_NonRecoverable; case EAI_NODATA: return ResolveError_NotInitialized; case EAI_MEMORY: return ResolveError_ResourceError; case EAI_AGAIN: return ResolveError_TemporaryFailure; } NazaraWarning("Unhandled EAI error: " + Error::GetLastSystemError(error) + " (" + String::Number(error) + ") as " + gai_strerror(error)); return ResolveError_Unknown; } } <commit_msg>Forgot to fix this for Linux too<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Network/Posix/IpAddressImpl.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Network/Posix/SocketImpl.hpp> #include <cstring> #include <Nazara/Network/Debug.hpp> namespace Nz { namespace Detail { using addrinfoImpl = addrinfo; int GetAddressInfo(const String& hostname, const String& service, const addrinfoImpl* hints, addrinfoImpl** results) { return getaddrinfo(hostname.GetConstBuffer(), service.GetConstBuffer(), hints, results); } int GetHostnameInfo(sockaddr* socketAddress, socklen_t socketLen, String* hostname, String* service, int flags) { std::array<char, NI_MAXHOST> hostnameBuffer; std::array<char, NI_MAXSERV> serviceBuffer; int result = getnameinfo(socketAddress, socketLen, hostnameBuffer.data(), hostnameBuffer.size(), serviceBuffer.data(), serviceBuffer.size(), flags); if (result == 0) { if (hostname) hostname->Set(hostnameBuffer.data()); if (service) service->Set(serviceBuffer.data()); } return result; } void FreeAddressInfo(addrinfoImpl* results) { freeaddrinfo(results); } IpAddress::IPv4 convertSockaddrToIPv4(const in_addr& addr) { union byteToInt { UInt8 b[sizeof(uint32_t)]; uint32_t i; }; byteToInt hostOrder; hostOrder.i = ntohl(addr.s_addr); return { {hostOrder.b[3], hostOrder.b[2], hostOrder.b[1], hostOrder.b[0]} }; } IpAddress::IPv6 convertSockaddr6ToIPv6(const in6_addr& addr) { auto& rawIpV6 = addr.s6_addr; IpAddress::IPv6 ipv6; for (unsigned int i = 0; i < 8; ++i) ipv6[i] = Nz::UInt16(rawIpV6[i * 2]) << 8 | rawIpV6[i * 2 + 1]; return ipv6; } } IpAddress IpAddressImpl::FromAddrinfo(const addrinfo* info) { switch (info->ai_family) { case AF_INET: { sockaddr_in* ipv4 = reinterpret_cast<sockaddr_in*>(info->ai_addr); return FromSockAddr(ipv4); } case AF_INET6: { sockaddr_in6* ipv6 = reinterpret_cast<sockaddr_in6*>(info->ai_addr); return FromSockAddr(ipv6); } } return IpAddress::Invalid; } IpAddress IpAddressImpl::FromSockAddr(const sockaddr* address) { switch (address->sa_family) { case AF_INET: return FromSockAddr(reinterpret_cast<const sockaddr_in*>(address)); case AF_INET6: return FromSockAddr(reinterpret_cast<const sockaddr_in6*>(address)); } return IpAddress::Invalid; } IpAddress IpAddressImpl::FromSockAddr(const sockaddr_in* addressv4) { IpAddress::IPv4 ip4Address = Detail::convertSockaddrToIPv4(addressv4->sin_addr); return IpAddress(ip4Address, ntohs(addressv4->sin_port)); } IpAddress IpAddressImpl::FromSockAddr(const sockaddr_in6* addressv6) { IpAddress::IPv6 ip6Address = Detail::convertSockaddr6ToIPv6(addressv6->sin6_addr); return IpAddress(ip6Address, ntohs(addressv6->sin6_port)); } bool IpAddressImpl::ResolveAddress(const IpAddress& ipAddress, String* hostname, String* service, ResolveError* error) { SockAddrBuffer socketAddress; socklen_t socketAddressLen = ToSockAddr(ipAddress, socketAddress.data()); if (Detail::GetHostnameInfo(reinterpret_cast<sockaddr*>(socketAddress.data()), socketAddressLen, hostname, service, NI_NUMERICSERV) != 0) { if (error) *error = TranslateEAIErrorToResolveError(errno); return false; } if (error) *error = ResolveError_NoError; return true; } std::vector<HostnameInfo> IpAddressImpl::ResolveHostname(NetProtocol procol, const String& hostname, const String& service, ResolveError* error) { std::vector<HostnameInfo> results; Detail::addrinfoImpl hints; std::memset(&hints, 0, sizeof(Detail::addrinfoImpl)); hints.ai_family = SocketImpl::TranslateNetProtocolToAF(procol); hints.ai_flags = AI_CANONNAME; hints.ai_socktype = SOCK_STREAM; Detail::addrinfoImpl* servinfo; if (Detail::GetAddressInfo(hostname, service, &hints, &servinfo) != 0) { if (error) *error = TranslateEAIErrorToResolveError(errno); return results; } CallOnExit onExit([servinfo]() { Detail::FreeAddressInfo(servinfo); }); // loop through all the results and connect to the first we can for (Detail::addrinfoImpl* p = servinfo; p != nullptr; p = p->ai_next) { HostnameInfo result; result.address = FromAddrinfo(p); result.canonicalName = String::Unicode(p->ai_canonname); result.protocol = TranslatePFToNetProtocol(p->ai_family); result.socketType = TranslateSockToNetProtocol(p->ai_socktype); results.push_back(result); } if (error) *error = ResolveError_NoError; return results; } socklen_t IpAddressImpl::ToSockAddr(const IpAddress& ipAddress, void* buffer) { if (ipAddress.IsValid()) { switch (ipAddress.GetProtocol()) { case NetProtocol_IPv4: { sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer); std::memset(socketAddress, 0, sizeof(sockaddr_in)); socketAddress->sin_family = AF_INET; socketAddress->sin_port = htons(ipAddress.GetPort()); socketAddress->sin_addr.s_addr = htonl(ipAddress.ToUInt32()); return sizeof(sockaddr_in); } case NetProtocol_IPv6: { sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer); std::memset(socketAddress, 0, sizeof(sockaddr_in6)); socketAddress->sin6_family = AF_INET6; socketAddress->sin6_port = htons(ipAddress.GetPort()); IpAddress::IPv6 address = ipAddress.ToIPv6(); for (unsigned int i = 0; i < 8; ++i) { u_short addressPart = htons(address[i]); socketAddress->sin6_addr.s6_addr[i * 2 + 0] = addressPart >> 0; socketAddress->sin6_addr.s6_addr[i * 2 + 1] = addressPart >> 8; } return sizeof(sockaddr_in6); } default: NazaraInternalError("Unhandled ip protocol (0x" + String::Number(ipAddress.GetProtocol()) + ')'); break; } } NazaraError("Invalid ip address"); return 0; } NetProtocol IpAddressImpl::TranslatePFToNetProtocol(int family) { switch (family) { case PF_INET: return NetProtocol_IPv4; case PF_INET6: return NetProtocol_IPv6; default: return NetProtocol_Unknown; } } SocketType IpAddressImpl::TranslateSockToNetProtocol(int socketType) { switch (socketType) { case SOCK_STREAM: return SocketType_TCP; case SOCK_DGRAM: return SocketType_UDP; case SOCK_RAW: return SocketType_Raw; default: return SocketType_Unknown; } } ResolveError IpAddressImpl::TranslateEAIErrorToResolveError(int error) { // http://man7.org/linux/man-pages/man3/gai_strerror.3.html switch (error) { case 0: return ResolveError_NoError; // Engine error case EAI_BADFLAGS: case EAI_SYSTEM: return ResolveError_Internal; case EAI_FAMILY: case EAI_SERVICE: case EAI_SOCKTYPE: return ResolveError_ProtocolNotSupported; case EAI_NONAME: return ResolveError_NotFound; case EAI_FAIL: return ResolveError_NonRecoverable; case EAI_NODATA: return ResolveError_NotInitialized; case EAI_MEMORY: return ResolveError_ResourceError; case EAI_AGAIN: return ResolveError_TemporaryFailure; } NazaraWarning("Unhandled EAI error: " + Error::GetLastSystemError(error) + " (" + String::Number(error) + ") as " + gai_strerror(error)); return ResolveError_Unknown; } } <|endoftext|>
<commit_before>// Copyright (c) 2010 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 <string> #include "base/command_line.h" #include "base/logging.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/test/test_suite.h" #include "chrome/test/test_launcher/test_runner.h" #include "chrome/test/unit/chrome_test_suite.h" #if defined(OS_WIN) #include "base/base_switches.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/sandbox_policy.h" #include "sandbox/src/dep.h" #include "sandbox/src/sandbox_factory.h" #include "sandbox/src/sandbox_types.h" // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*); #endif // This version of the test launcher forks a new process for each test it runs. namespace { const char kGTestListTestsFlag[] = "gtest_list_tests"; const char kGTestOutputFlag[] = "gtest_output"; const char kGTestHelpFlag[] = "gtest_help"; const char kSingleProcessTestsFlag[] = "single_process"; const char kSingleProcessTestsAndChromeFlag[] = "single-process"; const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout"; // The following is kept for historical reasons (so people that are used to // using it don't get surprised). const char kChildProcessFlag[] = "child"; const char kHelpFlag[] = "help"; // This value was changed from 30000 (30sec) to 45000 due to // http://crbug.com/43862. const int64 kDefaultTestTimeoutMs = 45000; class OutOfProcTestRunner : public tests::TestRunner { public: OutOfProcTestRunner() { } virtual ~OutOfProcTestRunner() { } bool Init() { return true; } // Returns true if the test succeeded, false if it failed. bool RunTest(const std::string& test_name) { const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); // Construct the new command line. Strip out gtest_output flag if // it has been given because otherwise each test outputs the same file // over and over overriding the previous one every time. // We will generate the final output file later in RunTests(). CommandLine new_cmd_line(cmd_line->GetProgram()); CommandLine::SwitchMap switches = cmd_line->GetSwitches(); switches.erase(kGTestOutputFlag); for (CommandLine::SwitchMap::const_iterator iter = switches.begin(); iter != switches.end(); ++iter) { new_cmd_line.AppendSwitchNative((*iter).first, (*iter).second); } // Always enable disabled tests. This method is not called with disabled // tests unless this flag was specified to the browser test executable. new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests"); new_cmd_line.AppendSwitchASCII("gtest_filter", test_name); new_cmd_line.AppendSwitch(kChildProcessFlag); // Do not let the child ignore failures. We need to propagate the // failure status back to the parent. new_cmd_line.AppendSwitch(kStrictFailureHandling); base::ProcessHandle process_handle; if (!base::LaunchApp(new_cmd_line, false, false, &process_handle)) return false; int test_terminate_timeout_ms = kDefaultTestTimeoutMs; if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) { std::string timeout_str = cmd_line->GetSwitchValueASCII(kTestTerminateTimeoutFlag); int timeout; base::StringToInt(timeout_str, &timeout); test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout); } int exit_code = 0; if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code, test_terminate_timeout_ms)) { LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms << " ms) exceeded for " << test_name; exit_code = -1; // Set a non-zero exit code to signal a failure. // Ensure that the process terminates. base::KillProcess(process_handle, -1, true); } return exit_code == 0; } private: DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner); }; class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory { public: OutOfProcTestRunnerFactory() { } virtual tests::TestRunner* CreateTestRunner() const { return new OutOfProcTestRunner(); } private: DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory); }; void PrintUsage() { fprintf(stdout, "Runs tests using the gtest framework, each test being run in its own\n" "process. Any gtest flags can be specified.\n" " --single_process\n" " Runs the tests and the launcher in the same process. Useful for \n" " debugging a specific test in a debugger.\n" " --single-process\n" " Same as above, and also runs Chrome in single-process mode.\n" " --test-terminate-timeout\n" " Specifies a timeout (in milliseconds) after which a running test\n" " will be forcefully terminated.\n" " --help\n" " Shows this message.\n" " --gtest_help\n" " Shows the gtest help message.\n"); } } // namespace int main(int argc, char** argv) { CommandLine::Init(argc, argv); const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(kHelpFlag)) { PrintUsage(); return 0; } // TODO(pkasting): This "single_process vs. single-process" design is terrible // UI. Instead, there should be some sort of signal flag on the command line, // with all subsequent arguments passed through to the underlying browser. if (command_line->HasSwitch(kChildProcessFlag) || command_line->HasSwitch(kSingleProcessTestsFlag) || command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) || command_line->HasSwitch(kGTestListTestsFlag) || command_line->HasSwitch(kGTestHelpFlag)) { #if defined(OS_WIN) if (command_line->HasSwitch(kChildProcessFlag) || command_line->HasSwitch(kSingleProcessTestsFlag)) { // This is the browser process, so setup the sandbox broker. sandbox::BrokerServices* broker_services = sandbox::SandboxFactory::GetBrokerServices(); if (broker_services) { sandbox::InitBrokerServices(broker_services); // Precreate the desktop and window station used by the renderers. sandbox::TargetPolicy* policy = broker_services->CreatePolicy(); sandbox::ResultCode result = policy->CreateAlternateDesktop(true); CHECK(sandbox::SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION != result); policy->Release(); } } #endif return ChromeTestSuite(argc, argv).Run(); } #if defined(OS_WIN) if (command_line->HasSwitch(switches::kProcessType)) { // This is a child process, call ChromeMain. FilePath chrome_path(command_line->GetProgram().DirName()); chrome_path = chrome_path.Append(chrome::kBrowserResourcesDll); HMODULE dll = LoadLibrary(chrome_path.value().c_str()); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll, "ChromeMain")); if (!entry_point) return -1; // Initialize the sandbox services. sandbox::SandboxInterfaceInfo sandbox_info = {0}; sandbox_info.target_services = sandbox::SandboxFactory::GetTargetServices(); return entry_point(GetModuleHandle(NULL), &sandbox_info, GetCommandLineW()); } #endif fprintf(stdout, "Starting tests...\n" "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n" "For debugging a test inside a debugger, use the\n" "--gtest_filter=<your_test_name> flag along with either\n" "--single_process (to run all tests in one launcher/browser process) or\n" "--single-process (to do the above, and also run Chrome in single-\n" "process mode).\n"); OutOfProcTestRunnerFactory test_runner_factory; return tests::RunTests(test_runner_factory) ? 0 : 1; } <commit_msg>Make --gtest_repeat flag work correctly for browser_tests.<commit_after>// Copyright (c) 2010 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 <string> #include "base/command_line.h" #include "base/logging.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/test/test_suite.h" #include "chrome/test/test_launcher/test_runner.h" #include "chrome/test/unit/chrome_test_suite.h" #if defined(OS_WIN) #include "base/base_switches.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/sandbox_policy.h" #include "sandbox/src/dep.h" #include "sandbox/src/sandbox_factory.h" #include "sandbox/src/sandbox_types.h" // The entry point signature of chrome.dll. typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*); #endif // This version of the test launcher forks a new process for each test it runs. namespace { const char kGTestHelpFlag[] = "gtest_help"; const char kGTestListTestsFlag[] = "gtest_list_tests"; const char kGTestOutputFlag[] = "gtest_output"; const char kGTestRepeatFlag[] = "gtest_repeat"; const char kSingleProcessTestsFlag[] = "single_process"; const char kSingleProcessTestsAndChromeFlag[] = "single-process"; const char kTestTerminateTimeoutFlag[] = "test-terminate-timeout"; // The following is kept for historical reasons (so people that are used to // using it don't get surprised). const char kChildProcessFlag[] = "child"; const char kHelpFlag[] = "help"; // This value was changed from 30000 (30sec) to 45000 due to // http://crbug.com/43862. const int64 kDefaultTestTimeoutMs = 45000; class OutOfProcTestRunner : public tests::TestRunner { public: OutOfProcTestRunner() { } virtual ~OutOfProcTestRunner() { } bool Init() { return true; } // Returns true if the test succeeded, false if it failed. bool RunTest(const std::string& test_name) { const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); CommandLine new_cmd_line(cmd_line->GetProgram()); CommandLine::SwitchMap switches = cmd_line->GetSwitches(); // Strip out gtest_output flag because otherwise we would overwrite results // of the previous test. We will generate the final output file later // in RunTests(). switches.erase(kGTestOutputFlag); // Strip out gtest_repeat flag because we can only run one test in the child // process (restarting the browser in the same process is illegal after it // has been shut down and will actually crash). switches.erase(kGTestRepeatFlag); for (CommandLine::SwitchMap::const_iterator iter = switches.begin(); iter != switches.end(); ++iter) { new_cmd_line.AppendSwitchNative((*iter).first, (*iter).second); } // Always enable disabled tests. This method is not called with disabled // tests unless this flag was specified to the browser test executable. new_cmd_line.AppendSwitch("gtest_also_run_disabled_tests"); new_cmd_line.AppendSwitchASCII("gtest_filter", test_name); new_cmd_line.AppendSwitch(kChildProcessFlag); // Do not let the child ignore failures. We need to propagate the // failure status back to the parent. new_cmd_line.AppendSwitch(kStrictFailureHandling); base::ProcessHandle process_handle; if (!base::LaunchApp(new_cmd_line, false, false, &process_handle)) return false; int test_terminate_timeout_ms = kDefaultTestTimeoutMs; if (cmd_line->HasSwitch(kTestTerminateTimeoutFlag)) { std::string timeout_str = cmd_line->GetSwitchValueASCII(kTestTerminateTimeoutFlag); int timeout; base::StringToInt(timeout_str, &timeout); test_terminate_timeout_ms = std::max(test_terminate_timeout_ms, timeout); } int exit_code = 0; if (!base::WaitForExitCodeWithTimeout(process_handle, &exit_code, test_terminate_timeout_ms)) { LOG(ERROR) << "Test timeout (" << test_terminate_timeout_ms << " ms) exceeded for " << test_name; exit_code = -1; // Set a non-zero exit code to signal a failure. // Ensure that the process terminates. base::KillProcess(process_handle, -1, true); } return exit_code == 0; } private: DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunner); }; class OutOfProcTestRunnerFactory : public tests::TestRunnerFactory { public: OutOfProcTestRunnerFactory() { } virtual tests::TestRunner* CreateTestRunner() const { return new OutOfProcTestRunner(); } private: DISALLOW_COPY_AND_ASSIGN(OutOfProcTestRunnerFactory); }; void PrintUsage() { fprintf(stdout, "Runs tests using the gtest framework, each test being run in its own\n" "process. Any gtest flags can be specified.\n" " --single_process\n" " Runs the tests and the launcher in the same process. Useful for \n" " debugging a specific test in a debugger.\n" " --single-process\n" " Same as above, and also runs Chrome in single-process mode.\n" " --test-terminate-timeout\n" " Specifies a timeout (in milliseconds) after which a running test\n" " will be forcefully terminated.\n" " --help\n" " Shows this message.\n" " --gtest_help\n" " Shows the gtest help message.\n"); } } // namespace int main(int argc, char** argv) { CommandLine::Init(argc, argv); const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(kHelpFlag)) { PrintUsage(); return 0; } // TODO(pkasting): This "single_process vs. single-process" design is terrible // UI. Instead, there should be some sort of signal flag on the command line, // with all subsequent arguments passed through to the underlying browser. if (command_line->HasSwitch(kChildProcessFlag) || command_line->HasSwitch(kSingleProcessTestsFlag) || command_line->HasSwitch(kSingleProcessTestsAndChromeFlag) || command_line->HasSwitch(kGTestListTestsFlag) || command_line->HasSwitch(kGTestHelpFlag)) { #if defined(OS_WIN) if (command_line->HasSwitch(kChildProcessFlag) || command_line->HasSwitch(kSingleProcessTestsFlag)) { // This is the browser process, so setup the sandbox broker. sandbox::BrokerServices* broker_services = sandbox::SandboxFactory::GetBrokerServices(); if (broker_services) { sandbox::InitBrokerServices(broker_services); // Precreate the desktop and window station used by the renderers. sandbox::TargetPolicy* policy = broker_services->CreatePolicy(); sandbox::ResultCode result = policy->CreateAlternateDesktop(true); CHECK(sandbox::SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION != result); policy->Release(); } } #endif return ChromeTestSuite(argc, argv).Run(); } #if defined(OS_WIN) if (command_line->HasSwitch(switches::kProcessType)) { // This is a child process, call ChromeMain. FilePath chrome_path(command_line->GetProgram().DirName()); chrome_path = chrome_path.Append(chrome::kBrowserResourcesDll); HMODULE dll = LoadLibrary(chrome_path.value().c_str()); DLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll, "ChromeMain")); if (!entry_point) return -1; // Initialize the sandbox services. sandbox::SandboxInterfaceInfo sandbox_info = {0}; sandbox_info.target_services = sandbox::SandboxFactory::GetTargetServices(); return entry_point(GetModuleHandle(NULL), &sandbox_info, GetCommandLineW()); } #endif fprintf(stdout, "Starting tests...\n" "IMPORTANT DEBUGGING NOTE: each test is run inside its own process.\n" "For debugging a test inside a debugger, use the\n" "--gtest_filter=<your_test_name> flag along with either\n" "--single_process (to run all tests in one launcher/browser process) or\n" "--single-process (to do the above, and also run Chrome in single-\n" "process mode).\n"); OutOfProcTestRunnerFactory test_runner_factory; int cycles = 1; if (command_line->HasSwitch(kGTestRepeatFlag)) { base::StringToInt(command_line->GetSwitchValueASCII(kGTestRepeatFlag), &cycles); } int exit_code = 0; while (cycles != 0) { if (!tests::RunTests(test_runner_factory)) { exit_code = 1; break; } // Special value "-1" means "repeat indefinitely". if (cycles != -1) cycles--; } return exit_code; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/render_audiosourceprovider.h" #include "base/basictypes.h" #include "base/logging.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebAudioSourceProviderClient.h" using std::vector; using WebKit::WebVector; RenderAudioSourceProvider::RenderAudioSourceProvider() : is_initialized_(false), channels_(0), sample_rate_(0), is_running_(false), volume_(1.0), renderer_(NULL), client_(NULL) { // We create the AudioDevice here because it must be created in the // main thread. But we don't yet know the audio format (sample-rate, etc.) // at this point. Later, when Initialize() is called, we have // the audio format information and call the AudioDevice::Initialize() // method to fully initialize it. default_sink_ = new AudioDevice(); } RenderAudioSourceProvider::~RenderAudioSourceProvider() {} void RenderAudioSourceProvider::Start() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Start(); is_running_ = true; } void RenderAudioSourceProvider::Stop() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Stop(); is_running_ = false; } void RenderAudioSourceProvider::Play() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Play(); is_running_ = true; } void RenderAudioSourceProvider::Pause(bool flush) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Pause(flush); is_running_ = false; } void RenderAudioSourceProvider::SetPlaybackRate(float rate) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->SetPlaybackRate(rate); } bool RenderAudioSourceProvider::SetVolume(double volume) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->SetVolume(volume); volume_ = volume; return true; } void RenderAudioSourceProvider::GetVolume(double* volume) { if (!client_) default_sink_->GetVolume(volume); else if (volume) *volume = volume_; } void RenderAudioSourceProvider::Initialize( const media::AudioParameters& params, RenderCallback* renderer) { base::AutoLock auto_lock(sink_lock_); CHECK(!is_initialized_); renderer_ = renderer; default_sink_->Initialize(params, renderer); // Keep track of the format in case the client hasn't yet been set. channels_ = params.channels(); sample_rate_ = params.sample_rate(); if (client_) { // Inform WebKit about the audio stream format. client_->setFormat(channels_, sample_rate_); } is_initialized_ = true; } void RenderAudioSourceProvider::setClient( WebKit::WebAudioSourceProviderClient* client) { // Synchronize with other uses of client_ and default_sink_. base::AutoLock auto_lock(sink_lock_); if (client && client != client_) { // Detach the audio renderer from normal playback. default_sink_->Pause(true); // The client will now take control by calling provideInput() periodically. client_ = client; if (is_initialized_) { // The client needs to be notified of the audio format, if available. // If the format is not yet available, we'll be notified later // when Initialize() is called. // Inform WebKit about the audio stream format. client->setFormat(channels_, sample_rate_); } } else if (!client && client_) { // Restore normal playback. client_ = NULL; // TODO(crogers): We should call default_sink_->Play() if we're // in the playing state. } } void RenderAudioSourceProvider::provideInput( const WebVector<float*>& audio_data, size_t number_of_frames) { DCHECK(client_); if (renderer_ && is_initialized_ && is_running_) { // Wrap WebVector as std::vector. vector<float*> v(audio_data.size()); for (size_t i = 0; i < audio_data.size(); ++i) v[i] = audio_data[i]; // TODO(crogers): figure out if we should volume scale here or in common // WebAudio code. In any case we need to take care of volume. renderer_->Render(v, number_of_frames, 0); } else { // Provide silence if the source is not running. for (size_t i = 0; i < audio_data.size(); ++i) memset(audio_data[i], 0, sizeof(float) * number_of_frames); } } <commit_msg>Fix crash when changing sources after createMediaSourceElement().<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/render_audiosourceprovider.h" #include "base/basictypes.h" #include "base/logging.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebAudioSourceProviderClient.h" using std::vector; using WebKit::WebVector; RenderAudioSourceProvider::RenderAudioSourceProvider() : is_initialized_(false), channels_(0), sample_rate_(0), is_running_(false), volume_(1.0), renderer_(NULL), client_(NULL) { // We create the AudioDevice here because it must be created in the // main thread. But we don't yet know the audio format (sample-rate, etc.) // at this point. Later, when Initialize() is called, we have // the audio format information and call the AudioDevice::Initialize() // method to fully initialize it. default_sink_ = new AudioDevice(); } RenderAudioSourceProvider::~RenderAudioSourceProvider() {} void RenderAudioSourceProvider::Start() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Start(); is_running_ = true; } void RenderAudioSourceProvider::Stop() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Stop(); is_running_ = false; } void RenderAudioSourceProvider::Play() { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Play(); is_running_ = true; } void RenderAudioSourceProvider::Pause(bool flush) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->Pause(flush); is_running_ = false; } void RenderAudioSourceProvider::SetPlaybackRate(float rate) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->SetPlaybackRate(rate); } bool RenderAudioSourceProvider::SetVolume(double volume) { base::AutoLock auto_lock(sink_lock_); if (!client_) default_sink_->SetVolume(volume); volume_ = volume; return true; } void RenderAudioSourceProvider::GetVolume(double* volume) { if (!client_) default_sink_->GetVolume(volume); else if (volume) *volume = volume_; } void RenderAudioSourceProvider::Initialize( const media::AudioParameters& params, RenderCallback* renderer) { base::AutoLock auto_lock(sink_lock_); CHECK(!is_initialized_); renderer_ = renderer; default_sink_->Initialize(params, renderer); // Keep track of the format in case the client hasn't yet been set. channels_ = params.channels(); sample_rate_ = params.sample_rate(); if (client_) { // Inform WebKit about the audio stream format. client_->setFormat(channels_, sample_rate_); } is_initialized_ = true; } void RenderAudioSourceProvider::setClient( WebKit::WebAudioSourceProviderClient* client) { // Synchronize with other uses of client_ and default_sink_. base::AutoLock auto_lock(sink_lock_); if (client && client != client_) { // Detach the audio renderer from normal playback. default_sink_->Stop(); // The client will now take control by calling provideInput() periodically. client_ = client; if (is_initialized_) { // The client needs to be notified of the audio format, if available. // If the format is not yet available, we'll be notified later // when Initialize() is called. // Inform WebKit about the audio stream format. client->setFormat(channels_, sample_rate_); } } else if (!client && client_) { // Restore normal playback. client_ = NULL; // TODO(crogers): We should call default_sink_->Play() if we're // in the playing state. } } void RenderAudioSourceProvider::provideInput( const WebVector<float*>& audio_data, size_t number_of_frames) { DCHECK(client_); if (renderer_ && is_initialized_ && is_running_) { // Wrap WebVector as std::vector. vector<float*> v(audio_data.size()); for (size_t i = 0; i < audio_data.size(); ++i) v[i] = audio_data[i]; // TODO(crogers): figure out if we should volume scale here or in common // WebAudio code. In any case we need to take care of volume. renderer_->Render(v, number_of_frames, 0); } else { // Provide silence if the source is not running. for (size_t i = 0; i < audio_data.size(); ++i) memset(audio_data[i], 0, sizeof(float) * number_of_frames); } } <|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <iostream> #include <random> #include <thread> #include <sstream> using namespace std; int main() { sf::TcpSocket socket; string ip = "172.31.247.41"; string portString = ""; string pseudo =""; int port = 80; int code=-1;; int idCLient=-1; sf::Packet data; string sizeGridString = ""; int sizeGrid = -1; string nbPionString = ""; int nbPion = -1; string ipPlayerString = "127.0.0.1"; /**************************** CREATE *****************************/ cout << "Client start" << endl; //Demande des infos de connexion /* cout << "Entrez IP : "; getline(cin, ip); cout << "Entrez port : "; getline(cin, portString); stringstream buffer(portString); buffer >> port; cout << "Entrez port : "; getline(cin, portString); stringstream buffer(portString); buffer >> port; */ cout << "Entrez Pseudo : "; getline(cin, pseudo); sf::Socket::Status status = socket.connect(ip, port); if (status != sf::Socket::Done) cout << "Impossible de se connecter" << endl; else cout << "connexion etablie avec le serveur distant" << endl; //Envoie du pseudo data << 0 << pseudo; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear(); if (socket.receive(data) != sf::Socket::Done) cout << "Erreur receive" << endl; data >> code; data.clear(); cout << code << endl; if(code==101) { idCLient = code-100; cout << "Vous etes les createurs de la partie." << endl; cout << "Veuillez renseigner les options suivantes : " << endl; cout << "Entrez taille de la grille : "; getline(cin, sizeGridString); stringstream buffer1(sizeGridString); buffer1 >> sizeGrid; cout << "Entrez nombre de pions a aligner : "; getline(cin, nbPionString); stringstream buffer2(nbPionString); buffer2 >> nbPion; data << 0 << sizeGrid << ipPlayerString << nbPion; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear(); } else if(code>101 && code<110) { idCLient = code-100; cout << "...En attente d'adversaire..." << endl; } /*if (socket.receive(data) != sf::Socket::Done) cout << "Erreur receive" << endl; data >> code;*/ data.clear(); //if(code == ) sf::RenderWindow window(sf::VideoMode(640, 480), "SFML works!"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { data << 11; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear(); window.close(); } } /**************************** STEP *****************************/ window.clear(); /**************************** DRAW *****************************/ window.display(); } return 0; } <commit_msg>Test branche<commit_after>#include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <iostream> #include <random> #include <thread> #include <sstream> using namespace std; int main() { sf::TcpSocket socket; string ip = "172.31.247.41"; string portString = ""; string pseudo =""; int port = 80; int code=-1;; int idCLient=-1; sf::Packet data; string sizeGridString = ""; int sizeGrid = -1; string nbPionString = ""; int nbPion = -1; string ipPlayerString = "127.0.0.1"; /**************************** CREATE *****************************/ cout << "Client start" << endl; //Demande des infos de connexion /* cout << "Entrez IP : "; getline(cin, ip); cout << "Entrez port : "; getline(cin, portString); stringstream buffer(portString); buffer >> port; cout << "Entrez port : "; getline(cin, portString); stringstream buffer(portString); buffer >> port; */ cout << "Entrez Pseudo : "; getline(cin, pseudo); sf::Socket::Status status = socket.connect(ip, port); if (status != sf::Socket::Done) cout << "Impossible de se connecter" << endl; else cout << "connexion etablie avec le serveur distant" << endl; //Envoie du pseudo data << 0 << pseudo; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear(); if (socket.receive(data) != sf::Socket::Done) cout << "Erreur receive" << endl; data >> code; data.clear(); cout << code << endl; if(code==101) { idCLient = code-100; /*cout << "Vous etes les createurs de la partie." << endl; cout << "Veuillez renseigner les options suivantes : " << endl; cout << "Entrez taille de la grille : "; getline(cin, sizeGridString); stringstream buffer1(sizeGridString); buffer1 >> sizeGrid; cout << "Entrez nombre de pions a aligner : "; getline(cin, nbPionString); stringstream buffer2(nbPionString); buffer2 >> nbPion; data << 0 << sizeGrid << ipPlayerString << nbPion; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear();*/ } else if(code>101 && code<110) { idCLient = code-100; cout << "...En attente d'adversaire..." << endl; } /*if (socket.receive(data) != sf::Socket::Done) cout << "Erreur receive" << endl; data >> code;*/ data.clear(); //if(code == ) sf::RenderWindow window(sf::VideoMode(640, 480), "SFML works!"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { data << 11; if (socket.send(data) != sf::Socket::Done) std::cout << "Impossible d'envoyer les donnees au serveur" << std::endl; data.clear(); window.close(); } } /**************************** STEP *****************************/ window.clear(); /**************************** DRAW *****************************/ window.display(); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp" #include "iceoryx_posh/popo/condition.hpp" #include "iceoryx_posh/popo/guard_condition.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include "timing_test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool setConditionVariable(ConditionVariableData* const conditionVariableDataPtr) noexcept override { m_condVarPtr = conditionVariableDataPtr; return true; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool unsetConditionVariable() noexcept override { m_condVarPtr = nullptr; return true; } /// @note done in ChunkQueuePusher void notify() { // We don't need to check if the WaitSet is still alive as it follows RAII and will inform every Condition about // a possible destruction m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_sut.detachAllConditions(); m_subscriberVector.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front()).has_error()); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, AttachConditionAndDestroyResultsInLifetimeFailure) { auto errorHandlerCalled{false}; iox::Error receivedError; WaitSet* m_sut2 = static_cast<WaitSet*>(malloc(sizeof(WaitSet))); new (m_sut2) WaitSet{&m_condVarData}; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&errorHandlerCalled, &receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerCalled = true; receivedError = error; }); { MockSubscriber scopedCondition; m_sut2->attachCondition(scopedCondition); } EXPECT_TRUE(errorHandlerCalled); EXPECT_THAT(receivedError, Eq(iox::Error::kPOPO__WAITSET_CONDITION_LIFETIME_ISSUE)); free(m_sut2); } TEST_F(WaitSet_test, AttachConditionAndDestroyWaitSetResultsInDetach) { { WaitSet m_sut2{&m_condVarData}; m_sut2.attachCondition(m_subscriberVector.front()); } EXPECT_FALSE(m_subscriberVector.front().isConditionVariableAttached()); } TEST_F(WaitSet_test, DISABLED_AttachConditionAndMoveIsSuccessful) { /// @todo move c'tor currently deleted } TEST_F(WaitSet_test, DISABLED_AttachConditionAndMoveAssignIsSuccessful) { /// @todo move assign currently deleted } TEST_F(WaitSet_test, AttachMaximumAllowedConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_FALSE(m_sut.attachCondition(currentSubscriber).has_error()); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_THAT(m_sut.attachCondition(extraCondition).get_error(), Eq(WaitSetError::CONDITION_VECTOR_OVERFLOW)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, AttachConditionInTwoWaitSetsResultsInAlreadySetError) { WaitSet m_sut2{&m_condVarData}; m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut2.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithMaximumNumberOfConditionsResultsInReturnOfMaximumNumberOfConditions) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); currentSubscriber.notify(); } auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(iox::MAX_NUMBER_OF_CONDITIONS)); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TIMING_TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded, Repeat(5), [&] { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); TIMING_TEST_ASSERT_TRUE(fulfilledConditions.size() == 2); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); }); TIMING_TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded, Repeat(5), [&] { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); }); TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.setTrigger(); waiter.join(); m_sut.detachCondition(guardCond); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.setTrigger(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); m_sut.detachCondition(guardCond); } <commit_msg>iox-#25: Increase repeat count in waitset test<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp" #include "iceoryx_posh/popo/condition.hpp" #include "iceoryx_posh/popo/guard_condition.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include "timing_test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool setConditionVariable(ConditionVariableData* const conditionVariableDataPtr) noexcept override { m_condVarPtr = conditionVariableDataPtr; return true; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool unsetConditionVariable() noexcept override { m_condVarPtr = nullptr; return true; } /// @note done in ChunkQueuePusher void notify() { // We don't need to check if the WaitSet is still alive as it follows RAII and will inform every Condition about // a possible destruction m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_sut.detachAllConditions(); m_subscriberVector.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front()).has_error()); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, AttachConditionAndDestroyResultsInLifetimeFailure) { auto errorHandlerCalled{false}; iox::Error receivedError; WaitSet* m_sut2 = static_cast<WaitSet*>(malloc(sizeof(WaitSet))); new (m_sut2) WaitSet{&m_condVarData}; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&errorHandlerCalled, &receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerCalled = true; receivedError = error; }); { MockSubscriber scopedCondition; m_sut2->attachCondition(scopedCondition); } EXPECT_TRUE(errorHandlerCalled); EXPECT_THAT(receivedError, Eq(iox::Error::kPOPO__WAITSET_CONDITION_LIFETIME_ISSUE)); free(m_sut2); } TEST_F(WaitSet_test, AttachConditionAndDestroyWaitSetResultsInDetach) { { WaitSet m_sut2{&m_condVarData}; m_sut2.attachCondition(m_subscriberVector.front()); } EXPECT_FALSE(m_subscriberVector.front().isConditionVariableAttached()); } TEST_F(WaitSet_test, DISABLED_AttachConditionAndMoveIsSuccessful) { /// @todo move c'tor currently deleted } TEST_F(WaitSet_test, DISABLED_AttachConditionAndMoveAssignIsSuccessful) { /// @todo move assign currently deleted } TEST_F(WaitSet_test, AttachMaximumAllowedConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_FALSE(m_sut.attachCondition(currentSubscriber).has_error()); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_THAT(m_sut.attachCondition(extraCondition).get_error(), Eq(WaitSetError::CONDITION_VECTOR_OVERFLOW)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, AttachConditionInTwoWaitSetsResultsInAlreadySetError) { WaitSet m_sut2{&m_condVarData}; m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut2.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithMaximumNumberOfConditionsResultsInReturnOfMaximumNumberOfConditions) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); currentSubscriber.notify(); } auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(iox::MAX_NUMBER_OF_CONDITIONS)); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TIMING_TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded, Repeat(5), [&] { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); TIMING_TEST_ASSERT_TRUE(fulfilledConditions.size() == 2); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); }); TIMING_TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded, Repeat(10), [&] { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); }); TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.setTrigger(); waiter.join(); m_sut.detachCondition(guardCond); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.setTrigger(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); m_sut.detachCondition(guardCond); } <|endoftext|>
<commit_before>//The MIT License (MIT) // //Copyright (c) 2015 // //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 "LFX2.h" //Can be found as part of the AlienFX SDK #include "ProcessHandler.h" #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { ShowWindow(GetConsoleWindow(), SW_HIDE); HINSTANCE hLibrary = LoadLibrary(_T("LightFX.dll")); if(hLibrary) { LFX2INITIALIZE LFX_Initialize = (LFX2INITIALIZE)GetProcAddress(hLibrary, LFX_DLL_INITIALIZE); LFX2RELEASE LFX_Release = (LFX2RELEASE)GetProcAddress(hLibrary, LFX_DLL_RELEASE); LFX2RESET LFX_Reset = (LFX2RESET)GetProcAddress(hLibrary,LFX_DLL_RESET); LFX2UPDATE LFX_Update = (LFX2UPDATE)GetProcAddress(hLibrary, LFX_DLL_UPDATE); LFX2LIGHT LFX_Light = (LFX2LIGHT)GetProcAddress(hLibrary,LFX_DLL_LIGHT); BYTE* pHealth = nullptr; HANDLE hProcess = OpenFirstSupportedProcess(&pHealth); if(hProcess && pHealth) { LFX_Initialize(); int playerHealth = 0; int playerMaxHealth = 0; int readBuf = NULL; SIZE_T numofbytesread = NULL; while(ReadProcessMemory(hProcess,pHealth,&readBuf,sizeof(int),&numofbytesread)) { if(playerHealth != readBuf) //prevents updating unnecessarily { playerHealth = readBuf; if(playerHealth > playerMaxHealth) playerMaxHealth = playerHealth; else if(playerHealth <= 0) playerMaxHealth = 1; LFX_Reset(); unsigned int brightness = (playerMaxHealth-playerHealth)*0x1000000; unsigned int lightSettings = LFX_RED | brightness; LFX_Light(LFX_ALL,lightSettings); LFX_Update(); Sleep(10); } } LFX_Release(); CloseHandle(hProcess); FreeLibrary(hLibrary); } else { MessageBox(0,L"Couldn't find a supported process\n",0,0); FreeLibrary(hLibrary); return 0; } } else { MessageBox(0,L"Couldn't load LightFX.dll\n",0,0); } return 0; }<commit_msg>Changed Console Application to Win32 Application<commit_after>//The MIT License (MIT) // //Copyright (c) 2015 // //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 "LFX2.h" //Can be found as part of the AlienFX SDK #include "ProcessHandler.h" #include <iostream> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HINSTANCE hLibrary = LoadLibrary(L"LightFX.dll"); if(hLibrary) { LFX2INITIALIZE LFX_Initialize = (LFX2INITIALIZE)GetProcAddress(hLibrary, LFX_DLL_INITIALIZE); LFX2RELEASE LFX_Release = (LFX2RELEASE)GetProcAddress(hLibrary, LFX_DLL_RELEASE); LFX2RESET LFX_Reset = (LFX2RESET)GetProcAddress(hLibrary,LFX_DLL_RESET); LFX2UPDATE LFX_Update = (LFX2UPDATE)GetProcAddress(hLibrary, LFX_DLL_UPDATE); LFX2LIGHT LFX_Light = (LFX2LIGHT)GetProcAddress(hLibrary,LFX_DLL_LIGHT); BYTE* pHealth = nullptr; HANDLE hProcess = OpenFirstSupportedProcess(&pHealth); if(hProcess && pHealth) { LFX_Initialize(); int playerHealth = 0; int playerMaxHealth = 0; int readBuf = NULL; SIZE_T numofbytesread = NULL; while(ReadProcessMemory(hProcess,pHealth,&readBuf,sizeof(int),&numofbytesread)) { if(playerHealth != readBuf) //prevents updating unnecessarily { playerHealth = readBuf; if(playerHealth > playerMaxHealth) playerMaxHealth = playerHealth; else if(playerHealth <= 0) playerMaxHealth = 1; LFX_Reset(); unsigned int brightness = (playerMaxHealth-playerHealth)*0x1000000; unsigned int lightSettings = LFX_RED | brightness; LFX_Light(LFX_ALL,lightSettings); LFX_Update(); Sleep(10); } } LFX_Release(); CloseHandle(hProcess); FreeLibrary(hLibrary); } else { MessageBox(0,L"ERROR: Couldn't find a supported process\nClosing health monitor",0,0); FreeLibrary(hLibrary); return 0; } } else { MessageBox(0,L"ERROR: Couldn't load LightFX.dll\n",0,0); } return 0; }<|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2012, hiDOF INC. // Copyright (C) 2013, PAL Robotics S.L. // // 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 PAL Robotics S.L. 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: Adolfo Rodriguez Tsouroukdissian #include "imu_sensor_controller/imu_sensor_controller.h" namespace imu_sensor_controller { bool ImuSensorController::init(hardware_interface::ImuSensorInterface* hw, ros::NodeHandle &root_nh, ros::NodeHandle& controller_nh) { // get all joint states from the hardware interface const std::vector<std::string>& sensor_names = hw->getNames(); for (unsigned i=0; i<sensor_names.size(); i++) ROS_DEBUG("Got sensor %s", sensor_names[i].c_str()); // get publishing period if (!controller_nh.getParam("publish_rate", publish_rate_)){ ROS_ERROR("Parameter 'publish_rate' not set"); return false; } for (unsigned i=0; i<sensor_names.size(); i++){ // sensor handle sensors_.push_back(hw->getHandle(sensor_names[i])); // realtime publisher RtPublisherPtr rt_pub(new realtime_tools::RealtimePublisher<sensor_msgs::Imu>(root_nh, sensor_names[i], 4)); realtime_pubs_.push_back(rt_pub); } // Last published times last_publish_times_.resize(sensor_names.size()); return true; } void ImuSensorController::starting(const ros::Time& time) { // initialize time for (unsigned i=0; i<last_publish_times_.size(); i++){ last_publish_times_[i] = time; } } void ImuSensorController::update(const ros::Time& time, const ros::Duration& /*period*/) { using namespace hardware_interface; // limit rate of publishing for (unsigned i=0; i<realtime_pubs_.size(); i++){ if (publish_rate_ > 0.0 && last_publish_times_[i] + ros::Duration(1.0/publish_rate_) < time){ // try to publish if (realtime_pubs_[i]->trylock()){ // we're actually publishing, so increment time last_publish_times_[i] = last_publish_times_[i] + ros::Duration(1.0/publish_rate_); // populate message realtime_pubs_[i]->msg_.header.stamp = time; realtime_pubs_[i]->msg_.header.frame_id = sensors_[i].getFrameId(); // Orientation if (sensors_[i].getOrientation()) { realtime_pubs_[i]->msg_.orientation.x = sensors_[i].getOrientation()[0]; realtime_pubs_[i]->msg_.orientation.y = sensors_[i].getOrientation()[1]; realtime_pubs_[i]->msg_.orientation.z = sensors_[i].getOrientation()[2]; realtime_pubs_[i]->msg_.orientation.w = sensors_[i].getOrientation()[3]; } // Orientation covariance if (sensors_[i].getOrientationCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.orientation_covariance.size(); ++j){ realtime_pubs_[i]->msg_.orientation_covariance[i] = sensors_[i].getOrientationCovariance()[i]; } } else { if (sensors_[i].getOrientation()) { // Orientation available for (unsigned j=0; j<realtime_pubs_[i]->msg_.orientation_covariance.size(); ++j){ realtime_pubs_[i]->msg_.orientation_covariance[j] = 0.0; } } else { // No orientation available realtime_pubs_[i]->msg_.orientation_covariance[0] = -1.0; } } // Angular velocity if (sensors_[i].getAngularVelocity()) { realtime_pubs_[i]->msg_.angular_velocity.x = sensors_[i].getAngularVelocity()[0]; realtime_pubs_[i]->msg_.angular_velocity.y = sensors_[i].getAngularVelocity()[1]; realtime_pubs_[i]->msg_.angular_velocity.z = sensors_[i].getAngularVelocity()[2]; } // Angular velocity covariance if (sensors_[i].getAngularVelocityCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.angular_velocity_covariance.size(); ++j){ realtime_pubs_[i]->msg_.angular_velocity_covariance[i] = sensors_[i].getAngularVelocityCovariance()[i]; } } else { if (sensors_[i].getAngularVelocity()) { // Angular velocity available for (unsigned j=0; j<realtime_pubs_[i]->msg_.angular_velocity_covariance.size(); ++j){ realtime_pubs_[i]->msg_.angular_velocity_covariance[j] = 0.0; } } else { // No angular velocity available realtime_pubs_[i]->msg_.angular_velocity_covariance[0] = -1.0; } } // Linear acceleration if (sensors_[i].getLinearAcceleration()) { realtime_pubs_[i]->msg_.linear_acceleration.x = sensors_[i].getLinearAcceleration()[0]; realtime_pubs_[i]->msg_.linear_acceleration.y = sensors_[i].getLinearAcceleration()[1]; realtime_pubs_[i]->msg_.linear_acceleration.z = sensors_[i].getLinearAcceleration()[2]; } // Linear acceleration covariance if (sensors_[i].getLinearAccelerationCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.linear_acceleration_covariance.size(); ++j){ realtime_pubs_[i]->msg_.linear_acceleration_covariance[i] = sensors_[i].getLinearAccelerationCovariance()[i]; } } else { if (sensors_[i].getLinearAcceleration()) { // Linear acceleration available for (unsigned j=0; j<realtime_pubs_[i]->msg_.linear_acceleration_covariance.size(); ++j){ realtime_pubs_[i]->msg_.linear_acceleration_covariance[j] = 0.0; } } else { // No linear acceleration available realtime_pubs_[i]->msg_.linear_acceleration_covariance[0] = -1.0; } } realtime_pubs_[i]->unlockAndPublish(); } } } } void ImuSensorController::stopping(const ros::Time& /*time*/) {} } PLUGINLIB_EXPORT_CLASS(imu_sensor_controller::ImuSensorController, controller_interface::ControllerBase) <commit_msg>Fixed covariances in ImuSensorController::update<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2012, hiDOF INC. // Copyright (C) 2013, PAL Robotics S.L. // // 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 PAL Robotics S.L. 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: Adolfo Rodriguez Tsouroukdissian #include "imu_sensor_controller/imu_sensor_controller.h" namespace imu_sensor_controller { bool ImuSensorController::init(hardware_interface::ImuSensorInterface* hw, ros::NodeHandle &root_nh, ros::NodeHandle& controller_nh) { // get all joint states from the hardware interface const std::vector<std::string>& sensor_names = hw->getNames(); for (unsigned i=0; i<sensor_names.size(); i++) ROS_DEBUG("Got sensor %s", sensor_names[i].c_str()); // get publishing period if (!controller_nh.getParam("publish_rate", publish_rate_)){ ROS_ERROR("Parameter 'publish_rate' not set"); return false; } for (unsigned i=0; i<sensor_names.size(); i++){ // sensor handle sensors_.push_back(hw->getHandle(sensor_names[i])); // realtime publisher RtPublisherPtr rt_pub(new realtime_tools::RealtimePublisher<sensor_msgs::Imu>(root_nh, sensor_names[i], 4)); realtime_pubs_.push_back(rt_pub); } // Last published times last_publish_times_.resize(sensor_names.size()); return true; } void ImuSensorController::starting(const ros::Time& time) { // initialize time for (unsigned i=0; i<last_publish_times_.size(); i++){ last_publish_times_[i] = time; } } void ImuSensorController::update(const ros::Time& time, const ros::Duration& /*period*/) { using namespace hardware_interface; // limit rate of publishing for (unsigned i=0; i<realtime_pubs_.size(); i++){ if (publish_rate_ > 0.0 && last_publish_times_[i] + ros::Duration(1.0/publish_rate_) < time){ // try to publish if (realtime_pubs_[i]->trylock()){ // we're actually publishing, so increment time last_publish_times_[i] = last_publish_times_[i] + ros::Duration(1.0/publish_rate_); // populate message realtime_pubs_[i]->msg_.header.stamp = time; realtime_pubs_[i]->msg_.header.frame_id = sensors_[i].getFrameId(); // Orientation if (sensors_[i].getOrientation()) { realtime_pubs_[i]->msg_.orientation.x = sensors_[i].getOrientation()[0]; realtime_pubs_[i]->msg_.orientation.y = sensors_[i].getOrientation()[1]; realtime_pubs_[i]->msg_.orientation.z = sensors_[i].getOrientation()[2]; realtime_pubs_[i]->msg_.orientation.w = sensors_[i].getOrientation()[3]; } // Orientation covariance if (sensors_[i].getOrientationCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.orientation_covariance.size(); ++j){ realtime_pubs_[i]->msg_.orientation_covariance[j] = sensors_[i].getOrientationCovariance()[j]; } } else { if (sensors_[i].getOrientation()) { // Orientation available for (unsigned j=0; j<realtime_pubs_[i]->msg_.orientation_covariance.size(); ++j){ realtime_pubs_[i]->msg_.orientation_covariance[j] = 0.0; } } else { // No orientation available realtime_pubs_[i]->msg_.orientation_covariance[0] = -1.0; } } // Angular velocity if (sensors_[i].getAngularVelocity()) { realtime_pubs_[i]->msg_.angular_velocity.x = sensors_[i].getAngularVelocity()[0]; realtime_pubs_[i]->msg_.angular_velocity.y = sensors_[i].getAngularVelocity()[1]; realtime_pubs_[i]->msg_.angular_velocity.z = sensors_[i].getAngularVelocity()[2]; } // Angular velocity covariance if (sensors_[i].getAngularVelocityCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.angular_velocity_covariance.size(); ++j){ realtime_pubs_[i]->msg_.angular_velocity_covariance[j] = sensors_[i].getAngularVelocityCovariance()[j]; } } else { if (sensors_[i].getAngularVelocity()) { // Angular velocity available for (unsigned j=0; j<realtime_pubs_[i]->msg_.angular_velocity_covariance.size(); ++j){ realtime_pubs_[i]->msg_.angular_velocity_covariance[j] = 0.0; } } else { // No angular velocity available realtime_pubs_[i]->msg_.angular_velocity_covariance[0] = -1.0; } } // Linear acceleration if (sensors_[i].getLinearAcceleration()) { realtime_pubs_[i]->msg_.linear_acceleration.x = sensors_[i].getLinearAcceleration()[0]; realtime_pubs_[i]->msg_.linear_acceleration.y = sensors_[i].getLinearAcceleration()[1]; realtime_pubs_[i]->msg_.linear_acceleration.z = sensors_[i].getLinearAcceleration()[2]; } // Linear acceleration covariance if (sensors_[i].getLinearAccelerationCovariance()) { for (unsigned j=0; j<realtime_pubs_[i]->msg_.linear_acceleration_covariance.size(); ++j){ realtime_pubs_[i]->msg_.linear_acceleration_covariance[j] = sensors_[i].getLinearAccelerationCovariance()[j]; } } else { if (sensors_[i].getLinearAcceleration()) { // Linear acceleration available for (unsigned j=0; j<realtime_pubs_[i]->msg_.linear_acceleration_covariance.size(); ++j){ realtime_pubs_[i]->msg_.linear_acceleration_covariance[j] = 0.0; } } else { // No linear acceleration available realtime_pubs_[i]->msg_.linear_acceleration_covariance[0] = -1.0; } } realtime_pubs_[i]->unlockAndPublish(); } } } } void ImuSensorController::stopping(const ros::Time& /*time*/) {} } PLUGINLIB_EXPORT_CLASS(imu_sensor_controller::ImuSensorController, controller_interface::ControllerBase) <|endoftext|>
<commit_before>#include <GL/gl3w.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <fstream> #include <string> #include <vector> #include <camera.h> #include <controls.h> #include <lights/lightlist.h> #include <materials/phongmaterial.h> #include <renderwindow.h> #include <texture.h> #include <utilities.h> const unsigned int screenWidth = 800; const unsigned int screenHeight = 600; struct Vertex { glm::vec3 position; glm::vec3 normal; glm::vec2 uvCoords; }; void calculateNormals( const std::vector<GLuint> &indices, std::vector<Vertex> &vertices ) { for (unsigned int i = 0; i < indices.size(); i += 3) { auto index0 = indices[i]; auto index1 = indices[i + 1]; auto index2 = indices[i + 2]; glm::vec3 v1 = vertices[index1].position - vertices[index0].position; glm::vec3 v2 = vertices[index2].position - vertices[index0].position; glm::vec3 normal = glm::cross(v1, v2); normal = glm::normalize(normal); vertices[index0].normal += normal; vertices[index1].normal += normal; vertices[index2].normal += normal; } for (unsigned int i = 0; i < vertices.size(); ++i) { vertices[i].normal = glm::normalize(vertices[i].normal); } } int main() { //Initialize SDL2 with video and event modes enabled, //and request an OpenGL 3.3 Core Profile RenderWindow renderWindow("ogldev.atspace.co.uk Tutorial 20 -- Point Light", screenWidth, screenHeight); //Vector, UV, normal std::vector<Vertex> vertices = { {glm::vec3(-10.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)}, {glm::vec3(0.0f, -10.0f, 10.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.5f, 0.0f)}, {glm::vec3(10.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f)}, {glm::vec3(0.0f, 10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.5f, 1.0f)} }; //Note: the order of indices for each vertex matters. They are used to determine the "facing" of the traingle. //These are specified properly in clockwise order, but mix it up and you'll get faces culled //because of the backface culling operation std::vector<GLuint> indices = { 0, 3, 1, 1, 3, 2, 2, 3, 0, 0, 1, 2 }; //Create an index buffer to share vertices among triangles GLuint IBO; glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * indices.size(), indices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); calculateNormals(indices, vertices); //Allocate a buffer for our vertices GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); std::string vertexShaderPath = "../src/shaders/passthrough.vsh"; std::string fragmentShaderPath = "../src/shaders/passthrough.fsh"; std::vector<uint8_t> vertexShaderSource; std::vector<uint8_t> geometryShaderSource; std::vector<uint8_t> fragmentShaderSource; if (!Utilities::File::getFileContents(vertexShaderSource, vertexShaderPath)) { std::cout << "Failed to load " + vertexShaderPath << std::endl; } if (!Utilities::File::getFileContents(fragmentShaderSource, fragmentShaderPath)) { std::cout << "Failed to load " + fragmentShaderPath << std::endl; } PhongMaterial basicPassthroughMaterial(vertexShaderSource, geometryShaderSource, fragmentShaderSource); SDL_Event event; bool userRequestedExit = false; glEnable(GL_DEPTH_TEST); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glFrontFace(GL_CW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); float scale = 0.0f; glm::mat4 worldMatrix; glm::mat4 scaleMatrix = glm::scale(glm::mat4(), glm::vec3(.5, .5, .5)); glm::mat4 rotationMatrix = glm::rotate(glm::mat4(), (float)(2 * Utilities::Math::PI * (60.0 / 360)), glm::vec3(-1, 0, 0)); glm::mat4 translationMatrix; glm::mat4 perspectiveProjection = glm::perspective( (GLfloat)Utilities::Math::degreesToRadians(60.0), ((GLfloat)screenWidth / (GLfloat)screenHeight), 0.1f, 100.0f ); Controls playerControls; auto playerCamera = std::make_shared<Camera>(glm::lookAt( glm::vec3(0, 0, 0), //position glm::vec3(0, 0, -1), //looking towards this direction glm::vec3(0, 1, 0) //up vector ) ); glm::mat4 viewMatrix = playerCamera->getViewMatrix(); glm::mat4 WVPMatrix; //Get handle to WVP uniform in the shader program basicPassthroughMaterial.addUniformAttribute("WVPMatrix"); auto WVPMatrixHandle = basicPassthroughMaterial.getUniformAttribute("WVPMatrix"); //Get handle to world matrix uniform for use w/ normals for lighting basicPassthroughMaterial.addUniformAttribute("worldMatrix"); auto worldMatrixHandle = basicPassthroughMaterial.getUniformAttribute("worldMatrix"); //Initialize glVertexAttribPointers while VBO is bound glBindBuffer(GL_ARRAY_BUFFER, VBO); basicPassthroughMaterial.addAttribute("position"); basicPassthroughMaterial.setGLVertexAttribPointer("position", 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); basicPassthroughMaterial.addAttribute("normal"); basicPassthroughMaterial.setGLVertexAttribPointer("normal", 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)sizeof(glm::vec3)); basicPassthroughMaterial.addAttribute("texCoord"); basicPassthroughMaterial.setGLVertexAttribPointer("texCoord", 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)(sizeof(glm::vec3) * 2)); glBindBuffer(GL_ARRAY_BUFFER, 0); //Set the sampler uniform for the fragment shader that we're going to use. //Note: technically unnecessary since we're only using 1 texture unit, //but good to be explicitly correct when possible //Note: need to bind the material so the contained shader program is active, otherwise //the glUniform* don't set values on the appropriate shader program basicPassthroughMaterial.bind(); basicPassthroughMaterial.addUniformAttribute("sampler"); glUniform1i(basicPassthroughMaterial.getUniformAttribute("sampler"), 0); //Add a directional light into the scene // basicPassthroughMaterial.addDirectionalLightUniformAttribute("directionalLight"); basicPassthroughMaterial.addPointLightUniformAttribute("pointLight"); basicPassthroughMaterial.addCameraPositionUniformAttribute("cameraPosition"); LightList lights(playerCamera); auto directionalLightHandle = lights.addDirectionalLight( glm::vec3(1.0f, 1.0f, 1.0f), //light color glm::vec3(1.0f, 1.0f, 0.0f), //light direction 0.1f, //ambient intensity 0.8f, //diffuse intensity 1.0f, //specular intensity 32 //specular power ); auto pointLightHandle = lights.addPointLight( glm::vec3(1.0f, 0.5f, 0.0f), //color glm::vec3(0.0f, 0.0f, 8.0f), //position 0.1f, //ambient intensity 0.5f, //diffuse intensity 1.0f, //specular intensity 32, //specular power 1.0f, //attenuation constant 0.1f, //attenuation linear 0.0f //attenuation exponential ); lights.setLights( basicPassthroughMaterial.getDirectionalLightUniforms(), basicPassthroughMaterial.getPointLightUniforms(), basicPassthroughMaterial.getCameraPositionUniformAttribute() ); basicPassthroughMaterial.unbind(); //Load the texture for our basic pyramid object std::vector<uint8_t> rawImageData; bool loadedImageFile = Utilities::File::getFileContents(rawImageData, "../test.png"); if (!loadedImageFile) { std::cout << "Failed to load the texture image"; return EXIT_FAILURE; } Texture pyramidTexture; pyramidTexture.load(GL_TEXTURE_2D, rawImageData, TextureFormat::PNG); pyramidTexture.setTextureParams( GL_REPEAT, GL_REPEAT, GL_LINEAR, GL_LINEAR, false ); pyramidTexture.bind(GL_TEXTURE0); auto pointLightBase = lights.getLightByID(pointLightHandle); auto pointLight = static_cast<PointLight*>(pointLightBase); while (userRequestedExit == false) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) { userRequestedExit = true; } } playerControls.update(); playerCamera->update(playerControls); //Quick hack for ambient light controls if (playerControls.isKeyPressed(ControlKeys::AmbientLightUp)) { lights.getLightByID(directionalLightHandle)->ambientIntensity += 0.05f; } if (playerControls.isKeyPressed(ControlKeys::AmbientLightDown)) { lights.getLightByID(directionalLightHandle)->ambientIntensity -= 0.05f; } scale += 0.002f; //Spin & move the dummy pyriamid rotationMatrix = glm::rotate(rotationMatrix, (float)(2 * Utilities::Math::PI * (2.0/360)), glm::vec3(0, 1, 0)); translationMatrix = glm::translate(glm::mat4(), glm::vec3(sinf(scale * 2), 0, -3)); // worldMatrix = translationMatrix * rotationMatrix * scaleMatrix; //Move the point light back and forth float lightMoveIncrement = .1; if (pointLight->position.x > 15 || pointLight->position.x < -15) { pointLight->position.x = -15; } pointLight->position.x += lightMoveIncrement; viewMatrix = playerCamera->getViewMatrix(); WVPMatrix = perspectiveProjection * viewMatrix * worldMatrix; basicPassthroughMaterial.bind(); lights.setLights( basicPassthroughMaterial.getDirectionalLightUniforms(), basicPassthroughMaterial.getPointLightUniforms(), basicPassthroughMaterial.getCameraPositionUniformAttribute() ); glUniformMatrix4fv(WVPMatrixHandle, 1, GL_FALSE, &WVPMatrix[0][0]); glUniformMatrix4fv(worldMatrixHandle, 1, GL_FALSE, &worldMatrix[0][0]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0); basicPassthroughMaterial.unbind(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); SDL_GL_SwapWindow(renderWindow.getRenderWindowHandle()); } //Shutdown SDL2 before exiting the program renderWindow.freeResources(); return EXIT_SUCCESS; } <commit_msg>Add directional light back. Tutorial 20 now shows a stationary directional light + moving point light<commit_after>#include <GL/gl3w.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <iostream> #include <fstream> #include <string> #include <vector> #include <camera.h> #include <controls.h> #include <lights/lightlist.h> #include <materials/phongmaterial.h> #include <renderwindow.h> #include <texture.h> #include <utilities.h> const unsigned int screenWidth = 800; const unsigned int screenHeight = 600; struct Vertex { glm::vec3 position; glm::vec3 normal; glm::vec2 uvCoords; }; void calculateNormals( const std::vector<GLuint> &indices, std::vector<Vertex> &vertices ) { for (unsigned int i = 0; i < indices.size(); i += 3) { auto index0 = indices[i]; auto index1 = indices[i + 1]; auto index2 = indices[i + 2]; glm::vec3 v1 = vertices[index1].position - vertices[index0].position; glm::vec3 v2 = vertices[index2].position - vertices[index0].position; glm::vec3 normal = glm::cross(v1, v2); normal = glm::normalize(normal); vertices[index0].normal += normal; vertices[index1].normal += normal; vertices[index2].normal += normal; } for (unsigned int i = 0; i < vertices.size(); ++i) { vertices[i].normal = glm::normalize(vertices[i].normal); } } int main() { //Initialize SDL2 with video and event modes enabled, //and request an OpenGL 3.3 Core Profile RenderWindow renderWindow("ogldev.atspace.co.uk Tutorial 20 -- Point Light", screenWidth, screenHeight); //Vector, UV, normal std::vector<Vertex> vertices = { {glm::vec3(-10.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)}, {glm::vec3(0.0f, -10.0f, 10.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.5f, 0.0f)}, {glm::vec3(10.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f)}, {glm::vec3(0.0f, 10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.5f, 1.0f)} }; //Note: the order of indices for each vertex matters. They are used to determine the "facing" of the traingle. //These are specified properly in clockwise order, but mix it up and you'll get faces culled //because of the backface culling operation std::vector<GLuint> indices = { 0, 3, 1, 1, 3, 2, 2, 3, 0, 0, 1, 2 }; //Create an index buffer to share vertices among triangles GLuint IBO; glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * indices.size(), indices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); calculateNormals(indices, vertices); //Allocate a buffer for our vertices GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); std::string vertexShaderPath = "../src/shaders/passthrough.vsh"; std::string fragmentShaderPath = "../src/shaders/passthrough.fsh"; std::vector<uint8_t> vertexShaderSource; std::vector<uint8_t> geometryShaderSource; std::vector<uint8_t> fragmentShaderSource; if (!Utilities::File::getFileContents(vertexShaderSource, vertexShaderPath)) { std::cout << "Failed to load " + vertexShaderPath << std::endl; } if (!Utilities::File::getFileContents(fragmentShaderSource, fragmentShaderPath)) { std::cout << "Failed to load " + fragmentShaderPath << std::endl; } PhongMaterial basicPassthroughMaterial(vertexShaderSource, geometryShaderSource, fragmentShaderSource); SDL_Event event; bool userRequestedExit = false; glEnable(GL_DEPTH_TEST); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glFrontFace(GL_CW); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); float scale = 0.0f; glm::mat4 worldMatrix; glm::mat4 scaleMatrix = glm::scale(glm::mat4(), glm::vec3(.5, .5, .5)); glm::mat4 rotationMatrix = glm::rotate(glm::mat4(), (float)(2 * Utilities::Math::PI * (60.0 / 360)), glm::vec3(-1, 0, 0)); glm::mat4 translationMatrix; glm::mat4 perspectiveProjection = glm::perspective( (GLfloat)Utilities::Math::degreesToRadians(60.0), ((GLfloat)screenWidth / (GLfloat)screenHeight), 0.1f, 100.0f ); Controls playerControls; auto playerCamera = std::make_shared<Camera>(glm::lookAt( glm::vec3(0, 0, 0), //position glm::vec3(0, 0, -1), //looking towards this direction glm::vec3(0, 1, 0) //up vector ) ); glm::mat4 viewMatrix = playerCamera->getViewMatrix(); glm::mat4 WVPMatrix; //Get handle to WVP uniform in the shader program basicPassthroughMaterial.addUniformAttribute("WVPMatrix"); auto WVPMatrixHandle = basicPassthroughMaterial.getUniformAttribute("WVPMatrix"); //Get handle to world matrix uniform for use w/ normals for lighting basicPassthroughMaterial.addUniformAttribute("worldMatrix"); auto worldMatrixHandle = basicPassthroughMaterial.getUniformAttribute("worldMatrix"); //Initialize glVertexAttribPointers while VBO is bound glBindBuffer(GL_ARRAY_BUFFER, VBO); basicPassthroughMaterial.addAttribute("position"); basicPassthroughMaterial.setGLVertexAttribPointer("position", 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); basicPassthroughMaterial.addAttribute("normal"); basicPassthroughMaterial.setGLVertexAttribPointer("normal", 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)sizeof(glm::vec3)); basicPassthroughMaterial.addAttribute("texCoord"); basicPassthroughMaterial.setGLVertexAttribPointer("texCoord", 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)(sizeof(glm::vec3) * 2)); glBindBuffer(GL_ARRAY_BUFFER, 0); //Set the sampler uniform for the fragment shader that we're going to use. //Note: technically unnecessary since we're only using 1 texture unit, //but good to be explicitly correct when possible //Note: need to bind the material so the contained shader program is active, otherwise //the glUniform* don't set values on the appropriate shader program basicPassthroughMaterial.bind(); basicPassthroughMaterial.addUniformAttribute("sampler"); glUniform1i(basicPassthroughMaterial.getUniformAttribute("sampler"), 0); //Add a directional light into the scene basicPassthroughMaterial.addDirectionalLightUniformAttribute("directionalLight"); basicPassthroughMaterial.addPointLightUniformAttribute("pointLight"); basicPassthroughMaterial.addCameraPositionUniformAttribute("cameraPosition"); LightList lights(playerCamera); auto directionalLightHandle = lights.addDirectionalLight( glm::vec3(1.0f, 1.0f, 1.0f), //light color glm::vec3(1.0f, 1.0f, 0.0f), //light direction 0.1f, //ambient intensity 0.8f, //diffuse intensity 1.0f, //specular intensity 32 //specular power ); auto pointLightHandle = lights.addPointLight( glm::vec3(1.0f, 0.5f, 0.0f), //color glm::vec3(0.0f, 0.0f, 8.0f), //position 0.1f, //ambient intensity 0.5f, //diffuse intensity 1.0f, //specular intensity 32, //specular power 1.0f, //attenuation constant 0.1f, //attenuation linear 0.0f //attenuation exponential ); lights.setLights( basicPassthroughMaterial.getDirectionalLightUniforms(), basicPassthroughMaterial.getPointLightUniforms(), basicPassthroughMaterial.getCameraPositionUniformAttribute() ); basicPassthroughMaterial.unbind(); //Load the texture for our basic pyramid object std::vector<uint8_t> rawImageData; bool loadedImageFile = Utilities::File::getFileContents(rawImageData, "../test.png"); if (!loadedImageFile) { std::cout << "Failed to load the texture image"; return EXIT_FAILURE; } Texture pyramidTexture; pyramidTexture.load(GL_TEXTURE_2D, rawImageData, TextureFormat::PNG); pyramidTexture.setTextureParams( GL_REPEAT, GL_REPEAT, GL_LINEAR, GL_LINEAR, false ); pyramidTexture.bind(GL_TEXTURE0); auto pointLightBase = lights.getLightByID(pointLightHandle); auto pointLight = static_cast<PointLight*>(pointLightBase); while (userRequestedExit == false) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) { userRequestedExit = true; } } playerControls.update(); playerCamera->update(playerControls); //Quick hack for ambient light controls if (playerControls.isKeyPressed(ControlKeys::AmbientLightUp)) { lights.getLightByID(directionalLightHandle)->ambientIntensity += 0.05f; } if (playerControls.isKeyPressed(ControlKeys::AmbientLightDown)) { lights.getLightByID(directionalLightHandle)->ambientIntensity -= 0.05f; } scale += 0.002f; //Spin & move the dummy pyriamid rotationMatrix = glm::rotate(rotationMatrix, (float)(2 * Utilities::Math::PI * (2.0/360)), glm::vec3(0, 1, 0)); translationMatrix = glm::translate(glm::mat4(), glm::vec3(sinf(scale * 2), 0, -3)); // worldMatrix = translationMatrix * rotationMatrix * scaleMatrix; //Move the point light back and forth float lightMoveIncrement = .1; if (pointLight->position.x > 15 || pointLight->position.x < -15) { pointLight->position.x = -15; } pointLight->position.x += lightMoveIncrement; viewMatrix = playerCamera->getViewMatrix(); WVPMatrix = perspectiveProjection * viewMatrix * worldMatrix; basicPassthroughMaterial.bind(); lights.setLights( basicPassthroughMaterial.getDirectionalLightUniforms(), basicPassthroughMaterial.getPointLightUniforms(), basicPassthroughMaterial.getCameraPositionUniformAttribute() ); glUniformMatrix4fv(WVPMatrixHandle, 1, GL_FALSE, &WVPMatrix[0][0]); glUniformMatrix4fv(worldMatrixHandle, 1, GL_FALSE, &worldMatrix[0][0]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0); basicPassthroughMaterial.unbind(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); SDL_GL_SwapWindow(renderWindow.getRenderWindowHandle()); } //Shutdown SDL2 before exiting the program renderWindow.freeResources(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 9:10:42 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } using Info = tuple<int, int>; int main() { int N; cin >> N; vector<int> A(N), B(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { cin >> B[i]; } vector<Info> V(N); for (auto i = 0; i < N; i++) { V[i] = Info(B[i], A[i]); } sort(A.begin(), A.end()); sort(B.begin(), B.end()); for (auto i = 0; i < N; i++) { if (A[i] > B[i]) { No(); } } vector<bool> C(N, true); for (auto i = 1; i < N; i++) { C[i] = (A[i] <= B[i - 1]); } vector<int> sum(N, 0); for (auto i = 1; i < N; i++) { int t{C[i] ? 0 : 1}; sum[i] = sum[i - 1] + t; } for (auto k = 0; k < N; k++) { int x{get<1>(V[k])}; int y{get<0>(V[k])}; if (x > y) { continue; } auto it_a{upper_bound(A.begin(), A.end(), x)}; --it_a; assert(*it_a == x); auto it_b{lower_bound(B.begin(), B.end(), y)}; assert(*it_b == y); int num_a(it_a - A.begin()); int num_b(it_b - B.begin()); if (num_b <= num_a) { Yes(); } else { bool ok{true}; for (auto i = num_a + 1; i <= num_b; i++) { if (!C[i]) { ok = false; break; } } if (ok) { Yes(); } } } assert(false); No(); }<commit_msg>submit C.cpp to 'C - Swaps' (nikkei2019-2-qual) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 9:10:42 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; // constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } int main() { int N; cin >> N; vector<int> A(N), B(N); for (auto i = 0; i < N; i++) { cin >> A[i]; } for (auto i = 0; i < N; i++) { cin >> B[i]; } vector<int> old_A{A}, old_B{B}; sort(A.begin(), A.end()); sort(B.begin(), B.end()); for (auto i = 0; i < N; i++) { if (A[i] > B[i]) { No(); } } vector<bool> C(N, true); for (auto i = 1; i < N; i++) { C[i] = (A[i] <= B[i - 1]); } for (auto k = 0; k < N; k++) { int x{old_A[k]}; int y{old_B[k]}; if (x > y) { continue; } auto it_a{upper_bound(A.begin(), A.end(), x)}; --it_a; assert(*it_a == x); auto it_b{lower_bound(B.begin(), B.end(), y)}; assert(*it_b == y); int num_a(it_a - A.begin()); int num_b(it_b - B.begin()); if (num_b <= num_a) { Yes(); } else { bool ok{true}; for (auto i = num_a + 1; i <= num_b; i++) { if (!C[i]) { ok = false; break; } } if (ok) { Yes(); } } } for (auto i = 0; i < N; i++) { if (old_A[i] == A[i]) { Yes(); } } vector<int> V(N, -1); for (auto i = 0; i < N; i++) { auto it{lower_bound(A.begin(), A.end(), old_A[i])}; int num(it - A.begin()); V[num] = i; } for (auto i = 0; i < N; i++) { if (V[i] == -1) { Yes(); } } vector<bool> used(N, false); int now{0}; int cnt{0}; while (cnt < N) { if (used[now]) { Yes(); } used[now] = true; cnt++; now = V[now]; } No(); }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 10:48:55 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } template <typename T> class SegTree { // 0-indexed, [0, N). private: int N; vector<T> dat; T unit; // モノイドの単位元 T(*func) // モノイドの演算 (T, T); T(*_update) // update で値をどうするか書く (T, T); public: SegTree() {} SegTree(int n, T unit, T (*func)(T, T), T (*_update)(T, T)) : N{1}, unit{unit}, func{func}, _update{_update} { while (N < n) { N *= 2; } dat = vector<T>(2 * N - 1, unit); } void update(int k, T a) { k += N - 1; dat[k] = _update(dat[k], a); while (k > 0) { k = (k - 1) / 2; dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]); } } private: T find(int a, int b, int k, int l, int r) { if (r <= a || b <= l) { return unit; } if (a <= l && r <= b) { return dat[k]; } T vl = find(a, b, k * 2 + 1, l, (l + r) / 2); T vr = find(a, b, k * 2 + 2, (l + r) / 2, r); return func(vl, vr); } public: T find(int a, int b) { // [a, b) の find をする。 return find(a, b, 0, 0, N); } }; using Info = tuple<int, int, ll>; int main() { int N, M; cin >> N >> M; vector<Info> I(M); for (auto i = 0; i < M; i++) { int l, r; ll c; cin >> l >> r >> c; l--; r--; I[i] = Info(l, r, c); } sort(I.begin(), I.end()); auto func = [](auto x, auto y) { return min(x, y); }; auto _update = [](auto x, auto y) { return min(x, y); }; constexpr ll unit{1LL << 60}; SegTree<ll> tree{N, unit, func, _update}; tree.update(0, 0); int now{0}; for (auto i = 0; i < M; i++) { int l, r; ll c; tie(l, r, c) = I[i]; if (now < l) { No(); } ch_max(now, r); } if (now < N - 1) { No(); } for (auto i = 0; i < M; i++) { int l, r; ll c; tie(l, r, c) = I[i]; ll mini{tree.find(0, l + 1)}; tree.update(r, mini + c); } cout << tree.find(N - 1, N) << endl; }<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 11/9/2019, 10:48:55 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } using ll = long long; constexpr ll MOD{1000000007LL}; constexpr ll MAX_SIZE{3000010LL}; template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // for C++14 using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // constexpr double epsilon = 1e-10; constexpr ll infty = 1000000000000000LL; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "-1" << endl; exit(0); } template <typename T> class SegTree { // 0-indexed, [0, N). private: int N; vector<T> dat; T unit; // モノイドの単位元 T(*func) // モノイドの演算 (T, T); T(*_update) // update で値をどうするか書く (T, T); public: SegTree() {} SegTree(int n, T unit, T (*func)(T, T), T (*_update)(T, T)) : N{1}, unit{unit}, func{func}, _update{_update} { while (N < n) { N *= 2; } dat = vector<T>(2 * N - 1, unit); } void update(int k, T a) { k += N - 1; dat[k] = _update(dat[k], a); while (k > 0) { k = (k - 1) / 2; dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]); } } private: T find(int a, int b, int k, int l, int r) { if (r <= a || b <= l) { return unit; } if (a <= l && r <= b) { return dat[k]; } T vl = find(a, b, k * 2 + 1, l, (l + r) / 2); T vr = find(a, b, k * 2 + 2, (l + r) / 2, r); return func(vl, vr); } public: T find(int a, int b) { // [a, b) の find をする。 return find(a, b, 0, 0, N); } }; using Info = tuple<int, int, ll>; int main() { int N, M; cin >> N >> M; vector<Info> I(M); for (auto i = 0; i < M; i++) { int l, r; ll c; cin >> l >> r >> c; l--; r--; I[i] = Info(l, r, c); } sort(I.begin(), I.end()); auto func = [](auto x, auto y) { return min(x, y); }; auto _update = [](auto x, auto y) { return min(x, y); }; constexpr ll unit{1LL << 60}; SegTree<ll> tree{N, unit, func, _update}; tree.update(0, 0); int now{0}; for (auto i = 0; i < M; i++) { int l, r; ll c; tie(l, r, c) = I[i]; if (now < l) { No(); } ch_max(now, r); } if (now < N - 1) { No(); } for (auto i = 0; i < M; i++) { int l, r; ll c; tie(l, r, c) = I[i]; #if DEBUG == 1 cerr << "l = " << l << ", r = " << r << ", c = " << c << endl; #endif ll mini{tree.find(0, l + 1)}; tree.update(r, mini + c); } cout << tree.find(N - 1, N) << endl; }<|endoftext|>
<commit_before>/* Why ? : To learn minimax algo To Do: 1) Menu ? 2) Minimax algo for perfect game A.I */ #include <iostream> #include <cstring> using namespace std; int board[10]; int win_combos[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 }, { 1, 5, 9 }, { 3, 5, 7 } }; int player; int mv_cnt; void init(); void draw(); void two_player(); bool running(); int main( int argc, char **argv ) { // if( argv[0][0] == '2' ) { // two_player(); // } two_player(); return 0; } void init() { memset( board, 0, sizeof board ); player = 1; mv_cnt = 9; } void draw() { for( int i=1; i<=9; i++ ) { if( board[i] ) { cout << "XO"[ board[i]-1 ] << "\n|"[ i % 3 != 0 ]; } else { cout << i << "\n|"[ i % 3 != 0 ]; } if( i == 3 or i == 6 ) { cout << string( 5, '-' ) << "\n"; } } cout << "\n"; } bool running() { if( !mv_cnt ) { return false; } for( int i=0; i<8; i++ ) { if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ] and board[ win_combos[i][1] ] == board[ win_combos[i][2] ] and board[ win_combos[i][2] ] != 0 ) { return false; } } return true; } string determine() { if( !mv_cnt ) { return "Tie!"; } for( int i=0; i<8; i++ ) { if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ] and board[ win_combos[i][1] ] == board[ win_combos[i][2] ] ) { if( board[ win_combos[i][2] ] == 1 ) { return "Player 1 Wins!"; } else { return "Player 2 Wins!"; } } } return "Not Complete!"; } void two_player() { int inp; bool invalid = false; init(); draw(); while( running() ) { while( inp < 1 or inp > 9 or board[inp] ) { if( invalid ) { cout << "Please Enter A Valid Input\n"; } cout << "Player " << player << " input: "; cin >> inp; invalid = true; cout << "\n"; } invalid = false; board[inp] = player; --mv_cnt; draw(); player = player == 1 ? 2 : 1 ; } cout << determine() << "\n"; } <commit_msg>Added Menu, single-player and perfect A.I( minimax )<commit_after>/* Author: Araf Al-Jami Last Edited: 21/05/16 */ #include <iostream> #include <cstring> using namespace std; int board[10]; int win_combos[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 }, { 1, 5, 9 }, { 3, 5, 7 } }; int mv_cnt; void init(); void draw(); void single_player( int player ); void two_player(); bool running(); int minimax( int player ); void player_move( int player ); void computer_move( int player ); int main( int argc, char **argv ) { int inp; bool invalid = false; do { if( invalid ) { cout << "Please Enter A Valid Input\n"; } cout << "Enter 1 for single player or 2 for Two Player: "; cin >> inp; invalid = true; cout << "\n"; } while( inp < 1 or inp > 2 ); if( inp == 1 ) { invalid = false; do { if( invalid ) { cout << "Please Enter A Valid Input\n"; } cout << "Enter 1 If You Want To Be The First Player\n"; cout << "Else Enter 2: "; cin >> inp; cout << "\n"; } while( inp < 1 or inp > 2 ); single_player( inp ); } else { two_player(); } return 0; } void init() { memset( board, 0, sizeof board ); mv_cnt = 9; } void draw() { for( int i=1; i<=9; i++ ) { if( board[i] ) { cout << "XO"[ board[i]-1 ] << "\n|"[ i % 3 != 0 ]; } else { cout << i << "\n|"[ i % 3 != 0 ]; } if( i == 3 or i == 6 ) { cout << string( 5, '-' ) << "\n"; } } cout << "\n"; } bool running() { if( !mv_cnt ) { return false; } for( int i=0; i<8; i++ ) { if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ] and board[ win_combos[i][1] ] == board[ win_combos[i][2] ] and board[ win_combos[i][2] ] != 0 ) { return false; } } return true; } string determine( int game_type, int player ) { if( !mv_cnt ) { return "Tie!"; } for( int i=0; i<8; i++ ) { if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ] and board[ win_combos[i][1] ] == board[ win_combos[i][2] ] and board[ win_combos[i][2] ] != 0 ) { if( board[ win_combos[i][2] ] == 1 ) { if( game_type == 1 ) { return player == 1 ? "You Win!" : "You lose!"; } else { return "Player 1 Wins!"; } } else { if( game_type == 1 ) { return player == 2 ? "You Win!" : "You lose!"; } else { return "Player 2 Wins!"; } } } } return "Not Complete!"; } void two_player() { int inp = 0; int player = 1; bool invalid = false; init(); draw(); while( running() ) { do { if( invalid ) { cout << "Please Enter A Valid Input\n"; } cout << "Player " << player << " input: "; cin >> inp; invalid = true; cout << "\n"; } while( inp < 1 or inp > 9 or board[inp] ); invalid = false; board[inp] = player; --mv_cnt; draw(); player = player == 1 ? 2 : 1 ; } cout << determine( 2, 0 ) << "\n"; } void single_player( int player ) { init(); draw(); while( running() ) { if( mv_cnt & 1 ) { player == 1 ? player_move( player ) : computer_move( player ); } else { player == 2 ? player_move( player ) : computer_move( player ); } --mv_cnt; draw(); } cout << determine( 1, player ) << "\n"; } void player_move( int player ) { int inp = 0; bool invalid = false; do { if( invalid ) { cout << "Please Enter A Valid Input\n"; } cout << "Player " << player << " input: "; cin >> inp; invalid = true; cout << "\n"; } while( inp < 1 or inp > 9 or board[inp] ); board[inp] = player; } void computer_move( int player ) { int cmp = player == 1 ? 2 : 1; int move = -1; int best = -11; int temp; for( int i=1; i<=9; i++ ) { if( board[i] == 0 ) { board[i] = cmp; --mv_cnt; temp = -minimax( player ); board[i] = 0; ++mv_cnt; if( temp > best ) { best = temp; move = i; } } } board[move] = cmp; } int score( int player ) { int enemy = player == 1 ? 2 : 1; for( int i=0; i<8; i++ ) { if( board[ win_combos[i][0] ] == board[ win_combos[i][1] ] and board[ win_combos[i][1] ] == board[ win_combos[i][2] ] ) { if( board[ win_combos[i][2] ] == player ) { return 10; } else if( board[ win_combos[i][2] ] == enemy ) { return -10; } } } return 0; } int minimax( int player ) { if( !running() ) { return score( player ); } int enemy = player == 1 ? 2 : 1; int move = -1; int best = -11; int temp; for( int i=1; i<=9; i++ ) { if( board[i] == 0 ) { board[i] = player; --mv_cnt; temp = -minimax( enemy ); board[i] = 0; ++mv_cnt; if( temp > best ) { best = temp; move = i; } } } if( move == -1 ) { return 0; } return best; }<|endoftext|>
<commit_before>/***************************************************************************** * Copyright © 2011-2012 VideoLAN * $Id$ * * Authors: Ludovic Fauvet <etix@l0cal.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "timetooltip.hpp" #include <QApplication> #include <QPainter> #include <QPainterPath> #include <QBitmap> #include <QFontMetrics> #include <QDesktopWidget> #define TIP_HEIGHT 5 TimeTooltip::TimeTooltip( QWidget *parent ) : QWidget( parent ) { setWindowFlags( Qt::Window | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint #if HAS_QT5 | Qt::WindowDoesNotAcceptFocus #endif ); // Tell Qt that it doesn't need to erase the background before // a paintEvent occurs. This should save some CPU cycles. setAttribute( Qt::WA_OpaquePaintEvent ); #if defined( Q_OS_WIN ) || defined( Q_OS_OS2 ) /* - This attribute is required on Windows and OS/2 to avoid focus stealing of other windows. - When set on Linux the TimeTooltip appears behind the FSController in fullscreen. */ setAttribute( Qt::WA_ShowWithoutActivating ); #endif // Inherit from the system default font size -5 mFont = QFont( "Verdana", qMax( qApp->font().pointSize() - 5, 7 ) ); mTipX = -1; // By default the widget is unintialized and should not be displayed resize( 0, 0 ); } void TimeTooltip::adjustPosition() { if( mDisplayedText.isEmpty() ) { resize( 0, 0 ); return; } // Get the bounding box required to print the text and add some padding QFontMetrics metrics( mFont ); QRect textbox = metrics.boundingRect( mDisplayedText ); textbox.adjust( -2, -2, 2, 2 ); textbox.moveTo( 0, 0 ); // Resize the widget to fit our needs QSize size( textbox.width() + 1, textbox.height() + TIP_HEIGHT + 1 ); // The desired label position is just above the target QPoint position( mTarget.x() - size.width() / 2, mTarget.y() - size.height() + TIP_HEIGHT / 2 ); // Keep the tooltip on the same screen if possible QRect screen = QApplication::desktop()->screenGeometry( mTarget ); position.setX( qMax( screen.left(), qMin( position.x(), screen.left() + screen.width() - size.width() ) ) ); position.setY( qMax( screen.top(), qMin( position.y(), screen.top() + screen.height() - size.height() ) ) ); move( position ); int tipX = mTarget.x() - position.x(); if( mBox != textbox || mTipX != tipX ) { mBox = textbox; mTipX = tipX; resize( size ); buildPath(); setMask( mMask ); } } void TimeTooltip::buildPath() { // Prepare the painter path for future use so // we only have to generate the text at runtime. // Draw the text box mPainterPath = QPainterPath(); mPainterPath.addRect( mBox ); // Draw the tip QPolygon polygon; polygon << QPoint( qMax( 0, mTipX - 3 ), mBox.height() ) << QPoint( mTipX, mBox.height() + TIP_HEIGHT ) << QPoint( qMin( mTipX + 3, mBox.width() ), mBox.height() ); mPainterPath.addPolygon( polygon ); // Store the simplified version of the path mPainterPath = mPainterPath.simplified(); // Create the mask used to erase the background // Note: this is a binary bitmap (black & white) mMask = QBitmap( size() ); QPainter painter( &mMask ); painter.fillRect( mMask.rect(), Qt::white ); painter.setPen( Qt::black ); painter.setBrush( Qt::black ); painter.drawPath( mPainterPath ); painter.end(); } void TimeTooltip::setTip( const QPoint& target, const QString& time, const QString& text ) { mDisplayedText = time; if ( !text.isEmpty() ) mDisplayedText.append( " - " ).append( text ); if( mTarget != target || time.length() != mTime.length() || mText != text ) { mTarget = target; mTime = time; mText = text; adjustPosition(); } update(); raise(); } void TimeTooltip::show() { setVisible( true ); raise(); } void TimeTooltip::paintEvent( QPaintEvent * ) { QPainter p( this ); p.setRenderHints( QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing ); p.setPen( Qt::black ); p.setBrush( qApp->palette().base() ); p.drawPath( mPainterPath ); p.setFont( mFont ); p.setPen( QPen( qApp->palette().text(), 1 ) ); p.drawText( mBox, Qt::AlignCenter, mDisplayedText ); } <commit_msg>Qt: Avoid focus stealing of the tooltip on Win32<commit_after>/***************************************************************************** * Copyright © 2011-2012 VideoLAN * $Id$ * * Authors: Ludovic Fauvet <etix@l0cal.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "timetooltip.hpp" #include <QApplication> #include <QPainter> #include <QPainterPath> #include <QBitmap> #include <QFontMetrics> #include <QDesktopWidget> #define TIP_HEIGHT 5 TimeTooltip::TimeTooltip( QWidget *parent ) : QWidget( parent ) { setWindowFlags( #if defined( Q_OS_WIN ) Qt::ToolTip #else Qt::Window | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint #endif ); // Tell Qt that it doesn't need to erase the background before // a paintEvent occurs. This should save some CPU cycles. setAttribute( Qt::WA_OpaquePaintEvent ); #if defined( Q_OS_WIN ) || defined( Q_OS_OS2 ) /* - This attribute is required on Windows and OS/2 to avoid focus stealing of other windows. - When set on Linux the TimeTooltip appears behind the FSController in fullscreen. */ setAttribute( Qt::WA_ShowWithoutActivating ); #endif // Inherit from the system default font size -5 mFont = QFont( "Verdana", qMax( qApp->font().pointSize() - 5, 7 ) ); mTipX = -1; // By default the widget is unintialized and should not be displayed resize( 0, 0 ); } void TimeTooltip::adjustPosition() { if( mDisplayedText.isEmpty() ) { resize( 0, 0 ); return; } // Get the bounding box required to print the text and add some padding QFontMetrics metrics( mFont ); QRect textbox = metrics.boundingRect( mDisplayedText ); textbox.adjust( -2, -2, 2, 2 ); textbox.moveTo( 0, 0 ); // Resize the widget to fit our needs QSize size( textbox.width() + 1, textbox.height() + TIP_HEIGHT + 1 ); // The desired label position is just above the target QPoint position( mTarget.x() - size.width() / 2, mTarget.y() - size.height() + TIP_HEIGHT / 2 ); // Keep the tooltip on the same screen if possible QRect screen = QApplication::desktop()->screenGeometry( mTarget ); position.setX( qMax( screen.left(), qMin( position.x(), screen.left() + screen.width() - size.width() ) ) ); position.setY( qMax( screen.top(), qMin( position.y(), screen.top() + screen.height() - size.height() ) ) ); move( position ); int tipX = mTarget.x() - position.x(); if( mBox != textbox || mTipX != tipX ) { mBox = textbox; mTipX = tipX; resize( size ); buildPath(); setMask( mMask ); } } void TimeTooltip::buildPath() { // Prepare the painter path for future use so // we only have to generate the text at runtime. // Draw the text box mPainterPath = QPainterPath(); mPainterPath.addRect( mBox ); // Draw the tip QPolygon polygon; polygon << QPoint( qMax( 0, mTipX - 3 ), mBox.height() ) << QPoint( mTipX, mBox.height() + TIP_HEIGHT ) << QPoint( qMin( mTipX + 3, mBox.width() ), mBox.height() ); mPainterPath.addPolygon( polygon ); // Store the simplified version of the path mPainterPath = mPainterPath.simplified(); // Create the mask used to erase the background // Note: this is a binary bitmap (black & white) mMask = QBitmap( size() ); QPainter painter( &mMask ); painter.fillRect( mMask.rect(), Qt::white ); painter.setPen( Qt::black ); painter.setBrush( Qt::black ); painter.drawPath( mPainterPath ); painter.end(); } void TimeTooltip::setTip( const QPoint& target, const QString& time, const QString& text ) { mDisplayedText = time; if ( !text.isEmpty() ) mDisplayedText.append( " - " ).append( text ); if( mTarget != target || time.length() != mTime.length() || mText != text ) { mTarget = target; mTime = time; mText = text; adjustPosition(); } update(); raise(); } void TimeTooltip::show() { setVisible( true ); raise(); } void TimeTooltip::paintEvent( QPaintEvent * ) { QPainter p( this ); p.setRenderHints( QPainter::HighQualityAntialiasing | QPainter::TextAntialiasing ); p.setPen( Qt::black ); p.setBrush( qApp->palette().base() ); p.drawPath( mPainterPath ); p.setFont( mFont ); p.setPen( QPen( qApp->palette().text(), 1 ) ); p.drawText( mBox, Qt::AlignCenter, mDisplayedText ); } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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 name of the copyright holders 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "ffmpeg_codecs.hpp" #include "opencv2/highgui/highgui.hpp" #ifdef HAVE_FFMPEG using namespace cv; using namespace std; class CV_FFmpegWriteBigVideoTest : public cvtest::BaseTest { public: void run(int) { const int img_r = 4096; const int img_c = 4096; Size frame_s = Size(img_c, img_r); const double fps = 30; const double time_sec = 2; const int coeff = static_cast<int>(static_cast<double>(cv::min(img_c, img_r)) / (fps * time_sec)); const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]); for (size_t j = 0; j < n; ++j) { stringstream s; s << codec_bmp_tags[j].tag; Mat img(img_r, img_c, CV_8UC3, Scalar::all(0)); try { VideoWriter writer(string(ts->get_data_path()) + "video/output_"+s.str()+".avi", codec_bmp_tags[j].tag, fps, frame_s); if (writer.isOpened() == false) ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); for (int i = 0 ; i < static_cast<int>(fps * time_sec); i++ ) { //circle(img, Point2i(img_c / 2, img_r / 2), cv::min(img_r, img_c) / 2 * (i + 1), Scalar(255, 0, 0, 0), 2); rectangle(img, Point2i(coeff * i, coeff * i), Point2i(coeff * (i + 1), coeff * (i + 1)), Scalar::all(255 * (1.0 - static_cast<double>(i) / (fps * time_sec * 2) )), -1); writer << img; } } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } } }; TEST(Highgui_FFmpeg_WriteBigVideo, regression) { CV_FFmpegWriteBigVideoTest test; test.safe_run(); } #endif <commit_msg>Fixed compilation error under Windows<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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 name of the copyright holders 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/highgui/highgui.hpp" #ifdef HAVE_FFMPEG #include "ffmpeg_codecs.hpp" using namespace cv; using namespace std; class CV_FFmpegWriteBigVideoTest : public cvtest::BaseTest { public: void run(int) { const int img_r = 4096; const int img_c = 4096; Size frame_s = Size(img_c, img_r); const double fps = 30; const double time_sec = 2; const int coeff = static_cast<int>(static_cast<double>(cv::min(img_c, img_r)) / (fps * time_sec)); const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]); for (size_t j = 0; j < n; ++j) { stringstream s; s << codec_bmp_tags[j].tag; Mat img(img_r, img_c, CV_8UC3, Scalar::all(0)); try { VideoWriter writer(string(ts->get_data_path()) + "video/output_"+s.str()+".avi", codec_bmp_tags[j].tag, fps, frame_s); if (writer.isOpened() == false) ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); for (int i = 0 ; i < static_cast<int>(fps * time_sec); i++ ) { //circle(img, Point2i(img_c / 2, img_r / 2), cv::min(img_r, img_c) / 2 * (i + 1), Scalar(255, 0, 0, 0), 2); rectangle(img, Point2i(coeff * i, coeff * i), Point2i(coeff * (i + 1), coeff * (i + 1)), Scalar::all(255 * (1.0 - static_cast<double>(i) / (fps * time_sec * 2) )), -1); writer << img; } } catch(...) { ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION); } ts->set_failed_test_info(cvtest::TS::OK); } } }; TEST(Highgui_FFmpeg_WriteBigVideo, regression) { CV_FFmpegWriteBigVideoTest test; test.safe_run(); } #endif <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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 name of the copyright holders 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/highgui/highgui.hpp" #ifdef HAVE_FFMPEG #include "ffmpeg_codecs.hpp" using namespace cv; using namespace std; class CV_FFmpegWriteBigVideoTest : public cvtest::BaseTest { public: void run(int) { const int img_r = 4096; const int img_c = 4096; const double fps0 = 15; const double time_sec = 1; const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]); bool created = false; for (size_t j = 0; j < n; ++j) { stringstream s; s << codec_bmp_tags[j].tag; int tag = codec_bmp_tags[j].tag; if( tag != MKTAG('H', '2', '6', '3') && tag != MKTAG('H', '2', '6', '1') && //tag != MKTAG('D', 'I', 'V', 'X') && tag != MKTAG('D', 'X', '5', '0') && tag != MKTAG('X', 'V', 'I', 'D') && tag != MKTAG('m', 'p', '4', 'v') && //tag != MKTAG('D', 'I', 'V', '3') && //tag != MKTAG('W', 'M', 'V', '1') && //tag != MKTAG('W', 'M', 'V', '2') && tag != MKTAG('M', 'P', 'E', 'G') && tag != MKTAG('M', 'J', 'P', 'G') && //tag != MKTAG('j', 'p', 'e', 'g') && tag != 0 && tag != MKTAG('I', '4', '2', '0') && //tag != MKTAG('Y', 'U', 'Y', '2') && tag != MKTAG('F', 'L', 'V', '1') ) continue; const string filename = "output_"+s.str()+".avi"; try { double fps = fps0; Size frame_s = Size(img_c, img_r); if( tag == CV_FOURCC('H', '2', '6', '1') ) frame_s = Size(352, 288); else if( tag == CV_FOURCC('H', '2', '6', '3') ) frame_s = Size(704, 576); /*else if( tag == CV_FOURCC('M', 'J', 'P', 'G') || tag == CV_FOURCC('j', 'p', 'e', 'g') ) frame_s = Size(1920, 1080);*/ if( tag == CV_FOURCC('M', 'P', 'E', 'G') ) fps = 25; VideoWriter writer(filename, tag, fps, frame_s); if (writer.isOpened() == false) { ts->printf(ts->LOG, "\n\nFile name: %s\n", filename.c_str()); ts->printf(ts->LOG, "Codec id: %d Codec tag: %c%c%c%c\n", j, tag & 255, (tag >> 8) & 255, (tag >> 16) & 255, (tag >> 24) & 255); ts->printf(ts->LOG, "Error: cannot create video file."); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); } else { Mat img(frame_s, CV_8UC3, Scalar::all(0)); const int coeff = cvRound(cv::min(frame_s.width, frame_s.height)/(fps0 * time_sec)); for (int i = 0 ; i < static_cast<int>(fps * time_sec); i++ ) { //circle(img, Point2i(img_c / 2, img_r / 2), cv::min(img_r, img_c) / 2 * (i + 1), Scalar(255, 0, 0, 0), 2); rectangle(img, Point2i(coeff * i, coeff * i), Point2i(coeff * (i + 1), coeff * (i + 1)), Scalar::all(255 * (1.0 - static_cast<double>(i) / (fps * time_sec * 2) )), -1); writer << img; } if (!created) created = true; else remove(filename.c_str()); } } catch(...) { ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); } ts->set_failed_test_info(cvtest::TS::OK); } } }; TEST(Highgui_Video, ffmpeg_writebig) { CV_FFmpegWriteBigVideoTest test; test.safe_run(); } #endif <commit_msg>added test to check #1737<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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 name of the copyright holders 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 Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/highgui/highgui.hpp" #ifdef HAVE_FFMPEG #include "ffmpeg_codecs.hpp" using namespace cv; using namespace std; class CV_FFmpegWriteBigVideoTest : public cvtest::BaseTest { public: void run(int) { const int img_r = 4096; const int img_c = 4096; const double fps0 = 15; const double time_sec = 1; const size_t n = sizeof(codec_bmp_tags)/sizeof(codec_bmp_tags[0]); bool created = false; for (size_t j = 0; j < n; ++j) { stringstream s; s << codec_bmp_tags[j].tag; int tag = codec_bmp_tags[j].tag; if( tag != MKTAG('H', '2', '6', '3') && tag != MKTAG('H', '2', '6', '1') && //tag != MKTAG('D', 'I', 'V', 'X') && tag != MKTAG('D', 'X', '5', '0') && tag != MKTAG('X', 'V', 'I', 'D') && tag != MKTAG('m', 'p', '4', 'v') && //tag != MKTAG('D', 'I', 'V', '3') && //tag != MKTAG('W', 'M', 'V', '1') && //tag != MKTAG('W', 'M', 'V', '2') && tag != MKTAG('M', 'P', 'E', 'G') && tag != MKTAG('M', 'J', 'P', 'G') && //tag != MKTAG('j', 'p', 'e', 'g') && tag != 0 && tag != MKTAG('I', '4', '2', '0') && //tag != MKTAG('Y', 'U', 'Y', '2') && tag != MKTAG('F', 'L', 'V', '1') ) continue; const string filename = "output_"+s.str()+".avi"; try { double fps = fps0; Size frame_s = Size(img_c, img_r); if( tag == CV_FOURCC('H', '2', '6', '1') ) frame_s = Size(352, 288); else if( tag == CV_FOURCC('H', '2', '6', '3') ) frame_s = Size(704, 576); /*else if( tag == CV_FOURCC('M', 'J', 'P', 'G') || tag == CV_FOURCC('j', 'p', 'e', 'g') ) frame_s = Size(1920, 1080);*/ if( tag == CV_FOURCC('M', 'P', 'E', 'G') ) fps = 25; VideoWriter writer(filename, tag, fps, frame_s); if (writer.isOpened() == false) { ts->printf(ts->LOG, "\n\nFile name: %s\n", filename.c_str()); ts->printf(ts->LOG, "Codec id: %d Codec tag: %c%c%c%c\n", j, tag & 255, (tag >> 8) & 255, (tag >> 16) & 255, (tag >> 24) & 255); ts->printf(ts->LOG, "Error: cannot create video file."); ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); } else { Mat img(frame_s, CV_8UC3, Scalar::all(0)); const int coeff = cvRound(cv::min(frame_s.width, frame_s.height)/(fps0 * time_sec)); for (int i = 0 ; i < static_cast<int>(fps * time_sec); i++ ) { //circle(img, Point2i(img_c / 2, img_r / 2), cv::min(img_r, img_c) / 2 * (i + 1), Scalar(255, 0, 0, 0), 2); rectangle(img, Point2i(coeff * i, coeff * i), Point2i(coeff * (i + 1), coeff * (i + 1)), Scalar::all(255 * (1.0 - static_cast<double>(i) / (fps * time_sec * 2) )), -1); writer << img; } if (!created) created = true; else remove(filename.c_str()); } } catch(...) { ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); } ts->set_failed_test_info(cvtest::TS::OK); } } }; TEST(Highgui_Video, ffmpeg_writebig) { CV_FFmpegWriteBigVideoTest test; test.safe_run(); } class CV_FFmpegReadImageTest : public cvtest::BaseTest { public: void run(int) { try { string filename = ts->get_data_path() + "../cv/features2d/tsukuba.png"; VideoCapture cap(filename); Mat img0 = imread(filename, 1); Mat img, img_next; cap >> img; cap >> img_next; CV_Assert( !img0.empty() && !img.empty() && img_next.empty() ); double diff = norm(img0, img, CV_C); CV_Assert( diff == 0 ); } catch(...) { ts->set_failed_test_info(ts->FAIL_INVALID_OUTPUT); } ts->set_failed_test_info(cvtest::TS::OK); } }; TEST(Highgui_Video, ffmpeg_image) { CV_FFmpegReadImageTest test; test.safe_run(); } #endif <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ #define _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ #include <boost/fusion/include/mpl.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/fusion/container/vector/convert.hpp> #include <boost/fusion/include/as_vector.hpp> #include <boost/fusion/include/as_list.hpp> #include <boost/fusion/algorithm/transformation/transform.hpp> #include <boost/fusion/include/transform.hpp> #include <boost/fusion/functional/invocation/invoke_function_object.hpp> #include <boost/fusion/container/generation/make_vector.hpp> #include <boost/fusion/include/make_vector.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> #include <boost/fusion/functional/adapter/unfused.hpp> #include <boost/fusion/functional/generation/make_unfused.hpp> #include <boost/fusion/functional/generation/make_fused.hpp> #include <qimessaging/genericvalue.hpp> namespace qi { inline Type* FunctionType::resultType() { return _resultType; } inline const std::vector<Type*>& FunctionType::argumentsType() { return _argumentsType; } namespace detail { struct PtrToConstRef { // Drop the const, it prevents method calls from working template <typename Sig> struct result; template <class Self, typename T> struct result< Self(T) > { typedef typename boost::add_reference< //typename boost::add_const< typename boost::remove_pointer< typename boost::remove_reference<T>::type >::type // >::type >::type type; }; template<typename T> T& operator() (T* ptr) const { return *ptr; } }; struct fill_arguments { inline fill_arguments(std::vector<Type*>* target) : target(target) {} template<typename T> void operator()(T*) const { target->push_back(typeOf<typename boost::remove_const<typename boost::remove_reference<T>::type>::type>()); } std::vector<Type*>* target; }; struct Transformer { public: inline Transformer(const std::vector<void*>* args) : args(args) , pos(0) {} template <typename Sig> struct result; template <class Self, typename T> struct result< Self(T) > { typedef T type; }; template<typename T> void operator() (T* &v) const { v = (T*)(*args)[pos++]; } const std::vector<void*> *args; mutable unsigned int pos; }; template<typename SEQ, typename F> void* apply(SEQ sequence, F& function, const std::vector<void*> args) { GenericValueCopy res; boost::fusion::for_each(sequence, Transformer(&args)); res(), boost::fusion::invoke_function_object(function, boost::fusion::transform(sequence, PtrToConstRef())); return res.value; } } // namespace detail template<typename T> class FunctionTypeImpl: public virtual FunctionType, public virtual TypeImpl<boost::function<T> > { public: FunctionTypeImpl() { _resultType = typeOf<typename boost::function_types::result_type<T>::type >(); typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > >(detail::fill_arguments(&_argumentsType)); } virtual void* call(void* func, const std::vector<void*>& args) { boost::function<T>* f = (boost::function<T>*)func; typedef typename boost::function_types::parameter_types<T>::type ArgsType; typedef typename boost::mpl::transform_view<ArgsType, boost::remove_const< boost::remove_reference<boost::mpl::_1> > >::type BareArgsType; typedef typename boost::mpl::transform_view<BareArgsType, boost::add_pointer<boost::mpl::_1> >::type PtrArgsType; return detail::apply(boost::fusion::as_vector(PtrArgsType()), *f, args); } }; template<typename T> FunctionType* makeFunctionType() { static FunctionTypeImpl<T> result; return &result; } template<typename T> GenericFunction makeGenericFunction(boost::function<T> f) { GenericFunction res; res.value = new boost::function<T>(f); res.type = makeFunctionType<T>(); return res; } template<typename F> GenericFunction makeGenericFunction(F func) { return makeGenericFunction(boost::function< typename boost::remove_pointer<F>::type>(func)); } namespace detail { /* Call a boost::function<F> binding the first argument. * Can't be done just with boost::bind without code generation. */ template<typename F> struct FusedBindOne { template <class Seq> struct result { typedef typename boost::function_types::result_type<F>::type type; }; template <class Seq> typename result<Seq>::type operator()(Seq const & s) const { return ::boost::fusion::invoke_function_object(func, ::boost::fusion::push_front(s, boost::ref(const_cast<ArgType&>(*arg1)))); } ::boost::function<F> func; typedef typename boost::remove_reference< typename ::boost::mpl::front< typename ::boost::function_types::parameter_types<F>::type >::type>::type ArgType; void setArg(ArgType* val) { arg1 = val;} ArgType* arg1; }; } template<typename C, typename F> GenericFunction makeGenericFunction(C* inst, F func) { // Return type typedef typename ::boost::function_types::result_type<F>::type RetType; // All arguments including class pointer typedef typename ::boost::function_types::parameter_types<F>::type MemArgsType; // Pop class pointer typedef typename ::boost::mpl::pop_front< MemArgsType >::type ArgsType; // Synthethise exposed function type typedef typename ::boost::mpl::push_front<ArgsType, RetType>::type ResultMPLType; typedef typename ::boost::function_types::function_type<ResultMPLType>::type ResultType; // Synthethise non-member function equivalent type of F typedef typename ::boost::mpl::push_front<MemArgsType, RetType>::type MemMPLType; typedef typename ::boost::function_types::function_type<MemMPLType>::type LinearizedType; // See func as R (C*, OTHER_ARGS) boost::function<LinearizedType> memberFunction = func; boost::function<ResultType> res; // Create the fusor detail::FusedBindOne<LinearizedType> fusor; // Bind member function and instance fusor.setArg(inst); fusor.func = memberFunction; // Convert it to a boost::function res = boost::fusion::make_unfused(fusor); return makeGenericFunction(res); } } // namespace qi #endif // _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ <commit_msg>FunctionType: drop constness in const ptr argument type.<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ #define _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ #include <boost/fusion/include/mpl.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/transform_view.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/function_types/function_type.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/fusion/container/vector/convert.hpp> #include <boost/fusion/include/as_vector.hpp> #include <boost/fusion/include/as_list.hpp> #include <boost/fusion/algorithm/transformation/transform.hpp> #include <boost/fusion/include/transform.hpp> #include <boost/fusion/functional/invocation/invoke_function_object.hpp> #include <boost/fusion/container/generation/make_vector.hpp> #include <boost/fusion/include/make_vector.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> #include <boost/fusion/functional/adapter/unfused.hpp> #include <boost/fusion/functional/generation/make_unfused.hpp> #include <boost/fusion/functional/generation/make_fused.hpp> #include <qimessaging/genericvalue.hpp> namespace qi { inline Type* FunctionType::resultType() { return _resultType; } inline const std::vector<Type*>& FunctionType::argumentsType() { return _argumentsType; } namespace detail { struct PtrToConstRef { // Drop the const, it prevents method calls from working template <typename Sig> struct result; template <class Self, typename T> struct result< Self(T) > { typedef typename boost::add_reference< //typename boost::add_const< typename boost::remove_pointer< typename boost::remove_reference<T>::type >::type // >::type >::type type; }; template<typename T> T& operator() (T* ptr) const { return *ptr; } }; template<typename T> struct remove_constptr { typedef T type; }; template<typename T> struct remove_constptr<const T*> { typedef T* type; }; struct fill_arguments { inline fill_arguments(std::vector<Type*>* target) : target(target) {} template<typename T> void operator()(T*) const { target->push_back(typeOf< typename remove_constptr< typename boost::remove_const< typename boost::remove_reference<T>::type >::type>::type>()); } std::vector<Type*>* target; }; struct Transformer { public: inline Transformer(const std::vector<void*>* args) : args(args) , pos(0) {} template <typename Sig> struct result; template <class Self, typename T> struct result< Self(T) > { typedef T type; }; template<typename T> void operator() (T* &v) const { v = (T*)(*args)[pos++]; } const std::vector<void*> *args; mutable unsigned int pos; }; template<typename SEQ, typename F> void* apply(SEQ sequence, F& function, const std::vector<void*> args) { GenericValueCopy res; boost::fusion::for_each(sequence, Transformer(&args)); res(), boost::fusion::invoke_function_object(function, boost::fusion::transform(sequence, PtrToConstRef())); return res.value; } } // namespace detail template<typename T> class FunctionTypeImpl: public virtual FunctionType, public virtual TypeImpl<boost::function<T> > { public: FunctionTypeImpl() { _resultType = typeOf<typename boost::function_types::result_type<T>::type >(); typedef typename boost::function_types::parameter_types<T>::type ArgsType; boost::mpl::for_each< boost::mpl::transform_view<ArgsType, boost::add_pointer< boost::remove_const< boost::remove_reference<boost::mpl::_1> > > > >(detail::fill_arguments(&_argumentsType)); } virtual void* call(void* func, const std::vector<void*>& args) { boost::function<T>* f = (boost::function<T>*)func; typedef typename boost::function_types::parameter_types<T>::type ArgsType; typedef typename boost::mpl::transform_view<ArgsType, boost::remove_const< boost::remove_reference<boost::mpl::_1> > >::type BareArgsType; typedef typename boost::mpl::transform_view<BareArgsType, boost::add_pointer<boost::mpl::_1> >::type PtrArgsType; return detail::apply(boost::fusion::as_vector(PtrArgsType()), *f, args); } }; template<typename T> FunctionType* makeFunctionType() { static FunctionTypeImpl<T> result; return &result; } template<typename T> GenericFunction makeGenericFunction(boost::function<T> f) { GenericFunction res; res.value = new boost::function<T>(f); res.type = makeFunctionType<T>(); return res; } template<typename F> GenericFunction makeGenericFunction(F func) { return makeGenericFunction(boost::function< typename boost::remove_pointer<F>::type>(func)); } namespace detail { /* Call a boost::function<F> binding the first argument. * Can't be done just with boost::bind without code generation. */ template<typename F> struct FusedBindOne { template <class Seq> struct result { typedef typename boost::function_types::result_type<F>::type type; }; template <class Seq> typename result<Seq>::type operator()(Seq const & s) const { return ::boost::fusion::invoke_function_object(func, ::boost::fusion::push_front(s, boost::ref(const_cast<ArgType&>(*arg1)))); } ::boost::function<F> func; typedef typename boost::remove_reference< typename ::boost::mpl::front< typename ::boost::function_types::parameter_types<F>::type >::type>::type ArgType; void setArg(ArgType* val) { arg1 = val;} ArgType* arg1; }; } template<typename C, typename F> GenericFunction makeGenericFunction(C* inst, F func) { // Return type typedef typename ::boost::function_types::result_type<F>::type RetType; // All arguments including class pointer typedef typename ::boost::function_types::parameter_types<F>::type MemArgsType; // Pop class pointer typedef typename ::boost::mpl::pop_front< MemArgsType >::type ArgsType; // Synthethise exposed function type typedef typename ::boost::mpl::push_front<ArgsType, RetType>::type ResultMPLType; typedef typename ::boost::function_types::function_type<ResultMPLType>::type ResultType; // Synthethise non-member function equivalent type of F typedef typename ::boost::mpl::push_front<MemArgsType, RetType>::type MemMPLType; typedef typename ::boost::function_types::function_type<MemMPLType>::type LinearizedType; // See func as R (C*, OTHER_ARGS) boost::function<LinearizedType> memberFunction = func; boost::function<ResultType> res; // Create the fusor detail::FusedBindOne<LinearizedType> fusor; // Bind member function and instance fusor.setArg(inst); fusor.func = memberFunction; // Convert it to a boost::function res = boost::fusion::make_unfused(fusor); return makeGenericFunction(res); } } // namespace qi #endif // _QIMESSAGING_DETAILS_FUNCTIONTYPE_HXX_ <|endoftext|>
<commit_before>// Copyright Toru Niina 2019. // Distributed under the MIT License. #ifndef TOML11_SERIALIZER_HPP #define TOML11_SERIALIZER_HPP #include "value.hpp" #include "lexer.hpp" #include <limits> namespace toml { struct serializer { serializer(const std::size_t w = 80, const int float_prec = std::numeric_limits<toml::floating>::max_digits10, const bool can_be_inlined = false, std::vector<toml::key> ks = {}) : can_be_inlined_(can_be_inlined), width_(w), keys_(std::move(ks)) {} ~serializer() = default; std::string operator()(const toml::boolean& b) const { return b ? "true" : "false"; } std::string operator()(const integer i) const { return std::to_string(i); } std::string operator()(const toml::floating f) const { std::string token = [=] { // every float value needs decimal point (or exponent). std::ostringstream oss; oss << std::setprecision(float_prec_) << std::showpoint << f; return oss.str(); }(); if(token.back() == '.') // 1. => 1.0 { token += '0'; } const auto e = std::find_if(token.cbegin(), token.cend(), [](const char c) -> bool { return c == 'E' || c == 'e'; }); if(e == token.cend()) { return token; // there is no exponent part. just return it. } // zero-prefix in an exponent is not allowed in TOML. // remove it if it exists. bool sign_exists = false; std::size_t zero_prefix = 0; for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter) { if(*iter == '+' || *iter == '-'){sign_exists = true; continue;} if(*iter == '0'){zero_prefix += 1;} else {break;} } if(zero_prefix != 0) { const auto offset = std::distance(token.cbegin(), e) + (sign_exists ? 2 : 1); token.erase(offset, zero_prefix); } return token; } std::string operator()(const string& s) const { if(s.kind == string_t::basic) { if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend()) { // if linefeed is contained, make it multiline-string. const std::string open("\"\"\"\n"); const std::string close("\\\n\"\"\""); return open + this->escape_ml_basic_string(s.str) + close; } // no linefeed. try to make it oneline-string. std::string oneline = this->escape_basic_string(s.str); if(oneline.size() + 2 < width_ || width_ < 2) { const std::string quote("\""); return quote + oneline + quote; } // the line is too long compared to the specified width. // split it into multiple lines. std::string token("\"\"\"\n"); while(!oneline.empty()) { if(oneline.size() < width_) { token += oneline; oneline.clear(); } else if(oneline.at(width_-2) == '\\') { token += oneline.substr(0, width_-2); token += "\\\n"; oneline.erase(0, width_-2); } else { token += oneline.substr(0, width_-1); token += "\\\n"; oneline.erase(0, width_-1); } } return token + std::string("\\\n\"\"\""); } else // the string `s` is literal-string. { if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() || std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() ) { const std::string open("'''\n"); const std::string close("'''"); return open + s.str + close; } else { const std::string quote("'"); return quote + s.str + quote; } } } std::string operator()(const local_date& d) const { std::ostringstream oss; oss << d; return oss.str(); } std::string operator()(const local_time& t) const { std::ostringstream oss; oss << t; return oss.str(); } std::string operator()(const local_datetime& dt) const { std::ostringstream oss; oss << dt; return oss.str(); } std::string operator()(const offset_datetime& odt) const { std::ostringstream oss; oss << odt; return oss.str(); } std::string operator()(const array& v) const { if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables { // if it's not inlined, we need to add `[[table.key]]`. // but if it can be inlined, we need `table.key = [...]`. if(this->can_be_inlined_) { std::string token; if(!keys_.empty()) { token += this->serialize_key(keys_.back()); token += " = "; } bool width_exceeds = false; token += "[\n"; for(const auto& item : v) { const auto t = this->make_inline_table(item.cast<value_t::Table>()); if(t.size() + 1 > width_ || // +1 for the last comma {...}, std::find(t.cbegin(), t.cend(), '\n') != t.cend()) { width_exceeds = true; break; } token += t; token += ",\n"; } if(!width_exceeds) { token += "]\n"; return token; } // if width_exceeds, serialize it as [[array.of.tables]]. } std::string token; for(const auto& item : v) { token += "[["; token += this->serialize_dotted_key(keys_); token += "]]\n"; token += this->make_multiline_table(item.cast<value_t::Table>()); } return token; } // not an array of tables. normal array. first, try to make it inline. { const auto inl = this->make_inline_array(v); if(inl.size() < this->width_ && std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend()) { return inl; } } // if the length exceeds this->width_, print multiline array std::string token; token += "[\n"; for(const auto& item : v) { token += toml::visit(*this, item); token += ",\n"; } token += "]\n"; return token; } std::string operator()(const table& v) const { if(this->can_be_inlined_) { std::string token; if(!this->keys_.empty()) { token += this->serialize_key(this->keys_.back()); token += " = "; } token += this->make_inline_table(v); if(token.size() < this->width_) { return token; } } std::string token; if(!keys_.empty()) { token += '['; token += this->serialize_dotted_key(keys_); token += "]\n"; } token += this->make_multiline_table(v); return token; } private: std::string serialize_key(const toml::key& key) const { detail::location<toml::key> loc(key, key); if(const auto unquoted = detail::lex_unquoted_key::invoke(loc)) { return key; // the key is unquoted-key } std::string token("\""); token += this->escape_basic_string(key); token += "\""; return token; } std::string serialize_dotted_key(const std::vector<toml::key>& keys) const { std::string token; if(keys.empty()){return token;} for(const auto& k : keys) { token += this->serialize_key(k); token += '.'; } token.erase(token.size() - 1, 1); // remove trailing `.` return token; } std::string escape_basic_string(const std::string& s) const { //XXX assuming `s` is a valid utf-8 sequence. std::string retval; for(const char c : s) { switch(c) { case '\\': {retval += "\\\\"; break;} case '\"': {retval += "\\\""; break;} case '\b': {retval += "\\b"; break;} case '\t': {retval += "\\t"; break;} case '\f': {retval += "\\f"; break;} case '\n': {retval += "\\n"; break;} case '\r': {retval += "\\r"; break;} default : {retval += c; break;} } } return retval; } std::string escape_ml_basic_string(const std::string& s) const { std::string retval; for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i) { switch(*i) { case '\\': {retval += "\\\\"; break;} case '\"': {retval += "\\\""; break;} case '\b': {retval += "\\b"; break;} case '\t': {retval += "\\t"; break;} case '\f': {retval += "\\f"; break;} case '\n': {retval += "\n"; break;} case '\r': { if(std::next(i) != e && *std::next(i) == '\n') { retval += "\r\n"; ++i; } else { retval += "\\r"; } break; } default: {retval += *i; break;} } } return retval; } std::string make_inline_array(const array& v) const { std::string token; token += '['; bool is_first = true; for(const auto& item : v) { if(is_first) {is_first = false;} else {token += ',';} token += visit(serializer(std::numeric_limits<std::size_t>::max(), this->float_prec_, true), item); } token += ']'; return token; } std::string make_inline_table(const table& v) const { assert(this->can_be_inlined_); std::string token; token += '{'; bool is_first = true; for(const auto& kv : v) { // in inline tables, trailing comma is not allowed (toml-lang #569). if(is_first) {is_first = false;} else {token += ',';} token += this->serialize_key(kv.first); token += '='; token += visit(serializer(std::numeric_limits<std::size_t>::max(), this->float_prec_, true), kv.second); } token += '}'; return token; } std::string make_multiline_table(const table& v) const { std::string token; // print non-table stuff first. because after printing [foo.bar], the // remaining non-table values will be assigned into [foo.bar], not [foo] for(const auto kv : v) { if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second)) { continue; } const auto key_and_sep = serialize_key(kv.first) + " = "; const auto residual_width = this->width_ - key_and_sep.size(); token += key_and_sep; token += visit(serializer(residual_width, this->float_prec_, true), kv.second); token += '\n'; } // normal tables / array of tables // after multiline table appeared, the other tables cannot be inline // because the table would be assigned into the table. // [foo] // ... // bar = {...} # <- bar will be a member of [foo]. bool multiline_table_printed = false; for(const auto& kv : v) { if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second)) { continue; // other stuff are already serialized. skip them. } std::vector<toml::key> ks(this->keys_); ks.push_back(kv.first); auto tmp = visit(serializer( this->width_, this->float_prec_, !multiline_table_printed, ks), kv.second); if((!multiline_table_printed) && std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend()) { multiline_table_printed = true; } else { // still inline tables only. tmp += '\n'; } token += tmp; } return token; } bool is_array_of_tables(const value& v) const { if(!v.is(value_t::Array)) {return false;} const auto& a = v.cast<value_t::Array>(); return !a.empty() && a.front().is(value_t::Table); } private: bool can_be_inlined_; std::size_t width_; int float_prec_; std::vector<toml::key> keys_; }; inline std::string format(const value& v, std::size_t w = 80, int fprec = std::numeric_limits<toml::floating>::max_digits10) { return visit(serializer(w, fprec, true), v); } inline std::string format(const table& t, std::size_t w = 80, int fprec = std::numeric_limits<toml::floating>::max_digits10) { return serializer(w, fprec, true)(t); } template<typename charT, typename traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const value& v) { // get status of std::setw(). if the width is narrower than 5 chars, ignore. const auto w = os.width(); const auto fprec = os.precision(); os << visit(serializer((w > 5 ? w : 80), fprec, false), v); return os; } } // toml #endif// TOML11_SERIALIZER_HPP <commit_msg>fix: correctly serialize quoted keys<commit_after>// Copyright Toru Niina 2019. // Distributed under the MIT License. #ifndef TOML11_SERIALIZER_HPP #define TOML11_SERIALIZER_HPP #include "value.hpp" #include "lexer.hpp" #include <limits> namespace toml { struct serializer { serializer(const std::size_t w = 80, const int float_prec = std::numeric_limits<toml::floating>::max_digits10, const bool can_be_inlined = false, std::vector<toml::key> ks = {}) : can_be_inlined_(can_be_inlined), width_(w), keys_(std::move(ks)) {} ~serializer() = default; std::string operator()(const toml::boolean& b) const { return b ? "true" : "false"; } std::string operator()(const integer i) const { return std::to_string(i); } std::string operator()(const toml::floating f) const { std::string token = [=] { // every float value needs decimal point (or exponent). std::ostringstream oss; oss << std::setprecision(float_prec_) << std::showpoint << f; return oss.str(); }(); if(token.back() == '.') // 1. => 1.0 { token += '0'; } const auto e = std::find_if(token.cbegin(), token.cend(), [](const char c) -> bool { return c == 'E' || c == 'e'; }); if(e == token.cend()) { return token; // there is no exponent part. just return it. } // zero-prefix in an exponent is not allowed in TOML. // remove it if it exists. bool sign_exists = false; std::size_t zero_prefix = 0; for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter) { if(*iter == '+' || *iter == '-'){sign_exists = true; continue;} if(*iter == '0'){zero_prefix += 1;} else {break;} } if(zero_prefix != 0) { const auto offset = std::distance(token.cbegin(), e) + (sign_exists ? 2 : 1); token.erase(offset, zero_prefix); } return token; } std::string operator()(const string& s) const { if(s.kind == string_t::basic) { if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend()) { // if linefeed is contained, make it multiline-string. const std::string open("\"\"\"\n"); const std::string close("\\\n\"\"\""); return open + this->escape_ml_basic_string(s.str) + close; } // no linefeed. try to make it oneline-string. std::string oneline = this->escape_basic_string(s.str); if(oneline.size() + 2 < width_ || width_ < 2) { const std::string quote("\""); return quote + oneline + quote; } // the line is too long compared to the specified width. // split it into multiple lines. std::string token("\"\"\"\n"); while(!oneline.empty()) { if(oneline.size() < width_) { token += oneline; oneline.clear(); } else if(oneline.at(width_-2) == '\\') { token += oneline.substr(0, width_-2); token += "\\\n"; oneline.erase(0, width_-2); } else { token += oneline.substr(0, width_-1); token += "\\\n"; oneline.erase(0, width_-1); } } return token + std::string("\\\n\"\"\""); } else // the string `s` is literal-string. { if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() || std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() ) { const std::string open("'''\n"); const std::string close("'''"); return open + s.str + close; } else { const std::string quote("'"); return quote + s.str + quote; } } } std::string operator()(const local_date& d) const { std::ostringstream oss; oss << d; return oss.str(); } std::string operator()(const local_time& t) const { std::ostringstream oss; oss << t; return oss.str(); } std::string operator()(const local_datetime& dt) const { std::ostringstream oss; oss << dt; return oss.str(); } std::string operator()(const offset_datetime& odt) const { std::ostringstream oss; oss << odt; return oss.str(); } std::string operator()(const array& v) const { if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables { // if it's not inlined, we need to add `[[table.key]]`. // but if it can be inlined, we need `table.key = [...]`. if(this->can_be_inlined_) { std::string token; if(!keys_.empty()) { token += this->serialize_key(keys_.back()); token += " = "; } bool width_exceeds = false; token += "[\n"; for(const auto& item : v) { const auto t = this->make_inline_table(item.cast<value_t::Table>()); if(t.size() + 1 > width_ || // +1 for the last comma {...}, std::find(t.cbegin(), t.cend(), '\n') != t.cend()) { width_exceeds = true; break; } token += t; token += ",\n"; } if(!width_exceeds) { token += "]\n"; return token; } // if width_exceeds, serialize it as [[array.of.tables]]. } std::string token; for(const auto& item : v) { token += "[["; token += this->serialize_dotted_key(keys_); token += "]]\n"; token += this->make_multiline_table(item.cast<value_t::Table>()); } return token; } // not an array of tables. normal array. first, try to make it inline. { const auto inl = this->make_inline_array(v); if(inl.size() < this->width_ && std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend()) { return inl; } } // if the length exceeds this->width_, print multiline array std::string token; token += "[\n"; for(const auto& item : v) { token += toml::visit(*this, item); token += ",\n"; } token += "]\n"; return token; } std::string operator()(const table& v) const { if(this->can_be_inlined_) { std::string token; if(!this->keys_.empty()) { token += this->serialize_key(this->keys_.back()); token += " = "; } token += this->make_inline_table(v); if(token.size() < this->width_) { return token; } } std::string token; if(!keys_.empty()) { token += '['; token += this->serialize_dotted_key(keys_); token += "]\n"; } token += this->make_multiline_table(v); return token; } private: std::string serialize_key(const toml::key& key) const { detail::location<toml::key> loc(key, key); detail::lex_unquoted_key::invoke(loc); if(loc.iter() == loc.end()) { return key; // all the tokens are consumed. the key is unquoted-key. } std::string token("\""); token += this->escape_basic_string(key); token += "\""; return token; } std::string serialize_dotted_key(const std::vector<toml::key>& keys) const { std::string token; if(keys.empty()){return token;} for(const auto& k : keys) { token += this->serialize_key(k); token += '.'; } token.erase(token.size() - 1, 1); // remove trailing `.` return token; } std::string escape_basic_string(const std::string& s) const { //XXX assuming `s` is a valid utf-8 sequence. std::string retval; for(const char c : s) { switch(c) { case '\\': {retval += "\\\\"; break;} case '\"': {retval += "\\\""; break;} case '\b': {retval += "\\b"; break;} case '\t': {retval += "\\t"; break;} case '\f': {retval += "\\f"; break;} case '\n': {retval += "\\n"; break;} case '\r': {retval += "\\r"; break;} default : {retval += c; break;} } } return retval; } std::string escape_ml_basic_string(const std::string& s) const { std::string retval; for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i) { switch(*i) { case '\\': {retval += "\\\\"; break;} case '\"': {retval += "\\\""; break;} case '\b': {retval += "\\b"; break;} case '\t': {retval += "\\t"; break;} case '\f': {retval += "\\f"; break;} case '\n': {retval += "\n"; break;} case '\r': { if(std::next(i) != e && *std::next(i) == '\n') { retval += "\r\n"; ++i; } else { retval += "\\r"; } break; } default: {retval += *i; break;} } } return retval; } std::string make_inline_array(const array& v) const { std::string token; token += '['; bool is_first = true; for(const auto& item : v) { if(is_first) {is_first = false;} else {token += ',';} token += visit(serializer(std::numeric_limits<std::size_t>::max(), this->float_prec_, true), item); } token += ']'; return token; } std::string make_inline_table(const table& v) const { assert(this->can_be_inlined_); std::string token; token += '{'; bool is_first = true; for(const auto& kv : v) { // in inline tables, trailing comma is not allowed (toml-lang #569). if(is_first) {is_first = false;} else {token += ',';} token += this->serialize_key(kv.first); token += '='; token += visit(serializer(std::numeric_limits<std::size_t>::max(), this->float_prec_, true), kv.second); } token += '}'; return token; } std::string make_multiline_table(const table& v) const { std::string token; // print non-table stuff first. because after printing [foo.bar], the // remaining non-table values will be assigned into [foo.bar], not [foo] for(const auto kv : v) { if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second)) { continue; } const auto key_and_sep = this->serialize_key(kv.first) + " = "; const auto residual_width = this->width_ - key_and_sep.size(); token += key_and_sep; token += visit(serializer(residual_width, this->float_prec_, true), kv.second); token += '\n'; } // normal tables / array of tables // after multiline table appeared, the other tables cannot be inline // because the table would be assigned into the table. // [foo] // ... // bar = {...} # <- bar will be a member of [foo]. bool multiline_table_printed = false; for(const auto& kv : v) { if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second)) { continue; // other stuff are already serialized. skip them. } std::vector<toml::key> ks(this->keys_); ks.push_back(kv.first); auto tmp = visit(serializer( this->width_, this->float_prec_, !multiline_table_printed, ks), kv.second); if((!multiline_table_printed) && std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend()) { multiline_table_printed = true; } else { // still inline tables only. tmp += '\n'; } token += tmp; } return token; } bool is_array_of_tables(const value& v) const { if(!v.is(value_t::Array)) {return false;} const auto& a = v.cast<value_t::Array>(); return !a.empty() && a.front().is(value_t::Table); } private: bool can_be_inlined_; std::size_t width_; int float_prec_; std::vector<toml::key> keys_; }; inline std::string format(const value& v, std::size_t w = 80, int fprec = std::numeric_limits<toml::floating>::max_digits10) { return visit(serializer(w, fprec, true), v); } inline std::string format(const table& t, std::size_t w = 80, int fprec = std::numeric_limits<toml::floating>::max_digits10) { return serializer(w, fprec, true)(t); } template<typename charT, typename traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const value& v) { // get status of std::setw(). if the width is narrower than 5 chars, ignore. const auto w = os.width(); const auto fprec = os.precision(); os << visit(serializer((w > 5 ? w : 80), fprec, false), v); return os; } } // toml #endif// TOML11_SERIALIZER_HPP <|endoftext|>
<commit_before><commit_msg>gtktiledviewer: invoke lok::Office::postKeyEvent() on key press / release<commit_after><|endoftext|>
<commit_before><commit_msg>gtktiledviewer: Replace deprecated Gtk functions<commit_after><|endoftext|>
<commit_before><commit_msg>Planning: set planning as not-ready when reference fails to update.<commit_after><|endoftext|>
<commit_before>// Copyright 2011 Google Inc. 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 "subprocess.h" #include <stdio.h> #include <windows.h> #include <algorithm> #include "util.h" namespace { void Win32Fatal(const char* function) { DWORD err = GetLastError(); char* msg_buf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg_buf, 0, NULL); Fatal("%s: %s", function, msg_buf); LocalFree(msg_buf); } } // anonymous namespace Subprocess::Subprocess() : child_(NULL) , overlapped_() { } Subprocess::~Subprocess() { // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[32]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_%p_out", ::GetModuleHandle(NULL)); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(struct SubprocessSet* set, const string& command) { HANDLE child_pipe = SetupPipe(set->ioport_); STARTUPINFOA startup_info = {}; startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdOutput = child_pipe; // TODO: what does this hook up stdin to? startup_info.hStdInput = NULL; // TODO: is it ok to reuse pipe like this? startup_info.hStdError = child_pipe; PROCESS_INFORMATION process_info; // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, 0, NULL, NULL, &startup_info, &process_info)) { Win32Fatal("CreateProcess"); } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } bool Subprocess::Finish() { // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } SubprocessSet::SubprocessSet() { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); } SubprocessSet::~SubprocessSet() { CloseHandle(ioport_); } void SubprocessSet::Add(Subprocess* subprocess) { running_.push_back(subprocess); } void SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = std::remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } <commit_msg>subprocess-win32.cc: change named pipe names to contain process ID and subprocess object address.<commit_after>// Copyright 2011 Google Inc. 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 "subprocess.h" #include <stdio.h> #include <windows.h> #include <algorithm> #include "util.h" namespace { void Win32Fatal(const char* function) { DWORD err = GetLastError(); char* msg_buf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg_buf, 0, NULL); Fatal("%s: %s", function, msg_buf); LocalFree(msg_buf); } } // anonymous namespace Subprocess::Subprocess() : child_(NULL) , overlapped_() { } Subprocess::~Subprocess() { // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%u_sp%p", GetProcessId(GetCurrentProcess()), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(struct SubprocessSet* set, const string& command) { HANDLE child_pipe = SetupPipe(set->ioport_); STARTUPINFOA startup_info = {}; startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdOutput = child_pipe; // TODO: what does this hook up stdin to? startup_info.hStdInput = NULL; // TODO: is it ok to reuse pipe like this? startup_info.hStdError = child_pipe; PROCESS_INFORMATION process_info; // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, 0, NULL, NULL, &startup_info, &process_info)) { Win32Fatal("CreateProcess"); } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } bool Subprocess::Finish() { // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } SubprocessSet::SubprocessSet() { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); } SubprocessSet::~SubprocessSet() { CloseHandle(ioport_); } void SubprocessSet::Add(Subprocess* subprocess) { running_.push_back(subprocess); } void SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = std::remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } <|endoftext|>
<commit_before>/* * Copyright 2016 WebAssembly Community Group participants * * 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 "support/archive.h" #include <cstring> #include "support/utilities.h" static const char* const magic = "!<arch>\n"; class ArchiveMemberHeader { public: uint8_t fileName[16]; uint8_t timestamp[12]; uint8_t UID[6]; uint8_t GID[6]; uint8_t accessMode[8]; uint8_t size[10]; // Size of data only, not including padding or header uint8_t magic[2]; std::string getName() const; // Members are not larger than 4GB uint32_t getSize() const; }; std::string ArchiveMemberHeader::getName() const { char endChar; if (fileName[0] == '/') { // Special name (string table or reference, or symbol table) endChar = ' '; } else { endChar = '/'; // regular name } auto* end = static_cast<const uint8_t*>(memchr(fileName, endChar, sizeof(fileName))); if (!end) end = fileName + sizeof(fileName); return std::string((char*)(fileName), end - fileName); } uint32_t ArchiveMemberHeader::getSize() const { auto* end = static_cast<const char*>(memchr(size, ' ', sizeof(size))); std::string sizeString((const char*)size, end); auto sizeInt = std::stoll(sizeString, nullptr, 10); if (sizeInt < 0 || sizeInt >= std::numeric_limits<uint32_t>::max()) { wasm::Fatal() << "Malformed archive: size parsing failed\n"; } return static_cast<uint32_t>(sizeInt); } Archive::Archive(Buffer& b, bool& error) : data(b) { error = false; if (data.size() < strlen(magic) || memcmp(data.data(), magic, strlen(magic))) { error = true; return; } // We require GNU format archives. So the first member may be named "/" and it // points to the symbol table. The next member may optionally be "//" and // point to a string table if a filename is too large to fit in the 16-char // name field of the header. child_iterator it = child_begin(false); if (it.hasError()) { error = true; return; } child_iterator end = child_end(); if (it == end) return; // Empty archive. const Child* c = &*it; auto increment = [&]() { ++it; error = it.hasError(); if (error) return true; c = &*it; return false; }; std::string name = c->getRawName(); if (name == "/") { symbolTable = c->getBuffer(); if (increment() || it == end) return; name = c->getRawName(); } if (name == "//") { stringTable = c->getBuffer(); if (increment() || it == end) return; setFirstRegular(*c); return; } if (name[0] != '/') { setFirstRegular(*c); return; } // Not a GNU archive. error = true; } Archive::Child::Child(const Archive* parent, const uint8_t* data, bool* error) : parent(parent), data(data) { if (!data) return; len = sizeof(ArchiveMemberHeader) + getHeader()->getSize(); startOfFile = sizeof(ArchiveMemberHeader); } uint32_t Archive::Child::getSize() const { return len - startOfFile; } Archive::SubBuffer Archive::Child::getBuffer() const { return {data + startOfFile, getSize()}; } std::string Archive::Child::getRawName() const { return getHeader()->getName(); } Archive::Child Archive::Child::getNext(bool& error) const { size_t toSkip = len; // Members are aligned to even byte boundaries. if (toSkip & 1) ++toSkip; const uint8_t* nextLoc = data + toSkip; if (nextLoc >= (uint8_t*)&*parent->data.end()) { // End of the archive. return Child(); } return Child(parent, nextLoc, &error); } std::string Archive::Child::getName() const { std::string name = getRawName(); // Check if it's a special name. if (name[0] == '/') { if (name.size() == 1) { // Linker member. return name; } if (name.size() == 2 && name[1] == '/') { // String table. return name; } // It's a long name. // Get the offset. int offset = std::stoi(name.substr(1), nullptr, 10); // Verify it. if (offset < 0 || (unsigned)offset >= parent->stringTable.len) { wasm::Fatal() << "Malformed archive: name parsing failed\n"; } std::string addr(parent->stringTable.data + offset, parent->stringTable.data + parent->stringTable.len); // GNU long file names end with a "/\n". size_t end = addr.find('\n'); return addr.substr(0, end - 1); } // It's a simple name. if (name[name.size() - 1] == '/') { return name.substr(0, name.size() - 1); } return name; } Archive::child_iterator Archive::child_begin(bool SkipInternal) const { if (data.size() == 0) return child_end(); if (SkipInternal) { child_iterator it; it.child = Child(this, firstRegularData, &it.error); return it; } auto* loc = (const uint8_t*)data.data() + strlen(magic); child_iterator it; it.child = Child(this, loc, &it.error); return it; } Archive::child_iterator Archive::child_end() const { return Child(); } namespace { struct Symbol { uint32_t symbolIndex; uint32_t stringIndex; void next(Archive::SubBuffer& symbolTable) { // Symbol table entries are NUL-terminated. Skip past the next NUL. stringIndex = strchr((char*)symbolTable.data + stringIndex, '\0') - (char*)symbolTable.data + 1; ++symbolIndex; } }; } static uint32_t read32be(const uint8_t* buf) { return static_cast<uint32_t>(buf[0]) << 24 | static_cast<uint32_t>(buf[1]) << 16 | static_cast<uint32_t>(buf[2]) << 8 | static_cast<uint32_t>(buf[3]); } void Archive::dump() const { printf("Archive data %p len %lu, firstRegularData %p\n", data.data(), (long unsigned)data.size(), firstRegularData); printf("Symbol table %p, len %u\n", symbolTable.data, symbolTable.len); printf("string table %p, len %u\n", stringTable.data, stringTable.len); const uint8_t* buf = symbolTable.data; if (!buf) { for (auto c = child_begin(), e = child_end(); c != e; ++c) { printf("Child %p, len %u, name %s, size %u\n", c->data, c->len, c->getName().c_str(), c->getSize()); } return; } uint32_t symbolCount = read32be(buf); printf("Symbol count %u\n", symbolCount); buf += sizeof(uint32_t) + (symbolCount * sizeof(uint32_t)); uint32_t string_start_offset = buf - symbolTable.data; Symbol sym = {0, string_start_offset}; while (sym.symbolIndex != symbolCount) { printf("Symbol %u, offset %u\n", sym.symbolIndex, sym.stringIndex); // get the member uint32_t offset = read32be(symbolTable.data + sym.symbolIndex * 4); auto* loc = (const uint8_t*)&data[offset]; child_iterator it; it.child = Child(this, loc, &it.error); printf("Child %p, len %u\n", it.child.data, it.child.len); } } <commit_msg>make print flags in archive.cpp nicer (#437)<commit_after>/* * Copyright 2016 WebAssembly Community Group participants * * 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 "support/archive.h" #include <cstring> #include "support/utilities.h" static const char* const magic = "!<arch>\n"; class ArchiveMemberHeader { public: uint8_t fileName[16]; uint8_t timestamp[12]; uint8_t UID[6]; uint8_t GID[6]; uint8_t accessMode[8]; uint8_t size[10]; // Size of data only, not including padding or header uint8_t magic[2]; std::string getName() const; // Members are not larger than 4GB uint32_t getSize() const; }; std::string ArchiveMemberHeader::getName() const { char endChar; if (fileName[0] == '/') { // Special name (string table or reference, or symbol table) endChar = ' '; } else { endChar = '/'; // regular name } auto* end = static_cast<const uint8_t*>(memchr(fileName, endChar, sizeof(fileName))); if (!end) end = fileName + sizeof(fileName); return std::string((char*)(fileName), end - fileName); } uint32_t ArchiveMemberHeader::getSize() const { auto* end = static_cast<const char*>(memchr(size, ' ', sizeof(size))); std::string sizeString((const char*)size, end); auto sizeInt = std::stoll(sizeString, nullptr, 10); if (sizeInt < 0 || sizeInt >= std::numeric_limits<uint32_t>::max()) { wasm::Fatal() << "Malformed archive: size parsing failed\n"; } return static_cast<uint32_t>(sizeInt); } Archive::Archive(Buffer& b, bool& error) : data(b) { error = false; if (data.size() < strlen(magic) || memcmp(data.data(), magic, strlen(magic))) { error = true; return; } // We require GNU format archives. So the first member may be named "/" and it // points to the symbol table. The next member may optionally be "//" and // point to a string table if a filename is too large to fit in the 16-char // name field of the header. child_iterator it = child_begin(false); if (it.hasError()) { error = true; return; } child_iterator end = child_end(); if (it == end) return; // Empty archive. const Child* c = &*it; auto increment = [&]() { ++it; error = it.hasError(); if (error) return true; c = &*it; return false; }; std::string name = c->getRawName(); if (name == "/") { symbolTable = c->getBuffer(); if (increment() || it == end) return; name = c->getRawName(); } if (name == "//") { stringTable = c->getBuffer(); if (increment() || it == end) return; setFirstRegular(*c); return; } if (name[0] != '/') { setFirstRegular(*c); return; } // Not a GNU archive. error = true; } Archive::Child::Child(const Archive* parent, const uint8_t* data, bool* error) : parent(parent), data(data) { if (!data) return; len = sizeof(ArchiveMemberHeader) + getHeader()->getSize(); startOfFile = sizeof(ArchiveMemberHeader); } uint32_t Archive::Child::getSize() const { return len - startOfFile; } Archive::SubBuffer Archive::Child::getBuffer() const { return {data + startOfFile, getSize()}; } std::string Archive::Child::getRawName() const { return getHeader()->getName(); } Archive::Child Archive::Child::getNext(bool& error) const { size_t toSkip = len; // Members are aligned to even byte boundaries. if (toSkip & 1) ++toSkip; const uint8_t* nextLoc = data + toSkip; if (nextLoc >= (uint8_t*)&*parent->data.end()) { // End of the archive. return Child(); } return Child(parent, nextLoc, &error); } std::string Archive::Child::getName() const { std::string name = getRawName(); // Check if it's a special name. if (name[0] == '/') { if (name.size() == 1) { // Linker member. return name; } if (name.size() == 2 && name[1] == '/') { // String table. return name; } // It's a long name. // Get the offset. int offset = std::stoi(name.substr(1), nullptr, 10); // Verify it. if (offset < 0 || (unsigned)offset >= parent->stringTable.len) { wasm::Fatal() << "Malformed archive: name parsing failed\n"; } std::string addr(parent->stringTable.data + offset, parent->stringTable.data + parent->stringTable.len); // GNU long file names end with a "/\n". size_t end = addr.find('\n'); return addr.substr(0, end - 1); } // It's a simple name. if (name[name.size() - 1] == '/') { return name.substr(0, name.size() - 1); } return name; } Archive::child_iterator Archive::child_begin(bool SkipInternal) const { if (data.size() == 0) return child_end(); if (SkipInternal) { child_iterator it; it.child = Child(this, firstRegularData, &it.error); return it; } auto* loc = (const uint8_t*)data.data() + strlen(magic); child_iterator it; it.child = Child(this, loc, &it.error); return it; } Archive::child_iterator Archive::child_end() const { return Child(); } namespace { struct Symbol { uint32_t symbolIndex; uint32_t stringIndex; void next(Archive::SubBuffer& symbolTable) { // Symbol table entries are NUL-terminated. Skip past the next NUL. stringIndex = strchr((char*)symbolTable.data + stringIndex, '\0') - (char*)symbolTable.data + 1; ++symbolIndex; } }; } static uint32_t read32be(const uint8_t* buf) { return static_cast<uint32_t>(buf[0]) << 24 | static_cast<uint32_t>(buf[1]) << 16 | static_cast<uint32_t>(buf[2]) << 8 | static_cast<uint32_t>(buf[3]); } void Archive::dump() const { printf("Archive data %p len %zu, firstRegularData %p\n", data.data(), data.size(), firstRegularData); printf("Symbol table %p, len %u\n", symbolTable.data, symbolTable.len); printf("string table %p, len %u\n", stringTable.data, stringTable.len); const uint8_t* buf = symbolTable.data; if (!buf) { for (auto c = child_begin(), e = child_end(); c != e; ++c) { printf("Child %p, len %u, name %s, size %u\n", c->data, c->len, c->getName().c_str(), c->getSize()); } return; } uint32_t symbolCount = read32be(buf); printf("Symbol count %u\n", symbolCount); buf += sizeof(uint32_t) + (symbolCount * sizeof(uint32_t)); uint32_t string_start_offset = buf - symbolTable.data; Symbol sym = {0, string_start_offset}; while (sym.symbolIndex != symbolCount) { printf("Symbol %u, offset %u\n", sym.symbolIndex, sym.stringIndex); // get the member uint32_t offset = read32be(symbolTable.data + sym.symbolIndex * 4); auto* loc = (const uint8_t*)&data[offset]; child_iterator it; it.child = Child(this, loc, &it.error); printf("Child %p, len %u\n", it.child.data, it.child.len); } } <|endoftext|>
<commit_before>#include <sstream> #include "TargetWordInsertionFeature.h" #include "Phrase.h" #include "TargetPhrase.h" #include "Hypothesis.h" #include "ChartHypothesis.h" #include "ScoreComponentCollection.h" #include "TranslationOption.h" #include "UserMessage.h" namespace Moses { using namespace std; TargetWordInsertionFeature::TargetWordInsertionFeature(const std::string &line) :StatelessFeatureFunction("twi", ScoreProducer::unlimited, line), m_unrestricted(true) { std::cerr << "Initializing target word insertion feature.." << std::endl; vector<string> tokens = Tokenize(line); //CHECK(tokens[0] == m_description); // set factor m_factorType = Scan<FactorType>(tokens[1]); // load word list for restricted feature set if (tokens.size() == 3) { string filename = tokens[2]; cerr << "loading target word insertion word list from " << filename << endl; if (!Load(filename)) { UserMessage::Add("Unable to load word list for target word insertion feature from file " + filename); //return false; } } } bool TargetWordInsertionFeature::Load(const std::string &filePath) { ifstream inFile(filePath.c_str()); if (!inFile) { cerr << "could not open file " << filePath << endl; return false; } std::string line; while (getline(inFile, line)) { m_vocab.insert(line); } inFile.close(); m_unrestricted = false; return true; } void TargetWordInsertionFeature::Evaluate( const PhraseBasedFeatureContext& context, ScoreComponentCollection* accumulator) const { const TargetPhrase& targetPhrase = context.GetTargetPhrase(); const AlignmentInfo &alignmentInfo = targetPhrase.GetAlignTerm(); ComputeFeatures(targetPhrase, accumulator, alignmentInfo); } void TargetWordInsertionFeature::EvaluateChart( const ChartBasedFeatureContext& context, ScoreComponentCollection* accumulator) const { const TargetPhrase& targetPhrase = context.GetTargetPhrase(); const AlignmentInfo &alignmentInfo = context.GetTargetPhrase().GetAlignTerm(); ComputeFeatures(targetPhrase, accumulator, alignmentInfo); } void TargetWordInsertionFeature::ComputeFeatures(const TargetPhrase& targetPhrase, ScoreComponentCollection* accumulator, const AlignmentInfo &alignmentInfo) const { // handle special case: unknown words (they have no word alignment) size_t targetLength = targetPhrase.GetSize(); size_t sourceLength = targetPhrase.GetSourcePhrase().GetSize(); if (targetLength == 1 && sourceLength == 1) { const Factor* f1 = targetPhrase.GetWord(0).GetFactor(1); if (f1 && f1->GetString().compare(UNKNOWN_FACTOR) == 0) { return; } } // flag aligned words bool aligned[16]; CHECK(targetLength < 16); for(size_t i=0; i<targetLength; i++) { aligned[i] = false; } for (AlignmentInfo::const_iterator alignmentPoint = alignmentInfo.begin(); alignmentPoint != alignmentInfo.end(); alignmentPoint++) { aligned[ alignmentPoint->second ] = true; } // process unaligned target words for(size_t i=0; i<targetLength; i++) { if (!aligned[i]) { Word w = targetPhrase.GetWord(i); if (!w.IsNonTerminal()) { const string &word = w.GetFactor(m_factorType)->GetString(); if (word != "<s>" && word != "</s>") { if (!m_unrestricted && m_vocab.find( word ) == m_vocab.end()) { accumulator->PlusEquals(this,"OTHER",1); } else { accumulator->PlusEquals(this,word,1); } } } } } } } <commit_msg>use key-value args for TargetWordInsertionFeature<commit_after>#include <sstream> #include "TargetWordInsertionFeature.h" #include "Phrase.h" #include "TargetPhrase.h" #include "Hypothesis.h" #include "ChartHypothesis.h" #include "ScoreComponentCollection.h" #include "TranslationOption.h" #include "UserMessage.h" namespace Moses { using namespace std; TargetWordInsertionFeature::TargetWordInsertionFeature(const std::string &line) :StatelessFeatureFunction("twi", ScoreProducer::unlimited, line), m_unrestricted(true) { std::cerr << "Initializing target word insertion feature.." << std::endl; string filename; for (size_t i = 0; i < m_args.size(); ++i) { const vector<string> &args = m_args[i]; if (args[0] == "factor") { m_factorType = Scan<FactorType>(args[1]); } else if (args[0] == "path") { filename = args[1]; } } // load word list for restricted feature set if (filename != "") { cerr << "loading target word insertion word list from " << filename << endl; if (!Load(filename)) { UserMessage::Add("Unable to load word list for target word insertion feature from file " + filename); //return false; } } } bool TargetWordInsertionFeature::Load(const std::string &filePath) { ifstream inFile(filePath.c_str()); if (!inFile) { cerr << "could not open file " << filePath << endl; return false; } std::string line; while (getline(inFile, line)) { m_vocab.insert(line); } inFile.close(); m_unrestricted = false; return true; } void TargetWordInsertionFeature::Evaluate( const PhraseBasedFeatureContext& context, ScoreComponentCollection* accumulator) const { const TargetPhrase& targetPhrase = context.GetTargetPhrase(); const AlignmentInfo &alignmentInfo = targetPhrase.GetAlignTerm(); ComputeFeatures(targetPhrase, accumulator, alignmentInfo); } void TargetWordInsertionFeature::EvaluateChart( const ChartBasedFeatureContext& context, ScoreComponentCollection* accumulator) const { const TargetPhrase& targetPhrase = context.GetTargetPhrase(); const AlignmentInfo &alignmentInfo = context.GetTargetPhrase().GetAlignTerm(); ComputeFeatures(targetPhrase, accumulator, alignmentInfo); } void TargetWordInsertionFeature::ComputeFeatures(const TargetPhrase& targetPhrase, ScoreComponentCollection* accumulator, const AlignmentInfo &alignmentInfo) const { // handle special case: unknown words (they have no word alignment) size_t targetLength = targetPhrase.GetSize(); size_t sourceLength = targetPhrase.GetSourcePhrase().GetSize(); if (targetLength == 1 && sourceLength == 1) { const Factor* f1 = targetPhrase.GetWord(0).GetFactor(1); if (f1 && f1->GetString().compare(UNKNOWN_FACTOR) == 0) { return; } } // flag aligned words bool aligned[16]; CHECK(targetLength < 16); for(size_t i=0; i<targetLength; i++) { aligned[i] = false; } for (AlignmentInfo::const_iterator alignmentPoint = alignmentInfo.begin(); alignmentPoint != alignmentInfo.end(); alignmentPoint++) { aligned[ alignmentPoint->second ] = true; } // process unaligned target words for(size_t i=0; i<targetLength; i++) { if (!aligned[i]) { Word w = targetPhrase.GetWord(i); if (!w.IsNonTerminal()) { const string &word = w.GetFactor(m_factorType)->GetString(); if (word != "<s>" && word != "</s>") { if (!m_unrestricted && m_vocab.find( word ) == m_vocab.end()) { accumulator->PlusEquals(this,"OTHER",1); } else { accumulator->PlusEquals(this,word,1); } } } } } } } <|endoftext|>
<commit_before>/* * ArduinoNunchuk.cpp - Improved Wii Nunchuk library for Arduino * * Copyright 2011-2013 Gabriel Bianconi, http://www.gabrielbianconi.com/ * * Project URL: http://www.gabrielbianconi.com/projects/arduinonunchuk/ * * Based on the following resources: * http://www.windmeadow.com/node/42 * http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/ * http://wiibrew.org/wiki/Wiimote/Extension_Controllers * */ #include <Arduino.h> #include <Wire.h> #include "ArduinoNunchuk.h" #define ADDRESS 0x52 void ArduinoNunchuk::init() { Wire.begin(); ArduinoNunchuk::_sendByte(0x55, 0xF0); ArduinoNunchuk::_sendByte(0x00, 0xFB); ArduinoNunchuk::update(); } void ArduinoNunchuk::update() { int count = 0; int values[6]; Wire.requestFrom(ADDRESS, 6); while(Wire.available()) { values[count] = Wire.read(); count++; } ArduinoNunchuk::analogX = values[0]; ArduinoNunchuk::analogY = values[1]; ArduinoNunchuk::accelX = (values[2] << 2) | ((values[5] >> 2) & 3); ArduinoNunchuk::accelY = (values[3] << 2) | ((values[5] >> 4) & 3); ArduinoNunchuk::accelZ = (values[4] << 2) | ((values[5] >> 6) & 3); ArduinoNunchuk::zButton = !((values[5] >> 0) & 1); ArduinoNunchuk::cButton = !((values[5] >> 1) & 1); ArduinoNunchuk::_sendByte(0x00, 0x00); } void ArduinoNunchuk::_sendByte(byte data, byte location) { Wire.beginTransmission(ADDRESS); Wire.write(location); Wire.write(data); Wire.endTransmission(); delay(10); }<commit_msg>Tweak for spark<commit_after>/* * ArduinoNunchuk.cpp - Improved Wii Nunchuk library for Arduino * * Copyright 2011-2013 Gabriel Bianconi, http://www.gabrielbianconi.com/ * * Project URL: http://www.gabrielbianconi.com/projects/arduinonunchuk/ * * Based on the following resources: * http://www.windmeadow.com/node/42 * http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/ * http://wiibrew.org/wiki/Wiimote/Extension_Controllers * */ #include "ArduinoNunchuk.h" #define ADDRESS 0x52 void ArduinoNunchuk::init() { Wire.begin(); ArduinoNunchuk::_sendByte(0x55, 0xF0); ArduinoNunchuk::_sendByte(0x00, 0xFB); ArduinoNunchuk::update(); } void ArduinoNunchuk::update() { int count = 0; int values[6]; Wire.requestFrom(ADDRESS, 6); while(Wire.available()) { values[count] = Wire.read(); count++; } ArduinoNunchuk::analogX = values[0]; ArduinoNunchuk::analogY = values[1]; ArduinoNunchuk::accelX = (values[2] << 2) | ((values[5] >> 2) & 3); ArduinoNunchuk::accelY = (values[3] << 2) | ((values[5] >> 4) & 3); ArduinoNunchuk::accelZ = (values[4] << 2) | ((values[5] >> 6) & 3); ArduinoNunchuk::zButton = !((values[5] >> 0) & 1); ArduinoNunchuk::cButton = !((values[5] >> 1) & 1); ArduinoNunchuk::_sendByte(0x00, 0x00); } void ArduinoNunchuk::_sendByte(byte data, byte location) { Wire.beginTransmission(ADDRESS); Wire.write(location); Wire.write(data); Wire.endTransmission(); delay(10); } <|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "CoreContext.h" #include "Autowired.h" #include "BoltBase.h" #include "CoreThread.h" #include "GlobalCoreContext.h" #include "OutstandingCountTracker.h" #include "ThreadStatusMaintainer.h" #include <algorithm> #include <memory> using namespace boost; thread_specific_ptr<std::shared_ptr<CoreContext> > CoreContext::s_curContext; CoreContext::CoreContext(std::shared_ptr<CoreContext> pParent): Autowirer(std::static_pointer_cast<Autowirer, CoreContext>(pParent)), m_shouldStop(true), m_refCount(0) { ASSERT(pParent.get() != this); } CoreContext::~CoreContext(void) { // The s_curContext pointer holds a shared_ptr to this--if we're in a dtor, and our caller // still holds a reference to us, then we have a serious problem. ASSERT( !s_curContext.get() || !s_curContext.get()->use_count() || s_curContext.get()->get() != this ); } void CoreContext::BroadcastContextCreationNotice(const char* contextName, const std::shared_ptr<CoreContext>& context) const { auto nameIter = m_nameListeners.find(contextName); if(nameIter != m_nameListeners.end()) { // Context creation notice requires that the created context be set before invocation: CurrentContextPusher pshr(context); // Iterate through all listeners: const std::list<BoltBase*>& list = nameIter->second; for(auto q = list.begin(); q != list.end(); q++) (**q).ContextCreated(); } // Pass the broadcast to all listening children: for(auto q = m_children.begin(); q != m_children.end(); q++) { std::shared_ptr<CoreContext> child = q->lock(); if(child) child->BroadcastContextCreationNotice(contextName, context); } } std::shared_ptr<OutstandingCountTracker> CoreContext::IncrementOutstandingThreadCount(void) { std::shared_ptr<OutstandingCountTracker> retVal = m_outstanding.lock(); if(!m_outstanding.expired()) return retVal; boost::lock_guard<boost::mutex> lk(m_outstandingLock); retVal.reset( new OutstandingCountTracker( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ) ); m_outstanding = retVal; return retVal; } std::shared_ptr<CoreContext> CoreContext::Create(void) { // Lock my child list lock_guard<mutex> lk(m_childrenLock); // Create the context CoreContext* pContext = new CoreContext( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ); // Reserve a place in the list for the child t_childList::iterator childIterator = m_children.insert(m_children.end(), std::weak_ptr<CoreContext>()); // Create the shared pointer for the context--do not add the context to itself, // this creates a dangerous cyclic reference. std::shared_ptr<CoreContext> retVal( pContext, [this, childIterator] (CoreContext* pContext) { lock_guard<mutex> lk(m_childrenLock); this->m_children.erase(childIterator); delete pContext; } ); pContext->m_self = retVal; *childIterator = retVal; return retVal; } void CoreContext::InitiateCoreThreads(void) { // Self-reference to ensure the context is not destroyed until all threads are gone std::shared_ptr<CoreContext> self = std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()); // Because the caller was able to invoke a method on this CoreContext, it must have // a shared_ptr to it. Thus, we can assert that the above lock operation succeeded. ASSERT(self); { lock_guard<mutex> lk(m_coreLock); if(m_refCount++) // Already running return; } if(m_pParent) // Start parent threads first // Parent MUST be a core context std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->InitiateCoreThreads(); // Set our stop flag before kicking off any threads: m_shouldStop = false; // Hold another lock to prevent m_threads from being modified while we sit on it lock_guard<mutex> lk(m_coreLock); for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); ++q) (*q)->Start(); } void CoreContext::SignalShutdown(void) { lock_guard<mutex> lk(m_coreLock); if(m_refCount == 0 || --m_refCount) // Someone else still depends on this return; // Global context is now "stop": m_shouldStop = true; m_stopping.notify_all(); // Also pass notice to all child threads: for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); ++q) (*q)->Stop(); // Pass notice to the parent. This is required because we use reference counts to decide // when to shut down, and it makes no sense to keep a parent context running when we were // the ones who got it going in the first place. if(m_pParent) std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->SignalShutdown(); } void CoreContext::SignalTerminate(void) { // We're stopping now. m_shouldStop = true; { // Tear down all the children. lock_guard<mutex> lk(m_childrenLock); for (t_childList::iterator it = m_children.begin(); it != m_children.end(); ++it) { std::shared_ptr<CoreContext> ptr = it->lock(); if(ptr) { ptr->SignalTerminate(); } } } // Shutmyself down. SignalShutdown(); // I shouldn't be referenced anywhere now. ASSERT(m_refCount == 0); // Wait for the treads to finish before returning. for (t_threadList::iterator it = m_threads.begin(); it != m_threads.end(); ++it) { (*it)->Wait(); } } std::shared_ptr<CoreContext> CoreContext::CurrentContext(void) { if(!s_curContext.get()) return std::static_pointer_cast<CoreContext, GlobalCoreContext>(GetGlobalContext()); std::shared_ptr<CoreContext>* retVal = s_curContext.get(); ASSERT(retVal); ASSERT(*retVal); return *retVal; } void CoreContext::AddCoreThread(CoreThread* ptr, bool allowNotReady) { // We don't allow the insertion of a thread that isn't ready unless the user really // wants that behavior. ASSERT(allowNotReady || ptr->IsReady()); // Insert into the linked list of threads first: lock_guard<mutex> lk(m_coreLock); m_threads.push_front(ptr); if(!m_shouldStop) // We're already running, this means we're late to the game and need to start _now_. ptr->Start(); } void CoreContext::AddBolt(BoltBase* pBase) { m_nameListeners[pBase->GetContextName()].push_back(pBase); } std::shared_ptr<CoreContext> GetCurrentContext() { return CoreContext::CurrentContext(); } void CoreContext::Dump(std::ostream& os) const { Autowirer::Dump(os); boost::lock_guard<boost::mutex> lk(m_lock); for(auto q = m_threads.begin(); q != m_threads.end(); q++) { CoreThread* pThread = *q; const char* name = pThread->GetName(); os << "Thread " << pThread << " " << (name ? name : "(no name)") << std::endl; } } std::ostream& operator<<(std::ostream& os, const CoreContext& context) { context.Dump(os); return os; } <commit_msg>Resolving deadlock caused by a lock being held too long<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "CoreContext.h" #include "Autowired.h" #include "BoltBase.h" #include "CoreThread.h" #include "GlobalCoreContext.h" #include "OutstandingCountTracker.h" #include "ThreadStatusMaintainer.h" #include <algorithm> #include <memory> using namespace boost; thread_specific_ptr<std::shared_ptr<CoreContext> > CoreContext::s_curContext; CoreContext::CoreContext(std::shared_ptr<CoreContext> pParent): Autowirer(std::static_pointer_cast<Autowirer, CoreContext>(pParent)), m_shouldStop(true), m_refCount(0) { ASSERT(pParent.get() != this); } CoreContext::~CoreContext(void) { // The s_curContext pointer holds a shared_ptr to this--if we're in a dtor, and our caller // still holds a reference to us, then we have a serious problem. ASSERT( !s_curContext.get() || !s_curContext.get()->use_count() || s_curContext.get()->get() != this ); } void CoreContext::BroadcastContextCreationNotice(const char* contextName, const std::shared_ptr<CoreContext>& context) const { auto nameIter = m_nameListeners.find(contextName); if(nameIter != m_nameListeners.end()) { // Context creation notice requires that the created context be set before invocation: CurrentContextPusher pshr(context); // Iterate through all listeners: const std::list<BoltBase*>& list = nameIter->second; for(auto q = list.begin(); q != list.end(); q++) (**q).ContextCreated(); } // Pass the broadcast to all listening children: for(auto q = m_children.begin(); q != m_children.end(); q++) { std::shared_ptr<CoreContext> child = q->lock(); if(child) child->BroadcastContextCreationNotice(contextName, context); } } std::shared_ptr<OutstandingCountTracker> CoreContext::IncrementOutstandingThreadCount(void) { std::shared_ptr<OutstandingCountTracker> retVal = m_outstanding.lock(); if(!m_outstanding.expired()) return retVal; boost::lock_guard<boost::mutex> lk(m_outstandingLock); retVal.reset( new OutstandingCountTracker( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ) ); m_outstanding = retVal; return retVal; } std::shared_ptr<CoreContext> CoreContext::Create(void) { t_childList::iterator childIterator; { // Lock the child list while we insert lock_guard<mutex> lk(m_childrenLock); // Reserve a place in the list for the child childIterator = m_children.insert(m_children.end(), std::weak_ptr<CoreContext>()); } // Create the child context CoreContext* pContext = new CoreContext( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ); // Create the shared pointer for the context--do not add the context to itself, // this creates a dangerous cyclic reference. std::shared_ptr<CoreContext> retVal( pContext, [this, childIterator] (CoreContext* pContext) { lock_guard<mutex> lk(m_childrenLock); this->m_children.erase(childIterator); delete pContext; } ); pContext->m_self = retVal; *childIterator = retVal; return retVal; } void CoreContext::InitiateCoreThreads(void) { // Self-reference to ensure the context is not destroyed until all threads are gone std::shared_ptr<CoreContext> self = std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()); // Because the caller was able to invoke a method on this CoreContext, it must have // a shared_ptr to it. Thus, we can assert that the above lock operation succeeded. ASSERT(self); { lock_guard<mutex> lk(m_coreLock); if(m_refCount++) // Already running return; } if(m_pParent) // Start parent threads first // Parent MUST be a core context std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->InitiateCoreThreads(); // Set our stop flag before kicking off any threads: m_shouldStop = false; // Hold another lock to prevent m_threads from being modified while we sit on it lock_guard<mutex> lk(m_coreLock); for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); ++q) (*q)->Start(); } void CoreContext::SignalShutdown(void) { lock_guard<mutex> lk(m_coreLock); if(m_refCount == 0 || --m_refCount) // Someone else still depends on this return; // Global context is now "stop": m_shouldStop = true; m_stopping.notify_all(); // Also pass notice to all child threads: for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); ++q) (*q)->Stop(); // Pass notice to the parent. This is required because we use reference counts to decide // when to shut down, and it makes no sense to keep a parent context running when we were // the ones who got it going in the first place. if(m_pParent) std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->SignalShutdown(); } void CoreContext::SignalTerminate(void) { // We're stopping now. m_shouldStop = true; { // Tear down all the children. lock_guard<mutex> lk(m_childrenLock); for (t_childList::iterator it = m_children.begin(); it != m_children.end(); ++it) { std::shared_ptr<CoreContext> ptr = it->lock(); if(ptr) { ptr->SignalTerminate(); } } } // Shutmyself down. SignalShutdown(); // I shouldn't be referenced anywhere now. ASSERT(m_refCount == 0); // Wait for the treads to finish before returning. for (t_threadList::iterator it = m_threads.begin(); it != m_threads.end(); ++it) { (*it)->Wait(); } } std::shared_ptr<CoreContext> CoreContext::CurrentContext(void) { if(!s_curContext.get()) return std::static_pointer_cast<CoreContext, GlobalCoreContext>(GetGlobalContext()); std::shared_ptr<CoreContext>* retVal = s_curContext.get(); ASSERT(retVal); ASSERT(*retVal); return *retVal; } void CoreContext::AddCoreThread(CoreThread* ptr, bool allowNotReady) { // We don't allow the insertion of a thread that isn't ready unless the user really // wants that behavior. ASSERT(allowNotReady || ptr->IsReady()); // Insert into the linked list of threads first: lock_guard<mutex> lk(m_coreLock); m_threads.push_front(ptr); if(!m_shouldStop) // We're already running, this means we're late to the game and need to start _now_. ptr->Start(); } void CoreContext::AddBolt(BoltBase* pBase) { m_nameListeners[pBase->GetContextName()].push_back(pBase); } std::shared_ptr<CoreContext> GetCurrentContext() { return CoreContext::CurrentContext(); } void CoreContext::Dump(std::ostream& os) const { Autowirer::Dump(os); boost::lock_guard<boost::mutex> lk(m_lock); for(auto q = m_threads.begin(); q != m_threads.end(); q++) { CoreThread* pThread = *q; const char* name = pThread->GetName(); os << "Thread " << pThread << " " << (name ? name : "(no name)") << std::endl; } } std::ostream& operator<<(std::ostream& os, const CoreContext& context) { context.Dump(os); return os; } <|endoftext|>
<commit_before>/* * opencog/atomspace/ImportanceIndex.cc * * Copyright (C) 2008-2011 OpenCog Foundation * All Rights Reserved * * 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 <algorithm> #include <opencog/util/functional.h> #include <opencog/atomspace/ImportanceIndex.h> #include <opencog/atoms/base/Atom.h> #include <opencog/atomspace/AtomTable.h> #include <boost/range/adaptor/reversed.hpp> using namespace opencog; //! Each bin has STI range of 32 means 2048 importance bins. #define IMPORTANCE_INDEX_BIN_SIZE 32 #define IMPORTANCE_INDEX_SIZE 2048 ImportanceIndex::ImportanceIndex(void) { resize(IMPORTANCE_INDEX_SIZE); } unsigned int ImportanceIndex::importanceBin(short importance) { // STI is in range of [-32768, 32767] so adding 32768 puts it in // [0, 65535] unsigned int bin = (importance + 32768) / IMPORTANCE_INDEX_BIN_SIZE; assert (bin < IMPORTANCE_INDEX_SIZE); return bin; } void ImportanceIndex::updateImportance(Atom* atom, int bin) { int newbin = importanceBin(atom->getAttentionValue()->getSTI()); if (bin == newbin) return; remove(bin, atom); insert(newbin, atom); } void ImportanceIndex::insertAtom(Atom* atom) { int sti = atom->getAttentionValue()->getSTI(); int bin = importanceBin(sti); insert(bin, atom); } void ImportanceIndex::removeAtom(Atom* atom) { int sti = atom->getAttentionValue()->getSTI(); int bin = importanceBin(sti); remove(bin, atom); } UnorderedHandleSet ImportanceIndex::getHandleSet( AttentionValue::sti_t lowerBound, AttentionValue::sti_t upperBound) const { AtomSet set; // The indexes for the lower bound and upper bound lists is returned. int lowerBin = importanceBin(lowerBound); int upperBin = importanceBin(upperBound); // Build a list of atoms whose importance is equal to the lower bound. // For the lower bound and upper bound index, the list is filtered, // because there may be atoms that have the same importanceIndex // and whose importance is lower than lowerBound or bigger than // upperBound. const AtomSet &sl = idx[lowerBin]; std::copy_if(sl.begin(), sl.end(), inserter(set), [&](Atom* atom)->bool { AttentionValue::sti_t sti = atom->getAttentionValue()->getSTI(); return (lowerBound <= sti and sti <= upperBound); }); // If both lower and upper bounds are in the same bin, // Then we are done. if (lowerBin == upperBin) { UnorderedHandleSet ret; std::transform(set.begin(), set.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } // For every index within lowerBound and upperBound, // add to the list. while (++lowerBin < upperBin) { const AtomSet &ss = idx[lowerBin]; set.insert(ss.begin(), ss.end()); } // The two lists are concatenated. const AtomSet &uset = idx[upperBin]; std::copy_if(uset.begin(), uset.end(), inserter(set), [&](Atom* atom)->bool { AttentionValue::sti_t sti = atom->getAttentionValue()->getSTI(); return (lowerBound <= sti and sti <= upperBound); }); UnorderedHandleSet ret; std::transform(set.begin(), set.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } UnorderedHandleSet ImportanceIndex::getMaxBinContents() { UnorderedHandleSet ret; for (AtomSet s : boost::adaptors::reverse(idx)) { if (s.size() > 0) { std::transform(s.begin(), s.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } } return ret; } UnorderedHandleSet ImportanceIndex::getMinBinContents() { UnorderedHandleSet ret; for (AtomSet s : idx) { if (s.size() > 0) { std::transform(s.begin(), s.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } } return ret; } <commit_msg>Biased ImportanceIndex to wards lower values i.e. smaller bin size at lower sti values<commit_after>/* * opencog/atomspace/ImportanceIndex.cc * * Copyright (C) 2008-2011 OpenCog Foundation * All Rights Reserved * * 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 <algorithm> #include <opencog/util/functional.h> #include <opencog/atomspace/ImportanceIndex.h> #include <opencog/atoms/base/Atom.h> #include <opencog/atomspace/AtomTable.h> #include <boost/range/adaptor/reversed.hpp> using namespace opencog; //! Each bin has STI range of 32 means 2048 importance bins. #define IMPORTANCE_INDEX_SIZE 104 //(12*8)+8 ImportanceIndex::ImportanceIndex(void) { resize(IMPORTANCE_INDEX_SIZE); } /** * The following formula is used to calculate the ammount of bins * 32768 = (sum 2^b , b = 0 to x) * 8 + 8 * This means we have x groups with 8 bins each * The range of each groups bin is doulbe the previous (2^b) and starts at 1 * We have to add 8 since 2^c - 1 = sum 2^b , b = 0 to (c-1) and we have 8 * such groups */ unsigned int ImportanceIndex::importanceBin(short importance) { if (importance <= 15) return importance; short imp = std::ceil((importance - 8.0) / 8.0); int sum = 0; int i; for (i = 0; i <= 11; i++) { if (sum >= imp) break; sum = sum + std::pow(2,i); } int ad = 8 - std::ceil(importance / std::pow(2,(i-1))); unsigned int bin = ((i * 8) - ad); assert(bin <= IMPORTANCE_INDEX_SIZE); return bin; } void ImportanceIndex::updateImportance(Atom* atom, int bin) { int newbin = importanceBin(atom->getAttentionValue()->getSTI()); if (bin == newbin) return; remove(bin, atom); insert(newbin, atom); } void ImportanceIndex::insertAtom(Atom* atom) { int sti = atom->getAttentionValue()->getSTI(); int bin = importanceBin(sti); insert(bin, atom); } void ImportanceIndex::removeAtom(Atom* atom) { int sti = atom->getAttentionValue()->getSTI(); int bin = importanceBin(sti); remove(bin, atom); } UnorderedHandleSet ImportanceIndex::getHandleSet( AttentionValue::sti_t lowerBound, AttentionValue::sti_t upperBound) const { AtomSet set; // The indexes for the lower bound and upper bound lists is returned. int lowerBin = importanceBin(lowerBound); int upperBin = importanceBin(upperBound); // Build a list of atoms whose importance is equal to the lower bound. // For the lower bound and upper bound index, the list is filtered, // because there may be atoms that have the same importanceIndex // and whose importance is lower than lowerBound or bigger than // upperBound. const AtomSet &sl = idx[lowerBin]; std::copy_if(sl.begin(), sl.end(), inserter(set), [&](Atom* atom)->bool { AttentionValue::sti_t sti = atom->getAttentionValue()->getSTI(); return (lowerBound <= sti and sti <= upperBound); }); // If both lower and upper bounds are in the same bin, // Then we are done. if (lowerBin == upperBin) { UnorderedHandleSet ret; std::transform(set.begin(), set.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } // For every index within lowerBound and upperBound, // add to the list. while (++lowerBin < upperBin) { const AtomSet &ss = idx[lowerBin]; set.insert(ss.begin(), ss.end()); } // The two lists are concatenated. const AtomSet &uset = idx[upperBin]; std::copy_if(uset.begin(), uset.end(), inserter(set), [&](Atom* atom)->bool { AttentionValue::sti_t sti = atom->getAttentionValue()->getSTI(); return (lowerBound <= sti and sti <= upperBound); }); UnorderedHandleSet ret; std::transform(set.begin(), set.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } UnorderedHandleSet ImportanceIndex::getMaxBinContents() { UnorderedHandleSet ret; for (AtomSet s : boost::adaptors::reverse(idx)) { if (s.size() > 0) { std::transform(s.begin(), s.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } } return ret; } UnorderedHandleSet ImportanceIndex::getMinBinContents() { UnorderedHandleSet ret; for (AtomSet s : idx) { if (s.size() > 0) { std::transform(s.begin(), s.end(), inserter(ret), [](Atom* atom)->Handle { return atom->getHandle(); }); return ret; } } return ret; } <|endoftext|>
<commit_before>/* * attention/AttentionModule.cc * * Copyright (C) 2008 by OpenCog Foundation * All Rights Reserved * * Written by Misgana Bayetta && Roman Treutlein * * 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 "AttentionModule.h" #include <opencog/cogserver/server/CogServer.h> #include "opencog/attention/atom_types.definitions" using namespace opencog; concurrent_queue<Handle> opencog::newAtomsInAV; DECLARE_MODULE(AttentionModule) AttentionModule::AttentionModule(CogServer& cs) : Module(cs) { // New Thread based ECAN agents. _cogserver.registerAgent(AFImportanceDiffusionAgent::info().id, &afImportanceFactory); _cogserver.registerAgent(WAImportanceDiffusionAgent::info().id, &waImportanceFactory); _cogserver.registerAgent(AFRentCollectionAgent::info().id, &afRentFactory); _cogserver.registerAgent(WARentCollectionAgent::info().id, &waRentFactory); _cogserver.registerAgent(ForgettingAgent::info().id, &forgettingFactory); _cogserver.registerAgent(MinMaxSTIUpdatingAgent::info().id,&minMaxSTIUpdatingFactory); _cogserver.registerAgent(HebbianCreationAgent::info().id,&hebbianCreationFactory); _cogserver.registerAgent(FocusBoundaryUpdatingAgent::info().id,&focusUpdatingFactory); _cogserver.registerAgent(HebbianUpdatingAgent::info().id,&hebbianUpdatingFactory); _forgetting_agentptr = _cogserver.createAgent(ForgettingAgent::info().id, false); _minmaxstiupdating_agentptr = _cogserver.createAgent(MinMaxSTIUpdatingAgent::info().id,false); _hebbiancreation_agentptr = _cogserver.createAgent(HebbianCreationAgent::info().id,false); _focusupdating_agentptr = _cogserver.createAgent(FocusBoundaryUpdatingAgent::info().id,false); _hebbianupdating_agentptr = _cogserver.createAgent(HebbianUpdatingAgent::info().id,false); _afImportanceAgentPtr = _cogserver.createAgent(AFImportanceDiffusionAgent::info().id,false); _waImportanceAgentPtr = _cogserver.createAgent(WAImportanceDiffusionAgent::info().id,false); _afRentAgentPtr = _cogserver.createAgent(AFRentCollectionAgent::info().id, false); _waRentAgentPtr = _cogserver.createAgent(WARentCollectionAgent::info().id, false); addAFConnection =_cogserver.getAtomSpace().AddAFSignal( boost::bind(&AttentionModule::addAFSignalHandler, this, _1, _2, _3)); do_start_ecan_register(); } AttentionModule::~AttentionModule() { logger().debug("[AttentionModule] enter destructor"); _cogserver.unregisterAgent(AFImportanceDiffusionAgent::info().id); _cogserver.unregisterAgent(WAImportanceDiffusionAgent::info().id); _cogserver.unregisterAgent(ForgettingAgent::info().id); _cogserver.unregisterAgent(MinMaxSTIUpdatingAgent::info().id); _cogserver.unregisterAgent(FocusBoundaryUpdatingAgent::info().id); _cogserver.unregisterAgent(HebbianUpdatingAgent::info().id); _cogserver.unregisterAgent(HebbianCreationAgent::info().id); do_start_ecan_unregister(); addAFConnection.disconnect(); logger().debug("[AttentionModule] exit destructor"); } void AttentionModule::init() { } std::string AttentionModule::do_start_ecan(Request *req, std::list<std::string> args) { std::string afImportance = AFImportanceDiffusionAgent::info().id; std::string waImportance = WAImportanceDiffusionAgent::info().id; std::string afRent = AFRentCollectionAgent::info().id; std::string waRent = WARentCollectionAgent::info().id; _cogserver.startAgent(_afImportanceAgentPtr, true, afImportance); _cogserver.startAgent(_waImportanceAgentPtr, true, waImportance); _cogserver.startAgent(_afRentAgentPtr, true, afRent); _cogserver.startAgent(_waRentAgentPtr, true, waRent); _cogserver.startAgent(_forgetting_agentptr,true,"attention"); // _cogserver.startAgent(_minmaxstiupdating_agentptr,true,"attention"); _cogserver.startAgent(_focusupdating_agentptr,true,"attention"); _cogserver.startAgent(_hebbiancreation_agentptr,true,"hca"); _cogserver.startAgent(_hebbianupdating_agentptr,true,"hua"); return ("Started the following agents:\n" + afImportance + "\n" + waImportance + "\n" + afRent + "\n" + waRent + "\n"); } /* * When an atom enters the AttentionalFocus, it is added to a concurrent_queue * so that the HebbianCreationAgent know to check it and create HebbianLinks if * neccesary */ void AttentionModule::addAFSignalHandler(const Handle& source, const AttentionValuePtr& av_old, const AttentionValuePtr& av_new) { newAtomsInAV.push(source); } <commit_msg>Disable agents temporarily<commit_after>/* * attention/AttentionModule.cc * * Copyright (C) 2008 by OpenCog Foundation * All Rights Reserved * * Written by Misgana Bayetta && Roman Treutlein * * 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 "AttentionModule.h" #include <opencog/cogserver/server/CogServer.h> #include "opencog/attention/atom_types.definitions" using namespace opencog; concurrent_queue<Handle> opencog::newAtomsInAV; DECLARE_MODULE(AttentionModule) AttentionModule::AttentionModule(CogServer& cs) : Module(cs) { // New Thread based ECAN agents. _cogserver.registerAgent(AFImportanceDiffusionAgent::info().id, &afImportanceFactory); _cogserver.registerAgent(WAImportanceDiffusionAgent::info().id, &waImportanceFactory); _cogserver.registerAgent(AFRentCollectionAgent::info().id, &afRentFactory); _cogserver.registerAgent(WARentCollectionAgent::info().id, &waRentFactory); _cogserver.registerAgent(ForgettingAgent::info().id, &forgettingFactory); _cogserver.registerAgent(MinMaxSTIUpdatingAgent::info().id,&minMaxSTIUpdatingFactory); _cogserver.registerAgent(HebbianCreationAgent::info().id,&hebbianCreationFactory); _cogserver.registerAgent(FocusBoundaryUpdatingAgent::info().id,&focusUpdatingFactory); _cogserver.registerAgent(HebbianUpdatingAgent::info().id,&hebbianUpdatingFactory); _forgetting_agentptr = _cogserver.createAgent(ForgettingAgent::info().id, false); _minmaxstiupdating_agentptr = _cogserver.createAgent(MinMaxSTIUpdatingAgent::info().id,false); _hebbiancreation_agentptr = _cogserver.createAgent(HebbianCreationAgent::info().id,false); _focusupdating_agentptr = _cogserver.createAgent(FocusBoundaryUpdatingAgent::info().id,false); _hebbianupdating_agentptr = _cogserver.createAgent(HebbianUpdatingAgent::info().id,false); _afImportanceAgentPtr = _cogserver.createAgent(AFImportanceDiffusionAgent::info().id,false); _waImportanceAgentPtr = _cogserver.createAgent(WAImportanceDiffusionAgent::info().id,false); _afRentAgentPtr = _cogserver.createAgent(AFRentCollectionAgent::info().id, false); _waRentAgentPtr = _cogserver.createAgent(WARentCollectionAgent::info().id, false); addAFConnection =_cogserver.getAtomSpace().AddAFSignal( boost::bind(&AttentionModule::addAFSignalHandler, this, _1, _2, _3)); do_start_ecan_register(); } AttentionModule::~AttentionModule() { logger().debug("[AttentionModule] enter destructor"); _cogserver.unregisterAgent(AFImportanceDiffusionAgent::info().id); _cogserver.unregisterAgent(WAImportanceDiffusionAgent::info().id); _cogserver.unregisterAgent(ForgettingAgent::info().id); _cogserver.unregisterAgent(MinMaxSTIUpdatingAgent::info().id); _cogserver.unregisterAgent(FocusBoundaryUpdatingAgent::info().id); _cogserver.unregisterAgent(HebbianUpdatingAgent::info().id); _cogserver.unregisterAgent(HebbianCreationAgent::info().id); do_start_ecan_unregister(); addAFConnection.disconnect(); logger().debug("[AttentionModule] exit destructor"); } void AttentionModule::init() { } std::string AttentionModule::do_start_ecan(Request *req, std::list<std::string> args) { std::string afImportance = AFImportanceDiffusionAgent::info().id; std::string waImportance = WAImportanceDiffusionAgent::info().id; std::string afRent = AFRentCollectionAgent::info().id; std::string waRent = WARentCollectionAgent::info().id; _cogserver.startAgent(_afImportanceAgentPtr, true, afImportance); _cogserver.startAgent(_waImportanceAgentPtr, true, waImportance); _cogserver.startAgent(_afRentAgentPtr, true, afRent); _cogserver.startAgent(_waRentAgentPtr, true, waRent); // _cogserver.startAgent(_forgetting_agentptr,true,"attention"); // _cogserver.startAgent(_minmaxstiupdating_agentptr,true,"attention"); _cogserver.startAgent(_focusupdating_agentptr,true,"attention"); // _cogserver.startAgent(_hebbiancreation_agentptr,true,"hca"); // _cogserver.startAgent(_hebbianupdating_agentptr,true,"hua"); return ("Started the following agents:\n" + afImportance + "\n" + waImportance + "\n" + afRent + "\n" + waRent + "\n"); } /* * When an atom enters the AttentionalFocus, it is added to a concurrent_queue * so that the HebbianCreationAgent know to check it and create HebbianLinks if * neccesary */ void AttentionModule::addAFSignalHandler(const Handle& source, const AttentionValuePtr& av_old, const AttentionValuePtr& av_new) { newAtomsInAV.push(source); } <|endoftext|>
<commit_before>#include "Diagnostics.h" #include <clang/Basic/SourceManager.h> #include <clang/Sema/SemaDiagnostic.h> namespace ccons { DiagnosticsProvider::DiagnosticsProvider(llvm::raw_os_ostream& out) : _tdp(out, false, true, false) , _diag(this) { _diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl, clang::diag::MAP_ERROR); _diag.setDiagnosticMapping(clang::diag::warn_unused_expr, clang::diag::MAP_IGNORE); _diag.setDiagnosticMapping(clang::diag::pp_macro_not_used, clang::diag::MAP_IGNORE); _diag.setSuppressSystemWarnings(true); } void DiagnosticsProvider::HandleDiagnostic(clang::Diagnostic::Level DiagLevel, const clang::DiagnosticInfo &Info) { std::pair<clang::diag::kind, unsigned> record = std::make_pair(Info.getID(), Info.getLocation().getManager().getFileOffset(Info.getLocation()) - _offs); if (_memory.insert(record).second) { _tdp.HandleDiagnostic(DiagLevel, Info); } } void DiagnosticsProvider::setOffset(unsigned offset) { _offs = offset; } clang::Diagnostic * DiagnosticsProvider::getDiagnostic() { return &_diag; } } // namespace ccons <commit_msg>ignore warn_missing_prototype<commit_after>#include "Diagnostics.h" #include <clang/Basic/SourceManager.h> #include <clang/Sema/SemaDiagnostic.h> namespace ccons { DiagnosticsProvider::DiagnosticsProvider(llvm::raw_os_ostream& out) : _tdp(out, false, true, false) , _diag(this) { _diag.setDiagnosticMapping(clang::diag::ext_implicit_function_decl, clang::diag::MAP_ERROR); _diag.setDiagnosticMapping(clang::diag::warn_unused_expr, clang::diag::MAP_IGNORE); _diag.setDiagnosticMapping(clang::diag::warn_missing_prototype, clang::diag::MAP_IGNORE); _diag.setDiagnosticMapping(clang::diag::pp_macro_not_used, clang::diag::MAP_IGNORE); _diag.setSuppressSystemWarnings(true); } void DiagnosticsProvider::HandleDiagnostic(clang::Diagnostic::Level DiagLevel, const clang::DiagnosticInfo &Info) { std::pair<clang::diag::kind, unsigned> record = std::make_pair(Info.getID(), Info.getLocation().getManager().getFileOffset(Info.getLocation()) - _offs); if (_memory.insert(record).second) { _tdp.HandleDiagnostic(DiagLevel, Info); } } void DiagnosticsProvider::setOffset(unsigned offset) { _offs = offset; } clang::Diagnostic * DiagnosticsProvider::getDiagnostic() { return &_diag; } } // namespace ccons <|endoftext|>
<commit_before>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file FunctionDialog.cpp * @brief Dialog for invoking Qt slots (i.e. functions) of entities and components. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "FunctionDialog.h" #include "ArgumentType.h" #include "DoxygenDocReader.h" #include "Entity.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("FunctionDialog"); #include <QWebView> #include "MemoryLeakCheck.h" // FunctionComboBox FunctionComboBox::FunctionComboBox(QWidget *parent) : QComboBox(parent) { //setInsertPolicy(QComboBox::InsertAlphabetically); setMinimumContentsLength(50); setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); } void FunctionComboBox::AddFunction(const FunctionMetaData &f) { addItem(f.fullSignature); functions.append(f); } void FunctionComboBox::AddFunctions(const QList<FunctionMetaData> &funcs) { foreach(FunctionMetaData f, funcs) addItem(f.fullSignature); functions.append(funcs); } FunctionMetaData FunctionComboBox::CurrentFunction() const { foreach(FunctionMetaData f, functions) if (f.fullSignature == currentText()) return f; return FunctionMetaData(); } // FunctionDialog FunctionDialog::FunctionDialog(const QList<boost::weak_ptr<QObject> > &objs, QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), objects(objs), returnValueArgument(0) { // Set up the UI setAttribute(Qt::WA_DeleteOnClose); if (graphicsProxyWidget()) graphicsProxyWidget()->setWindowTitle(tr("Trigger Function")); setWindowTitle(tr("Trigger Function")); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(5,5,5,5); mainLayout->setSpacing(6); targetsLabel = new QLabel; targetsLabel->setWordWrap(true); functionComboBox = new FunctionComboBox; connect(functionComboBox, SIGNAL(currentIndexChanged(int)), SLOT(UpdateEditors())); doxygenView = new QTextEdit/*QWebView*/; // doxygenView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // doxygenView->setMinimumSize(300, 50); // doxygenView->setMaximumSize(600, 200); doxygenView->hide(); mainLayout->addWidget(targetsLabel); mainLayout->addWidget(doxygenView); mainLayout->addWidget(functionComboBox); editorLayout = new QGridLayout; mainLayout->insertLayout(-1, editorLayout); QLabel *returnValueLabel = new QLabel(tr("Return value(s):")); returnValueEdit = new QTextEdit; mainLayout->addWidget(returnValueLabel); mainLayout->addWidget(returnValueEdit); QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); mainLayout->insertSpacerItem(-1, spacer); QHBoxLayout *buttonsLayout = new QHBoxLayout; QSpacerItem *buttonSpacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); buttonsLayout->addSpacerItem(buttonSpacer); mainLayout->insertLayout(-1, buttonsLayout); QPushButton *execButton = new QPushButton(tr("Execute")); QPushButton *execAndCloseButton = new QPushButton(tr("Execute and Close")); QPushButton *closeButton = new QPushButton(tr("Close")); connect(execButton, SIGNAL(clicked()), SLOT(Execute())); connect(execAndCloseButton, SIGNAL(clicked()), SLOT(accept())); connect(closeButton, SIGNAL(clicked()), SLOT(reject())); buttonsLayout->addWidget(execButton); buttonsLayout->addWidget(execAndCloseButton); buttonsLayout->addWidget(closeButton); GenerateTargetLabelAndFunctions(); UpdateEditors(); } FunctionDialog::~FunctionDialog() { qDeleteAll(allocatedArguments); } QList<boost::weak_ptr<QObject> > FunctionDialog::Objects() const { return objects; } QString FunctionDialog::Function() const { return functionComboBox->CurrentFunction().function; } IArgumentType *FunctionDialog::ReturnValueArgument() const { return returnValueArgument; } QList<IArgumentType *> FunctionDialog::Arguments() const { return allocatedArguments; } void FunctionDialog::SetReturnValueText(const QString &text) { returnValueEdit->setText(text); } void FunctionDialog::AppendReturnValueText(const QString &text) { QString newText = returnValueEdit->toPlainText(); if (!newText.isEmpty()) newText.append('\n'); newText.append(text); returnValueEdit->setText(newText); } void FunctionDialog::hideEvent(QHideEvent *) { close(); } void FunctionDialog::GenerateTargetLabelAndFunctions() { // Generate functions for the function combo box. QList<FunctionMetaData> fmds; QSet<QString> functions; QString targetText; assert(objects.size()); if (objects.size() == 1) targetText.append(tr("Target: ")); else targetText.append(tr("Targets: ")); int objectsTotal = objects.size(); for(int i = 0; i < objectsTotal; ++i) { QObject *obj = objects[i].lock().get(); assert(obj); if (!obj) { --objectsTotal; continue; } const QMetaObject *mo = obj->metaObject(); targetText.append(mo->className()); { Scene::Entity *e = dynamic_cast<Scene::Entity *>(obj); IComponent *c = dynamic_cast<IComponent *>(obj); if (e) targetText.append('(' + QString::number((uint)e->GetId()) + ')'); else if (c) targetText.append('(' + c->Name() + ')'); } if (i < objects.size() - 1) targetText.append(", "); for(int i = mo->methodOffset(); i < mo->methodCount(); ++i) { const QMetaMethod &mm = mo->method(i); //if ((mm.methodType() == QMetaMethod::Slot) && (mm.access() == QMetaMethod::Public)) // if (mm matches with current filter) { // Craft full signature with return type and parameter names. QString fullSig = mm.signature(); QList<QByteArray> pNames = mm.parameterNames(); QList<QByteArray> pTypes = mm.parameterTypes(); if (pTypes.size()) { // Insert as many parameter names as we pNames in total; function signatures might be missing some param names. int idx, searchStart = 0; for(int pIdx = 0; pIdx < pNames.size(); ++pIdx) { idx = fullSig.indexOf(',', searchStart); QString param = ' ' + QString(pNames[pIdx]); if (idx == -1) { // No more commas found. Assume that we can insert the last param name now. if (pIdx < pNames.size()) fullSig.insert(fullSig.size() - 1, param); break; } // Insert parameter name. fullSig.insert(idx, param); searchStart = idx + param.size() + 1; } } // Prepend full signature with return type. QString returnType = mm.typeName(); if (returnType.isEmpty()) returnType = "void"; fullSig.prepend(returnType + ' '); // Construct FunctionMetaData struct. FunctionMetaData f; int start = fullSig.indexOf(' '); int end = fullSig.indexOf('('); f.function = fullSig.mid(start + 1, end - start - 1); f.returnType = returnType; f.fullSignature = fullSig; f.signature = mm.signature(); for(int k = 0; k < pTypes.size(); ++k) if (k < pNames.size()) f.parameters.push_back(qMakePair(QString(pTypes[k]), QString(pNames[k]))); else // Protection agains missing parameter names in the signature: insert just an empty string. f.parameters.push_back(qMakePair(QString(pTypes[k]), QString())); fmds.push_back(f); } } } targetsLabel->setText(targetText); functionComboBox ->AddFunctions(fmds); } void FunctionDialog::CreateArgumentList() { QList<IArgumentType *> args; QPair<QString, QString> pair; foreach(pair, functionComboBox->CurrentFunction().parameters) { IArgumentType *arg = CreateArgumentType(pair.first); if (arg) args.append(arg); } qDeleteAll(allocatedArguments); allocatedArguments = args; } IArgumentType *FunctionDialog::CreateArgumentType(const QString &type) { IArgumentType *arg = 0; const char *typeChar = type.toStdString().c_str(); if (type == "void") arg = new VoidArgumentType; else if (type == "QString") arg = new ArgumentType<QString>(typeChar); else if (type == "QStringList") arg = new ArgumentType<QStringList>(typeChar); else if (type == "std::string") arg = new ArgumentType<std::string>(typeChar); else if (type == "bool") arg = new ArgumentType<bool>(typeChar); else if(type == "unsigned int" || type == "uint" || type == "size_t" || type == "entity_id_t") arg = new ArgumentType<unsigned int>(typeChar); else if (type == "int") arg = new ArgumentType<int>(typeChar); else if (type == "float") arg = new ArgumentType<float>(typeChar); else if (type == "double") arg = new ArgumentType<double>(typeChar); else LogDebug("Unsupported argument type: " + type.toStdString()); return arg; } void FunctionDialog::Execute() { emit finished(2); } void FunctionDialog::UpdateEditors() { QPoint orgPos = pos(); // delete widgets from gridlayout QLayoutItem *child; while((child = editorLayout->takeAt(0)) != 0) { QWidget *w = child->widget(); SAFE_DELETE(child); SAFE_DELETE(w); } FunctionMetaData fmd = functionComboBox->CurrentFunction(); if (fmd.function.isEmpty()) return; if (objects[0].expired()) return; SAFE_DELETE(returnValueArgument); returnValueArgument = CreateArgumentType(fmd.returnType); // Create and show doxygen documentation for the function. QString doxyFuncName = QString(objects[0].lock()->metaObject()->className()) + "::" + fmd.function; QUrl styleSheetPath; QString documentation; bool success = DoxygenDocReader::GetSymbolDocumentation(doxyFuncName, &documentation, &styleSheetPath); if (documentation.length() != 0) { doxygenView->setHtml(documentation);//, styleSheetPath); doxygenView->show(); } else { LogDebug("Failed to find documentation!"); doxygenView->hide(); } CreateArgumentList(); if (allocatedArguments.empty() || (allocatedArguments.size() != fmd.parameters.size())) return; for(int idx = 0; idx < allocatedArguments.size(); ++idx) { QLabel *label = new QLabel(fmd.parameters[idx].first + ' ' + fmd.parameters[idx].second); label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); QWidget *editor = allocatedArguments[idx]->CreateEditor(); // Layout takes ownership of label and editor. editorLayout->addWidget(label, idx, 0); editorLayout->addWidget(editor, idx, 1); } move(orgPos); } <commit_msg>Fix bug which caused ArgumentType<T>::typeName to be invalid.<commit_after>/** * For conditions of distribution and use, see copyright notice in license.txt * * @file FunctionDialog.cpp * @brief Dialog for invoking Qt slots (i.e. functions) of entities and components. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "FunctionDialog.h" #include "ArgumentType.h" #include "DoxygenDocReader.h" #include "Entity.h" #include "LoggingFunctions.h" DEFINE_POCO_LOGGING_FUNCTIONS("FunctionDialog"); #include <QWebView> #include "MemoryLeakCheck.h" // FunctionComboBox FunctionComboBox::FunctionComboBox(QWidget *parent) : QComboBox(parent) { //setInsertPolicy(QComboBox::InsertAlphabetically); setMinimumContentsLength(50); setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); } void FunctionComboBox::AddFunction(const FunctionMetaData &f) { addItem(f.fullSignature); functions.append(f); } void FunctionComboBox::AddFunctions(const QList<FunctionMetaData> &funcs) { foreach(FunctionMetaData f, funcs) addItem(f.fullSignature); functions.append(funcs); } FunctionMetaData FunctionComboBox::CurrentFunction() const { foreach(FunctionMetaData f, functions) if (f.fullSignature == currentText()) return f; return FunctionMetaData(); } // FunctionDialog FunctionDialog::FunctionDialog(const QList<boost::weak_ptr<QObject> > &objs, QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), objects(objs), returnValueArgument(0) { // Set up the UI setAttribute(Qt::WA_DeleteOnClose); resize(500, 200); if (graphicsProxyWidget()) graphicsProxyWidget()->setWindowTitle(tr("Trigger Function")); setWindowTitle(tr("Trigger Function")); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setContentsMargins(5,5,5,5); mainLayout->setSpacing(6); targetsLabel = new QLabel; targetsLabel->setWordWrap(true); functionComboBox = new FunctionComboBox; connect(functionComboBox, SIGNAL(currentIndexChanged(int)), SLOT(UpdateEditors())); doxygenView = new QTextEdit/*QWebView*/; // doxygenView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // doxygenView->setMinimumSize(300, 50); // doxygenView->setMaximumSize(600, 200); doxygenView->hide(); mainLayout->addWidget(targetsLabel); mainLayout->addWidget(doxygenView); mainLayout->addWidget(functionComboBox); editorLayout = new QGridLayout; mainLayout->insertLayout(-1, editorLayout); QLabel *returnValueLabel = new QLabel(tr("Return value(s):")); returnValueEdit = new QTextEdit; mainLayout->addWidget(returnValueLabel); mainLayout->addWidget(returnValueEdit); QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); mainLayout->insertSpacerItem(-1, spacer); QHBoxLayout *buttonsLayout = new QHBoxLayout; QSpacerItem *buttonSpacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); buttonsLayout->addSpacerItem(buttonSpacer); mainLayout->insertLayout(-1, buttonsLayout); QPushButton *execButton = new QPushButton(tr("Execute")); QPushButton *execAndCloseButton = new QPushButton(tr("Execute and Close")); QPushButton *closeButton = new QPushButton(tr("Close")); connect(execButton, SIGNAL(clicked()), SLOT(Execute())); connect(execAndCloseButton, SIGNAL(clicked()), SLOT(accept())); connect(closeButton, SIGNAL(clicked()), SLOT(reject())); buttonsLayout->addWidget(execButton); buttonsLayout->addWidget(execAndCloseButton); buttonsLayout->addWidget(closeButton); GenerateTargetLabelAndFunctions(); UpdateEditors(); } FunctionDialog::~FunctionDialog() { qDeleteAll(allocatedArguments); } QList<boost::weak_ptr<QObject> > FunctionDialog::Objects() const { return objects; } QString FunctionDialog::Function() const { return functionComboBox->CurrentFunction().function; } IArgumentType *FunctionDialog::ReturnValueArgument() const { return returnValueArgument; } QList<IArgumentType *> FunctionDialog::Arguments() const { return allocatedArguments; } void FunctionDialog::SetReturnValueText(const QString &text) { returnValueEdit->setText(text); } void FunctionDialog::AppendReturnValueText(const QString &text) { QString newText = returnValueEdit->toPlainText(); if (!newText.isEmpty()) newText.append('\n'); newText.append(text); returnValueEdit->setText(newText); } void FunctionDialog::hideEvent(QHideEvent *) { close(); } void FunctionDialog::GenerateTargetLabelAndFunctions() { // Generate functions for the function combo box. QList<FunctionMetaData> fmds; QSet<QString> functions; QString targetText; assert(objects.size()); if (objects.size() == 1) targetText.append(tr("Target: ")); else targetText.append(tr("Targets: ")); int objectsTotal = objects.size(); for(int i = 0; i < objectsTotal; ++i) { QObject *obj = objects[i].lock().get(); assert(obj); if (!obj) { --objectsTotal; continue; } const QMetaObject *mo = obj->metaObject(); targetText.append(mo->className()); { Scene::Entity *e = dynamic_cast<Scene::Entity *>(obj); IComponent *c = dynamic_cast<IComponent *>(obj); if (e) targetText.append('(' + QString::number((uint)e->GetId()) + ')'); else if (c) targetText.append('(' + c->Name() + ')'); } if (i < objects.size() - 1) targetText.append(", "); for(int i = mo->methodOffset(); i < mo->methodCount(); ++i) { const QMetaMethod &mm = mo->method(i); //if ((mm.methodType() == QMetaMethod::Slot) && (mm.access() == QMetaMethod::Public)) // if (mm matches with current filter) { // Craft full signature with return type and parameter names. QString fullSig = mm.signature(); QList<QByteArray> pNames = mm.parameterNames(); QList<QByteArray> pTypes = mm.parameterTypes(); if (pTypes.size()) { // Insert as many parameter names as we pNames in total; function signatures might be missing some param names. int idx, searchStart = 0; for(int pIdx = 0; pIdx < pNames.size(); ++pIdx) { idx = fullSig.indexOf(',', searchStart); QString param = ' ' + QString(pNames[pIdx]); if (idx == -1) { // No more commas found. Assume that we can insert the last param name now. if (pIdx < pNames.size()) fullSig.insert(fullSig.size() - 1, param); break; } // Insert parameter name. fullSig.insert(idx, param); searchStart = idx + param.size() + 1; } } // Prepend full signature with return type. QString returnType = mm.typeName(); if (returnType.isEmpty()) returnType = "void"; fullSig.prepend(returnType + ' '); // Construct FunctionMetaData struct. FunctionMetaData f; int start = fullSig.indexOf(' '); int end = fullSig.indexOf('('); f.function = fullSig.mid(start + 1, end - start - 1); f.returnType = returnType; f.fullSignature = fullSig; f.signature = mm.signature(); for(int k = 0; k < pTypes.size(); ++k) if (k < pNames.size()) f.parameters.push_back(qMakePair(QString(pTypes[k]), QString(pNames[k]))); else // Protection agains missing parameter names in the signature: insert just an empty string. f.parameters.push_back(qMakePair(QString(pTypes[k]), QString())); fmds.push_back(f); } } } targetsLabel->setText(targetText); functionComboBox ->AddFunctions(fmds); } void FunctionDialog::CreateArgumentList() { QList<IArgumentType *> args; QPair<QString, QString> pair; foreach(pair, functionComboBox->CurrentFunction().parameters) { IArgumentType *arg = CreateArgumentType(pair.first); if (arg) args.append(arg); } qDeleteAll(allocatedArguments); allocatedArguments = args; } IArgumentType *FunctionDialog::CreateArgumentType(const QString &type) { IArgumentType *arg = 0; if (type == "void") arg = new VoidArgumentType; else if (type == "QString") arg = new ArgumentType<QString>(type.toStdString().c_str()); else if (type == "QStringList") arg = new ArgumentType<QStringList>(type.toStdString().c_str()); else if (type == "std::string") arg = new ArgumentType<std::string>(type.toStdString().c_str()); else if (type == "bool") arg = new ArgumentType<bool>(type.toStdString().c_str()); else if(type == "unsigned int" || type == "uint" || type == "size_t" || type == "entity_id_t") arg = new ArgumentType<unsigned int>(type.toStdString().c_str()); else if (type == "int") arg = new ArgumentType<int>(type.toStdString().c_str()); else if (type == "float") arg = new ArgumentType<float>(type.toStdString().c_str()); else if (type == "double") arg = new ArgumentType<double>(type.toStdString().c_str()); else LogDebug("Unsupported argument type: " + type.toStdString()); return arg; } void FunctionDialog::Execute() { emit finished(2); } void FunctionDialog::UpdateEditors() { QPoint orgPos = pos(); // delete widgets from gridlayout QLayoutItem *child; while((child = editorLayout->takeAt(0)) != 0) { QWidget *w = child->widget(); SAFE_DELETE(child); SAFE_DELETE(w); } FunctionMetaData fmd = functionComboBox->CurrentFunction(); if (fmd.function.isEmpty()) return; if (objects[0].expired()) return; SAFE_DELETE(returnValueArgument); returnValueArgument = CreateArgumentType(fmd.returnType); // Create and show doxygen documentation for the function. QString doxyFuncName = QString(objects[0].lock()->metaObject()->className()) + "::" + fmd.function; QUrl styleSheetPath; QString documentation; bool success = DoxygenDocReader::GetSymbolDocumentation(doxyFuncName, &documentation, &styleSheetPath); if (documentation.length() != 0) { doxygenView->setHtml(documentation);//, styleSheetPath); doxygenView->show(); } else { LogDebug("Failed to find documentation!"); doxygenView->hide(); } CreateArgumentList(); if (allocatedArguments.empty() || (allocatedArguments.size() != fmd.parameters.size())) return; for(int idx = 0; idx < allocatedArguments.size(); ++idx) { QLabel *label = new QLabel(fmd.parameters[idx].first + ' ' + fmd.parameters[idx].second); label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); QWidget *editor = allocatedArguments[idx]->CreateEditor(); // Layout takes ownership of label and editor. editorLayout->addWidget(label, idx, 0); editorLayout->addWidget(editor, idx, 1); } move(orgPos); } <|endoftext|>
<commit_before>#include <iostream> #include "EightQueens.h" namespace EightQueensProblem { bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned ) {//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't. } bool EightQueensSolver::isLegal( bool chessBoard[8][8] ) {//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal. int count;//Number of queens encountered in a given row/column/diagonal. //Check the rows. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this row, the board isn't legal so return false. return false; } } } //Check the columns. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[i][j] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this column, the board isn't legal so return false. return false; } } } //Check the diagonals. for( int i = 0; i < 8; i++ ) { int j = 0; while( (i < 8) && (j < 8) ) { } } } static void printBoard( bool chessBoard[8][8] ) {//Prints out chessBoard to standard output. //Go through each element one by one and print - for empty and * for queen. for( int i = 0; i < 8; i++ ) { for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Queen space std::cout << "*"; } else {//Empty space std::cout << "-"; } //Print a space after the character, but not if it's the last one since only want spaces between characters. if( j < 7 ) { std::cout << " "; } } //Print an endline after the current line. std::cout << std::endl; } } <commit_msg>Added a little to the isLegal method.<commit_after>#include <iostream> #include "EightQueens.h" namespace EightQueensProblem { bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned ) {//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't. } bool EightQueensSolver::isLegal( bool chessBoard[8][8] ) {//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal. int count;//Number of queens encountered in a given row/column/diagonal. //Check the rows. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this row, the board isn't legal so return false. return false; } } } //Check the columns. for( int i = 0; i < 8; i++ ) { count = 0; for( int j = 0; j < 8; j++ ) { if( chessBoard[i][j] == true ) {//Found a queen. count++; } if( count > 1 ) {//If more than one queen has been found on this column, the board isn't legal so return false. return false; } } } //Check the diagonals. for( int i = 0; i < 8; i++ ) { int j = 0; while( (i < 8) && (j < 8) ) { j++; } } } static void printBoard( bool chessBoard[8][8] ) {//Prints out chessBoard to standard output. //Go through each element one by one and print - for empty and * for queen. for( int i = 0; i < 8; i++ ) { for( int j = 0; j < 8; j++ ) { if( chessBoard[j][i] == true ) {//Queen space std::cout << "*"; } else {//Empty space std::cout << "-"; } //Print a space after the character, but not if it's the last one since only want spaces between characters. if( j < 7 ) { std::cout << " "; } } //Print an endline after the current line. std::cout << std::endl; } } <|endoftext|>
<commit_before> #include "odrive_main.h" Encoder::Encoder(const EncoderHardwareConfig_t& hw_config, Config_t& config) : hw_config_(hw_config), config_(config) { // Calculate encoder pll gains // This calculation is currently identical to the PLL in SensorlessEstimator float pll_bandwidth = 1000.0f; // [rad/s] pll_kp_ = 2.0f * pll_bandwidth; // Critically damped pll_ki_ = 0.25f * (pll_kp_ * pll_kp_); if (config.pre_calibrated && (config.mode == Encoder::MODE_HALL)) { offset_ = config.offset; is_ready_ = true; } } static void enc_index_cb_wrapper(void* ctx) { reinterpret_cast<Encoder*>(ctx)->enc_index_cb(); } void Encoder::setup() { HAL_TIM_Encoder_Start(hw_config_.timer, TIM_CHANNEL_ALL); GPIO_subscribe(hw_config_.index_port, hw_config_.index_pin, GPIO_NOPULL, enc_index_cb_wrapper, this); } void Encoder::set_error(Encoder::Error_t error) { error_ |= error; axis_->error_ |= Axis::ERROR_MOTOR_FAILED; } bool Encoder::do_checks(){ return error_ == ERROR_NONE; } //-------------------- // Hardware Dependent //-------------------- // Triggered when an encoder passes over the "Index" pin // TODO: only arm index edge interrupt when we know encoder has powered up // TODO: disable interrupt once we found the index void Encoder::enc_index_cb() { if (config_.use_index && !index_found_) { set_circular_count(0); if (config_.pre_calibrated) { offset_ = config_.offset; is_ready_ = true; } index_found_ = true; } } // Function that sets the current encoder count to a desired 32-bit value. void Encoder::set_linear_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Update states shadow_count_ = count; pos_estimate_ = (float)count; //Write hardware last hw_config_.timer->Instance->CNT = count; __set_PRIMASK(prim); } // Function that sets the CPR circular tracking encoder count to a desired 32-bit value. // Note that this will get mod'ed down to [0, cpr) void Encoder::set_circular_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Offset and state must be shifted by the same amount offset_ += count - count_in_cpr_; offset_ = mod(offset_, config_.cpr); // Update states count_in_cpr_ = mod(count, config_.cpr); pos_cpr_ = (float)count_in_cpr_; __set_PRIMASK(prim); } // @brief Slowly turns the motor in one direction until the // encoder index is found. // TODO: Do the scan with current, not voltage! bool Encoder::run_index_search() { float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; float omega = (float)(axis_->motor_.config_.direction) * config_.idx_search_speed; index_found_ = false; float phase = 0.0f; axis_->run_control_loop([&](){ phase = wrap_pm_pi(phase + omega * current_meas_period); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_IDX_SEARCH); // continue until the index is found return !index_found_; }); return true; } // @brief Turns the motor in one direction for a bit and then in the other // direction in order to find the offset between the electrical phase 0 // and the encoder state 0. // TODO: Do the scan with current, not voltage! bool Encoder::run_offset_calibration() { static const float start_lock_duration = 1.0f; static const float scan_omega = 4.0f * M_PI; static const float scan_distance = 16.0f * M_PI; static const int num_steps = scan_distance / scan_omega * current_meas_hz; // Temporarily disable index search so it doesn't mess // with the offset calibration bool old_use_index = config_.use_index; config_.use_index = false; float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; // go to motor zero phase for start_lock_duration to get ready to scan int i = 0; axis_->run_control_loop([&](){ if (!axis_->motor_.enqueue_voltage_timings(voltage_magnitude, 0.0f)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); return ++i < start_lock_duration * current_meas_hz; }); if (axis_->error_ != Axis::ERROR_NONE) return false; int32_t init_enc_val = shadow_count_; int64_t encvaluesum = 0; // scan forward i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(scan_distance * (float)i / (float)num_steps - scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float expected_encoder_delta = scan_distance / elec_rad_per_enc; float actual_encoder_delta_abs = fabsf(shadow_count_-init_enc_val); if(fabsf(actual_encoder_delta_abs - expected_encoder_delta)/expected_encoder_delta > config_.calib_range) { set_error(ERROR_CPR_OUT_OF_RANGE); return false; } // check direction if (shadow_count_ > init_enc_val + 8) { // motor same dir as encoder axis_->motor_.config_.direction = 1; } else if (shadow_count_ < init_enc_val - 8) { // motor opposite dir as encoder axis_->motor_.config_.direction = -1; } else { // Encoder response error set_error(ERROR_RESPONSE); return false; } // scan backwards i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(-scan_distance * (float)i / (float)num_steps + scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; offset_ = encvaluesum / (num_steps * 2); config_.offset = offset_; int32_t residual = encvaluesum - ((int64_t)offset_ * (int64_t)(num_steps * 2)); config_.offset_float = (float)residual / (float)(num_steps * 2) + 0.5f; // add 0.5 to center-align state to phase is_ready_ = true; config_.use_index = old_use_index; return true; } static bool decode_hall(uint8_t hall_state, int32_t* hall_cnt) { switch (hall_state) { case 0b001: *hall_cnt = 0; return true; case 0b011: *hall_cnt = 1; return true; case 0b010: *hall_cnt = 2; return true; case 0b110: *hall_cnt = 3; return true; case 0b100: *hall_cnt = 4; return true; case 0b101: *hall_cnt = 5; return true; default: return false; } } bool Encoder::update() { // Check that we don't get problems with discrete time approximation if (!(current_meas_period * pll_kp_ < 1.0f)) { set_error(ERROR_UNSTABLE_GAIN); return false; } // update internal encoder state. int32_t delta_enc = 0; switch (config_.mode) { case MODE_INCREMENTAL: { //TODO: use count_in_cpr_ instead as shadow_count_ can overflow //or use 64 bit int16_t delta_enc_16 = (int16_t)hw_config_.timer->Instance->CNT - (int16_t)shadow_count_; delta_enc = (int32_t)delta_enc_16; //sign extend } break; case MODE_HALL: { int32_t hall_cnt; if (decode_hall(hall_state_, &hall_cnt)) { delta_enc = hall_cnt - count_in_cpr_; delta_enc = mod(delta_enc, 6); if (delta_enc > 3) delta_enc -= 6; } else { set_error(ERROR_ILLEGAL_HALL_STATE); return false; } } break; default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); return false; } break; } shadow_count_ += delta_enc; count_in_cpr_ += delta_enc; count_in_cpr_ = mod(count_in_cpr_, config_.cpr); //// run pll (for now pll is in units of encoder counts) // Predict current pos pos_estimate_ += current_meas_period * pll_vel_; pos_cpr_ += current_meas_period * pll_vel_; // discrete phase detector float delta_pos = (float)(shadow_count_ - (int32_t)floorf(pos_estimate_)); float delta_pos_cpr = (float)(count_in_cpr_ - (int32_t)floorf(pos_cpr_)); delta_pos_cpr = wrap_pm(delta_pos_cpr, 0.5f * (float)(config_.cpr)); // pll feedback pos_estimate_ += current_meas_period * pll_kp_ * delta_pos; pos_cpr_ += current_meas_period * pll_kp_ * delta_pos_cpr; pos_cpr_ = fmodf_pos(pos_cpr_, (float)(config_.cpr)); pll_vel_ += current_meas_period * pll_ki_ * delta_pos_cpr; bool snap_to_zero_vel = false; if (fabsf(pll_vel_) < 0.5f * current_meas_period * pll_ki_) { pll_vel_ = 0.0f; //align delta-sigma on zero to prevent jitter snap_to_zero_vel = true; } //// run encoder count interpolation int32_t corrected_enc = count_in_cpr_ - offset_; // if we are stopped, make sure we don't randomly drift if (snap_to_zero_vel) { interpolation_ = 0.5f; // reset interpolation if encoder edge comes } else if (delta_enc > 0) { interpolation_ = 0.0f; } else if (delta_enc < 0) { interpolation_ = 1.0f; } else { // Interpolate (predict) between encoder counts using pll_vel, interpolation_ += current_meas_period * pll_vel_; // don't allow interpolation indicated position outside of [enc, enc+1) if (interpolation_ > 1.0f) interpolation_ = 1.0f; if (interpolation_ < 0.0f) interpolation_ = 0.0f; } float interpolated_enc = corrected_enc + interpolation_; //// compute electrical phase //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float ph = elec_rad_per_enc * (interpolated_enc - config_.offset_float); // ph = fmodf(ph, 2*M_PI); phase_ = wrap_pm_pi(ph); return true; } <commit_msg>set bandwidth to 100<commit_after> #include "odrive_main.h" Encoder::Encoder(const EncoderHardwareConfig_t& hw_config, Config_t& config) : hw_config_(hw_config), config_(config) { // Calculate encoder pll gains // This calculation is currently identical to the PLL in SensorlessEstimator float pll_bandwidth = 100.0f; // [rad/s] pll_kp_ = 2.0f * pll_bandwidth; // Critically damped pll_ki_ = 0.25f * (pll_kp_ * pll_kp_); if (config.pre_calibrated && (config.mode == Encoder::MODE_HALL)) { offset_ = config.offset; is_ready_ = true; } } static void enc_index_cb_wrapper(void* ctx) { reinterpret_cast<Encoder*>(ctx)->enc_index_cb(); } void Encoder::setup() { HAL_TIM_Encoder_Start(hw_config_.timer, TIM_CHANNEL_ALL); GPIO_subscribe(hw_config_.index_port, hw_config_.index_pin, GPIO_NOPULL, enc_index_cb_wrapper, this); } void Encoder::set_error(Encoder::Error_t error) { error_ |= error; axis_->error_ |= Axis::ERROR_MOTOR_FAILED; } bool Encoder::do_checks(){ return error_ == ERROR_NONE; } //-------------------- // Hardware Dependent //-------------------- // Triggered when an encoder passes over the "Index" pin // TODO: only arm index edge interrupt when we know encoder has powered up // TODO: disable interrupt once we found the index void Encoder::enc_index_cb() { if (config_.use_index && !index_found_) { set_circular_count(0); if (config_.pre_calibrated) { offset_ = config_.offset; is_ready_ = true; } index_found_ = true; } } // Function that sets the current encoder count to a desired 32-bit value. void Encoder::set_linear_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Update states shadow_count_ = count; pos_estimate_ = (float)count; //Write hardware last hw_config_.timer->Instance->CNT = count; __set_PRIMASK(prim); } // Function that sets the CPR circular tracking encoder count to a desired 32-bit value. // Note that this will get mod'ed down to [0, cpr) void Encoder::set_circular_count(int32_t count) { // Disable interrupts to make a critical section to avoid race condition uint32_t prim = __get_PRIMASK(); __disable_irq(); // Offset and state must be shifted by the same amount offset_ += count - count_in_cpr_; offset_ = mod(offset_, config_.cpr); // Update states count_in_cpr_ = mod(count, config_.cpr); pos_cpr_ = (float)count_in_cpr_; __set_PRIMASK(prim); } // @brief Slowly turns the motor in one direction until the // encoder index is found. // TODO: Do the scan with current, not voltage! bool Encoder::run_index_search() { float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; float omega = (float)(axis_->motor_.config_.direction) * config_.idx_search_speed; index_found_ = false; float phase = 0.0f; axis_->run_control_loop([&](){ phase = wrap_pm_pi(phase + omega * current_meas_period); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_IDX_SEARCH); // continue until the index is found return !index_found_; }); return true; } // @brief Turns the motor in one direction for a bit and then in the other // direction in order to find the offset between the electrical phase 0 // and the encoder state 0. // TODO: Do the scan with current, not voltage! bool Encoder::run_offset_calibration() { static const float start_lock_duration = 1.0f; static const float scan_omega = 4.0f * M_PI; static const float scan_distance = 16.0f * M_PI; static const int num_steps = scan_distance / scan_omega * current_meas_hz; // Temporarily disable index search so it doesn't mess // with the offset calibration bool old_use_index = config_.use_index; config_.use_index = false; float voltage_magnitude; if (axis_->motor_.config_.motor_type == MOTOR_TYPE_HIGH_CURRENT) voltage_magnitude = axis_->motor_.config_.calibration_current * axis_->motor_.config_.phase_resistance; else if (axis_->motor_.config_.motor_type == MOTOR_TYPE_GIMBAL) voltage_magnitude = axis_->motor_.config_.calibration_current; else return false; // go to motor zero phase for start_lock_duration to get ready to scan int i = 0; axis_->run_control_loop([&](){ if (!axis_->motor_.enqueue_voltage_timings(voltage_magnitude, 0.0f)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); return ++i < start_lock_duration * current_meas_hz; }); if (axis_->error_ != Axis::ERROR_NONE) return false; int32_t init_enc_val = shadow_count_; int64_t encvaluesum = 0; // scan forward i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(scan_distance * (float)i / (float)num_steps - scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float expected_encoder_delta = scan_distance / elec_rad_per_enc; float actual_encoder_delta_abs = fabsf(shadow_count_-init_enc_val); if(fabsf(actual_encoder_delta_abs - expected_encoder_delta)/expected_encoder_delta > config_.calib_range) { set_error(ERROR_CPR_OUT_OF_RANGE); return false; } // check direction if (shadow_count_ > init_enc_val + 8) { // motor same dir as encoder axis_->motor_.config_.direction = 1; } else if (shadow_count_ < init_enc_val - 8) { // motor opposite dir as encoder axis_->motor_.config_.direction = -1; } else { // Encoder response error set_error(ERROR_RESPONSE); return false; } // scan backwards i = 0; axis_->run_control_loop([&](){ float phase = wrap_pm_pi(-scan_distance * (float)i / (float)num_steps + scan_distance / 2.0f); float v_alpha = voltage_magnitude * arm_cos_f32(phase); float v_beta = voltage_magnitude * arm_sin_f32(phase); if (!axis_->motor_.enqueue_voltage_timings(v_alpha, v_beta)) return false; // error set inside enqueue_voltage_timings axis_->motor_.log_timing(Motor::TIMING_LOG_ENC_CALIB); encvaluesum += shadow_count_; return ++i < num_steps; }); if (axis_->error_ != Axis::ERROR_NONE) return false; offset_ = encvaluesum / (num_steps * 2); config_.offset = offset_; int32_t residual = encvaluesum - ((int64_t)offset_ * (int64_t)(num_steps * 2)); config_.offset_float = (float)residual / (float)(num_steps * 2) + 0.5f; // add 0.5 to center-align state to phase is_ready_ = true; config_.use_index = old_use_index; return true; } static bool decode_hall(uint8_t hall_state, int32_t* hall_cnt) { switch (hall_state) { case 0b001: *hall_cnt = 0; return true; case 0b011: *hall_cnt = 1; return true; case 0b010: *hall_cnt = 2; return true; case 0b110: *hall_cnt = 3; return true; case 0b100: *hall_cnt = 4; return true; case 0b101: *hall_cnt = 5; return true; default: return false; } } bool Encoder::update() { // Check that we don't get problems with discrete time approximation if (!(current_meas_period * pll_kp_ < 1.0f)) { set_error(ERROR_UNSTABLE_GAIN); return false; } // update internal encoder state. int32_t delta_enc = 0; switch (config_.mode) { case MODE_INCREMENTAL: { //TODO: use count_in_cpr_ instead as shadow_count_ can overflow //or use 64 bit int16_t delta_enc_16 = (int16_t)hw_config_.timer->Instance->CNT - (int16_t)shadow_count_; delta_enc = (int32_t)delta_enc_16; //sign extend } break; case MODE_HALL: { int32_t hall_cnt; if (decode_hall(hall_state_, &hall_cnt)) { delta_enc = hall_cnt - count_in_cpr_; delta_enc = mod(delta_enc, 6); if (delta_enc > 3) delta_enc -= 6; } else { set_error(ERROR_ILLEGAL_HALL_STATE); return false; } } break; default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); return false; } break; } shadow_count_ += delta_enc; count_in_cpr_ += delta_enc; count_in_cpr_ = mod(count_in_cpr_, config_.cpr); //// run pll (for now pll is in units of encoder counts) // Predict current pos pos_estimate_ += current_meas_period * pll_vel_; pos_cpr_ += current_meas_period * pll_vel_; // discrete phase detector float delta_pos = (float)(shadow_count_ - (int32_t)floorf(pos_estimate_)); float delta_pos_cpr = (float)(count_in_cpr_ - (int32_t)floorf(pos_cpr_)); delta_pos_cpr = wrap_pm(delta_pos_cpr, 0.5f * (float)(config_.cpr)); // pll feedback pos_estimate_ += current_meas_period * pll_kp_ * delta_pos; pos_cpr_ += current_meas_period * pll_kp_ * delta_pos_cpr; pos_cpr_ = fmodf_pos(pos_cpr_, (float)(config_.cpr)); pll_vel_ += current_meas_period * pll_ki_ * delta_pos_cpr; bool snap_to_zero_vel = false; if (fabsf(pll_vel_) < 0.5f * current_meas_period * pll_ki_) { pll_vel_ = 0.0f; //align delta-sigma on zero to prevent jitter snap_to_zero_vel = true; } //// run encoder count interpolation int32_t corrected_enc = count_in_cpr_ - offset_; // if we are stopped, make sure we don't randomly drift if (snap_to_zero_vel) { interpolation_ = 0.5f; // reset interpolation if encoder edge comes } else if (delta_enc > 0) { interpolation_ = 0.0f; } else if (delta_enc < 0) { interpolation_ = 1.0f; } else { // Interpolate (predict) between encoder counts using pll_vel, interpolation_ += current_meas_period * pll_vel_; // don't allow interpolation indicated position outside of [enc, enc+1) if (interpolation_ > 1.0f) interpolation_ = 1.0f; if (interpolation_ < 0.0f) interpolation_ = 0.0f; } float interpolated_enc = corrected_enc + interpolation_; //// compute electrical phase //TODO avoid recomputing elec_rad_per_enc every time float elec_rad_per_enc = axis_->motor_.config_.pole_pairs * 2 * M_PI * (1.0f / (float)(config_.cpr)); float ph = elec_rad_per_enc * (interpolated_enc - config_.offset_float); // ph = fmodf(ph, 2*M_PI); phase_ = wrap_pm_pi(ph); return true; } <|endoftext|>
<commit_before>#include <headers/bruteforcecrack.h> #include <headers/md5.h> #include <QFuture> #include <QThread> #include <QtConcurrent/QtConcurrent> #include <QtConcurrent/QtConcurrentRun> #include <QtConcurrent/qtconcurrentrun.h> //base conversion: http://stackoverflow.com/questions/8870121/c-template-for-conversion-between-decimal-and-arbitrary-base#8870154 std::string foundValue; bool finished; std::string incrementStringW(std::string in){ char z = 'z'; if(!in.compare("")){ return in.append("a"); } else if(in[in.length()-1] == z){ in.resize(in.length()-1); in = ::incrementStringW(in); in.append("a"); return in; } else{ char r = in[in.length()-1] +1; in[in.length()-1] = r; return in; } } void worker(std::string begin, std::string end, Hash *whash, std::string d){ std::string plaintextGuess = begin; while(!finished) { whash->plaintext = plaintextGuess; whash->compute(); if(d.compare(whash->digest) == 0) { foundValue = plaintextGuess; finished = true; break; } plaintextGuess = incrementStringW(plaintextGuess); std::cout<<plaintextGuess<<std::endl; if(plaintextGuess.compare(end) == 0){ break; } } } /** * Set the desired hash method. * @brief BruteForceCrack::BruteForceCrack * @param h the hash method to use: MD5, SHA, etc. */ BruteForceCrack::BruteForceCrack(Hash* h, std::string alph, int chCount) { hashType = h; alphabet = alph; charCount = chCount; } /** * Reverses a hash using brute force. The idea is to count to * (alphabet length)^(password length) in base (alphabet length). This * ensures that every possible combination of the alphabet is guessed. * @brief BruteForceCrack::reverse * @param charCount user-specified password length * @return length,time pair if successful, max length,time if unsuccessful. */ QPointF BruteForceCrack::reverse() { plaintext = ""; foundValue = ""; finished = false; if(hashType == NULL) { return QPointF(-1,-1); } int range = alphabet.length(); //watch out for overflow errors here n = (unsigned long)pow(range, charCount); if(n == 0) { std::cout << "Avoiding overflow error! Setting n to max value: " << std::numeric_limits<unsigned long>::max() << std::endl; n = std::numeric_limits<unsigned long>::max(); } std::string plaintextGuess = begin; QElapsedTimer timer; long elapsed; //Thread stuff starts here. int threads = QThread::idealThreadCount(); std::vector<QFuture<void>> t; int tot = threads; //threads = 1; int amtChar = range / threads; std::string a = "a"; while(threads != 0){ std::string b = ""; for( int i = 0; i < amtChar; i++){ b = b + "a"; } Hash* newH = new Md5(); /*QFuture<void> temp = */QtConcurrent::run(::worker, a, b, newH ,digest); //t.assign(1, temp); a = b; threads--; } timer.start(); while(!finished); elapsed = timer.elapsed(); plaintext = foundValue; std::cout<<"Hi"<<std::endl; return QPointF(charCount, elapsed); } /** * Converts decimal number into given base. * @brief BruteForceCrack::baseTenToBaseN * @param num number to convert * @param base base to convert to. * @return number converted to given base. */ std::string BruteForceCrack::baseTenToBaseN(unsigned long num, unsigned int base) { if(base == 0) { //lazy fix to avoid divide by zero return "Divide by zero!!!"; } std::string result; while(num) { result += alphabet.at(num % base); num /= base; } return std::string(result.rbegin(), result.rend()); //reverse string } void BruteForceCrack::setOptions(unsigned int words, unsigned int endDigits, unsigned int preDigits, bool symb, bool cap, bool complete) { std::cout << "Incorrect usage of crack class. This method is for DictionaryCrack." << std::endl; } /** * Increments a stirng by the next lowercase character. * @brief BruteForceCrack::incrementString * @param in * @return */ std::string BruteForceCrack::incrementString(std::string in){ char z = 'z'; if(!in.compare("")){ return in.append("a"); } else if(in[in.length()-1] == z){ in.resize(in.length()-1); in = BruteForceCrack::incrementString(in); in.append("a"); return in; } else{ char r = in[in.length()-1] +1; in[in.length()-1] = r; return in; } } <commit_msg>completing merge<commit_after>#include <headers/bruteforcecrack.h> #include <headers/md5.h> #include <QFuture> #include <QThread> #include <QtConcurrent/QtConcurrent> #include <QtConcurrent/QtConcurrentRun> #include <QtConcurrent/qtconcurrentrun.h> //base conversion: http://stackoverflow.com/questions/8870121/c-template-for-conversion-between-decimal-and-arbitrary-base#8870154 std::string foundValue; bool finished; std::string incrementStringW(std::string in, std::string alpha){ char z = alpha[alpha.size()-1]; if(!in.compare("")){ return in.append("a"); } else if(in[in.length()-1] == z){ in.resize(in.length()-1); in = ::incrementStringW(in, alpha); in.append("a"); return in; } else{ char r = in[in.length()-1]; int i = alpha.find(r); r = alpha[ i + 1 ]; in[in.length()-1] = r; return in; } } void worker(std::string begin, std::string end, Hash *whash, std::string d, std::string alpha){ std::string plaintextGuess = begin; while(!finished) { whash->plaintext = plaintextGuess; whash->compute(); if(d.compare(whash->digest) == 0) { foundValue = plaintextGuess; finished = true; break; } plaintextGuess = incrementStringW(plaintextGuess, alpha); std::cout<<plaintextGuess<<std::endl; if(plaintextGuess.compare(end) == 0){ break; } } } /** * Set the desired hash method. * @brief BruteForceCrack::BruteForceCrack * @param h the hash method to use: MD5, SHA, etc. */ BruteForceCrack::BruteForceCrack(Hash* h, std::string alph, int chCount) { hashType = h; alphabet = alph; charCount = chCount; } /** * Reverses a hash using brute force. The idea is to count to * (alphabet length)^(password length) in base (alphabet length). This * ensures that every possible combination of the alphabet is guessed. * @brief BruteForceCrack::reverse * @param charCount user-specified password length * @return length,time pair if successful, max length,time if unsuccessful. */ QPointF BruteForceCrack::reverse() { plaintext = ""; foundValue = ""; finished = false; if(hashType == NULL) { return QPointF(-1,-1); } int range = alphabet.length(); //watch out for overflow errors here n = (unsigned long)pow(range, charCount); if(n == 0) { std::cout << "Avoiding overflow error! Setting n to max value: " << std::numeric_limits<unsigned long>::max() << std::endl; n = std::numeric_limits<unsigned long>::max(); } std::string plaintextGuess = begin; QElapsedTimer timer; long elapsed; //Thread stuff starts here. int threads = QThread::idealThreadCount(); std::vector<QFuture<void>> t; int tot = threads; //threads = 1; int amtChar = range / threads; std::string a = "a"; while(threads != 0){ std::string b = ""; for( int i = 0; i < amtChar; i++){ b = b + "a"; } Hash* newH = new Md5(); /*QFuture<void> temp = */QtConcurrent::run(::worker, a, b, newH ,digest, alphabet); //t.assign(1, temp); a = b; threads--; } timer.start(); while(!finished); elapsed = timer.elapsed(); plaintext = foundValue; std::cout<<"Hi"<<std::endl; return QPointF(charCount, elapsed); } /** * Converts decimal number into given base. * @brief BruteForceCrack::baseTenToBaseN * @param num number to convert * @param base base to convert to. * @return number converted to given base. */ std::string BruteForceCrack::baseTenToBaseN(unsigned long num, unsigned int base) { if(base == 0) { //lazy fix to avoid divide by zero return "Divide by zero!!!"; } std::string result; while(num) { result += alphabet.at(num % base); num /= base; } return std::string(result.rbegin(), result.rend()); //reverse string } void BruteForceCrack::setOptions(unsigned int words, unsigned int endDigits, unsigned int preDigits, bool symb, bool cap, bool complete) { std::cout << "Incorrect usage of crack class. This method is for DictionaryCrack." << std::endl; } /** * Increments a stirng by the next lowercase character. * @brief BruteForceCrack::incrementString * @param in * @return */ std::string BruteForceCrack::incrementString(std::string in){ char z = 'z'; if(!in.compare("")){ return in.append("a"); } else if(in[in.length()-1] == z){ in.resize(in.length()-1); in = BruteForceCrack::incrementString(in); in.append("a"); return in; } else{ char r = in[in.length()-1] +1; in[in.length()-1] = r; return in; } } <|endoftext|>
<commit_before>#include "mitkSlicedGeometry3D.h" #include "mitkPlaneGeometry.h" #include <vecmath.h> #include <vtkTransform.h> #ifdef MBI_INTERNAL extern "C" { #include "ipDicom.h" } #endif //##ModelId=3DCBF50C0377 mitk::Geometry2D* mitk::SlicedGeometry3D::GetGeometry2D(int s) const { mitk::Geometry2D::Pointer geometry2d = NULL; if(IsValidSlice(s)) { geometry2d = m_Geometry2Ds[s]; //If (a) m_EvenlySpaced==true, (b) we don't have a Geometry2D stored //for the requested slice, and (c) the first slice (s=0) //is a PlaneGeometry instance, then we calculate the geometry of the //requested as the plane of the first slice shifted by m_Spacing.z*s //in the direction of m_DirectionVector. if((m_EvenlySpaced) && (geometry2d.IsNull())) { PlaneGeometry* firstslice=dynamic_cast<PlaneGeometry*> (m_Geometry2Ds[0].GetPointer()); if(firstslice != NULL) { mitk::PlaneView view=firstslice->GetPlaneView(); if((m_DirectionVector.x==0) && (m_DirectionVector.y==0) && (m_DirectionVector.z==0)) { m_DirectionVector=view.normal; m_DirectionVector.normalize(); } Vector3D direction; direction = m_DirectionVector*m_Spacing.z; mitk::PlaneGeometry::Pointer requestedslice; requestedslice = mitk::PlaneGeometry::New(); requestedslice->Initialize(); requestedslice->SetTimeBoundsInMS(firstslice->GetTimeBoundsInMS()); view.point+=direction*s; requestedslice->SetPlaneView(view); requestedslice->SetThickness(firstslice->GetThickness()); geometry2d = requestedslice; m_Geometry2Ds[s] = geometry2d; } } } else return NULL; return geometry2d; } //##ModelId=3DCBF5D40253 const mitk::BoundingBox* mitk::SlicedGeometry3D::GetBoundingBox() const { mitk::BoundingBox::Pointer boundingBox=mitk::BoundingBox::New(); mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New(); mitk::ScalarType nullpoint[]={0,0,0}; mitk::BoundingBox::PointType p(nullpoint); unsigned int s; mitk::Geometry2D* geometry2d; mitk::BoundingBox::ConstPointer nextBoundingBox; mitk::BoundingBox::PointIdentifier pointid=0; for(s=0; s<m_Slices; ++s) { geometry2d = GetGeometry2D(s); assert(geometry2d!=NULL); nextBoundingBox = geometry2d->GetBoundingBox(); const mitk::BoundingBox::PointsContainer * nextPoints = nextBoundingBox->GetPoints(); if(nextPoints!=NULL) { mitk::BoundingBox::PointsContainer::ConstIterator pointsIt = nextPoints->Begin(); while (pointsIt != nextPoints->End() ) { pointscontainer->InsertElement( pointid++, pointsIt->Value()); ++pointsIt; } } } boundingBox->SetPoints(pointscontainer); boundingBox->ComputeBoundingBox(); m_BoundingBox=boundingBox; return boundingBox.GetPointer(); } //##ModelId=3DCBC65C017C const float* mitk::SlicedGeometry3D::GetSpacing() const { return &m_Spacing.x; } //##ModelId=3E15578402BD bool mitk::SlicedGeometry3D::SetGeometry2D(mitk::Geometry2D* geometry2D, int s) { if(IsValidSlice(s)) { m_Geometry2Ds[s]=geometry2D; return true; } return false; } //##ModelId=3E155839024F bool mitk::SlicedGeometry3D::SetGeometry2D(ipPicDescriptor* pic, int s) { if((pic!=NULL) && (IsValidSlice(s))) { //construct standard view mitk::Point3D origin, right, bottom; origin.set(0,0,s); UnitsToMM(origin, origin); right.set(pic->n[0],0,0); UnitsToMM(right, right); bottom.set(0,pic->n[1],0); UnitsToMM(bottom, bottom); PlaneView view_std(origin, right, bottom); mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New(); planegeometry->SetPlaneView(view_std); planegeometry->SetThicknessBySpacing(&m_Spacing); planegeometry->SetSizeInUnits(pic->n[0], pic->n[1]); SetGeometry2D(planegeometry, s); return true; } return false; } //##ModelId=3E3453C703AF void mitk::SlicedGeometry3D::Initialize(unsigned int slices) { Superclass::Initialize(); m_Slices = slices; m_Geometry2Ds.clear(); Geometry2D::Pointer gnull=NULL; m_Geometry2Ds.reserve(m_Slices); m_Geometry2Ds.assign(m_Slices, gnull); //initialize m_TransformOfOrigin and m_Spacing (and m_TransformUnitsToMM/m_TransformMMToUnits). m_TransformOfOrigin.setIdentity(); SetSpacing(Vector3D(1.0,1.0,1.0)); } //##ModelId=3E15572E0269 mitk::SlicedGeometry3D::SlicedGeometry3D() : m_Slices(0), m_EvenlySpaced(true) { Initialize(m_Slices); } //##ModelId=3E3456C50067 mitk::SlicedGeometry3D::~SlicedGeometry3D() { } //##ModelId=3E3BE1F10106 bool mitk::SlicedGeometry3D::IsValidSlice(int s) const { return ((s>=0) && (s<(int)m_Slices)); } //##ModelId=3E3BE8CF010E /** * @warning the values of passe the spacing parameter are not checked for correctness! * When passing wrong values application can hang and/or crash --> * @todo Implement tests! */ void mitk::SlicedGeometry3D::SetSpacing(mitk::Vector3D aSpacing) { bool hasEvenlySpacedPlaneGeometry=false; mitk::Point3D origin, rightDV, bottomDV; unsigned int width, height; mitk::ScalarType thickness; //in case of evenly-spaced data: re-initialize instances of Geometry2D, since the spacing influences them if((m_EvenlySpaced) && (m_Geometry2Ds.size()>0)) { mitk::Geometry2D::ConstPointer firstGeometry = m_Geometry2Ds[0].GetPointer(); const PlaneGeometry* constplanegeometry=dynamic_cast<const PlaneGeometry*>(firstGeometry.GetPointer()); if(constplanegeometry != NULL) { MMToUnits(constplanegeometry->GetPlaneView().point, origin); MMToUnits(constplanegeometry->GetPlaneView().getOrientation1(), rightDV); MMToUnits(constplanegeometry->GetPlaneView().getOrientation2(), bottomDV); width = constplanegeometry->GetWidthInUnits(); height = constplanegeometry->GetHeightInUnits(); thickness = constplanegeometry->GetThickness(); hasEvenlySpacedPlaneGeometry=true; } } m_Spacing = aSpacing; m_TransformUnitsToMM=m_TransformOfOrigin; mitk::Vector4D col; m_TransformUnitsToMM.getColumn(0, &col); col*=aSpacing.x; m_TransformUnitsToMM.setColumn(0, col); m_TransformUnitsToMM.getColumn(1, &col); col*=aSpacing.y; m_TransformUnitsToMM.setColumn(1, col); m_TransformUnitsToMM.getColumn(2, &col); col*=aSpacing.z; m_TransformUnitsToMM.setColumn(2, col); m_TransformMMToUnits.invert(m_TransformUnitsToMM); //re-initialize the bounding box, since the spacing influences the size of the bounding box m_BoundingBox = NULL; mitk::Geometry2D::Pointer firstGeometry; //in case of evenly-spaced data: re-initialize instances of Geometry2D, since the spacing influences them if(hasEvenlySpacedPlaneGeometry) { //create planegeometry according to new spacing UnitsToMM(origin, origin); UnitsToMM(rightDV, rightDV); UnitsToMM(bottomDV, bottomDV); PlaneView view_std(origin, origin+rightDV, origin+bottomDV); mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New(); planegeometry->SetPlaneView(view_std); planegeometry->SetSizeInUnits(width, height); planegeometry->SetThickness(thickness); firstGeometry = planegeometry; } else if((m_EvenlySpaced) && (m_Geometry2Ds.size()>0)) firstGeometry = m_Geometry2Ds[0].GetPointer(); //clear and reserve m_Geometry2Ds.clear(); Geometry2D::Pointer gnull=NULL; m_Geometry2Ds.reserve(m_Slices); m_Geometry2Ds.assign(m_Slices, gnull); if(m_Slices>0) m_Geometry2Ds[0] = firstGeometry; Modified(); } void mitk::SlicedGeometry3D::SetSpacing(const float aSpacing[3]) { mitk::Vector3D tmp(aSpacing[0], aSpacing[1], aSpacing[2]); SetSpacing(tmp); } //##ModelId=3E3C13F802A6 void mitk::SlicedGeometry3D::SetEvenlySpaced(bool on) { m_EvenlySpaced=on; Modified(); } //##ModelId=3E3C2C37031B void mitk::SlicedGeometry3D::SetSpacing(ipPicDescriptor* pic) { Vector3D spacing(m_Spacing); ipPicTSV_t *tsv; tsv = ipPicQueryTag( pic, "PIXEL SIZE" ); if(tsv) { if((tsv->dim*tsv->n[0]>=3) && (tsv->type==ipPicFloat)) { if(tsv->bpe==32) spacing.set(((ipFloat4_t*)tsv->value)[0], ((ipFloat4_t*)tsv->value)[1],((ipFloat4_t*)tsv->value)[2]); else if(tsv->bpe==64) spacing.set(((ipFloat8_t*)tsv->value)[0], ((ipFloat8_t*)tsv->value)[1],((ipFloat8_t*)tsv->value)[2]); } } #ifdef MBI_INTERNAL else { tsv = ipPicQueryTag( pic, "SOURCE HEADER" ); if( tsv ) { void *data; ipUInt4_t len; ipFloat8_t spacing_z = 0; ipFloat8_t thickness = 1; ipFloat8_t fx = 1; ipFloat8_t fy = 1; if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0088, &data, &len ) ) { sscanf( (char *) data, "%lf", &spacing ); itkDebugMacro( "spacing: %5.2f mm\n" << spacing_z ); } if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0050, &data, &len ) ) { sscanf( (char *) data, "%lf", &thickness ); itkDebugMacro( "thickness: %5.2f mm\n" << thickness ); if( thickness == 0 ) thickness = 1; } if( dicomFindElement( (unsigned char *) tsv->value, 0x0028, 0x0030, &data, &len ) && len>0 && ((char *)data)[0] ) { sscanf( (char *) data, "%lf\\%lf", &fy, &fx ); // row / column value itkDebugMacro( "fx, fy: %5.2f/%5.2f mm\n" << fx << fy ); } spacing.set(fx, fy,( spacing_z > 0 ? spacing_z : thickness)); } } #endif // @FIXME: // nur fuer Testdatensatz // spacing = Vector3D(1/3.0,1/4.0,1/5.0); SetSpacing(spacing); } void mitk::SlicedGeometry3D::SetDirectionVector(const mitk::Vector3D& directionVector) { if(Vector3D(m_DirectionVector-directionVector).lengthSquared()>=0.0001) { m_DirectionVector = directionVector; m_DirectionVector.normalize(); Modified(); } } void mitk::SlicedGeometry3D::SetTimeBoundsInMS(const mitk::TimeBounds& timebounds) { Superclass::SetTimeBoundsInMS(timebounds); int s; for(s=0; s<m_Slices; ++s) { if(m_Geometry2Ds[s]!=NULL) { m_Geometry2Ds[s]->SetTimeBoundsInMS(timebounds); } } m_TimeBoundsInMS = timebounds; } mitk::Geometry3D::Pointer mitk::SlicedGeometry3D::Clone() const { mitk::SlicedGeometry3D::Pointer newGeometry = SlicedGeometry3D::New(); newGeometry->Initialize(m_Slices); newGeometry->SetTimeBoundsInMS(m_TimeBoundsInMS); newGeometry->GetTransform()->SetMatrix(m_Transform->GetMatrix()); //newGeometry->GetRelativeTransform()->SetMatrix(m_RelativeTransform->GetMatrix()); newGeometry->SetEvenlySpaced(m_EvenlySpaced); newGeometry->SetSpacing(GetSpacing()); unsigned int s; for(s=0; s<m_Slices; ++s) { if(m_Geometry2Ds[s]==NULL) { assert(m_EvenlySpaced); } else { Geometry3D::Pointer geometry = m_Geometry2Ds[s]->Clone(); Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry.GetPointer()); assert(geometry2d!=NULL); newGeometry->SetGeometry2D(geometry2d, s); } } return newGeometry.GetPointer(); } <commit_msg>clone bug fixed: added missing transfer of m_DirectionVector<commit_after>#include "mitkSlicedGeometry3D.h" #include "mitkPlaneGeometry.h" #include <vecmath.h> #include <vtkTransform.h> #ifdef MBI_INTERNAL extern "C" { #include "ipDicom.h" } #endif //##ModelId=3DCBF50C0377 mitk::Geometry2D* mitk::SlicedGeometry3D::GetGeometry2D(int s) const { mitk::Geometry2D::Pointer geometry2d = NULL; if(IsValidSlice(s)) { geometry2d = m_Geometry2Ds[s]; //If (a) m_EvenlySpaced==true, (b) we don't have a Geometry2D stored //for the requested slice, and (c) the first slice (s=0) //is a PlaneGeometry instance, then we calculate the geometry of the //requested as the plane of the first slice shifted by m_Spacing.z*s //in the direction of m_DirectionVector. if((m_EvenlySpaced) && (geometry2d.IsNull())) { PlaneGeometry* firstslice=dynamic_cast<PlaneGeometry*> (m_Geometry2Ds[0].GetPointer()); if(firstslice != NULL) { mitk::PlaneView view=firstslice->GetPlaneView(); if((m_DirectionVector.x==0) && (m_DirectionVector.y==0) && (m_DirectionVector.z==0)) { m_DirectionVector=view.normal; m_DirectionVector.normalize(); } Vector3D direction; direction = m_DirectionVector*m_Spacing.z; mitk::PlaneGeometry::Pointer requestedslice; requestedslice = mitk::PlaneGeometry::New(); requestedslice->Initialize(); requestedslice->SetTimeBoundsInMS(firstslice->GetTimeBoundsInMS()); view.point+=direction*s; requestedslice->SetPlaneView(view); requestedslice->SetThickness(firstslice->GetThickness()); geometry2d = requestedslice; m_Geometry2Ds[s] = geometry2d; } } } else return NULL; return geometry2d; } //##ModelId=3DCBF5D40253 const mitk::BoundingBox* mitk::SlicedGeometry3D::GetBoundingBox() const { mitk::BoundingBox::Pointer boundingBox=mitk::BoundingBox::New(); mitk::BoundingBox::PointsContainer::Pointer pointscontainer=mitk::BoundingBox::PointsContainer::New(); mitk::ScalarType nullpoint[]={0,0,0}; mitk::BoundingBox::PointType p(nullpoint); unsigned int s; mitk::Geometry2D* geometry2d; mitk::BoundingBox::ConstPointer nextBoundingBox; mitk::BoundingBox::PointIdentifier pointid=0; for(s=0; s<m_Slices; ++s) { geometry2d = GetGeometry2D(s); assert(geometry2d!=NULL); nextBoundingBox = geometry2d->GetBoundingBox(); const mitk::BoundingBox::PointsContainer * nextPoints = nextBoundingBox->GetPoints(); if(nextPoints!=NULL) { mitk::BoundingBox::PointsContainer::ConstIterator pointsIt = nextPoints->Begin(); while (pointsIt != nextPoints->End() ) { pointscontainer->InsertElement( pointid++, pointsIt->Value()); ++pointsIt; } } } boundingBox->SetPoints(pointscontainer); boundingBox->ComputeBoundingBox(); m_BoundingBox=boundingBox; return boundingBox.GetPointer(); } //##ModelId=3DCBC65C017C const float* mitk::SlicedGeometry3D::GetSpacing() const { return &m_Spacing.x; } //##ModelId=3E15578402BD bool mitk::SlicedGeometry3D::SetGeometry2D(mitk::Geometry2D* geometry2D, int s) { if(IsValidSlice(s)) { m_Geometry2Ds[s]=geometry2D; return true; } return false; } //##ModelId=3E155839024F bool mitk::SlicedGeometry3D::SetGeometry2D(ipPicDescriptor* pic, int s) { if((pic!=NULL) && (IsValidSlice(s))) { //construct standard view mitk::Point3D origin, right, bottom; origin.set(0,0,s); UnitsToMM(origin, origin); right.set(pic->n[0],0,0); UnitsToMM(right, right); bottom.set(0,pic->n[1],0); UnitsToMM(bottom, bottom); PlaneView view_std(origin, right, bottom); mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New(); planegeometry->SetPlaneView(view_std); planegeometry->SetThicknessBySpacing(&m_Spacing); planegeometry->SetSizeInUnits(pic->n[0], pic->n[1]); SetGeometry2D(planegeometry, s); return true; } return false; } //##ModelId=3E3453C703AF void mitk::SlicedGeometry3D::Initialize(unsigned int slices) { Superclass::Initialize(); m_Slices = slices; m_Geometry2Ds.clear(); Geometry2D::Pointer gnull=NULL; m_Geometry2Ds.reserve(m_Slices); m_Geometry2Ds.assign(m_Slices, gnull); //initialize m_TransformOfOrigin and m_Spacing (and m_TransformUnitsToMM/m_TransformMMToUnits). m_TransformOfOrigin.setIdentity(); SetSpacing(Vector3D(1.0,1.0,1.0)); } //##ModelId=3E15572E0269 mitk::SlicedGeometry3D::SlicedGeometry3D() : m_Slices(0), m_EvenlySpaced(true) { Initialize(m_Slices); } //##ModelId=3E3456C50067 mitk::SlicedGeometry3D::~SlicedGeometry3D() { } //##ModelId=3E3BE1F10106 bool mitk::SlicedGeometry3D::IsValidSlice(int s) const { return ((s>=0) && (s<(int)m_Slices)); } //##ModelId=3E3BE8CF010E /** * @warning the values of passe the spacing parameter are not checked for correctness! * When passing wrong values application can hang and/or crash --> * @todo Implement tests! */ void mitk::SlicedGeometry3D::SetSpacing(mitk::Vector3D aSpacing) { bool hasEvenlySpacedPlaneGeometry=false; mitk::Point3D origin, rightDV, bottomDV; unsigned int width, height; mitk::ScalarType thickness; //in case of evenly-spaced data: re-initialize instances of Geometry2D, since the spacing influences them if((m_EvenlySpaced) && (m_Geometry2Ds.size()>0)) { mitk::Geometry2D::ConstPointer firstGeometry = m_Geometry2Ds[0].GetPointer(); const PlaneGeometry* constplanegeometry=dynamic_cast<const PlaneGeometry*>(firstGeometry.GetPointer()); if(constplanegeometry != NULL) { MMToUnits(constplanegeometry->GetPlaneView().point, origin); MMToUnits(constplanegeometry->GetPlaneView().getOrientation1(), rightDV); MMToUnits(constplanegeometry->GetPlaneView().getOrientation2(), bottomDV); width = constplanegeometry->GetWidthInUnits(); height = constplanegeometry->GetHeightInUnits(); thickness = constplanegeometry->GetThickness(); hasEvenlySpacedPlaneGeometry=true; } } m_Spacing = aSpacing; m_TransformUnitsToMM=m_TransformOfOrigin; mitk::Vector4D col; m_TransformUnitsToMM.getColumn(0, &col); col*=aSpacing.x; m_TransformUnitsToMM.setColumn(0, col); m_TransformUnitsToMM.getColumn(1, &col); col*=aSpacing.y; m_TransformUnitsToMM.setColumn(1, col); m_TransformUnitsToMM.getColumn(2, &col); col*=aSpacing.z; m_TransformUnitsToMM.setColumn(2, col); m_TransformMMToUnits.invert(m_TransformUnitsToMM); //re-initialize the bounding box, since the spacing influences the size of the bounding box m_BoundingBox = NULL; mitk::Geometry2D::Pointer firstGeometry; //in case of evenly-spaced data: re-initialize instances of Geometry2D, since the spacing influences them if(hasEvenlySpacedPlaneGeometry) { //create planegeometry according to new spacing UnitsToMM(origin, origin); UnitsToMM(rightDV, rightDV); UnitsToMM(bottomDV, bottomDV); PlaneView view_std(origin, origin+rightDV, origin+bottomDV); mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New(); planegeometry->SetPlaneView(view_std); planegeometry->SetSizeInUnits(width, height); planegeometry->SetThickness(thickness); firstGeometry = planegeometry; } else if((m_EvenlySpaced) && (m_Geometry2Ds.size()>0)) firstGeometry = m_Geometry2Ds[0].GetPointer(); //clear and reserve m_Geometry2Ds.clear(); Geometry2D::Pointer gnull=NULL; m_Geometry2Ds.reserve(m_Slices); m_Geometry2Ds.assign(m_Slices, gnull); if(m_Slices>0) m_Geometry2Ds[0] = firstGeometry; Modified(); } void mitk::SlicedGeometry3D::SetSpacing(const float aSpacing[3]) { mitk::Vector3D tmp(aSpacing[0], aSpacing[1], aSpacing[2]); SetSpacing(tmp); } //##ModelId=3E3C13F802A6 void mitk::SlicedGeometry3D::SetEvenlySpaced(bool on) { m_EvenlySpaced=on; Modified(); } //##ModelId=3E3C2C37031B void mitk::SlicedGeometry3D::SetSpacing(ipPicDescriptor* pic) { Vector3D spacing(m_Spacing); ipPicTSV_t *tsv; tsv = ipPicQueryTag( pic, "PIXEL SIZE" ); if(tsv) { if((tsv->dim*tsv->n[0]>=3) && (tsv->type==ipPicFloat)) { if(tsv->bpe==32) spacing.set(((ipFloat4_t*)tsv->value)[0], ((ipFloat4_t*)tsv->value)[1],((ipFloat4_t*)tsv->value)[2]); else if(tsv->bpe==64) spacing.set(((ipFloat8_t*)tsv->value)[0], ((ipFloat8_t*)tsv->value)[1],((ipFloat8_t*)tsv->value)[2]); } } #ifdef MBI_INTERNAL else { tsv = ipPicQueryTag( pic, "SOURCE HEADER" ); if( tsv ) { void *data; ipUInt4_t len; ipFloat8_t spacing_z = 0; ipFloat8_t thickness = 1; ipFloat8_t fx = 1; ipFloat8_t fy = 1; if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0088, &data, &len ) ) { sscanf( (char *) data, "%lf", &spacing ); itkDebugMacro( "spacing: %5.2f mm\n" << spacing_z ); } if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0050, &data, &len ) ) { sscanf( (char *) data, "%lf", &thickness ); itkDebugMacro( "thickness: %5.2f mm\n" << thickness ); if( thickness == 0 ) thickness = 1; } if( dicomFindElement( (unsigned char *) tsv->value, 0x0028, 0x0030, &data, &len ) && len>0 && ((char *)data)[0] ) { sscanf( (char *) data, "%lf\\%lf", &fy, &fx ); // row / column value itkDebugMacro( "fx, fy: %5.2f/%5.2f mm\n" << fx << fy ); } spacing.set(fx, fy,( spacing_z > 0 ? spacing_z : thickness)); } } #endif // @FIXME: // nur fuer Testdatensatz // spacing = Vector3D(1/3.0,1/4.0,1/5.0); SetSpacing(spacing); } void mitk::SlicedGeometry3D::SetDirectionVector(const mitk::Vector3D& directionVector) { if(Vector3D(m_DirectionVector-directionVector).lengthSquared()>=0.0001) { m_DirectionVector = directionVector; m_DirectionVector.normalize(); Modified(); } } void mitk::SlicedGeometry3D::SetTimeBoundsInMS(const mitk::TimeBounds& timebounds) { Superclass::SetTimeBoundsInMS(timebounds); int s; for(s=0; s<m_Slices; ++s) { if(m_Geometry2Ds[s]!=NULL) { m_Geometry2Ds[s]->SetTimeBoundsInMS(timebounds); } } m_TimeBoundsInMS = timebounds; } mitk::Geometry3D::Pointer mitk::SlicedGeometry3D::Clone() const { mitk::SlicedGeometry3D::Pointer newGeometry = SlicedGeometry3D::New(); newGeometry->Initialize(m_Slices); newGeometry->SetTimeBoundsInMS(m_TimeBoundsInMS); newGeometry->GetTransform()->SetMatrix(m_Transform->GetMatrix()); //newGeometry->GetRelativeTransform()->SetMatrix(m_RelativeTransform->GetMatrix()); newGeometry->SetEvenlySpaced(m_EvenlySpaced); newGeometry->SetSpacing(GetSpacing()); newGeometry->SetDirectionVector(GetDirectionVector()); unsigned int s; for(s=0; s<m_Slices; ++s) { if(m_Geometry2Ds[s]==NULL) { assert(m_EvenlySpaced); } else { Geometry3D::Pointer geometry = m_Geometry2Ds[s]->Clone(); Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry.GetPointer()); assert(geometry2d!=NULL); newGeometry->SetGeometry2D(geometry2d, s); } } return newGeometry.GetPointer(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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. =========================================================================*/ #include "mitkTransferFunction.h" #include "mitkImageToItk.h" #include "mitkHistogramGenerator.h" #include <itkRGBPixel.h> #include <itkScalarImageToHistogramGenerator.h> #include <vector> mitk::TransferFunction::TransferFunction() { m_ScalarOpacityFunction = vtkPiecewiseFunction::New(); m_ColorTransferFunction = vtkColorTransferFunction::New(); m_GradientOpacityFunction = vtkPiecewiseFunction::New(); this->m_ScalarOpacityFunction->Initialize(); this->m_GradientOpacityFunction->Initialize(); } mitk::TransferFunction::~TransferFunction() { } void mitk::TransferFunction::SetPoints(int channel, mitk::TransferFunction::ControlPoints points) { switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityFunction->RemoveAllPoints(); m_ScalarOpacityPoints.clear(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddPoint(channel, points[i].first, points[i].second); } break; } case 1: //gradient opacity { m_GradientOpacityFunction->RemoveAllPoints(); m_GradientOpacityPoints.clear(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddPoint(channel, points[i].first, points[i].second); } break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::SetRGBPoints(mitk::TransferFunction::RGBControlPoints rgbpoints) { m_ColorTransferFunction->RemoveAllPoints(); m_RGBPoints.clear(); for(unsigned int i=0; i<=rgbpoints.size()-1;i++) { this->AddRGBPoint(rgbpoints[i].first, rgbpoints[i].second[0], rgbpoints[i].second[1], rgbpoints[i].second[2]); } } void mitk::TransferFunction::AddPoint(int channel, double x, double value) { //std::cout<<"mitk::TransferFunction::AddPoint( "<<channel<<", "<<x<<", "<<value<<")"<<std::endl; switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityPoints.push_back(std::make_pair(x, value)); m_ScalarOpacityFunction->AddPoint(x, value); break; } case 1: //gradient opacity { m_GradientOpacityPoints.push_back(std::make_pair(x, value)); m_GradientOpacityFunction->AddPoint(x, value); break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::AddRGBPoint(double x, double r, double g, double b) { //std::cout<<"mitk::TransferFunction::AddRGBPoint( "<<x<<", "<<r<<", "<<g<<", "<<b<<")"<<std::endl; double rgb[] = {r,g,b}; m_RGBPoints.push_back(std::make_pair(x, rgb)); m_ColorTransferFunction->AddRGBPoint(x, r, g, b); } mitk::TransferFunction::ControlPoints mitk::TransferFunction::GetPoints(int channel) { switch ( channel ) { case 0: //scalar opacity { return m_ScalarOpacityPoints; } case 1: //gradient opacity { return m_GradientOpacityPoints; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } mitk::TransferFunction::RGBControlPoints mitk::TransferFunction::GetRGBPoints() { return m_RGBPoints; } void mitk::TransferFunction::ClearPoints(int channel) { switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityPoints.clear(); m_ScalarOpacityFunction->RemoveAllPoints(); break; } case 1: //gradient opacity { m_GradientOpacityPoints.clear(); m_GradientOpacityFunction->RemoveAllPoints(); break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::ClearRGBPoints() { m_RGBPoints.clear(); m_ColorTransferFunction->RemoveAllPoints(); } void mitk::TransferFunction::SetRequestedRegionToLargestPossibleRegion() { //nothing } bool mitk::TransferFunction::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::TransferFunction::VerifyRequestedRegion() { return true; } void mitk::TransferFunction::SetRequestedRegion(itk::DataObject*) { //nothing } void mitk::TransferFunction::InitializeByItkHistogram(const itk::Statistics::Histogram<double>* histogram) { m_Histogram = histogram; m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); std::cout << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; } void mitk::TransferFunction::InitializeByMitkImage( const mitk::Image * image ) { mitk::HistogramGenerator::Pointer histGen= mitk::HistogramGenerator::New(); histGen->SetImage(image); histGen->SetSize(100); histGen->ComputeHistogram(); m_Histogram = histGen->GetHistogram(); m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); //std::cout << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; } <commit_msg>FIX: fixed warning<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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. =========================================================================*/ #include "mitkTransferFunction.h" #include "mitkImageToItk.h" #include "mitkHistogramGenerator.h" #include <itkRGBPixel.h> #include <itkScalarImageToHistogramGenerator.h> #include <vector> mitk::TransferFunction::TransferFunction() { m_ScalarOpacityFunction = vtkPiecewiseFunction::New(); m_ColorTransferFunction = vtkColorTransferFunction::New(); m_GradientOpacityFunction = vtkPiecewiseFunction::New(); this->m_ScalarOpacityFunction->Initialize(); this->m_GradientOpacityFunction->Initialize(); } mitk::TransferFunction::~TransferFunction() { } void mitk::TransferFunction::SetPoints(int channel, mitk::TransferFunction::ControlPoints points) { switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityFunction->RemoveAllPoints(); m_ScalarOpacityPoints.clear(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddPoint(channel, points[i].first, points[i].second); } break; } case 1: //gradient opacity { m_GradientOpacityFunction->RemoveAllPoints(); m_GradientOpacityPoints.clear(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddPoint(channel, points[i].first, points[i].second); } break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::SetRGBPoints(mitk::TransferFunction::RGBControlPoints rgbpoints) { m_ColorTransferFunction->RemoveAllPoints(); m_RGBPoints.clear(); for(unsigned int i=0; i<=rgbpoints.size()-1;i++) { this->AddRGBPoint(rgbpoints[i].first, rgbpoints[i].second[0], rgbpoints[i].second[1], rgbpoints[i].second[2]); } } void mitk::TransferFunction::AddPoint(int channel, double x, double value) { //std::cout<<"mitk::TransferFunction::AddPoint( "<<channel<<", "<<x<<", "<<value<<")"<<std::endl; switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityPoints.push_back(std::make_pair(x, value)); m_ScalarOpacityFunction->AddPoint(x, value); break; } case 1: //gradient opacity { m_GradientOpacityPoints.push_back(std::make_pair(x, value)); m_GradientOpacityFunction->AddPoint(x, value); break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::AddRGBPoint(double x, double r, double g, double b) { //std::cout<<"mitk::TransferFunction::AddRGBPoint( "<<x<<", "<<r<<", "<<g<<", "<<b<<")"<<std::endl; double rgb[] = {r,g,b}; m_RGBPoints.push_back(std::make_pair(x, rgb)); m_ColorTransferFunction->AddRGBPoint(x, r, g, b); } mitk::TransferFunction::ControlPoints mitk::TransferFunction::GetPoints(int channel) { switch ( channel ) { case 0: //scalar opacity { return m_ScalarOpacityPoints; } case 1: //gradient opacity { return m_GradientOpacityPoints; } } } mitk::TransferFunction::RGBControlPoints mitk::TransferFunction::GetRGBPoints() { return m_RGBPoints; } void mitk::TransferFunction::ClearPoints(int channel) { switch ( channel ) { case 0: //scalar opacity { m_ScalarOpacityPoints.clear(); m_ScalarOpacityFunction->RemoveAllPoints(); break; } case 1: //gradient opacity { m_GradientOpacityPoints.clear(); m_GradientOpacityFunction->RemoveAllPoints(); break; } default: { std::cerr<<"cannot access channel "<<channel<<std::endl; } } } void mitk::TransferFunction::ClearRGBPoints() { m_RGBPoints.clear(); m_ColorTransferFunction->RemoveAllPoints(); } void mitk::TransferFunction::SetRequestedRegionToLargestPossibleRegion() { //nothing } bool mitk::TransferFunction::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::TransferFunction::VerifyRequestedRegion() { return true; } void mitk::TransferFunction::SetRequestedRegion(itk::DataObject*) { //nothing } void mitk::TransferFunction::InitializeByItkHistogram(const itk::Statistics::Histogram<double>* histogram) { m_Histogram = histogram; m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); std::cout << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; } void mitk::TransferFunction::InitializeByMitkImage( const mitk::Image * image ) { mitk::HistogramGenerator::Pointer histGen= mitk::HistogramGenerator::New(); histGen->SetImage(image); histGen->SetSize(100); histGen->ComputeHistogram(); m_Histogram = histGen->GetHistogram(); m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); //std::cout << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; } <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #define PI 3.14159265 using namespace cv; using namespace std; double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 948.6071428572; // in pixels int ERROR_MARGIN = 18; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } Point edgePoint(Mat imageDest, Point def) { int thresh = 100; Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); if(contours.size() == 0) { return def; } return contours[0][0]; } void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } int main( int argc, char** argv ) { int cap_num = atoi(argv[1]); string color = argv[2]; VideoCapture cap; if(!cap.open(cap_num)) return 1; while(1) { Mat imageSrc; cap >> imageSrc; vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; cout << "distance is: "<< distance << " "<< rotation_angle << " "<< diameter << endl; // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 4); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 5); // Center circle(tmpSource, Point(x_center,y_center), 10, Scalar(255, 255, 255), 10); imwrite("/var/www/html/mr_robot/out.jpg", tmpSource); } // int n = system("ssh root@$BBB_IP \"/root/mr_robot/tools/lab/lab_5/write 255,255,255#\""); // Show images in windows // imshow("Destination", imageDest); // imshow("Source", tmpSource); // waitKey(0); return 0; } <commit_msg>Added drive function<commit_after>#include <iostream> #include <cstring> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <string> #include <vector> #include <math.h> #include <stdlib.h> #define PI 3.14159265 using namespace cv; using namespace std; double getDistance(double realDimention, double digitalDimention) { double FOCAL_LENGTH = 948.6071428572; // in pixels int ERROR_MARGIN = 18; //pixels lost due to selection of circular shape return realDimention * FOCAL_LENGTH / (digitalDimention + ERROR_MARGIN); } Point edgePoint(Mat imageDest, Point def) { int thresh = 100; Canny(imageDest, imageDest, thresh /*threshold1*/, thresh*2 /*threshold2*/, 3/*apertureSize*/); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(imageDest, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); if(contours.size() == 0) { return def; } return contours[0][0]; } void get_color_specs(vector<vector<int> > &specs, string color){ if (!color.compare("blue")) { specs[0][0] = 100; specs[0][1] = 115; specs[0][2] = 50; specs[1][0] = 130; specs[1][1] = 255; specs[1][2] = 255; } else if (!color.compare("red")) { specs[0][0] = 0; specs[0][1] = 197; specs[0][2] = 109; specs[1][0] = 182; specs[1][1] = 255; specs[1][2] = 255; } else { specs[0][0] = 255; specs[0][1] = 255; specs[0][2] = 255; specs[1][0] = 255; specs[1][1] = 255; specs[1][2] = 255; } } void drive(double angle, double distance) { MAX_ANGLE = 45; MIN_ANGLE = 0; PWM_RANGE = 55; MIN_PWM = 200; MAX_PWM = 255; // for back wheels (might be change to respect distace to cover) double fr_left, fr_right, back; if (angle > 0){ // Go right fr_left = PWM_RANGE - (angle / MAX_ANGLE) * PWM_RANGE + MIN_PWM; fr_right = (angle / MAX_ANGLE) * PWM_RANGE + MIN_PWM; back = MAX_PWM; } else if (angle < 0) { // Go left fr_right = PWM_RANGE - (angle / MAX_ANGLE) * PWM_RANGE + MIN_PWM; fr_left = (angle / MAX_ANGLE) * PWM_RANGE + MIN_PWM; back = MAX_PWM; } else { // Go straight if (distance >= 100.0) { fr_right = MAX_PWM; fr_left = MAX_PWM; back = MAX_PWM; } else { fr_right = 200; fr_left = 200; back = 200; } } system("ssh root@$BBB_IP \"/root/mr_robot/tools/lab/lab_5/write" + fr_left + fr_right + back + "#\""); } int main( int argc, char** argv ) { int cap_num = atoi(argv[1]); string color = argv[2]; VideoCapture cap; if(!cap.open(cap_num)) return 1; while(1) { Mat imageSrc; cap >> imageSrc; vector<vector<int> > color_specs(2, vector<int>(3)); get_color_specs(color_specs, color); // HSV low-high values int lowH = color_specs[0][0]; int highH = color_specs[1][0]; int lowS = color_specs[0][1]; int highS = color_specs[1][1]; int lowV = color_specs[0][2]; int highV = color_specs[1][2]; // Destination image Mat imageDest; // Convert BGR to HSV cvtColor(imageSrc, imageDest, COLOR_BGR2HSV); // Get colors in specified range inRange(imageDest, Scalar(lowH, lowS, lowV), Scalar(highH, highS, highV), imageDest); // Morphological opening erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); // Morphological closing dilate(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); erode(imageDest, imageDest, getStructuringElement(MORPH_ELLIPSE, Size(8, 8)) ); // Create moment Moments mmts = moments(imageDest); // Calculate center x and y (Centroids) double x_object = mmts.m10 / mmts.m00; double y_object = mmts.m01 / mmts.m00; // Center of image cv::Size size = imageSrc.size(); double x_center = size.width/2.0f; double y_center = size.height/2.0f; // contour Mat tmpDest = imageDest.clone(); Point point = edgePoint(tmpDest, Point(x_center, y_center)); double diameter = norm(Point(x_object, y_object)- point)*2; double realDiameter = 6.5; double distance = getDistance(realDiameter, diameter); // Get rotation angle int digitalDiff = x_object - x_center; double realDiff = digitalDiff * (realDiameter / diameter); double rotation_angle = atan(realDiff / distance) * 180 / PI; cout << "distance is: "<< distance << " "<< rotation_angle << " "<< diameter << endl; // Draw circle at x and y Mat tmpSource = imageSrc.clone(); circle(tmpSource, Point(x_object,y_object), 3, Scalar(229, 240, 76), 4); circle(tmpSource, Point(x_object,y_object), diameter/2, Scalar(44, 252, 14), 5); // Center circle(tmpSource, Point(x_center,y_center), 10, Scalar(255, 255, 255), 10); imwrite("/var/www/html/mr_robot/out.jpg", tmpSource); drive(rotation_angle, distance); } // Show images in windows // imshow("Destination", imageDest); // imshow("Source", tmpSource); // waitKey(0); return 0; } <|endoftext|>
<commit_before>/* This file is part of the MinSG library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_IMAGECOMPARE #include "AbstractOnGpuComparator.h" #include <Geometry/Rect.h> #include <Geometry/Vec2.h> #include <Rendering/Shader/Shader.h> #include <Rendering/Shader/Uniform.h> #include <Rendering/RenderingContext/RenderingParameters.h> #include <Rendering/RenderingContext/RenderingContext.h> #include <Rendering/Texture/Texture.h> #include <Rendering/Texture/TextureUtils.h> #include <Rendering/Draw.h> #include <Rendering/FBO.h> #include <Util/Graphics/Bitmap.h> #include <Util/IO/FileName.h> #include <Util/IO/FileLocator.h> #include <Util/Macros.h> #include <cassert> #include <iostream> namespace MinSG { namespace ImageCompare { using Rendering::Texture; using Rendering::Shader; using Rendering::Uniform; using Rendering::FBO; using Rendering::RenderingContext; using Util::Reference; using Geometry::Vec2i; std::set<Util::Reference<Rendering::Texture> > AbstractOnGpuComparator::usedTextures; std::map<Geometry::Vec2i, std::vector<Util::Reference<Rendering::Texture> >, AbstractOnGpuComparator::Vec2iComp> AbstractOnGpuComparator::freeTextures; static Util::FileLocator shaderFileLocator; //! (static) void AbstractOnGpuComparator::initShaderFileLocator( const Util::FileLocator& locator){ shaderFileLocator = locator; } //! (static) const Util::FileLocator& AbstractOnGpuComparator::getShaderFileLocator(){ return shaderFileLocator; } AbstractOnGpuComparator::AbstractOnGpuComparator(int32_t _filterSize) : fbo(new FBO), texDownSize(64), filterSize(_filterSize), filterType(GAUSS), filterValid(false), initialized(false) { } AbstractOnGpuComparator::~AbstractOnGpuComparator() { deleteTextures(); } Util::Reference<Rendering::Texture> AbstractOnGpuComparator::createTexture(const Geometry::Vec2i & size) { Util::Reference<Texture> tex; std::vector<Reference<Texture> > & vec = freeTextures[size]; if (vec.empty()) { tex = Rendering::TextureUtils::createHDRTexture(size.getWidth(), size.getHeight(), false); //std::cerr << "created HDR Texture: " << size << endl; } else { tex = vec.back(); vec.pop_back(); } usedTextures.insert(tex); return tex; } void AbstractOnGpuComparator::releaseTexture(const Util::Reference<Texture> & tex) { usedTextures.erase(tex); freeTextures[Geometry::Vec2i(tex->getWidth(), tex->getHeight())].push_back(tex); } void AbstractOnGpuComparator::deleteTextures() { assert(usedTextures.empty()); freeTextures.clear(); // std::cerr << "deleting Textures: " << std::endl; } void AbstractOnGpuComparator::copy(Rendering::RenderingContext & context, TexRef_t src, TexRef_t dst) { context.pushAndSetShader(shaderCopy.get()); context.pushAndSetTexture(0, src->get()); context.pushAndSetScissor(Rendering::ScissorParameters(Geometry::Rect_i(0, 0, src->get()->getWidth(), src->get()->getHeight()))); fbo->attachColorTexture(context, dst->get()); Rendering::drawFullScreenRect(context); fbo->detachColorTexture(context); context.popScissor(); context.popTexture(0); context.popShader(); } void AbstractOnGpuComparator::filter(Rendering::RenderingContext & context, TexRef_t src, TexRef_t dst) { if (!filterValid) { shaderFilterH->setUniform(context, Uniform("filterSize", filterSize)); shaderFilterV->setUniform(context, Uniform("filterSize", filterSize)); // std::cerr << getTypeName() << " Filter: " << (filterType == GAUSS ? "Gauss" : "Box") << " (" << filterSize << ") : " << "["; std::vector<float> values; if (filterType == GAUSS) { // old formula was filterSize * 1.5, which was too big. // older value used for some measurements in 2013's papers: 0.3 const double sigma = 0.3 * (filterSize - 1) + 0.8; // sqrtOfTwoTimesPi = std::sqrt(2.0 * pi) const double sqrtOfTwoTimesPi = 2.506628274631000502415765284811045253006986740609938316629923; const double a = 1.0 / (sigma * sqrtOfTwoTimesPi); double sum = 0.0; for (int i = 0; i <= filterSize; i++) { const double v = a * std::exp(-((i * i) / (2.0 * sigma * sigma))); values.push_back(v); sum += (i == 0 ? v : 2 * v); } for (int i = 0; i <= filterSize; i++) { values[i] /= sum; } } else if (filterType == BOX) { for (int i = 0; i <= filterSize; i++) { float v = 1.0f / (filterSize * 2.0f + 1.0f); values.push_back(v); } } else WARN("the roof is on fire"); // for(const auto & x : values) // std::cerr << x << " "; // std::cerr << "\b]" << std::endl; while (values.size() < 16) values.push_back(0.0f); shaderFilterH->setUniform(context, Uniform("filterValues", values)); shaderFilterV->setUniform(context, Uniform("filterValues", values)); filterValid = true; } Reference<TexRef> tmp = new TexRef(Vec2i(src->get()->getWidth(), src->get()->getHeight())); context.pushAndSetShader(shaderFilterH.get()); context.pushAndSetTexture(0, src->get()); fbo->attachColorTexture(context, tmp->get()); Rendering::drawFullScreenRect(context); context.setShader(shaderFilterV.get()); context.setTexture(0, tmp->get()); fbo->attachColorTexture(context, dst.isNull() ? src->get() : dst->get()); Rendering::drawFullScreenRect(context); fbo->detachColorTexture(context); context.popTexture(0); context.popShader(); } float AbstractOnGpuComparator::average(Rendering::RenderingContext & context, TexRef_t src) { // shrink on gpu TexRef_t in = src; context.pushAndSetShader(shaderShrink.get()); context.pushTexture(0); context.pushViewport(); uint32_t w = in->get()->getWidth(); uint32_t h = in->get()->getHeight(); while (w * h > texDownSize * texDownSize && w % 2 == 0 && h % 2 == 0) { w /= 2; h /= 2; Reference<TexRef> tmp = new TexRef(Geometry::Vec2i(w, h)); fbo->attachColorTexture(context, tmp->get()); context.setViewport(Geometry::Rect_i(0, 0, tmp->get()->getWidth(), tmp->get()->getHeight())); context.setTexture(0, in->get()); Rendering::drawFullScreenRect(context); in = tmp; } context.popViewport(); context.popShader(); context.popTexture(0); // shrink on cpu in->get()->downloadGLTexture(context); double quality = 0.0; auto localBitmap = in->get()->getLocalBitmap(); const float * tex = reinterpret_cast<const float *>(localBitmap->data()); const float * end = reinterpret_cast<const float *>(localBitmap->data() + localBitmap->getDataSize()); const uint32_t numFloats = end - tex; while (tex != end) { quality += *(tex++); } return quality /= numFloats; } void AbstractOnGpuComparator::setFBO(Util::Reference<Rendering::FBO> _fbo) { this->fbo = _fbo; } void AbstractOnGpuComparator::checkTextureSize(Geometry::Vec2i size) { checkTextureSize(size.x(), size.y()); } void AbstractOnGpuComparator::checkTextureSize(uint32_t width, uint32_t height) { while (width * height > texDownSize * texDownSize) { if (width % 2 != 0 || height % 2 != 0) { WARN("try to use resolutions where width and height contain more prime factors of two to speed up image quality calculation"); break; } width /= 2; height /= 2; } } bool AbstractOnGpuComparator::compare(Rendering::RenderingContext & context, Rendering::Texture * firstTex, Rendering::Texture * secondTex, double & value, Rendering::Texture * resultTex) { init(context); prepare(context); bool ret = doCompare(context, firstTex, secondTex, value, resultTex); finish(context); return ret; } bool AbstractOnGpuComparator::init(RenderingContext & context) { if (!initialized) { const auto& locator = getShaderFileLocator(); auto vsLocation = locator.locateFile(Util::FileName("shader/ImageCompare/ImageCompare.vs")); if(!vsLocation.first) throw std::runtime_error("AbstractOnGpuComparator: Could not locate required shader file. Did you init the shaderFileLocator?!?"); shaderCopy = Shader::loadShader( vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/Copy.fs")).second, Shader::USE_UNIFORMS); shaderCopy->setUniform(context, Rendering::Uniform("A", 0)); shaderShrink = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/Shrink.fs")).second, Shader::USE_UNIFORMS); shaderShrink->setUniform(context, Rendering::Uniform("A", 0)); shaderFilterH = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/FilterH.fs")).second, Shader::USE_UNIFORMS); shaderFilterH->setUniform(context, Rendering::Uniform("A", 0)); shaderFilterV = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/FilterV.fs")).second, Shader::USE_UNIFORMS); shaderFilterV->setUniform(context, Rendering::Uniform("A", 0)); initialized = true; return true; } return false; } void AbstractOnGpuComparator::prepare(RenderingContext & context) { // timer.resume(); context.pushViewport(); context.pushAndSetFBO(fbo.get()); // in case an external set fbo has a depth texture fbo->detachDepthTexture(context); } void AbstractOnGpuComparator::finish(RenderingContext & context) { context.popFBO(); context.popViewport(); // timer.stop(); // testCounter++; // if (timer.getSeconds() > 1) { // std::cerr << "tps: " << testCounter / timer.getSeconds() << std::endl; // testCounter = 0; // timer.reset(); // timer.stop(); // } } } } #endif // MINSG_EXT_IMAGECOMPARE <commit_msg>AbstractOnGpuComparator: Show "wrong size" warning only once.<commit_after>/* This file is part of the MinSG library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef MINSG_EXT_IMAGECOMPARE #include "AbstractOnGpuComparator.h" #include <Geometry/Rect.h> #include <Geometry/Vec2.h> #include <Rendering/Shader/Shader.h> #include <Rendering/Shader/Uniform.h> #include <Rendering/RenderingContext/RenderingParameters.h> #include <Rendering/RenderingContext/RenderingContext.h> #include <Rendering/Texture/Texture.h> #include <Rendering/Texture/TextureUtils.h> #include <Rendering/Draw.h> #include <Rendering/FBO.h> #include <Util/Graphics/Bitmap.h> #include <Util/IO/FileName.h> #include <Util/IO/FileLocator.h> #include <Util/Macros.h> #include <cassert> #include <iostream> namespace MinSG { namespace ImageCompare { using Rendering::Texture; using Rendering::Shader; using Rendering::Uniform; using Rendering::FBO; using Rendering::RenderingContext; using Util::Reference; using Geometry::Vec2i; std::set<Util::Reference<Rendering::Texture> > AbstractOnGpuComparator::usedTextures; std::map<Geometry::Vec2i, std::vector<Util::Reference<Rendering::Texture> >, AbstractOnGpuComparator::Vec2iComp> AbstractOnGpuComparator::freeTextures; static Util::FileLocator shaderFileLocator; //! (static) void AbstractOnGpuComparator::initShaderFileLocator( const Util::FileLocator& locator){ shaderFileLocator = locator; } //! (static) const Util::FileLocator& AbstractOnGpuComparator::getShaderFileLocator(){ return shaderFileLocator; } AbstractOnGpuComparator::AbstractOnGpuComparator(int32_t _filterSize) : fbo(new FBO), texDownSize(64), filterSize(_filterSize), filterType(GAUSS), filterValid(false), initialized(false) { } AbstractOnGpuComparator::~AbstractOnGpuComparator() { deleteTextures(); } Util::Reference<Rendering::Texture> AbstractOnGpuComparator::createTexture(const Geometry::Vec2i & size) { Util::Reference<Texture> tex; std::vector<Reference<Texture> > & vec = freeTextures[size]; if (vec.empty()) { tex = Rendering::TextureUtils::createHDRTexture(size.getWidth(), size.getHeight(), false); //std::cerr << "created HDR Texture: " << size << endl; } else { tex = vec.back(); vec.pop_back(); } usedTextures.insert(tex); return tex; } void AbstractOnGpuComparator::releaseTexture(const Util::Reference<Texture> & tex) { usedTextures.erase(tex); freeTextures[Geometry::Vec2i(tex->getWidth(), tex->getHeight())].push_back(tex); } void AbstractOnGpuComparator::deleteTextures() { assert(usedTextures.empty()); freeTextures.clear(); // std::cerr << "deleting Textures: " << std::endl; } void AbstractOnGpuComparator::copy(Rendering::RenderingContext & context, TexRef_t src, TexRef_t dst) { context.pushAndSetShader(shaderCopy.get()); context.pushAndSetTexture(0, src->get()); context.pushAndSetScissor(Rendering::ScissorParameters(Geometry::Rect_i(0, 0, src->get()->getWidth(), src->get()->getHeight()))); fbo->attachColorTexture(context, dst->get()); Rendering::drawFullScreenRect(context); fbo->detachColorTexture(context); context.popScissor(); context.popTexture(0); context.popShader(); } void AbstractOnGpuComparator::filter(Rendering::RenderingContext & context, TexRef_t src, TexRef_t dst) { if (!filterValid) { shaderFilterH->setUniform(context, Uniform("filterSize", filterSize)); shaderFilterV->setUniform(context, Uniform("filterSize", filterSize)); // std::cerr << getTypeName() << " Filter: " << (filterType == GAUSS ? "Gauss" : "Box") << " (" << filterSize << ") : " << "["; std::vector<float> values; if (filterType == GAUSS) { // old formula was filterSize * 1.5, which was too big. // older value used for some measurements in 2013's papers: 0.3 const double sigma = 0.3 * (filterSize - 1) + 0.8; // sqrtOfTwoTimesPi = std::sqrt(2.0 * pi) const double sqrtOfTwoTimesPi = 2.506628274631000502415765284811045253006986740609938316629923; const double a = 1.0 / (sigma * sqrtOfTwoTimesPi); double sum = 0.0; for (int i = 0; i <= filterSize; i++) { const double v = a * std::exp(-((i * i) / (2.0 * sigma * sigma))); values.push_back(v); sum += (i == 0 ? v : 2 * v); } for (int i = 0; i <= filterSize; i++) { values[i] /= sum; } } else if (filterType == BOX) { for (int i = 0; i <= filterSize; i++) { float v = 1.0f / (filterSize * 2.0f + 1.0f); values.push_back(v); } } else WARN("the roof is on fire"); // for(const auto & x : values) // std::cerr << x << " "; // std::cerr << "\b]" << std::endl; while (values.size() < 16) values.push_back(0.0f); shaderFilterH->setUniform(context, Uniform("filterValues", values)); shaderFilterV->setUniform(context, Uniform("filterValues", values)); filterValid = true; } Reference<TexRef> tmp = new TexRef(Vec2i(src->get()->getWidth(), src->get()->getHeight())); context.pushAndSetShader(shaderFilterH.get()); context.pushAndSetTexture(0, src->get()); fbo->attachColorTexture(context, tmp->get()); Rendering::drawFullScreenRect(context); context.setShader(shaderFilterV.get()); context.setTexture(0, tmp->get()); fbo->attachColorTexture(context, dst.isNull() ? src->get() : dst->get()); Rendering::drawFullScreenRect(context); fbo->detachColorTexture(context); context.popTexture(0); context.popShader(); } float AbstractOnGpuComparator::average(Rendering::RenderingContext & context, TexRef_t src) { // shrink on gpu TexRef_t in = src; context.pushAndSetShader(shaderShrink.get()); context.pushTexture(0); context.pushViewport(); uint32_t w = in->get()->getWidth(); uint32_t h = in->get()->getHeight(); while (w * h > texDownSize * texDownSize && w % 2 == 0 && h % 2 == 0) { w /= 2; h /= 2; Reference<TexRef> tmp = new TexRef(Geometry::Vec2i(w, h)); fbo->attachColorTexture(context, tmp->get()); context.setViewport(Geometry::Rect_i(0, 0, tmp->get()->getWidth(), tmp->get()->getHeight())); context.setTexture(0, in->get()); Rendering::drawFullScreenRect(context); in = tmp; } context.popViewport(); context.popShader(); context.popTexture(0); // shrink on cpu in->get()->downloadGLTexture(context); double quality = 0.0; auto localBitmap = in->get()->getLocalBitmap(); const float * tex = reinterpret_cast<const float *>(localBitmap->data()); const float * end = reinterpret_cast<const float *>(localBitmap->data() + localBitmap->getDataSize()); const uint32_t numFloats = end - tex; while (tex != end) { quality += *(tex++); } return quality /= numFloats; } void AbstractOnGpuComparator::setFBO(Util::Reference<Rendering::FBO> _fbo) { this->fbo = _fbo; } void AbstractOnGpuComparator::checkTextureSize(Geometry::Vec2i size) { checkTextureSize(size.x(), size.y()); } void AbstractOnGpuComparator::checkTextureSize(uint32_t width, uint32_t height) { while (width * height > texDownSize * texDownSize) { if (width % 2 != 0 || height % 2 != 0) { static bool warningShown = false; if(!warningShown){ warningShown = true; WARN("(once) try to use resolutions where width and height contain more prime factors of two to speed up image quality calculation"); } break; } width /= 2; height /= 2; } } bool AbstractOnGpuComparator::compare(Rendering::RenderingContext & context, Rendering::Texture * firstTex, Rendering::Texture * secondTex, double & value, Rendering::Texture * resultTex) { init(context); prepare(context); bool ret = doCompare(context, firstTex, secondTex, value, resultTex); finish(context); return ret; } bool AbstractOnGpuComparator::init(RenderingContext & context) { if (!initialized) { const auto& locator = getShaderFileLocator(); auto vsLocation = locator.locateFile(Util::FileName("shader/ImageCompare/ImageCompare.vs")); if(!vsLocation.first) throw std::runtime_error("AbstractOnGpuComparator: Could not locate required shader file. Did you init the shaderFileLocator?!?"); shaderCopy = Shader::loadShader( vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/Copy.fs")).second, Shader::USE_UNIFORMS); shaderCopy->setUniform(context, Rendering::Uniform("A", 0)); shaderShrink = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/Shrink.fs")).second, Shader::USE_UNIFORMS); shaderShrink->setUniform(context, Rendering::Uniform("A", 0)); shaderFilterH = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/FilterH.fs")).second, Shader::USE_UNIFORMS); shaderFilterH->setUniform(context, Rendering::Uniform("A", 0)); shaderFilterV = Shader::loadShader(vsLocation.second, locator.locateFile(Util::FileName("shader/ImageCompare/FilterV.fs")).second, Shader::USE_UNIFORMS); shaderFilterV->setUniform(context, Rendering::Uniform("A", 0)); initialized = true; return true; } return false; } void AbstractOnGpuComparator::prepare(RenderingContext & context) { // timer.resume(); context.pushViewport(); context.pushAndSetFBO(fbo.get()); // in case an external set fbo has a depth texture fbo->detachDepthTexture(context); } void AbstractOnGpuComparator::finish(RenderingContext & context) { context.popFBO(); context.popViewport(); // timer.stop(); // testCounter++; // if (timer.getSeconds() > 1) { // std::cerr << "tps: " << testCounter / timer.getSeconds() << std::endl; // testCounter = 0; // timer.reset(); // timer.stop(); // } } } } #endif // MINSG_EXT_IMAGECOMPARE <|endoftext|>
<commit_before>/// @file /// @version 3.03 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #include <hltypes/exception.h> #include <hltypes/harray.h> #include "MultiPlaylist.h" #include "Playlist.h" namespace xal { MultiPlaylist::MultiPlaylist() { } MultiPlaylist::~MultiPlaylist() { this->clear(); } bool MultiPlaylist::isEnabled() { foreach (Playlist*, it, this->playlists) { if (!(*it)->isEnabled()) { return false; } } return true; } void MultiPlaylist::setEnabled(bool value) { foreach (Playlist*, it, this->playlists) { (*it)->setEnabled(value); } } bool MultiPlaylist::isPlaying() { foreach (Playlist*, it, this->playlists) { if ((*it)->isPlaying()) { return true; } } return false; } bool MultiPlaylist::isPaused() { foreach (Playlist*, it, this->playlists) { if (!(*it)->isPaused()) { return false; } } return true; } void MultiPlaylist::registerPlaylist(Playlist* playlist) { if (this->playlists.contains(playlist)) { throw hl_exception("Playlist was already registered!"); } this->playlists += playlist; } void MultiPlaylist::unregisterPlaylist(Playlist* playlist) { if (!this->playlists.contains(playlist)) { throw hl_exception("Playlist has not been registered!"); } this->playlists -= playlist; } void MultiPlaylist::clear() { this->stop(); foreach (Playlist*, it, this->playlists) { delete (*it); } this->playlists.clear(); } void MultiPlaylist::update() { foreach (Playlist*, it, this->playlists) { (*it)->update(); } } void MultiPlaylist::play(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->play(fadeTime); } } void MultiPlaylist::stop(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->stop(fadeTime); } } void MultiPlaylist::pause(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->pause(fadeTime); } } void MultiPlaylist::shuffle() { foreach (Playlist*, it, this->playlists) { (*it)->shuffle(); } } void MultiPlaylist::reset() { foreach (Playlist*, it, this->playlists) { (*it)->reset(); } } } <commit_msg>- hltypes exceptions update<commit_after>/// @file /// @version 3.03 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #include <hltypes/exception.h> #include <hltypes/harray.h> #include "MultiPlaylist.h" #include "Playlist.h" namespace xal { MultiPlaylist::MultiPlaylist() { } MultiPlaylist::~MultiPlaylist() { this->clear(); } bool MultiPlaylist::isEnabled() { foreach (Playlist*, it, this->playlists) { if (!(*it)->isEnabled()) { return false; } } return true; } void MultiPlaylist::setEnabled(bool value) { foreach (Playlist*, it, this->playlists) { (*it)->setEnabled(value); } } bool MultiPlaylist::isPlaying() { foreach (Playlist*, it, this->playlists) { if ((*it)->isPlaying()) { return true; } } return false; } bool MultiPlaylist::isPaused() { foreach (Playlist*, it, this->playlists) { if (!(*it)->isPaused()) { return false; } } return true; } void MultiPlaylist::registerPlaylist(Playlist* playlist) { if (this->playlists.contains(playlist)) { throw Exception("Playlist was already registered!"); } this->playlists += playlist; } void MultiPlaylist::unregisterPlaylist(Playlist* playlist) { if (!this->playlists.contains(playlist)) { throw Exception("Playlist has not been registered!"); } this->playlists -= playlist; } void MultiPlaylist::clear() { this->stop(); foreach (Playlist*, it, this->playlists) { delete (*it); } this->playlists.clear(); } void MultiPlaylist::update() { foreach (Playlist*, it, this->playlists) { (*it)->update(); } } void MultiPlaylist::play(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->play(fadeTime); } } void MultiPlaylist::stop(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->stop(fadeTime); } } void MultiPlaylist::pause(float fadeTime) { foreach (Playlist*, it, this->playlists) { (*it)->pause(fadeTime); } } void MultiPlaylist::shuffle() { foreach (Playlist*, it, this->playlists) { (*it)->shuffle(); } } void MultiPlaylist::reset() { foreach (Playlist*, it, this->playlists) { (*it)->reset(); } } } <|endoftext|>
<commit_before>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : encoder_(codec, this), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { } XCodecEncoderPipe::~XCodecEncoderPipe() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * XCodecEncoderPipe::input(Buffer *buf, EventCallback *cb) { if (output_callback_ != NULL) { ASSERT(input_buffer_.empty()); ASSERT(output_action_ == NULL); if (!buf->empty()) { Buffer tmp; encoder_.encode(&tmp, buf); ASSERT(buf->empty()); output_callback_->event(Event(Event::Done, 0, tmp)); } else { input_eos_ = true; output_callback_->event(Event(Event::EOS, 0)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } else { if (!buf->empty()) { encoder_.encode(&input_buffer_, buf); ASSERT(buf->empty()); } else { input_eos_ = true; } } cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * XCodecEncoderPipe::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); if (!input_buffer_.empty() || input_eos_) { if (input_eos_) { cb->event(Event(Event::EOS, 0, input_buffer_)); if (!input_buffer_.empty()) input_buffer_.clear(); } else { cb->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); } return (EventSystem::instance()->schedule(cb)); } output_callback_ = cb; return (cancellation(this, &XCodecEncoderPipe::output_cancel)); } void XCodecEncoderPipe::output_ready(void) { if (input_eos_) { if (input_buffer_.empty()) { ERROR("/xcodec/encoder/pipe") << "Ignoring spontaneous output after EOS."; return; } DEBUG("/xcodec/encoder/pipe") << "Retrieving spontaneous data along with buffered data at EOS."; } Buffer empty; encoder_.encode(&input_buffer_, &empty); ASSERT(!input_buffer_.empty()); if (output_callback_ != NULL) { /* * If EOS has come, we can only get here if it is being serviced * and there is data pending to be pushed before EOS. Make sure * that's the case. */ ASSERT(!input_eos_); ASSERT(output_action_ == NULL); output_callback_->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } } void XCodecEncoderPipe::output_cancel(void) { if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } } <commit_msg>Pepper with assertions.<commit_after>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : encoder_(codec, this), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { ASSERT(output_callback_ == NULL || output_action_ == NULL); } XCodecEncoderPipe::~XCodecEncoderPipe() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * XCodecEncoderPipe::input(Buffer *buf, EventCallback *cb) { ASSERT(output_callback_ == NULL || output_action_ == NULL); if (output_callback_ != NULL) { ASSERT(input_buffer_.empty()); ASSERT(output_action_ == NULL); if (!buf->empty()) { Buffer tmp; encoder_.encode(&tmp, buf); ASSERT(buf->empty()); output_callback_->event(Event(Event::Done, 0, tmp)); } else { input_eos_ = true; output_callback_->event(Event(Event::EOS, 0)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; ASSERT(output_callback_ == NULL || output_action_ == NULL); } else { if (!buf->empty()) { encoder_.encode(&input_buffer_, buf); ASSERT(buf->empty()); } else { input_eos_ = true; } } ASSERT(output_callback_ == NULL || output_action_ == NULL); cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * XCodecEncoderPipe::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); ASSERT(output_callback_ == NULL || output_action_ == NULL); if (!input_buffer_.empty() || input_eos_) { if (input_eos_) { cb->event(Event(Event::EOS, 0, input_buffer_)); if (!input_buffer_.empty()) input_buffer_.clear(); } else { cb->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); } return (EventSystem::instance()->schedule(cb)); } ASSERT(output_callback_ == NULL || output_action_ == NULL); output_callback_ = cb; ASSERT(output_callback_ == NULL || output_action_ == NULL); return (cancellation(this, &XCodecEncoderPipe::output_cancel)); } void XCodecEncoderPipe::output_ready(void) { if (input_eos_) { if (input_buffer_.empty()) { ERROR("/xcodec/encoder/pipe") << "Ignoring spontaneous output after EOS."; return; } DEBUG("/xcodec/encoder/pipe") << "Retrieving spontaneous data along with buffered data at EOS."; } Buffer empty; encoder_.encode(&input_buffer_, &empty); ASSERT(!input_buffer_.empty()); if (output_callback_ != NULL) { /* * If EOS has come, we can only get here if it is being serviced * and there is data pending to be pushed before EOS. Make sure * that's the case. */ ASSERT(!input_eos_); ASSERT(output_callback_ == NULL || output_action_ == NULL); ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL || output_action_ == NULL); output_callback_->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; ASSERT(output_callback_ == NULL || output_action_ == NULL); } } void XCodecEncoderPipe::output_cancel(void) { ASSERT(output_callback_ == NULL || output_action_ == NULL); if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } ASSERT(output_callback_ == NULL || output_action_ == NULL); if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } ASSERT(output_callback_ == NULL || output_action_ == NULL); } <|endoftext|>
<commit_before>/* * ImageProcessing.cpp * Robert Collins */ #include <jni.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "ImageProcessing.h" using namespace std; using namespace cv; extern "C" jboolean Java_com_software_corvidae_imageproc_CameraActivity_ImageProcessing ( JNIEnv* env, const jobject thiz, const jint width, const jint height, const int lowThreshold, const jbyteArray NV21FrameData, jintArray outPixels) { int ratio = 3; /// Original image and grayscale copy jbyte* pNV21FrameData = env->GetByteArrayElements(NV21FrameData, 0); Mat originalImage(height, width, CV_8UC4, (unsigned char *)pNV21FrameData); Mat gray_image(height, width, CV_8UC1, (unsigned char *)pNV21FrameData); /// Final Result image jint* poutPixels = env->GetIntArrayElements(outPixels, 0); Mat finalImage(height, width, CV_8UC4, (unsigned char *)poutPixels); /// Reduce noise with a 3x3 kernel Mat blurred; GaussianBlur(gray_image, blurred, Size(3, 3), 0); /// create new cv::Mat, canny it and convert Mat cannyMat(height, width, CV_8UC1); Canny(blurred, cannyMat, lowThreshold, lowThreshold * ratio, 3); Mat tempImage(height, width, CV_8UC4); cvtColor(cannyMat, finalImage, CV_GRAY2BGRA); // finalImage = tempImage; /// cleanup env->ReleaseByteArrayElements(NV21FrameData, pNV21FrameData, 0); env->ReleaseIntArrayElements(outPixels, poutPixels, 0); return true; } <commit_msg>Minor code cleanup<commit_after>/* * ImageProcessing.cpp * Robert Collins */ #include <jni.h> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "ImageProcessing.h" using namespace std; using namespace cv; extern "C" jboolean Java_com_software_corvidae_imageproc_CameraActivity_ImageProcessing ( JNIEnv* env, const jobject thiz, const jint width, const jint height, const int lowThreshold, const jbyteArray NV21FrameData, jintArray outPixels) { int ratio = 3; /// Original image and grayscale copy jbyte* pNV21FrameData = env->GetByteArrayElements(NV21FrameData, 0); Mat gray_image(height, width, CV_8UC1, (unsigned char *)pNV21FrameData); /// Final Result image jint* poutPixels = env->GetIntArrayElements(outPixels, 0); Mat finalImage(height, width, CV_8UC4, (unsigned char *)poutPixels); /// Reduce noise with a 3x3 kernel Mat blurred; GaussianBlur(gray_image, blurred, Size(3, 3), 0); /// create new cv::Mat, canny it and convert Mat cannyMat(height, width, CV_8UC1); Canny(blurred, cannyMat, lowThreshold, lowThreshold * ratio, 3); cvtColor(cannyMat, finalImage, CV_GRAY2BGRA); /// cleanup env->ReleaseByteArrayElements(NV21FrameData, pNV21FrameData, 0); env->ReleaseIntArrayElements(outPixels, poutPixels, 0); return true; } <|endoftext|>
<commit_before>// ***************************************************************************************************************************** // math_misc.hpp // Miscellaneous Math Functions // Author(s): Cory Douthat // Copyright (c) 2017 Cory Douthat, All Rights Reserved. // ***************************************************************************************************************************** #ifndef MATH_MISC_HPP_ #define MATH_MISC_HPP_ #include <stdlib.h> #define _USE_MATH_DEFINES //For PI definition #include <cmath> #include "vec.hpp" #include "mat.hpp" // Determinant() - Calculate the determinant of an arbitrary-sized square matrix // Inputs: mat = matrix data array // size = matrix size (width of square matrix) // Return: determinant result template <typename T> T Determinant(const T *mat,unsigned int size) { if (size < 2) return (T)0; // 2x2 if (size == 2) return Mat2<T>(mat).det(); // 3x3 if (size == 3) return Mat3<T>(mat).det(); // 4x4 if (size == 4) return Mat4<T>(mat).det(); // 5x5+ T det = (T)0; T *sub_mat; sub_mat = new T[(size - 1)*(size - 1)]; for (unsigned int i = 0; i < size; i++) { int col = 0; for (unsigned int col_maj = 0; col_maj < size; col_maj++) { if (col_maj != i) { for (unsigned int row = 0; row < size - 1; row++) { sub_mat[col*(size - 1) + row] = mat[col_maj*(size) + row + 1]; } col++; } } if (i % 2 == 0) det += mat[i*size] * Determinant(sub_mat,size - 1); else det -= mat[i*size] * Determinant(sub_mat,size - 1); } delete sub_mat; return det; } // CAUTION: Numerically unstable. Use Gaussian Elimination instead unless you know what you're doing. // SolveCramer() - Solve a system of linear equations using Cramer's Rule. // Format Ax = b // Inputs: A_mat = n x n matrix (array) defining the coefficients of the equations // b_vec = n size vector (array) defining right-hand side of each linear equation // n = number of equations/variables // Return: x_vec = n size vector (array) representing solutions - passed by pointer // return boolean specifying whether the operation was successful or not template <typename T> bool SolveCramer(const T *A_mat,const T *b_vec,unsigned int n,T *x_vec) { T det_A = Determinant(A_mat,n); if (det_A == T(0)) return false; // Matrix for temporary A with column replaced T *Ai = new T[n * n]; memcpy(Ai,A_mat,n * n * sizeof(T)); for (unsigned int i = 0; i < n; i++) { // Copy in b vector to column i memcpy(&Ai[i * n],b_vec,n * sizeof(T)); // Solve for xi x_vec[i] = Determinant(Ai,n) / det_A; // Copy regular values back into column i memcpy(&Ai[i * n],&A_mat[i * n],n * sizeof(T)); } return true; } // TODO: Improve efficiency by checking for special cases or no solution earlier? // SolveGaussElim() - Solve a system of linear equations using Gaussian Elimination // Performs Partial Pivoting; does not perform Full Pivoting // Format: Ax = b // Inputs: A_mat = n x n matrix (array) defining the coefficients of the equations // b_vec = n size vector (array) defining right-hand side of each linear equation // n = number of equations/variables // Return: x_vec = n size vector (array) representing solutions - passed by pointer // return boolean specifying whether the operation was successful or not template <typename T> bool SolveGaussElim(const T *A_mat, const T *b_vec, unsigned int n, T *x_vec) { T *A = new T[n*n]; T *b = new T[n]; memcpy(A, A_mat, sizeof(T)*n*n); memcpy(b, b_vec, sizeof(T)*n); unsigned int *row_index = new unsigned int[n]; // Vector to track row order for (unsigned int i = 0; i < n; i++) row_index[i] = i; // Reduce matrix to row echelon form using Gaussian Elimination and partial pivoting for (unsigned int r = 0; r < n; r++) { // Pivot row 'r' (check for rows with larger absolute values in the pivot column) if (r < n - 1) // Do not do this when on last row { for (unsigned int i = r + 1; i < n; i++) { // Check each successive row to see if absolute value in 'r'th column is larger if (abs(A[r*n + row_index[i]]) > abs(A[r*n + row_index[r]])) { // Swap rows unsigned int temp = row_index[r]; row_index[r] = row_index[i]; row_index[i] = temp; } } } // Check for zero pivot (no solution) if (A[r*n + row_index[r]] == (T)0) { delete A; delete b; delete row_index; return false; } // Reduce successive rows (eliminate columns below pivot of 'r') if (r < n - 1) // Do not do this when on last row { for (unsigned int i = r + 1; i < n; i++) // ROWS { // Multiplication factor T temp_mult = A[r*n + row_index[i]] / A[r*n + row_index[r]]; // First column set 0 A[r*n + row_index[i]] = (T)0; // Addl columns for (unsigned int j = r + 1; j < n; j++) A[j*n + row_index[i]] -= temp_mult * A[j*n + row_index[r]]; // b vector b[row_index[i]] -= temp_mult * b[row_index[r]]; } } } // Back-substitue for x values for (int x = n - 1; x >= 0; x--) { // Set 'x' to right side of equation x_vec[x] = b[row_index[x]]; // Subtract known 'x' values from right side of equation for (int j = n - 1; j > x; j--) { x_vec[x] -= x_vec[j] * A[j*n + row_index[x]]; } // Solve for 'x' x_vec[x] /= A[x*n + row_index[x]]; } delete A; delete b; delete row_index; return true; } // TODO/NOTE: It looks like this may be a failed experiment. Does not provide correct results when clamping. Problem form may simply be invalid. // TODO: UNTESTED // TODO: Add termination criteria (i.e. residual, etc) // TODO: Handle default min/max for x or individual +/- infinity values // TODO: TO-DO add checks for convergence issues?? // SolveGaussSeidelClamped() - Solve an MLCP (Mixed Linear Complimentarity Problem) using Gauss-Seidel // method with simple clamping constraints on unknowns. This may be equivalent to // Projected Gauss-Seidel method, but it's unclear. No optimization is attempted to // target this to rigid body constraints specifically, or take advantage of matrix // sparsity by reducing dimensions (as with Erin Catto GDC 2005 presentation) // References: https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method // Format: Ax = b // Inputs: A_mat = [n by n], col-major order, defines the coefficients of the equations // b_vec = [n] defines right-hand side of each linear equation // x_min = [n] minimum bound of x, null ptr means -infinity (for whole vector) // x_max = [n] maximum bound of x, null ptr means +infinity (for whole vector) // n = number of equations/variables // max_iter = maximum number of iterations // Return: x_vec = [n] represents solution variables - passed by pointer // Note: x_vec may be initialized with a best-guess (e.g. results from prev. // frame) to warm-start the algorithm. // return boolean specifying whether the operation was successful or not template <typename T> bool SolveGaussSeidelClamped(const T* A_mat, const T* b_vec, const T* x_min, const T* x_max, unsigned int n, unsigned int max_iter, T* x_vec) { // Basic checks if (n <= 0) return false; if (x_min && x_max) { for (unsigned int c = 0; c < n; c++) { if (x_min[c] > x_max[c]) return false; } } T sum1, sum2; for (unsigned int iter = 0; iter < max_iter; iter++) { for (int i = 0; i < n; i++) { // Calculate next iteration of x (i.e. k+1) using forward-substitution // First summation term: sum1 = 0; for (int j = 0; j < i; j++) { sum1 += A_mat[i * n + j] * x_vec[j]; } // Second summation term: sum2 = 0; for (int j = i + 1; j < n; j++) { sum2 += A_mat[i * n + j] * x_vec[j]; } x_vec[i] = b_vec[i] - sum1 - sum2; // Clamp value if (x_min && x_vec[i] < x_min[i]) x_vec[i] = x_min[i]; else if (x_max && x_vec[i] > x_max[i]) x_vec[i] = x_max[i]; } // Check termination criteria // TO-DO } return true; } // TODO: UNTESTED // TODO: Check for positive semi-definite (if necessary), i.e. the JB matrix // TODO: Add alternate methods for termination / error checking? // TODO: How to handle infinity for min/max? // SolvePGSCatto() - Solve an MLCP (Mixed Linear Complimentarity Problem) using Projected Gauss- // Seidel method, an extension of Gauss-Seidel. In a computer graphics application, the primary use // case for this method is to solve systems of inequalities related to constraints such as non- // penetrating collisions, joints, etc. This implementation has been written with that particular // case in mind and is not be a fully generalized MLCP / PGS algorithm (though functionally the same). // This algorithm assumes constraints only exist between pairs of bodies, so J and B are stored in a // "sparse" format with fixed number of columns based on body dimensionality (i.e. n_d). This requires // J_map to decode. // References: https://www.toptal.com/game/video-game-physics-part-iii-constrained-rigid-body-simulation // Erin Catto GDC 2005 https://code.google.com/archive/p/box2d/downloads // Format: JBλ = η or J_mat*B_mat*x_vec = z_vec // Inputs: J_sp = [s by 2*n_d] jacobian matrix of constraint functions (sparse) // J_map = [s by 2] mapping of sparse jacobian matrix bodies // Note: Each element(i,j) is the index of a rigid body. By convention, if a constraint // is between a single rigid body and ground, then (i,1) = 0 and the corresponding // J(i,1) is zero. // B_mat = [n*n_d by s] M(inv)*J(transpose) // M is a mass and inertia diagonal matrix of n*n_d by n*n_d // z_vec (η) = [n*n_d] (1/dt)*ζ - J((1/dt)*V1 + M(inv)*F_ext) // ζ is a constraint bias factor for stabilization // V1 is the initial (previous) velocity // F_ext is the external force acting on a body // x_min (λ-) = minimum bound // x_max (λ+) = maximum bound // s = number of constraints // n = number of bodies // n_d = number of elements per body (i.e. x,y,theta; x,y,z,quat(a,b,c); etc) // Return: x_vec (λ) = [s] solution of unknowns // Note: x_vec may be initialized with a best-guess (e.g. results from prev. // frame) to warm-start the algorithm. // return boolean specifying whether the operation was successful or not template <typename T> bool SolvePGSCatto() { //TO-DO return false; // TEMP } #endif <commit_msg>Finished implementation of SolveMLCP_PGS_Catto (still untested)<commit_after>// ***************************************************************************************************************************** // math_misc.hpp // Miscellaneous Math Functions // Author(s): Cory Douthat // Copyright (c) 2020 Cory Douthat, All Rights Reserved. // ***************************************************************************************************************************** #ifndef MATH_MISC_HPP_ #define MATH_MISC_HPP_ #include <stdlib.h> #define _USE_MATH_DEFINES //For PI definition #include <cmath> #include <limits> #include "vec.hpp" #include "mat.hpp" // Determinant() - Calculate the determinant of an arbitrary-sized square matrix // Inputs: mat = matrix data array // size = matrix size (width of square matrix) // Return: determinant result template <typename T> T Determinant(const T *mat,unsigned int size) { if (size < 2) return (T)0; // 2x2 if (size == 2) return Mat2<T>(mat).det(); // 3x3 if (size == 3) return Mat3<T>(mat).det(); // 4x4 if (size == 4) return Mat4<T>(mat).det(); // 5x5+ T det = (T)0; T *sub_mat; sub_mat = new T[(size - 1)*(size - 1)]; for (unsigned int i = 0; i < size; i++) { int col = 0; for (unsigned int col_maj = 0; col_maj < size; col_maj++) { if (col_maj != i) { for (unsigned int row = 0; row < size - 1; row++) { sub_mat[col*(size - 1) + row] = mat[col_maj*(size) + row + 1]; } col++; } } if (i % 2 == 0) det += mat[i*size] * Determinant(sub_mat,size - 1); else det -= mat[i*size] * Determinant(sub_mat,size - 1); } delete sub_mat; return det; } // CAUTION: Numerically unstable. Use Gaussian Elimination instead unless you know what you're doing. // SolveCramer() - Solve a system of linear equations using Cramer's Rule. // Format Ax = b // Inputs: A_mat = n x n matrix (array) defining the coefficients of the equations // b_vec = n size vector (array) defining right-hand side of each linear equation // n = number of equations/variables // Return: x_vec = n size vector (array) representing solutions - passed by pointer // return boolean specifying whether the operation was successful or not template <typename T> bool SolveCramer(const T *A_mat,const T *b_vec,unsigned int n,T *x_vec) { T det_A = Determinant(A_mat,n); if (det_A == T(0)) return false; // Matrix for temporary A with column replaced T *Ai = new T[n * n]; memcpy(Ai,A_mat,n * n * sizeof(T)); for (unsigned int i = 0; i < n; i++) { // Copy in b vector to column i memcpy(&Ai[i * n],b_vec,n * sizeof(T)); // Solve for xi x_vec[i] = Determinant(Ai,n) / det_A; // Copy regular values back into column i memcpy(&Ai[i * n],&A_mat[i * n],n * sizeof(T)); } return true; } // TODO: Improve efficiency by checking for special cases or no solution earlier? // SolveGaussElim() - Solve a system of linear equations using Gaussian Elimination // Performs Partial Pivoting; does not perform Full Pivoting // Format: Ax = b // Inputs: A_mat = n x n matrix (array) defining the coefficients of the equations // b_vec = n size vector (array) defining right-hand side of each linear equation // n = number of equations/variables // Return: x_vec = n size vector (array) representing solutions - passed by pointer // return boolean specifying whether the operation was successful or not template <typename T> bool SolveGaussElim(const T *A_mat, const T *b_vec, unsigned int n, T *x_vec) { T *A = new T[n*n]; T *b = new T[n]; memcpy(A, A_mat, sizeof(T)*n*n); memcpy(b, b_vec, sizeof(T)*n); unsigned int *row_index = new unsigned int[n]; // Vector to track row order for (unsigned int i = 0; i < n; i++) row_index[i] = i; // Reduce matrix to row echelon form using Gaussian Elimination and partial pivoting for (unsigned int r = 0; r < n; r++) { // Pivot row 'r' (check for rows with larger absolute values in the pivot column) if (r < n - 1) // Do not do this when on last row { for (unsigned int i = r + 1; i < n; i++) { // Check each successive row to see if absolute value in 'r'th column is larger if (abs(A[r*n + row_index[i]]) > abs(A[r*n + row_index[r]])) { // Swap rows unsigned int temp = row_index[r]; row_index[r] = row_index[i]; row_index[i] = temp; } } } // Check for zero pivot (no solution) if (A[r*n + row_index[r]] == (T)0) { delete A; delete b; delete row_index; return false; } // Reduce successive rows (eliminate columns below pivot of 'r') if (r < n - 1) // Do not do this when on last row { for (unsigned int i = r + 1; i < n; i++) // ROWS { // Multiplication factor T temp_mult = A[r*n + row_index[i]] / A[r*n + row_index[r]]; // First column set 0 A[r*n + row_index[i]] = (T)0; // Addl columns for (unsigned int j = r + 1; j < n; j++) A[j*n + row_index[i]] -= temp_mult * A[j*n + row_index[r]]; // b vector b[row_index[i]] -= temp_mult * b[row_index[r]]; } } } // Back-substitue for x values for (int x = n - 1; x >= 0; x--) { // Set 'x' to right side of equation x_vec[x] = b[row_index[x]]; // Subtract known 'x' values from right side of equation for (int j = n - 1; j > x; j--) { x_vec[x] -= x_vec[j] * A[j*n + row_index[x]]; } // Solve for 'x' x_vec[x] /= A[x*n + row_index[x]]; } delete A; delete b; delete row_index; return true; } // TODO: UNTESTED // SolveMLCP_PGS_Catto() - Solve an MLCP (Mixed Linear Complimentarity Problem) using Projected Gauss- // Seidel method, an extension of Gauss-Seidel. In a computer graphics application, the primary use // case for this method is to solve systems of inequalities related to constraints such as non- // penetrating collisions, joints, etc. This implementation has been written with that particular // case in mind and is not be a fully generalized MLCP / PGS algorithm (though functionally the same). // This algorithm assumes constraints only exist between pairs of bodies, so J and B are stored in a // "sparse" format with fixed number of columns based on body dimensionality (i.e. n_d). This requires // J_map to decode. // References: https://www.toptal.com/game/video-game-physics-part-iii-constrained-rigid-body-simulation // Erin Catto GDC 2005 https://code.google.com/archive/p/box2d/downloads // Format: JBλ = η or JBx = z // Note: All matrix arrays stored in column major order // Inputs: J_sp = [s by 2*n_d] // Jacobian matrix of constraint functions (sparse) // J_map = [s by 2] // Mapping of sparse jacobian matrix bodies (0 indexed) // Note: Each element(i,j) is the index of a rigid body. By convention, if a constraint // is between a single rigid body and ground, then (i,0) = 0 and the corresponding // J(i,0) is zero. // B_sp = [2*n_d by s] // B term: M(inv)*J(transpose) (sparse) // M is a mass and inertia diagonal matrix of n*n_d by n*n_d // Use J_map for indexing // z_vec (η) = [s] // z(η) term: (1/dt)*ζ - J((1/dt)*V1 + M(inv)*F_ext) // ζ is a constraint bias factor for stabilization // V1 is the initial (previous) velocity // F_ext is the external force acting on a body // x_min_vec (λ-) = [s] // Minimum bound - use std inf (1.0 / 0.0) or max value to represent positive infinity // x_max_vec (λ+) = [s] // Maximum bound - use std -inf (-1.0 / 0.0) or lowest value to represent negative infinity // s = number of constraints // n = number of bodies // n_d = number of elements per body (i.e. x,y,theta; x,y,z,quat(a,b,c); etc) // max_iter = maximum number of iterations // x0_vec_in (λ0) [s] // Warm start - initial guess at λ, usually result from the previous frame // Return: x_vec (λ) = [s] // Solution of unknowns // Note: x_vec may be initialized with a best-guess (e.g. results from prev. frame) // to warm-start the algorithm. // (return) boolean specifying whether the operation was successful or not template <typename T> bool SolveMLCP_PGS_Catto(const T *J_sp, const unsigned int *J_map, const T *B_sp, const T *z_vec, const T *x_min_vec, const T *x_max_vec, unsigned int s, unsigned int n, unsigned int n_d, unsigned int max_iter, const T *x0_vec_in, T *x_vec) { // TO-DO: // Add early termination checks - less than max error, etc // Check for valid pointers, ints, etc // Check max iterations for <= 0 and do something with it // Check for positive semi-definite (if necessary), i.e. the JB matrix // Work Variables T a* = new T[n * n_d]; T d* = new T[s]; T temp1* = new T[n_d]; // Temp array vector T temp3* = new T[n_d]; // Temp array vector T temp2* = new T[n_d]; // Temp array vector T temp4* = new T[n_d]; // Temp array vector unsigned int b1; // Jmap object 1 index unsigned int b2; // Jmap object 2 index T x_delta; // Temporary x(λ) delta T a_b1* = new T[n_d]; // Temp array vector T a_b2* = new T[n_d]; // Temp array vector // Copy x0_vec_in T x0_vec* = new T[s]; if (x0_vec_in) memcpy(x0_vec, x0_vec_in, s * sizeof(T)); else memset(x0_vec, 0, s * sizeof(T)); // Initialize / Warm Start x memcpy(x_vec, x0_vec, s * sizeof(T)); // Initialize work variable a a = ArrayMatMult(B, x); // Initialize work variable d // d(i) = dot(Jsp(i,0),Bsp(0,i)) + dot(Jsp(i,1),Bsp(1,i)) for (int i = 0; i < s; i++) { for (int j = 0; j < n_d; j++) { // Get J_sp(i,0) (i.e. first n_d-length half of row) temp1[j] = J_sp[j * s + i]; // Get J_sp(i,1) (i.e. second n_d-length half of row) temp3[j] = J_sp[(j + n_d) * s + i]; // Get B_sp(0,i) (i.e. first n_d-length half of col) temp2[j] = B_sp[i * (2 * n_d) + j]; // Get B_sp(1,i) (i.e. second n_d-length half of col) temp4[j] = B_sp[i * (2 * n_d) + j + n_d]; } d[i] = ArrayVecDot(temp1, temp2) + ArrayVecDot(temp3, temp4); } // Main Iterative Loop for (int iter = 1; iter <= max_iter; iter++) { for (int i = 0; i < s; i++) { for (int j = 0; j < n_d; j++) { // Get J_sp(i,0) (i.e. first n_d-length half of row) temp1[j] = J_sp[j * s + i]; // Get J_sp(i,1) (i.e. second n_d-length half of row) temp3[j] = J_sp[(j + n_d) * s + i]; // Get B_sp(0,i) (i.e. first n_d-length half of col) temp2[j] = B_sp[i * (2 * n_d) + j]; // Get B_sp(1,i) (i.e. second n_d-length half of col) temp4[j] = B_sp[i * (2 * n_d) + j + n_d]; // Get a(b1) a_b1[j] = a[b1 * n_d + j]; // Get a(b2) a_b2[j] = a[b2 * n_d + j]; } b1 = J_map[i]; // Object 1 index b2 = J_map[s + i]; // Object 2 index // Tentative x_delta x_delta = (z_vec[i] - ArrayVecDot(temp1, a_b1) - ArrayVecDot(temp3, a_b2)) / d[i]; // Test against constraints x0_vec[i] = x_vec[i]; // Save last iteration result (same on first loop) x_vec[i] = max(x_min_vec, min(x0_vec[i] + x_delta, x_max_vec)); // Check min/max x_delta = x_vec[i] - x0_vec[i]; // Final delta // Update work variable a for (int j = 0; j < n_d; j++) { a[b1 * n_d + j] = a_b1[j] + x_delta[i] * temp2[j]; a[b2 * n_d + j] = a_b2[j] + x_delta[i] * temp4[j]; } } } return true; // TODO - check for issues } #endif <|endoftext|>