<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>

namespace arangodb { namespace fuerte { namespace js {

///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
  if (info.IsConstructCall()) {
      NConnectionBuilder* obj = new NConnectionBuilder();
      obj->Wrap(info.This());
      info.GetReturnValue().Set(info.This());
  } else {
    v8::Local<v8::Function> builder = Nan::New(constructor());
    info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
 }
}

NAN_METHOD(NConnectionBuilder::connect){
  v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
  const int argc = 1;
  v8::Local<v8::Value> argv[argc] = {info.This()};
  auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
  info.GetReturnValue().Set(connInstance);
}

NAN_METHOD(NConnectionBuilder::host){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::async){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
  info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::user){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(NConnectionBuilder::password){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}

///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
  if (info.IsConstructCall()) {
    NConnection* obj = new NConnection();
    if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
      obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
    }
    obj->Wrap(info.This());
    info.GetReturnValue().Set(info.This());
  } else {
    v8::Local<v8::Function> cons = Nan::New(constructor());
    info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
 }
}

NAN_METHOD(NConnection::sendRequest) {
  if (info.Length() != 3 ) {
    Nan::ThrowTypeError("Not 3 Arguments");
  }

  // get isolate - has node only one context??!?!? how do they work
  // context is probably a lighter version of isolate but does not allow threads
  v8::Isolate* iso = v8::Isolate::GetCurrent();

  auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
  v8::Persistent<v8::Function> persOnErr;
  persOnErr.Reset(iso, jsOnErr);

  auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
  v8::Persistent<v8::Function> persOnSucc;
  persOnSucc.Reset(iso, jsOnSucc);

  fu::OnErrorCallback err = [iso,&persOnErr](unsigned err
                              ,std::unique_ptr<fu::Request> creq
                              ,std::unique_ptr<fu::Response> cres)
  {
    v8::HandleScope scope(iso);
    v8::Local<v8::Function> jsOnErr = v8::Local<v8::Function>::New(iso,persOnErr);

    // wrap request
    v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor());
    auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked();
    unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));

    // wrap response
    v8::Local<v8::Function> responseProto = Nan::New(NConnection::constructor());
    auto resObj = Nan::NewInstance(requestProto).ToLocalChecked();
    unwrap<NResponse>(resObj)->setCppClass(std::move(cres));

    // build args
    const unsigned argc = 3;
    v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };

    // call and dispose
    jsOnErr->Call(v8::Null(iso), argc, argv);
    persOnErr.Reset(); // dispose of persistent
  };

  fu::OnSuccessCallback succ = [iso,&persOnSucc](std::unique_ptr<fu::Request> creq
                                 ,std::unique_ptr<fu::Response> cres)
  {
    v8::HandleScope scope(iso);

    std::cout << std::endl << "req/res " << creq.get() << "/" << cres.get() << std::endl;
    // wrap request
    //v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
    v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    //auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
    auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
    unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));

    // wrap response
    v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
    unwrap<NResponse>(resObj)->setCppClass(std::move(cres));

    // build args
    const unsigned argc = 2;
    v8::Local<v8::Value> argv[argc] = { reqObj, resObj };

    // call and dispose
    std::cout << std::endl << "running js callback success, with iso: " << iso << std::endl;
    v8::Local<v8::Function> jsOnSucc = v8::Local<v8::Function>::New(iso,persOnSucc);
    //jsOnSucc->Call(v8::Null(iso), argc, argv);
    jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);
    persOnSucc.Reset(); // dispose of persistent
    //persOnSucc.Reset(iso,v8::Local<v8::Function>()); // dispose of persistent

  };

  //finally invoke the c++ callback
  auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
  unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
}

}}}
<commit_msg>successfully send first request via JavaScript<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <atomic>

namespace arangodb { namespace fuerte { namespace js {

///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
  if (info.IsConstructCall()) {
      NConnectionBuilder* obj = new NConnectionBuilder();
      obj->Wrap(info.This());
      info.GetReturnValue().Set(info.This());
  } else {
    v8::Local<v8::Function> builder = Nan::New(constructor());
    info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
 }
}

NAN_METHOD(NConnectionBuilder::connect){
  v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
  const int argc = 1;
  v8::Local<v8::Value> argv[argc] = {info.This()};
  auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
  info.GetReturnValue().Set(connInstance);
}

NAN_METHOD(NConnectionBuilder::host){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::async){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
  info.GetReturnValue().Set(info.This());
}
NAN_METHOD(NConnectionBuilder::user){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(NConnectionBuilder::password){
  if (info.Length() != 1 ) {
    Nan::ThrowTypeError("Wrong number of Arguments");
  }
  unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
  info.GetReturnValue().Set(info.This());
}

///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
  if (info.IsConstructCall()) {
    NConnection* obj = new NConnection();
    if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
      obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
    }
    obj->Wrap(info.This());
    info.GetReturnValue().Set(info.This());
  } else {
    v8::Local<v8::Function> cons = Nan::New(constructor());
    info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
 }
}

///////////////////////////////////////////////////////////////////////////////
// SendRequest ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

// When we switch to c++14 we should use UniquePersistent and move it into
// the generalized lambda caputre avoiding the locking alltogehter
static std::map<fu::MessageID
               ,std::pair<v8::Persistent<v8::Function> // error
                         ,v8::Persistent<v8::Function> // success
                         >
              > callbackMap;

static std::mutex maplock;
static std::atomic<uint64_t> jsMessageID(0);

NAN_METHOD(NConnection::sendRequest) {
  if (info.Length() != 3 ) {
    Nan::ThrowTypeError("Not 3 Arguments");
  }

  if (!info[1]->IsFunction() || !info[2]->IsFunction()){
    Nan::ThrowTypeError("Callback is not a Function");
  }

  // get isolate - has node only one context??!?!? how do they work
  // context is probably a lighter version of isolate but does not allow threads
  v8::Isolate* iso = v8::Isolate::GetCurrent();

  uint64_t id =0;
  {
    std::lock_guard<std::mutex> lock(maplock);
    auto& callbackPair = callbackMap[++id]; //create map element
    auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
    callbackPair.first.Reset(iso, jsOnErr);

    auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
    callbackPair.second.Reset(iso, jsOnSucc);
  }

  fu::OnErrorCallback err = [iso,id](unsigned err
                              ,std::unique_ptr<fu::Request> creq
                              ,std::unique_ptr<fu::Response> cres)
  {
    v8::HandleScope scope(iso);

    auto jsOnErr = v8::Local<v8::Function>();
    { //create local function and dispose persistent
      std::lock_guard<std::mutex> lock(maplock);
      auto& mapElement = callbackMap[id];
      jsOnErr = v8::Local<v8::Function>::New(iso,mapElement.first);
      mapElement.first.Reset();
      mapElement.second.Reset();
      callbackMap.erase(id);
    }

    // wrap request
    v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
    unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));

    // wrap response
    v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
    unwrap<NResponse>(resObj)->setCppClass(std::move(cres));

    // build args
    const unsigned argc = 3;
    v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };

    // call
    jsOnErr->Call(iso->GetCurrentContext(), jsOnErr, argc, argv);

  };

  fu::OnSuccessCallback succ = [iso,id](std::unique_ptr<fu::Request> creq
                                 ,std::unique_ptr<fu::Response> cres)
  {
    v8::HandleScope scope(iso);

    auto jsOnSucc = v8::Local<v8::Function>();
    { // create locacl function and dispose persistent
      std::lock_guard<std::mutex> lock(maplock);
      auto& mapElement = callbackMap[id];
      //create local function
      jsOnSucc = v8::Local<v8::Function>::New(iso,callbackMap[id].second);

      //dispose map element
      mapElement.first.Reset(); // do not depend on kResetInDestructorFlag of Persistent
      mapElement.second.Reset();
      callbackMap.erase(id);
    }

    // wrap request
    //v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
    v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    //auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
    auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
    unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));

    // wrap response
    v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NConnection::constructor());
    auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
    unwrap<NResponse>(resObj)->setCppClass(std::move(cres));

    // build args
    const unsigned argc = 2;
    v8::Local<v8::Value> argv[argc] = { reqObj, resObj };

    // call
    //jsOnSucc->Call(v8::Null(iso), argc, argv);
    jsOnSucc->Call(iso->GetCurrentContext(), jsOnSucc, argc, argv);
    //jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);

  };

  //finally invoke the c++ callback
  auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
  unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
}

}}}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "test_string_aogo.h"

void test_case_conv()
{
    std::string sText = "123WSxx";
    std::string sT2 = boost::to_lower_copy(sText);
    assert(sText == "123WSxx");
    assert(sT2 == "123wsxx");
    boost::to_lower(sText);
    assert(sText == "123wsxx");
    boost::to_upper(sText);
    assert(sText == "123WSXX");
}

struct string_pred
{
    bool operator()(char p)
    {
        if (p>'0'&&p<'9' || p>'a'&&p<'z')
        {
            return true;
        }
        return false;
    }
};
struct string_pred2
{
    bool operator()(char p)
    {
        if (p>'0'&&p<'9')
        {
            return true;
        }
        return false;
    }
};

void test_predicates()
{
    std::string sText = "123WSxx";
    assert(boost::starts_with(sText, "123"));
    assert(boost::istarts_with(sText, "123wsXX"));
    assert(boost::ends_with(sText, "123") == false);
    assert(boost::contains(sText, "x"));
    std::string sText2 = "123sss";
    assert(boost::all(sText2, string_pred()));
    assert(boost::all(sText2, string_pred2()) == false);
}

void test_classification()
{
    std::string sText = "123a";
    std::string sText2 = "123";
    std::string sText3 = "ass";
    assert(all(sText, boost::is_digit()) == false);
    assert(all(sText2, boost::is_digit()));
    assert(all(sText3, boost::is_lower()));
}

void test_trim()
{
    string str1 = "     hello world!     ";
    string str2 = boost::trim_left_copy(str1);
    assert(str2 == "hello world!     ");
    string str3 = boost::trim_right_copy(str1);
    assert(str3 == "     hello world!");
    boost::trim(str1);
    assert(str1 == "hello world!");

    string phone = "00423333444";
    boost::trim_if(phone, boost::is_any_of("04"));
    assert(phone == "23333");
}

