<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// 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 "BitFunnel/Allocators/IAllocator.h"
#include "BitFunnel/IDiagnosticStream.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/IShard.h"
#include "BitFunnel/Index/Token.h"
#include "BitFunnel/Plan/Factories.h"
#include "BitFunnel/Plan/QueryInstrumentation.h"
#include "BitFunnel/Plan/TermMatchNode.h"
#include "BitFunnel/Utilities/Factories.h"
#include "BitFunnel/Utilities/IObjectFormatter.h"
#include "ByteCodeInterpreter.h"
#include "CompileNode.h"
#include "IPlanRows.h"
#include "MatchTreeCompiler.h"
#include "MatchTreeRewriter.h"
#include "QueryPlanner.h"
#include "QueryResources.h"
#include "RankDownCompiler.h"
#include "RegisterAllocator.h"
#include "RowSet.h"
#include "TermPlan.h"
#include "TermPlanConverter.h"

namespace BitFunnel
{
    // TODO: remove. This is a quick shortcut to try to connect QueryPlanner the
    // way SimplePlanner is connected.
    void Factories::RunQueryPlanner(TermMatchNode const & tree,
                                    ISimpleIndex const & index,
                                    QueryResources & resources,
                                    IDiagnosticStream & diagnosticStream,
                                    QueryInstrumentation & instrumentation,
                                    ResultsBuffer & resultsBuffer,
                                    bool useNativeCode)
    {
        const int c_arbitraryRowCount = 500;
        QueryPlanner planner(tree,
                             c_arbitraryRowCount,
                             index,
                             resources,
                             diagnosticStream,
                             instrumentation,
                             resultsBuffer,
                             useNativeCode);
    }

    unsigned const c_targetCrossProductTermCount = 180;

    // TODO: this should take a TermPlan instead of a TermMatchNode when we have
    // scoring and query preferences.
    QueryPlanner::QueryPlanner(TermMatchNode const & tree,
                               unsigned targetRowCount,
                               ISimpleIndex const & index,
                               QueryResources & resources,
                               IDiagnosticStream & diagnosticStream,
                               QueryInstrumentation & instrumentation,
                               ResultsBuffer & resultsBuffer,
                               bool useNativeCode)
      : m_resultsBuffer(resultsBuffer)
    {
        if (diagnosticStream.IsEnabled("planning/term"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Term Plan:" << std::endl;
            tree.Format(*formatter);
            out << std::endl;
        }

        RowPlan const & rowPlan =
            TermPlanConverter::BuildRowPlan(tree,
                                            index,
                                            // generateNonBodyPlan,
                                            resources.GetMatchTreeAllocator());

        if (diagnosticStream.IsEnabled("planning/row"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Row Plan:" << std::endl;
            rowPlan.Format(*formatter);
            out << std::endl;
        }

        m_planRows = &rowPlan.GetPlanRows();

        if (diagnosticStream.IsEnabled("planning/planrows"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "IPlanRows:" << std::endl;
            out << "  ShardCount: " << m_planRows->GetShardCount() << std::endl;
            for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)
            {
                for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)
                {
                    RowId row = m_planRows->PhysicalRow(shard, id);

                    out
                        << "  (" << shard << ", " << id << "): "
                        << "RowId(" << ", " << row.GetRank()
                        << ", " << row.GetIndex() << ")" << std::endl;
                }
            }
        }

        // Rewrite match tree to optimal form for the RankDownCompiler.
        RowMatchNode const & rewritten =
            MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),
                                       targetRowCount,
                                       c_targetCrossProductTermCount,
                                       resources.GetMatchTreeAllocator());

        if (diagnosticStream.IsEnabled("planning/rewrite"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Rewritten Plan:" << std::endl;
            rewritten.Format(*formatter);
            out << std::endl;
        }

        // Compile the match tree into CompileNodes.
        RankDownCompiler compiler(resources.GetMatchTreeAllocator());
        compiler.Compile(rewritten);
        const Rank initialRank = compiler.GetMaximumRank();
        CompileNode const & compileTree = compiler.CreateTree(initialRank);

        if (diagnosticStream.IsEnabled("planning/compile"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Compile Nodes:" << std::endl;
            compileTree.Format(*formatter);
            out << std::endl;
        }

        RowSet rowSet(index, *m_planRows, resources.GetMatchTreeAllocator());
        rowSet.LoadRows();

        if (diagnosticStream.IsEnabled("planning/rowset"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            out << "--------------------" << std::endl;
            out << "Row Set:" << std::endl;
            out << "  ShardCount: " << rowSet.GetShardCount() << std::endl;
            out << "  Row Count: " << rowSet.GetRowCount() << std::endl;

        }

        instrumentation.SetRowCount(rowSet.GetRowCount());

        if (useNativeCode)
        {
            RunNativeCode(index,
                          resources,
                          instrumentation,
                          compileTree,
                          initialRank,
                          rowSet);
        }
        else
        {
            RunByteCodeInterpreter(index,
                                   resources,
                                   instrumentation,
                                   compileTree,
                                   initialRank,
                                   rowSet);
        }
    }

    void QueryPlanner::RunByteCodeInterpreter(ISimpleIndex const & index,
                                              QueryResources & resources,
                                              QueryInstrumentation & instrumentation,
                                              CompileNode const & compileTree,
                                              Rank initialRank,
                                              RowSet const & rowSet)
    {
        // TODO: Clear results buffer here?
        compileTree.Compile(m_code);
        m_code.Seal();

        instrumentation.FinishPlanning();

        // Get token before we GetSliceBuffers.
        {
            auto token = index.GetIngestor().GetTokenManager().RequestToken();

            for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)
            {
                auto & shard = index.GetIngestor().GetShard(shardId);
                auto & sliceBuffers = shard.GetSliceBuffers();

                // Iterations per slice calculation.
                auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;

                m_resultsBuffer.Reset();

                ByteCodeInterpreter intepreter(m_code,
                                               m_resultsBuffer,
                                               sliceBuffers.size(),
                                               sliceBuffers.data(),
                                               iterationsPerSlice,
                                               initialRank,
                                               rowSet.GetRowOffsets(shardId),
                                               nullptr,
                                               instrumentation,
                                               resources.GetCacheLineRecorder());

                intepreter.Run();
            }

            instrumentation.FinishMatching();
            instrumentation.SetMatchCount(m_resultsBuffer.size());
        } // End of token lifetime.
    }

    void QueryPlanner::RunNativeCode(ISimpleIndex const & index,
                                     QueryResources & resources,
                                     QueryInstrumentation & instrumentation,
                                     CompileNode const & compileTree,
                                     Rank initialRank,
                                     RowSet const & rowSet)
    {
         // Perform register allocation on the compile tree.
         RegisterAllocator const registers(compileTree,
                                           rowSet.GetRowCount(),
                                           c_registerBase,
                                           c_registerCount,
                                           resources.GetMatchTreeAllocator());

         MatchTreeCompiler compiler(resources,
                                    compileTree,
                                    registers,
                                    initialRank);

         // TODO: Clear results buffer here?
        compileTree.Compile(m_code);
        m_code.Seal();

        instrumentation.FinishPlanning();

        // Get token before we GetSliceBuffers.
        {
            auto token = index.GetIngestor().GetTokenManager().RequestToken();

            for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)
            {
                auto & shard = index.GetIngestor().GetShard(shardId);
                auto & sliceBuffers = shard.GetSliceBuffers();

                // Iterations per slice calculation.
                auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;

                m_resultsBuffer.Reset();

                size_t quadwordCount = compiler.Run(sliceBuffers.size(),
                                                    sliceBuffers.data(),
                                                    iterationsPerSlice,
                                                    rowSet.GetRowOffsets(shardId),
                                                    m_resultsBuffer);

                instrumentation.IncrementQuadwordCount(quadwordCount);
            }

            instrumentation.FinishMatching();
            instrumentation.SetMatchCount(m_resultsBuffer.size());
        } // End of token lifetime.
    }

    IPlanRows const & QueryPlanner::GetPlanRows() const
    {
        return *m_planRows;
    }
}
<commit_msg>Avoid throwing away all but last shard's results. Fixes #380.<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// 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 "BitFunnel/Allocators/IAllocator.h"
#include "BitFunnel/IDiagnosticStream.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/IShard.h"
#include "BitFunnel/Index/Token.h"
#include "BitFunnel/Plan/Factories.h"
#include "BitFunnel/Plan/QueryInstrumentation.h"
#include "BitFunnel/Plan/TermMatchNode.h"
#include "BitFunnel/Utilities/Factories.h"
#include "BitFunnel/Utilities/IObjectFormatter.h"
#include "ByteCodeInterpreter.h"
#include "CompileNode.h"
#include "IPlanRows.h"
#include "MatchTreeCompiler.h"
#include "MatchTreeRewriter.h"
#include "QueryPlanner.h"
#include "QueryResources.h"
#include "RankDownCompiler.h"
#include "RegisterAllocator.h"
#include "RowSet.h"
#include "TermPlan.h"
#include "TermPlanConverter.h"

