<commit_before>// Copyright 2020 Google LLC
//
// 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
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iree/hal/vulkan/timepoint_util.h"

#include <memory>

#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/utility/utility.h"
#include "iree/base/tracing.h"
#include "iree/hal/vulkan/dynamic_symbols.h"
#include "iree/hal/vulkan/status_util.h"

namespace iree {
namespace hal {
namespace vulkan {

// static
void TimePointFence::Delete(TimePointFence* ptr) {
  ptr->pool()->ReleaseResolved(ptr);
}

VkResult TimePointFence::GetStatus() {
  absl::MutexLock lock(&status_mutex_);
  if (status_ == VK_NOT_READY) {
    const auto& device = pool()->logical_device();
    status_ = device->syms()->vkGetFenceStatus(*device, fence_);
  }
  return status_;
}

// static
StatusOr<ref_ptr<TimePointFencePool>> TimePointFencePool::Create(
    ref_ptr<VkDeviceHandle> logical_device) {
  IREE_TRACE_SCOPE0("TimePointFencePool::Create");
  ref_ptr<TimePointFencePool> pool(
      new TimePointFencePool(std::move(logical_device)));
  RETURN_IF_ERROR(pool->PreallocateFences());
  return pool;
}

TimePointFencePool::~TimePointFencePool() {
  IREE_TRACE_SCOPE0("TimePointFencePool::dtor");

  absl::MutexLock lock(&mutex_);
  int free_count = 0;
  for (auto* fence : free_fences_) {
    syms()->vkDestroyFence(*logical_device_, fence->value(),
                           logical_device_->allocator());
    ++free_count;
  }
  DCHECK_EQ(free_count, kMaxInFlightFenceCount);
  free_fences_.clear();
}

StatusOr<ref_ptr<TimePointFence>> TimePointFencePool::Acquire() {
  IREE_TRACE_SCOPE0("TimePointFencePool::Acquire");

  absl::MutexLock lock(&mutex_);
  if (free_fences_.empty()) {
    return ResourceExhaustedErrorBuilder(IREE_LOC)
           << "Fence pool out of free fences";
  }

  // To acquire from the pool, we:
  //   1) Pop from the front of the queue (reference count of 0);
  //   2) Release the unique_ptr, since lifetime will be managed by ref counts;
  //   3) Return as a raw RefObject with a reference count of 1;
  // When the reference count goes back to 0, it will be returned to the pool,
  // wrapped with unique_ptr.
  // When the pool is destroyed, all free fences are freed by unique_ptr
  // automatically.
  std::unique_ptr<TimePointFence> fence =
      free_fences_.take(free_fences_.front());
  return add_ref(fence.release());
}

void TimePointFencePool::ReleaseResolved(TimePointFence* fence) {
  IREE_TRACE_SCOPE0("TimePointFencePool::ReleaseResolved");
  VkFence f = fence->value();
  syms()->vkResetFences(*logical_device_, 1, &f);
  absl::MutexLock lock(&mutex_);
  free_fences_.push_back(absl::WrapUnique(fence));
}

TimePointFencePool::TimePointFencePool(ref_ptr<VkDeviceHandle> logical_device)
    : logical_device_(std::move(logical_device)) {}

const ref_ptr<DynamicSymbols>& TimePointFencePool::syms() const {
  return logical_device_->syms();
}

Status TimePointFencePool::PreallocateFences() {
  IREE_TRACE_SCOPE0("TimePointFencePool::PreallocateFences");

  VkFenceCreateInfo create_info;
  create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;

  std::array<std::unique_ptr<TimePointFence>, kMaxInFlightFenceCount> fences;
  {
    absl::MutexLock lock(&mutex_);
    for (int i = 0; i < fences.size(); ++i) {
      VkFence fence = VK_NULL_HANDLE;
      VK_RETURN_IF_ERROR(syms()->vkCreateFence(*logical_device_, &create_info,
                                               logical_device_->allocator(),
                                               &fence));
      fences[i] = absl::MakeUnique<TimePointFence>(this, fence);
    }
  }

  for (int i = 0; i < fences.size(); ++i) {
    // The `TimePointFence`s was created with an initial ref-count of one.
    // Decrease explicitly to zero so that later we can rely on the ref-count
    // reaching zero to auto-release the `TimePointFence` back to the free
    // list. As a nice side effect, this will also initialize the free list
    // with all newly created fences.
    // TODO: Might want to avoid acquiring and releasing the mutex for each
    // fence.
    fences[i].release()->ReleaseReference();
  }

  return OkStatus();
}

// static
StatusOr<ref_ptr<TimePointSemaphorePool>> TimePointSemaphorePool::Create(
    ref_ptr<VkDeviceHandle> logical_device) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::Create");
  ref_ptr<TimePointSemaphorePool> pool(
      new TimePointSemaphorePool(std::move(logical_device)));
  RETURN_IF_ERROR(pool->PreallocateSemaphores());
  return pool;
}

TimePointSemaphorePool::~TimePointSemaphorePool() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::dtor");

  absl::MutexLock lock(&mutex_);

  DCHECK_EQ(free_semaphores_.size(), kMaxInFlightSemaphoreCount);
  free_semaphores_.clear();

  for (auto& semaphore : storage_) {
    syms()->vkDestroySemaphore(*logical_device_, semaphore.semaphore,
                               logical_device_->allocator());
  }
}

StatusOr<TimePointSemaphore*> TimePointSemaphorePool::Acquire() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::Acquire");

  absl::MutexLock lock(&mutex_);
  if (free_semaphores_.empty()) {
    return ResourceExhaustedErrorBuilder(IREE_LOC)
           << "Semaphore pool out of free semaphores";
  }

  auto* semaphore = free_semaphores_.front();
  free_semaphores_.pop_front();
  return semaphore;
}

void TimePointSemaphorePool::ReleaseResolved(
    IntrusiveList<TimePointSemaphore>* semaphores) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::ReleaseResolved");

  for (auto* semaphore : *semaphores) {
    DCHECK(!semaphore->signal_fence && !semaphore->wait_fence);
    semaphore->value = UINT64_MAX;
  }

  absl::MutexLock lock(&mutex_);
  free_semaphores_.merge_from(semaphores);
}

void TimePointSemaphorePool::ReleaseUnresolved(
    IntrusiveList<TimePointSemaphore>* semaphores) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::ReleaseUnresolved");

  for (auto* semaphore : *semaphores) {
    semaphore->signal_fence = nullptr;
    semaphore->wait_fence = nullptr;
    semaphore->value = UINT64_MAX;
  }

  absl::MutexLock lock(&mutex_);
  free_semaphores_.merge_from(semaphores);
}

TimePointSemaphorePool::TimePointSemaphorePool(
    ref_ptr<VkDeviceHandle> logical_device)
    : logical_device_(std::move(logical_device)) {}

const ref_ptr<DynamicSymbols>& TimePointSemaphorePool::syms() const {
  return logical_device_->syms();
}

Status TimePointSemaphorePool::PreallocateSemaphores() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::PreallocateSemaphores");

  VkSemaphoreCreateInfo create_info;
  create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;

  absl::MutexLock lock(&mutex_);
  for (int i = 0; i < kMaxInFlightSemaphoreCount; ++i) {
    auto* semaphore = &storage_[i];
    VK_RETURN_IF_ERROR(syms()->vkCreateSemaphore(*logical_device_, &create_info,
                                                 logical_device_->allocator(),
                                                 &semaphore->semaphore));
    free_semaphores_.push_back(semaphore);
  }

  return OkStatus();
}

}  // namespace vulkan
}  // namespace hal
}  // namespace iree
<commit_msg>Fix make_unique casing. (#2350)<commit_after>// Copyright 2020 Google LLC
//
// 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
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iree/hal/vulkan/timepoint_util.h"

#include <memory>

#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/utility/utility.h"
#include "iree/base/tracing.h"
#include "iree/hal/vulkan/dynamic_symbols.h"
#include "iree/hal/vulkan/status_util.h"

namespace iree {
namespace hal {
namespace vulkan {

// static
void TimePointFence::Delete(TimePointFence* ptr) {
  ptr->pool()->ReleaseResolved(ptr);
}

VkResult TimePointFence::GetStatus() {
  absl::MutexLock lock(&status_mutex_);
  if (status_ == VK_NOT_READY) {
    const auto& device = pool()->logical_device();
    status_ = device->syms()->vkGetFenceStatus(*device, fence_);
  }
  return status_;
}

// static
StatusOr<ref_ptr<TimePointFencePool>> TimePointFencePool::Create(
    ref_ptr<VkDeviceHandle> logical_device) {
  IREE_TRACE_SCOPE0("TimePointFencePool::Create");
  ref_ptr<TimePointFencePool> pool(
      new TimePointFencePool(std::move(logical_device)));
  RETURN_IF_ERROR(pool->PreallocateFences());
  return pool;
}

TimePointFencePool::~TimePointFencePool() {
  IREE_TRACE_SCOPE0("TimePointFencePool::dtor");

  absl::MutexLock lock(&mutex_);
  int free_count = 0;
  for (auto* fence : free_fences_) {
    syms()->vkDestroyFence(*logical_device_, fence->value(),
                           logical_device_->allocator());
    ++free_count;
  }
  DCHECK_EQ(free_count, kMaxInFlightFenceCount);
  free_fences_.clear();
}

StatusOr<ref_ptr<TimePointFence>> TimePointFencePool::Acquire() {
  IREE_TRACE_SCOPE0("TimePointFencePool::Acquire");

  absl::MutexLock lock(&mutex_);
  if (free_fences_.empty()) {
    return ResourceExhaustedErrorBuilder(IREE_LOC)
           << "Fence pool out of free fences";
  }

  // To acquire from the pool, we:
  //   1) Pop from the front of the queue (reference count of 0);
  //   2) Release the unique_ptr, since lifetime will be managed by ref counts;
  //   3) Return as a raw RefObject with a reference count of 1;
  // When the reference count goes back to 0, it will be returned to the pool,
  // wrapped with unique_ptr.
  // When the pool is destroyed, all free fences are freed by unique_ptr
  // automatically.
  std::unique_ptr<TimePointFence> fence =
      free_fences_.take(free_fences_.front());
  return add_ref(fence.release());
}

void TimePointFencePool::ReleaseResolved(TimePointFence* fence) {
  IREE_TRACE_SCOPE0("TimePointFencePool::ReleaseResolved");
  VkFence f = fence->value();
  syms()->vkResetFences(*logical_device_, 1, &f);
  absl::MutexLock lock(&mutex_);
  free_fences_.push_back(absl::WrapUnique(fence));
}

TimePointFencePool::TimePointFencePool(ref_ptr<VkDeviceHandle> logical_device)
    : logical_device_(std::move(logical_device)) {}

const ref_ptr<DynamicSymbols>& TimePointFencePool::syms() const {
  return logical_device_->syms();
}

Status TimePointFencePool::PreallocateFences() {
  IREE_TRACE_SCOPE0("TimePointFencePool::PreallocateFences");

  VkFenceCreateInfo create_info;
  create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;

  std::array<std::unique_ptr<TimePointFence>, kMaxInFlightFenceCount> fences;
  {
    absl::MutexLock lock(&mutex_);
    for (int i = 0; i < fences.size(); ++i) {
      VkFence fence = VK_NULL_HANDLE;
      VK_RETURN_IF_ERROR(syms()->vkCreateFence(*logical_device_, &create_info,
                                               logical_device_->allocator(),
                                               &fence));
      fences[i] = absl::make_unique<TimePointFence>(this, fence);
    }
  }

  for (int i = 0; i < fences.size(); ++i) {
    // The `TimePointFence`s was created with an initial ref-count of one.
    // Decrease explicitly to zero so that later we can rely on the ref-count
    // reaching zero to auto-release the `TimePointFence` back to the free
    // list. As a nice side effect, this will also initialize the free list
    // with all newly created fences.
    // TODO: Might want to avoid acquiring and releasing the mutex for each
    // fence.
    fences[i].release()->ReleaseReference();
  }

  return OkStatus();
}

// static
StatusOr<ref_ptr<TimePointSemaphorePool>> TimePointSemaphorePool::Create(
    ref_ptr<VkDeviceHandle> logical_device) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::Create");
  ref_ptr<TimePointSemaphorePool> pool(
      new TimePointSemaphorePool(std::move(logical_device)));
  RETURN_IF_ERROR(pool->PreallocateSemaphores());
  return pool;
}

TimePointSemaphorePool::~TimePointSemaphorePool() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::dtor");

  absl::MutexLock lock(&mutex_);

  DCHECK_EQ(free_semaphores_.size(), kMaxInFlightSemaphoreCount);
  free_semaphores_.clear();

  for (auto& semaphore : storage_) {
    syms()->vkDestroySemaphore(*logical_device_, semaphore.semaphore,
                               logical_device_->allocator());
  }
}

StatusOr<TimePointSemaphore*> TimePointSemaphorePool::Acquire() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::Acquire");

  absl::MutexLock lock(&mutex_);
  if (free_semaphores_.empty()) {
    return ResourceExhaustedErrorBuilder(IREE_LOC)
           << "Semaphore pool out of free semaphores";
  }

  auto* semaphore = free_semaphores_.front();
  free_semaphores_.pop_front();
  return semaphore;
}

void TimePointSemaphorePool::ReleaseResolved(
    IntrusiveList<TimePointSemaphore>* semaphores) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::ReleaseResolved");

  for (auto* semaphore : *semaphores) {
    DCHECK(!semaphore->signal_fence && !semaphore->wait_fence);
    semaphore->value = UINT64_MAX;
  }

  absl::MutexLock lock(&mutex_);
  free_semaphores_.merge_from(semaphores);
}

