<commit_before>/*
 * Copyright (c) 2009-2010 jMonkeyEngine
 * 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 'jMonkeyEngine' 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: Normen Hansen
 */

#include "com_jme3_bullet_objects_VehicleWheel.h"
#include "jmeBulletUtil.h"

#ifdef __cplusplus
extern "C" {
#endif

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getWheelLocation
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getWheelLocation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_worldTransform.getOrigin(), out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getWheelRotation
     * Signature: (JLcom/jme3/math/Matrix3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getWheelRotation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_worldTransform.getBasis(), out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    applyInfo
     * Signature: (JFFFFFFFFZF)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_applyInfo
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jfloat suspensionStiffness, jfloat wheelsDampingRelaxation, jfloat wheelsDampingCompression, jfloat frictionSlip, jfloat rollInfluence, jfloat maxSuspensionTravelCm, jfloat maxSuspensionForce, jfloat radius, jboolean frontWheel, jfloat restLength) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        vehicle->getWheelInfo(wheelIndex).m_suspensionStiffness = suspensionStiffness;
        vehicle->getWheelInfo(wheelIndex).m_wheelsDampingRelaxation = wheelsDampingRelaxation;
        vehicle->getWheelInfo(wheelIndex).m_wheelsDampingCompression = wheelsDampingCompression;
        vehicle->getWheelInfo(wheelIndex).m_frictionSlip = frictionSlip;
        vehicle->getWheelInfo(wheelIndex).m_rollInfluence = rollInfluence;
        vehicle->getWheelInfo(wheelIndex).m_maxSuspensionTravelCm = maxSuspensionTravelCm;
        vehicle->getWheelInfo(wheelIndex).m_maxSuspensionForce = maxSuspensionForce;
        vehicle->getWheelInfo(wheelIndex).m_wheelsRadius = radius;
        vehicle->getWheelInfo(wheelIndex).m_bIsFrontWheel = frontWheel;
        vehicle->getWheelInfo(wheelIndex).m_suspensionRestLength1 = restLength;

    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getCollisionLocation
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getCollisionLocation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_raycastInfo.m_contactPointWS, out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getCollisionNormal
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getCollisionNormal
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_raycastInfo.m_contactNormalWS, out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getSkidInfo
     * Signature: (J)F
     */
    JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getSkidInfo
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return 0;
        }
        return vehicle->getWheelInfo(wheelIndex).m_skidInfo;
    }

    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_finalizeNative
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        delete(&vehicle->getWheelInfo(wheelIndex));
    }
#ifdef __cplusplus
}
#endif
<commit_msg>- change finalize method of VehicleWheel<commit_after>/*
 * Copyright (c) 2009-2010 jMonkeyEngine
 * 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 'jMonkeyEngine' 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: Normen Hansen
 */

#include "com_jme3_bullet_objects_VehicleWheel.h"
#include "jmeBulletUtil.h"

#ifdef __cplusplus
extern "C" {
#endif

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getWheelLocation
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getWheelLocation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_worldTransform.getOrigin(), out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getWheelRotation
     * Signature: (JLcom/jme3/math/Matrix3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getWheelRotation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_worldTransform.getBasis(), out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    applyInfo
     * Signature: (JFFFFFFFFZF)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_applyInfo
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jfloat suspensionStiffness, jfloat wheelsDampingRelaxation, jfloat wheelsDampingCompression, jfloat frictionSlip, jfloat rollInfluence, jfloat maxSuspensionTravelCm, jfloat maxSuspensionForce, jfloat radius, jboolean frontWheel, jfloat restLength) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        vehicle->getWheelInfo(wheelIndex).m_suspensionStiffness = suspensionStiffness;
        vehicle->getWheelInfo(wheelIndex).m_wheelsDampingRelaxation = wheelsDampingRelaxation;
        vehicle->getWheelInfo(wheelIndex).m_wheelsDampingCompression = wheelsDampingCompression;
        vehicle->getWheelInfo(wheelIndex).m_frictionSlip = frictionSlip;
        vehicle->getWheelInfo(wheelIndex).m_rollInfluence = rollInfluence;
        vehicle->getWheelInfo(wheelIndex).m_maxSuspensionTravelCm = maxSuspensionTravelCm;
        vehicle->getWheelInfo(wheelIndex).m_maxSuspensionForce = maxSuspensionForce;
        vehicle->getWheelInfo(wheelIndex).m_wheelsRadius = radius;
        vehicle->getWheelInfo(wheelIndex).m_bIsFrontWheel = frontWheel;
        vehicle->getWheelInfo(wheelIndex).m_suspensionRestLength1 = restLength;

    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getCollisionLocation
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getCollisionLocation
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_raycastInfo.m_contactPointWS, out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getCollisionNormal
     * Signature: (JLcom/jme3/math/Vector3f;)V
     */
    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getCollisionNormal
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex, jobject out) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        jmeBulletUtil::convert(env, &vehicle->getWheelInfo(wheelIndex).m_raycastInfo.m_contactNormalWS, out);
    }

    /*
     * Class:     com_jme3_bullet_objects_VehicleWheel
     * Method:    getSkidInfo
     * Signature: (J)F
     */
    JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_objects_VehicleWheel_getSkidInfo
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return 0;
        }
        return vehicle->getWheelInfo(wheelIndex).m_skidInfo;
    }

    JNIEXPORT void JNICALL Java_com_jme3_bullet_objects_VehicleWheel_finalizeNative
    (JNIEnv *env, jobject object, jlong vehicleId, jint wheelIndex) {
        btRaycastVehicle* vehicle = reinterpret_cast<btRaycastVehicle*>(vehicleId);
        if (vehicle == NULL) {
            jclass newExc = env->FindClass("java/lang/NullPointerException");
            env->ThrowNew(newExc, "The native object does not exist.");
            return;
        }
        btWheelInfo  m_wheelInfo[wheelIndex];
        delete(&m_wheelInfo);
    }
#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before><commit_msg>Handle partial sends over the ChromeDevToolsProtocol.<commit_after><|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 "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class AppBackgroundPageApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisablePopupBlocking);
  }
};

// TODO(mpcomplete): http://crbug.com/56091
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, DISABLED_Basic) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  LoadExtension(test_data_dir_.AppendASCII(
      "app_background_page/app_has_permission"));
  ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, LacksPermission) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  LoadExtension(test_data_dir_.AppendASCII(
      "app_background_page/app_lacks_permission"));
  ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
      << message_;
}
<commit_msg>Revert 59893 - Disable failing Basic test that I broke.<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 "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class AppBackgroundPageApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kDisablePopupBlocking);
  }
};

IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, Basic) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  LoadExtension(test_data_dir_.AppendASCII(
      "app_background_page/app_has_permission"));
  ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_;
}

IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, LacksPermission) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  LoadExtension(test_data_dir_.AppendASCII(
      "app_background_page/app_lacks_permission"));
  ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
      << message_;
}
<|endoftext|>


<commit_before><commit_msg>Remove flaky label from ParseFeed tests. No failure can be found within Pavel's log. There used to be two sources of flakiness, one that I could reproduce locally, made perfect sense and I managed to weed out. The other made no sense and I could never repro locally, and that is the one that seems to have disappeared now.<commit_after><|endoftext|>


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

#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"