namespace BitFunnel
{
    // TODO: remove. This is a quick shortcut to try to connect QueryPlanner the
    // way SimplePlanner is connected.
    void Factories::RunQueryPlanner(TermMatchNode const & tree,
                                    ISimpleIndex const & index,
                                    QueryResources & resources,
                                    IDiagnosticStream & diagnosticStream,
                                    QueryInstrumentation & instrumentation,
                                    ResultsBuffer & resultsBuffer,
                                    bool useNativeCode)
    {
        const int c_arbitraryRowCount = 500;
        QueryPlanner planner(tree,
                             c_arbitraryRowCount,
                             index,
                             resources,
                             diagnosticStream,
                             instrumentation,
                             resultsBuffer,
                             useNativeCode);
    }

    unsigned const c_targetCrossProductTermCount = 180;

    // TODO: this should take a TermPlan instead of a TermMatchNode when we have
    // scoring and query preferences.
    QueryPlanner::QueryPlanner(TermMatchNode const & tree,
                               unsigned targetRowCount,
                               ISimpleIndex const & index,
                               QueryResources & resources,
                               IDiagnosticStream & diagnosticStream,
                               QueryInstrumentation & instrumentation,
                               ResultsBuffer & resultsBuffer,
                               bool useNativeCode)
      : m_resultsBuffer(resultsBuffer)
    {
        if (diagnosticStream.IsEnabled("planning/term"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Term Plan:" << std::endl;
            tree.Format(*formatter);
            out << std::endl;
        }

        RowPlan const & rowPlan =
            TermPlanConverter::BuildRowPlan(tree,
                                            index,
                                            // generateNonBodyPlan,
                                            resources.GetMatchTreeAllocator());

        if (diagnosticStream.IsEnabled("planning/row"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Row Plan:" << std::endl;
            rowPlan.Format(*formatter);
            out << std::endl;
        }

        m_planRows = &rowPlan.GetPlanRows();

        if (diagnosticStream.IsEnabled("planning/planrows"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "IPlanRows:" << std::endl;
            out << "  ShardCount: " << m_planRows->GetShardCount() << std::endl;
            for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)
            {
                for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)
                {
                    RowId row = m_planRows->PhysicalRow(shard, id);

                    out
                        << "  (" << shard << ", " << id << "): "
                        << "RowId(" << ", " << row.GetRank()
                        << ", " << row.GetIndex() << ")" << std::endl;
                }
            }
        }

        // Rewrite match tree to optimal form for the RankDownCompiler.
        RowMatchNode const & rewritten =
            MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),
                                       targetRowCount,
                                       c_targetCrossProductTermCount,
                                       resources.GetMatchTreeAllocator());

        if (diagnosticStream.IsEnabled("planning/rewrite"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Rewritten Plan:" << std::endl;
            rewritten.Format(*formatter);
            out << std::endl;
        }

        // Compile the match tree into CompileNodes.
        RankDownCompiler compiler(resources.GetMatchTreeAllocator());
        compiler.Compile(rewritten);
        const Rank initialRank = compiler.GetMaximumRank();
        CompileNode const & compileTree = compiler.CreateTree(initialRank);

        if (diagnosticStream.IsEnabled("planning/compile"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));

            out << "--------------------" << std::endl;
            out << "Compile Nodes:" << std::endl;
            compileTree.Format(*formatter);
            out << std::endl;
        }

        RowSet rowSet(index, *m_planRows, resources.GetMatchTreeAllocator());
        rowSet.LoadRows();

        if (diagnosticStream.IsEnabled("planning/rowset"))
        {
            std::ostream& out = diagnosticStream.GetStream();
            out << "--------------------" << std::endl;
            out << "Row Set:" << std::endl;
            out << "  ShardCount: " << rowSet.GetShardCount() << std::endl;
            out << "  Row Count: " << rowSet.GetRowCount() << std::endl;

        }

        instrumentation.SetRowCount(rowSet.GetRowCount());

        if (useNativeCode)
        {
            RunNativeCode(index,
                          resources,
                          instrumentation,
                          compileTree,
                          initialRank,
                          rowSet);
        }
        else
        {
            RunByteCodeInterpreter(index,
                                   resources,
                                   instrumentation,
                                   compileTree,
                                   initialRank,
                                   rowSet);
        }
    }

    void QueryPlanner::RunByteCodeInterpreter(ISimpleIndex const & index,
                                              QueryResources & resources,
                                              QueryInstrumentation & instrumentation,
                                              CompileNode const & compileTree,
                                              Rank initialRank,
                                              RowSet const & rowSet)
    {
        // TODO: Clear results buffer here?
        compileTree.Compile(m_code);
        m_code.Seal();

        instrumentation.FinishPlanning();
        m_resultsBuffer.Reset();

        // Get token before we GetSliceBuffers.
        {
            auto token = index.GetIngestor().GetTokenManager().RequestToken();

            for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)
            {
                auto & shard = index.GetIngestor().GetShard(shardId);
                auto & sliceBuffers = shard.GetSliceBuffers();

                // Iterations per slice calculation.
                auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;

                ByteCodeInterpreter intepreter(m_code,
                                               m_resultsBuffer,
                                               sliceBuffers.size(),
                                               sliceBuffers.data(),
                                               iterationsPerSlice,
                                               initialRank,
                                               rowSet.GetRowOffsets(shardId),
                                               nullptr,
                                               instrumentation,
                                               resources.GetCacheLineRecorder());

                intepreter.Run();
            }

            instrumentation.FinishMatching();
            instrumentation.SetMatchCount(m_resultsBuffer.size());
        } // End of token lifetime.
    }

    void QueryPlanner::RunNativeCode(ISimpleIndex const & index,
                                     QueryResources & resources,
                                     QueryInstrumentation & instrumentation,
                                     CompileNode const & compileTree,
                                     Rank initialRank,
                                     RowSet const & rowSet)
    {
         // Perform register allocation on the compile tree.
         RegisterAllocator const registers(compileTree,
                                           rowSet.GetRowCount(),
                                           c_registerBase,
                                           c_registerCount,
                                           resources.GetMatchTreeAllocator());

         MatchTreeCompiler compiler(resources,
                                    compileTree,
                                    registers,
                                    initialRank);

         // TODO: Clear results buffer here?
        compileTree.Compile(m_code);
        m_code.Seal();

        instrumentation.FinishPlanning();

        m_resultsBuffer.Reset();

        // Get token before we GetSliceBuffers.
        {
            auto token = index.GetIngestor().GetTokenManager().RequestToken();

            for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)
            {
                auto & shard = index.GetIngestor().GetShard(shardId);
                auto & sliceBuffers = shard.GetSliceBuffers();

                // Iterations per slice calculation.
                auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;

                size_t quadwordCount = compiler.Run(sliceBuffers.size(),
                                                    sliceBuffers.data(),
                                                    iterationsPerSlice,
                                                    rowSet.GetRowOffsets(shardId),
                                                    m_resultsBuffer);

                instrumentation.IncrementQuadwordCount(quadwordCount);
            }

            instrumentation.FinishMatching();
            instrumentation.SetMatchCount(m_resultsBuffer.size());
        } // End of token lifetime.
    }

    IPlanRows const & QueryPlanner::GetPlanRows() const
    {
        return *m_planRows;
    }
}
<|endoftext|>


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

#include "base/command_line.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/media_switches.h"
#include "net/test/embedded_test_server/embedded_test_server.h"

static const char kMainWebrtcTestHtmlPage[] =
    "/webrtc/webrtc_jsep01_test.html";

// Top-level integration test for WebRTC. It always uses fake devices; see
// WebRtcWebcamBrowserTest for a test that acquires any real webcam on the
// system.
class WebRtcBrowserTest : public WebRtcTestBase {
 public:
  void SetUpInProcessBrowserTestFixture() override {
    DetectErrorsInJavaScript();  // Look for errors in our rather complex js.
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Ensure the infobar is enabled, since we expect that in this test.
    EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));

    // Always use fake devices.
    command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);

    // Flag used by TestWebAudioMediaStream to force garbage collection.
    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
  }
};

// Flaky on ChromeOS (?), Windows: http://crbug.com/443542.
#if defined(OS_CHROMEOS) || defined(OS_WIN)
#define MAYBE_RunsAudioVideoWebRTCCallInTwoTabs \
    DISABLED_RunsAudioVideoWebRTCCallInTwoTabs
#else
#define MAYBE_RunsAudioVideoWebRTCCallInTwoTabs \
    RunsAudioVideoWebRTCCallInTwoTabs
#endif
IN_PROC_BROWSER_TEST_F(WebRtcBrowserTest,
                       MAYBE_RunsAudioVideoWebRTCCallInTwoTabs) {
  if (OnWinXp()) return;

  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());

  content::WebContents* left_tab =
      OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);
  content::WebContents* right_tab =
      OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);

  SetupPeerconnectionWithLocalStream(left_tab);
  SetupPeerconnectionWithLocalStream(right_tab);

  NegotiateCall(left_tab, right_tab);

  StartDetectingVideo(left_tab, "remote-view");
  StartDetectingVideo(right_tab, "remote-view");

#if !defined(OS_MACOSX)
  // Video is choppy on Mac OS X. http://crbug.com/443542.
  WaitForVideoToPlay(left_tab);
  WaitForVideoToPlay(right_tab);
#endif

  HangUp(left_tab);
  HangUp(right_tab);
}