void test_find()
{
    char text[] = "hello dolly!";
    boost::iterator_range<char*> result = boost::find_last(text, "ll");
    std::transform( result.begin(), result.end(), result.begin(), std::bind2nd(std::plus<char>(), 1));
    assert(boost::equal(text, "hello dommy!"));
    boost::to_upper(result);
    assert(boost::equal(text, "hello doMMy!"));
    boost::iterator_range<char*> result2 = boost::find_first(text, "doMMy");
    assert(result2.size() == 5);
}

void test_replace()
{

}

void test_find_iterator()
{

}

void test_split()
{

}

void test_string_aogo()
{
    test_case_conv();
    test_predicates();
    test_classification();
    test_trim();
    test_find();
    test_replace();
    test_find_iterator();
    test_split();
}

<commit_msg>* boost.str_aogo.split<commit_after>#include "stdafx.h"
#include "test_string_aogo.h"

void test_case_conv()
{
    std::string sText = "123WSxx";
    std::string sT2 = boost::to_lower_copy(sText);
    assert(sText == "123WSxx");
    assert(sT2 == "123wsxx");
    boost::to_lower(sText);
    assert(sText == "123wsxx");
    boost::to_upper(sText);
    assert(sText == "123WSXX");
}

struct string_pred
{
    bool operator()(char p)
    {
        if (p>'0'&&p<'9' || p>'a'&&p<'z')
        {
            return true;
        }
        return false;
    }
};
struct string_pred2
{
    bool operator()(char p)
    {
        if (p>'0'&&p<'9')
        {
            return true;
        }
        return false;
    }
};

void test_predicates()
{
    std::string sText = "123WSxx";
    assert(boost::starts_with(sText, "123"));
    assert(boost::istarts_with(sText, "123wsXX"));
    assert(boost::ends_with(sText, "123") == false);
    assert(boost::contains(sText, "x"));
    std::string sText2 = "123sss";
    assert(boost::all(sText2, string_pred()));
    assert(boost::all(sText2, string_pred2()) == false);
}

void test_classification()
{
    std::string sText = "123a";
    std::string sText2 = "123";
    std::string sText3 = "ass";
    assert(all(sText, boost::is_digit()) == false);
    assert(all(sText2, boost::is_digit()));
    assert(all(sText3, boost::is_lower()));
}

void test_trim()
{
    string str1 = "     hello world!     ";
    string str2 = boost::trim_left_copy(str1);
    assert(str2 == "hello world!     ");
    string str3 = boost::trim_right_copy(str1);
    assert(str3 == "     hello world!");
    boost::trim(str1);
    assert(str1 == "hello world!");

    string phone = "00423333444";
    boost::trim_if(phone, boost::is_any_of("04"));
    assert(phone == "23333");
}

void test_find()
{
    char text[] = "hello dolly!";
    boost::iterator_range<char*> result = boost::find_last(text, "ll");
    std::transform( result.begin(), result.end(), result.begin(), std::bind2nd(std::plus<char>(), 1));
    assert(boost::equal(text, "hello dommy!"));
    boost::to_upper(result);
    assert(boost::equal(text, "hello doMMy!"));
    boost::iterator_range<char*> result2 = boost::find_first(text, "doMMy");
    assert(result2.size() == 5);
}

void test_replace()
{

}

void test_find_iterator()
{

}

void test_split()
{
    string str1("hello abc-*-ABC-*-aBc goodbye");
    std::vector<string> SplitVec;
    boost::split(SplitVec, str1, boost::is_any_of("-*"), boost::token_compress_on);
    // SplitVec == { "hello abc","ABC","aBc goodbye" }
    for each (auto var in SplitVec)
    {
        cout<<var<<endl;
    }
}

void test_string_aogo()
{
    test_case_conv();
    test_predicates();
    test_classification();
    test_trim();
    test_find();
    test_replace();
    test_find_iterator();
    test_split();
}

<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright © 2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * css::rule_set
 * In memory representation of CSS.
 */

#ifndef SKUI_CSS_RULE_SET_H
#define SKUI_CSS_RULE_SET_H

#include <css/property.h++>
#include "css/declaration_block.h++"

#include <core/string.h++>

#include <any>
#include <unordered_map>

namespace skui::css
{
  using rule_set = std::unordered_map<core::string, std::unordered_map<property, std::any>>;
}

#endif
<commit_msg>Adapt rule_set to better reflect intent of the class.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * css::rule_set
 * In memory representation of CSS.
 */

#ifndef SKUI_CSS_RULE_SET_H
#define SKUI_CSS_RULE_SET_H

#include "css/declaration_block.h++"
#include "css/selector.h++"

#include <core/string.h++>

#include <utility>
#include <vector>

namespace skui::css
{
  class rule_set
  {
    std::vector<std::pair<selector, declaration_block>> declaration_blocks;
  };
}

#endif
<|endoftext|>


<commit_before>#include <r2d2.hpp>

#include <sstream>
#include <boost/format.hpp>
#include <iostream>
#include <iomanip>

Message::Message(bool isDirect, bool requiresResponse) {
    this->isDirect_ = isDirect;
    this->requiresResponse_ = requiresResponse;
}

bool Message::requiresResponse() const {
    return this->requiresResponse_;
}

bool Message::isDirect() const {
    return this->isDirect_;
}

void Message::add_u8(uint8_t v) {
    this->sstream_ << v;
}

void Message::add_s8(int8_t v) {
    this->sstream_ << v;
}

void Message::add_string(size_t n_bytes, const std::string& v) {
    this->sstream_ << std::setfill(static_cast<char>(0x00)) << std::left << std::setw(n_bytes) << v;
}

std::string Message::get_value() {
    return this->sstream_.str();
}

Motor::Motor(NXT *nxt, uint8_t port) {
    this->nxt_ = nxt;
    this->port_ = port;
}

void Motor::setForward(uint8_t power) {
    Message msg(true, false);
    msg.add_u8(Message::START_MOTOR);
    msg.add_u8(this->port_);
    msg.add_s8(power);

    msg.add_u8(0x01 | 0x04); // UNKNOWN
    msg.add_u8(0x01); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x20); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN

    std::string out = msg.get_value();

    this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}

void Motor::setReverse(uint8_t power) {
    Message msg(true, false);
    msg.add_u8(Message::START_MOTOR);
    msg.add_u8(this->port_);
    msg.add_s8(-power);

    msg.add_u8(0x01 | 0x04); // UNKNOWN
    msg.add_u8(0x01); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x20); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN

    std::string out = msg.get_value();

    this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}

void Motor::stop(bool brake) {
    Message msg(true, false);
    msg.add_u8(Message::STOP_MOTOR);
    msg.add_u8(this->port_);
    msg.add_s8(0); // power 0?

    if (brake) {
        msg.add_u8(0x01 | 0x02 | 0x04); // UNKNOWN
        msg.add_u8(0x01); // UNKNOWN
        msg.add_u8(0x00); // UNKNOWN
        msg.add_u8(0x20); // UNKNOWN
    } else {
        msg.add_u8(0x00); // UNKNOWN
        msg.add_u8(0x00); // UNKNOWN
        msg.add_u8(0x00); // UNKNOWN
        msg.add_u8(0x00); // UNKNOWN
    }

    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN
    msg.add_u8(0x00); // UNKNOWN

    std::string out = msg.get_value();

    this->nxt_->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
}

Sensor::Sensor(NXT *nxt, uint8_t port) {
    this->nxt_ = nxt;
    this->port_ = port;
}

int Sensor::getValue() {
    Message msg(true, true);
    msg.add_u8(Message::GET_VALUE);
    msg.add_u8(this->port_);

    std::string out = msg.get_value();

    uint8_t responseBuffer[16];

    memset(responseBuffer, 1, sizeof(responseBuffer));

    this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));

    return responseBuffer[13] * 256 + responseBuffer[12];
}

SonarSensor::SonarSensor(NXT *nxt, uint8_t port) : Sensor(nxt, port) {
    this->nxt_ = nxt;
    this->port_ = port;
}

int SonarSensor::lsGetStatus(uint8_t *outbuf) {
    Message msg(true, true);
    msg.add_u8(Message::LS_GET_STATUS);
    msg.add_u8(this->port_);

    std::string out = msg.get_value();

    uint8_t responseBuffer[4];

    memset(responseBuffer, 1, sizeof(responseBuffer));

    this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));

    std::copy(responseBuffer, responseBuffer + sizeof(responseBuffer), outbuf);

    return static_cast<int>(responseBuffer[3]);
}

void SonarSensor::lsRead(uint8_t *outbuf) {
    Message msg(true, true);
    msg.add_u8(Message::LS_READ);
    msg.add_u8(this->port_);

    std::string out = msg.get_value();

    uint8_t responseBuffer[20];

    memset(responseBuffer, 1, sizeof(responseBuffer));

    this->nxt_->sendDirectCommand(true, (int8_t *)out.c_str(), out.size(), responseBuffer, sizeof(responseBuffer));

    std::copy(responseBuffer, responseBuffer + sizeof(responseBuffer), outbuf);
}

void SonarSensor::lsWrite(const std::string& indata, uint8_t *outBuf, size_t outSize) {
    Message msg(true, true);
    msg.add_u8(Message::LS_WRITE);
    msg.add_u8(this->port_);
    msg.add_u8(indata.size());
    msg.add_u8(outSize);
    msg.add_string(indata.size(), indata);

    std::string tosend = msg.get_value();

    uint8_t responseBuffer[3];

    memset(responseBuffer, 1, sizeof(responseBuffer));

    this->nxt_->sendDirectCommand(true, (int8_t *)(tosend.c_str()), tosend.size(), responseBuffer, sizeof(responseBuffer));

    std::memcpy(outBuf, responseBuffer, outSize * sizeof(uint8_t));
}