using content::WebContents;

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {
  ASSERT_TRUE(StartTestServer());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("incognito")
      .AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);
  WebContents* tab = otr_browser->GetSelectedWebContents();

  // Verify the script didn't run.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result));
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("content_scripts")
      .AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);
  WebContents* tab = otr_browser->GetSelectedWebContents();

  // Verify the script ran.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result));
  EXPECT_TRUE(result);
}

// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
// Test disabled due to http://crbug.com/89054.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_DontCreateIncognitoProfile) {
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
  ASSERT_TRUE(RunExtensionTestIncognito(
      "incognito/dont_create_profile")) << message_;
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}

#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Incognito) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
#endif
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoSplitMode) {
#endif
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  ExtensionTestMessageListener listener("waiting", true);
  ExtensionTestMessageListener listener_incognito("waiting_incognito", true);

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  // Wait for both extensions to be ready before telling them to proceed.
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
  listener.Reply("go");
  listener_incognito.Reply("go");

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

#if defined(OS_WIN)
// http://crbug.com/104438.
#define MAYBE_IncognitoPopup DISABLED_IncognitoPopup
#else
#define MAYBE_IncognitoPopup IncognitoPopup
#endif
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* incognito_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Disable timed out test in Windows<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 "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"

using content::WebContents;

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoNoScript) {
  ASSERT_TRUE(StartTestServer());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("incognito")
      .AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);
  WebContents* tab = otr_browser->GetSelectedWebContents();

  // Verify the script didn't run.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result));
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("content_scripts")
      .AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* otr_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);
  WebContents* tab = otr_browser->GetSelectedWebContents();

  // Verify the script ran.
  bool result = false;
  ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->GetRenderViewHost(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result));
  EXPECT_TRUE(result);
}

// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
// Test disabled due to http://crbug.com/89054.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_DontCreateIncognitoProfile) {
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
  ASSERT_TRUE(RunExtensionTestIncognito(
      "incognito/dont_create_profile")) << message_;
  ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}

#if defined(OS_WIN)
// http://crbug.com/120484
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Incognito) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
#endif
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
#if defined(OS_WIN)
// http://crbug.com/120484
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoSplitMode) {
#endif
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  ExtensionTestMessageListener listener("waiting", true);
  ExtensionTestMessageListener listener_incognito("waiting_incognito", true);

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  // Wait for both extensions to be ready before telling them to proceed.
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
  listener.Reply("go");
  listener_incognito.Reply("go");

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
#if defined(OS_WIN)
// http://crbug.com/120484
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
#endif
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

#if defined(OS_WIN)
// http://crbug.com/104438.
#define MAYBE_IncognitoPopup DISABLED_IncognitoPopup
#else
#define MAYBE_IncognitoPopup IncognitoPopup
#endif
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(
      browser()->profile(),
      test_server()->GetURL("files/extensions/test_file.html"));

  Browser* incognito_browser = BrowserList::FindTabbedBrowser(
      browser()->profile()->GetOffTheRecordProfile(), false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>


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

#include "chrome/browser/policy/configuration_policy_loader_win.h"

#include <userenv.h>

#include "content/browser/browser_thread.h"

// userenv.dll is required for RegisterGPNotification().
#pragma comment(lib, "userenv.lib")

namespace policy {

ConfigurationPolicyLoaderWin::ConfigurationPolicyLoaderWin(
    AsynchronousPolicyProvider::Delegate* delegate,
    int reload_interval_minutes)
    : AsynchronousPolicyLoader(delegate, reload_interval_minutes),
      user_policy_changed_event_(false, false),
      machine_policy_changed_event_(false, false),
      user_policy_watcher_failed_(false),
      machine_policy_watcher_failed_(false) {
  if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) {
    PLOG(WARNING) << "Failed to register user group policy notification";
    user_policy_watcher_failed_ = true;
  }
  if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) {
    PLOG(WARNING) << "Failed to register machine group policy notification.";
    machine_policy_watcher_failed_ = true;
  }
}

void ConfigurationPolicyLoaderWin::InitOnFileThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  AsynchronousPolicyLoader::InitOnFileThread();
  SetupWatches();
}

void ConfigurationPolicyLoaderWin::StopOnFileThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  user_policy_watcher_.StopWatching();
  machine_policy_watcher_.StopWatching();
  AsynchronousPolicyLoader::StopOnFileThread();
}

void ConfigurationPolicyLoaderWin::SetupWatches() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  CancelReloadTask();

  if (!user_policy_watcher_failed_ &&
      !user_policy_watcher_.GetWatchedObject() &&
      !user_policy_watcher_.StartWatching(
          user_policy_changed_event_.handle(), this)) {
    LOG(WARNING) << "Failed to start watch for user policy change event";
    user_policy_watcher_failed_ = true;
  }
  if (!machine_policy_watcher_failed_ &&
      !machine_policy_watcher_.GetWatchedObject() &&
      !machine_policy_watcher_.StartWatching(
          machine_policy_changed_event_.handle(), this)) {
    LOG(WARNING) << "Failed to start watch for machine policy change event";
    machine_policy_watcher_failed_ = true;
   }

  if (user_policy_watcher_failed_ || machine_policy_watcher_failed_)
    ScheduleFallbackReloadTask();
}

void ConfigurationPolicyLoaderWin::Reload() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  AsynchronousPolicyLoader::Reload();
  SetupWatches();
}

void ConfigurationPolicyLoaderWin::OnObjectSignaled(HANDLE object) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  DCHECK(object == user_policy_changed_event_.handle() ||
         object == machine_policy_changed_event_.handle())
      << "unexpected object signaled policy reload, obj = "
      << std::showbase << std::hex << object;
  Reload();
}

}  // namespace policy
<commit_msg>Reset the Policy Change notification watcher before reading the policy.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/configuration_policy_loader_win.h"

#include <userenv.h>

#include "content/browser/browser_thread.h"

// userenv.dll is required for RegisterGPNotification().
#pragma comment(lib, "userenv.lib")

namespace policy {

ConfigurationPolicyLoaderWin::ConfigurationPolicyLoaderWin(
    AsynchronousPolicyProvider::Delegate* delegate,
    int reload_interval_minutes)
    : AsynchronousPolicyLoader(delegate, reload_interval_minutes),
      user_policy_changed_event_(false, false),
      machine_policy_changed_event_(false, false),
      user_policy_watcher_failed_(false),
      machine_policy_watcher_failed_(false) {
  if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) {
    PLOG(WARNING) << "Failed to register user group policy notification";
    user_policy_watcher_failed_ = true;
  }
  if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) {
    PLOG(WARNING) << "Failed to register machine group policy notification.";
    machine_policy_watcher_failed_ = true;
  }
}

void ConfigurationPolicyLoaderWin::InitOnFileThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  AsynchronousPolicyLoader::InitOnFileThread();
  SetupWatches();
}

void ConfigurationPolicyLoaderWin::StopOnFileThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  user_policy_watcher_.StopWatching();
  machine_policy_watcher_.StopWatching();
  AsynchronousPolicyLoader::StopOnFileThread();
}