IN_PROC_BROWSER_TEST_F(WebRtcBrowserTest, TestWebAudioMediaStream) {
  // This tests against crash regressions for the WebAudio-MediaStream
  // integration.
  if (OnWinXp()) return;

  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  GURL url(embedded_test_server()->GetURL("/webrtc/webaudio_crash.html"));
  ui_test_utils::NavigateToURL(browser(), url);
  content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();

  // A sleep is necessary to be able to detect the crash.
  test::SleepInJavascript(tab, 1000);

  ASSERT_FALSE(tab->IsCrashed());
}
<commit_msg>Trying to re-enable WebRTC browser test on win and CrOS.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/media_switches.h"
#include "net/test/embedded_test_server/embedded_test_server.h"

static const char kMainWebrtcTestHtmlPage[] =
    "/webrtc/webrtc_jsep01_test.html";

// Top-level integration test for WebRTC. It always uses fake devices; see
// WebRtcWebcamBrowserTest for a test that acquires any real webcam on the
// system.
class WebRtcBrowserTest : public WebRtcTestBase {
 public:
  void SetUpInProcessBrowserTestFixture() override {
    DetectErrorsInJavaScript();  // Look for errors in our rather complex js.
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Ensure the infobar is enabled, since we expect that in this test.
    EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));

    // Always use fake devices.
    command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);

    // Flag used by TestWebAudioMediaStream to force garbage collection.
    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
  }
};

IN_PROC_BROWSER_TEST_F(WebRtcBrowserTest,
                       RunsAudioVideoWebRTCCallInTwoTabs) {
  if (OnWinXp()) return;

  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());

  content::WebContents* left_tab =
      OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);
  content::WebContents* right_tab =
      OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);

  SetupPeerconnectionWithLocalStream(left_tab);
  SetupPeerconnectionWithLocalStream(right_tab);

  NegotiateCall(left_tab, right_tab);

  StartDetectingVideo(left_tab, "remote-view");
  StartDetectingVideo(right_tab, "remote-view");

#if !defined(OS_MACOSX)
  // Video is choppy on Mac OS X. http://crbug.com/443542.
  WaitForVideoToPlay(left_tab);
  WaitForVideoToPlay(right_tab);
#endif

  HangUp(left_tab);
  HangUp(right_tab);
}

IN_PROC_BROWSER_TEST_F(WebRtcBrowserTest, TestWebAudioMediaStream) {
  // This tests against crash regressions for the WebAudio-MediaStream
  // integration.
  if (OnWinXp()) return;

  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  GURL url(embedded_test_server()->GetURL("/webrtc/webaudio_crash.html"));
  ui_test_utils::NavigateToURL(browser(), url);
  content::WebContents* tab =
      browser()->tab_strip_model()->GetActiveWebContents();

  // A sleep is necessary to be able to detect the crash.
  test::SleepInJavascript(tab, 1000);

  ASSERT_FALSE(tab->IsCrashed());
}
<|endoftext|>


<commit_before>#include "FoundationModel.h"
#include <iomanip>      // Included this to create tables - debugging

namespace voom {

  // Constructor
  FoundationModel::FoundationModel(Mesh* aMesh, const uint NodeDoF, const string SpNodes, Real SpringK):
  Model(aMesh, NodeDoF), _springK(SpringK)
  {
    _field.resize(  (_myMesh->getNumberOfNodes() )*_nodeDoF );
    this->initializeField();
    this->initSpringBC(SpNodes);
  }

  // Compute Function - Compute Energy, Force, Stiffness
  void FoundationModel::compute(Result * R)
  {
    const vector<GeomElement* > elements = _myMesh->getElements();
    const int AvgNodePerEl = ((elements[0])->getNodesID()).size();
    const int NumEl = elements.size();
    const int dim = _myMesh->getDimension();
    vector<Triplet<Real > > KtripletList;

    int PbDoF = R->getPbDoF();

    // Reset values in result struct
    // Todo: Once we have the wrapper, we won't want to do this
    if ( R->getRequest() & ENERGY ) {
      R->setEnergy(0.0);
    }
    if ( R->getRequest() & FORCE)  {
      R->resetResidualToZero();
    }
    if ( R->getRequest() & STIFFNESS ) {
      // R->resetStiffnessToZero();
      KtripletList.reserve(dim*dim*NumEl*AvgNodePerEl*AvgNodePerEl);
    }

    // Loop through nodes
    MechanicsMaterial::FKresults FKres;
    FKres.request = R->getRequest();

    //** Insert stuff from the spring here **//
    vector <Triplet<Real > > KtripletList_FromSpring;

    // Loop through _spNodes
    for(int n = 0; n < _spNodes.size(); n++)
    {
      int NodeID = _spNodes[n];
      Vector3d xa_prev, xa_curr;
      xa_prev << _prevField[NodeID*3], _prevField[NodeID*3+1], _prevField[NodeID*3+2];
      xa_curr << _field[NodeID*3], _field[NodeID*3+1], _field[NodeID*3+2];

      // Compute energy
      if (R->getRequest() & ENERGY) {
        R->addEnergy( 0.5* _springK*pow( (xa_curr - xa_prev).dot(_spNormals[n]), 2.0) );
      }

      // Compute Residual
      if ((R->getRequest() & FORCE)) {
        for(uint i = 0; i < 3; i++) {
          R->addResidual(NodeID*3+i,  _springK*_spNormals[n](i)*(xa_curr - xa_prev).dot(_spNormals[n]) );
        } // i loop
      } // Internal force loop

      // Compute stiffness matrix
      if ( R->getRequest() & STIFFNESS ) {
        for(uint i = 0; i < 3; i++) {
          for(uint j = 0; j < 3; j++) {
            KtripletList_FromSpring.push_back(Triplet<Real >( NodeID*3+i, NodeID*3+j, _springK*_spNormals[n](i)*_spNormals[n](j) ));
          } // j loop
        } // i loop
        KtripletList.insert( KtripletList.end(), KtripletList_FromSpring.begin(), KtripletList_FromSpring.end() );
        R->setStiffnessFromTriplets(KtripletList);
        R->FinalizeGlobalStiffnessAssembly();
      } // Stiffness loop
    } // Spring nodes loop
  } // Compute Mechanics Model

  void FoundationModel::computeNormals() {

    // First compute normal of any element in _myMesh
    const vector<GeomElement* > elements = _myMesh->getElements();

    vector<Vector3d > ElNormals(elements.size(), Vector3d::Zero());

    // Loop over elements
    for(int e = 0; e < elements.size(); e++)
    {
      GeomElement* geomEl = elements[e];
      const vector<int  >& NodesID = geomEl->getNodesID();
      const int numQP    = geomEl->getNumberOfQuadPoints();
      const int numNodes = NodesID.size();

      // Loop over quadrature points
      for(int q = 0; q < numQP; q++) {

        // Compute normal based on _prevField
        Vector3d a1 = Vector3d::Zero(), a2 = Vector3d::Zero(), a3 = Vector3d::Zero();
        for (int a = 0; a < NodesID.size(); a++) {
          int nodeID = NodesID[a];
          Vector3d xa_prev;
          xa_prev << _prevField[nodeID*3], _prevField[nodeID*3+1], _prevField[nodeID*3+2];
          a1 += xa_prev*geomEl->getDN(q, a, 0);
          a2 += xa_prev*geomEl->getDN(q, a, 1);
        }
        ElNormals[e] += a1.cross(a2); // Not normalized with respect to area (elements with larger area count more)
      } // loop over QP

    } // loop over elements

    // loop over _spNodes
    for (int n = 0; n < _spNodes.size(); n++) {
      // Reset normal to zero
      _spNormals[n] = Vector3d::Zero();
      // Loop over all elements sharing that node
      for (int m = 0; m < _spNodesToEle[n].size(); m++) {
        _spNormals[n] += ElNormals[_spNodesToEle[n][m]];
      }
      Real normFactor = 1.0/_spNormals[n].norm();
      _spNormals[n] *= normFactor;
    }

  } // compute Normals

  void FoundationModel::initSpringBC(const string SpNodes) {
    // Store node number on the outer surface
    ifstream inp(SpNodes.c_str());
    int nodeNum = 0;
    while (inp >> nodeNum)
    _spNodes.push_back(nodeNum);

    // Collect elements that share a node in _spNodes
    const vector<GeomElement* > elements = _myMesh->getElements();

    for (int n = 0; n < _spNodes.size(); n++) {
      vector<int > connected;
      for(int e = 0; e < elements.size(); e++) {
        const vector<int >& NodesID = elements[e]->getNodesID();
        for (int m = 0; m < NodesID.size(); m++) {
          if (NodesID[m] == _spNodes[n]) {
            connected.push_back(e);
            break;
          } //  check if node belong to element
        } // loop over nodes of the element
      } // loop over elements
      _spNodesToEle.push_back(connected);

    } // loop over _spNodes

    _spNormals.resize(_spNodes.size(), Vector3d::Zero());
    // Compute initial node normals
    this->computeNormals();

  } // InitSpringBC