void TimePointSemaphorePool::ReleaseUnresolved(
    IntrusiveList<TimePointSemaphore>* semaphores) {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::ReleaseUnresolved");

  for (auto* semaphore : *semaphores) {
    semaphore->signal_fence = nullptr;
    semaphore->wait_fence = nullptr;
    semaphore->value = UINT64_MAX;
  }

  absl::MutexLock lock(&mutex_);
  free_semaphores_.merge_from(semaphores);
}

TimePointSemaphorePool::TimePointSemaphorePool(
    ref_ptr<VkDeviceHandle> logical_device)
    : logical_device_(std::move(logical_device)) {}

const ref_ptr<DynamicSymbols>& TimePointSemaphorePool::syms() const {
  return logical_device_->syms();
}

Status TimePointSemaphorePool::PreallocateSemaphores() {
  IREE_TRACE_SCOPE0("TimePointSemaphorePool::PreallocateSemaphores");

  VkSemaphoreCreateInfo create_info;
  create_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;

  absl::MutexLock lock(&mutex_);
  for (int i = 0; i < kMaxInFlightSemaphoreCount; ++i) {
    auto* semaphore = &storage_[i];
    VK_RETURN_IF_ERROR(syms()->vkCreateSemaphore(*logical_device_, &create_info,
                                                 logical_device_->allocator(),
                                                 &semaphore->semaphore));
    free_semaphores_.push_back(semaphore);
  }

  return OkStatus();
}

}  // namespace vulkan
}  // namespace hal
}  // namespace iree
<|endoftext|>


<commit_before>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <uv.h>
#include "storj.h"

using namespace v8;
using namespace Nan;

void Timestamp(const v8::FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    uint64_t timestamp = storj_util_timestamp();
    Local<Number> timestamp_local = Number::New(isolate, timestamp);

    args.GetReturnValue().Set(timestamp_local);
}

void MnemonicCheck(const v8::FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    String::Utf8Value str(args[0]);
    const char *mnemonic = *str;

    bool mnemonic_check_result = storj_mnemonic_check(mnemonic);
    Local<Boolean> mnemonic_check_result_local = Boolean::New(isolate, mnemonic_check_result);

    args.GetReturnValue().Set(mnemonic_check_result_local);
}

void GetInfoCallback(uv_work_t *work_req, int status) {
    Nan::HandleScope scope;

    json_request_t *req = (json_request_t *) work_req->data;

    Nan::Callback *callback = (Nan::Callback*)req->handle;

    const char *result_str = json_object_to_json_string(req->response);

    Local<Value> argv[] = {
        Nan::Null(),
        v8::JSON::Parse(Nan::New(result_str).ToLocalChecked())
    };

    callback->Call(2, argv);
    free(req);
    free(work_req);
}

void GetInfo(const Nan::FunctionCallbackInfo<Value>& args) {
    if (args.This()->InternalFieldCount() != 1)
    {
        Nan::ThrowError("Environment not available for instance");
    }

    storj_env_t *env = (storj_env_t *)args.This()->GetAlignedPointerFromInternalField(0);

    Nan::Callback *callback = new Nan::Callback(args[0].As<Function>());

    storj_bridge_get_info(env, (void *) callback, GetInfoCallback);
}

void GetBucketsCallback(uv_work_t *work_req, int status) {
    Nan::HandleScope scope;

    json_request_t *req = (json_request_t *) work_req->data;

    Nan::Callback *callback = (Nan::Callback*)req->handle;

    const char *result_str = json_object_to_json_string(req->response);

    printf("%s\n", result_str);
    printf("status code: %i, error code: %i\n", req->status_code, req->error_code);
    Local<Value> argv[] = {
        Nan::Null(),
        v8::JSON::Parse(Nan::New(result_str).ToLocalChecked())
    };

    callback->Call(2, argv);
    free(req);
    free(work_req);
}

void GetBuckets(const Nan::FunctionCallbackInfo<Value>& args) {
    if (args.This()->InternalFieldCount() != 1)
    {
        Nan::ThrowError("Environment not available for instance");
    }

    storj_env_t *env = (storj_env_t *)args.This()->GetAlignedPointerFromInternalField(0);

    Nan::Callback *callback = new Nan::Callback(args[0].As<Function>());

    storj_bridge_get_buckets(env, (void *) callback, GetBucketsCallback);
}