void ConfigurationPolicyLoaderWin::SetupWatches() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  CancelReloadTask();

  if (!user_policy_watcher_failed_ &&
      !user_policy_watcher_.GetWatchedObject() &&
      !user_policy_watcher_.StartWatching(
          user_policy_changed_event_.handle(), this)) {
    LOG(WARNING) << "Failed to start watch for user policy change event";
    user_policy_watcher_failed_ = true;
  }
  if (!machine_policy_watcher_failed_ &&
      !machine_policy_watcher_.GetWatchedObject() &&
      !machine_policy_watcher_.StartWatching(
          machine_policy_changed_event_.handle(), this)) {
    LOG(WARNING) << "Failed to start watch for machine policy change event";
    machine_policy_watcher_failed_ = true;
   }

  if (user_policy_watcher_failed_ || machine_policy_watcher_failed_)
    ScheduleFallbackReloadTask();
}

void ConfigurationPolicyLoaderWin::Reload() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  // Reset the watches BEFORE reading the individual policies to avoid
  // missing a change notification.
  SetupWatches();
  AsynchronousPolicyLoader::Reload();
}

void ConfigurationPolicyLoaderWin::OnObjectSignaled(HANDLE object) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  DCHECK(object == user_policy_changed_event_.handle() ||
         object == machine_policy_changed_event_.handle())
      << "unexpected object signaled policy reload, obj = "
      << std::showbase << std::hex << object;
  Reload();
}

}  // namespace policy
<|endoftext|>


<commit_before>#include "archivator.h"
#include <vector>
#include <algorithm>
#include <fstream>

void archivator::compress(const std::string &dir, const std::string &destination)
{
	archive *a;
	archive_entry *entry;
	long r;

	std::vector<fs::path> files;
	fs::path dir_path;
	try {
		dir_path = fs::canonical(fs::path(dir));
		if (fs::is_directory(dir_path)) {
			for (auto i = fs::recursive_directory_iterator(dir_path); i != fs::recursive_directory_iterator(); ++i) {
				fs::path file = *i;
				if (fs::is_regular_file(file)) {
					// find out where the two paths diverge
					fs::path::const_iterator itr_dir = dir_path.begin();
					fs::path::const_iterator itr_file = file.begin();
					while (*itr_dir == *itr_file && itr_dir != dir_path.end()) {
						++itr_dir;
						++itr_file;
					}
					// result is what is left in second path (it's relative path to the first one)
					fs::path result;
					while (itr_file != file.end()) {
						result /= *itr_file;
						itr_file++;
					}
					files.push_back(result);
				}
			}
		}
	} catch (fs::filesystem_error &e) {
		throw archive_exception(e.what());
	}

	a = archive_write_new();
	archive_write_set_format_zip(a);
	r = archive_write_open_filename(a, destination.c_str());
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open destination archive.");
	}

	for (auto &file : files) {
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, (fs::path(destination).stem() / file).string().c_str());
		archive_entry_set_size(entry, fs::file_size(dir_path / file));
		archive_entry_set_mtime(entry, fs::last_write_time(dir_path / file), 0);
		archive_entry_set_filetype(entry, AE_IFREG);
		archive_entry_set_perm(entry, 0644);

		r = archive_write_header(a, entry);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		std::ifstream ifs((dir_path / file).string(), std::ios::binary);
		if (ifs.is_open()) {
			// read data by small blocks to avoid memory overfill on possibly large files
			char buff[4096];

			while (!ifs.eof()) {
				ifs.read(buff, sizeof(buff));

				if (ifs.gcount() <= 0) {
					throw archive_exception("Error reading input file");
				}

				r = archive_write_data(a, buff, (size_t) ifs.gcount());
				if (r < ARCHIVE_OK) {
					throw archive_exception(archive_error_string(a));
				}
			}
		}
		archive_entry_free(entry);
	}
	archive_write_close(a);
	archive_write_free(a);
}

void archivator::decompress(const std::string &filename, const std::string &destination)
{
	archive *a;
	archive *ext;
	archive_entry *entry;
	int flags;
	long r;

	// Select which attributes we want to restore.
	flags = ARCHIVE_EXTRACT_TIME;
	flags |= ARCHIVE_EXTRACT_FFLAGS;
	// Don't allow ".." in any path within archive
	flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;

	a = archive_read_new();
	archive_read_support_format_all(a);
	archive_read_support_compression_all(a);
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
	archive_write_disk_set_standard_lookup(ext);

	r = archive_read_open_filename(a, filename.c_str(), 10240);
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open source archive.");
	}

	while (true) {
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		const char* current_file = archive_entry_pathname(entry);
		const std::string full_path = (fs::path(destination) / current_file).string();
		archive_entry_set_pathname(entry, full_path.c_str());

		r = archive_write_header(ext, entry);

		if (archive_entry_size(entry) > 0) {
			copy_data(a, ext);
		}

		r = archive_write_finish_entry(ext);

		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ext));
		}
	}

	archive_read_close(a);
	archive_read_free(a);
	archive_write_close(ext);
	archive_write_free(ext);
}

void archivator::copy_data(archive *ar, archive *aw)
{
	int r;
	const void *buff;
	size_t size;
	int64_t offset;

	while (true) {
		r = archive_read_data_block(ar, &buff, &size, &offset);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ar));
		}
		r = archive_write_data_block(aw, buff, size, offset);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(aw));
		}
	}
}
<commit_msg>Revert "use long instead of ssize_t and int in archivator"<commit_after>#include "archivator.h"
#include <vector>
#include <algorithm>
#include <fstream>

void archivator::compress(const std::string &dir, const std::string &destination)
{
	archive *a;
	archive_entry *entry;
	ssize_t r;

	std::vector<fs::path> files;
	fs::path dir_path;
	try {
		dir_path = fs::canonical(fs::path(dir));
		if (fs::is_directory(dir_path)) {
			for (auto i = fs::recursive_directory_iterator(dir_path); i != fs::recursive_directory_iterator(); ++i) {
				fs::path file = *i;
				if (fs::is_regular_file(file)) {
					// find out where the two paths diverge
					fs::path::const_iterator itr_dir = dir_path.begin();
					fs::path::const_iterator itr_file = file.begin();
					while (*itr_dir == *itr_file && itr_dir != dir_path.end()) {
						++itr_dir;
						++itr_file;
					}
					// result is what is left in second path (it's relative path to the first one)
					fs::path result;
					while (itr_file != file.end()) {
						result /= *itr_file;
						itr_file++;
					}
					files.push_back(result);
				}
			}
		}
	} catch (fs::filesystem_error &e) {
		throw archive_exception(e.what());
	}

	a = archive_write_new();
	archive_write_set_format_zip(a);
	r = archive_write_open_filename(a, destination.c_str());
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open destination archive.");
	}

	for (auto &file : files) {
		entry = archive_entry_new();

		archive_entry_set_pathname(entry, (fs::path(destination).stem() / file).string().c_str());
		archive_entry_set_size(entry, fs::file_size(dir_path / file));
		archive_entry_set_mtime(entry, fs::last_write_time(dir_path / file), 0);
		archive_entry_set_filetype(entry, AE_IFREG);
		archive_entry_set_perm(entry, 0644);

		r = archive_write_header(a, entry);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		std::ifstream ifs((dir_path / file).string(), std::ios::binary);
		if (ifs.is_open()) {
			// read data by small blocks to avoid memory overfill on possibly large files
			char buff[4096];

			while (!ifs.eof()) {
				ifs.read(buff, sizeof(buff));

				if (ifs.gcount() <= 0) {
					throw archive_exception("Error reading input file");
				}

				r = archive_write_data(a, buff, (size_t) ifs.gcount());
				if (r < ARCHIVE_OK) {
					throw archive_exception(archive_error_string(a));
				}
			}
		}
		archive_entry_free(entry);
	}
	archive_write_close(a);
	archive_write_free(a);
}

