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

#include "chrome/browser/extensions/extension_processes_api.h"

#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"

#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"

namespace keys = extension_processes_api_constants;

DictionaryValue* CreateProcessValue(int process_id,
                                    const std::string& type,
                                    double cpu,
                                    int64 net,
                                    int64 pr_mem,
                                    int64 sh_mem) {
  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(keys::kIdKey, process_id);
  result->SetString(keys::kTypeKey, type);
  result->SetDouble(keys::kCpuKey, cpu);
  result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
  result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
  result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
  return result;
}

ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
  return Singleton<ExtensionProcessesEventRouter>::get();
}

ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
  model_ = TaskManager::GetInstance()->model();
  model_->AddObserver(this);
}

ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
  model_->RemoveObserver(this);
}

void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
  profiles_.insert(profile);
}

void ExtensionProcessesEventRouter::ListenerAdded() {
  model_->StartUpdating();
}

void ExtensionProcessesEventRouter::ListenerRemoved() {
  model_->StopUpdating();
}

void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
  if (model_) {
    ListValue args;
    DictionaryValue* processes = new DictionaryValue();
    for (int i = start; i < start + length; i++) {
      if (model_->IsResourceFirstInGroup(i)) {
        int id = model_->GetProcessId(i);

        // Determine process type
        std::string type = keys::kProcessTypeOther;
        TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
        switch (resource_type) {
          case TaskManager::Resource::BROWSER:
            type = keys::kProcessTypeBrowser;
            break;
          case TaskManager::Resource::RENDERER:
            type = keys::kProcessTypeRenderer;
            break;
          case TaskManager::Resource::EXTENSION:
            type = keys::kProcessTypeExtension;
            break;
          case TaskManager::Resource::NOTIFICATION:
            type = keys::kProcessTypeNotification;
            break;
          case TaskManager::Resource::PLUGIN:
            type = keys::kProcessTypePlugin;
            break;
          case TaskManager::Resource::WORKER:
            type = keys::kProcessTypeWorker;
            break;
          case TaskManager::Resource::NACL:
            type = keys::kProcessTypeNacl;
            break;
          case TaskManager::Resource::UTILITY:
            type = keys::kProcessTypeUtility;
            break;
          case TaskManager::Resource::GPU:
            type = keys::kProcessTypeGPU;
            break;
          case TaskManager::Resource::PROFILE_IMPORT:
          case TaskManager::Resource::ZYGOTE:
          case TaskManager::Resource::SANDBOX_HELPER:
          case TaskManager::Resource::UNKNOWN:
            type = keys::kProcessTypeOther;
            break;
          default:
            NOTREACHED() << "Unknown resource type.";
        }

        // Get process metrics as numbers
        double cpu = model_->GetCPUUsage(i);

        // TODO(creis): Network is actually reported per-resource (tab),
        // not per-process.  We should aggregate it here.
        int64 net = model_->GetNetworkUsage(i);
        size_t mem;
        int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;
        int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;

        // Store each process indexed by the string version of its id
        processes->Set(base::IntToString(id),
                       CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
      }
    }
    args.Append(processes);

    std::string json_args;
    base::JSONWriter::Write(&args, &json_args);

    // Notify each profile that is interested.
    for (ProfileSet::iterator it = profiles_.begin();
         it != profiles_.end(); it++) {
      Profile* profile = *it;
      DispatchEvent(profile, keys::kOnUpdated, json_args);
    }
  }
}

void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
    const char* event_name,
    const std::string& json_args) {
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, NULL, GURL());
  }
}

bool GetProcessIdForTabFunction::RunImpl() {
  int tab_id;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));

  TabContentsWrapper* contents = NULL;
  int tab_index = -1;
  if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
                                    NULL, NULL, &contents, &tab_index)) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        extension_tabs_module_constants::kTabNotFoundError,
        base::IntToString(tab_id));
    return false;
  }

  // Return the process ID of the tab as an integer.
  int id = base::GetProcId(contents->web_contents()->
      GetRenderProcessHost()->GetHandle());
  result_.reset(Value::CreateIntegerValue(id));
  return true;
}
<commit_msg>ifdef'd out more references to TaskManager<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/extension_processes_api.h"

#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"

#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"

namespace keys = extension_processes_api_constants;

DictionaryValue* CreateProcessValue(int process_id,
                                    const std::string& type,
                                    double cpu,
                                    int64 net,
                                    int64 pr_mem,
                                    int64 sh_mem) {
  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(keys::kIdKey, process_id);
  result->SetString(keys::kTypeKey, type);
  result->SetDouble(keys::kCpuKey, cpu);
  result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
  result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
  result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
  return result;
}

ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
  return Singleton<ExtensionProcessesEventRouter>::get();
}

ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
  model_ = TaskManager::GetInstance()->model();
  model_->AddObserver(this);
#endif  // defined(ENABLE_TASK_MANAGER)
}

ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
  model_->RemoveObserver(this);
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
  profiles_.insert(profile);
}