int SonarSensor::getSonarValue() {
    Message msg(true, true);
    msg.add_u8(0x02); // I2C_DEV
    msg.add_u8(0x41); // COMMAND
    msg.add_u8(0x02); // CONTINUOUS

    std::string out = msg.get_value();

    uint8_t outbuf2[66];
    memset(outbuf2, 1, sizeof(outbuf2));
    this->lsWrite(out, outbuf2, 0x00);

    while (1) {
        Message msg(true, true);
        msg.add_u8(0x02); // I2C_DEV
        msg.add_u8(0x42); // READ VALUE FROM I2C
        std::string out2 = msg.get_value();

        uint8_t outbuf3[66];
        memset(outbuf3, 1, sizeof(outbuf3));
        this->lsWrite(out2, outbuf3, 1);

        uint8_t outbuf4[4];
        memset(outbuf4, 1, sizeof(outbuf4));
        this->lsGetStatus(outbuf4);
        if (outbuf4[3] >= 1) { // 1 bytes
            break;
        }
    }

    uint8_t outbuf5[20];
    memset(outbuf5, 1, sizeof(outbuf5));
    this->lsRead(outbuf5);
    if (outbuf5[2] == 0) {
        return outbuf5[4];
    } else {
        return -1;
    }
}

BTComm::BTComm(struct sockaddr_rc addr) {
    this->addr_ = addr;
}

bool BTComm::open() {
    this->sock_ = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    int status = connect(this->sock_, (struct sockaddr *)&(this->addr_), sizeof(this->addr_));
    return (status == 0);
}

void BTComm::devWrite(uint8_t * buf, int buf_size) {
    uint8_t bf = buf_size;
    uint8_t header[] = {bf, 0x00};
    uint8_t outBuf[2 + buf_size];
    memcpy(outBuf, header, sizeof(header));
    memcpy(outBuf + 2, buf, buf_size);
    write(this->sock_, outBuf, sizeof(outBuf));
}

void BTComm::devRead(uint8_t * buf, int buf_size) {
    char reply[64];
    memset(reply, 0, sizeof(reply));

    // read data from the client
    int bytes_read = read(this->sock_, reply, 2);

    if ( bytes_read > 0 ) {
        int replylength = reply[0] + (reply[1] * 256);
        bytes_read = read(this->sock_, reply, replylength);
        if (bytes_read == replylength) {
            memcpy(buf, reply, buf_size);
        }
    }
}

bool USBComm::open() {

    int nEp = 0;

    if (this->usb_dev_ == 0) {
        std::cerr << "Device not found!" << std::endl;
        return false;
    }

    int r = libusb_open(this->usb_dev_, &(this->pUSBHandle_));

    if (r != 0) {
        std::cerr << "Not able to claim the USB device" << std::endl;
        return false;
    } else {
        libusb_config_descriptor *config;
        libusb_get_config_descriptor(this->usb_dev_, 0, &config);
        if (config->interface) {
            if (config->interface->altsetting) {
                r = libusb_claim_interface(this->pUSBHandle_, config->interface->altsetting->bInterfaceNumber);
                if ((nEp = config->interface->altsetting->bNumEndpoints)) {
                    if (config->interface->altsetting->endpoint) {
                        this->ucEpIn_ = (config->interface->altsetting->endpoint[0].bEndpointAddress);
                        if (nEp > 1) {
                            this->ucEpOut_ = (config->interface->altsetting->endpoint[1].bEndpointAddress);
                        }

                    }
                }
            }
        }
    }
    return true;
}

void USBComm::devWrite(uint8_t * buf, int buf_size) {
    boost::mutex::scoped_lock lock(this->io_mutex);
    if (this->pUSBHandle_) {
        int actual_length;
        int r = libusb_bulk_transfer(this->pUSBHandle_, this->ucEpIn_, buf, buf_size, &actual_length, TIMEOUT);
        if (r == 0 && actual_length == buf_size) {
        } else {
            std::cerr << "ERROR WRITING" << std::endl;
            std::cerr << "READ: " << actual_length << std::endl;
            std::cerr << "BUF LEN: " << buf_size << std::endl;
            std::cerr << "RES: " << r << std::endl;
        }
    }
}

void USBComm::devRead(uint8_t * buf, int buf_size) {
    boost::mutex::scoped_lock lock(this->io_mutex);
    if (this->pUSBHandle_) {
        int actual_length;
        int r = libusb_bulk_transfer(this->pUSBHandle_, this->ucEpOut_, buf, buf_size, &actual_length, TIMEOUT);
        if (r == 0 && actual_length <= buf_size) {
        } else {
            std::cerr << "ERROR READING" << std::endl;
            std::cerr << "READ: " << actual_length << std::endl;
            std::cerr << "BUF LEN: " << buf_size << std::endl;
            std::cerr << "RES: " << r << std::endl;
        }
    }
}

USBComm::USBComm(libusb_context *ctx, libusb_device *usb_dev) {
    this->ctx_ = ctx;
    this->usb_dev_ = usb_dev;
}

USBComm::~USBComm() {
    libusb_unref_device(this->usb_dev_);
    libusb_close(this->pUSBHandle_);
}

Sensor* NXT::makeTouch(uint8_t port) {
    Message msg(true, false);
    msg.add_u8(Message::SET_INPUT_MODE);
    msg.add_u8(port);
    msg.add_u8(Message::TOUCH);
    msg.add_u8(Mode::BOOLEAN);

    std::string out = msg.get_value();
    this->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
    return new Sensor(this, port);
}

SonarSensor* NXT::makeSonar(uint8_t port) {
    // 0x05 -> setInputMode
    // 0x0B -> LOWSPEED_9V
    // 0x00 -> RAW
    Message msg(true, false);
    msg.add_u8(Message::SET_INPUT_MODE);
    msg.add_u8(port);
    msg.add_u8(Message::LOWSPEED_9V);
    msg.add_u8(Mode::RAW);

    std::string out = msg.get_value();
    this->sendDirectCommand( false, (int8_t *)out.c_str(), out.size(), NULL, 0);
    return new SonarSensor(this, port);
}

Motor* NXT::makeMotor(uint8_t port) {
    return new Motor(this, port);
}

bool NXT::open() {
    return this->comm_->open();
}

bool NXT::isHalted() const {
    return this->halted;
}

void NXT::halt() {
    for (uint8_t port = 0; port < 3; ++port) {
        this->makeMotor(port)->stop(false);
    }
    this->halted = true;
}

double NXT::getFirmwareVersion() {
    uint8_t outBuf[7];
    const int min = 4, maj = 5;

    Message msg(false, true);
    msg.add_u8(0x88);
    std::string data = msg.get_value();

    // Send the system command to the NXT.
    this->sendSystemCommand(true, (int8_t *)data.c_str(), data.size(), outBuf, sizeof(outBuf));

    double version = outBuf[min];

    while (version >= 1)
        version /= 10;
    version += outBuf[maj];

    return version;
}

void NXT::getDeviceInfo(uint8_t * outBuf, size_t size) {
    //uint8_t inBuf[] = { 0x01, 0x9B };
    int8_t inBuf[] = { static_cast<int8_t>(0x9B) };

    // Send the system command to the NXT.
    this->sendSystemCommand(true, inBuf, sizeof(inBuf), outBuf, size);
}

std::string NXT::getName() {
    uint8_t outBuf[33];
    char name[15];

    name[0] = '\0';

    this->getDeviceInfo(outBuf, sizeof(outBuf));

    std::memcpy(name, outBuf + 2, 15 * sizeof(uint8_t));

    name[15] = '\0';

    return std::string(name);
}

NXT::NXT(Comm *comm) {
    this->comm_ = comm;
    this->halted = false;
}

void NXT::sendSystemCommand(bool response, int8_t * dc_buf,
                            size_t dc_buf_size, uint8_t * re_buf, size_t re_buf_size) {
    uint8_t buf[dc_buf_size + 1];

    std::copy(dc_buf, dc_buf + dc_buf_size, buf + 1);

    buf[0] = response ? 0x01 : 0x81;

    this->comm_->devWrite(buf, dc_buf_size + 1);

    if (response) {
        uint8_t tempreadbuf[re_buf_size];
        this->comm_->devRead(tempreadbuf, re_buf_size);

        std::copy(tempreadbuf + 1, tempreadbuf + re_buf_size, re_buf);
    }
}

void NXT::submitDirectCommand(Command *command) {
}

void NXT::sendDirectCommand(bool response, int8_t * dc_buf,
                            size_t dc_buf_size, uint8_t * re_buf, size_t re_buf_size) {
    uint8_t buf[dc_buf_size + 1];

    std::copy(dc_buf, dc_buf + dc_buf_size, buf + 1);

    buf[0] = response ? 0x00 : 0x80;

    this->comm_->devWrite(buf, dc_buf_size + 1);

    if (response) {
        this->comm_->devRead(re_buf, re_buf_size);
    }
}

std::vector<NXT *>* USBNXTManager::list() {

    // List all the NXT devices
    std::vector<NXT*>* v = new std::vector<NXT*>();

    libusb_device **devs;
    libusb_context *ctx = NULL;
    libusb_device *dev;

    int r;
    ssize_t cnt; //holding number of devices in list

    r = libusb_init(&ctx);

    if (r < 0) {
        std::cout<<"Init Error "<<r<<std::endl; //there was an error
        return v;
    }

    libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation

    cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
    if (cnt < 0) {
        std::cout<<"Get Device Error"<<std::endl; //there was an error
        return v;
    }

    std::cout<<cnt<<" Devices in list."<<std::endl; //print total number of usb devices
    ssize_t i; //for iterating through the list
    for (i = 0; i < cnt; i++) {
        libusb_device_descriptor desc;
        int r = libusb_get_device_descriptor(devs[i], &desc);
        if (r < 0) {
            std::cout<<"failed to get device descriptor"<<std::endl;
            continue;
        }

        if (desc.idVendor == NXT_VENDOR_ID && desc.idProduct == NXT_PRODUCT_ID) {
            libusb_device_handle *devh = NULL;
            libusb_open(devs[i], &devh);
            libusb_reset_device(devh);
            libusb_close(devh);
        }
    }

    cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
    if (cnt < 0) {
        std::cout<<"Get Device Error"<<std::endl; //there was an error
        return v;
    }

    std::cout<<cnt<<" Devices in list."<<std::endl; //print total number of usb devices
    for (i = 0; i < cnt; i++) {
        libusb_device_descriptor desc;
        int r = libusb_get_device_descriptor(devs[i], &desc);
        if (r < 0) {
            std::cout<<"failed to get device descriptor"<<std::endl;
            continue;
        }

        if (desc.idVendor == NXT_VENDOR_ID && desc.idProduct == NXT_PRODUCT_ID) {
            dev = libusb_ref_device(devs[i]);
            USBComm *comm = new USBComm(ctx, dev);
            NXT *nxt = new NXT(comm);
            v->push_back(nxt);
        }
    }
    libusb_free_device_list(devs, 1); //free the list, unref the devices in it
//        libusb_exit(ctx); //close the session
    return v;
}