void archivator::decompress(const std::string &filename, const std::string &destination)
{
	archive *a;
	archive *ext;
	archive_entry *entry;
	int flags;
	int r;

	// Select which attributes we want to restore.
	flags = ARCHIVE_EXTRACT_TIME;
	flags |= ARCHIVE_EXTRACT_FFLAGS;
	// Don't allow ".." in any path within archive
	flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;

	a = archive_read_new();
	archive_read_support_format_all(a);
	archive_read_support_compression_all(a);
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
	archive_write_disk_set_standard_lookup(ext);

	r = archive_read_open_filename(a, filename.c_str(), 10240);
	if (r != ARCHIVE_OK) {
		throw archive_exception("Cannot open source archive.");
	}

	while (true) {
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(a));
		}

		const char* current_file = archive_entry_pathname(entry);
		const std::string full_path = (fs::path(destination) / current_file).string();
		archive_entry_set_pathname(entry, full_path.c_str());

		r = archive_write_header(ext, entry);

		if (archive_entry_size(entry) > 0) {
			copy_data(a, ext);
		}

		r = archive_write_finish_entry(ext);

		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ext));
		}
	}

	archive_read_close(a);
	archive_read_free(a);
	archive_write_close(ext);
	archive_write_free(ext);
}

void archivator::copy_data(archive *ar, archive *aw)
{
	int r;
	const void *buff;
	size_t size;
	int64_t offset;

	while (true) {
		r = archive_read_data_block(ar, &buff, &size, &offset);
		if (r == ARCHIVE_EOF) {
			break;
		}
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(ar));
		}
		r = archive_write_data_block(aw, buff, size, offset);
		if (r < ARCHIVE_OK) {
			throw archive_exception(archive_error_string(aw));
		}
	}
}
<|endoftext|>


<commit_before>#include "MINDSi.h"
#include "wiring_private.h"

const uint16_t RADIO_CHECK_INTERVAL = 0x7550;  //loops - no interrupt timeout
const uint32_t RADIO_TIMEOUT 		= 1000000; //microseconds interrupt timeout
const uint16_t PING_MAX			    = 20000;   //microseconds until no response

volatile uint32_t pStart[EXTERNAL_NUM_INTERRUPTS];
volatile uint32_t pTime [EXTERNAL_NUM_INTERRUPTS];
int8_t interruptPin[EXTERNAL_NUM_INTERRUPTS];
boolean interruptOn[EXTERNAL_NUM_INTERRUPTS];

template<int num>
void inline iFunc(void){
	if(fastDigitalRead(interruptPin[num])) pStart[num] = micros();
	else pTime[num] = micros()-pStart[num];
}

//number of interrupts can only by 2,3,5 or 8 on current models
voidFuncPtr func[EXTERNAL_NUM_INTERRUPTS]={
	 iFunc<0>
	,iFunc<1>
#if EXTERNAL_NUM_INTERRUPTS > 2
	,iFunc<2>
#if EXTERNAL_NUM_INTERRUPTS > 3
	,iFunc<3>
#if EXTERNAL_NUM_INTERRUPTS > 4
	,iFunc<4>
#if EXTERNAL_NUM_INTERRUPTS > 5
	,iFunc<5>
	,iFunc<6>
	,iFunc<7>
#endif
#endif
#endif
#endif
};

boolean inline isIntOn(int interrupt){
	//the registers differ too much on each chip to read directly
	return interruptOn[interrupt];
}

int getRadioPulse(int pin, bool interrupt){
	int pulse;
	int iNum = digitalPinToInterrupt(pin);

	//get signal width
	if(interrupt && iNum!=NOT_AN_INTERRUPT){
		if( !isIntOn(iNum) ) {
			attachInterrupt(iNum, func[iNum], CHANGE);
			interruptPin[iNum]=pin; //there is no interruptToDigitalPin Macro
			interruptOn[iNum]=true;
			interrupts();
		} else {
			pulse = pTime[iNum];
		}
	} else {
		pulse = pulseIn(pin, HIGH);
	}

	if(pulse == 0) pulse = 1500; //1500 is exactly centered ppm signal
	return pulse;
}

int getRadio(int pin, int min, int max, bool interrupt){
	int sig = map(getRadioPulse(pin,interrupt), 1020, 1980, min, max);
	bound(0, sig, 180);
	return sig;
}

unsigned long timeLastSignal(){
	unsigned long latestSignal = 0;
	for(int i=0; i<EXTERNAL_NUM_INTERRUPTS; i++){
		max(pStart[i], latestSignal);
	}
	return latestSignal;
}

bool isRadioOn(int pin){
	int iNum = digitalPinToInterrupt(pin);
	if( iNum!=NOT_AN_INTERRUPT && isIntOn(iNum) ){
		return (micros() < pStart[iNum] + RADIO_TIMEOUT);
	} else {
		uint16_t numloops;
		uint8_t lastState = fastDigitalRead(pin);
		while (fastDigitalRead(pin) == lastState) {
			if (numloops++ >= RADIO_CHECK_INTERVAL) return false;
		}
		return true;
	}
}

int getPing(int pin){
	pinMode(pin, OUTPUT);
	digitalWrite(pin, LOW);
	delayMicroseconds(5);
	digitalWrite(pin, HIGH);
	delayMicroseconds(5);
	digitalWrite(pin, LOW);
	delayMicroseconds(5);
	setInput(pin);
	int inputpulse = pulseIn(pin, HIGH, PING_MAX);
	if(inputpulse == 0) inputpulse = PING_MAX;
	delayMicroseconds(200);
	pinMode(pin, OUTPUT);
	digitalWrite(pin, LOW);
	return inputpulse;
}

int QTI(int pin){
	unsigned int time = 0;
	pinMode(pin, OUTPUT);
	digitalWrite(pin, HIGH);
	delay(1);
	setInput(pin);
	digitalWrite(pin, LOW);
	//fastDigitalRead is not used to keep values consistent with older versions
	while (digitalRead(pin)) {
		time++;
		if(time >= 10000) break;
	}
	return time;
}

//setting pinMode takes time; this will check if it has already been set first
void inline setInput(int pin){
	if((*portModeRegister(digitalPinToPort(pin)) & digitalPinToBitMask(pin))!=0)
		pinMode(pin, INPUT);
}

//normal digitalRead is also too slow for some applications
inline bool fastDigitalRead(int pin){
	return *portInputRegister(digitalPinToPort(pin)) & digitalPinToBitMask(pin);
}
<commit_msg>message<commit_after>#include "MINDSi.h"
#include "wiring_private.h"

const uint16_t RADIO_CHECK_INTERVAL = 0x7550;  //loops - no interrupt timeout
const uint32_t RADIO_TIMEOUT 		= 1000000; //microseconds interrupt timeout
const uint16_t PING_MAX			    = 20000;   //microseconds until no response