void ExtensionProcessesEventRouter::ListenerAdded() {
#if defined(ENABLE_TASK_MANAGER)
  model_->StartUpdating();
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::ListenerRemoved() {
#if defined(ENABLE_TASK_MANAGER)
  model_->StopUpdating();
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
#if defined(ENABLE_TASK_MANAGER)
  if (model_) {
    ListValue args;
    DictionaryValue* processes = new DictionaryValue();
    for (int i = start; i < start + length; i++) {
      if (model_->IsResourceFirstInGroup(i)) {
        int id = model_->GetProcessId(i);

        // Determine process type
        std::string type = keys::kProcessTypeOther;
        TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
        switch (resource_type) {
          case TaskManager::Resource::BROWSER:
            type = keys::kProcessTypeBrowser;
            break;
          case TaskManager::Resource::RENDERER:
            type = keys::kProcessTypeRenderer;
            break;
          case TaskManager::Resource::EXTENSION:
            type = keys::kProcessTypeExtension;
            break;
          case TaskManager::Resource::NOTIFICATION:
            type = keys::kProcessTypeNotification;
            break;
          case TaskManager::Resource::PLUGIN:
            type = keys::kProcessTypePlugin;
            break;
          case TaskManager::Resource::WORKER:
            type = keys::kProcessTypeWorker;
            break;
          case TaskManager::Resource::NACL:
            type = keys::kProcessTypeNacl;
            break;
          case TaskManager::Resource::UTILITY:
            type = keys::kProcessTypeUtility;
            break;
          case TaskManager::Resource::GPU:
            type = keys::kProcessTypeGPU;
            break;
          case TaskManager::Resource::PROFILE_IMPORT:
          case TaskManager::Resource::ZYGOTE:
          case TaskManager::Resource::SANDBOX_HELPER:
          case TaskManager::Resource::UNKNOWN:
            type = keys::kProcessTypeOther;
            break;
          default:
            NOTREACHED() << "Unknown resource type.";
        }

        // Get process metrics as numbers
        double cpu = model_->GetCPUUsage(i);

        // TODO(creis): Network is actually reported per-resource (tab),
        // not per-process.  We should aggregate it here.
        int64 net = model_->GetNetworkUsage(i);
        size_t mem;
        int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;
        int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;

        // Store each process indexed by the string version of its id
        processes->Set(base::IntToString(id),
                       CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
      }
    }
    args.Append(processes);

    std::string json_args;
    base::JSONWriter::Write(&args, &json_args);

    // Notify each profile that is interested.
    for (ProfileSet::iterator it = profiles_.begin();
         it != profiles_.end(); it++) {
      Profile* profile = *it;
      DispatchEvent(profile, keys::kOnUpdated, json_args);
    }
  }
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
    const char* event_name,
    const std::string& json_args) {
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, NULL, GURL());
  }
}

bool GetProcessIdForTabFunction::RunImpl() {
  int tab_id;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));

  TabContentsWrapper* contents = NULL;
  int tab_index = -1;
  if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
                                    NULL, NULL, &contents, &tab_index)) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        extension_tabs_module_constants::kTabNotFoundError,
        base::IntToString(tab_id));
    return false;
  }

  // Return the process ID of the tab as an integer.
  int id = base::GetProcId(contents->web_contents()->
      GetRenderProcessHost()->GetHandle());
  result_.reset(Value::CreateIntegerValue(id));
  return true;
}
<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I2C.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> sensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> values;         //Vector of the values from the sensors
vector<int> active;
Camera& cam;                //Pointer to the camera

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void setCam(bool b);

void init();

int main() {

    while(1) {
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
			cout<<"uhoh"<<endl;
			// Guard.sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    Light x(22);
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors
    MotionSensor s1(0x05,i2c);
    Log log(LOG);
    PressureSensor s2(0x06, i2c, log);

    sensors.push_back(&s1);
    sensors.push_back(&s2);

    lights.push_back(&x);

    active.resize(sensors.sizeof);
    values.resize(sensors.sizeof);
}

/*Sets the camera*/
void setCam(bool b){
    cam.setCamera(b);
}
<commit_msg>added attributes & checkAnomaly function<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I2C.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> sensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> values;         //Vector of the values from the sensors
vector<int> active;
Camera& cam;                //Pointer to the camera

bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void checkAnomaly();

void checkCam();

void init();

int main() {

    while(1) {
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
			cout<<"uhoh"<<endl;
			// Guard.sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    Light x(22);
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors
    MotionSensor s1(0x05,i2c);
    Log log(LOG);
    PressureSensor s2(0x06, i2c, log);

    sensors.push_back(&s1);
    sensors.push_back(&s2);

    lights.push_back(&x);

    active.resize(sensors.sizeof);
    values.resize(sensors.sizeof);
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam.setCamera(true);
    } else if(anamoly) {
        cam.setCamera(true);
    } else {
        cam.setCamera(false);
    }
}

void checkAnomaly(){

    int pressureValue = values[2];

    if(pressureValue > 20 && value < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        sleep = true;
    }

}

<|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 "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
 public:
  DOMAutomationTest() {
    EnableDOMAutomation();
    JavaScriptExecutionController::set_timeout(30000);
  }

  GURL GetTestURL(const char* path) {
    std::string url_path = "files/dom_automation/";
    url_path.append(path);
    return test_server()->GetURL(url_path);
  }
};

typedef DOMElementProxy::By By;

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindByXPath) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
  ASSERT_TRUE(first_div);
  ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
  elements.clear();
  ASSERT_EQ(0u, elements.size());

  // Find with invalid xpath.
  ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
  ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
  ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
  ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::XPath("./span"));
  }
  ASSERT_EQ(3, nested_count);
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_myclass =
      main_doc->FindElement(By::Selectors(".myclass"));
  ASSERT_TRUE(first_myclass);
  ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
  ASSERT_EQ(0u, elements.size());

  // Find with invalid selectors.
  ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
  ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::Selectors("span"));
  }
  ASSERT_EQ(3, nested_count);
}