std::vector<NXT *>* BTNXTManager::list() {

    // List all the NXT devices
    std::vector<NXT*>* v = new std::vector<NXT*>();

    inquiry_info *ii = NULL;
    int max_rsp, num_rsp;
    int dev_id, sock, len, flags;
    int i;

    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    if (dev_id < 0 || sock < 0) {
        perror("opening socket");
        exit(1);
    }

    len  = 8;
    max_rsp = 255;
    flags = IREQ_CACHE_FLUSH;
    ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

    num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
    if ( num_rsp < 0 ) perror("hci_inquiry");

    for (i = 0; i < num_rsp; i++) {
        bdaddr_t *ba = &(ii+i)->bdaddr;

        if (ba->b[5] == 0x00 && ba->b[4] == 0x16 && ba->b[3] == 0x53) {
            struct sockaddr_rc addr;
            // set the connection parameters (who to connect to)
            addr.rc_family = AF_BLUETOOTH;
            addr.rc_channel = (uint8_t) 1;
            memcpy(&(addr.rc_bdaddr), ba, sizeof(bdaddr_t));

            BTComm *comm = new BTComm(addr);
            NXT *nxt = new NXT(comm);
            v->push_back(nxt);
        }
    }

    free( ii );
    close( sock );
    return v;
}
<commit_msg>removed unused comm.cpp file<commit_after><|endoftext|>


<commit_before>class OSingleton
{
public:
    static OSingleton * GetSingleton();
    virtual ~OSingleton(){}
protected :
    OSingleton(){}
    static OSingleton * m_pSingleton;
};

OSingleton * OSingleton::m_pSingleton = NULL;
OSingleton * OSingleton::GetSingleton()
{
    if(m_pSingleton  == NULL )
    {
        m_pSingleton = new OSingleton;
    }
    return m_pSingleton;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.1.126); FILE MERGED 2006/09/01 17:53:49 kaib 1.1.126.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: singleton.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:47:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
class OSingleton
{
public:
    static OSingleton * GetSingleton();
    virtual ~OSingleton(){}
protected :
    OSingleton(){}
    static OSingleton * m_pSingleton;
};

OSingleton * OSingleton::m_pSingleton = NULL;
OSingleton * OSingleton::GetSingleton()
{
    if(m_pSingleton  == NULL )
    {
        m_pSingleton = new OSingleton;
    }
    return m_pSingleton;
}
<|endoftext|>


<commit_before>/***************************************************************************
                          yahooaddcontact.cpp  -  description
                             -------------------
    begin                : Fri Apr 26 2002
    copyright            : (C) 2002 by Gav Wood
    email                : gav@kde.org

    Based on code from   : (C) 2002 by Duncan Mac-Vicar Prett
    email                : duncan@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

// QT Includes
#include <qcheckbox.h>

// KDE Includes
#include <kdebug.h>
#include <kmessagebox.h>

// Kopete Includes
#include <addcontactpage.h>

// Local Includes
#include "yahooaccount.h"
#include "yahoocontact.h"
#include "yahooeditaccount.h"

// Yahoo Add Contact page
YahooEditAccount::YahooEditAccount(YahooProtocol *protocol, KopeteAccount *theAccount, QWidget *parent, const char *name): YahooEditAccountBase(parent), EditAccountWidget(theAccount)
{
	kdDebug(14180) << "YahooEditAccount::YahooEditAccount(<protocol>, <theAccount>, <parent>, " << name << ")";

	theProtocol = protocol;
	if(m_account)
	{	mScreenName->setText(m_account->accountId());
		if(m_account->rememberPassword())
			mPassword->setText(m_account->getPassword());
		mAutoConnect->setChecked(m_account->autoLogin());
		mRememberPassword->setChecked(true);
	}
	show();
}

bool YahooEditAccount::validateData()
{
	kdDebug(14180) << "YahooEditAccount::validateData()";

	if(mScreenName->text() == "")
	{	KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name</qt>"), i18n("Yahoo"));
		return false;
	}
	if(mPassword->text() == "")
	{	KMessageBox::sorry(this, i18n("<qt>You must enter a valid password</qt>"), i18n("Yahoo"));
		return false;
	}
	return true;
}

KopeteAccount *YahooEditAccount::apply()
{
	kdDebug(14180) << "YahooEditAccount::apply()";

	if(!m_account)
		m_account = new YahooAccount(theProtocol, mScreenName->text());
	else
		m_account->setAccountId(mScreenName->text());
	m_account->setAutoLogin(mAutoConnect->isChecked());
	if(mRememberPassword->isChecked())
		m_account->setPassword(mPassword->text());

	return m_account;
}

#include "yahooeditaccount.moc"
/*
 * Local variables:
 * c-indentation-style: k&r
 * c-basic-offset: 8
 * indent-tabs-mode: t
 * End:
 */
// vim: set noet ts=4 sts=4 sw=4:

<commit_msg><commit_after>/***************************************************************************
                          yahooaddcontact.cpp  -  description
                             -------------------
    begin                : Fri Apr 26 2002
    copyright            : (C) 2002 by Gav Wood
    email                : gav@kde.org

    Based on code from   : (C) 2002 by Duncan Mac-Vicar Prett
    email                : duncan@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

// QT Includes
#include <qcheckbox.h>
#include <qlineedit.h>

// KDE Includes
#include <kdebug.h>
#include <kmessagebox.h>

// Kopete Includes
#include <addcontactpage.h>

// Local Includes
#include "yahooaccount.h"
#include "yahoocontact.h"
#include "yahooeditaccount.h"

// Yahoo Add Contact page
YahooEditAccount::YahooEditAccount(YahooProtocol *protocol, KopeteAccount *theAccount, QWidget *parent, const char *name): YahooEditAccountBase(parent), EditAccountWidget(theAccount)
{
	kdDebug(14180) << "YahooEditAccount::YahooEditAccount(<protocol>, <theAccount>, <parent>, " << name << ")";

	theProtocol = protocol;
	if(m_account)
	{	mScreenName->setText(m_account->accountId());
		if(m_account->rememberPassword())
			mPassword->setText(m_account->getPassword());
		mAutoConnect->setChecked(m_account->autoLogin());
		mRememberPassword->setChecked(true);
	}
	show();
}

bool YahooEditAccount::validateData()
{
	kdDebug(14180) << "YahooEditAccount::validateData()";

	if(mScreenName->text() == "")
	{	KMessageBox::sorry(this, i18n("<qt>You must enter a valid screen name</qt>"), i18n("Yahoo"));
		return false;
	}
	if(mPassword->text() == "")
	{	KMessageBox::sorry(this, i18n("<qt>You must enter a valid password</qt>"), i18n("Yahoo"));
		return false;
	}
	return true;
}

KopeteAccount *YahooEditAccount::apply()
{
	kdDebug(14180) << "YahooEditAccount::apply()";

	if(!m_account)
		m_account = new YahooAccount(theProtocol, mScreenName->text());
	else
		m_account->setAccountId(mScreenName->text());
	m_account->setAutoLogin(mAutoConnect->isChecked());
	if(mRememberPassword->isChecked())
		m_account->setPassword(mPassword->text());

	return m_account;
}

#include "yahooeditaccount.moc"
/*
 * Local variables:
 * c-indentation-style: k&r
 * c-basic-offset: 8
 * indent-tabs-mode: t
 * End:
 */
// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*
** Copyright 2014-2016 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/

#include "com/centreon/broker/bam/bool_binary_operator.hh"

using namespace com::centreon::broker::bam;

/**
 *  Default constructor.
 */
bool_binary_operator::bool_binary_operator()
  : _left_hard(0.0),
    _left_soft(0.0),
    _right_hard(0.0),
    _right_soft(0.0),
    _state_known(false),
    _in_downtime(false) {}

/**
 *  Copy constructor.
 *
 *  @param[in] right Object to copy.
 */
bool_binary_operator::bool_binary_operator(
                        bool_binary_operator const& right)
  : bool_value(right) {
  _internal_copy(right);
}

/**
 *  Destructor.
 */
bool_binary_operator::~bool_binary_operator() {}

/**
 *  Assignment operator.
 *
 *  @param[in] right Object to copy.
 *
 *  @return This object.
 */
bool_binary_operator& bool_binary_operator::operator=(
                                              bool_binary_operator const& right) {
  if (this != &right) {
    bool_value::operator=(right);
    _internal_copy(right);
  }
  return (*this);
}

/**
 *  Notification of child update.
 *
 *  @param[in] child     Child that got updated.
 *  @param[out] visitor  Visitor.
 *
 *  @return              True if the values of this object were modified.
 */
bool bool_binary_operator::child_has_update(
                             computable* child,
                             io::stream* visitor) {
  (void)visitor;
  bool retval(true);

  // Check operation members values.
  if (child) {
    if (child == _left.data()) {
      double value_hard(_left->value_hard());
      double value_soft(_left->value_soft());
      if ((_left_hard != value_hard) || (_left_soft != value_soft)) {
        _left_hard = value_hard;
        _left_soft = value_soft;
        retval = true;
      }
    }
    else if (child == _right.data()) {
      double value_hard(_right->value_hard());
      double value_soft(_right->value_soft());
      if ((_right_hard != value_hard) || (_right_soft == value_soft)) {
        _right_hard = value_hard;
        _right_soft = value_soft;
        retval = true;
      }
    }
  }

  // Check known flag.
  bool known(state_known());
  if (_state_known != known) {
    _state_known = known;
    retval = true;
  }

  // Check downtime flag.
  bool in_dt(in_downtime());
  if (_in_downtime != in_dt) {
    _in_downtime = in_dt;
    retval = true;
  }

  return (retval);
}

/**
 *  Set left member.
 *
 *  @param[in] left Left member of the boolean operator.
 */
void bool_binary_operator::set_left(
                             misc::shared_ptr<bool_value> const& left) {
  _left = left;
  return ;
}