void Environment(const v8::FunctionCallbackInfo<Value>& args) {
    Nan::EscapableHandleScope scope;

    v8::Local<v8::Object> options = args[0].As<v8::Object>();

    v8::Local<v8::String> bridgeUrl = options->Get(Nan::New("bridgeUrl").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> bridgeUser = options->Get(Nan::New("bridgeUser").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> bridgePass = options->Get(Nan::New("bridgePass").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> encryptionKey = options->Get(Nan::New("encryptionKey").ToLocalChecked()).As<v8::String>();

    v8::Local<v8::FunctionTemplate> constructor = Nan::New<v8::FunctionTemplate>();
    constructor->SetClassName(Nan::New("Environment").ToLocalChecked());
    constructor->InstanceTemplate()->SetInternalFieldCount(1);

    Nan::SetPrototypeMethod(constructor, "getInfo", GetInfo);
    Nan::SetPrototypeMethod(constructor, "getBuckets", GetBuckets);

    Nan::MaybeLocal<v8::Object> maybeInstance;
    v8::Local<v8::Object> instance;

    v8::Local<v8::Value> argv[] = {};
    maybeInstance = Nan::NewInstance(constructor->GetFunction(), 0, argv);

    if (maybeInstance.IsEmpty()) {
        Nan::ThrowError("Could not create new Storj instance");
    } else {
        instance = maybeInstance.ToLocalChecked();
    }

    // Bridge URL handling

    String::Utf8Value _bridgeUrl(bridgeUrl);
    const char *url = *_bridgeUrl;
    char proto[6];
    char host[100];
    int port = 0;
    sscanf(url, "%5[^://]://%99[^:/]:%99d", proto, host, &port);
    if (port == 0) {
        if (strcmp(proto, "http") == 0) {
            port = 80;
        } else {
            port = 443;
        }
    }

    // V8 types to C types

    String::Utf8Value _bridgeUser(bridgeUser);
    const char *user = *_bridgeUser;
    String::Utf8Value _bridgePass(bridgePass);
    const char *pass = *_bridgePass;
    String::Utf8Value _encryptionKey(encryptionKey);
    const char *mnemonic = *_encryptionKey;

    // Setup option structs

    storj_bridge_options_t bridge_options = {};
    bridge_options.proto = proto;
    bridge_options.host  = host;
    bridge_options.port  = port;
    bridge_options.user  = user;
    bridge_options.pass  = pass;

    storj_encrypt_options_t encrypt_options = {};
    encrypt_options.mnemonic = mnemonic;

    storj_http_options_t http_options = {};
    http_options.user_agent = "storj-test";
    http_options.low_speed_limit = STORJ_LOW_SPEED_LIMIT;
    http_options.low_speed_time = STORJ_LOW_SPEED_TIME;
    http_options.timeout = STORJ_HTTP_TIMEOUT;

    storj_log_options_t log_options = {};
    log_options.logger = NULL;
    log_options.level = 0;

    // Initialize environment

    storj_env_t *env = storj_init_env(&bridge_options,
                                      &encrypt_options,
                                      &http_options,
                                      &log_options);

    // Use Node.js default event loop that will already be running
    env->loop = uv_default_loop();

    // Pass along the environment so it can be accessed by methods
    instance->SetAlignedPointerInInternalField(0, env);

    args.GetReturnValue().Set(scope.Escape(instance));
}

void init(Handle<Object> exports) {
    NODE_SET_METHOD(exports, "Environment", Environment);
    NODE_SET_METHOD(exports, "utilTimestamp", Timestamp);
    NODE_SET_METHOD(exports, "mnemonicCheck", MnemonicCheck);
}

NODE_MODULE(storj, init);
<commit_msg>Use correct type for buckets call<commit_after>#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <uv.h>
#include "storj.h"

using namespace v8;
using namespace Nan;

void Timestamp(const v8::FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    uint64_t timestamp = storj_util_timestamp();
    Local<Number> timestamp_local = Number::New(isolate, timestamp);

    args.GetReturnValue().Set(timestamp_local);
}

void MnemonicCheck(const v8::FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    String::Utf8Value str(args[0]);
    const char *mnemonic = *str;

    bool mnemonic_check_result = storj_mnemonic_check(mnemonic);
    Local<Boolean> mnemonic_check_result_local = Boolean::New(isolate, mnemonic_check_result);

    args.GetReturnValue().Set(mnemonic_check_result_local);
}

void GetInfoCallback(uv_work_t *work_req, int status) {
    Nan::HandleScope scope;

    json_request_t *req = (json_request_t *) work_req->data;

    Nan::Callback *callback = (Nan::Callback*)req->handle;

    const char *result_str = json_object_to_json_string(req->response);

    Local<Value> argv[] = {
        Nan::Null(),
        v8::JSON::Parse(Nan::New(result_str).ToLocalChecked())
    };

    callback->Call(2, argv);
    free(req);
    free(work_req);
}

void GetInfo(const Nan::FunctionCallbackInfo<Value>& args) {
    if (args.This()->InternalFieldCount() != 1)
    {
        Nan::ThrowError("Environment not available for instance");
    }

    storj_env_t *env = (storj_env_t *)args.This()->GetAlignedPointerFromInternalField(0);

    Nan::Callback *callback = new Nan::Callback(args[0].As<Function>());

    storj_bridge_get_info(env, (void *) callback, GetInfoCallback);
}

void GetBucketsCallback(uv_work_t *work_req, int status) {
    Nan::HandleScope scope;

    get_buckets_request_t *req = (get_buckets_request_t *) work_req->data;

    Nan::Callback *callback = (Nan::Callback*)req->handle;

    const char *result_str = json_object_to_json_string(req->response);

    printf("%s\n", result_str);
    printf("status code: %i, error code: %i\n", req->status_code, req->error_code);
    Local<Value> argv[] = {
        Nan::Null(),
        v8::JSON::Parse(Nan::New(result_str).ToLocalChecked())
    };

    callback->Call(2, argv);
    free(req);
    free(work_req);
}

void GetBuckets(const Nan::FunctionCallbackInfo<Value>& args) {
    if (args.This()->InternalFieldCount() != 1)
    {
        Nan::ThrowError("Environment not available for instance");
    }

    storj_env_t *env = (storj_env_t *)args.This()->GetAlignedPointerFromInternalField(0);

    Nan::Callback *callback = new Nan::Callback(args[0].As<Function>());

    storj_bridge_get_buckets(env, (void *) callback, GetBucketsCallback);
}

void Environment(const v8::FunctionCallbackInfo<Value>& args) {
    Nan::EscapableHandleScope scope;

    v8::Local<v8::Object> options = args[0].As<v8::Object>();

    v8::Local<v8::String> bridgeUrl = options->Get(Nan::New("bridgeUrl").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> bridgeUser = options->Get(Nan::New("bridgeUser").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> bridgePass = options->Get(Nan::New("bridgePass").ToLocalChecked()).As<v8::String>();
    v8::Local<v8::String> encryptionKey = options->Get(Nan::New("encryptionKey").ToLocalChecked()).As<v8::String>();

    v8::Local<v8::FunctionTemplate> constructor = Nan::New<v8::FunctionTemplate>();
    constructor->SetClassName(Nan::New("Environment").ToLocalChecked());
    constructor->InstanceTemplate()->SetInternalFieldCount(1);

    Nan::SetPrototypeMethod(constructor, "getInfo", GetInfo);
    Nan::SetPrototypeMethod(constructor, "getBuckets", GetBuckets);

    Nan::MaybeLocal<v8::Object> maybeInstance;
    v8::Local<v8::Object> instance;

    v8::Local<v8::Value> argv[] = {};
    maybeInstance = Nan::NewInstance(constructor->GetFunction(), 0, argv);

    if (maybeInstance.IsEmpty()) {
        Nan::ThrowError("Could not create new Storj instance");
    } else {
        instance = maybeInstance.ToLocalChecked();
    }

    // Bridge URL handling

    String::Utf8Value _bridgeUrl(bridgeUrl);
    const char *url = *_bridgeUrl;
    char proto[6];
    char host[100];
    int port = 0;
    sscanf(url, "%5[^://]://%99[^:/]:%99d", proto, host, &port);
    if (port == 0) {
        if (strcmp(proto, "http") == 0) {
            port = 80;
        } else {
            port = 443;
        }
    }

    // V8 types to C types

    String::Utf8Value _bridgeUser(bridgeUser);
    const char *user = *_bridgeUser;
    String::Utf8Value _bridgePass(bridgePass);
    const char *pass = *_bridgePass;
    String::Utf8Value _encryptionKey(encryptionKey);
    const char *mnemonic = *_encryptionKey;

    // Setup option structs

    storj_bridge_options_t bridge_options = {};
    bridge_options.proto = proto;
    bridge_options.host  = host;
    bridge_options.port  = port;
    bridge_options.user  = user;
    bridge_options.pass  = pass;

    storj_encrypt_options_t encrypt_options = {};
    encrypt_options.mnemonic = mnemonic;

    storj_http_options_t http_options = {};
    http_options.user_agent = "storj-test";
    http_options.low_speed_limit = STORJ_LOW_SPEED_LIMIT;
    http_options.low_speed_time = STORJ_LOW_SPEED_TIME;
    http_options.timeout = STORJ_HTTP_TIMEOUT;

    storj_log_options_t log_options = {};
    log_options.logger = NULL;
    log_options.level = 0;

    // Initialize environment

    storj_env_t *env = storj_init_env(&bridge_options,
                                      &encrypt_options,
                                      &http_options,
                                      &log_options);

    // Use Node.js default event loop that will already be running
    env->loop = uv_default_loop();

    // Pass along the environment so it can be accessed by methods
    instance->SetAlignedPointerInInternalField(0, env);

    args.GetReturnValue().Set(scope.Escape(instance));
}

void init(Handle<Object> exports) {
    NODE_SET_METHOD(exports, "Environment", Environment);
    NODE_SET_METHOD(exports, "utilTimestamp", Timestamp);
    NODE_SET_METHOD(exports, "mnemonicCheck", MnemonicCheck);
}

NODE_MODULE(storj, init);
<|endoftext|>


<commit_before>#include "mag3110.h"

mag3110::mag3110() {
  read_position = 0;
  write_position = 0;
  fill = 0;
}

mag3110::~mag3110() {}

byte mag3110::fastread(void){
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_X_REG);              // x MSB reg
  Wire.endTransmission();       // stop transmitting

  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
  byte response = Wire.requestFrom(MAG_ADDR, 6);
  if (response == 6){  // request 6 bytes, if we get them all, great, if not ignore
    x[write_position] = Wire.read() << 8; // receive the byte
    x[write_position] = x[write_position] | Wire.read(); // receive the byte
    y[write_position] = Wire.read() << 8; // receive the byte
    y[write_position] = y[write_position] | Wire.read(); // receive the byte
    z[write_position] = Wire.read() << 8; // receive the byte
    z[write_position] = z[write_position] | Wire.read(); // receive the byte
    write_position = (write_position + 1) % MAG_BUFFER_DEPTH;          // Move the write position into the next spot so its clearly ready
    fill ++;
    return 0;
  }
  else {
    return 1;
  }
}

void mag3110::config(bool active_mode, bool auto_restart){
  byte config_reg = 0;
  if (active_mode){
    config_reg |= MAG_ACTIVE_MODE;
  }
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_CONFIG_REG1);      // select control register 1
  Wire.write(config_reg);           // Send config data
  Wire.endTransmission();           // stop transmitting

  delay(15);                        //Let config settle?

  config_reg = 0;
  if (auto_restart){
    config_reg |= MAG_AUTO_RESTART;
  }
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_CONFIG_REG2);      // select control register 2
  Wire.write(config_reg);           // Send config data
  Wire.endTransmission();           // stop transmitting
}

int16_t mag3110::getx(){
  return x[read_position];
}

int16_t mag3110::gety(){
  return y[read_position];
}

int16_t mag3110::getz(){
  return z[read_position];
}

byte mag3110::available(){
  return fill;
}

void mag3110::advance(){
  read_position = (read_position + 1) % MAG_BUFFER_DEPTH;
  fill --;
}

int16_t mag3110::readx(){
  return mag3110::read(MAG_X_REG);
}

int16_t mag3110::ready(){
  return mag3110::read(MAG_Y_REG);
}

int16_t mag3110::readz(){
  return mag3110::read(MAG_Z_REG);
}

int16_t mag3110::read(byte start_offset){

  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(start_offset);              // z MSB reg
  Wire.endTransmission();       // stop transmitting

  delayMicroseconds(2); //needs at least 1.3us free time between start and stop

  Wire.requestFrom(MAG_ADDR, 2); // request 2 bytes
  while(Wire.available() < 2)    // slave may send less than requested
    {
    }
  int result = Wire.read() << 8; // receive the high byte
  result |= Wire.read();
  return result;
}
<commit_msg>don't loop forever waiting on data that will never come - this was a hack I figured I might use, but I dont - beware<commit_after>#include "mag3110.h"

mag3110::mag3110() {
  read_position = 0;
  write_position = 0;
  fill = 0;
}

mag3110::~mag3110() {}

byte mag3110::fastread(void){
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_X_REG);              // x MSB reg
  Wire.endTransmission();       // stop transmitting

  delayMicroseconds(2); //needs at least 1.3us free time between start and stop
  byte response = Wire.requestFrom(MAG_ADDR, 6);
  if (response == 6){  // request 6 bytes, if we get them all, great, if not ignore
    x[write_position] = Wire.read() << 8; // receive the byte
    x[write_position] = x[write_position] | Wire.read(); // receive the byte
    y[write_position] = Wire.read() << 8; // receive the byte
    y[write_position] = y[write_position] | Wire.read(); // receive the byte
    z[write_position] = Wire.read() << 8; // receive the byte
    z[write_position] = z[write_position] | Wire.read(); // receive the byte
    write_position = (write_position + 1) % MAG_BUFFER_DEPTH;          // Move the write position into the next spot so its clearly ready
    fill ++;
    return 0;
  }
  else {
    return 1;
  }
}

void mag3110::config(bool active_mode, bool auto_restart){
  byte config_reg = 0;
  if (active_mode){
    config_reg |= MAG_ACTIVE_MODE;
  }
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_CONFIG_REG1);      // select control register 1
  Wire.write(config_reg);           // Send config data
  Wire.endTransmission();           // stop transmitting

  delay(15);                        //Let config settle?

  config_reg = 0;
  if (auto_restart){
    config_reg |= MAG_AUTO_RESTART;
  }
  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(MAG_CONFIG_REG2);      // select control register 2
  Wire.write(config_reg);           // Send config data
  Wire.endTransmission();           // stop transmitting
}