#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
  ASSERT_TRUE(first_text);
  ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
  ASSERT_EQ(0u, elements.size());

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::Text("span_text"));
  }
  ASSERT_EQ(3, nested_count);

  // Find only visible text.
  DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
  ASSERT_TRUE(shown_td);
  ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));

  // Find text in inputs.
  ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
  ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef div =
      main_doc->WaitFor1VisibleElement(By::Selectors("div"));
  ASSERT_TRUE(div.get());
  ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
  std::vector<DOMElementProxyRef> img_elements;
  ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
  ASSERT_EQ(0u, img_elements.size());
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
  ASSERT_TRUE(anchor.get());
  ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
      "href", "http://www.google.com"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Get both frame elements.
  std::vector<DOMElementProxyRef> frame_elements;
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
  ASSERT_EQ(2u, frame_elements.size());

  // Get both frames, checking their contents are correct.
  DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
  DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
  ASSERT_TRUE(frame1 && frame2);
  DOMElementProxyRef frame_div =
      frame1->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
  frame_div = frame2->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));

  // Get both inner iframes, checking their contents are correct.
  DOMElementProxyRef iframe1 =
      frame1->GetDocumentFromFrame("0");
  DOMElementProxyRef iframe2 =
      frame2->GetDocumentFromFrame("0");
  ASSERT_TRUE(iframe1 && iframe2);
  frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
  frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));

  // Get nested frame.
  ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
  ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Click link and make sure text changes.
  DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
  ASSERT_TRUE(link && link->Click());
  ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));

  // Click input button and make sure textfield changes.
  DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
  DOMElementProxyRef textfield =
      main_doc->FindElement(By::Selectors("#textfield"));
  ASSERT_TRUE(textfield && button && button->Click());
  ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));

  // Type in the textfield.
  ASSERT_TRUE(textfield->SetText("test"));
  ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));

  // Type in the textarea.
  DOMElementProxyRef textarea =
      main_doc->FindElement(By::Selectors("textarea"));
  ASSERT_TRUE(textarea && textarea->Type("test"));
  ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("string_escape/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef textarea =
      main_doc->FindElement(By::Selectors("textarea"));
  ASSERT_TRUE(textarea);
  ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));

  const wchar_t* set_and_expect_strings[] = {
      L"\u00FF and \u00FF",
      L"\n \t \\",
      L"' \""
  };
  for (size_t i = 0; i < 3; i++) {
    ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
    ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
        WideToUTF8(set_and_expect_strings[i])));
  }
}

}  // namespace
<commit_msg>Re-mark DOMAutomationTest.FindByXPath as FLAKY on Windows.<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 "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/test/automation/dom_element_proxy.h"
#include "chrome/test/automation/javascript_execution_controller.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Tests the DOMAutomation framework for manipulating DOMElements within
// browser tests.
class DOMAutomationTest : public InProcessBrowserTest {
 public:
  DOMAutomationTest() {
    EnableDOMAutomation();
    JavaScriptExecutionController::set_timeout(30000);
  }

  GURL GetTestURL(const char* path) {
    std::string url_path = "files/dom_automation/";
    url_path.append(path);
    return test_server()->GetURL(url_path);
  }
};

typedef DOMElementProxy::By By;

#if defined(OS_WIN)
// See http://crbug.com/61636
#define MAYBE_FindByXPath FLAKY_FindByXPath
#else
#define MAYBE_FindByXPath FindByXPath
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByXPath) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_div = main_doc->FindElement(By::XPath("//div"));
  ASSERT_TRUE(first_div);
  ASSERT_NO_FATAL_FAILURE(first_div->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//div"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::XPath("//nosuchtag")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//nosuchtag"), &elements));
  elements.clear();
  ASSERT_EQ(0u, elements.size());

  // Find with invalid xpath.
  ASSERT_FALSE(main_doc->FindElement(By::XPath("'invalid'")));
  ASSERT_FALSE(main_doc->FindElement(By::XPath(" / / ")));
  ASSERT_FALSE(main_doc->FindElements(By::XPath("'invalid'"), &elements));
  ASSERT_FALSE(main_doc->FindElements(By::XPath(" / / "), &elements));

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::XPath("/html/body/span"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::XPath("./span"));
  }
  ASSERT_EQ(3, nested_count);
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, FindBySelectors) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_myclass =
      main_doc->FindElement(By::Selectors(".myclass"));
  ASSERT_TRUE(first_myclass);
  ASSERT_NO_FATAL_FAILURE(first_myclass->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::Selectors(".myclass"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::Selectors("#nosuchid")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::Selectors("#nosuchid"), &elements));
  ASSERT_EQ(0u, elements.size());

  // Find with invalid selectors.
  ASSERT_FALSE(main_doc->FindElement(By::Selectors("1#2")));
  ASSERT_FALSE(main_doc->FindElements(By::Selectors("1#2"), &elements));

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::Selectors("span"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::Selectors("span"));
  }
  ASSERT_EQ(3, nested_count);
}