volatile uint32_t pStart[EXTERNAL_NUM_INTERRUPTS];
volatile uint32_t pTime [EXTERNAL_NUM_INTERRUPTS];
int8_t interruptPin[EXTERNAL_NUM_INTERRUPTS];
boolean interruptOn[EXTERNAL_NUM_INTERRUPTS];

template<int num>
void inline iFunc(void){
	if(fastDigitalRead(interruptPin[num])) pStart[num] = micros();
	else pTime[num] = micros()-pStart[num];
}

//number of interrupts can only by 2,3,5 or 8 on current models
voidFuncPtr func[EXTERNAL_NUM_INTERRUPTS]={
	 iFunc<0>
	,iFunc<1>
#if EXTERNAL_NUM_INTERRUPTS > 2
	,iFunc<2>
#if EXTERNAL_NUM_INTERRUPTS > 3
	,iFunc<3>
#if EXTERNAL_NUM_INTERRUPTS > 4
	,iFunc<4>
#if EXTERNAL_NUM_INTERRUPTS > 5
	,iFunc<5>
	,iFunc<6>
	,iFunc<7>
#endif
#endif
#endif
#endif
};

boolean inline isIntOn(int interrupt){
	//the registers differ too much on each chip to read directly
	return interruptOn[interrupt];
}

int getRadioPulse(int pin, bool interrupt){
	int pulse;
	int iNum = digitalPinToInterrupt(pin);

	//get signal width
	if(interrupt && iNum!=NOT_AN_INTERRUPT){
		if( !isIntOn(iNum) ) {
			attachInterrupt(iNum, func[iNum], CHANGE);
			interruptPin[iNum]=pin; //there is no interruptToDigitalPin Macro
			interruptOn[iNum] =true;
			interrupts();
		} else {
			pulse = pTime[iNum];
		}
	} else {
		pulse = pulseIn(pin, HIGH);
	}

	if(pulse == 0) pulse = 1500; //1500 is exactly centered ppm signal
	return pulse;
}

int getRadio(int pin, int min, int max, bool interrupt){
	int sig = map(getRadioPulse(pin,interrupt), 1020, 1980, min, max);
	bound(0, sig, 180);
	return sig;
}

unsigned long timeLastSignal(){
	unsigned long latestSignal = 0;
	for(int i=0; i<EXTERNAL_NUM_INTERRUPTS; i++){
		max(pStart[i], latestSignal);
	}
	return latestSignal;
}

bool isRadioOn(int pin){
	int iNum = digitalPinToInterrupt(pin);
	if( iNum!=NOT_AN_INTERRUPT && isIntOn(iNum) ){
		return (micros() < pStart[iNum] + RADIO_TIMEOUT);
	} else {
		uint16_t numloops;
		uint8_t lastState = fastDigitalRead(pin);
		while (fastDigitalRead(pin) == lastState) {
			if (numloops++ >= RADIO_CHECK_INTERVAL) return false;
		}
		return true;
	}
}

int getPing(int pin){
	pinMode(pin, OUTPUT);
	digitalWrite(pin, LOW);
	delayMicroseconds(5);
	digitalWrite(pin, HIGH);
	delayMicroseconds(5);
	digitalWrite(pin, LOW);
	delayMicroseconds(5);
	setInput(pin);
	int inputpulse = pulseIn(pin, HIGH, PING_MAX);
	if(inputpulse == 0) inputpulse = PING_MAX;
	delayMicroseconds(200);
	pinMode(pin, OUTPUT);
	digitalWrite(pin, LOW);
	return inputpulse;
}

int QTI(int pin){
	unsigned int time = 0;
	pinMode(pin, OUTPUT);
	digitalWrite(pin, HIGH);
	delay(1);
	setInput(pin);
	digitalWrite(pin, LOW);
	//fastDigitalRead is not used to keep values consistent with older versions
	while (digitalRead(pin)) {
		time++;
		if(time >= 10000) break;
	}
	return time;
}

//setting pinMode takes time; this will check if it has already been set first
void inline setInput(int pin){
	if((*portModeRegister(digitalPinToPort(pin)) & digitalPinToBitMask(pin))!=0)
		pinMode(pin, INPUT);
}

//normal digitalRead is also too slow for some applications
inline bool fastDigitalRead(int pin){
	return *portInputRegister(digitalPinToPort(pin)) & digitalPinToBitMask(pin);
}
<|endoftext|>


<commit_before>#include "Matrix.h"

#include <stdexcept>

static const float EPSILON = 1.e-10;

/******************************** HELPER *******************************/

static void updateHelper2(float& val, float delta)
{
    val = std::abs(val + delta) < EPSILON ? 0.0 : val + delta;
}

template<class GenericMatrix>
static void updateHelper(GenericMatrix &mat, const MatrixChange &change)
{
    updateHelper2(mat(change.row1, change.col1), change.delta1);
    if (change.nChanges > 1)
    {
        updateHelper2(mat(change.row2, change.col2), change.delta2);
    }
}

template<class GenericMatrix>
static Rcpp::NumericMatrix convertToRMatrix(const GenericMatrix &mat)
{
    Rcpp::NumericMatrix rmat(mat.nRow(), mat.nCol());
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        for (unsigned j = 0; j < mat.nCol(); ++j)
        {
            rmat(i,j) = mat(i,j);
        }
    }
    return rmat;
}

/******************************** VECTOR *******************************/

void Vector::concat(const Vector& vec)
{
    mValues.insert(mValues.end(), vec.mValues.begin(), vec.mValues.end());
}

void Vector::operator+=(const Vector &vec)
{
    for (unsigned i = 0; i < size(); ++i)
    {
        mValues[i] += vec[i];
    }
}

void Vector::operator=(const Vector &vec)
{
    mValues = vec.mValues;
}

Vector Vector::operator+(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] += mValues[i];
    }
    return vec;
}

Vector Vector::operator-(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] -= mValues[i];
    }
    return vec;
}

Vector Vector::operator*(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] *= mValues[i];
    }
    return vec;
}

Vector Vector::operator/(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] /= mValues[i];
    }
    return vec;
}

Vector Vector::operator+(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] += val;
    }
    return vec;
}

Vector Vector::operator-(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] -= val;
    }
    return vec;
}

Vector Vector::operator*(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] *= val;
    }
    return vec;
}

Vector Vector::operator/(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] /= val;
    }
    return vec;
}

Archive& operator<<(Archive &ar, Vector &vec)
{
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        ar << vec[i];
    }
    return ar;
}

Archive& operator>>(Archive &ar, Vector &vec)
{
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        ar >> vec.mValues[i];
    }
    return ar;
}

/****************************** ROW MATRIX *****************************/

RowMatrix::RowMatrix(unsigned nrow, unsigned ncol)
: mNumRows(nrow), mNumCols(ncol)
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
    }
}

RowMatrix::RowMatrix(const Rcpp::NumericMatrix &rmat)
: mNumRows(rmat.nrow()), mNumCols(rmat.ncol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
        for (unsigned j = 0; j < mNumCols; ++j)
        {
            this->operator()(i,j) = rmat(i,j);
        }
    }
}

RowMatrix::RowMatrix(const RowMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(mat.getRow(i));
    }
}

RowMatrix::RowMatrix(const ColMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
        for (unsigned j = 0; j < mNumCols; ++j)
        {
            this->operator()(i,j) = mat(i,j);
        }
    }
}