int16_t mag3110::getx(){
  return x[read_position];
}

int16_t mag3110::gety(){
  return y[read_position];
}

int16_t mag3110::getz(){
  return z[read_position];
}

byte mag3110::available(){
  return fill;
}

void mag3110::advance(){
  read_position = (read_position + 1) % MAG_BUFFER_DEPTH;
  fill --;
}

int16_t mag3110::readx(){
  return mag3110::read(MAG_X_REG);
}

int16_t mag3110::ready(){
  return mag3110::read(MAG_Y_REG);
}

int16_t mag3110::readz(){
  return mag3110::read(MAG_Z_REG);
}

int16_t mag3110::read(byte start_offset){

  Wire.beginTransmission(MAG_ADDR); // transmit to device 0x0E
  Wire.write(start_offset);              // z MSB reg
  Wire.endTransmission();       // stop transmitting

  delayMicroseconds(2); //needs at least 1.3us free time between start and stop

  if (Wire.requestFrom(MAG_ADDR, 2) != 2){
    return 0; // This is ghetto...  should really have a way to signal an error
  };
  int result = Wire.read() << 8; // receive the high byte
  result |= Wire.read();
  return result;
}
<|endoftext|>


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

enum class EStickerAttributeType
{
	Index,
	Wear,
	Scale,
	Rotation
};

static auto s_econ_item_interface_wrapper_offset = std::uint16_t(0);

struct GetStickerAttributeBySlotIndexFloat
{
	static auto __fastcall hooked(void* thisptr, void*, const int slot,
		const EStickerAttributeType attribute, const float unknown) -> float
	{
		auto item = reinterpret_cast<sdk::C_BaseAttributableItem*>(std::uintptr_t(thisptr) - s_econ_item_interface_wrapper_offset);

		const auto defindex = item->GetItemDefinitionIndex();

		auto config = g_config.get_by_definition_index(defindex);

		if(config)
		{
			switch(attribute)
			{
			case EStickerAttributeType::Wear:
				return config->stickers.at(slot).wear;
			case EStickerAttributeType::Scale:
				return config->stickers.at(slot).scale;
			case EStickerAttributeType::Rotation:
				return config->stickers.at(slot).rotation;
			default:
				break;
			}
		}

		return m_original(thisptr, nullptr, slot, attribute, unknown);
	}

	static decltype(&hooked) m_original;
};

decltype(GetStickerAttributeBySlotIndexFloat::m_original) GetStickerAttributeBySlotIndexFloat::m_original;

struct GetStickerAttributeBySlotIndexInt
{
	static auto __fastcall hooked(void* thisptr, void*, const int slot,
		const EStickerAttributeType attribute, const int unknown) -> int
	{
		auto item = reinterpret_cast<sdk::C_BaseAttributableItem*>(std::uintptr_t(thisptr) - s_econ_item_interface_wrapper_offset);

		if(attribute == EStickerAttributeType::Index)
		{
			const auto defindex = item->GetItemDefinitionIndex();

			auto config = g_config.get_by_definition_index(defindex);

			if(config)
				return config->stickers.at(slot).kit_index;
		}

		return m_original(thisptr, nullptr, slot, attribute, unknown);
	}

	static decltype(&hooked) m_original;
};

decltype(GetStickerAttributeBySlotIndexInt::m_original) GetStickerAttributeBySlotIndexInt::m_original;

auto apply_sticker_changer(sdk::C_BaseAttributableItem* item) -> void
{
	if(!s_econ_item_interface_wrapper_offset)
		s_econ_item_interface_wrapper_offset = netvar_manager::get().get_offset(FNV("CBaseAttributableItem->m_Item")) + 0xC;

	vmt_multi_hook hook;

	const auto econ_item_interface_wrapper = std::uintptr_t(item) + s_econ_item_interface_wrapper_offset;

	if(hook.initialize_and_hook_instance(reinterpret_cast<void*>(econ_item_interface_wrapper)))
	{
		hook.apply_hook<GetStickerAttributeBySlotIndexFloat>(4);
		hook.apply_hook<GetStickerAttributeBySlotIndexInt>(5);
	}
}<commit_msg>fix big ass memory leak rofl<commit_after>/* This file is part of nSkinz by namazso, licensed under the MIT license:
*
* MIT License
*
* Copyright (c) namazso 2018
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <cstring>
#include "SDK.hpp"
#include "config.hpp"

enum class EStickerAttributeType
{
	Index,
	Wear,
	Scale,
	Rotation
};

static auto s_econ_item_interface_wrapper_offset = std::uint16_t(0);

struct GetStickerAttributeBySlotIndexFloat
{
	static auto __fastcall hooked(void* thisptr, void*, const int slot,
		const EStickerAttributeType attribute, const float unknown) -> float
	{
		auto item = reinterpret_cast<sdk::C_BaseAttributableItem*>(std::uintptr_t(thisptr) - s_econ_item_interface_wrapper_offset);

		const auto defindex = item->GetItemDefinitionIndex();

		auto config = g_config.get_by_definition_index(defindex);

		if(config)
		{
			switch(attribute)
			{
			case EStickerAttributeType::Wear:
				return config->stickers.at(slot).wear;
			case EStickerAttributeType::Scale:
				return config->stickers.at(slot).scale;
			case EStickerAttributeType::Rotation:
				return config->stickers.at(slot).rotation;
			default:
				break;
			}
		}

		return m_original(thisptr, nullptr, slot, attribute, unknown);
	}

	static decltype(&hooked) m_original;
};

decltype(GetStickerAttributeBySlotIndexFloat::m_original) GetStickerAttributeBySlotIndexFloat::m_original;

struct GetStickerAttributeBySlotIndexInt
{
	static auto __fastcall hooked(void* thisptr, void*, const int slot,
		const EStickerAttributeType attribute, const int unknown) -> int
	{
		auto item = reinterpret_cast<sdk::C_BaseAttributableItem*>(std::uintptr_t(thisptr) - s_econ_item_interface_wrapper_offset);

		if(attribute == EStickerAttributeType::Index)
		{
			const auto defindex = item->GetItemDefinitionIndex();

			auto config = g_config.get_by_definition_index(defindex);

			if(config)
				return config->stickers.at(slot).kit_index;
		}

		return m_original(thisptr, nullptr, slot, attribute, unknown);
	}

	static decltype(&hooked) m_original;
};

decltype(GetStickerAttributeBySlotIndexInt::m_original) GetStickerAttributeBySlotIndexInt::m_original;

auto apply_sticker_changer(sdk::C_BaseAttributableItem* item) -> void
{
	if(!s_econ_item_interface_wrapper_offset)
		s_econ_item_interface_wrapper_offset = netvar_manager::get().get_offset(FNV("CBaseAttributableItem->m_Item")) + 0xC;

	static vmt_multi_hook hook;

	const auto econ_item_interface_wrapper = std::uintptr_t(item) + s_econ_item_interface_wrapper_offset;

	if(hook.initialize_and_hook_instance(reinterpret_cast<void*>(econ_item_interface_wrapper)))
	{
		hook.apply_hook<GetStickerAttributeBySlotIndexFloat>(4);
		hook.apply_hook<GetStickerAttributeBySlotIndexInt>(5);
	}
}<|endoftext|>


<commit_before>#include <RcppArmadillo.h>

//#include "summary_inf_mod.h"

// Inference goodies
#include "inference.h"

// Model Selection criterion
#include "analytical_matrix_derivatives.h"

// Model Selection criterion
#include "model_selection.h"

// Bootstraps!
#include "bootstrappers.h"

using namespace Rcpp;

// [[Rcpp::export]]

arma::field<arma::mat> get_summary(arma::vec theta,
                                   const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc,
                                   std::string model_type,
                                   const arma::vec& wv_empir, const arma::vec& theo, const arma::vec& scales,
                                   arma::mat V, const arma::mat& omega, double obj_value,
                                   unsigned int N, double alpha,
                                   bool robust, double eff,
                                   bool inference, bool model_select, bool fullV,
                                   bool bs_gof,  bool bs_gof_p_ci, bool bs_theta_est, bool bs_ci, bool bs_optimism,
                                   unsigned int B){

  // Inference test result storage
  arma::vec gof;

  arma::mat ci;

  arma::vec score;

  // Bootstrap results
  arma::vec sd;

  arma::mat cov_nu_nu_theta;

  arma::vec bs_obj_values;

    // Take derivatives
  arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

  if(!(bs_ci || bs_optimism || bs_gof) & !fullV & (inference || model_select)){
    Rcout << "stand alone" << std::endl;
     V = cov_bootstrapper(theta,
                       desc, objdesc,
                       N, robust, eff,
                       B, true);
  }else if(bs_ci || bs_optimism || bs_gof){
    Rcout << "BS model" << std::endl;

    arma::field<arma::mat> bs = all_bootstrapper(theta,
                                                 desc, objdesc,
                                                 scales, model_type,
                                                 N, robust, eff, alpha, B);

    if(bs_optimism){
      cov_nu_nu_theta = bs(0);
    }

    if(!fullV){
      V = bs(1);
    }

    if(bs_theta_est){
      theta = bs(2);
    }

    if(bs_ci){
      sd = bs(3);
    }

    if(bs_gof){
      bs_obj_values = bs(4);
    }
  }

  // Generate inference information
  if(inference){
    // Obtain a confidence interval for the parameter estimates AND calculate chisq goodness of fit
    if(bs_ci){
      ci = format_ci(theta, sd, alpha);
    }else if(!bs_ci){
      ci = theta_ci(theta, A, V, omega, alpha);
    }

    if(bs_gof){
      arma::vec temp(3);

      temp(0) = sum(obj_value < bs_obj_values)/double(B);
      if(bs_gof_p_ci){
        temp.rows(1,2) = boot_pval_gof(obj_value, bs_obj_values, 1000, alpha);
      }
      gof = temp;
    }else{
      gof = gof_test(theta, desc, objdesc, model_type, scales, V, wv_empir);
    }

  }

  if(model_select){

    /* A note to someone in the future...
     * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
     *  and the model_score diff (theo-wv_empir).
     */
    if(bs_optimism){

      Rcout << "BS" << std::endl;
      arma::vec temp(2);

      double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

      temp(0) = obj_value + optimism;
      temp(1) = optimism;

      score = temp;
    }else{
      Rcout << "Asymptotic" << std::endl;

      // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
      arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

      // Calculate the model score according to model selection criteria paper
      score = model_score(A, D, omega, V,  obj_value);
    }
  }

  // Export information back
  arma::field<arma::mat> out(3);
  out(0) = ci;
  out(1) = gof;
  out(2) = score;

  return out;

}<commit_msg>Removed rcouts...<commit_after>#include <RcppArmadillo.h>