#if defined(OS_WIN)
// http://crbug.com/72745
#define MAYBE_FindByText FLAKY_FindByText
#else
#define MAYBE_FindByText FindByText
#endif
IN_PROC_BROWSER_TEST_F(DOMAutomationTest, MAYBE_FindByText) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("find_elements/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Find first element.
  DOMElementProxyRef first_text = main_doc->FindElement(By::Text("div_text"));
  ASSERT_TRUE(first_text);
  ASSERT_NO_FATAL_FAILURE(first_text->EnsureNameMatches("0"));

  // Find many elements.
  std::vector<DOMElementProxyRef> elements;
  ASSERT_TRUE(main_doc->FindElements(By::Text("div_text"), &elements));
  ASSERT_EQ(2u, elements.size());
  for (size_t i = 0; i < elements.size(); i++) {
    ASSERT_NO_FATAL_FAILURE(elements[i]->EnsureNameMatches(
        base::UintToString(i)));
  }

  // Find 0 elements.
  ASSERT_FALSE(main_doc->FindElement(By::Text("nosuchtext")));
  elements.clear();
  ASSERT_TRUE(main_doc->FindElements(By::Text("nosuchtext"), &elements));
  ASSERT_EQ(0u, elements.size());

  // Find nested elements.
  int nested_count = 0;
  std::string span_name;
  DOMElementProxyRef node = main_doc->FindElement(By::Text("span_text"));
  while (node) {
    nested_count++;
    span_name.append("span");
    ASSERT_NO_FATAL_FAILURE(node->EnsureNameMatches(span_name));
    node = node->FindElement(By::Text("span_text"));
  }
  ASSERT_EQ(3, nested_count);

  // Find only visible text.
  DOMElementProxyRef shown_td = main_doc->FindElement(By::Text("table_text"));
  ASSERT_TRUE(shown_td);
  ASSERT_NO_FATAL_FAILURE(shown_td->EnsureNameMatches("shown"));

  // Find text in inputs.
  ASSERT_TRUE(main_doc->FindElement(By::Text("textarea_text")));
  ASSERT_TRUE(main_doc->FindElement(By::Text("input_text")));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitFor1VisibleElement) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef div =
      main_doc->WaitFor1VisibleElement(By::Selectors("div"));
  ASSERT_TRUE(div.get());
  ASSERT_NO_FATAL_FAILURE(div->EnsureInnerHTMLMatches("div_inner"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, WaitForElementsToDisappear) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  ASSERT_TRUE(main_doc->WaitForElementsToDisappear(By::Selectors("img")));
  std::vector<DOMElementProxyRef> img_elements;
  ASSERT_TRUE(main_doc->FindElements(By::Selectors("img"), &img_elements));
  ASSERT_EQ(0u, img_elements.size());
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, EnsureAttributeEventuallyMatches) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("wait/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef anchor = main_doc->FindElement(By::Selectors("a"));
  ASSERT_TRUE(anchor.get());
  ASSERT_NO_FATAL_FAILURE(anchor->EnsureAttributeEventuallyMatches(
      "href", "http://www.google.com"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Frames) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("frames/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Get both frame elements.
  std::vector<DOMElementProxyRef> frame_elements;
  ASSERT_TRUE(main_doc->FindElements(By::XPath("//frame"), &frame_elements));
  ASSERT_EQ(2u, frame_elements.size());

  // Get both frames, checking their contents are correct.
  DOMElementProxyRef frame1 = frame_elements[0]->GetContentDocument();
  DOMElementProxyRef frame2 = frame_elements[1]->GetContentDocument();
  ASSERT_TRUE(frame1 && frame2);
  DOMElementProxyRef frame_div =
      frame1->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 1"));
  frame_div = frame2->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("frame 2"));

  // Get both inner iframes, checking their contents are correct.
  DOMElementProxyRef iframe1 =
      frame1->GetDocumentFromFrame("0");
  DOMElementProxyRef iframe2 =
      frame2->GetDocumentFromFrame("0");
  ASSERT_TRUE(iframe1 && iframe2);
  frame_div = iframe1->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 1"));
  frame_div = iframe2->FindElement(By::XPath("/html/body/div"));
  ASSERT_TRUE(frame_div);
  ASSERT_NO_FATAL_FAILURE(frame_div->EnsureInnerHTMLMatches("iframe 2"));

  // Get nested frame.
  ASSERT_EQ(iframe1.get(), main_doc->GetDocumentFromFrame("0", "0").get());
  ASSERT_EQ(iframe2.get(), main_doc->GetDocumentFromFrame("1", "0").get());
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, Events) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(), GetTestURL("events/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  // Click link and make sure text changes.
  DOMElementProxyRef link = main_doc->FindElement(By::Selectors("a"));
  ASSERT_TRUE(link && link->Click());
  ASSERT_NO_FATAL_FAILURE(link->EnsureTextMatches("clicked"));

  // Click input button and make sure textfield changes.
  DOMElementProxyRef button = main_doc->FindElement(By::Selectors("#button"));
  DOMElementProxyRef textfield =
      main_doc->FindElement(By::Selectors("#textfield"));
  ASSERT_TRUE(textfield && button && button->Click());
  ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("clicked"));

  // Type in the textfield.
  ASSERT_TRUE(textfield->SetText("test"));
  ASSERT_NO_FATAL_FAILURE(textfield->EnsureTextMatches("test"));

  // Type in the textarea.
  DOMElementProxyRef textarea =
      main_doc->FindElement(By::Selectors("textarea"));
  ASSERT_TRUE(textarea && textarea->Type("test"));
  ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches("textareatest"));
}

IN_PROC_BROWSER_TEST_F(DOMAutomationTest, StringEscape) {
  ASSERT_TRUE(test_server()->Start());
  ui_test_utils::NavigateToURL(browser(),
                               GetTestURL("string_escape/test.html"));
  DOMElementProxyRef main_doc = ui_test_utils::GetActiveDOMDocument(browser());

  DOMElementProxyRef textarea =
      main_doc->FindElement(By::Selectors("textarea"));
  ASSERT_TRUE(textarea);
  ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(WideToUTF8(L"\u00FF")));

  const wchar_t* set_and_expect_strings[] = {
      L"\u00FF and \u00FF",
      L"\n \t \\",
      L"' \""
  };
  for (size_t i = 0; i < 3; i++) {
    ASSERT_TRUE(textarea->SetText(WideToUTF8(set_and_expect_strings[i])));
    ASSERT_NO_FATAL_FAILURE(textarea->EnsureTextMatches(
        WideToUTF8(set_and_expect_strings[i])));
  }
}

}  // namespace
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