/**
 *  Set right member.
 *
 *  @param[in] right Right member of the boolean operator.
 */
void bool_binary_operator::set_right(
                             misc::shared_ptr<bool_value> const& right) {
  _right = right;
  return ;
}

/**
 *  Copy internal data members.
 *
 *  @param[in] right Object to copy.
 */
void bool_binary_operator::_internal_copy(
                             bool_binary_operator const& right) {
  _left = right._left;
  _left_hard = right._left_hard;
  _left_soft = right._left_soft;
  _right = right._right;
  _right_hard = right._right_hard;
  _right_soft = right._right_soft;
  _state_known = right._state_known;
  _in_downtime = right._in_downtime;
  return ;
}

/**
 *  Get if the state is known, i.e has been computed at least once.
 *
 *  @return  True if the state is known.
 */
bool bool_binary_operator::state_known() const {
  return (!_left.isNull()
          && !_right.isNull()
          && _left->state_known()
          && _right->state_known());
}

/**
 *  Is this expression in downtime?
 *
 *  @return  True if this expression is in downtime.
 */
bool bool_binary_operator::in_downtime() const {
  return ((!_left.isNull() && _left->in_downtime())
          || (!_right.isNull() && _right->in_downtime()));
}
<commit_msg>BAM: properly initialize cache of bool_binary_operator.<commit_after>/*
** Copyright 2014-2016 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/

#include "com/centreon/broker/bam/bool_binary_operator.hh"

using namespace com::centreon::broker::bam;

/**
 *  Default constructor.
 */
bool_binary_operator::bool_binary_operator()
  : _left_hard(0.0),
    _left_soft(0.0),
    _right_hard(0.0),
    _right_soft(0.0),
    _state_known(false),
    _in_downtime(false) {}

/**
 *  Copy constructor.
 *
 *  @param[in] right Object to copy.
 */
bool_binary_operator::bool_binary_operator(
                        bool_binary_operator const& right)
  : bool_value(right) {
  _internal_copy(right);
}

/**
 *  Destructor.
 */
bool_binary_operator::~bool_binary_operator() {}

/**
 *  Assignment operator.
 *
 *  @param[in] right Object to copy.
 *
 *  @return This object.
 */
bool_binary_operator& bool_binary_operator::operator=(
                                              bool_binary_operator const& right) {
  if (this != &right) {
    bool_value::operator=(right);
    _internal_copy(right);
  }
  return (*this);
}

/**
 *  Notification of child update.
 *
 *  @param[in] child     Child that got updated.
 *  @param[out] visitor  Visitor.
 *
 *  @return              True if the values of this object were modified.
 */
bool bool_binary_operator::child_has_update(
                             computable* child,
                             io::stream* visitor) {
  (void)visitor;
  bool retval(true);

  // Check operation members values.
  if (child) {
    if (child == _left.data()) {
      double value_hard(_left->value_hard());
      double value_soft(_left->value_soft());
      if ((_left_hard != value_hard) || (_left_soft != value_soft)) {
        _left_hard = value_hard;
        _left_soft = value_soft;
        retval = true;
      }
    }
    else if (child == _right.data()) {
      double value_hard(_right->value_hard());
      double value_soft(_right->value_soft());
      if ((_right_hard != value_hard) || (_right_soft == value_soft)) {
        _right_hard = value_hard;
        _right_soft = value_soft;
        retval = true;
      }
    }
  }

  // Check known flag.
  bool known(state_known());
  if (_state_known != known) {
    _state_known = known;
    retval = true;
  }

  // Check downtime flag.
  bool in_dt(in_downtime());
  if (_in_downtime != in_dt) {
    _in_downtime = in_dt;
    retval = true;
  }

  return (retval);
}

/**
 *  Set left member.
 *
 *  @param[in] left Left member of the boolean operator.
 */
void bool_binary_operator::set_left(
                             misc::shared_ptr<bool_value> const& left) {
  _left = left;
  _left_hard = _left->value_hard();
  _left_soft = _left->value_soft();
  _state_known = state_known();
  _in_downtime = in_downtime();
  return ;
}

/**
 *  Set right member.
 *
 *  @param[in] right Right member of the boolean operator.
 */
void bool_binary_operator::set_right(
                             misc::shared_ptr<bool_value> const& right) {
  _right = right;
  _right_hard = _right->value_hard();
  _right_soft = _right->value_soft();
  _state_known = state_known();
  _in_downtime = in_downtime();
  return ;
}

/**
 *  Copy internal data members.
 *
 *  @param[in] right Object to copy.
 */
void bool_binary_operator::_internal_copy(
                             bool_binary_operator const& right) {
  _left = right._left;
  _left_hard = right._left_hard;
  _left_soft = right._left_soft;
  _right = right._right;
  _right_hard = right._right_hard;
  _right_soft = right._right_soft;
  _state_known = right._state_known;
  _in_downtime = right._in_downtime;
  return ;
}

/**
 *  Get if the state is known, i.e has been computed at least once.
 *
 *  @return  True if the state is known.
 */
bool bool_binary_operator::state_known() const {
  return (!_left.isNull()
          && !_right.isNull()
          && _left->state_known()
          && _right->state_known());
}

/**
 *  Is this expression in downtime?
 *
 *  @return  True if this expression is in downtime.
 */
bool bool_binary_operator::in_downtime() const {
  return ((!_left.isNull() && _left->in_downtime())
          || (!_right.isNull() && _right->in_downtime()));
}
<|endoftext|>