void RowMatrix::update(const MatrixChange &change)
{
    updateHelper<RowMatrix>(*this, change);
}

Rcpp::NumericMatrix RowMatrix::rMatrix() const
{
    return convertToRMatrix<RowMatrix>(*this);
}

RowMatrix RowMatrix::operator/(float val) const
{
    RowMatrix mat(mNumRows, mNumCols);
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mat.getRow(i) = mRows[i] / val;
    }
    return mat;
}

Archive& operator<<(Archive &ar, RowMatrix &mat)
{
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        ar << mat.mRows[i];
    }
    return ar;
}

Archive& operator>>(Archive &ar, RowMatrix &mat)
{
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        ar >> mat.mRows[i];
    }
    return ar;
}

/**************************** COLUMN MATRIX ****************************/

ColMatrix::ColMatrix(unsigned nrow, unsigned ncol)
: mNumRows(nrow), mNumCols(ncol)
{
    for (unsigned i = 0; i < mNumCols; ++i)
    {
        mCols.push_back(Vector(mNumRows));
    }
}

ColMatrix::ColMatrix(const Rcpp::NumericMatrix &rmat)
: mNumRows(rmat.nrow()), mNumCols(rmat.ncol())
{
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mCols.push_back(Vector(mNumRows));
        for (unsigned i = 0; i < mNumRows; ++i)
        {
            this->operator()(i,j) = rmat(i,j);
        }
    }
}

ColMatrix::ColMatrix(const ColMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mCols.push_back(mat.getCol(j));
    }
}

void ColMatrix::update(const MatrixChange &change)
{
    updateHelper<ColMatrix>(*this, change);
}

ColMatrix ColMatrix::operator/(float val) const
{
    ColMatrix mat(mNumRows, mNumCols);
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mat.getCol(j) = mCols[j] / val;
    }
    return mat;
}

Rcpp::NumericMatrix ColMatrix::rMatrix() const
{
    return convertToRMatrix<ColMatrix>(*this);
}

Archive& operator<<(Archive &ar, ColMatrix &mat)
{
    for (unsigned j = 0; j < mat.nCol(); ++j)
    {
        ar << mat.mCols[j];
    }
    return ar;
}

Archive& operator>>(Archive &ar, ColMatrix &mat)
{
    for (unsigned j = 0; j < mat.nCol(); ++j)
    {
        ar >> mat.mCols[j];
    }
    return ar;
}<commit_msg>don't allow negatives<commit_after>#include "Matrix.h"

#include <stdexcept>

static const float EPSILON = 1.e-10f;

/******************************** HELPER *******************************/

static void updateHelper2(float& val, float delta)
{
    val = val + delta < EPSILON ? 0.f : val + delta;
}

template<class GenericMatrix>
static void updateHelper(GenericMatrix &mat, const MatrixChange &change)
{
    updateHelper2(mat(change.row1, change.col1), change.delta1);
    if (change.nChanges > 1)
    {
        updateHelper2(mat(change.row2, change.col2), change.delta2);
    }
}

template<class GenericMatrix>
static Rcpp::NumericMatrix convertToRMatrix(const GenericMatrix &mat)
{
    Rcpp::NumericMatrix rmat(mat.nRow(), mat.nCol());
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        for (unsigned j = 0; j < mat.nCol(); ++j)
        {
            rmat(i,j) = mat(i,j);
        }
    }
    return rmat;
}

/******************************** VECTOR *******************************/

void Vector::concat(const Vector& vec)
{
    mValues.insert(mValues.end(), vec.mValues.begin(), vec.mValues.end());
}

void Vector::operator+=(const Vector &vec)
{
    for (unsigned i = 0; i < size(); ++i)
    {
        mValues[i] += vec[i];
    }
}

void Vector::operator=(const Vector &vec)
{
    mValues = vec.mValues;
}

Vector Vector::operator+(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] += mValues[i];
    }
    return vec;
}

Vector Vector::operator-(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] -= mValues[i];
    }
    return vec;
}

Vector Vector::operator*(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] *= mValues[i];
    }
    return vec;
}

Vector Vector::operator/(Vector vec) const
{
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] /= mValues[i];
    }
    return vec;
}

Vector Vector::operator+(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] += val;
    }
    return vec;
}

Vector Vector::operator-(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] -= val;
    }
    return vec;
}

Vector Vector::operator*(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] *= val;
    }
    return vec;
}

Vector Vector::operator/(float val) const
{
    Vector vec(*this);
    for (unsigned i = 0; i < size(); ++i)
    {
        vec[i] /= val;
    }
    return vec;
}

Archive& operator<<(Archive &ar, Vector &vec)
{
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        ar << vec[i];
    }
    return ar;
}

Archive& operator>>(Archive &ar, Vector &vec)
{
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        ar >> vec.mValues[i];
    }
    return ar;
}

/****************************** ROW MATRIX *****************************/

RowMatrix::RowMatrix(unsigned nrow, unsigned ncol)
: mNumRows(nrow), mNumCols(ncol)
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
    }
}

RowMatrix::RowMatrix(const Rcpp::NumericMatrix &rmat)
: mNumRows(rmat.nrow()), mNumCols(rmat.ncol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
        for (unsigned j = 0; j < mNumCols; ++j)
        {
            this->operator()(i,j) = rmat(i,j);
        }
    }
}

RowMatrix::RowMatrix(const RowMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(mat.getRow(i));
    }
}

RowMatrix::RowMatrix(const ColMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mRows.push_back(Vector(mNumCols));
        for (unsigned j = 0; j < mNumCols; ++j)
        {
            this->operator()(i,j) = mat(i,j);
        }
    }
}

void RowMatrix::update(const MatrixChange &change)
{
    updateHelper<RowMatrix>(*this, change);
}

Rcpp::NumericMatrix RowMatrix::rMatrix() const
{
    return convertToRMatrix<RowMatrix>(*this);
}

RowMatrix RowMatrix::operator/(float val) const
{
    RowMatrix mat(mNumRows, mNumCols);
    for (unsigned i = 0; i < mNumRows; ++i)
    {
        mat.getRow(i) = mRows[i] / val;
    }
    return mat;
}

Archive& operator<<(Archive &ar, RowMatrix &mat)
{
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        ar << mat.mRows[i];
    }
    return ar;
}

Archive& operator>>(Archive &ar, RowMatrix &mat)
{
    for (unsigned i = 0; i < mat.nRow(); ++i)
    {
        ar >> mat.mRows[i];
    }
    return ar;
}

/**************************** COLUMN MATRIX ****************************/

ColMatrix::ColMatrix(unsigned nrow, unsigned ncol)
: mNumRows(nrow), mNumCols(ncol)
{
    for (unsigned i = 0; i < mNumCols; ++i)
    {
        mCols.push_back(Vector(mNumRows));
    }
}

ColMatrix::ColMatrix(const Rcpp::NumericMatrix &rmat)
: mNumRows(rmat.nrow()), mNumCols(rmat.ncol())
{
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mCols.push_back(Vector(mNumRows));
        for (unsigned i = 0; i < mNumRows; ++i)
        {
            this->operator()(i,j) = rmat(i,j);
        }
    }
}