#include "recommender_base.hpp"

using std::make_pair;
using std::pair;
using std::string;
using std::vector;

namespace jubatus {
namespace core {
namespace recommender {

class recommender_impl : public recommender_base {
 public:
  recommender_impl()
      : recommender_base() {
    // make mock
    orig_.set("r1", "a1", 1.0);
    orig_.set("r1", "a2", 1.0);

    orig_.set("r2", "b1", 1.0);
    orig_.set("r2", "b2", 1.0);

    orig_.set("r3", "a1", 1.0);
    orig_.set("r3", "b1", 1.0);
  }

  void similar_row(
      const common::sfv_t& query,
      vector<pair<string, float> >& ids,
      size_t ret_num) const {
    ids.clear();
    ids.push_back(make_pair("r1", 2.0));
    ids.push_back(make_pair("r3", 1.0));
  }

  void neighbor_row(
      const common::sfv_t& query,
      vector<pair<string, float> >& ids,
      size_t ret_num) const {
    ids.clear();
    ids.push_back(make_pair("r1", 1.0));
    ids.push_back(make_pair("r3", 2.0));
  }

  void clear() {
  }

  void clear_row(const string& id) {
  }

  void update_row(const string& id, const sfv_diff_t& diff) {
  }

  void get_all_row_ids(vector<string>& ids) const {
    ids.clear();
    ids.push_back("r1");
    ids.push_back("r2");
    ids.push_back("r3");
  }

  string type() const {
    return string("recommender_impl");
  }

  framework::mixable* get_mixable() const {}

  void pack(framework::packer&) const {
  }
  void unpack(msgpack::object) {
  }
};

TEST(recommender_base, complete_row) {
  recommender_impl r;
  common::sfv_t q;
  common::sfv_t ret;
  r.complete_row(q, ret);
  ASSERT_EQ(3u, ret.size());
  EXPECT_EQ("a1", ret[0].first);
  EXPECT_EQ("a2", ret[1].first);
  EXPECT_EQ("b1", ret[2].first);
}

TEST(recommender_base, get_all_row_ids) {
  vector<string> ids;
  recommender_impl r;
  r.get_all_row_ids(ids);
  ASSERT_EQ(3u, ids.size());
  sort(ids.begin(), ids.end());
  EXPECT_EQ("r1", ids[0]);
  EXPECT_EQ("r2", ids[1]);
  EXPECT_EQ("r3", ids[2]);
}

TEST(recommender_base, decode_row) {
  recommender_impl r;
  common::sfv_t v;
  r.decode_row("r1", v);
  ASSERT_EQ(2u, v.size());
  EXPECT_EQ("a1", v[0].first);
  EXPECT_EQ(1.0, v[0].second);
  EXPECT_EQ("a2", v[1].first);
  EXPECT_EQ(1.0, v[1].second);

  r.decode_row("r", v);
  ASSERT_TRUE(v.empty());
}

TEST(recommender_base, calc_l2norm) {
  recommender_impl r;
  common::sfv_t q;
  q.push_back(make_pair("a1", 1.0));
  q.push_back(make_pair("a2", 2.0));
  q.push_back(make_pair("a3", 3.0));

  EXPECT_FLOAT_EQ(std::sqrt(1.0 + 4.0 + 9.0), r.calc_l2norm(q));
}

TEST(recommender_base, calc_similality) {
  recommender_impl r;
  common::sfv_t q1;
  common::sfv_t q2;

  q1.push_back(make_pair("c1", 1.0));
  q1.push_back(make_pair("c2", 2.0));
  q1.push_back(make_pair("c3", 3.0));

  q2.push_back(make_pair("c4", 2.0));
  q2.push_back(make_pair("c3", 3.0));
  q2.push_back(make_pair("c2", 3.0));

  EXPECT_FLOAT_EQ(
      (2.0 * 3.0 + 3.0 * 3.0) / r.calc_l2norm(q1) / r.calc_l2norm(q2),
      r.calc_similality(q1, q2));
}

}  // namespace recommender
}  // namespace core
}  // namespace jubatus
<commit_msg>Fix recommender_base_test for libc++.<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

#include "recommender_base.hpp"

using std::make_pair;
using std::pair;
using std::string;
using std::vector;

namespace jubatus {
namespace core {
namespace recommender {

class recommender_impl : public recommender_base {
 public:
  recommender_impl()
      : recommender_base() {
    // make mock
    orig_.set("r1", "a1", 1.0);
    orig_.set("r1", "a2", 1.0);

    orig_.set("r2", "b1", 1.0);
    orig_.set("r2", "b2", 1.0);

    orig_.set("r3", "a1", 1.0);
    orig_.set("r3", "b1", 1.0);
  }

  void similar_row(
      const common::sfv_t& query,
      vector<pair<string, float> >& ids,
      size_t ret_num) const {
    ids.clear();
    ids.push_back(make_pair("r1", 2.0));
    ids.push_back(make_pair("r3", 1.0));
  }

  void neighbor_row(
      const common::sfv_t& query,
      vector<pair<string, float> >& ids,
      size_t ret_num) const {
    ids.clear();
    ids.push_back(make_pair("r1", 1.0));
    ids.push_back(make_pair("r3", 2.0));
  }