<commit_before>/*
   Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "HelpOperationFactory.hpp"

#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"

#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"

#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"

#include "MTProto/StreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"

#include <QLoggingCategory>

namespace Telegram {

namespace Server {

// Generated process methods
bool HelpRpcOperation::processGetAppChangelog(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetAppChangelog);
    context.inputStream() >> m_getAppChangelog;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetAppUpdate(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetAppUpdate);
    context.inputStream() >> m_getAppUpdate;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetCdnConfig(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetCdnConfig);
    context.inputStream() >> m_getCdnConfig;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetConfig(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetConfig);
    context.inputStream() >> m_getConfig;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetInviteText(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetInviteText);
    context.inputStream() >> m_getInviteText;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetNearestDc(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetNearestDc);
    context.inputStream() >> m_getNearestDc;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetRecentMeUrls(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetRecentMeUrls);
    context.inputStream() >> m_getRecentMeUrls;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetSupport(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetSupport);
    context.inputStream() >> m_getSupport;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetTermsOfService(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetTermsOfService);
    context.inputStream() >> m_getTermsOfService;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processSaveAppLog(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runSaveAppLog);
    context.inputStream() >> m_saveAppLog;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processSetBotUpdatesStatus(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runSetBotUpdatesStatus);
    context.inputStream() >> m_setBotUpdatesStatus;
    return !context.inputStream().error();
}
// End of generated process methods

// Generated run methods
void HelpRpcOperation::runGetAppChangelog()
{
    // TLFunctions::TLHelpGetAppChangelog &arguments = m_getAppChangelog;
    if (processNotImplementedMethod(TLValue::HelpGetAppChangelog)) {
        return;
    }
    TLUpdates result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetAppUpdate()
{
    if (processNotImplementedMethod(TLValue::HelpGetAppUpdate)) {
        return;
    }
    TLHelpAppUpdate result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetCdnConfig()
{
    if (processNotImplementedMethod(TLValue::HelpGetCdnConfig)) {
        return;
    }
    TLCdnConfig result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetConfig()
{
    const DcConfiguration dcConfig = api()->serverConfiguration();
    TLConfig result;
    result.flags = TLConfig::PhonecallsEnabled;
    result.testMode = true;
    result.thisDc = api()->dcId();
    // TODO: fill other fields of result
    // manually copy fields from all DcOption's to TLDcOption's
    for (const DcOption &dcOption : dcConfig.dcOptions) {
        TLDcOption tlDcOption;
        tlDcOption.id = dcOption.id;
        tlDcOption.ipAddress = dcOption.address;
        tlDcOption.port = dcOption.port;
        tlDcOption.flags = dcOption.flags;
        result.dcOptions.append(std::move(tlDcOption));
    }
    sendRpcReply(result);
}

void HelpRpcOperation::runGetInviteText()
{
    if (processNotImplementedMethod(TLValue::HelpGetInviteText)) {
        return;
    }
    TLHelpInviteText result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetNearestDc()
{
    TLNearestDc result;
    result.thisDc = api()->dcId();
    result.nearestDc = 1;
    // ISO 3166-1 alpha-2
    result.country = QStringLiteral("AQ");
    sendRpcReply(result);
}

void HelpRpcOperation::runGetRecentMeUrls()
{
    // TLFunctions::TLHelpGetRecentMeUrls &arguments = m_getRecentMeUrls;
    if (processNotImplementedMethod(TLValue::HelpGetRecentMeUrls)) {
        return;
    }
    TLHelpRecentMeUrls result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetSupport()
{
    if (processNotImplementedMethod(TLValue::HelpGetSupport)) {
        return;
    }
    TLHelpSupport result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetTermsOfService()
{
    if (processNotImplementedMethod(TLValue::HelpGetTermsOfService)) {
        return;
    }
    TLHelpTermsOfService result;
    sendRpcReply(result);
}

void HelpRpcOperation::runSaveAppLog()
{
    // TLFunctions::TLHelpSaveAppLog &arguments = m_saveAppLog;
    if (processNotImplementedMethod(TLValue::HelpSaveAppLog)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void HelpRpcOperation::runSetBotUpdatesStatus()
{
    // TLFunctions::TLHelpSetBotUpdatesStatus &arguments = m_setBotUpdatesStatus;
    if (processNotImplementedMethod(TLValue::HelpSetBotUpdatesStatus)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}
// End of generated run methods

void HelpRpcOperation::setRunMethod(HelpRpcOperation::RunMethod method)
{
    m_runMethod = method;
}

HelpRpcOperation::ProcessingMethod HelpRpcOperation::getMethodForRpcFunction(TLValue function)
{
    switch (function) {
    // Generated methodForRpcFunction cases
    case TLValue::HelpGetAppChangelog:
        return &HelpRpcOperation::processGetAppChangelog;
    case TLValue::HelpGetAppUpdate:
        return &HelpRpcOperation::processGetAppUpdate;
    case TLValue::HelpGetCdnConfig:
        return &HelpRpcOperation::processGetCdnConfig;
    case TLValue::HelpGetConfig:
        return &HelpRpcOperation::processGetConfig;
    case TLValue::HelpGetInviteText:
        return &HelpRpcOperation::processGetInviteText;
    case TLValue::HelpGetNearestDc:
        return &HelpRpcOperation::processGetNearestDc;
    case TLValue::HelpGetRecentMeUrls:
        return &HelpRpcOperation::processGetRecentMeUrls;
    case TLValue::HelpGetSupport:
        return &HelpRpcOperation::processGetSupport;
    case TLValue::HelpGetTermsOfService:
        return &HelpRpcOperation::processGetTermsOfService;
    case TLValue::HelpSaveAppLog:
        return &HelpRpcOperation::processSaveAppLog;
    case TLValue::HelpSetBotUpdatesStatus:
        return &HelpRpcOperation::processSetBotUpdatesStatus;
    // End of generated methodForRpcFunction cases
    default:
        return nullptr;
    }
}

RpcOperation *HelpOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
    return processRpcCallImpl<HelpRpcOperation>(layer, context);
}

} // Server namespace

} // Telegram namespace
<commit_msg>Server: Add 'date' to help.getConfig result<commit_after>/*
   Copyright (C) 2018 Alexander Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "HelpOperationFactory.hpp"

#include "RpcOperationFactory_p.hpp"
// TODO: Instead of this include, add a generated cpp with all needed template instances
#include "ServerRpcOperation_p.hpp"

#include "ServerApi.hpp"
#include "ServerRpcLayer.hpp"
#include "TelegramServerUser.hpp"

#include "ApiUtils.hpp"
#include "Debug_p.hpp"
#include "RpcError.hpp"
#include "RpcProcessingContext.hpp"

#include "MTProto/StreamExtraOperators.hpp"
#include "FunctionStreamOperators.hpp"

#include <QLoggingCategory>

namespace Telegram {

namespace Server {

// Generated process methods
bool HelpRpcOperation::processGetAppChangelog(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetAppChangelog);
    context.inputStream() >> m_getAppChangelog;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetAppUpdate(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetAppUpdate);
    context.inputStream() >> m_getAppUpdate;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetCdnConfig(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetCdnConfig);
    context.inputStream() >> m_getCdnConfig;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetConfig(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetConfig);
    context.inputStream() >> m_getConfig;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetInviteText(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetInviteText);
    context.inputStream() >> m_getInviteText;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetNearestDc(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetNearestDc);
    context.inputStream() >> m_getNearestDc;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetRecentMeUrls(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetRecentMeUrls);
    context.inputStream() >> m_getRecentMeUrls;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetSupport(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetSupport);
    context.inputStream() >> m_getSupport;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processGetTermsOfService(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runGetTermsOfService);
    context.inputStream() >> m_getTermsOfService;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processSaveAppLog(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runSaveAppLog);
    context.inputStream() >> m_saveAppLog;
    return !context.inputStream().error();
}

bool HelpRpcOperation::processSetBotUpdatesStatus(RpcProcessingContext &context)
{
    setRunMethod(&HelpRpcOperation::runSetBotUpdatesStatus);
    context.inputStream() >> m_setBotUpdatesStatus;
    return !context.inputStream().error();
}
// End of generated process methods

// Generated run methods
void HelpRpcOperation::runGetAppChangelog()
{
    // TLFunctions::TLHelpGetAppChangelog &arguments = m_getAppChangelog;
    if (processNotImplementedMethod(TLValue::HelpGetAppChangelog)) {
        return;
    }
    TLUpdates result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetAppUpdate()
{
    if (processNotImplementedMethod(TLValue::HelpGetAppUpdate)) {
        return;
    }
    TLHelpAppUpdate result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetCdnConfig()
{
    if (processNotImplementedMethod(TLValue::HelpGetCdnConfig)) {
        return;
    }
    TLCdnConfig result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetConfig()
{
    const DcConfiguration dcConfig = api()->serverConfiguration();
    TLConfig result;
    result.flags = TLConfig::PhonecallsEnabled;
    result.date = Telegram::Utils::getCurrentTime();
    result.testMode = true;
    result.thisDc = api()->dcId();
    // TODO: fill other fields of result
    // manually copy fields from all DcOption's to TLDcOption's
    for (const DcOption &dcOption : dcConfig.dcOptions) {
        TLDcOption tlDcOption;
        tlDcOption.id = dcOption.id;
        tlDcOption.ipAddress = dcOption.address;
        tlDcOption.port = dcOption.port;
        tlDcOption.flags = dcOption.flags;
        result.dcOptions.append(std::move(tlDcOption));
    }
    sendRpcReply(result);
}

void HelpRpcOperation::runGetInviteText()
{
    if (processNotImplementedMethod(TLValue::HelpGetInviteText)) {
        return;
    }
    TLHelpInviteText result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetNearestDc()
{
    TLNearestDc result;
    result.thisDc = api()->dcId();
    result.nearestDc = 1;
    // ISO 3166-1 alpha-2
    result.country = QStringLiteral("AQ");
    sendRpcReply(result);
}

void HelpRpcOperation::runGetRecentMeUrls()
{
    // TLFunctions::TLHelpGetRecentMeUrls &arguments = m_getRecentMeUrls;
    if (processNotImplementedMethod(TLValue::HelpGetRecentMeUrls)) {
        return;
    }
    TLHelpRecentMeUrls result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetSupport()
{
    if (processNotImplementedMethod(TLValue::HelpGetSupport)) {
        return;
    }
    TLHelpSupport result;
    sendRpcReply(result);
}

void HelpRpcOperation::runGetTermsOfService()
{
    if (processNotImplementedMethod(TLValue::HelpGetTermsOfService)) {
        return;
    }
    TLHelpTermsOfService result;
    sendRpcReply(result);
}

void HelpRpcOperation::runSaveAppLog()
{
    // TLFunctions::TLHelpSaveAppLog &arguments = m_saveAppLog;
    if (processNotImplementedMethod(TLValue::HelpSaveAppLog)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}

void HelpRpcOperation::runSetBotUpdatesStatus()
{
    // TLFunctions::TLHelpSetBotUpdatesStatus &arguments = m_setBotUpdatesStatus;
    if (processNotImplementedMethod(TLValue::HelpSetBotUpdatesStatus)) {
        return;
    }
    bool result;
    sendRpcReply(result);
}
// End of generated run methods

void HelpRpcOperation::setRunMethod(HelpRpcOperation::RunMethod method)
{
    m_runMethod = method;
}

HelpRpcOperation::ProcessingMethod HelpRpcOperation::getMethodForRpcFunction(TLValue function)
{
    switch (function) {
    // Generated methodForRpcFunction cases
    case TLValue::HelpGetAppChangelog:
        return &HelpRpcOperation::processGetAppChangelog;
    case TLValue::HelpGetAppUpdate:
        return &HelpRpcOperation::processGetAppUpdate;
    case TLValue::HelpGetCdnConfig:
        return &HelpRpcOperation::processGetCdnConfig;
    case TLValue::HelpGetConfig:
        return &HelpRpcOperation::processGetConfig;
    case TLValue::HelpGetInviteText:
        return &HelpRpcOperation::processGetInviteText;
    case TLValue::HelpGetNearestDc:
        return &HelpRpcOperation::processGetNearestDc;
    case TLValue::HelpGetRecentMeUrls:
        return &HelpRpcOperation::processGetRecentMeUrls;
    case TLValue::HelpGetSupport:
        return &HelpRpcOperation::processGetSupport;
    case TLValue::HelpGetTermsOfService:
        return &HelpRpcOperation::processGetTermsOfService;
    case TLValue::HelpSaveAppLog:
        return &HelpRpcOperation::processSaveAppLog;
    case TLValue::HelpSetBotUpdatesStatus:
        return &HelpRpcOperation::processSetBotUpdatesStatus;
    // End of generated methodForRpcFunction cases
    default:
        return nullptr;
    }
}

RpcOperation *HelpOperationFactory::processRpcCall(RpcLayer *layer, RpcProcessingContext &context)
{
    return processRpcCallImpl<HelpRpcOperation>(layer, context);
}

} // Server namespace

} // Telegram namespace
<|endoftext|>


<commit_before>#include "MyModel.h"
#include "DNest4/code/DNest4.h"
#include "Data.h"
#include <cmath>

using namespace std;
using namespace DNest4;

MyModel::MyModel()
:objects(3, 10, false, MyConditionalPrior(-10., 10., 1E-3, 1E3))
,mu(Data::get_instance().get_t().size())
{

}

void MyModel::from_prior(RNG& rng)
{
	objects.from_prior(rng);
	objects.consolidate_diff();
	sigma = exp(log(1E-3) + log(1E6)*rng.rand());
	calculate_mu();
}

void MyModel::calculate_mu()
{
	// Get the times from the data
	const vector<double>& t = Data::get_instance().get_t();

	// Update or from scratch?
	bool update = false;//(objects.get_added().size() < objects.get_components().size());

	// Get the components
	const vector< vector<double> >& components = (update)?(objects.get_added()):
				(objects.get_components());

	// Zero the signal
	if(!update)
		mu.assign(mu.size(), 0.);

	double T, A, phi;
	for(size_t j=0; j<components.size(); j++)
	{
		T = exp(components[j][0]);
		A = components[j][1];
		phi = components[j][2];
		for(size_t i=0; i<t.size(); i++)
			mu[i] += A*sin(2.*M_PI*t[i]/T + phi);
	}
}

double MyModel::perturb(RNG& rng)
{
	double logH = 0.;

	if(rng.rand() <= 0.75)
	{
		logH += objects.perturb(rng);
		objects.consolidate_diff();
		calculate_mu();
	}
	else
	{
		sigma = log(sigma);
		sigma += log(1E6)*rng.randh();
		sigma = mod(sigma - log(1E-3), log(1E6)) + log(1E-3);
		sigma = exp(sigma);
	}

	return logH;
}

double MyModel::log_likelihood() const
{
	// Get the data
	const vector<double>& y = Data::get_instance().get_y();

	double logL = 0.;
	double var = sigma*sigma;
	for(size_t i=0; i<y.size(); i++)
		logL += -0.5*log(2.*M_PI*var) - 0.5*pow(y[i] - mu[i], 2)/var;

	return logL;
}

void MyModel::print(std::ostream& out) const
{
	for(size_t i=0; i<mu.size(); i++)
		out<<mu[i]<<' ';
	out<<sigma<<' ';
	objects.print(out); out<<' ';
}

string MyModel::description() const
{
	return string("objects, sigma");
}

<commit_msg>Faster by using partial updates<commit_after>#include "MyModel.h"
#include "DNest4/code/DNest4.h"
#include "Data.h"
#include <cmath>

using namespace std;
using namespace DNest4;

MyModel::MyModel()
:objects(3, 10, false, MyConditionalPrior(-10., 10., 1E-3, 1E3))
,mu(Data::get_instance().get_t().size())
{

}

void MyModel::from_prior(RNG& rng)
{
	objects.from_prior(rng);
	sigma = exp(log(1E-3) + log(1E6)*rng.rand());
	calculate_mu();
}

void MyModel::calculate_mu()
{
	// Get the times from the data
	const vector<double>& t = Data::get_instance().get_t();

	// Update or from scratch?
	bool update = (objects.get_removed().size() == 0);

	// Get the components
	const vector< vector<double> >& components = (update)?(objects.get_added()):
				                                          (objects.get_components());

	// Zero the signal
	if(!update)
		mu.assign(mu.size(), 0.0);

	double T, A, phi;
	for(size_t j=0; j<components.size(); j++)
	{
		T = exp(components[j][0]);
		A = components[j][1];
		phi = components[j][2];
		for(size_t i=0; i<t.size(); i++)
			mu[i] += A*sin(2.*M_PI*t[i]/T + phi);
	}
}

double MyModel::perturb(RNG& rng)
{
	double logH = 0.;

	if(rng.rand() <= 0.75)
	{
		logH += objects.perturb(rng);
		calculate_mu();
	}
	else
	{
		sigma = log(sigma);
		sigma += log(1E6)*rng.randh();
		sigma = mod(sigma - log(1E-3), log(1E6)) + log(1E-3);
		sigma = exp(sigma);
	}

	return logH;
}

double MyModel::log_likelihood() const
{
	// Get the data
	const vector<double>& y = Data::get_instance().get_y();

	double logL = 0.;
	double var = sigma*sigma;
	for(size_t i=0; i<y.size(); i++)
		logL += -0.5*log(2.*M_PI*var) - 0.5*pow(y[i] - mu[i], 2)/var;

	return logL;
}

void MyModel::print(std::ostream& out) const
{
	for(size_t i=0; i<mu.size(); i++)
		out<<mu[i]<<' ';
	out<<sigma<<' ';
	objects.print(out); out<<' ';
}

string MyModel::description() const
{
	return string("objects, sigma");
}

<|endoftext|>


<commit_before>#include "throttle.hpp"
#include <unistd.h>
#include <fcntl.h>

/**
 * Read a configuration file.
 *
 * This function is guaranteed to read in all syntactically correct files, but
 * might also accept others.
 */