  // Writing output
  void FoundationModel::writeOutputVTK(const string OutputFile, int step) {

    cout << "Step " << step << " Output:" << endl;
    cout << left << setw(8) << setfill(' ') << "Node";
    cout << left << setw(8) << setfill(' ') << "Pos X";
    cout << left << setw(8) << setfill(' ') << "Pos Y";
    cout << left << setw(8) << setfill(' ') << "Pos Z" << endl;

    for (int i = 0; i < _myMesh->getNumberOfNodes(); i++) {
      cout << left << setw(8) << setfill(' ') << i;
      cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(0);
      cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(1);
      cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(2) << endl;
    }

  } // writeOutput

} // namespace voom
<commit_msg>Changes to FoundationModel.cc Output<commit_after>#include "FoundationModel.h"
#include <iomanip>      // Included this to create tables - debugging

namespace voom {

  // Constructor
  FoundationModel::FoundationModel(Mesh* aMesh, const uint NodeDoF, const string SpNodes, Real SpringK):
  Model(aMesh, NodeDoF), _springK(SpringK)
  {
    _field.resize(  (_myMesh->getNumberOfNodes() )*_nodeDoF );
    this->initializeField();
    this->initSpringBC(SpNodes);
  }

  // Compute Function - Compute Energy, Force, Stiffness
  void FoundationModel::compute(Result * R)
  {
    const vector<GeomElement* > elements = _myMesh->getElements();
    const int AvgNodePerEl = ((elements[0])->getNodesID()).size();
    const int NumEl = elements.size();
    const int dim = _myMesh->getDimension();
    vector<Triplet<Real > > KtripletList;

    int PbDoF = R->getPbDoF();

    // Reset values in result struct
    // Todo: Once we have the wrapper, we won't want to do this
    if ( R->getRequest() & ENERGY ) {
      R->setEnergy(0.0);
    }
    if ( R->getRequest() & FORCE)  {
      R->resetResidualToZero();
    }
    if ( R->getRequest() & STIFFNESS ) {
      // R->resetStiffnessToZero();
      KtripletList.reserve(dim*dim*NumEl*AvgNodePerEl*AvgNodePerEl);
    }

    // Loop through nodes
    MechanicsMaterial::FKresults FKres;
    FKres.request = R->getRequest();

    //** Insert stuff from the spring here **//
    vector <Triplet<Real > > KtripletList_FromSpring;

    // Loop through _spNodes
    for(int n = 0; n < _spNodes.size(); n++)
    {
      int NodeID = _spNodes[n];
      Vector3d xa_prev, xa_curr;
      xa_prev << _prevField[NodeID*3], _prevField[NodeID*3+1], _prevField[NodeID*3+2];
      xa_curr << _field[NodeID*3], _field[NodeID*3+1], _field[NodeID*3+2];

      // Compute energy
      if (R->getRequest() & ENERGY) {
        R->addEnergy( 0.5* _springK*pow( (xa_curr - xa_prev).dot(_spNormals[n]), 2.0) );
      }

      // Compute Residual
      if ((R->getRequest() & FORCE)) {
        for(uint i = 0; i < 3; i++) {
          R->addResidual(NodeID*3+i,  _springK*_spNormals[n](i)*(xa_curr - xa_prev).dot(_spNormals[n]) );
        } // i loop
      } // Internal force loop

      // Compute stiffness matrix
      if ( R->getRequest() & STIFFNESS ) {
        for(uint i = 0; i < 3; i++) {
          for(uint j = 0; j < 3; j++) {
            KtripletList_FromSpring.push_back(Triplet<Real >( NodeID*3+i, NodeID*3+j, _springK*_spNormals[n](i)*_spNormals[n](j) ));
          } // j loop
        } // i loop
        KtripletList.insert( KtripletList.end(), KtripletList_FromSpring.begin(), KtripletList_FromSpring.end() );
        R->setStiffnessFromTriplets(KtripletList);
        R->FinalizeGlobalStiffnessAssembly();
      } // Stiffness loop
    } // Spring nodes loop
  } // Compute Mechanics Model

  void FoundationModel::computeNormals() {

    // First compute normal of any element in _myMesh
    const vector<GeomElement* > elements = _myMesh->getElements();

    vector<Vector3d > ElNormals(elements.size(), Vector3d::Zero());

    // Loop over elements
    for(int e = 0; e < elements.size(); e++)
    {
      GeomElement* geomEl = elements[e];
      const vector<int  >& NodesID = geomEl->getNodesID();
      const int numQP    = geomEl->getNumberOfQuadPoints();
      const int numNodes = NodesID.size();

      // Loop over quadrature points
      for(int q = 0; q < numQP; q++) {

        // Compute normal based on _prevField
        Vector3d a1 = Vector3d::Zero(), a2 = Vector3d::Zero(), a3 = Vector3d::Zero();
        for (int a = 0; a < NodesID.size(); a++) {
          int nodeID = NodesID[a];
          Vector3d xa_prev;
          xa_prev << _prevField[nodeID*3], _prevField[nodeID*3+1], _prevField[nodeID*3+2];
          a1 += xa_prev*geomEl->getDN(q, a, 0);
          a2 += xa_prev*geomEl->getDN(q, a, 1);
        }
        ElNormals[e] += a1.cross(a2); // Not normalized with respect to area (elements with larger area count more)
      } // loop over QP

    } // loop over elements

    // loop over _spNodes
    for (int n = 0; n < _spNodes.size(); n++) {
      // Reset normal to zero
      _spNormals[n] = Vector3d::Zero();
      // Loop over all elements sharing that node
      for (int m = 0; m < _spNodesToEle[n].size(); m++) {
        _spNormals[n] += ElNormals[_spNodesToEle[n][m]];
      }
      Real normFactor = 1.0/_spNormals[n].norm();
      _spNormals[n] *= normFactor;
    }

  } // compute Normals

  void FoundationModel::initSpringBC(const string SpNodes) {
    // Store node number on the outer surface
    ifstream inp(SpNodes.c_str());
    int nodeNum = 0;
    while (inp >> nodeNum)
    _spNodes.push_back(nodeNum);

    // Collect elements that share a node in _spNodes
    const vector<GeomElement* > elements = _myMesh->getElements();

    for (int n = 0; n < _spNodes.size(); n++) {
      vector<int > connected;
      for(int e = 0; e < elements.size(); e++) {
        const vector<int >& NodesID = elements[e]->getNodesID();
        for (int m = 0; m < NodesID.size(); m++) {
          if (NodesID[m] == _spNodes[n]) {
            connected.push_back(e);
            break;
          } //  check if node belong to element
        } // loop over nodes of the element
      } // loop over elements
      _spNodesToEle.push_back(connected);

    } // loop over _spNodes

    _spNormals.resize(_spNodes.size(), Vector3d::Zero());
    // Compute initial node normals
    this->computeNormals();

  } // InitSpringBC

  // Writing output
  void FoundationModel::writeOutputVTK(const string OutputFile, int step) {

    cout << "Step " << step << " Output:" << endl;
    cout << left << setw(8) << setfill(' ') << "Node";
    cout << left << setw(8) << setfill(' ') << "Pos X";
    cout << left << setw(8) << setfill(' ') << "Pos Y";
    if (_nodeDoF > 2)
      cout << left << setw(8) << setfill(' ') << "Pos Z" << endl;
    else
      cout << endl;

    for (int i = 0; i < _myMesh->getNumberOfNodes(); i++) {
      cout << left << setw(8) << setfill(' ') << i;
      cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(0);
      cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(1);
      if (_nodeDoF > 2)
        cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(2) << endl;
      else
        cout << endl;
    }

  } // writeOutput

} // namespace voom
<|endoftext|>


<commit_before>//functor_overload header
//Copyright (c) 2014 mmYYmmdd

#include "functor_overload.hpp"

template <typename T>
    struct is_Numeric   {
        static const bool value = std::is_integral<typename std::remove_reference<T>::type>::value ||
                                std::is_floating_point<typename std::remove_reference<T>::type>::value;
};

template <typename T>
    struct is_Pointer   {
        static const bool value = std::is_pointer<typename std::remove_reference<T>::type>::value;
};

struct Plus {
    template <typename T>
        auto operator()(T a, T b) const
        { return a + b; }
    template <typename T>
        auto operator()(T* a, T* b) const
        { return *a + *b; }
};

struct Minus {
    template <typename T>
        auto operator()(T a, T b) const
        { return a - b; }
    template <typename T>
        auto operator()(T* a, T* b) const
        { return *a - *b; }
};

#include <iostream>

int main()
{
    using namespace mymd;
    std::cout << "//数値／ポインタに対する計算をオーバーロードする人工的な例" << std::endl;
    std::cout << "//ふたつのファンクタのシグネチャは同一。それを意識的に選択する。" << std::endl;
    auto mm = gen<cond<is_Numeric>, cond<is_Numeric>>(Plus{} ) +
              gen<cond<is_Pointer>, cond<is_Pointer>>(Minus{}) ;
    int i = 4, j = 5;
    double a = 3.676, b = 8.3212;
    std::cout << mm(i, j) << std::endl;
    std::cout << mm(a, b+0.0) << std::endl;
    std::cout << mm(&i, &j) << std::endl;
    std::cout << mm(&a, &b) << std::endl;
}
<commit_msg>sample for functor overload(gen) のサンプル<commit_after>//functor_overload header
//Copyright (c) 2014 mmYYmmdd

#include "functor_overload.hpp"