  void clear() {
  }

  void clear_row(const string& id) {
  }

  void update_row(const string& id, const sfv_diff_t& diff) {
  }

  void get_all_row_ids(vector<string>& ids) const {
    ids.clear();
    ids.push_back("r1");
    ids.push_back("r2");
    ids.push_back("r3");
  }

  string type() const {
    return string("recommender_impl");
  }

  framework::mixable* get_mixable() const {}

  void pack(framework::packer&) const {
  }
  void unpack(msgpack::object) {
  }
};

TEST(recommender_base, complete_row) {
  recommender_impl r;
  common::sfv_t q;
  common::sfv_t ret;
  r.complete_row(q, ret);
  ASSERT_EQ(3u, ret.size());
  EXPECT_EQ("a1", ret[0].first);
  EXPECT_EQ("a2", ret[1].first);
  EXPECT_EQ("b1", ret[2].first);
}

TEST(recommender_base, get_all_row_ids) {
  vector<string> ids;
  recommender_impl r;
  r.get_all_row_ids(ids);
  ASSERT_EQ(3u, ids.size());
  sort(ids.begin(), ids.end());
  EXPECT_EQ("r1", ids[0]);
  EXPECT_EQ("r2", ids[1]);
  EXPECT_EQ("r3", ids[2]);
}

TEST(recommender_base, decode_row) {
  recommender_impl r;
  common::sfv_t v;
  r.decode_row("r1", v);
  ASSERT_EQ(2u, v.size());
  std::sort(v.begin(), v.end());
  EXPECT_EQ("a1", v[0].first);
  EXPECT_EQ(1.0, v[0].second);
  EXPECT_EQ("a2", v[1].first);
  EXPECT_EQ(1.0, v[1].second);

  r.decode_row("r", v);
  ASSERT_TRUE(v.empty());
}

TEST(recommender_base, calc_l2norm) {
  recommender_impl r;
  common::sfv_t q;
  q.push_back(make_pair("a1", 1.0));
  q.push_back(make_pair("a2", 2.0));
  q.push_back(make_pair("a3", 3.0));

  EXPECT_FLOAT_EQ(std::sqrt(1.0 + 4.0 + 9.0), r.calc_l2norm(q));
}

TEST(recommender_base, calc_similality) {
  recommender_impl r;
  common::sfv_t q1;
  common::sfv_t q2;

  q1.push_back(make_pair("c1", 1.0));
  q1.push_back(make_pair("c2", 2.0));
  q1.push_back(make_pair("c3", 3.0));

  q2.push_back(make_pair("c4", 2.0));
  q2.push_back(make_pair("c3", 3.0));
  q2.push_back(make_pair("c2", 3.0));

  EXPECT_FLOAT_EQ(
      (2.0 * 3.0 + 3.0 * 3.0) / r.calc_l2norm(q1) / r.calc_l2norm(q2),
      r.calc_similality(q1, q2));
}

}  // namespace recommender
}  // namespace core
}  // namespace jubatus
<|endoftext|>