ColMatrix::ColMatrix(const ColMatrix &mat)
: mNumRows(mat.nRow()), mNumCols(mat.nCol())
{
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mCols.push_back(mat.getCol(j));
    }
}

void ColMatrix::update(const MatrixChange &change)
{
    updateHelper<ColMatrix>(*this, change);
}

ColMatrix ColMatrix::operator/(float val) const
{
    ColMatrix mat(mNumRows, mNumCols);
    for (unsigned j = 0; j < mNumCols; ++j)
    {
        mat.getCol(j) = mCols[j] / val;
    }
    return mat;
}

Rcpp::NumericMatrix ColMatrix::rMatrix() const
{
    return convertToRMatrix<ColMatrix>(*this);
}

Archive& operator<<(Archive &ar, ColMatrix &mat)
{
    for (unsigned j = 0; j < mat.nCol(); ++j)
    {
        ar << mat.mCols[j];
    }
    return ar;
}

Archive& operator>>(Archive &ar, ColMatrix &mat)
{
    for (unsigned j = 0; j < mat.nCol(); ++j)
    {
        ar >> mat.mCols[j];
    }
    return ar;
}<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>

template<typename HyperplaneType> void hyperplane(const HyperplaneType& _plane)
{
  /* this test covers the following files:
     Hyperplane.h
  */
  typedef typename HyperplaneType::Index Index;
  const Index dim = _plane.dim();
  enum { Options = HyperplaneType::Options };
  typedef typename HyperplaneType::Scalar Scalar;
  typedef Matrix<Scalar, HyperplaneType::AmbientDimAtCompileTime, 1> VectorType;
  typedef Matrix<Scalar, HyperplaneType::AmbientDimAtCompileTime,
                         HyperplaneType::AmbientDimAtCompileTime> MatrixType;

  VectorType p0 = VectorType::Random(dim);
  VectorType p1 = VectorType::Random(dim);

  VectorType n0 = VectorType::Random(dim).normalized();
  VectorType n1 = VectorType::Random(dim).normalized();

  HyperplaneType pl0(n0, p0);
  HyperplaneType pl1(n1, p1);
  HyperplaneType pl2 = pl1;

  Scalar s0 = internal::random<Scalar>();
  Scalar s1 = internal::random<Scalar>();

  VERIFY_IS_APPROX( n1.dot(n1), Scalar(1) );

  VERIFY_IS_MUCH_SMALLER_THAN( pl0.absDistance(p0), Scalar(1) );
  VERIFY_IS_APPROX( pl1.signedDistance(p1 + n1 * s0), s0 );
  VERIFY_IS_MUCH_SMALLER_THAN( pl1.signedDistance(pl1.projection(p0)), Scalar(1) );
  VERIFY_IS_MUCH_SMALLER_THAN( pl1.absDistance(p1 +  pl1.normal().unitOrthogonal() * s1), Scalar(1) );

  // transform
  if (!NumTraits<Scalar>::IsComplex)
  {
    MatrixType rot = MatrixType::Random(dim,dim).householderQr().householderQ();
    DiagonalMatrix<Scalar,HyperplaneType::AmbientDimAtCompileTime> scaling(VectorType::Random());
    Translation<Scalar,HyperplaneType::AmbientDimAtCompileTime> translation(VectorType::Random());

    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot).absDistance(rot * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot,Isometry).absDistance(rot * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*scaling).absDistance((rot*scaling) * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*scaling*translation)
                                 .absDistance((rot*scaling*translation) * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*translation,Isometry)
                                 .absDistance((rot*translation) * p1), Scalar(1) );
  }

  // casting
  const int Dim = HyperplaneType::AmbientDimAtCompileTime;
  typedef typename GetDifferentType<Scalar>::type OtherScalar;
  Hyperplane<OtherScalar,Dim,Options> hp1f = pl1.template cast<OtherScalar>();
  VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),pl1);
  Hyperplane<Scalar,Dim,Options> hp1d = pl1.template cast<Scalar>();
  VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),pl1);
}

template<typename Scalar> void lines()
{
  using std::abs;
  typedef Hyperplane<Scalar, 2> HLine;
  typedef ParametrizedLine<Scalar, 2> PLine;
  typedef Matrix<Scalar,2,1> Vector;
  typedef Matrix<Scalar,3,1> CoeffsType;

  for(int i = 0; i < 10; i++)
  {
    Vector center = Vector::Random();
    Vector u = Vector::Random();
    Vector v = Vector::Random();
    Scalar a = internal::random<Scalar>();
    while (abs(a-1) < 1e-4) a = internal::random<Scalar>();
    while (u.norm() < 1e-4) u = Vector::Random();
    while (v.norm() < 1e-4) v = Vector::Random();

    HLine line_u = HLine::Through(center + u, center + a*u);
    HLine line_v = HLine::Through(center + v, center + a*v);

    // the line equations should be normalized so that a^2+b^2=1
    VERIFY_IS_APPROX(line_u.normal().norm(), Scalar(1));
    VERIFY_IS_APPROX(line_v.normal().norm(), Scalar(1));

    Vector result = line_u.intersection(line_v);

    // the lines should intersect at the point we called "center"
    VERIFY_IS_APPROX(result, center);

    // check conversions between two types of lines
    PLine pl(line_u); // gcc 3.3 will commit suicide if we don't name this variable
    CoeffsType converted_coeffs = HLine(pl).coeffs();
    converted_coeffs *= (line_u.coeffs()[0])/(converted_coeffs[0]);
    VERIFY(line_u.coeffs().isApprox(converted_coeffs));
  }
}

template<typename Scalar> void hyperplane_alignment()
{
  typedef Hyperplane<Scalar,3,AutoAlign> Plane3a;
  typedef Hyperplane<Scalar,3,DontAlign> Plane3u;

  EIGEN_ALIGN16 Scalar array1[4];
  EIGEN_ALIGN16 Scalar array2[4];
  EIGEN_ALIGN16 Scalar array3[4+1];
  Scalar* array3u = array3+1;

  Plane3a *p1 = ::new(reinterpret_cast<void*>(array1)) Plane3a;
  Plane3u *p2 = ::new(reinterpret_cast<void*>(array2)) Plane3u;
  Plane3u *p3 = ::new(reinterpret_cast<void*>(array3u)) Plane3u;

  p1->coeffs().setRandom();
  *p2 = *p1;
  *p3 = *p1;

  VERIFY_IS_APPROX(p1->coeffs(), p2->coeffs());
  VERIFY_IS_APPROX(p1->coeffs(), p3->coeffs());

  #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY
  if(internal::packet_traits<Scalar>::Vectorizable)
    VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Plane3a));
  #endif
}

void test_geo_hyperplane()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( hyperplane(Hyperplane<float,2>()) );
    CALL_SUBTEST_2( hyperplane(Hyperplane<float,3>()) );
    CALL_SUBTEST_2( hyperplane(Hyperplane<float,3,DontAlign>()) );
    CALL_SUBTEST_2( hyperplane_alignment<float>() );
    CALL_SUBTEST_3( hyperplane(Hyperplane<double,4>()) );
    CALL_SUBTEST_4( hyperplane(Hyperplane<std::complex<double>,5>()) );
    CALL_SUBTEST_1( lines<float>() );
    CALL_SUBTEST_3( lines<double>() );
  }
}
<commit_msg>Make geo_hyperplane unit test more stable (bug 539)<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/QR>