Conf::Conf(const char *config_fn) {
	// open the file
	std::ifstream conf_file(config_fn);
	if (!conf_file)
		throw std::runtime_error(std::string("Couldn't open config file '") + config_fn + '\'');

	// read every line and put it in the map
	char line[LINE_LENGTH];
	std::string name;

	// parse: first comes the name of the command
	while (conf_file >> name) {
		// if line starts with '#', ignore it
		if (name[0] == '#') {
			conf_file.ignore(LINE_LENGTH, '\n');
			continue;
		}

		conf_file.ignore(LINE_LENGTH, '=');
		conf_file.ignore(LINE_LENGTH, ' ');
		conf_file.getline(line, LINE_LENGTH);

		DEBUG_PRINT("[Conf] " << name << " = " << line);

		// write into map
		attributes[name] = std::string(line);
	}
}

/**
 * Translation table for a command queue.
 */
const std::map<std::string, CommQueue::Command> CommQueue::translate = {
	{"max", CommQueue::SET_MAX},
	{"min", CommQueue::SET_MIN},
	{"freq", CommQueue::SET_FREQ},
	{"reset", CommQueue::RESET}
};

/**
 * Construct a command queue.
 *
 * We want to know the parent, where we can write changes to,
 * and which pipe to listen on.
 */
CommQueue::CommQueue(Throttle *parent, const char *pipe_fn) : Throt(parent)
{
	// Open the command pipe
	if ((comm_file = open(pipe_fn, O_RDONLY | O_NONBLOCK)) < 0)
		throw std::runtime_error(std::string("Couldn't open command pipe '") + pipe_fn + '\'');
}

/**
 * Destruct the command queue.
 *
 * We have to close the file manually here.
 */
CommQueue::~CommQueue()
{
	close(comm_file);
}

/**
 * Look for updates from the command pipe and process them.
 */
void CommQueue::update()
{
	char buf[LINE_LENGTH];
	ssize_t ret;
	do {
		ret = read(comm_file, buf, LINE_LENGTH-1);
		if (ret > 0)
			processCommand(std::string(buf, ret));
	} while (ret > 0);

	// This should be because there's nothing more to read
	if (ret != 0 && errno != EAGAIN)
		throw std::runtime_error("Read error while checking command pipe");
}

/**
 * Process a command coming through the pipe.
 */
void CommQueue::processCommand(const std::string &comm)
{
	std::istringstream stream(comm);
	std::string command;
	stream >> command;

	int value;
	switch (translate.find(command)->second) {
	case DEFAULT:		// we land here if "command" is not found
		DEBUG_PRINT("[CommQueue] Ignored unknown command: " << command);
		break;
	case SET_MIN:
		stream >> value;
		Throt->setMinTemp(value);
		DEBUG_PRINT("[CommQueue] Set minimum temperature to " << value);
		break;
	case SET_MAX:
		stream >> value;
		Throt->setMaxTemp(value);
		DEBUG_PRINT("[CommQueue] Set maximum temperature to " << value);
		break;
	case SET_FREQ:
		stream >> value;
		Throt->setOverrideFreq(value);
		DEBUG_PRINT("[CommQueue] Set frequency to " << value);
		break;
	case RESET:
		Throt->setOverrideFreq(0);
		DEBUG_PRINT("[CommQueue] Reset mechanism");
		break;
	}
}
<commit_msg>Simplification in constructor<commit_after>#include "throttle.hpp"
#include <unistd.h>
#include <fcntl.h>

/**
 * Read a configuration file.
 *
 * This function is guaranteed to read in all syntactically correct files, but
 * might also accept others.
 */
Conf::Conf(const char *config_fn) {
	// open the file
	std::ifstream conf_file(config_fn);
	if (!conf_file)
		throw std::runtime_error(std::string("Couldn't open config file '") + config_fn + '\'');

	// read every line and put it in the map
	char line[LINE_LENGTH];
	std::string name;

	// parse: first comes the name of the command
	while (conf_file >> name) {
		// if line starts with '#', ignore it
		if (name[0] == '#') {
			conf_file.ignore(LINE_LENGTH, '\n');
			continue;
		}

		conf_file.ignore(LINE_LENGTH, '=');
		conf_file.ignore(LINE_LENGTH, ' ');
		conf_file.getline(line, LINE_LENGTH);

		DEBUG_PRINT("[Conf] " << name << " = " << line);

		// write into map
		attributes[name] = std::string(line);
	}
}

/**
 * Translation table for a command queue.
 */
const std::map<std::string, CommQueue::Command> CommQueue::translate = {
	{"max", CommQueue::SET_MAX},
	{"min", CommQueue::SET_MIN},
	{"freq", CommQueue::SET_FREQ},
	{"reset", CommQueue::RESET}
};

/**
 * Construct a command queue.
 *
 * We want to know the parent, where we can write changes to,
 * and which pipe to listen on.
 */
CommQueue::CommQueue(Throttle *parent, const char *pipe_fn) : Throt(parent)
{
	// Open the command pipe
	comm_file = open(pipe_fn, O_RDONLY | O_NONBLOCK);

	if (comm_file < 0)
		throw std::runtime_error(std::string("Couldn't open command pipe '") + pipe_fn + '\'');
}

/**
 * Destruct the command queue.
 *
 * We have to close the file manually here.
 */
CommQueue::~CommQueue()
{
	close(comm_file);
}

/**
 * Look for updates from the command pipe and process them.
 */
void CommQueue::update()
{
	char buf[LINE_LENGTH];
	ssize_t ret;
	do {
		ret = read(comm_file, buf, LINE_LENGTH-1);
		if (ret > 0)
			processCommand(std::string(buf, ret));
	} while (ret > 0);

	// This should be because there's nothing more to read
	if (ret != 0 && errno != EAGAIN)
		throw std::runtime_error("Read error while checking command pipe");
}

/**
 * Process a command coming through the pipe.
 */