template <typename T>
    struct is_Numeric   {
        static const bool value = std::is_integral<typename std::remove_reference<T>::type>::value ||
                                std::is_floating_point<typename std::remove_reference<T>::type>::value;
};

template <typename T>
    struct is_Pointer   {
        static const bool value = std::is_pointer<typename std::remove_reference<T>::type>::value;
};

struct Plus {
    template <typename T>
        auto operator()(T a, T b) const
        { return a + b; }
    template <typename T>
        auto operator()(T* a, T* b) const
        { return *a + *b; }
};

struct Minus {
    template <typename T>
        auto operator()(T a, T b) const
        { return a - b; }
    template <typename T>
        auto operator()(T* a, T* b) const
        { return *a - *b; }
};

#include <iostream>

int main()
{
    using namespace mymd;
    std::cout << "// sample for overload the calculation of numerics and of pointers" << std::endl;
    std::cout << "// sets of signatures of two functors are same,  " << std::endl;
    std::cout << "// and choice the members to use from them " << std::endl;
    std::cout << "//数値／ポインタに対する計算をオーバーロードする人工的な例" << std::endl;
    std::cout << "//ふたつのファンクタのシグネチャは同一。それを意識的に選択する。" << std::endl;
    auto mm = gen<cond<is_Numeric>, cond<is_Numeric>>(Plus{} ) +
              gen<cond<is_Pointer>, cond<is_Pointer>>(Minus{}) ;
    int i = 4, j = 5;
    double a = 3.676, b = 8.3212;
    std::cout << mm(i, j) << std::endl;
    std::cout << mm(a, b+0.0) << std::endl;
    std::cout << mm(&i, &j) << std::endl;
    std::cout << mm(&a, &b) << std::endl;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <rtl/ref.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/supportsservice.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/accessibility/XMSAAService.hpp>
#include <com/sun/star/accessibility/AccessibleRole.hpp>

#include <com/sun/star/awt/XExtendedToolkit.hpp>
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>

#include <prewin.h>
#include <postwin.h>

using namespace ::com::sun::star; // for odk interfaces
using namespace ::com::sun::star::uno; // for basic types
using namespace ::com::sun::star::accessibility;

using namespace ::com::sun::star::awt;

#include "AccTopWindowListener.hxx"

namespace my_sc_impl
{

static Sequence< OUString > getSupportedServiceNames_MSAAServiceImpl()
{
    Sequence< OUString > seqNames(1);
    seqNames.getArray()[0] = "com.sun.star.accessibility.MSAAService";
    return seqNames;
}

static OUString getImplementationName_MSAAServiceImpl()
{
    return OUString( "com.sun.star.accessibility.my_sc_implementation.MSAAService" );
}

class MSAAServiceImpl : public ::cppu::WeakImplHelper2<
            XMSAAService, lang::XServiceInfo >
{
private:
    rtl::Reference<AccTopWindowListener> m_pTopWindowListener;

public:
    MSAAServiceImpl ();
    virtual ~MSAAServiceImpl();

    // XComponent - as used by VCL to lifecycle manage this bridge.
    virtual void SAL_CALL dispose();
    virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& )    { /* dummy */ }
    virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { /* dummy */ }

    // XMSAAService
    virtual sal_Int64 SAL_CALL getAccObjectPtr(
            sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam);
    virtual void SAL_CALL handleWindowOpened(sal_Int64);

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName();
    virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName );
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames();
};

/**
   * Implemention of getAccObjectPtr.
   * @param
   * @return Com interface.
   */
sal_Int64 MSAAServiceImpl::getAccObjectPtr(
        sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam)
throw (RuntimeException)
{
    SolarMutexGuard g;

    if (!m_pTopWindowListener.is())
    {
        return 0;
    }
    return m_pTopWindowListener->GetMSComPtr(hWnd, lParam, wParam);
}

/**
   * Implemention of handleWindowOpened, the method will be invoked when a
   * top window is opened and AT starts up.
   * @param
   * @return
   */
void MSAAServiceImpl::handleWindowOpened(sal_Int64 nAcc)
{
    SolarMutexGuard g;

    SAL_INFO( "iacc2", "Window opened " << nAcc );

    if (m_pTopWindowListener.is() && nAcc)
    {
        m_pTopWindowListener->HandleWindowOpened(
            static_cast<com::sun::star::accessibility::XAccessible*>(
                reinterpret_cast<void*>(nAcc)));
    }
}

OUString MSAAServiceImpl::getImplementationName() throw (RuntimeException)
{
    return OUString( "com.sun.star.accessibility.my_sc_impl.MSAAService" );
}

/**
   * Implemention of XServiceInfo,return support service name.
   * @param Service name.
   * @return If the service name is supported.
   */
sal_Bool MSAAServiceImpl::supportsService( OUString const & serviceName ) throw (RuntimeException)
{
    return cppu::supportsService(this, serviceName);
}

/**
   * Implemention of XServiceInfo,return all service names.
   * @param.
   * @return service name sequence.
   */
Sequence< OUString > MSAAServiceImpl::getSupportedServiceNames() throw (RuntimeException)
{
    return getSupportedServiceNames_MSAAServiceImpl();
}

static void AccessBridgeHandleExistingWindow(const Reference< XMSAAService > &xAccMgr,
                                             vcl::Window *pWindow, bool bShow)
{
    if ( pWindow )
    {
        css::uno::Reference< css::accessibility::XAccessible > xAccessible;

        SAL_INFO( "iacc2", "Decide whether to register existing window with IAccessible2" );

        // Test for combo box - drop down floating windows first
        vcl::Window * pParentWindow = pWindow->GetParent();

        if ( pParentWindow )
        {
            try
            {
                // The parent window of a combo box floating window should have the role COMBO_BOX
                css::uno::Reference< css::accessibility::XAccessible > xParentAccessible(pParentWindow->GetAccessible());
                if ( xParentAccessible.is() )
                {
                    css::uno::Reference< css::accessibility::XAccessibleContext > xParentAC( xParentAccessible->getAccessibleContext() );
                    if ( xParentAC.is() && (css::accessibility::AccessibleRole::COMBO_BOX == xParentAC->getAccessibleRole()) )
                    {
                        // O.k. - this is a combo box floating window corresponding to the child of role LIST of the parent.
                        // Let's not rely on a specific child order, just search for the child with the role LIST
                        sal_Int32 nCount = xParentAC->getAccessibleChildCount();
                        for ( sal_Int32 n = 0; (n < nCount) && !xAccessible.is(); n++)
                        {
                            css::uno::Reference< css::accessibility::XAccessible > xChild = xParentAC->getAccessibleChild(n);
                            if ( xChild.is() )
                            {
                                css::uno::Reference< css::accessibility::XAccessibleContext > xChildAC = xChild->getAccessibleContext();
                                if ( xChildAC.is() && (css::accessibility::AccessibleRole::LIST == xChildAC->getAccessibleRole()) )
                                {
                                    xAccessible = xChild;
                                }
                            }
                        }
                    }
                }
            }
            catch (::com::sun::star::uno::RuntimeException const&)
            {
                // Ignore show events that throw DisposedExceptions in getAccessibleContext(),
                // but keep revoking these windows in hide(s).
                if (bShow)
                    return;
            }
        }

        // We have to rely on the fact that Window::GetAccessible()->getAccessibleContext() returns a valid XAccessibleContext
        // also for other menus than menubar or toplevel popup window. Otherwise we had to traverse the hierarchy to find the
        // context object to this menu floater. This makes the call to Window->IsMenuFloatingWindow() obsolete.
        if ( ! xAccessible.is() )
            xAccessible = pWindow->GetAccessible();

        assert( xAccMgr.is() );
        if ( xAccessible.is() )
        {
            xAccMgr->handleWindowOpened(
                    reinterpret_cast<sal_Int64>(xAccessible.get()));
            SAL_INFO( "iacc2", "Decide whether to register existing window with IAccessible2" );
        }
    }
}

/*
 * Setup and notify the OS of Accessible peers for all existing windows.
 */
static void AccessBridgeUpdateOldTopWindows( const Reference< XMSAAService > &xAccMgr )
{
    sal_uInt16 nTopWindowCount = (sal_uInt16)Application::GetTopWindowCount();

    for ( sal_uInt16 i = 0; i < nTopWindowCount; i++ )
    {
        vcl::Window* pTopWindow = Application::GetTopWindow( i );
        css::uno::Reference< css::accessibility::XAccessible > xAccessible = pTopWindow->GetAccessible();
        if ( xAccessible.is() )
        {
            css::uno::Reference< css::accessibility::XAccessibleContext > xAC( xAccessible->getAccessibleContext() );
            if ( xAC.is())
            {
                if ( !xAC->getAccessibleName().isEmpty() )
                    AccessBridgeHandleExistingWindow( xAccMgr, pTopWindow, true );
            }
        }
    }
}

/**
 * Static method that can create an entity of our MSAA Service
 * @param xContext No use here.
 * @return The object interface.
 */
Reference< XInterface > SAL_CALL create_MSAAServiceImpl( Reference< XComponentContext > const & /*xContext*/ )
{
    Reference< XMSAAService > xAccMgr( new MSAAServiceImpl() );

    AccessBridgeUpdateOldTopWindows( xAccMgr );

    SAL_INFO("iacc2", "Created new IAccessible2 service impl.");

    return xAccMgr;
}