template<typename HyperplaneType> void hyperplane(const HyperplaneType& _plane)
{
  /* this test covers the following files:
     Hyperplane.h
  */
  using std::abs;
  typedef typename HyperplaneType::Index Index;
  const Index dim = _plane.dim();
  enum { Options = HyperplaneType::Options };
  typedef typename HyperplaneType::Scalar Scalar;
  typedef typename HyperplaneType::RealScalar RealScalar;
  typedef Matrix<Scalar, HyperplaneType::AmbientDimAtCompileTime, 1> VectorType;
  typedef Matrix<Scalar, HyperplaneType::AmbientDimAtCompileTime,
                         HyperplaneType::AmbientDimAtCompileTime> MatrixType;

  VectorType p0 = VectorType::Random(dim);
  VectorType p1 = VectorType::Random(dim);

  VectorType n0 = VectorType::Random(dim).normalized();
  VectorType n1 = VectorType::Random(dim).normalized();

  HyperplaneType pl0(n0, p0);
  HyperplaneType pl1(n1, p1);
  HyperplaneType pl2 = pl1;

  Scalar s0 = internal::random<Scalar>();
  Scalar s1 = internal::random<Scalar>();

  VERIFY_IS_APPROX( n1.dot(n1), Scalar(1) );

  VERIFY_IS_MUCH_SMALLER_THAN( pl0.absDistance(p0), Scalar(1) );
  if(numext::abs2(s0)>RealScalar(1e-6))
    VERIFY_IS_APPROX( pl1.signedDistance(p1 + n1 * s0), s0);
  else
    VERIFY_IS_MUCH_SMALLER_THAN( abs(pl1.signedDistance(p1 + n1 * s0) - s0), Scalar(1) );
  VERIFY_IS_MUCH_SMALLER_THAN( pl1.signedDistance(pl1.projection(p0)), Scalar(1) );
  VERIFY_IS_MUCH_SMALLER_THAN( pl1.absDistance(p1 +  pl1.normal().unitOrthogonal() * s1), Scalar(1) );

  // transform
  if (!NumTraits<Scalar>::IsComplex)
  {
    MatrixType rot = MatrixType::Random(dim,dim).householderQr().householderQ();
    DiagonalMatrix<Scalar,HyperplaneType::AmbientDimAtCompileTime> scaling(VectorType::Random());
    Translation<Scalar,HyperplaneType::AmbientDimAtCompileTime> translation(VectorType::Random());

    while(scaling.diagonal().cwiseAbs().minCoeff()<RealScalar(1e-4)) scaling.diagonal() = VectorType::Random();

    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot).absDistance(rot * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot,Isometry).absDistance(rot * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*scaling).absDistance((rot*scaling) * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*scaling*translation)
                                  .absDistance((rot*scaling*translation) * p1), Scalar(1) );
    pl2 = pl1;
    VERIFY_IS_MUCH_SMALLER_THAN( pl2.transform(rot*translation,Isometry)
                                 .absDistance((rot*translation) * p1), Scalar(1) );
  }

  // casting
  const int Dim = HyperplaneType::AmbientDimAtCompileTime;
  typedef typename GetDifferentType<Scalar>::type OtherScalar;
  Hyperplane<OtherScalar,Dim,Options> hp1f = pl1.template cast<OtherScalar>();
  VERIFY_IS_APPROX(hp1f.template cast<Scalar>(),pl1);
  Hyperplane<Scalar,Dim,Options> hp1d = pl1.template cast<Scalar>();
  VERIFY_IS_APPROX(hp1d.template cast<Scalar>(),pl1);
}

template<typename Scalar> void lines()
{
  using std::abs;
  typedef Hyperplane<Scalar, 2> HLine;
  typedef ParametrizedLine<Scalar, 2> PLine;
  typedef Matrix<Scalar,2,1> Vector;
  typedef Matrix<Scalar,3,1> CoeffsType;

  for(int i = 0; i < 10; i++)
  {
    Vector center = Vector::Random();
    Vector u = Vector::Random();
    Vector v = Vector::Random();
    Scalar a = internal::random<Scalar>();
    while (abs(a-1) < 1e-4) a = internal::random<Scalar>();
    while (u.norm() < 1e-4) u = Vector::Random();
    while (v.norm() < 1e-4) v = Vector::Random();

    HLine line_u = HLine::Through(center + u, center + a*u);
    HLine line_v = HLine::Through(center + v, center + a*v);

    // the line equations should be normalized so that a^2+b^2=1
    VERIFY_IS_APPROX(line_u.normal().norm(), Scalar(1));
    VERIFY_IS_APPROX(line_v.normal().norm(), Scalar(1));

    Vector result = line_u.intersection(line_v);

    // the lines should intersect at the point we called "center"
    if(abs(a-1) > 1e-2 && abs(v.normalized().dot(u.normalized()))<0.9)
      VERIFY_IS_APPROX(result, center);

    // check conversions between two types of lines
    PLine pl(line_u); // gcc 3.3 will commit suicide if we don't name this variable
    HLine line_u2(pl);
    CoeffsType converted_coeffs = line_u2.coeffs();
    if(line_u2.normal().dot(line_u.normal())<0.)
      converted_coeffs = -line_u2.coeffs();
    VERIFY(line_u.coeffs().isApprox(converted_coeffs));
  }
}

template<typename Scalar> void hyperplane_alignment()
{
  typedef Hyperplane<Scalar,3,AutoAlign> Plane3a;
  typedef Hyperplane<Scalar,3,DontAlign> Plane3u;

  EIGEN_ALIGN16 Scalar array1[4];
  EIGEN_ALIGN16 Scalar array2[4];
  EIGEN_ALIGN16 Scalar array3[4+1];
  Scalar* array3u = array3+1;

  Plane3a *p1 = ::new(reinterpret_cast<void*>(array1)) Plane3a;
  Plane3u *p2 = ::new(reinterpret_cast<void*>(array2)) Plane3u;
  Plane3u *p3 = ::new(reinterpret_cast<void*>(array3u)) Plane3u;

  p1->coeffs().setRandom();
  *p2 = *p1;
  *p3 = *p1;

  VERIFY_IS_APPROX(p1->coeffs(), p2->coeffs());
  VERIFY_IS_APPROX(p1->coeffs(), p3->coeffs());

  #if defined(EIGEN_VECTORIZE) && EIGEN_ALIGN_STATICALLY
  if(internal::packet_traits<Scalar>::Vectorizable)
    VERIFY_RAISES_ASSERT((::new(reinterpret_cast<void*>(array3u)) Plane3a));
  #endif
}

void test_geo_hyperplane()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( hyperplane(Hyperplane<float,2>()) );
    CALL_SUBTEST_2( hyperplane(Hyperplane<float,3>()) );
    CALL_SUBTEST_2( hyperplane(Hyperplane<float,3,DontAlign>()) );
    CALL_SUBTEST_2( hyperplane_alignment<float>() );
    CALL_SUBTEST_3( hyperplane(Hyperplane<double,4>()) );
    CALL_SUBTEST_4( hyperplane(Hyperplane<std::complex<double>,5>()) );
    CALL_SUBTEST_1( lines<float>() );
    CALL_SUBTEST_3( lines<double>() );
  }
}
<|endoftext|>