//#include "summary_inf_mod.h"

// Inference goodies
#include "inference.h"

// Model Selection criterion
#include "analytical_matrix_derivatives.h"

// Model Selection criterion
#include "model_selection.h"

// Bootstraps!
#include "bootstrappers.h"

using namespace Rcpp;

// [[Rcpp::export]]

arma::field<arma::mat> get_summary(arma::vec theta,
                                   const std::vector<std::string>& desc, const arma::field<arma::vec>& objdesc,
                                   std::string model_type,
                                   const arma::vec& wv_empir, const arma::vec& theo, const arma::vec& scales,
                                   arma::mat V, const arma::mat& omega, double obj_value,
                                   unsigned int N, double alpha,
                                   bool robust, double eff,
                                   bool inference, bool model_select, bool fullV,
                                   bool bs_gof,  bool bs_gof_p_ci, bool bs_theta_est, bool bs_ci, bool bs_optimism,
                                   unsigned int B){

  // Inference test result storage
  arma::vec gof;

  arma::mat ci;

  arma::vec score;

  // Bootstrap results
  arma::vec sd;

  arma::mat cov_nu_nu_theta;

  arma::vec bs_obj_values;

    // Take derivatives
  arma::mat A = derivative_first_matrix(theta, desc, objdesc, scales);

  if(!(bs_ci || bs_optimism || bs_gof) & !fullV & (inference || model_select)){
     V = cov_bootstrapper(theta,
                       desc, objdesc,
                       N, robust, eff,
                       B, true);
  }else if(bs_ci || bs_optimism || bs_gof){
    arma::field<arma::mat> bs = all_bootstrapper(theta,
                                                 desc, objdesc,
                                                 scales, model_type,
                                                 N, robust, eff, alpha, B);

    if(bs_optimism){
      cov_nu_nu_theta = bs(0);
    }

    if(!fullV){
      V = bs(1);
    }

    if(bs_theta_est){
      theta = bs(2);
    }

    if(bs_ci){
      sd = bs(3);
    }

    if(bs_gof){
      bs_obj_values = bs(4);
    }
  }

  // Generate inference information
  if(inference){
    // Obtain a confidence interval for the parameter estimates AND calculate chisq goodness of fit
    if(bs_ci){
      ci = format_ci(theta, sd, alpha);
    }else if(!bs_ci){
      ci = theta_ci(theta, A, V, omega, alpha);
    }

    if(bs_gof){
      arma::vec temp(3);

      temp(0) = sum(obj_value < bs_obj_values)/double(B);
      if(bs_gof_p_ci){
        temp.rows(1,2) = boot_pval_gof(obj_value, bs_obj_values, 1000, alpha);
      }
      gof = temp;
    }else{
      gof = gof_test(theta, desc, objdesc, model_type, scales, V, wv_empir);
    }

  }

  if(model_select){

    /* A note to someone in the future...
     * Yes, there is a difference in order between the diff (wv_empir-theo) for D_matrix
     *  and the model_score diff (theo-wv_empir).
     */
    if(bs_optimism){
      arma::vec temp(2);

      double optimism = 2*sum(diagvec(cov_nu_nu_theta * omega));

      temp(0) = obj_value + optimism;
      temp(1) = optimism;

      score = temp;
    }else{
      // Create the D Matrix (note this is in the analytical_matrix_derivaties.cpp file)
      arma::mat D = D_matrix(theta, desc, objdesc, scales, omega*(wv_empir - theo));

      // Calculate the model score according to model selection criteria paper
      score = model_score(A, D, omega, V,  obj_value);
    }
  }

  // Export information back
  arma::field<arma::mat> out(3);
  out(0) = ci;
  out(1) = gof;
  out(2) = score;

  return out;

}<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file jsonrpc.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2014
 */

#if ETH_JSONRPC && 1

#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libweb3jsonrpc/WebThreeStubServer.h>
#include <libweb3jsonrpc/CorsHttpServer.h>
#include <jsonrpc/connectors/httpserver.h>
#include <jsonrpc/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"

using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;

namespace jsonrpc_tests
{

string name = "Ethereum(++) tests";
string dbPath;
auto s = set<string>{"eth", "shh"};
dev::p2p::NetworkPreferences np(30303, std::string(), false);
dev::WebThreeDirect web3(name, dbPath, true, s, np);

unique_ptr<WebThreeStubServer> jsonrpcServer;
unique_ptr<WebThreeStubClient> jsonrpcClient;

struct JsonrpcFixture  {
	JsonrpcFixture()
	{
		cnote << "setup jsonrpc";

		web3.setIdealPeerCount(5);
		web3.ethereum()->setForceMining(true);
		jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(new jsonrpc::CorsHttpServer(8080), web3, {}));
		jsonrpcServer->setIdentities({});
		jsonrpcServer->StartListening();

		jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(new jsonrpc::HttpClient("http://localhost:8080")));
	}
	~JsonrpcFixture()
	{
		cnote << "teardown jsonrpc";
	}
};

BOOST_GLOBAL_FIXTURE(JsonrpcFixture)

BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
	cnote << "Testing jsonrpc defaultBlock...";
	int defaultBlock = jsonrpcClient->defaultBlock();
	BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());
}

BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
	cnote << "Testing jsonrpc gasPrice...";
	string gasPrice = jsonrpcClient->gasPrice();
	BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}

BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
	cnote << "Testing jsonrpc isListening...";

	web3.startNetwork();
	bool listeningOn = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOn, web3.isNetworkStarted());

	web3.stopNetwork();
	bool listeningOff = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOff, web3.isNetworkStarted());
}

BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
	cnote << "Testing jsonrpc isMining...";

	web3.ethereum()->startMining();
	bool miningOn = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());

	web3.ethereum()->stopMining();
	bool miningOff = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());
}

BOOST_AUTO_TEST_CASE(jsonrpc_accounts)
{
	cnote << "Testing jsonrpc accounts...";
	std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
	jsonrpcServer->setAccounts(keys);
	Json::Value k = jsonrpcClient->accounts();
	jsonrpcServer->setAccounts({});
	BOOST_CHECK_EQUAL(k.isArray(), true);
	BOOST_CHECK_EQUAL(k.size(),  keys.size());
	for (auto &i:k)
	{
		auto it = std::find_if(keys.begin(), keys.end(), [i](dev::KeyPair const& keyPair){
			return jsToAddress(i.asString()) == keyPair.address();
		});
		BOOST_CHECK_EQUAL(it != keys.end(), true);
	}
}

BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
	cnote << "Testing jsonrpc number2...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
	dev::eth::mine(*(web3.ethereum()), 1);
	int numberAfter = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number + 1, numberAfter);
	BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
	cnote << "Testing jsonrpc peerCount...";
	int peerCount = jsonrpcClient->peerCount();
	BOOST_CHECK_EQUAL(web3.peerCount(), peerCount);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
	cnote << "Testing jsonrpc setListening...";

	jsonrpcClient->setListening(true);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), true);

	jsonrpcClient->setListening(false);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
	cnote << "Testing jsonrpc setMining...";

	jsonrpcClient->setMining(true);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);

	jsonrpcClient->setMining(false);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
	cnote << "Testing jsonrpc stateAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string stateAt = jsonrpcClient->stateAt(toJS(address), "0");
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}

BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
	cnote << "Testing jsonrpc transact...";
	string coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());

	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	auto receiver = KeyPair::create();
	web3.ethereum()->setAddress(address);

	coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), address);

	jsonrpcServer->setAccounts({key});
	auto balance = web3.ethereum()->balanceAt(address, 0);
	string balanceString = jsonrpcClient->balanceAt(toJS(address));
	double countAt = jsonrpcClient->countAt(toJS(address));

	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address));
	BOOST_CHECK_EQUAL(countAt, 0);
	BOOST_CHECK_EQUAL(toJS(balance), balanceString);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "0");

	dev::eth::mine(*(web3.ethereum()), 1);
	balance = web3.ethereum()->balanceAt(address, 0);
	balanceString = jsonrpcClient->balanceAt(toJS(address));

	BOOST_CHECK_EQUAL(toJS(balance), balanceString);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "1500000000000000000");

	auto txAmount = balance / 2u;
	auto gasPrice = 10 * dev::eth::szabo;
	auto gas = dev::eth::c_txGas;

	Json::Value t;
	t["from"] = toJS(address);
	t["value"] = jsToDecimal(toJS(txAmount));
	t["to"] = toJS(receiver.address());
	t["data"] = toJS(bytes());
	t["gas"] = toJS(gas);
	t["gasPrice"] = toJS(gasPrice);

	jsonrpcClient->transact(t);
	jsonrpcServer->setAccounts({});
	dev::eth::mine(*(web3.ethereum()), 1);

	countAt = jsonrpcClient->countAt(toJS(address));
	auto balance2 = web3.ethereum()->balanceAt(receiver.address());
	string balanceString2 = jsonrpcClient->balanceAt(toJS(receiver.address()));

	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address));
	BOOST_CHECK_EQUAL(countAt, 1);
	BOOST_CHECK_EQUAL(toJS(balance2), balanceString2);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString2), "750000000000000000");
	BOOST_CHECK_EQUAL(txAmount, balance2);
}

}

#endif
<commit_msg>fixed style issue<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file jsonrpc.cpp
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2014
 */

#if ETH_JSONRPC && 1

#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libwebthree/WebThree.h>
#include <libweb3jsonrpc/WebThreeStubServer.h>
#include <libweb3jsonrpc/CorsHttpServer.h>
#include <jsonrpc/connectors/httpserver.h>
#include <jsonrpc/connectors/httpclient.h>
#include <set>
#include "JsonSpiritHeaders.h"
#include "TestHelper.h"
#include "webthreestubclient.h"

using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;

namespace jsonrpc_tests
{

string name = "Ethereum(++) tests";
string dbPath;
auto s = set<string>{"eth", "shh"};
dev::p2p::NetworkPreferences np(30303, std::string(), false);
dev::WebThreeDirect web3(name, dbPath, true, s, np);

unique_ptr<WebThreeStubServer> jsonrpcServer;
unique_ptr<WebThreeStubClient> jsonrpcClient;

struct JsonrpcFixture  {
	JsonrpcFixture()
	{
		cnote << "setup jsonrpc";

		web3.setIdealPeerCount(5);
		web3.ethereum()->setForceMining(true);
		jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(new jsonrpc::CorsHttpServer(8080), web3, {}));
		jsonrpcServer->setIdentities({});
		jsonrpcServer->StartListening();

		jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(new jsonrpc::HttpClient("http://localhost:8080")));
	}
	~JsonrpcFixture()
	{
		cnote << "teardown jsonrpc";
	}
};

BOOST_GLOBAL_FIXTURE(JsonrpcFixture)