<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_queued_disk_bytes", &session_settings::max_queued_disk_bytes)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("announce_to_all_tiers", &session_settings::announce_to_all_tiers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
        .def_readwrite("optimistic_disk_retry", &session_settings::optimistic_disk_retry)
        .def_readwrite("disable_hash_checks", &session_settings::disable_hash_checks)
        .def_readwrite("allow_reordered_disk_operations", &session_settings::allow_reordered_disk_operations)
        .def_readwrite("allow_i2p_mixed", &session_settings::allow_i2p_mixed)
        .def_readwrite("max_suggest_pieces", &session_settings::max_suggest_pieces)
        .def_readwrite("drop_skipped_requests", &session_settings::drop_skipped_requests)
        .def_readwrite("low_prio_disk", &session_settings::low_prio_disk)
        .def_readwrite("local_service_announce_interval", &session_settings::local_service_announce_interval)
        .def_readwrite("udp_tracker_token_expiry", &session_settings::udp_tracker_token_expiry)
        .def_readwrite("volatile_read_cache", &session_settings::volatile_read_cache)
        .def_readwrite("guided_read_cache", &guided_read_cache)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
        .value("lru", session_settings::lru)
        .value("largest_contiguous", session_settings::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
        .def_readwrite("search_branching", &dht_settings::search_branching)
        .def_readwrite("service_port", &dht_settings::service_port)
        .def_readwrite("max_fail_count", &dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>fixed python binding<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("stop_tracker_timeout", &session_settings::stop_tracker_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_timeout", &session_settings::request_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("urlseed_wait_retry", &session_settings::urlseed_wait_retry)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("optimistic_unchoke_interval", &session_settings::optimistic_unchoke_interval)
        .def_readwrite("num_want", &session_settings::num_want)
        .def_readwrite("initial_picker_threshold", &session_settings::initial_picker_threshold)
        .def_readwrite("allowed_fast_set_size", &session_settings::allowed_fast_set_size)
        .def_readwrite("max_queued_disk_bytes", &session_settings::max_queued_disk_bytes)
        .def_readwrite("handshake_timeout", &session_settings::handshake_timeout)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
        .def_readwrite("free_torrent_hashes", &session_settings::free_torrent_hashes)
        .def_readwrite("upnp_ignore_nonrouters", &session_settings::upnp_ignore_nonrouters)
        .def_readwrite("send_buffer_watermark", &session_settings::send_buffer_watermark)
        .def_readwrite("auto_upload_slots", &session_settings::auto_upload_slots)
        .def_readwrite("auto_upload_slots_rate_based", &session_settings::auto_upload_slots_rate_based)
        .def_readwrite("use_parole_mode", &session_settings::use_parole_mode)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_buffer_chunk_size", &session_settings::cache_buffer_chunk_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
        .def_readwrite("use_read_cache", &session_settings::use_read_cache)
        .def_readwrite("disk_io_write_mode", &session_settings::disk_io_write_mode)
        .def_readwrite("disk_io_read_mode", &session_settings::disk_io_read_mode)
        .def_readwrite("coalesce_reads", &session_settings::coalesce_reads)
        .def_readwrite("coalesce_writes", &session_settings::coalesce_writes)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("peer_turnover", &session_settings::peer_turnover)
        .def_readwrite("peer_turnover_cutoff", &session_settings::peer_turnover_cutoff)
        .def_readwrite("close_redundant_connections", &session_settings::close_redundant_connections)
        .def_readwrite("auto_scrape_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("auto_scrape_min_interval", &session_settings::auto_scrape_min_interval)
        .def_readwrite("max_peerlist_size", &session_settings::max_peerlist_size)
        .def_readwrite("max_paused_peerlist_size", &session_settings::max_paused_peerlist_size)
        .def_readwrite("min_announce_interval", &session_settings::min_announce_interval)
        .def_readwrite("prioritize_partial_pieces", &session_settings::prioritize_partial_pieces)
        .def_readwrite("auto_manage_startup", &session_settings::auto_manage_startup)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("announce_to_all_trackers", &session_settings::announce_to_all_trackers)
        .def_readwrite("announce_to_all_tiers", &session_settings::announce_to_all_tiers)
        .def_readwrite("prefer_udp_trackers", &session_settings::prefer_udp_trackers)
        .def_readwrite("strict_super_seeding", &session_settings::strict_super_seeding)
        .def_readwrite("seeding_piece_quota", &session_settings::seeding_piece_quota)
        .def_readwrite("max_sparse_regions", &session_settings::max_sparse_regions)
#ifndef TORRENT_DISABLE_MLOCK
        .def_readwrite("lock_disk_cache", &session_settings::lock_disk_cache)
#endif
        .def_readwrite("max_rejects", &session_settings::max_rejects)
        .def_readwrite("recv_socket_buffer_size", &session_settings::recv_socket_buffer_size)
        .def_readwrite("send_socket_buffer_size", &session_settings::send_socket_buffer_size)
        .def_readwrite("optimize_hashing_for_speed", &session_settings::optimize_hashing_for_speed)
        .def_readwrite("file_checks_delay_per_block", &session_settings::file_checks_delay_per_block)
        .def_readwrite("disk_cache_algorithm", &session_settings::disk_cache_algorithm)
        .def_readwrite("read_cache_line_size", &session_settings::read_cache_line_size)
        .def_readwrite("write_cache_line_size", &session_settings::write_cache_line_size)
        .def_readwrite("optimistic_disk_retry", &session_settings::optimistic_disk_retry)
        .def_readwrite("disable_hash_checks", &session_settings::disable_hash_checks)
        .def_readwrite("allow_reordered_disk_operations", &session_settings::allow_reordered_disk_operations)
        .def_readwrite("allow_i2p_mixed", &session_settings::allow_i2p_mixed)
        .def_readwrite("max_suggest_pieces", &session_settings::max_suggest_pieces)
        .def_readwrite("drop_skipped_requests", &session_settings::drop_skipped_requests)
        .def_readwrite("low_prio_disk", &session_settings::low_prio_disk)
        .def_readwrite("local_service_announce_interval", &session_settings::local_service_announce_interval)
        .def_readwrite("udp_tracker_token_expiry", &session_settings::udp_tracker_token_expiry)
        .def_readwrite("volatile_read_cache", &session_settings::volatile_read_cache)
        .def_readwrite("guided_read_cache", &session_settings::guided_read_cache)
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;

    enum_<session_settings::disk_cache_algo_t>("disk_cache_algo_t")
        .value("lru", session_settings::lru)
        .value("largest_contiguous", session_settings::largest_contiguous)
    ;

    enum_<session_settings::io_buffer_mode_t>("io_buffer_mode_t")
        .value("enable_os_cache", session_settings::enable_os_cache)
        .value("disable_os_cache_for_aligned_files", session_settings::disable_os_cache_for_aligned_files)
        .value("disable_os_cache", session_settings::disable_os_cache)
    ;

    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_DHT
    class_<dht_settings>("dht_settings")
        .def_readwrite("max_peers_reply", &dht_settings::max_peers_reply)
        .def_readwrite("search_branching", &dht_settings::search_branching)
        .def_readwrite("service_port", &dht_settings::service_port)
        .def_readwrite("max_fail_count", &dht_settings::max_fail_count)
    ;
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIOpenGLGeometryBuffer.cpp
    created:    Wed, 8th Feb 2012
    author:     Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 <GL/glew.h>

#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :
    OpenGLGeometryBufferBase(owner),
    d_shader(owner.getShaderStandard()),
    d_shaderPosLoc(owner.getShaderStandardPositionLoc()),
    d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),
    d_shaderColourLoc(owner.getShaderStandardColourLoc()),
    d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),
    d_glStateChanger(owner.getOpenGLStateChanger()),
    d_bufferSize(0)
{
    initialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
    deinitialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
    CEGUI::Rectf viewPort = d_owner->getActiveViewPort();

    d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
              static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
              static_cast<GLint>(d_clipRect.getWidth()),
              static_cast<GLint>(d_clipRect.getHeight()));

    // apply the transformations we need to use.
    if (!d_matrixValid)
        updateMatrix();

    // Send ModelViewProjection matrix to shader
    glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
    glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));

    // activate desired blending mode
    d_owner->setupRenderingBlendMode(d_blendMode);

    // Bind our vao
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
     size_t pos = 0;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches

        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            const BatchInfo& currentBatch = *i;

            if (currentBatch.clip)
                glEnable(GL_SCISSOR_TEST);
            else
                glDisable(GL_SCISSOR_TEST);

            glBindTexture(GL_TEXTURE_2D, currentBatch.texture);

            // draw the geometry
            const unsigned int numVertices = currentBatch.vertexCount;
            glDrawArrays(GL_TRIANGLES, pos, numVertices);

            pos += numVertices;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,
    uint vertex_count)
{
    OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
    OpenGLGeometryBufferBase::reset();
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
    glGenVertexArrays(1, &d_verticesVAO);
    glBindVertexArray(d_verticesVAO);

    // Generate and bind position vbo
    glGenBuffers(1, &d_verticesVBO);
    glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);

    d_shader->bind();

    GLsizei stride = 9 * sizeof(GL_FLOAT);

    glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(d_shaderTexCoordLoc);

    glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(d_shaderColourLoc);

    glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(d_shaderPosLoc);

    d_shader->unbind();

    // Unbind Vertex Attribute Array (VAO)
    glBindVertexArray(0);

    // Unbind array and element array buffers
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
    glDeleteVertexArrays(1, &d_verticesVAO);
    glDeleteBuffers(1, &d_verticesVBO);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
    bool needNewBuffer = false;
    unsigned int vertexCount = d_vertices.size();

    if(d_bufferSize < vertexCount)
    {
        needNewBuffer = true;
        d_bufferSize = vertexCount;
    }

    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    GLsizei dataSize = d_bufferSize * sizeof(GLVertex);

    if(needNewBuffer)
    {
        glBufferData(GL_ARRAY_BUFFER, dataSize, d_vertices.data(), GL_DYNAMIC_DRAW);
    }
    else
    {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, d_vertices.data());
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>FIX: Don't use std::vector::data since it only exists for C++11<commit_after>/***********************************************************************
    filename:   CEGUIOpenGLGeometryBuffer.cpp
    created:    Wed, 8th Feb 2012
    author:     Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 <GL/glew.h>