MSAAServiceImpl::MSAAServiceImpl()
{
    Reference< XExtendedToolkit > xToolkit =
        Reference< XExtendedToolkit >(Application::GetVCLToolkit(), UNO_QUERY);

    if( xToolkit.is() )
    {
        m_pTopWindowListener.set(new AccTopWindowListener());
        Reference<XTopWindowListener> const xRef(m_pTopWindowListener.get());
        xToolkit->addTopWindowListener( xRef );
        SAL_INFO( "iacc2", "successfully connected to the toolkit event hose" );
    }
    else
        SAL_WARN( "iacc2", "No VCL toolkit interface to listen to for events");
}

MSAAServiceImpl::~MSAAServiceImpl()
{
}

void MSAAServiceImpl::dispose()
{
    SolarMutexGuard g;

    // As all folders and streams contain references to their parents,
    // we must remove these references so that they will be deleted when
    // the hash_map of the root folder is cleared, releasing all subfolders
    // and substreams which in turn release theirs, etc. When xRootFolder is
    // released when this destructor completes, the folder tree should be
    // deleted fully (and automagically).
    m_pTopWindowListener.clear();
}

}

/* shared lib exports implemented without helpers in service_impl1.cxx */
namespace my_sc_impl
{
static struct ::cppu::ImplementationEntry s_component_entries [] =
    {
        {
            create_MSAAServiceImpl, getImplementationName_MSAAServiceImpl,
            getSupportedServiceNames_MSAAServiceImpl,
            ::cppu::createSingleComponentFactory,
            0, 0
        },
        { 0, 0, 0, 0, 0, 0 }
    };
}