BOOST_AUTO_TEST_CASE(jsonrpc_defaultBlock)
{
	cnote << "Testing jsonrpc defaultBlock...";
	int defaultBlock = jsonrpcClient->defaultBlock();
	BOOST_CHECK_EQUAL(defaultBlock, web3.ethereum()->getDefault());
}

BOOST_AUTO_TEST_CASE(jsonrpc_gasPrice)
{
	cnote << "Testing jsonrpc gasPrice...";
	string gasPrice = jsonrpcClient->gasPrice();
	BOOST_CHECK_EQUAL(gasPrice, toJS(10 * dev::eth::szabo));
}

BOOST_AUTO_TEST_CASE(jsonrpc_isListening)
{
	cnote << "Testing jsonrpc isListening...";

	web3.startNetwork();
	bool listeningOn = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOn, web3.isNetworkStarted());

	web3.stopNetwork();
	bool listeningOff = jsonrpcClient->listening();
	BOOST_CHECK_EQUAL(listeningOff, web3.isNetworkStarted());
}

BOOST_AUTO_TEST_CASE(jsonrpc_isMining)
{
	cnote << "Testing jsonrpc isMining...";

	web3.ethereum()->startMining();
	bool miningOn = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOn, web3.ethereum()->isMining());

	web3.ethereum()->stopMining();
	bool miningOff = jsonrpcClient->mining();
	BOOST_CHECK_EQUAL(miningOff, web3.ethereum()->isMining());
}

BOOST_AUTO_TEST_CASE(jsonrpc_accounts)
{
	cnote << "Testing jsonrpc accounts...";
	std::vector <dev::KeyPair> keys = {KeyPair::create(), KeyPair::create()};
	jsonrpcServer->setAccounts(keys);
	Json::Value k = jsonrpcClient->accounts();
	jsonrpcServer->setAccounts({});
	BOOST_CHECK_EQUAL(k.isArray(), true);
	BOOST_CHECK_EQUAL(k.size(),  keys.size());
	for (auto &i:k)
	{
		auto it = std::find_if(keys.begin(), keys.end(), [i](dev::KeyPair const& keyPair)
		{
			return jsToAddress(i.asString()) == keyPair.address();
		});
		BOOST_CHECK_EQUAL(it != keys.end(), true);
	}
}

BOOST_AUTO_TEST_CASE(jsonrpc_number)
{
	cnote << "Testing jsonrpc number2...";
	int number = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number, web3.ethereum()->number() + 1);
	dev::eth::mine(*(web3.ethereum()), 1);
	int numberAfter = jsonrpcClient->number();
	BOOST_CHECK_EQUAL(number + 1, numberAfter);
	BOOST_CHECK_EQUAL(numberAfter, web3.ethereum()->number() + 1);
}

BOOST_AUTO_TEST_CASE(jsonrpc_peerCount)
{
	cnote << "Testing jsonrpc peerCount...";
	int peerCount = jsonrpcClient->peerCount();
	BOOST_CHECK_EQUAL(web3.peerCount(), peerCount);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setListening)
{
	cnote << "Testing jsonrpc setListening...";

	jsonrpcClient->setListening(true);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), true);

	jsonrpcClient->setListening(false);
	BOOST_CHECK_EQUAL(web3.isNetworkStarted(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_setMining)
{
	cnote << "Testing jsonrpc setMining...";

	jsonrpcClient->setMining(true);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), true);

	jsonrpcClient->setMining(false);
	BOOST_CHECK_EQUAL(web3.ethereum()->isMining(), false);
}

BOOST_AUTO_TEST_CASE(jsonrpc_stateAt)
{
	cnote << "Testing jsonrpc stateAt...";
	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	string stateAt = jsonrpcClient->stateAt(toJS(address), "0");
	BOOST_CHECK_EQUAL(toJS(web3.ethereum()->stateAt(address, jsToU256("0"), 0)), stateAt);
}

BOOST_AUTO_TEST_CASE(jsonrpc_transact)
{
	cnote << "Testing jsonrpc transact...";
	string coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());

	dev::KeyPair key = KeyPair::create();
	auto address = key.address();
	auto receiver = KeyPair::create();
	web3.ethereum()->setAddress(address);

	coinbase = jsonrpcClient->coinbase();
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), web3.ethereum()->address());
	BOOST_CHECK_EQUAL(jsToAddress(coinbase), address);

	jsonrpcServer->setAccounts({key});
	auto balance = web3.ethereum()->balanceAt(address, 0);
	string balanceString = jsonrpcClient->balanceAt(toJS(address));
	double countAt = jsonrpcClient->countAt(toJS(address));

	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address));
	BOOST_CHECK_EQUAL(countAt, 0);
	BOOST_CHECK_EQUAL(toJS(balance), balanceString);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "0");

	dev::eth::mine(*(web3.ethereum()), 1);
	balance = web3.ethereum()->balanceAt(address, 0);
	balanceString = jsonrpcClient->balanceAt(toJS(address));

	BOOST_CHECK_EQUAL(toJS(balance), balanceString);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString), "1500000000000000000");

	auto txAmount = balance / 2u;
	auto gasPrice = 10 * dev::eth::szabo;
	auto gas = dev::eth::c_txGas;

	Json::Value t;
	t["from"] = toJS(address);
	t["value"] = jsToDecimal(toJS(txAmount));
	t["to"] = toJS(receiver.address());
	t["data"] = toJS(bytes());
	t["gas"] = toJS(gas);
	t["gasPrice"] = toJS(gasPrice);

	jsonrpcClient->transact(t);
	jsonrpcServer->setAccounts({});
	dev::eth::mine(*(web3.ethereum()), 1);

	countAt = jsonrpcClient->countAt(toJS(address));
	auto balance2 = web3.ethereum()->balanceAt(receiver.address());
	string balanceString2 = jsonrpcClient->balanceAt(toJS(receiver.address()));

	BOOST_CHECK_EQUAL(countAt, (double)(uint64_t)web3.ethereum()->countAt(address));
	BOOST_CHECK_EQUAL(countAt, 1);
	BOOST_CHECK_EQUAL(toJS(balance2), balanceString2);
	BOOST_CHECK_EQUAL(jsToDecimal(balanceString2), "750000000000000000");
	BOOST_CHECK_EQUAL(txAmount, balance2);
}

}

#endif
<|endoftext|>


<commit_before><commit_msg>Some enhancements to DeclStmt printing.  Some of this should  move to DeclPrinter.cpp, but I haven't quite worked out how best to do  that.<commit_after><|endoftext|>


<commit_before>
#include "api.h"

Menu::Controller* PluginApi::menu_;
Notebook::Controller* PluginApi::notebook_;

/////////////////////////////
//// API ServiceProvider ////
/////////////////////////////

void PluginApi::ReplaceWord(std::string word) {
  Glib::RefPtr<Gtk::TextBuffer> buffer = libjuci::BufferFromNotebook();
  Gtk::TextIter word_start = libjuci::IterFromNotebook();
  Gtk::TextIter word_end = libjuci::IterFromNotebook();

  libjuci::IterToWordStart(word_start);
  libjuci::IterToWordEnd(word_end);
  if(word_start != word_end) {
    buffer->erase(word_start, word_end);
    Gtk::TextIter current = libjuci::IterFromNotebook();
    buffer->insert(current, word);
  }
}

void PluginApi::ReplaceLine(std::string line) {
  std::cout << "unimplemented: " << __func__ << std::endl;
}

std::string PluginApi::GetWord() {
  // TODO forgie: use notebook's functions
  Glib::RefPtr<Gtk::TextBuffer> buffer = libjuci::BufferFromNotebook();
  Gtk::TextIter word_start = libjuci::IterFromNotebook();
  Gtk::TextIter word_end = libjuci::IterFromNotebook();

  libjuci::IterToWordStart(word_start);
  libjuci::IterToWordEnd(word_end);

  if(word_start < word_end) {
    std::string word = buffer->get_text(word_start, word_end);
    return word;
  }
  return "";
}

//runs the pythonscript that initiates every plugin within plugins/
void PluginApi::InitPlugins() {
  libjuci::LoadPlugin(g_project_root+"plugins.py");
}

void PluginApi::AddMenuElement(std::string plugin_name){
  AddMenuXml(plugin_name, "PluginMenu");
  std::string plugin_action_name = plugin_name+"Menu";

  menu_->keybindings_.action_group_menu()
    ->add(Gtk::Action::create(plugin_action_name, plugin_name));
}

void PluginApi::AddSubMenuElement(std::string parent_menu,
				  std::string menu_name,
				  std::string menu_func_name,
				  std::string plugin_path,
				  std::string menu_keybinding) {

  AddSubMenuXml(menu_func_name, parent_menu);

  menu_->keybindings_.action_group_menu()
    ->add(Gtk::Action::create(menu_func_name,
			      menu_name),
	  Gtk::AccelKey(menu_keybinding),
	  [=]() {
	    libjuci::LoadPluginFunction(menu_func_name, plugin_path);
	  });
}

void PluginApi::AddMenuXml(std::string plugin_name, std::string parent_menu) {

  std::string temp_menu = menu_->keybindings_.model_.menu_ui_string();

  std::size_t plugin_menu_pos = temp_menu.find(parent_menu);
  // +2 gets you outside of the tag:<'menu_name'> ref: keybindings.cc
  plugin_menu_pos+=parent_menu.size() +2;
  std::string menu_prefix = temp_menu.substr(0, plugin_menu_pos);
  std::string menu_suffix = temp_menu.substr(plugin_menu_pos);

  std::string menu_input =
    "           <menu action='"+plugin_name+"Menu'>               "
    "           </menu>                                           ";

  menu_->keybindings_.model_.menu_ui_string_ =
    menu_prefix + menu_input + menu_suffix;
}

void PluginApi::AddSubMenuXml(std::string plugin_name, std::string parent_menu){
  std::string temp_menu = menu_->keybindings_.model_.menu_ui_string();

  std::size_t parent_menu_pos = temp_menu.find(parent_menu);
  // +2 gets you outside of the tag:<'menu_name'> ref: keybindings.cc
  parent_menu_pos+=parent_menu.size() +2;
  std::string menu_prefix = temp_menu.substr(0, parent_menu_pos);
  std::string menu_suffix = temp_menu.substr(parent_menu_pos);

  std::string menu_input ="<menuitem action='"+plugin_name+"'/>";

  menu_->keybindings_.model_.menu_ui_string_ =
    menu_prefix + menu_input + menu_suffix;
}

///////////////////////
//// Api to python ////
///////////////////////
void libjuci::ReplaceWord(const std::string word) {
  PluginApi::ReplaceWord(word);
}

void libjuci::ReplaceLine(const std::string line) {
  std::cout << "unimplemented function: 'libjuci::ReplaceLine()' called"
	    << std::endl;
}
std::string libjuci::GetWord() {
  return PluginApi::GetWord();
}