#include "glm/glm.hpp"
#include "glm/gtc/quaternion.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/RendererModules/OpenGL/Texture.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) :
    OpenGLGeometryBufferBase(owner),
    d_shader(owner.getShaderStandard()),
    d_shaderPosLoc(owner.getShaderStandardPositionLoc()),
    d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()),
    d_shaderColourLoc(owner.getShaderStandardColourLoc()),
    d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()),
    d_glStateChanger(owner.getOpenGLStateChanger()),
    d_bufferSize(0)
{
    initialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
    deinitialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
    CEGUI::Rectf viewPort = d_owner->getActiveViewPort();

    d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
              static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
              static_cast<GLint>(d_clipRect.getWidth()),
              static_cast<GLint>(d_clipRect.getHeight()));

    // apply the transformations we need to use.
    if (!d_matrixValid)
        updateMatrix();

    // Send ModelViewProjection matrix to shader
    glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
    glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix));

    // activate desired blending mode
    d_owner->setupRenderingBlendMode(d_blendMode);

    // Bind our vao
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
     size_t pos = 0;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches

        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            const BatchInfo& currentBatch = *i;

            if (currentBatch.clip)
                glEnable(GL_SCISSOR_TEST);
            else
                glDisable(GL_SCISSOR_TEST);

            glBindTexture(GL_TEXTURE_2D, currentBatch.texture);

            // draw the geometry
            const unsigned int numVertices = currentBatch.vertexCount;
            glDrawArrays(GL_TRIANGLES, pos, numVertices);

            pos += numVertices;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff,
    uint vertex_count)
{
    OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count);
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
    OpenGLGeometryBufferBase::reset();
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseOpenGLBuffers()
{
    glGenVertexArrays(1, &d_verticesVAO);
    glBindVertexArray(d_verticesVAO);

    // Generate and bind position vbo
    glGenBuffers(1, &d_verticesVBO);
    glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);

    d_shader->bind();

    GLsizei stride = 9 * sizeof(GL_FLOAT);

    glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0);
    glEnableVertexAttribArray(d_shaderTexCoordLoc);

    glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(d_shaderColourLoc);

    glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT)));
    glEnableVertexAttribArray(d_shaderPosLoc);

    d_shader->unbind();

    // Unbind Vertex Attribute Array (VAO)
    glBindVertexArray(0);

    // Unbind array and element array buffers
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
    glDeleteVertexArrays(1, &d_verticesVAO);
    glDeleteBuffers(1, &d_verticesVBO);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
    bool needNewBuffer = false;
    unsigned int vertexCount = d_vertices.size();

    if(d_bufferSize < vertexCount)
    {
        needNewBuffer = true;
        d_bufferSize = vertexCount;
    }

    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    GLsizei dataSize = d_bufferSize * sizeof(GLVertex);

    if(needNewBuffer)
    {
        glBufferData(GL_ARRAY_BUFFER, dataSize, &d_vertices.front(), GL_DYNAMIC_DRAW);
    }
    else
    {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, &d_vertices.front());
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<|endoftext|>