void CommQueue::processCommand(const std::string &comm)
{
	std::istringstream stream(comm);
	std::string command;
	stream >> command;

	int value;
	switch (translate.find(command)->second) {
	case DEFAULT:		// we land here if "command" is not found
		DEBUG_PRINT("[CommQueue] Ignored unknown command: " << command);
		break;
	case SET_MIN:
		stream >> value;
		Throt->setMinTemp(value);
		DEBUG_PRINT("[CommQueue] Set minimum temperature to " << value);
		break;
	case SET_MAX:
		stream >> value;
		Throt->setMaxTemp(value);
		DEBUG_PRINT("[CommQueue] Set maximum temperature to " << value);
		break;
	case SET_FREQ:
		stream >> value;
		Throt->setOverrideFreq(value);
		DEBUG_PRINT("[CommQueue] Set frequency to " << value);
		break;
	case RESET:
		Throt->setOverrideFreq(0);
		DEBUG_PRINT("[CommQueue] Reset mechanism");
		break;
	}
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "sal/config.h"
#include "sal/precppunit.hxx"

// autogenerated file with codegen.pl

#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/curve/b2dbeziertools.hxx>
#include <basegfx/range/b2dpolyrange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/numeric/ftools.hxx>

#include <boost/bind.hpp>

using namespace ::basegfx;

namespace basegfx2d
{

class genericclipper : public CppUnit::TestFixture
{
private:
    B2DPolygon aSelfIntersecting;
    B2DPolygon aShiftedRectangle;

public:
    // initialise your test code values here.
    void setUp()
    {
        aSelfIntersecting.append(B2DPoint(0,  0));
        aSelfIntersecting.append(B2DPoint(0,  100));
        aSelfIntersecting.append(B2DPoint(75, 100));
        aSelfIntersecting.append(B2DPoint(75, 50));
        aSelfIntersecting.append(B2DPoint(25, 50));
        aSelfIntersecting.append(B2DPoint(25, 150));
        aSelfIntersecting.append(B2DPoint(100,150));
        aSelfIntersecting.append(B2DPoint(100,0));
        aSelfIntersecting.setClosed(true);

        aShiftedRectangle = tools::createPolygonFromRect(
            B2DRange(0,90,20,150));
    }

    void tearDown()
    {}

    void validate(const char* pName,
                  const char* pValidSvgD,
                  B2DPolyPolygon (*pFunc)(const B2DPolyPolygon&, const B2DPolyPolygon&))
    {
        const B2DPolyPolygon aSelfIntersect(
            tools::prepareForPolygonOperation(aSelfIntersecting));
        const B2DPolyPolygon aRect(
            tools::prepareForPolygonOperation(aShiftedRectangle));
#if OSL_DEBUG_LEVEL > 2
        fprintf(stderr, "%s input LHS - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(
                        aSelfIntersect),
                    RTL_TEXTENCODING_UTF8).getStr() );
        fprintf(stderr, "%s input RHS - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(
                        aRect),
                    RTL_TEXTENCODING_UTF8).getStr() );
#endif

        const B2DPolyPolygon aRes=
            pFunc(aSelfIntersect, aRect);

#if OSL_DEBUG_LEVEL > 2
        fprintf(stderr, "%s - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(aRes),
                    RTL_TEXTENCODING_UTF8).getStr() );
#endif

        rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);

        CPPUNIT_ASSERT_MESSAGE(pName,
                               basegfx::tools::exportToSvgD(aRes) == aValid);
    }

    void validateOr()
    {
        const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm75 100v-50h-50v50z";
        validate("validateOr", pValid, &tools::solvePolygonOperationOr);
    }

    void validateXor()
    {
        const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm0 100h20v-10h-20zm75 0v-50h-50v50z";
        validate("validateXor", pValid, &tools::solvePolygonOperationXor);
    }

    void validateAnd()
    {
        const char* pValid="m0 100v-10h20v10z";
        validate("validateAnd", pValid, &tools::solvePolygonOperationAnd);
    }

    void validateDiff()
    {
        const char* pValid="m0 90v-90h100v150h-75v-50h-5v-10zm75 10v-50h-50v50z";
        validate("validateDiff", pValid, &tools::solvePolygonOperationDiff);
    }

    void checkCrossoverSolver()
    {
        B2DPolyPolygon aPoly;
        tools::importFromSvgD(
            aPoly,
            ::rtl::OUString(
                RTL_CONSTASCII_USTRINGPARAM(
                    "m0 0 v 5  h 3 h 1 h 1 h 1 v -2 v -3 z"
                    "m3 7 v -2 h 1 h 1 h 1 v -2 h 1 v 3 z")));

        tools::solveCrossovers(aPoly);
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(genericclipper);
    CPPUNIT_TEST(validateOr);
    CPPUNIT_TEST(validateXor);
    CPPUNIT_TEST(validateAnd);
    CPPUNIT_TEST(validateDiff);
    CPPUNIT_TEST(checkCrossoverSolver);
    CPPUNIT_TEST_SUITE_END();
};

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION(basegfx2d::genericclipper);
} // namespace basegfx2d

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Add more unit test coverage for generic clipper<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "sal/config.h"
#include "sal/precppunit.hxx"

// autogenerated file with codegen.pl

#include "cppunit/TestAssert.h"
#include "cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/curve/b2dcubicbezier.hxx>
#include <basegfx/curve/b2dbeziertools.hxx>
#include <basegfx/range/b2dpolyrange.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygoncutter.hxx>
#include <basegfx/polygon/b2dpolygonclipper.hxx>
#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <basegfx/numeric/ftools.hxx>

#include <boost/bind.hpp>

using namespace ::basegfx;

namespace basegfx2d
{

class genericclipper : public CppUnit::TestFixture
{
private:
    B2DPolygon aSelfIntersecting;
    B2DPolygon aShiftedRectangle;

public:
    // initialise your test code values here.
    void setUp()
    {
        aSelfIntersecting.append(B2DPoint(0,  0));
        aSelfIntersecting.append(B2DPoint(0,  100));
        aSelfIntersecting.append(B2DPoint(75, 100));
        aSelfIntersecting.append(B2DPoint(75, 50));
        aSelfIntersecting.append(B2DPoint(25, 50));
        aSelfIntersecting.append(B2DPoint(25, 150));
        aSelfIntersecting.append(B2DPoint(100,150));
        aSelfIntersecting.append(B2DPoint(100,0));
        aSelfIntersecting.setClosed(true);

        aShiftedRectangle = tools::createPolygonFromRect(
            B2DRange(0,90,20,150));
    }

    void tearDown()
    {}

    void validate(const char* pName,
                  const char* pValidSvgD,
                  B2DPolyPolygon (*pFunc)(const B2DPolyPolygon&, const B2DPolyPolygon&))
    {
        const B2DPolyPolygon aSelfIntersect(
            tools::prepareForPolygonOperation(aSelfIntersecting));
        const B2DPolyPolygon aRect(
            tools::prepareForPolygonOperation(aShiftedRectangle));
#if OSL_DEBUG_LEVEL > 2
        fprintf(stderr, "%s input LHS - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(
                        aSelfIntersect),
                    RTL_TEXTENCODING_UTF8).getStr() );
        fprintf(stderr, "%s input RHS - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(
                        aRect),
                    RTL_TEXTENCODING_UTF8).getStr() );
#endif

        const B2DPolyPolygon aRes=
            pFunc(aSelfIntersect, aRect);

#if OSL_DEBUG_LEVEL > 2
        fprintf(stderr, "%s - svg:d=\"%s\"\n",
                pName, rtl::OUStringToOString(
                    basegfx::tools::exportToSvgD(aRes),
                    RTL_TEXTENCODING_UTF8).getStr() );
#endif

        rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);

        CPPUNIT_ASSERT_MESSAGE(pName,
                               basegfx::tools::exportToSvgD(aRes) == aValid);
    }

    void validateOr()
    {
        const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm75 100v-50h-50v50z";
        validate("validateOr", pValid, &tools::solvePolygonOperationOr);
    }

    void validateXor()
    {
        const char* pValid="m0 0h100v150h-75v-50h-5v50h-20v-50-10zm0 100h20v-10h-20zm75 0v-50h-50v50z";
        validate("validateXor", pValid, &tools::solvePolygonOperationXor);
    }

    void validateAnd()
    {
        const char* pValid="m0 100v-10h20v10z";
        validate("validateAnd", pValid, &tools::solvePolygonOperationAnd);
    }

    void validateDiff()
    {
        const char* pValid="m0 90v-90h100v150h-75v-50h-5v-10zm75 10v-50h-50v50z";
        validate("validateDiff", pValid, &tools::solvePolygonOperationDiff);
    }

    void validateCrossover(const char* pName,
                           const char* pInputSvgD,
                           const char* pValidSvgD)
    {
        rtl::OUString aInput=rtl::OUString::createFromAscii(pInputSvgD);
        rtl::OUString aValid=rtl::OUString::createFromAscii(pValidSvgD);
        B2DPolyPolygon aInputPoly, aValidPoly;

        tools::importFromSvgD(aInputPoly, aInput);
        tools::importFromSvgD(aValidPoly, aValid);

        CPPUNIT_ASSERT_MESSAGE(
            pName,
            basegfx::tools::exportToSvgD(
                tools::solveCrossovers(aInputPoly)) == aValid);
    }

    void checkCrossoverSolver()
    {
        // partially intersecting polygons, with a common subsection
        validateCrossover(
            "partially intersecting",
            "m0 0 v 5  h 3 h 1 h 1 h 1 v -2 v -3 z"
              "m3 7 v -2 h 1 h 1 h 1 v -2 h 1 v 3 z",
            "m0 0v5h3 1 1 1v-2-3zm3 7v-2h1 1 1v-2h1v3z");

        // first polygon is identical to subset of second polygon
        validateCrossover(
            "full subset",
            "m0 0 v 5  h 3 h 1 h 1 v -5 z"
              "m3 10 v -5 h 1 h 1 v -5 h -5 v 5 h 3 z",
            "m0 0v5h3 1 1v-5zm3 10v-5zm1-5h1v-5h-5v5h3z");

        // first polygon is identical to subset of second polygon, but
        // oriented in the opposite direction
        validateCrossover(
            "full subset, opposite direction",
            "m0 0 v 5 h 3 h 1 h 1 v -5 z"
              "m3 10 v -5 h -1 h -1 h -1 v -5 h 5 v 5 h 2 z",
            "m0 0v5h1 1 1-1-1-1v-5h5v5-5zm4 5h1 2l-4 5v-5z");

        // first polygon is identical to subset of second polygon, and
        // has a curve segment (triggers different code path)
        validateCrossover(
            "full subset, plus curves",
            "m0 0 v 5  h 3 h 1 h 1 c 2 0 2 0 0 -5 z"
              "m3 10 v -5 h 1 h 1 c 2 0 2 0 0 -5 h -5 v 5 h 3 z",
            "m0 0v5h3 1 1c2 0 2 0 0-5zm3 10v-5zm1-5h1c2 0 2 0 0-5h-5v5h3z");
    }

    // Change the following lines only, if you add, remove or rename
    // member functions of the current class,
    // because these macros are need by auto register mechanism.

    CPPUNIT_TEST_SUITE(genericclipper);
    CPPUNIT_TEST(validateOr);
    CPPUNIT_TEST(validateXor);
    CPPUNIT_TEST(validateAnd);
    CPPUNIT_TEST(validateDiff);
    CPPUNIT_TEST(checkCrossoverSolver);
    CPPUNIT_TEST_SUITE_END();
};

// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION(basegfx2d::genericclipper);
} // namespace basegfx2d

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