void libjuci::AddMenuElement(std::string plugin_name){
  PluginApi::AddMenuElement(plugin_name);
}

void libjuci::AddSubMenuElement(std::string parent_menu,
				std::string menu_name,
				std::string menu_func_name,
				std::string plugin_path,
				std::string menu_keybinding) {

  PluginApi::AddSubMenuElement(parent_menu,
			       menu_name,
			       menu_func_name,
			       plugin_path,
			       menu_keybinding);
}

//////////////////////////////
//// Boost.Python methods ////
//////////////////////////////
namespace bp = boost::python;

bp::api::object libjuci::OpenPythonScript(const std::string path,
					  bp::api::object python_name_space) {
  bp::str str_path(path);
  return bp::exec_file(str_path, python_name_space);
}

void libjuci::LoadPlugin(const std::string& plugin_name) {
  std::cout << "libjuci::LoadPlugin " << plugin_name << std::endl;
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace =
      main_module.attr("__dict__");
    bp::api::object ignored2 =
      OpenPythonScript(plugin_name, main_namespace);

  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

void libjuci::LoadPluginFunction(const std::string &function_name,
				 const std::string &plugin_path){
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace = main_module.attr("__dict__");
    bp::api::object ignored2 = OpenPythonScript(plugin_path, main_namespace);
    bp::str func_name(function_name);
    bp::api::object returnValue = bp::eval(func_name, main_namespace);
  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

void libjuci::InitPlugin(const std::string& plugin_path) {
  std::cout << "libjuci::InitPlugin " << plugin_path << std::endl;
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace = main_module.attr("__dict__");
    bp::api::object ignored2 = OpenPythonScript(plugin_path, main_namespace);
    bp::object returnValue  =  bp::eval("initPlugin()",	main_namespace);
    //std::string return_value = bp::extract<std::string>(pySnippet);
    //do something with return_value
  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

///////////////////////
//// Glib wrappers ////
///////////////////////
void libjuci::IterToWordStart(Gtk::TextIter &iter) {
  if(!iter.starts_line()) {
    while(!iter.starts_word()) {
      iter.backward_char();
    }
  }
}

void libjuci::IterToWordEnd(Gtk::TextIter &iter) {
  if(!iter.ends_line()) {
    while(!iter.ends_word()) {
      iter.forward_char();
    }
  }
}

Glib::RefPtr<Gtk::TextBuffer> libjuci::BufferFromNotebook() {
  //finding focused view
  int i = 0;
  while(!PluginApi::notebook_->source_vec_.at(i)->view().has_focus()) {
    i++;
  }
  return Glib::RefPtr<Gtk::TextBuffer>(PluginApi::notebook_
				       ->source_vec_.at(i)
				       ->view().get_buffer());
}

Gtk::TextIter libjuci::IterFromNotebook() {
  return libjuci::BufferFromNotebook()->get_insert()->get_iter();
}
<commit_msg>BAB-50 #comment merged with master<commit_after>
#include "api.h"

Menu::Controller* PluginApi::menu_;
Notebook::Controller* PluginApi::notebook_;

/////////////////////////////
//// API ServiceProvider ////
/////////////////////////////

void PluginApi::ReplaceWord(std::string word) {
  Glib::RefPtr<Gtk::TextBuffer> buffer = libjuci::BufferFromNotebook();
  Gtk::TextIter word_start = libjuci::IterFromNotebook();
  Gtk::TextIter word_end = libjuci::IterFromNotebook();

  libjuci::IterToWordStart(word_start);
  libjuci::IterToWordEnd(word_end);
  if(word_start != word_end) {
    buffer->erase(word_start, word_end);
    Gtk::TextIter current = libjuci::IterFromNotebook();
    buffer->insert(current, word);
  }
}

void PluginApi::ReplaceLine(std::string line) {
  std::cout << "unimplemented: " << __func__ << std::endl;
}

std::string PluginApi::GetWord() {
  // TODO forgie: use notebook's functions
  Glib::RefPtr<Gtk::TextBuffer> buffer = libjuci::BufferFromNotebook();
  Gtk::TextIter word_start = libjuci::IterFromNotebook();
  Gtk::TextIter word_end = libjuci::IterFromNotebook();

  libjuci::IterToWordStart(word_start);
  libjuci::IterToWordEnd(word_end);

  if(word_start < word_end) {
    std::string word = buffer->get_text(word_start, word_end);
    return word;
  }
  return "";
}

//runs the pythonscript that initiates every plugin within plugins/
void PluginApi::InitPlugins() {
  libjuci::LoadPlugin(g_project_root+"plugins.py");
}

void PluginApi::AddMenuElement(std::string plugin_name){
  AddMenuXml(plugin_name, "PluginMenu");
  std::string plugin_action_name = plugin_name+"Menu";

  menu_->keybindings_.action_group_menu()
    ->add(Gtk::Action::create(plugin_action_name, plugin_name));
}

void PluginApi::AddSubMenuElement(std::string parent_menu,
				  std::string menu_name,
				  std::string menu_func_name,
				  std::string plugin_path,
				  std::string menu_keybinding) {

  AddSubMenuXml(menu_func_name, parent_menu);

  menu_->keybindings_.action_group_menu()
    ->add(Gtk::Action::create(menu_func_name,
			      menu_name),
	  Gtk::AccelKey(menu_keybinding),
	  [=]() {
	    libjuci::LoadPluginFunction(menu_func_name, plugin_path);
	  });
}

void PluginApi::AddMenuXml(std::string plugin_name, std::string parent_menu) {

  std::string temp_menu = menu_->keybindings_.model_.menu_ui_string();

  std::size_t plugin_menu_pos = temp_menu.find(parent_menu);
  // +2 gets you outside of the tag:<'menu_name'> ref: keybindings.cc
  plugin_menu_pos+=parent_menu.size() +2;
  std::string menu_prefix = temp_menu.substr(0, plugin_menu_pos);
  std::string menu_suffix = temp_menu.substr(plugin_menu_pos);

  std::string menu_input =
    "           <menu action='"+plugin_name+"Menu'>               "
    "           </menu>                                           ";

  menu_->keybindings_.model_.menu_ui_string_ =
    menu_prefix + menu_input + menu_suffix;
}

void PluginApi::AddSubMenuXml(std::string plugin_name, std::string parent_menu){
  std::string temp_menu = menu_->keybindings_.model_.menu_ui_string();

  std::size_t parent_menu_pos = temp_menu.find(parent_menu);
  // +2 gets you outside of the tag:<'menu_name'> ref: keybindings.cc
  parent_menu_pos+=parent_menu.size() +2;
  std::string menu_prefix = temp_menu.substr(0, parent_menu_pos);
  std::string menu_suffix = temp_menu.substr(parent_menu_pos);

  std::string menu_input ="<menuitem action='"+plugin_name+"'/>";

  menu_->keybindings_.model_.menu_ui_string_ =
    menu_prefix + menu_input + menu_suffix;
}

///////////////////////
//// Api to python ////
///////////////////////
void libjuci::ReplaceWord(const std::string word) {
  PluginApi::ReplaceWord(word);
}

void libjuci::ReplaceLine(const std::string line) {
  std::cout << "unimplemented function: 'libjuci::ReplaceLine()' called"
	    << std::endl;
}
std::string libjuci::GetWord() {
  return PluginApi::GetWord();
}

void libjuci::AddMenuElement(std::string plugin_name){
  PluginApi::AddMenuElement(plugin_name);
}

void libjuci::AddSubMenuElement(std::string parent_menu,
				std::string menu_name,
				std::string menu_func_name,
				std::string plugin_path,
				std::string menu_keybinding) {

  PluginApi::AddSubMenuElement(parent_menu,
			       menu_name,
			       menu_func_name,
			       plugin_path,
			       menu_keybinding);
}

//////////////////////////////
//// Boost.Python methods ////
//////////////////////////////
namespace bp = boost::python;

bp::api::object libjuci::OpenPythonScript(const std::string path,
					  bp::api::object python_name_space) {
  bp::str str_path(path);
  return bp::exec_file(str_path, python_name_space);
}

void libjuci::LoadPlugin(const std::string& plugin_name) {
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace =
      main_module.attr("__dict__");
    bp::api::object ignored2 =
      OpenPythonScript(plugin_name, main_namespace);

  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

void libjuci::LoadPluginFunction(const std::string &function_name,
				 const std::string &plugin_path){
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace = main_module.attr("__dict__");
    bp::api::object ignored2 = OpenPythonScript(plugin_path, main_namespace);
    bp::str func_name(function_name);
    bp::api::object returnValue = bp::eval(func_name, main_namespace);
  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

void libjuci::InitPlugin(const std::string& plugin_path) {
  try{
    Py_Initialize();
    bp::api::object main_module = bp::import("__main__");
    bp::api::object main_namespace = main_module.attr("__dict__");
    bp::api::object ignored2 = OpenPythonScript(plugin_path, main_namespace);
    bp::object returnValue  =  bp::eval("initPlugin()",	main_namespace);
    //std::string return_value = bp::extract<std::string>(pySnippet);
    //do something with return_value
  }catch(bp::error_already_set const&) {
    PyErr_Print();
  }
}

///////////////////////
//// Glib wrappers ////
///////////////////////
void libjuci::IterToWordStart(Gtk::TextIter &iter) {
  if(!iter.starts_line()) {
    while(!iter.starts_word()) {
      iter.backward_char();
    }
  }
}

void libjuci::IterToWordEnd(Gtk::TextIter &iter) {
  if(!iter.ends_line()) {
    while(!iter.ends_word()) {
      iter.forward_char();
    }
  }
}

Glib::RefPtr<Gtk::TextBuffer> libjuci::BufferFromNotebook() {
  //finding focused view
  int i = 0;
  while(!PluginApi::notebook_->source_vec_.at(i)->view().has_focus()) {
    i++;
  }
  return Glib::RefPtr<Gtk::TextBuffer>(PluginApi::notebook_
				       ->source_vec_.at(i)
				       ->view().get_buffer());
}

Gtk::TextIter libjuci::IterFromNotebook() {
  return libjuci::BufferFromNotebook()->get_insert()->get_iter();
}
<|endoftext|>


<commit_before>/*
  Q Light Controller
  olaio.cpp

  Copyright (c) Simon Newton
                Heikki Junnila

  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.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QApplication>
#include <QSettings>
#include <QString>
#include <QDebug>

#include "qlclogdestination.h"
#include "configureolaio.h"
#include "olaio.h"

#define SETTINGS_EMBEDDED "OlaIO/embedded"
#define UNIVERSE_COUNT 4

/****************************************************************************
 * Initialization
 ****************************************************************************/

OlaIO::~OlaIO()
{
    if (m_thread != NULL)
    {
        m_thread->stop();
        delete m_thread;
    }
    ola::InitLogging(ola::OLA_LOG_WARN, NULL);
}

/**
 * Start the plugin. It's hard to say if we want OLA running if there aren't
 * any output universes active.
 */
void OlaIO::init()
{
    m_embedServer = false;
    m_thread = NULL;
    ola::InitLogging(ola::OLA_LOG_WARN, new ola::QLCLogDestination());
    // TODO: load this from a savefile at some point
    for (unsigned int i = 1; i <= UNIVERSE_COUNT; ++i)
        m_outputs.append(i);

    bool es = false;
    QSettings settings;
    QVariant var = settings.value(SETTINGS_EMBEDDED);
    if (var.isValid() == true)
        es = settings.value(SETTINGS_EMBEDDED).toBool();

    // Make sure the thread is started the first time round
    m_embedServer = !es;
    // This should load from the settings when it is made
    setServerEmbedded(es);
}

QString OlaIO::name()
{
    return QString("OLA");
}

int OlaIO::capabilities() const
{
    return QLCIOPlugin::Output;
}

bool OlaIO::isServerEmbedded() const
{
    return m_embedServer;
}

void OlaIO::setServerEmbedded(bool embedServer)
{
    if (embedServer != m_embedServer)
    {
        if (m_thread != NULL)
        {
            m_thread->stop();
            delete m_thread;
        }

        m_embedServer = embedServer;
        if (m_embedServer)
        {
            qWarning() << "[OLA] Running with embedded server";
            m_thread = new OlaEmbeddedServer();
        }
        else
        {
            m_thread = new OlaStandaloneClient();
        }

        if (!m_thread->start())
            qWarning() << "[OLA] Start thread failed";

        QSettings settings;
        settings.setValue(SETTINGS_EMBEDDED, m_embedServer);
    }
}

/****************************************************************************
 * Outputs
 ****************************************************************************/

bool OlaIO::openOutput(quint32 output, quint32 universe)
{
    if (output >= UNIVERSE_COUNT)
    {
        qWarning() << "[OLA] output" << output << "is out of range";
        return false;
    }
    addToMap(universe, output, Output);
    return true;
}

void OlaIO::closeOutput(quint32 output, quint32 universe)
{
    if (output >= UNIVERSE_COUNT)
        qWarning() << "[OLA] output" << output << "is out of range";
    else
        removeFromMap(output, universe, Output);
}

QStringList OlaIO::outputs()
{
    QStringList list;
    for (int i = 0; i < m_outputs.size(); ++i)
        list << QString("%1: OLA Universe %1").arg(i + 1);
    return list;
}

QString OlaIO::pluginInfo()
{
    QString str;

    str += QString("");
    str += QString("");
    str += QString("<TITLE>%1</TITLE>").arg(name());
    str += QString("");
    str += QString("");

    str += QString("
");
    str += QString("
%1
").arg(name());
    str += tr("This plugin provides DMX output support for the Open Lighting Architecture (OLA).");
    str += QString("
");

    return str;
}

QString OlaIO::outputInfo(quint32 output)
{
    QString str;

    if (output != QLCIOPlugin::invalidLine())
    {
        str += QString("
%1
").arg(outputs()[output]);
        str += QString("
");
        str += tr("This is the output for OLA universe %1").arg(output + 1);
        str += QString("
");
    }

    str += QString("");
    str += QString("");
    return str;
}

void OlaIO::writeUniverse(quint32 universe, quint32 output, const QByteArray &data)
{
    Q_UNUSED(universe)

    if (output > UNIVERSE_COUNT || !m_thread)
        return;
    else
        m_thread->write_dmx(m_outputs[output], data);
}

QList <uint> OlaIO::outputMapping() const
{
    return m_outputs;
}

void OlaIO::setOutputUniverse(quint32 output, unsigned int universe)
{
    if (output > UNIVERSE_COUNT)
        return;
    m_outputs[output] = universe;
}

/****************************************************************************
 * Configuration
 ****************************************************************************/

void OlaIO::configure()
{
    ConfigureOlaIO conf(this, NULL);
    conf.exec();
    emit configurationChanged();
}

bool OlaIO::canConfigure()
{
    return true;
}

void OlaIO::setParameter(quint32 universe, quint32 line, Capability type,
                         QString name, QVariant value)
{
    QLCIOPlugin::setParameter(universe, line, type, name, value);
}

/****************************************************************************
 * Plugin export
 ****************************************************************************/
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(olaio, OlaIO)
#endif
<commit_msg>added compile option to change OLA plugin starting universe<commit_after>/*
  Q Light Controller
  olaio.cpp

  Copyright (c) Simon Newton
                Heikki Junnila

  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.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <QApplication>
#include <QSettings>
#include <QString>
#include <QDebug>

#include "qlclogdestination.h"
#include "configureolaio.h"
#include "olaio.h"

#define SETTINGS_EMBEDDED "OlaIO/embedded"
#define UNIVERSE_COUNT 4

#ifndef QLC_OLA_FIRST_UNIVERSE
#define QLC_OLA_FIRST_UNIVERSE 1
#endif

/****************************************************************************
 * Initialization
 ****************************************************************************/

OlaIO::~OlaIO()
{
    if (m_thread != NULL)
    {
        m_thread->stop();
        delete m_thread;
    }
    ola::InitLogging(ola::OLA_LOG_WARN, NULL);
}

/**
 * Start the plugin. It's hard to say if we want OLA running if there aren't
 * any output universes active.
 */
void OlaIO::init()
{
    m_embedServer = false;
    m_thread = NULL;
    ola::InitLogging(ola::OLA_LOG_WARN, new ola::QLCLogDestination());
    // TODO: load this from a savefile at some point
    for (unsigned int i = 0; i < UNIVERSE_COUNT; ++i)
        m_outputs.append(i + QLC_OLA_FIRST_UNIVERSE);

    bool es = false;
    QSettings settings;
    QVariant var = settings.value(SETTINGS_EMBEDDED);
    if (var.isValid() == true)
        es = settings.value(SETTINGS_EMBEDDED).toBool();

    // Make sure the thread is started the first time round
    m_embedServer = !es;
    // This should load from the settings when it is made
    setServerEmbedded(es);
}

QString OlaIO::name()
{
    return QString("OLA");
}

int OlaIO::capabilities() const
{
    return QLCIOPlugin::Output;
}

bool OlaIO::isServerEmbedded() const
{
    return m_embedServer;
}

void OlaIO::setServerEmbedded(bool embedServer)
{
    if (embedServer != m_embedServer)
    {
        if (m_thread != NULL)
        {
            m_thread->stop();
            delete m_thread;
        }

        m_embedServer = embedServer;
        if (m_embedServer)
        {
            qWarning() << "[OLA] Running with embedded server";
            m_thread = new OlaEmbeddedServer();
        }
        else
        {
            m_thread = new OlaStandaloneClient();
        }

        if (!m_thread->start())
            qWarning() << "[OLA] Start thread failed";

        QSettings settings;
        settings.setValue(SETTINGS_EMBEDDED, m_embedServer);
    }
}

/****************************************************************************
 * Outputs
 ****************************************************************************/

bool OlaIO::openOutput(quint32 output, quint32 universe)
{
    if (output >= UNIVERSE_COUNT)
    {
        qWarning() << "[OLA] output" << output << "is out of range";
        return false;
    }
    addToMap(universe, output, Output);
    return true;
}

void OlaIO::closeOutput(quint32 output, quint32 universe)
{
    if (output >= UNIVERSE_COUNT)
        qWarning() << "[OLA] output" << output << "is out of range";
    else
        removeFromMap(output, universe, Output);
}

QStringList OlaIO::outputs()
{
    QStringList list;
    for (int i = 0; i < m_outputs.size(); ++i)
        list << QString("%1: OLA Universe %2").arg(i + 1).arg(m_outputs[i]);
    return list;
}

QString OlaIO::pluginInfo()
{
    QString str;

    str += QString("");
    str += QString("");
    str += QString("<TITLE>%1</TITLE>").arg(name());
    str += QString("");
    str += QString("");

    str += QString("
");
    str += QString("
%1
").arg(name());
    str += tr("This plugin provides DMX output support for the Open Lighting Architecture (OLA).");
    str += QString("
");

    return str;
}

QString OlaIO::outputInfo(quint32 output)
{
    QString str;

    if (output != QLCIOPlugin::invalidLine())
    {
        str += QString("
%1
").arg(outputs()[output]);
        str += QString("
");
        str += tr("This is the output for OLA universe %1").arg(m_outputs[output]);
        str += QString("
");
    }

    str += QString("");
    str += QString("");
    return str;
}

void OlaIO::writeUniverse(quint32 universe, quint32 output, const QByteArray &data)
{
    Q_UNUSED(universe)

    if (output > UNIVERSE_COUNT || !m_thread)
        return;
    else
        m_thread->write_dmx(m_outputs[output], data);
}

QList <uint> OlaIO::outputMapping() const
{
    return m_outputs;
}

void OlaIO::setOutputUniverse(quint32 output, unsigned int universe)
{
    if (output > UNIVERSE_COUNT)
        return;
    m_outputs[output] = universe;
}

/****************************************************************************
 * Configuration
 ****************************************************************************/

void OlaIO::configure()
{
    ConfigureOlaIO conf(this, NULL);
    conf.exec();
    emit configurationChanged();
}

bool OlaIO::canConfigure()
{
    return true;
}

void OlaIO::setParameter(quint32 universe, quint32 line, Capability type,
                         QString name, QVariant value)
{
    QLCIOPlugin::setParameter(universe, line, type, name, value);
}

/****************************************************************************
 * Plugin export
 ****************************************************************************/
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_EXPORT_PLUGIN2(olaio, OlaIO)
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ZipPackageSink.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:19:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_SINK_HXX
#define _ZIP_PACKAGE_SINK_HXX

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class ZipPackageSink : public ::cppu::WeakImplHelper1
<
    com::sun::star::io::XActiveDataSink
>
{
protected:
    com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
public:
    ZipPackageSink();
    virtual ~ZipPackageSink();
    virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  )
        throw(::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.98); FILE MERGED 2008/04/01 15:22:25 thb 1.4.98.3: #i85898# Stripping all external header guards 2008/04/01 12:32:15 thb 1.4.98.2: #i85898# Stripping all external header guards 2008/03/31 16:19:10 rt 1.4.98.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ZipPackageSink.hxx,v $
 * $Revision: 1.5 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_SINK_HXX
#define _ZIP_PACKAGE_SINK_HXX

#include <com/sun/star/io/XActiveDataSink.hpp>
#include <cppuhelper/implbase1.hxx>

class ZipPackageSink : public ::cppu::WeakImplHelper1
<
    com::sun::star::io::XActiveDataSink
>
{
protected:
    com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
public:
    ZipPackageSink();
    virtual ~ZipPackageSink();
    virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(  )
        throw(::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>