extern "C"
{
    SAL_DLLPUBLIC_EXPORT void * SAL_CALL iacc2_component_getFactory(
        sal_Char const * implName, lang::XMultiServiceFactory * xMgr,
        registry::XRegistryKey * xRegistry )
    {
        return ::cppu::component_getFactoryHelper(
                   implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>presumably this will fix the mismatch of the service names<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include <rtl/ref.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/supportsservice.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/accessibility/XMSAAService.hpp>
#include <com/sun/star/accessibility/AccessibleRole.hpp>

#include <com/sun/star/awt/XExtendedToolkit.hpp>
#include <vcl/svapp.hxx>
#include <vcl/window.hxx>

#include <prewin.h>
#include <postwin.h>

using namespace ::com::sun::star; // for odk interfaces
using namespace ::com::sun::star::uno; // for basic types
using namespace ::com::sun::star::accessibility;

using namespace ::com::sun::star::awt;

#include "AccTopWindowListener.hxx"

namespace my_sc_impl
{

static Sequence< OUString > getSupportedServiceNames_MSAAServiceImpl()
{
    Sequence< OUString > seqNames(1);
    seqNames.getArray()[0] = "com.sun.star.accessibility.MSAAService";
    return seqNames;
}

static OUString getImplementationName_MSAAServiceImpl()
{
    return OUString( "com.sun.star.accessibility.my_sc_implementation.MSAAService" );
}

class MSAAServiceImpl : public ::cppu::WeakImplHelper2<
            XMSAAService, lang::XServiceInfo >
{
private:
    rtl::Reference<AccTopWindowListener> m_pTopWindowListener;

public:
    MSAAServiceImpl ();
    virtual ~MSAAServiceImpl();

    // XComponent - as used by VCL to lifecycle manage this bridge.
    virtual void SAL_CALL dispose();
    virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& )    { /* dummy */ }
    virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { /* dummy */ }

    // XMSAAService
    virtual sal_Int64 SAL_CALL getAccObjectPtr(
            sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam);
    virtual void SAL_CALL handleWindowOpened(sal_Int64);

    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName();
    virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName );
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames();
};

/**
   * Implemention of getAccObjectPtr.
   * @param
   * @return Com interface.
   */
sal_Int64 MSAAServiceImpl::getAccObjectPtr(
        sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam)
throw (RuntimeException)
{
    SolarMutexGuard g;

    if (!m_pTopWindowListener.is())
    {
        return 0;
    }
    return m_pTopWindowListener->GetMSComPtr(hWnd, lParam, wParam);
}

/**
   * Implemention of handleWindowOpened, the method will be invoked when a
   * top window is opened and AT starts up.
   * @param
   * @return
   */
void MSAAServiceImpl::handleWindowOpened(sal_Int64 nAcc)
{
    SolarMutexGuard g;

    SAL_INFO( "iacc2", "Window opened " << nAcc );

    if (m_pTopWindowListener.is() && nAcc)
    {
        m_pTopWindowListener->HandleWindowOpened(
            static_cast<com::sun::star::accessibility::XAccessible*>(
                reinterpret_cast<void*>(nAcc)));
    }
}

OUString MSAAServiceImpl::getImplementationName() throw (RuntimeException)
{
    return getImplementationName_MSAAServiceImpl();
}

/**
   * Implemention of XServiceInfo,return support service name.
   * @param Service name.
   * @return If the service name is supported.
   */
sal_Bool MSAAServiceImpl::supportsService( OUString const & serviceName ) throw (RuntimeException)
{
    return cppu::supportsService(this, serviceName);
}

/**
   * Implemention of XServiceInfo,return all service names.
   * @param.
   * @return service name sequence.
   */
Sequence< OUString > MSAAServiceImpl::getSupportedServiceNames() throw (RuntimeException)
{
    return getSupportedServiceNames_MSAAServiceImpl();
}

static void AccessBridgeHandleExistingWindow(const Reference< XMSAAService > &xAccMgr,
                                             vcl::Window *pWindow, bool bShow)
{
    if ( pWindow )
    {
        css::uno::Reference< css::accessibility::XAccessible > xAccessible;

        SAL_INFO( "iacc2", "Decide whether to register existing window with IAccessible2" );

        // Test for combo box - drop down floating windows first
        vcl::Window * pParentWindow = pWindow->GetParent();

        if ( pParentWindow )
        {
            try
            {
                // The parent window of a combo box floating window should have the role COMBO_BOX
                css::uno::Reference< css::accessibility::XAccessible > xParentAccessible(pParentWindow->GetAccessible());
                if ( xParentAccessible.is() )
                {
                    css::uno::Reference< css::accessibility::XAccessibleContext > xParentAC( xParentAccessible->getAccessibleContext() );
                    if ( xParentAC.is() && (css::accessibility::AccessibleRole::COMBO_BOX == xParentAC->getAccessibleRole()) )
                    {
                        // O.k. - this is a combo box floating window corresponding to the child of role LIST of the parent.
                        // Let's not rely on a specific child order, just search for the child with the role LIST
                        sal_Int32 nCount = xParentAC->getAccessibleChildCount();
                        for ( sal_Int32 n = 0; (n < nCount) && !xAccessible.is(); n++)
                        {
                            css::uno::Reference< css::accessibility::XAccessible > xChild = xParentAC->getAccessibleChild(n);
                            if ( xChild.is() )
                            {
                                css::uno::Reference< css::accessibility::XAccessibleContext > xChildAC = xChild->getAccessibleContext();
                                if ( xChildAC.is() && (css::accessibility::AccessibleRole::LIST == xChildAC->getAccessibleRole()) )
                                {
                                    xAccessible = xChild;
                                }
                            }
                        }
                    }
                }
            }
            catch (::com::sun::star::uno::RuntimeException const&)
            {
                // Ignore show events that throw DisposedExceptions in getAccessibleContext(),
                // but keep revoking these windows in hide(s).
                if (bShow)
                    return;
            }
        }

        // We have to rely on the fact that Window::GetAccessible()->getAccessibleContext() returns a valid XAccessibleContext
        // also for other menus than menubar or toplevel popup window. Otherwise we had to traverse the hierarchy to find the
        // context object to this menu floater. This makes the call to Window->IsMenuFloatingWindow() obsolete.
        if ( ! xAccessible.is() )
            xAccessible = pWindow->GetAccessible();

        assert( xAccMgr.is() );
        if ( xAccessible.is() )
        {
            xAccMgr->handleWindowOpened(
                    reinterpret_cast<sal_Int64>(xAccessible.get()));
            SAL_INFO( "iacc2", "Decide whether to register existing window with IAccessible2" );
        }
    }
}

/*
 * Setup and notify the OS of Accessible peers for all existing windows.
 */
static void AccessBridgeUpdateOldTopWindows( const Reference< XMSAAService > &xAccMgr )
{
    sal_uInt16 nTopWindowCount = (sal_uInt16)Application::GetTopWindowCount();

    for ( sal_uInt16 i = 0; i < nTopWindowCount; i++ )
    {
        vcl::Window* pTopWindow = Application::GetTopWindow( i );
        css::uno::Reference< css::accessibility::XAccessible > xAccessible = pTopWindow->GetAccessible();
        if ( xAccessible.is() )
        {
            css::uno::Reference< css::accessibility::XAccessibleContext > xAC( xAccessible->getAccessibleContext() );
            if ( xAC.is())
            {
                if ( !xAC->getAccessibleName().isEmpty() )
                    AccessBridgeHandleExistingWindow( xAccMgr, pTopWindow, true );
            }
        }
    }
}

/**
 * Static method that can create an entity of our MSAA Service
 * @param xContext No use here.
 * @return The object interface.
 */
Reference< XInterface > SAL_CALL create_MSAAServiceImpl( Reference< XComponentContext > const & /*xContext*/ )
{
    Reference< XMSAAService > xAccMgr( new MSAAServiceImpl() );

    AccessBridgeUpdateOldTopWindows( xAccMgr );

    SAL_INFO("iacc2", "Created new IAccessible2 service impl.");

    return xAccMgr;
}

MSAAServiceImpl::MSAAServiceImpl()
{
    Reference< XExtendedToolkit > xToolkit =
        Reference< XExtendedToolkit >(Application::GetVCLToolkit(), UNO_QUERY);

    if( xToolkit.is() )
    {
        m_pTopWindowListener.set(new AccTopWindowListener());
        Reference<XTopWindowListener> const xRef(m_pTopWindowListener.get());
        xToolkit->addTopWindowListener( xRef );
        SAL_INFO( "iacc2", "successfully connected to the toolkit event hose" );
    }
    else
        SAL_WARN( "iacc2", "No VCL toolkit interface to listen to for events");
}

MSAAServiceImpl::~MSAAServiceImpl()
{
}

void MSAAServiceImpl::dispose()
{
    SolarMutexGuard g;

    // As all folders and streams contain references to their parents,
    // we must remove these references so that they will be deleted when
    // the hash_map of the root folder is cleared, releasing all subfolders
    // and substreams which in turn release theirs, etc. When xRootFolder is
    // released when this destructor completes, the folder tree should be
    // deleted fully (and automagically).
    m_pTopWindowListener.clear();
}

}

/* shared lib exports implemented without helpers in service_impl1.cxx */
namespace my_sc_impl
{
static struct ::cppu::ImplementationEntry s_component_entries [] =
    {
        {
            create_MSAAServiceImpl, getImplementationName_MSAAServiceImpl,
            getSupportedServiceNames_MSAAServiceImpl,
            ::cppu::createSingleComponentFactory,
            0, 0
        },
        { 0, 0, 0, 0, 0, 0 }
    };
}

extern "C"
{
    SAL_DLLPUBLIC_EXPORT void * SAL_CALL iacc2_component_getFactory(
        sal_Char const * implName, lang::XMultiServiceFactory * xMgr,
        registry::XRegistryKey * xRegistry )
    {
        return ::cppu::component_getFactoryHelper(
                   implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*! \file unitTestRandomNumberGenerator.cpp
 *    Source file that defines a unit test that tests the random number
 *    generator included in Tudat.
 *
 *    Path              : /Mathematics/
 *    Version           : 3
 *    Check status      : Checked
 *
 *    Author            : K. Kumar
 *    Affiliation       : Delft University of Technology
 *    E-mail address    : K.Kumar@tudelft.nl
 *
 *    Checker           : D. Dirkx
 *    Affiliation       : Delft University of Technology
 *    E-mail address    : D.Dirkx@student.tudelft.nl
 *
 *    Date created      : 7 January, 2011
 *    Last modified     : 7 July, 2011
 *
 *    References
 *      Walpole, R.E., et al. Probabilty and Statistics for Engineers &
 *          Scientists, Seventh Edition, Prentice Hall, NJ, 2002.
 *      Texas A&M University. Chi Square Calculator,
 *          http://www.stat.tamu.edu/~west/applets/chisqdemo.html, last
 *          accessed: 7 July, 2011.
 *      Faculty of Mathematics and Informatics, University of Sofia.
 *          http://www.fmi.uni-sofia.bg/vesta/virtual_labs/interval/interval6.html,
 *          last accessed: 7 July, 2011.
 *
 *    Notes
 *      Test runs code and verifies result against expected value.
 *      If the tested code is erroneous, the test function returns a boolean
 *      true; if the code is correct, the function returns a boolean false.
 *
 *      The code tests for the quality of the uniform distribution by testing
 *      the sample mean and variance against the true mean and variance using
 *      standard error estimates. These estimates are stated with a
 *      confidence of 99.96%. If the unit test fails due to Test 5, it is
 *      recommended that the unit test is run again to rule out statistical
 *      anomalies.
 *
 *    Copyright (c) 2010 Delft University of Technology.
 *
 *    This software is protected by national and international copyright.
 *    Any unauthorized use, reproduction or modification is unlawful and
 *    will be prosecuted. Commercial and non-private application of the
 *    software in any form is strictly prohibited unless otherwise granted
 *    by the authors.
 *
 *    The code is provided without any warranty; without even the implied
 *    warranty of merchantibility or fitness for a particular purpose.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      110107    K. Kumar          First creation of code.
 *      110207    K. Kumar          Updated code to conform to protocol; added
 *                                  cerr statements.
 *      110209    K. Kumar          Updated tests and added test for mean and
 *                                  variance of uniform distribution; added
 *                                  note and reference.
 *      110707    K. Kumar          Corrected variance calculation errors;
 *                                  updated references.
 */

// Include statements.
#include "randomNumberGenerator.h"

// Using declarations.
using mathematics::computeAbsoluteValue;
using mathematics::raiseToIntegerPower;
using mathematics::MACHINE_PRECISION_DOUBLES;
using std::cerr;
using std::endl;

//! Namespace for all unit tests.
namespace unit_tests
{

//! Test of implementation of random number generator class.
bool testRandomNumberGenerator( )
{
    // Four tests.
    // Test 1: Get a random integer ( 64-bit ).
    // Test 2: Get a random integer ( 32-bit ).
    // Test 3: Get a normalized random double in the interval [ 0, 1 ].
    // Test 4: Get a random plus/minus sign.
    // Test 5: Compute sample mean and standard distrubution of distribution
    //         and compare to analytical results.

    // Test result initialised to false.
    bool isRandomNumberGeneratorErroneous = false;

    // Create random number generator object.
    RandomNumberGenerator randomNumbers( time( NULL ) );

    // Results computed using implementation of random number generator class.
    // Test 1: Get a random integer ( 64-bit ).
    int computedResultForTest1 = randomNumbers
                                 .getUniformlyDistributedRandom64BitInteger( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( fmod( computedResultForTest1, floor( computedResultForTest1 ) )
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest1
                << " ) using the 64-bit random integer generator "
                << "is not an integer" << endl;
    }

    // Test 2: Get a random integer ( 32-bit ).
    int computedResultForTest2 = randomNumbers
                                 .getUniformlyDistributedRandom32BitInteger( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( fmod( computedResultForTest2, floor( computedResultForTest2 ) )
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest2
                << " ) using the 32-bit random integer generator "
                << "is not an integer" << endl;
    }

    // Test 3: Get a normalized random double in the interval [ 0, 1 ].
    double computedResultForTest3
            = randomNumbers.getUniformlyDistributedNormalizedRandomDouble( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( computedResultForTest3 < 0.0 && computedResultForTest3 > 1.0 )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest3
                << " ) using the normalized random number generator "
                << "is not within the prescribed bounds [ 0, 1 ]" << endl;
    }

    // Test 4: Get a random plus/minus sign.
    double computedResultForTest4 = randomNumbers.getRandomPlusMinusSign( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( computeAbsoluteValue( computedResultForTest4 ) - 1.0
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest4
                << " ) using the plus/minus sign random generator "
                << "is not equal to either +1 or -1" << endl;
    }

    // Test 5: Compute sample mean and variance of distribution and compare to
    //         analytical results.
    // Declare and initialize number of samples.
    unsigned int numberOfSamples = 100000;

    // Declare and set size of vector of sample random values.
    VectorXd sampleOfRandomValues = VectorXd( numberOfSamples );

    // Fill vector of sample random values.
    for ( unsigned int i = 0; i < numberOfSamples; i++ )
    {
        sampleOfRandomValues( i )
                = randomNumbers
                  .getUniformlyDistributedNormalizedRandomDouble( );
    }

    // Estimate sample mean of the distribution.
    double sampleMean = sampleOfRandomValues.sum( )
                        / numberOfSamples;

    // Estimate sample variance.
    double sumOfResidualsSquared = 0.0;
    for ( unsigned int i = 0; i < numberOfSamples; i++ )
    {
        sumOfResidualsSquared +=
                raiseToIntegerPower( sampleOfRandomValues( i )
                                     - sampleMean, 2 );
    }
    double sampleVariance
            = 1.0 / ( numberOfSamples - 1.0 ) * sumOfResidualsSquared;

    // Compute differences between computed and expected results.
    // Test sample mean versus true mean with a confidence of 99.96%.
    // This means that the test below guarentees that this unit test will
    // fail on average every 2500 times it is run.
    // Also test sample variance versus true variance with a confidence of
    // 99.96%. The true mean and true variance of a uniform distribution
    // from 0 to 1 are 1/2 and 1/12 respectively.
    // The tolerances were computed using confidence intervals for the sample
    // mean and variance and table lookup.
    if ( computeAbsoluteValue( sampleMean - 0.5 )
         > 3.49 * 1.0 / sqrt( 12.0 )
           * 1.0 / static_cast< double >( sqrt( numberOfSamples ) )
        )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed sample mean ( " << sampleMean
             << " ) using a sample size of " << numberOfSamples
             << " is not within the standard error of the true sample mean"
             << " ( 1/2 ) " << endl;
        cerr << "The distribution is not uniform to a confidence of 99.96%. "
             << "Run the unit test again to ensure error is not due to "
             << "statistical anomaly. " << endl;
    }

    if ( ( 1.0 / 12.0 ) / sampleVariance
         < static_cast< double >( numberOfSamples - 1 ) / 101291
         || ( 1.0 / 12.0 ) / sampleVariance
         > static_cast< double>( numberOfSamples - 1 ) / 98717 )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed sample variance ( " << sampleVariance
             << " ) using a sample size of " << numberOfSamples
             << " is not within the standard error of the true sample variance"
             << "( 1/12 ) " << endl;
        cerr << "The distribution is not uniform to a confidence of 99.96%. "
             << "Run the unit test again to ensure error is not due to "
             << "statistical anomaly." << endl;
    }

    // Return test result.
    // If test is successful return false; if test fails, return true.
    return isRandomNumberGeneratorErroneous;
}

}

// End of file.
<commit_msg>Commit of correction to random number generator unit test.<commit_after>/*! \file unitTestRandomNumberGenerator.cpp
 *    Source file that defines a unit test that tests the random number
 *    generator included in Tudat.
 *
 *    Path              : /Mathematics/
 *    Version           : 3
 *    Check status      : Checked
 *
 *    Author            : K. Kumar
 *    Affiliation       : Delft University of Technology
 *    E-mail address    : K.Kumar@tudelft.nl
 *
 *    Checker           : D. Dirkx
 *    Affiliation       : Delft University of Technology
 *    E-mail address    : D.Dirkx@student.tudelft.nl
 *
 *    Date created      : 7 January, 2011
 *    Last modified     : 7 July, 2011
 *
 *    References
 *      Walpole, R.E., et al. Probabilty and Statistics for Engineers &
 *          Scientists, Seventh Edition, Prentice Hall, NJ, 2002.
 *      Texas A&M University. Chi Square Calculator,
 *          http://www.stat.tamu.edu/~west/applets/chisqdemo.html, last
 *          accessed: 7 July, 2011.
 *      Faculty of Mathematics and Informatics, University of Sofia.
 *          http://www.fmi.uni-sofia.bg/vesta/virtual_labs/interval/interval6.html,
 *          last accessed: 7 July, 2011.
 *
 *    Notes
 *      Test runs code and verifies result against expected value.
 *      If the tested code is erroneous, the test function returns a boolean
 *      true; if the code is correct, the function returns a boolean false.
 *
 *      The code tests for the quality of the uniform distribution by testing
 *      the sample mean and variance against the true mean and variance using
 *      standard error estimates. These estimates are stated with a
 *      confidence of 99.96%. If the unit test fails due to Test 5, it is
 *      recommended that the unit test is run again to rule out statistical
 *      anomalies.
 *
 *    Copyright (c) 2010 Delft University of Technology.
 *
 *    This software is protected by national and international copyright.
 *    Any unauthorized use, reproduction or modification is unlawful and
 *    will be prosecuted. Commercial and non-private application of the
 *    software in any form is strictly prohibited unless otherwise granted
 *    by the authors.
 *
 *    The code is provided without any warranty; without even the implied
 *    warranty of merchantibility or fitness for a particular purpose.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      110107    K. Kumar          First creation of code.
 *      110207    K. Kumar          Updated code to conform to protocol; added
 *                                  cerr statements.
 *      110209    K. Kumar          Updated tests and added test for mean and
 *                                  variance of uniform distribution; added
 *                                  note and reference.
 *      110707    K. Kumar          Corrected variance calculation errors;
 *                                  updated references.
 */

// Include statements.
#include "randomNumberGenerator.h"

// Using declarations.
using mathematics::computeAbsoluteValue;
using mathematics::raiseToIntegerPower;
using mathematics::MACHINE_PRECISION_DOUBLES;
using std::cerr;
using std::endl;

//! Namespace for all unit tests.
namespace unit_tests
{

//! Test of implementation of random number generator class.
bool testRandomNumberGenerator( )
{
    // Four tests.
    // Test 1: Get a random integer ( 64-bit ).
    // Test 2: Get a random integer ( 32-bit ).
    // Test 3: Get a normalized random double in the interval [ 0, 1 ].
    // Test 4: Get a random plus/minus sign.
    // Test 5: Compute sample mean and standard distrubution of distribution
    //         and compare to analytical results.

    // Test result initialised to false.
    bool isRandomNumberGeneratorErroneous = false;

    // Create random number generator object.
    RandomNumberGenerator randomNumbers( time( NULL ) );

    // Results computed using implementation of random number generator class.
    // Test 1: Get a random integer ( 64-bit ).
    int computedResultForTest1 = randomNumbers
                                 .getUniformlyDistributedRandom64BitInteger( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( fmod( computedResultForTest1, floor( computedResultForTest1 ) )
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest1
                << " ) using the 64-bit random integer generator "
                << "is not an integer" << endl;
    }

    // Test 2: Get a random integer ( 32-bit ).
    int computedResultForTest2 = randomNumbers
                                 .getUniformlyDistributedRandom32BitInteger( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( fmod( computedResultForTest2, floor( computedResultForTest2 ) )
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest2
                << " ) using the 32-bit random integer generator "
                << "is not an integer" << endl;
    }

    // Test 3: Get a normalized random double in the interval [ 0, 1 ].
    double computedResultForTest3
            = randomNumbers.getUniformlyDistributedNormalizedRandomDouble( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( computedResultForTest3 < 0.0 && computedResultForTest3 > 1.0 )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest3
                << " ) using the normalized random number generator "
                << "is not within the prescribed bounds [ 0, 1 ]" << endl;
    }

    // Test 4: Get a random plus/minus sign.
    double computedResultForTest4 = randomNumbers.getRandomPlusMinusSign( );

    // Compute differences between computed and expected results and generate
    // cerr statement if test fails.
    if ( computeAbsoluteValue( computedResultForTest4 ) - 1.0
         > MACHINE_PRECISION_DOUBLES )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed value ( " << computedResultForTest4
                << " ) using the plus/minus sign random generator "
                << "is not equal to either +1 or -1" << endl;
    }

    // Test 5: Compute sample mean and variance of distribution and compare to
    //         analytical results.
    // Declare and initialize number of samples.
    unsigned int numberOfSamples = 100000;

    // Declare and set size of vector of sample random values.
    VectorXd sampleOfRandomValues = VectorXd( numberOfSamples );

    // Fill vector of sample random values.
    for ( unsigned int i = 0; i < numberOfSamples; i++ )
    {
        sampleOfRandomValues( i )
                = randomNumbers
                  .getUniformlyDistributedNormalizedRandomDouble( );
    }

    // Estimate sample mean of the distribution.
    double sampleMean = sampleOfRandomValues.sum( )
                        / numberOfSamples;

    // Estimate sample variance.
    double sumOfResidualsSquared = 0.0;
    for ( unsigned int i = 0; i < numberOfSamples; i++ )
    {
        sumOfResidualsSquared +=
                raiseToIntegerPower( sampleOfRandomValues( i )
                                     - sampleMean, 2 );
    }
    double sampleVariance
            = 1.0 / ( numberOfSamples - 1.0 ) * sumOfResidualsSquared;

    // Compute differences between computed and expected results.
    // Test sample mean versus true mean with a confidence of 99.96%.
    // This means that the test below guarentees that this unit test will
    // fail on average every 2500 times it is run.
    // Also test sample variance versus true variance with a confidence of
    // 99.96%. The true mean and true variance of a uniform distribution
    // from 0 to 1 are 1/2 and 1/12 respectively.
    // The tolerances were computed using confidence intervals for the sample
    // mean and variance and table lookup.
    if ( computeAbsoluteValue( sampleMean - 0.5 )
         > 3.49 * 1.0 / sqrt( 12.0 )
           * 1.0 / static_cast< double >( sqrt( numberOfSamples ) )
        )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed sample mean ( " << sampleMean
             << " ) using a sample size of " << numberOfSamples
             << " is not within the standard error of the true sample mean"
             << " ( 1/2 ) " << endl;
        cerr << "The distribution is not uniform to a confidence of 99.96%. "
             << "Run the unit test again to ensure error is not due to "
             << "statistical anomaly. " << endl;
    }

    if ( ( 1.0 / 12.0 ) / sampleVariance
         < static_cast< double >( numberOfSamples - 1 ) / 101590
         || ( 1.0 / 12.0 ) / sampleVariance
         > static_cast< double>( numberOfSamples - 1 ) / 98424 )
    {
        isRandomNumberGeneratorErroneous = true;

        cerr << "The computed sample variance ( " << sampleVariance
             << " ) using a sample size of " << numberOfSamples
             << " is not within the standard error of the true sample variance"
             << "( 1/12 ) " << endl;
        cerr << "The distribution is not uniform to a confidence of 99.96%. "
             << "Run the unit test again to ensure error is not due to "
             << "statistical anomaly." << endl;
    }

    // Return test result.
    // If test is successful return false; if test fails, return true.
    return isRandomNumberGeneratorErroneous;
}

}

// End of file.
<|endoftext|>