<commit_before>/******************************************************************************
 * @file     hgpu_timer.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.0
 *
 * @brief    [HGPU library]
 *           timer submodule
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2013, Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/

#include "../include/hgpu_timer.h"

// start timer
HGPU_timer
HGPU_timer_start(void){
    return clock();
}

// get timer value in seconds (time delta)
double
HGPU_timer_get(HGPU_timer timer){
    double result = ((double) (clock() - timer)) / CLOCKS_PER_SEC;
    return result;
}

// get timer value in seconds (from start)
double
HGPU_timer_get_from_start(void){
    return ((double) clock()) / CLOCKS_PER_SEC;
}

// get date-time string
char*
HGPU_timer_get_current_datetime(void){
    time_t tim;
	time(&tim);
    char* result = (char*) calloc(30,sizeof(char));
#ifdef _WIN32
    ctime_s(result, 30, &tim);
#else
    sprintf(result,"%s",ctime((const time_t*) &tim));
#endif
    HGPU_string_char_replace(result,HGPU_CHAR_CR,0);
    HGPU_string_char_replace(result,HGPU_CHAR_NEWLINE,0);
    return result;
}

// get (HGPU_timer_deviation) from profiling data
HGPU_timer_deviation
HGPU_timer_deviation_get(double elapsed_time, double elapsed_time_squared, double number_of_elements){
    HGPU_timer_deviation execution_time;
    execution_time.mean = elapsed_time;
    execution_time.number_of_elements = number_of_elements;
    execution_time.deviation = number_of_elements < 2 ? 0.0 : sqrt(abs(elapsed_time_squared - pow(elapsed_time,2)) / number_of_elements);
    return execution_time;
}
<commit_msg>timer submodule<commit_after>/******************************************************************************
 * @file     hgpu_timer.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.0.2
 *
 * @brief    [HGPU library]
 *           timer submodule
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2013, 2014 Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/

#include "../include/hgpu_timer.h"

// start timer
HGPU_timer
HGPU_timer_start(void){
#ifdef SAFE_LINUX_TIMER
    HGPU_timer timer;
    time(&timer);
    return (HGPU_timer) timer;
#else
    return clock();
#endif
}

// get timer value in seconds (time delta)
double
HGPU_timer_get(HGPU_timer timer){
#ifdef SAFE_LINUX_TIMER
    double result = difftime(HGPU_timer_start(),timer);
#else
    double result = ((double) (clock() - timer)) / CLOCKS_PER_SEC;
#endif
    return result;
}

// get timer value in seconds (from start)
double
HGPU_timer_get_from_start(void){
    return ((double) clock()) / CLOCKS_PER_SEC;
}

// get date-time string
char*
HGPU_timer_get_current_datetime(void){
    time_t tim;
	time(&tim);
    char* result = (char*) calloc(30,sizeof(char));
#ifdef _WIN32
    ctime_s(result, 30, &tim);
#else
    sprintf(result,"%s",ctime((const time_t*) &tim));
#endif
    HGPU_string_char_replace(result,HGPU_CHAR_CR,0);
    HGPU_string_char_replace(result,HGPU_CHAR_NEWLINE,0);
    return result;
}

// get (HGPU_timer_deviation) from profiling data
HGPU_timer_deviation
HGPU_timer_deviation_get(double elapsed_time, double elapsed_time_squared, double number_of_elements){
    HGPU_timer_deviation execution_time;
    execution_time.mean = elapsed_time;
    execution_time.number_of_elements = number_of_elements;
    execution_time.deviation = number_of_elements < 2 ? 0.0 : sqrt(abs(elapsed_time_squared - pow(elapsed_time,2)) / number_of_elements);
    return execution_time;
}
<|endoftext|>


<commit_before>/**\file
 * \brief "Hello World" HTTP Server
 *
 * \copyright
 * Copyright (c) 2015, ef.gy Project Members
 * \copyright
 * 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:
 * \copyright
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * \copyright
 * 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.
 *
 * \see Project Documentation: http://ef.gy/documentation/libefgy
 * \see Project Source Code: https://github.com/ef-gy/libefgy
 */

#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>

using namespace efgy;
using namespace asio;
using namespace std;

using asio::ip::tcp;

static bool hello(typename net::http::server<tcp>::session &session,
                  std::smatch &) {
  session.reply(200, "Hello World!");

  return true;
}

int main(int argc, char *argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: http-hello <host> <port>\n";
      return 1;
    }

    asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    if (endpoint_iterator != end) {
      tcp::endpoint endpoint = *endpoint_iterator;
      net::http::server<tcp> s(io_service, endpoint, cout);

      s.processor.add("^/$", hello);

      io_service.run();
    }
  }
  catch (std::exception & e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  catch (std::system_error & e) {
    std::cerr << "System Error: " << e.what() << "\n";
  }

  return 0;
}
<commit_msg>add a bit more documentation to the HTTP demo<commit_after>/**\file
 * \brief "Hello World" HTTP Server
 *
 * This is an example HTTP server that serves a simple "Hello World!" on /, and
 * a 404 on all other resources.
 *
 * Call it like this:
 * \code
 * $ ./http-hello localhost 8080
 * \endcode
 *
 * With localhost and 8080 being a host name and port of your choosing. Then,
 * while the programme is running, open a browser and go to
 * http://localhost:8080/ and you should see the familiar greeting.
 *
 * \copyright
 * Copyright (c) 2015, ef.gy Project Members
 * \copyright
 * 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:
 * \copyright
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * \copyright
 * 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.
 *
 * \see Project Documentation: http://ef.gy/documentation/libefgy
 * \see Project Source Code: https://github.com/ef-gy/libefgy
 */

#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>

using namespace efgy;
using asio::ip::tcp;

/**\brief Hello World request handler
 *
 * This function serves the familiar "Hello World!" when called.
 *
 * \param[out] session The HTTP session to answer on.
 *
 * \returns true (always, as we always reply).
 */
static bool hello(typename net::http::server<tcp>::session &session,
                  std::smatch &) {
  session.reply(200, "Hello World!");

  return true;
}

/**\brief Main function for the HTTP demo
 *
 * This is the main function for the HTTP Hello World demo.
 *
 * \param[in] argc Process argument count.
 * \param[in] argv Process argument vector.
 *
 * \returns 0 when nothing bad happened, 1 otherwise.
 */
int main(int argc, char *argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: http-hello <host> <port>\n";
      return 1;
    }

    asio::io_service io_service;
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    if (endpoint_iterator != end) {
      tcp::endpoint endpoint = *endpoint_iterator;
      net::http::server<tcp> s(io_service, endpoint, std::cout);

      s.processor.add("^/$", hello);

      io_service.run();
    }

    return 0;
  }
  catch (std::exception & e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }
  catch (std::system_error & e) {
    std::cerr << "System Error: " << e.what() << "\n";
  }

  return 1;
}
<|endoftext|>


<commit_before>/* inchi_input.cc
 * Copyright 2014 Cubane Canada, Inc.
 *
 * Released under the MIT license -- see MIT-LICENSE for details
 */
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <nan.h>

#include <cstring>

#include "./inchi_input.h"

#include "./using_v8.h"

/**
 * Wrapper for INCHI_Input structure
 *
 * @module InChILib
 * @class  InchiInput
 */

/* local (non-API) functions */
static void populate_input(Handle<Value> val, InchiInput* in);
static void populate_ret(Handle<Object> ret,
                         const inchi_Output& out, int result);
static void addstring(Handle<Object> ret,
                      const char * name, const char * value);

/**
 * Create an InchiInput structure from a partially or fully specified
 * JavaScript object
 *
 * @method Create
 * @param {Handle<Object>} val Object handle that parallels an inchi_Input
 */
InchiInput * InchiInput::Create(Handle<Value> val) {
  // TODO(SOM): validation

  // create an empty InchiInput
  InchiInput * input = new InchiInput;

  // populate it
  populate_input(val, input);

  // return it
  return input;
}

Handle<Object> InchiInput::GetINCHIData::GetResult() {
  Local<Object> ret = Object::New();

  populate_ret(ret, this->out_, result_);

  return ret;
}

struct GetINCHIWorker : public NanAsyncWorker {
  InchiInput::GetINCHIData * data_;

  GetINCHIWorker(NanCallback * callback, InchiInput* input) :
    NanAsyncWorker(callback) {
    data_ = input->tearOffGetINCHIData();
  }
  ~GetINCHIWorker() {}

  void Execute() {
    data_->GetInchi();
  }

  void HandleOKCallback() {
    NanScope();

    Handle<Object> result = data_->GetResult();

    Local<Value> argv[] = {
      Local<Value>::New(v8::Null()),
      Local<Value>::New(result)
    };

    callback->Call(2, argv);
  }
};

/**
 * calls the "classic" GetINCHI function
 * @method GetINCHI
 * @param {Object}   molecule Description of molecule
 * @param {Function} callback Callback function
 */
NAN_METHOD(GetINCHI) {
  NanScope();

  InchiInput * input = NULL;
  Handle<Object> ret;

  try {
    // TODO(SOM): validate args
    Handle<Value> mol = args[0];
    NanCallback * callback = new NanCallback(args[1].As<Function>());

    input = InchiInput::Create(mol);

    NanAsyncQueueWorker(new GetINCHIWorker(callback, input));
  } catch(...) {
  }

  delete input;

  NanReturnUndefined();
};

void add_atom(InchiInput* in, Handle<Object> atom) {
  Handle<String> elname_string = atom->Get(NanSymbol("elname"))->ToString();

  char * elname = NanCString(elname_string, 0);
  int index = in->addAtom(elname);

  Handle<Array> neighbor =
    Handle<Array>::Cast(atom->Get(NanSymbol("neighbor")));

  int bonds = neighbor->Length();
  for (int i = 0; i < bonds; ++i) {
    int bonded = neighbor->Get(i)->ToNumber()->Value();
    in->addBond(index, bonded);
  }
}

static void populate_input(Handle<Value> val, InchiInput* in) {
  // TODO(SOM): support validation, possibly return error code

  // expect args[0] to be an Object, call it 'mol'
  // expect mol.atom to be an Array
  // expect mol.options to be a string
  // expect mol.stereo0D to be an Array

  if (!val->IsObject()) {
    return;
  }
  Handle<Object> mol = val->ToObject();

  if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
    return;
  }
  Handle<Array> atom = Handle<Array>::Cast(mol->Get(NanSymbol("atom")));

  int atoms = atom->Length();
  for (int i = 0; i < atoms; i += 1) {
    add_atom(in, atom->Get(i)->ToObject());
  }
}

static void addstring(Handle<Object> ret,
                      const char * name, const char * value) {
  if (value) {
    ret->Set(NanSymbol(name), String::New(value));
  } else {
    ret->Set(NanSymbol(name), String::New(""));
  }
}

static void populate_ret(Handle<Object> ret,
                         const inchi_Output& out, int result) {
  addstring(ret, "inchi", out.szInChI);
  addstring(ret, "auxinfo", out.szAuxInfo);
  addstring(ret, "message", out.szMessage);
  addstring(ret, "log", out.szLog);
  ret->Set(NanSymbol("code"), Number::New(result));
}
<commit_msg>use NanNewLocal (0.11-friendly) to construct callback args<commit_after>/* inchi_input.cc
 * Copyright 2014 Cubane Canada, Inc.
 *
 * Released under the MIT license -- see MIT-LICENSE for details
 */
#include <node.h>
#include <v8.h>
#include <uv.h>
#include <nan.h>

#include <cstring>

#include "./inchi_input.h"

#include "./using_v8.h"

/**
 * Wrapper for INCHI_Input structure
 *
 * @module InChILib
 * @class  InchiInput
 */

/* local (non-API) functions */
static void populate_input(Handle<Value> val, InchiInput* in);
static void populate_ret(Handle<Object> ret,
                         const inchi_Output& out, int result);
static void addstring(Handle<Object> ret,
                      const char * name, const char * value);

/**
 * Create an InchiInput structure from a partially or fully specified
 * JavaScript object
 *
 * @method Create
 * @param {Handle<Object>} val Object handle that parallels an inchi_Input
 */
InchiInput * InchiInput::Create(Handle<Value> val) {
  // TODO(SOM): validation

  // create an empty InchiInput
  InchiInput * input = new InchiInput;

  // populate it
  populate_input(val, input);

  // return it
  return input;
}

Handle<Object> InchiInput::GetINCHIData::GetResult() {
  Local<Object> ret = Object::New();

  populate_ret(ret, this->out_, result_);

  return ret;
}

struct GetINCHIWorker : public NanAsyncWorker {
  InchiInput::GetINCHIData * data_;

  GetINCHIWorker(NanCallback * callback, InchiInput* input) :
    NanAsyncWorker(callback) {
    data_ = input->tearOffGetINCHIData();
  }
  ~GetINCHIWorker() {}

  void Execute() {
    data_->GetInchi();
  }

  void HandleOKCallback() {
    NanScope();

    Handle<Object> result = data_->GetResult();

    Local<Value> argv[] = {
      NanNewLocal<Value>(v8::Null()),
      NanNewLocal<Value>(result)
    };

    callback->Call(2, argv);
  }
};

/**
 * calls the "classic" GetINCHI function
 * @method GetINCHI
 * @param {Object}   molecule Description of molecule
 * @param {Function} callback Callback function
 */
NAN_METHOD(GetINCHI) {
  NanScope();

  InchiInput * input = NULL;
  Handle<Object> ret;

  try {
    // TODO(SOM): validate args
    Handle<Value> mol = args[0];
    NanCallback * callback = new NanCallback(args[1].As<Function>());

    input = InchiInput::Create(mol);

    NanAsyncQueueWorker(new GetINCHIWorker(callback, input));
  } catch(...) {
  }

  delete input;

  NanReturnUndefined();
};

void add_atom(InchiInput* in, Handle<Object> atom) {
  Handle<String> elname_string = atom->Get(NanSymbol("elname"))->ToString();

  char * elname = NanCString(elname_string, 0);
  int index = in->addAtom(elname);

  Handle<Array> neighbor =
    Handle<Array>::Cast(atom->Get(NanSymbol("neighbor")));

  int bonds = neighbor->Length();
  for (int i = 0; i < bonds; ++i) {
    int bonded = neighbor->Get(i)->ToNumber()->Value();
    in->addBond(index, bonded);
  }
}

static void populate_input(Handle<Value> val, InchiInput* in) {
  // TODO(SOM): support validation, possibly return error code

  // expect args[0] to be an Object, call it 'mol'
  // expect mol.atom to be an Array
  // expect mol.options to be a string
  // expect mol.stereo0D to be an Array

  if (!val->IsObject()) {
    return;
  }
  Handle<Object> mol = val->ToObject();

  if (!mol->Has(NanSymbol("atom")) || !mol->Get(NanSymbol("atom"))->IsArray()) {
    return;
  }
  Handle<Array> atom = Handle<Array>::Cast(mol->Get(NanSymbol("atom")));

  int atoms = atom->Length();
  for (int i = 0; i < atoms; i += 1) {
    add_atom(in, atom->Get(i)->ToObject());
  }
}

static void addstring(Handle<Object> ret,
                      const char * name, const char * value) {
  if (value) {
    ret->Set(NanSymbol(name), String::New(value));
  } else {
    ret->Set(NanSymbol(name), String::New(""));
  }
}

static void populate_ret(Handle<Object> ret,
                         const inchi_Output& out, int result) {
  addstring(ret, "inchi", out.szInChI);
  addstring(ret, "auxinfo", out.szAuxInfo);
  addstring(ret, "message", out.szMessage);
  addstring(ret, "log", out.szLog);
  ret->Set(NanSymbol("code"), Number::New(result));
}
<|endoftext|>


<commit_before>// https://github.com/KubaO/stackoverflown/tree/master/tooling

#include "backport.h"
#include "tooling.h"

#ifdef QT_WIDGETS_LIB

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if 0  // The Qt-4 style hooks work just fine and are portable.
#include <private/qhooks_p.h>
#endif
#endif
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QDir>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QPainter>
#include <QScreen>

#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
#include <QWindow>
#endif

namespace tooling {

struct Times {
   static int constexpr collect() { return 1000; }
   static int constexpr minCollect() { return 100; }
   static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }
};

static bool isProxied(QWidget *widget) {
   static EventLoopContext ctx;
   static PointerList<QWidget> proxied;
   Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());

   if (ctx.needsRearm()) {
      proxied = getProxiedWidgets();
      ctx.rearm();
   }
   return proxied.contains(widget);
}

static void takeScreenshot(int n, QWidget *w) {
   auto rect = shadowlessFrameGeometry(w->frameGeometry());
   if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);
   QPixmap pix;
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
   auto *const win = w->windowHandle();
   auto *const screen = win->screen();
   pix = screen->grabWindow(0);
#endif
   if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))
      pix = QPixmap::grabWindow(QApplication::desktop()->winId());

   if ((1)) {
      pix = pix.copy(rect);
   } else {
      QPainter p(&pix);
      p.drawRect(w->frameGeometry());
      p.end();
   }
   if (pix.isNull()) {
      qWarning() << "Discarding null screenshot of" << w;
      return;
   }
   auto const name = w->objectName();
   auto const fileName =
       QStringLiteral("screenshot_%1_%2%3.png")
           .arg(n)
           .arg(QLatin1String(w->metaObject()->className()))
           .arg(name.isNull() ? QString() : QStringLiteral("_%1").arg(name));
   QDir path = QCoreApplication::applicationDirPath();
   if (HostOsInfo::isMacHost() && path.path().endsWith(".app/Contents/MacOS")) {
      // store the widget in the app-containing folder, not in the bundle itself
      path.cdUp();
      path.cdUp();
      path.cdUp();
   }
   tooling::QSaveFile f(path.absoluteFilePath(fileName));
   if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, "PNG")) {
      qDebug() << "Took screenshot of" << w << ":" << f.fileName();
      if (!showInGraphicalShell(w, f.fileName(), n == 1))
         qWarning()
             << "Can't invoke the graphical file shell to show screenshot location.";
   } else {
      qWarning() << "Can't save screenshot" << f.fileName()
                 << "Error:" << f.errorString();
   }
}

class ScreenshotTaker : public QObject {
   static int n;
   QAtomicInt eventCount = 0;
   enum Phase { Collecting, Collected, Screenshot };
   enum State { Initial, Updated, Painted, Ignored };
   Phase phase = Collecting;
   QBasicTimer timer;
   QElapsedTimer time;
   struct TopLevel {
      QPointer<QWidget> w = {};
      State state = Initial;
      TopLevel() = default;
      explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}
      operator QWidget *() const { return w; }
      QWidget *operator->() const { return w; }
      bool operator==(QWidget *o) const { return o == w; }
   };
   QVector<TopLevel> topLevels;
   int leftToPaint = 0;
   void timerEvent(QTimerEvent *ev) override {
      if (ev->timerId() == timer.timerId()) {
         if (phase == Collecting || phase == Collected)
            scheduleScreenshots();
         else if (phase == Screenshot)
            takeScreenshots();
      }
   }
   void scheduleScreenshots() {
      qDebug() << "Deferring screenshots. Noted" << topLevels.count() << "widgets.";
      qApp->removeEventFilter(this);
      timer.start(Times::screenshotDelay(), this);
      phase = Screenshot;
   }
   void takeScreenshots() {
      if (qApp->property("no_screenshots").toBool())
         qDebug() << "Screenshot: Disabled by application property";
      else
         for (auto &tl : qAsConst(topLevels)) {
            if (!tl.w)
               continue;
            else if (!tl->isWindow()) {
            } else if (isProxied(tl))
               qDebug() << "Skipping proxied widget" << tl;
            else if (tl.state == Painted)
               takeScreenshot(++n, tl);
         }
      deleteLater();
   }
   bool eventFilter(QObject *o, QEvent *ev) override {
      static bool recursed;
      eventCount.fetchAndAddOrdered(1);
      if (recursed) return recursed = false;
      recursed = true;
      if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;
      auto *w = static_cast<QWidget *>(o);
      auto *window = w->window();
      auto i = std::find(topLevels.begin(), topLevels.end(), window);
      if (phase == Collecting && i == topLevels.end()) {
         topLevels.push_back(TopLevel(window));
         i = std::prev(topLevels.end());
         if (tooling::hasEventLoopSpunUp())
            qDebug() << "Noting" << window << "for a screenshot";
         leftToPaint++;
      } else if (i != topLevels.end()) {
         if (tooling::hasEventLoopSpunUp() && window->isVisible() &&
             i->state == Initial) {
            bool raise =
                QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();
            qDebug() << (raise ? "Raising" : "Updating") << window << "for a screnshot";
            if (raise) window->raise();
            window->update();
            i->state = Updated;
         }
         if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&
             i->state != Painted && i->state != Ignored) {
            i->state = Painted;
            (w != window ? qDebug() << window : qDebug()) << w << "painted";
            leftToPaint--;
         }
         if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {
            timer.stop();
            scheduleScreenshots();
         }
      }
      return recursed = false;
   }

  public:
   ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {
      if (parent) {
         Q_ASSERT(parent->isWindow());
         phase = Collected;
         topLevels.push_back(TopLevel(parent, Painted));
      } else {
         time.start();
         timer.start(Times::collect(), this);
      }
      qApp->installEventFilter(this);
   }
   ~ScreenshotTaker() override {
      qDebug() << "Saw" << eventCount << "events before taking screenshots.";
   }
};  // namespace tooling

int ScreenshotTaker::n;

void takeScreenshot(QWidget *widget) {
   Q_ASSERT(widget && widget->isWindow());
   if (isProxied(widget)) {
      qDebug() << "Skipping proxied widget" << widget;
      return;
   }
   if (!widget->isVisible()) {
      qDebug() << "Skipping hidden widget" << widget;
      return;
   }
   new ScreenshotTaker(widget);
}

static bool takeScreenshots(const HookData &) {
#ifdef NO_SCREENSHOTS
   return;
#endif
   if (qApp->property("no_screenshots").toBool()) {
      qDebug() << "Screenshot: Disabled by application property";
      return false;
   }
   qDebug() << "Screenshot: Startup";
   new ScreenshotTaker();
   return false;
}

static bool initialized = [] {
   registerHook(HasQApplicationHook, &takeScreenshots);
   return true;
}();

}  // namespace tooling

#endif  // QT_WIDGETS_LIB
<commit_msg>Fix savefile handling.<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/tooling

#include "backport.h"
#include "tooling.h"

#ifdef QT_WIDGETS_LIB

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#if 0  // The Qt-4 style hooks work just fine and are portable.
#include <private/qhooks_p.h>
#endif
#endif
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include <QDir>
#include <QElapsedTimer>
#include <QEvent>
#include <QFile>
#include <QPainter>
#include <QScreen>

#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
#include <QWindow>
#endif

namespace tooling {

struct Times {
   static int constexpr collect() { return 1000; }
   static int constexpr minCollect() { return 100; }
   static int constexpr screenshotDelay() { return HostOsInfo::isMacHost() ? 250 : 500; }
};

static bool isProxied(QWidget *widget) {
   static EventLoopContext ctx;
   static PointerList<QWidget> proxied;
   Q_ASSERT(widget && !wasDeleted(widget) && widget->isWindow());

   if (ctx.needsRearm()) {
      proxied = getProxiedWidgets();
      ctx.rearm();
   }
   return proxied.contains(widget);
}

static void takeScreenshot(int n, QWidget *w) {
   auto rect = shadowlessFrameGeometry(w->frameGeometry());
   if (HostOsInfo::isMacHost()) rect.adjust(-1, -1, 1, 1);
   QPixmap pix;
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
   auto *const win = w->windowHandle();
   auto *const screen = win->screen();
   pix = screen->grabWindow(0);
#endif
   if (QT_VERSION < QT_VERSION_CHECK(5, 3, 0))
      pix = QPixmap::grabWindow(QApplication::desktop()->winId());

   if ((1)) {
      pix = pix.copy(rect);
   } else {
      QPainter p(&pix);
      p.drawRect(w->frameGeometry());
      p.end();
   }
   if (pix.isNull()) {
      qWarning() << "Discarding null screenshot of" << w;
      return;
   }
   auto const name = w->objectName();
   auto const fileName =
       QStringLiteral("screenshot_%1_%2%3.png")
           .arg(n)
           .arg(QLatin1String(w->metaObject()->className()))
           .arg(name.isNull() ? QString() : QStringLiteral("_%1").arg(name));
   QDir path = QCoreApplication::applicationDirPath();
   if (HostOsInfo::isMacHost() && path.path().endsWith(".app/Contents/MacOS")) {
      // store the widget in the app-containing folder, not in the bundle itself
      path.cdUp();
      path.cdUp();
      path.cdUp();
   }
   tooling::QSaveFile f(path.absoluteFilePath(fileName));
   if (f.open(QIODevice::WriteOnly | QIODevice::Truncate) && pix.save(&f, "PNG") && f.commit()) {
      qDebug() << "Took screenshot of" << w << ":" << f.fileName();
      if (!showInGraphicalShell(w, f.fileName(), n == 1))
         qWarning()
             << "Can't invoke the graphical file shell to show screenshot location.";
   } else {
      qWarning() << "Can't save screenshot" << f.fileName()
                 << "Error:" << f.errorString();
   }
}

class ScreenshotTaker : public QObject {
   static int n;
   QAtomicInt eventCount = 0;
   enum Phase { Collecting, Collected, Screenshot };
   enum State { Initial, Updated, Painted, Ignored };
   Phase phase = Collecting;
   QBasicTimer timer;
   QElapsedTimer time;
   struct TopLevel {
      QPointer<QWidget> w = {};
      State state = Initial;
      TopLevel() = default;
      explicit TopLevel(QWidget *w, State state = Initial) : w(w), state(state) {}
      operator QWidget *() const { return w; }
      QWidget *operator->() const { return w; }
      bool operator==(QWidget *o) const { return o == w; }
   };
   QVector<TopLevel> topLevels;
   int leftToPaint = 0;
   void timerEvent(QTimerEvent *ev) override {
      if (ev->timerId() == timer.timerId()) {
         if (phase == Collecting || phase == Collected)
            scheduleScreenshots();
         else if (phase == Screenshot)
            takeScreenshots();
      }
   }
   void scheduleScreenshots() {
      qDebug() << "Deferring screenshots. Noted" << topLevels.count() << "widgets.";
      qApp->removeEventFilter(this);
      timer.start(Times::screenshotDelay(), this);
      phase = Screenshot;
   }
   void takeScreenshots() {
      if (qApp->property("no_screenshots").toBool())
         qDebug() << "Screenshot: Disabled by application property";
      else
         for (auto &tl : qAsConst(topLevels)) {
            if (!tl.w)
               continue;
            else if (!tl->isWindow()) {
            } else if (isProxied(tl))
               qDebug() << "Skipping proxied widget" << tl;
            else if (tl.state == Painted)
               takeScreenshot(++n, tl);
         }
      deleteLater();
   }
   bool eventFilter(QObject *o, QEvent *ev) override {
      static bool recursed;
      eventCount.fetchAndAddOrdered(1);
      if (recursed) return recursed = false;
      recursed = true;
      if (o->thread() != thread() || !o->isWidgetType()) return recursed = false;
      auto *w = static_cast<QWidget *>(o);
      auto *window = w->window();
      auto i = std::find(topLevels.begin(), topLevels.end(), window);
      if (phase == Collecting && i == topLevels.end()) {
         topLevels.push_back(TopLevel(window));
         i = std::prev(topLevels.end());
         if (tooling::hasEventLoopSpunUp())
            qDebug() << "Noting" << window << "for a screenshot";
         leftToPaint++;
      } else if (i != topLevels.end()) {
         if (tooling::hasEventLoopSpunUp() && window->isVisible() &&
             i->state == Initial) {
            bool raise =
                QT_VERSION < QT_VERSION_CHECK(5, 0, 0) && HostOsInfo::isMacHost();
            qDebug() << (raise ? "Raising" : "Updating") << window << "for a screnshot";
            if (raise) window->raise();
            window->update();
            i->state = Updated;
         }
         if ((ev->type() == QEvent::Paint || ev->type() == QEvent::UpdateRequest) &&
             i->state != Painted && i->state != Ignored) {
            i->state = Painted;
            (w != window ? qDebug() << window : qDebug()) << w << "painted";
            leftToPaint--;
         }
         if (leftToPaint == 0 && time.elapsed() > Times::minCollect()) {
            timer.stop();
            scheduleScreenshots();
         }
      }
      return recursed = false;
   }

  public:
   ScreenshotTaker(QWidget *parent = {}) : QObject(parent) {
      if (parent) {
         Q_ASSERT(parent->isWindow());
         phase = Collected;
         topLevels.push_back(TopLevel(parent, Painted));
      } else {
         time.start();
         timer.start(Times::collect(), this);
      }
      qApp->installEventFilter(this);
   }
   ~ScreenshotTaker() override {
      qDebug() << "Saw" << eventCount << "events before taking screenshots.";
   }
};  // namespace tooling

int ScreenshotTaker::n;

void takeScreenshot(QWidget *widget) {
   Q_ASSERT(widget && widget->isWindow());
   if (isProxied(widget)) {
      qDebug() << "Skipping proxied widget" << widget;
      return;
   }
   if (!widget->isVisible()) {
      qDebug() << "Skipping hidden widget" << widget;
      return;
   }
   new ScreenshotTaker(widget);
}

static bool takeScreenshots(const HookData &) {
#ifdef NO_SCREENSHOTS
   return;
#endif
   if (qApp->property("no_screenshots").toBool()) {
      qDebug() << "Screenshot: Disabled by application property";
      return false;
   }
   qDebug() << "Screenshot: Startup";
   new ScreenshotTaker();
   return false;
}

static bool initialized = [] {
   registerHook(HasQApplicationHook, &takeScreenshots);
   return true;
}();

}  // namespace tooling

#endif  // QT_WIDGETS_LIB
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/HeaderSearchOptions.h"

#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"

#include <iostream>
#include <vector>
#include <string>

int main( int argc, char **argv ) {

  llvm::llvm_shutdown_obj shutdownTrigger;

  //llvm::sys::PrintStackTraceOnErrorSignal();
  //llvm::PrettyStackTraceProgram X(argc, argv);

  // Set up the interpreter
  cling::Interpreter interp(argc, argv);
  if (interp.getOptions().Help) {
    return 0;
  }

  clang::CompilerInstance* CI = interp.getCI();
  interp.AddIncludePath(".");

  for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {
    interp.loadFile(interp.getOptions().LibsToLoad[I]);
  }

   bool ret = true;
   const std::vector<clang::FrontendInputFile>& Inputs
     = CI->getInvocation().getFrontendOpts().Inputs;

   // Interactive means no input (or one input that's "-")
   bool Interactive = Inputs.empty() || (Inputs.size() == 1
                                         && Inputs[0].File == "-");

   cling::UserInterface ui(interp);
   // If we are not interactive we're supposed to parse files
   if (!Interactive) {
     for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
       ui.getMetaProcessor()->process((".x " + Inputs[I].File).c_str());
       ret = !CI->getDiagnostics().getClient()->getNumErrors();
     }
   }
   else {
      cling::UserInterface ui(interp);
      ui.runInteractively(interp.getOptions().NoLogo);
   }

   // if we are running with -verify a reported has to be returned as unsuccess.
   // This is relevan especially for the test suite.
   if (CI->getDiagnosticOpts().VerifyDiagnostics)
     ret = !CI->getDiagnostics().getClient()->getNumErrors();

   return ret ? 0 : 1;
}
<commit_msg>unused include<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Lukasz Janyst <ljanyst@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/Basic/LangOptions.h"
#include "clang/Frontend/CompilerInstance.h"

#include "llvm/Support/Signals.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ManagedStatic.h"

#include <iostream>
#include <vector>
#include <string>

int main( int argc, char **argv ) {

  llvm::llvm_shutdown_obj shutdownTrigger;

  //llvm::sys::PrintStackTraceOnErrorSignal();
  //llvm::PrettyStackTraceProgram X(argc, argv);

  // Set up the interpreter
  cling::Interpreter interp(argc, argv);
  if (interp.getOptions().Help) {
    return 0;
  }

  clang::CompilerInstance* CI = interp.getCI();
  interp.AddIncludePath(".");

  for (size_t I = 0, N = interp.getOptions().LibsToLoad.size(); I < N; ++I) {
    interp.loadFile(interp.getOptions().LibsToLoad[I]);
  }

   bool ret = true;
   const std::vector<clang::FrontendInputFile>& Inputs
     = CI->getInvocation().getFrontendOpts().Inputs;

   // Interactive means no input (or one input that's "-")
   bool Interactive = Inputs.empty() || (Inputs.size() == 1
                                         && Inputs[0].File == "-");

   cling::UserInterface ui(interp);
   // If we are not interactive we're supposed to parse files
   if (!Interactive) {
     for (size_t I = 0, N = Inputs.size(); I < N; ++I) {
       ui.getMetaProcessor()->process((".x " + Inputs[I].File).c_str());
       ret = !CI->getDiagnostics().getClient()->getNumErrors();
     }
   }
   else {
      cling::UserInterface ui(interp);
      ui.runInteractively(interp.getOptions().NoLogo);
   }

   // if we are running with -verify a reported has to be returned as unsuccess.
   // This is relevan especially for the test suite.
   if (CI->getDiagnosticOpts().VerifyDiagnostics)
     ret = !CI->getDiagnostics().getClient()->getNumErrors();

   return ret ? 0 : 1;
}
<|endoftext|>


<commit_before>/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_Precompiled.h"
#include "MyGUI_ScrollView.h"
#include "MyGUI_SkinManager.h"
#include "MyGUI_ISubWidgetText.h"
#include "MyGUI_ScrollBar.h"

namespace MyGUI
{

	const int SCROLL_VIEW_MOUSE_WHEEL = 50; // колличество пикселей для колеса мыши
	const int SCROLL_VIEW_SCROLL_PAGE = 16; // колличество пикселей для кнопок скрола

	ScrollView::ScrollView() :
		mContentAlign(Align::Center),
		mRealClient(nullptr)
	{
		mChangeContentByResize = false;
		mContentAlign = Align::Center;
	}

	void ScrollView::initialiseOverride()
	{
		Base::initialiseOverride();

		// FIXME нам нужен фокус клавы
		setNeedKeyFocus(true);

		///@wskin_child{ScrollView, Widget, Client} Клиентская зона.
		assignWidget(mClient, "Client");
		MyGUI::Widget* realClientOwner = this;
		if (mClient != nullptr)
		{
			mClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);
			realClientOwner = mClient;
		}

		// создаем холcт, реальный владелец детей
		mRealClient = realClientOwner->createWidget<Widget>("Default", IntCoord(), Align::Default);
		mRealClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);
		setWidgetClient(mRealClient);

		///@wskin_child{ScrollView, ScrollBar, VScroll} Вертикальная полоса прокрутки.
		assignWidget(mVScroll, "VScroll");
		if (mVScroll != nullptr)
		{
			mVScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);
		}

		///@wskin_child{ScrollView, ScrollBar, HScroll} Горизонтальная полоса прокрутки.
		assignWidget(mHScroll, "HScroll");
		if (mHScroll != nullptr)
		{
			mHScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);
		}

		updateView();
	}

	void ScrollView::shutdownOverride()
	{
		mVScroll = nullptr;
		mHScroll = nullptr;
		mClient = nullptr;
		mRealClient = nullptr;

		Base::shutdownOverride();
	}

	void ScrollView::setPosition(const IntPoint& _point)
	{
		Base::setPosition(_point);
	}

	void ScrollView::setSize(const IntSize& _size)
	{
		Base::setSize(_size);

		updateView();
	}

	void ScrollView::setCoord(const IntCoord& _coord)
	{
		Base::setCoord(_coord);

		updateView();
	}

	void ScrollView::notifyScrollChangePosition(ScrollBar* _sender, size_t _position)
	{
		if (mRealClient == nullptr)
			return;

		if (_sender == mVScroll)
		{
			IntPoint point = mRealClient->getPosition();
			point.top = -(int)_position;
			mRealClient->setPosition(point);
		}
		else if (_sender == mHScroll)
		{
			IntPoint point = mRealClient->getPosition();
			point.left = -(int)_position;
			mRealClient->setPosition(point);
		}
	}

	void ScrollView::notifyMouseWheel(Widget* _sender, int _rel)
	{
		if (mRealClient == nullptr)
			return;

		if (mVRange != 0)
		{
			IntPoint point = mRealClient->getPosition();
			int offset = -point.top;
			if (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;
			else  offset -= SCROLL_VIEW_MOUSE_WHEEL;

			if (offset < 0) offset = 0;
			else if (offset > (int)mVRange) offset = mVRange;

			if (offset != point.top)
			{
				point.top = -offset;
				if (mVScroll != nullptr)
				{
					mVScroll->setScrollPosition(offset);
				}
				mRealClient->setPosition(point);
			}
		}
		else if (mHRange != 0)
		{
			IntPoint point = mRealClient->getPosition();
			int offset = -point.left;
			if (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;
			else  offset -= SCROLL_VIEW_MOUSE_WHEEL;

			if (offset < 0) offset = 0;
			else if (offset > (int)mHRange) offset = mHRange;

			if (offset != point.left)
			{
				point.left = -offset;
				if (mHScroll != nullptr)
				{
					mHScroll->setScrollPosition(offset);
				}
				mRealClient->setPosition(point);
			}
		}
	}

	IntSize ScrollView::getContentSize()
	{
		return mRealClient == nullptr ? IntSize() : mRealClient->getSize();
	}

	IntPoint ScrollView::getContentPosition()
	{
		return mRealClient == nullptr ? IntPoint() : (IntPoint() - mRealClient->getPosition());
	}

	void ScrollView::setContentPosition(const IntPoint& _point)
	{
		if (mRealClient != nullptr)
			mRealClient->setPosition(IntPoint() - _point);
	}

	IntSize ScrollView::getViewSize()
	{
		return mClient == nullptr ? getSize() : mClient->getSize();
	}

	size_t ScrollView::getVScrollPage()
	{
		return SCROLL_VIEW_SCROLL_PAGE;
	}

	size_t ScrollView::getHScrollPage()
	{
		return SCROLL_VIEW_SCROLL_PAGE;
	}

	void ScrollView::updateView()
	{
		updateScrollSize();
		updateScrollPosition();
	}

	void ScrollView::setVisibleVScroll(bool _value)
	{
		mVisibleVScroll = _value;
		updateView();
	}

	void ScrollView::setVisibleHScroll(bool _value)
	{
		mVisibleHScroll = _value;
		updateView();
	}

	void ScrollView::setCanvasAlign(Align _value)
	{
		mContentAlign = _value;
		updateView();
	}

	void ScrollView::setCanvasSize(const IntSize& _value)
	{
		if (mRealClient != nullptr)
			mRealClient->setSize(_value);
		updateView();
	}

	IntSize ScrollView::getCanvasSize()
	{
		return mRealClient == nullptr ? IntSize() : mRealClient->getSize();
	}

	void ScrollView::setPropertyOverride(const std::string& _key, const std::string& _value)
	{
		/// @wproperty{ScrollView, VisibleVScroll, bool} Видимость вертикальной полосы прокрутки.
		if (_key == "VisibleVScroll")
			setVisibleVScroll(utility::parseValue<bool>(_value));

		/// @wproperty{ScrollView, VisibleHScroll, bool} Видимость горизонтальной полосы прокрутки.
		else if (_key == "VisibleHScroll")
			setVisibleHScroll(utility::parseValue<bool>(_value));

		/// @wproperty{ScrollView, CanvasAlign, Align} Выравнивание содержимого.
		else if (_key == "CanvasAlign")
			setCanvasAlign(utility::parseValue<Align>(_value));

		/// @wproperty{ScrollView, CanvasSize, int int} Размер содержимого.
		else if (_key == "CanvasSize")
			setCanvasSize(utility::parseValue<IntSize>(_value));

		else
		{
			Base::setPropertyOverride(_key, _value);
			return;
		}

		eventChangeProperty(this, _key, _value);
	}

	void ScrollView::setPosition(int _left, int _top)
	{
		setPosition(IntPoint(_left, _top));
	}

	void ScrollView::setSize(int _width, int _height)
	{
		setSize(IntSize(_width, _height));
	}

	void ScrollView::setCoord(int _left, int _top, int _width, int _height)
	{
		setCoord(IntCoord(_left, _top, _width, _height));
	}

	bool ScrollView::isVisibleVScroll() const
	{
		return mVisibleVScroll;
	}

	bool ScrollView::isVisibleHScroll() const
	{
		return mVisibleHScroll;
	}

	Align ScrollView::getCanvasAlign() const
	{
		return mContentAlign;
	}

	void ScrollView::setCanvasSize(int _width, int _height)
	{
		setCanvasSize(IntSize(_width, _height));
	}

	Align ScrollView::getContentAlign()
	{
		return mContentAlign;
	}

	void ScrollView::setViewOffset(const IntPoint& _value)
	{
		IntPoint value = _value;
		IntPoint currentOffset = mRealClient->getPosition();

		if (mHRange != 0)
		{
			if (value.left > 0)
				value.left = 0;
			else if (value.left < -(int)mHRange)
				value.left = -(int)mHRange;
		}
		else
		{
			value.left = currentOffset.left;
		}

		if (mVRange != 0)
		{
			if (value.top > 0)
				value.top = 0;
			else if (value.top < -(int)mVRange)
				value.top = -(int)mVRange;
		}
		else
		{
			value.top = currentOffset.top;
		}

		if (mHScroll != nullptr)
			mHScroll->setScrollPosition(-value.left);

		if (mVScroll != nullptr)
			mVScroll->setScrollPosition(-value.top);

		mRealClient->setPosition(value);
	}

	IntPoint ScrollView::getViewOffset() const
	{
		return mRealClient->getPosition();
	}

	IntCoord ScrollView::getViewCoord() const
	{
		return mClient == nullptr ? getCoord() : mClient->getCoord();
	}

	ScrollBar* ScrollView::getVScroll()
	{
		return mVScroll;
	}

} // namespace MyGUI
<commit_msg>Made canvas size adjust by the scaling factor if it is set as a property.<commit_after>/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_Precompiled.h"
#include "MyGUI_ScrollView.h"
#include "MyGUI_SkinManager.h"
#include "MyGUI_ISubWidgetText.h"
#include "MyGUI_ScrollBar.h"
#include "MyGUI_Gui.h"

namespace MyGUI
{

	const int SCROLL_VIEW_MOUSE_WHEEL = 50; // колличество пикселей для колеса мыши
	const int SCROLL_VIEW_SCROLL_PAGE = 16; // колличество пикселей для кнопок скрола

	ScrollView::ScrollView() :
		mContentAlign(Align::Center),
		mRealClient(nullptr)
	{
		mChangeContentByResize = false;
		mContentAlign = Align::Center;
	}

	void ScrollView::initialiseOverride()
	{
		Base::initialiseOverride();

		// FIXME нам нужен фокус клавы
		setNeedKeyFocus(true);

		///@wskin_child{ScrollView, Widget, Client} Клиентская зона.
		assignWidget(mClient, "Client");
		MyGUI::Widget* realClientOwner = this;
		if (mClient != nullptr)
		{
			mClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);
			realClientOwner = mClient;
		}

		// создаем холcт, реальный владелец детей
		mRealClient = realClientOwner->createWidget<Widget>("Default", IntCoord(), Align::Default);
		mRealClient->eventMouseWheel += newDelegate(this, &ScrollView::notifyMouseWheel);
		setWidgetClient(mRealClient);

		///@wskin_child{ScrollView, ScrollBar, VScroll} Вертикальная полоса прокрутки.
		assignWidget(mVScroll, "VScroll");
		if (mVScroll != nullptr)
		{
			mVScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);
		}

		///@wskin_child{ScrollView, ScrollBar, HScroll} Горизонтальная полоса прокрутки.
		assignWidget(mHScroll, "HScroll");
		if (mHScroll != nullptr)
		{
			mHScroll->eventScrollChangePosition += newDelegate(this, &ScrollView::notifyScrollChangePosition);
		}

		updateView();
	}

	void ScrollView::shutdownOverride()
	{
		mVScroll = nullptr;
		mHScroll = nullptr;
		mClient = nullptr;
		mRealClient = nullptr;

		Base::shutdownOverride();
	}

	void ScrollView::setPosition(const IntPoint& _point)
	{
		Base::setPosition(_point);
	}

	void ScrollView::setSize(const IntSize& _size)
	{
		Base::setSize(_size);

		updateView();
	}

	void ScrollView::setCoord(const IntCoord& _coord)
	{
		Base::setCoord(_coord);

		updateView();
	}

	void ScrollView::notifyScrollChangePosition(ScrollBar* _sender, size_t _position)
	{
		if (mRealClient == nullptr)
			return;

		if (_sender == mVScroll)
		{
			IntPoint point = mRealClient->getPosition();
			point.top = -(int)_position;
			mRealClient->setPosition(point);
		}
		else if (_sender == mHScroll)
		{
			IntPoint point = mRealClient->getPosition();
			point.left = -(int)_position;
			mRealClient->setPosition(point);
		}
	}

	void ScrollView::notifyMouseWheel(Widget* _sender, int _rel)
	{
		if (mRealClient == nullptr)
			return;

		if (mVRange != 0)
		{
			IntPoint point = mRealClient->getPosition();
			int offset = -point.top;
			if (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;
			else  offset -= SCROLL_VIEW_MOUSE_WHEEL;

			if (offset < 0) offset = 0;
			else if (offset > (int)mVRange) offset = mVRange;

			if (offset != point.top)
			{
				point.top = -offset;
				if (mVScroll != nullptr)
				{
					mVScroll->setScrollPosition(offset);
				}
				mRealClient->setPosition(point);
			}
		}
		else if (mHRange != 0)
		{
			IntPoint point = mRealClient->getPosition();
			int offset = -point.left;
			if (_rel < 0) offset += SCROLL_VIEW_MOUSE_WHEEL;
			else  offset -= SCROLL_VIEW_MOUSE_WHEEL;

			if (offset < 0) offset = 0;
			else if (offset > (int)mHRange) offset = mHRange;

			if (offset != point.left)
			{
				point.left = -offset;
				if (mHScroll != nullptr)
				{
					mHScroll->setScrollPosition(offset);
				}
				mRealClient->setPosition(point);
			}
		}
	}

	IntSize ScrollView::getContentSize()
	{
		return mRealClient == nullptr ? IntSize() : mRealClient->getSize();
	}

	IntPoint ScrollView::getContentPosition()
	{
		return mRealClient == nullptr ? IntPoint() : (IntPoint() - mRealClient->getPosition());
	}

	void ScrollView::setContentPosition(const IntPoint& _point)
	{
		if (mRealClient != nullptr)
			mRealClient->setPosition(IntPoint() - _point);
	}

	IntSize ScrollView::getViewSize()
	{
		return mClient == nullptr ? getSize() : mClient->getSize();
	}

	size_t ScrollView::getVScrollPage()
	{
		return SCROLL_VIEW_SCROLL_PAGE;
	}

	size_t ScrollView::getHScrollPage()
	{
		return SCROLL_VIEW_SCROLL_PAGE;
	}

	void ScrollView::updateView()
	{
		updateScrollSize();
		updateScrollPosition();
	}

	void ScrollView::setVisibleVScroll(bool _value)
	{
		mVisibleVScroll = _value;
		updateView();
	}

	void ScrollView::setVisibleHScroll(bool _value)
	{
		mVisibleHScroll = _value;
		updateView();
	}

	void ScrollView::setCanvasAlign(Align _value)
	{
		mContentAlign = _value;
		updateView();
	}

	void ScrollView::setCanvasSize(const IntSize& _value)
	{
		if (mRealClient != nullptr)
			mRealClient->setSize(_value);
		updateView();
	}

	IntSize ScrollView::getCanvasSize()
	{
		return mRealClient == nullptr ? IntSize() : mRealClient->getSize();
	}

	void ScrollView::setPropertyOverride(const std::string& _key, const std::string& _value)
	{
		/// @wproperty{ScrollView, VisibleVScroll, bool} Видимость вертикальной полосы прокрутки.
		if (_key == "VisibleVScroll")
			setVisibleVScroll(utility::parseValue<bool>(_value));

		/// @wproperty{ScrollView, VisibleHScroll, bool} Видимость горизонтальной полосы прокрутки.
		else if (_key == "VisibleHScroll")
			setVisibleHScroll(utility::parseValue<bool>(_value));

		/// @wproperty{ScrollView, CanvasAlign, Align} Выравнивание содержимого.
		else if (_key == "CanvasAlign")
			setCanvasAlign(utility::parseValue<Align>(_value));

		/// @wproperty{ScrollView, CanvasSize, int int} Размер содержимого.
		else if (_key == "CanvasSize")
			setCanvasSize(utility::parseValue<IntSize>(_value) * Gui::getInstance().getScaleFactor());

		else
		{
			Base::setPropertyOverride(_key, _value);
			return;
		}

		eventChangeProperty(this, _key, _value);
	}

	void ScrollView::setPosition(int _left, int _top)
	{
		setPosition(IntPoint(_left, _top));
	}

	void ScrollView::setSize(int _width, int _height)
	{
		setSize(IntSize(_width, _height));
	}

	void ScrollView::setCoord(int _left, int _top, int _width, int _height)
	{
		setCoord(IntCoord(_left, _top, _width, _height));
	}

	bool ScrollView::isVisibleVScroll() const
	{
		return mVisibleVScroll;
	}

	bool ScrollView::isVisibleHScroll() const
	{
		return mVisibleHScroll;
	}

	Align ScrollView::getCanvasAlign() const
	{
		return mContentAlign;
	}

	void ScrollView::setCanvasSize(int _width, int _height)
	{
		setCanvasSize(IntSize(_width, _height));
	}

	Align ScrollView::getContentAlign()
	{
		return mContentAlign;
	}

	void ScrollView::setViewOffset(const IntPoint& _value)
	{
		IntPoint value = _value;
		IntPoint currentOffset = mRealClient->getPosition();

		if (mHRange != 0)
		{
			if (value.left > 0)
				value.left = 0;
			else if (value.left < -(int)mHRange)
				value.left = -(int)mHRange;
		}
		else
		{
			value.left = currentOffset.left;
		}

		if (mVRange != 0)
		{
			if (value.top > 0)
				value.top = 0;
			else if (value.top < -(int)mVRange)
				value.top = -(int)mVRange;
		}
		else
		{
			value.top = currentOffset.top;
		}

		if (mHScroll != nullptr)
			mHScroll->setScrollPosition(-value.left);

		if (mVScroll != nullptr)
			mVScroll->setScrollPosition(-value.top);

		mRealClient->setPosition(value);
	}

	IntPoint ScrollView::getViewOffset() const
	{
		return mRealClient->getPosition();
	}

	IntCoord ScrollView::getViewCoord() const
	{
		return mClient == nullptr ? getCoord() : mClient->getCoord();
	}

	ScrollBar* ScrollView::getVScroll()
	{
		return mVScroll;
	}

} // namespace MyGUI
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

// This is a simple OpenCL Hello World that tests you have a functioning OpenCL setup.

#include "cl.hpp"
#include <initializer_list>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>

static inline void assert_cl(cl_int rc, const char* file, int line) {
    if (rc != CL_SUCCESS) {
        fprintf(stderr, "%s:%d, got OpenCL error code %d\n", file,line,rc);
        exit(1);
    }
}
#define cl_ok(err) assert_cl(err, __FILE__, __LINE__)

int main(int argc, char** argv) {
    // Find any OpenCL platform+device with these substrings.
    const char* platform_match = argc > 1 ? argv[1] : "";
    const char* device_match   = argc > 2 ? argv[2] : "";

    cl::Platform platform;
    {
        std::vector<cl::Platform> platforms;
        cl_ok(cl::Platform::get(&platforms));

        bool found = false;
        for (cl::Platform p : platforms) {
            std::string name;
            cl_ok(p.getInfo(CL_PLATFORM_NAME, &name));

            fprintf(stdout, "Available platform %s\n", name.c_str());

            if (name.find(platform_match) != std::string::npos) {
                platform = p;
                found = true;
            }
        }
        if (!found) {
            fprintf(stderr, "No platform containing '%s' found.\n", platform_match);
            exit(1);
        }
    }

    cl::Device device;
    {
        std::vector<cl::Device> devices;
        cl_ok(platform.getDevices(CL_DEVICE_TYPE_ALL, &devices));

        bool found = false;
        for (cl::Device d : devices) {
            std::string name,
                        version,
                        driver;
            cl_ok(d.getInfo(CL_DEVICE_NAME,    &name));
            cl_ok(d.getInfo(CL_DEVICE_VERSION, &version));
            cl_ok(d.getInfo(CL_DRIVER_VERSION, &driver));

            fprintf(stdout, "Available device %s%s, driver version %s\n"
                          , version.c_str(), name.c_str(), driver.c_str());

            if (name.find(device_match) != std::string::npos) {
                device = d;
                found = true;
            }
        }
        if (!found) {
            fprintf(stderr, "No device containing '%s' found.\n", device_match);
            exit(2);
        }
    }

    std::string name,
                vendor,
                extensions;
    cl_ok(device.getInfo(CL_DEVICE_NAME,       &name));
    cl_ok(device.getInfo(CL_DEVICE_VENDOR,     &vendor));
    cl_ok(device.getInfo(CL_DEVICE_EXTENSIONS, &extensions));

    fprintf(stdout, "Using %s, vendor %s, extensions:\n%s\n",
            name.c_str(), vendor.c_str(), extensions.c_str());

    std::vector<cl::Device> devices = { device };

    // Some APIs can't return their cl_int error but might still fail,
    // so they take a pointer.  cl_ok() is really handy here too.
    cl_int ok;
    cl::Context ctx(devices,
                    nullptr/*optional cl_context_properties*/,
                    nullptr/*optional error reporting callback*/,
                    nullptr/*context arguement for error reporting callback*/,
                    &ok);
    cl_ok(ok);

    cl::Program program(ctx,
                        "__kernel void mul(__global const float* a,    "
                        "                  __global const float* b,    "
                        "                  __global       float* dst) {"
                        "    int i = get_global_id(0);                 "
                        "    dst[i] = a[i] * b[i];                     "
                        "}                                             ",
                        /*and build now*/true,
                        &ok);
    cl_ok(ok);

    std::vector<float> a,b,p;
    for (int i = 0; i < 1000; i++) {
        a.push_back(+i);
        b.push_back(-i);
        p.push_back( 0);
    }

    cl::Buffer A(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*a.size(), a.data()),
               B(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*b.size(), b.data()),
               P(ctx, CL_MEM_WRITE_ONLY| CL_MEM_HOST_READ_ONLY, sizeof(float)*p.size());

    cl::Kernel mul(program, "mul", &ok);
    cl_ok(ok);
    cl_ok(mul.setArg(0, A));
    cl_ok(mul.setArg(1, B));
    cl_ok(mul.setArg(2, P));

    cl::CommandQueue queue(ctx, device);

    cl_ok(queue.enqueueNDRangeKernel(mul, cl::NDRange(0)  /*offset*/
                                        , cl::NDRange(1000) /*size*/));

    cl_ok(queue.enqueueReadBuffer(P, true/*block until read is done*/
                                   , 0                     /*offset in bytes*/
                                   , sizeof(float)*p.size() /*size in bytes*/
                                   , p.data()));

    for (int i = 0; i < 1000; i++) {
        if (p[i] != a[i]*b[i]) {
            return 1;
        }
    }

    fprintf(stdout, "OpenCL sez: %g x %g = %g\n", a[42], b[42], p[42]);
    return 0;
}
<commit_msg>run all available OpenCL devices<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

// This is a simple OpenCL Hello World that tests you have a functioning OpenCL setup.

#include "cl.hpp"
#include <initializer_list>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>

static inline void assert_cl(cl_int rc, const char* file, int line) {
    if (rc != CL_SUCCESS) {
        fprintf(stderr, "%s:%d, got OpenCL error code %d\n", file,line,rc);
        exit(1);
    }
}
#define cl_ok(err) assert_cl(err, __FILE__, __LINE__)

int main(int, char**) {
    std::vector<cl::Platform> platforms;
    cl_ok(cl::Platform::get(&platforms));

    std::vector<cl::Device> devices;
    for (cl::Platform platform : platforms) {
        std::vector<cl::Device> platform_devices;
        cl_ok(platform.getDevices(CL_DEVICE_TYPE_ALL, &platform_devices));
        devices.insert(devices.end(), platform_devices.begin(), platform_devices.end());
    }

    if (devices.empty()) {
        fprintf(stderr, "No OpenCL devices available. :(\n");
        return 1;
    }

    // To keep things simple we'll only create single-device cl::Contexts.
    for (cl::Device device : devices) {
        std::string name,
                    version,
                    driver,
                    vendor,
                    extensions;
        cl_ok(device.getInfo(CL_DEVICE_NAME,       &name));
        cl_ok(device.getInfo(CL_DEVICE_VERSION,    &version));
        cl_ok(device.getInfo(CL_DEVICE_VENDOR,     &vendor));
        cl_ok(device.getInfo(CL_DEVICE_EXTENSIONS, &extensions));
        cl_ok(device.getInfo(CL_DRIVER_VERSION,    &driver));

        fprintf(stdout, "Using %s%s, vendor %s, version %s, extensions:\n%s\n",
                version.c_str(), name.c_str(), vendor.c_str(), driver.c_str(), extensions.c_str());

        std::vector<cl::Device> devices = { device };

        // Some APIs can't return their cl_int error but might still fail,
        // so they take a pointer.  cl_ok() is really handy here too.
        cl_int ok;
        cl::Context ctx(devices,
                        nullptr/*optional cl_context_properties*/,
                        nullptr/*optional error reporting callback*/,
                        nullptr/*context argument for error reporting callback*/,
                        &ok);
        cl_ok(ok);

        cl::Program program(ctx,
                            "__kernel void mul(__global const float* a,    "
                            "                  __global const float* b,    "
                            "                  __global       float* dst) {"
                            "    int i = get_global_id(0);                 "
                            "    dst[i] = a[i] * b[i];                     "
                            "}                                             ",
                            /*and build now*/true,
                            &ok);
        cl_ok(ok);

        std::vector<float> a,b,p;
        for (int i = 0; i < 1000; i++) {
            a.push_back(+i);
            b.push_back(-i);
            p.push_back( 0);
        }

        cl::Buffer
            A(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*a.size(), a.data()),
            B(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR , sizeof(float)*b.size(), b.data()),
            P(ctx, CL_MEM_WRITE_ONLY| CL_MEM_HOST_READ_ONLY, sizeof(float)*p.size());

        cl::Kernel mul(program, "mul", &ok);
        cl_ok(ok);
        cl_ok(mul.setArg(0, A));
        cl_ok(mul.setArg(1, B));
        cl_ok(mul.setArg(2, P));

        cl::CommandQueue queue(ctx, device);

        cl_ok(queue.enqueueNDRangeKernel(mul, cl::NDRange(0)  /*offset*/
                                            , cl::NDRange(1000) /*size*/));

        cl_ok(queue.enqueueReadBuffer(P, true/*block until read is done*/
                                       , 0                     /*offset in bytes*/
                                       , sizeof(float)*p.size() /*size in bytes*/
                                       , p.data()));

        fprintf(stdout, "OpenCL sez: %g x %g = %g\n", a[42], b[42], p[42]);
        for (int i = 0; i < 1000; i++) {
            if (p[i] != a[i]*b[i]) {
                return 1;
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "sitkCastImageFilter.h"
#include "sitkCastImageFilter.txx"

namespace itk
{
namespace simple
{

void CastImageFilter::RegisterMemberFactory2()
{

  // cast between vector images
  m_DualMemberFactory->RegisterMemberFunctions<VectorPixelIDTypeList, VectorPixelIDTypeList, 2, CastAddressor<MemberFunctionType> > ();

  // basic to vector
  m_DualMemberFactory->RegisterMemberFunctions<BasicPixelIDTypeList, VectorPixelIDTypeList, 2, ToVectorAddressor<MemberFunctionType> > ();

}

} // end namespace simple
} // end namespace itk
<commit_msg>BUG: incorrect function name in CastImageFilter instiation file<commit_after>#include "sitkCastImageFilter.h"
#include "sitkCastImageFilter.txx"

namespace itk
{
namespace simple
{

void CastImageFilter::RegisterMemberFactory2v()
{

  // cast between vector images
  m_DualMemberFactory->RegisterMemberFunctions<VectorPixelIDTypeList, VectorPixelIDTypeList, 2, CastAddressor<MemberFunctionType> > ();

  // basic to vector
  m_DualMemberFactory->RegisterMemberFunctions<BasicPixelIDTypeList, VectorPixelIDTypeList, 2, ToVectorAddressor<MemberFunctionType> > ();

}

} // end namespace simple
} // end namespace itk
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSpectralSensitivityReader.h"

#include "base/ossimFilename.h"
#include <fstream>
#include "otbSpotImageMetadataInterface.h"
#include "itkExceptionObject.h"

namespace otb
{
SpectralSensitivityReader
::SpectralSensitivityReader() :
  m_FileName(""),
  m_DataPath("")
{
  this->Superclass::SetNumberOfRequiredOutputs(1);
  this->Superclass::SetNthOutput(0, WavelengthSpectralBandVectorType::New().GetPointer());
  m_Image = ImageType::New();
}

SpectralSensitivityReader
::~SpectralSensitivityReader()
{
}

SpectralSensitivityReader::WavelengthSpectralBandVectorType *
SpectralSensitivityReader
::GetOutput()
{
  if (this->GetNumberOfOutputs() < 1)
    {
    return 0;
    }
  return static_cast<WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));
}

const SpectralSensitivityReader::WavelengthSpectralBandVectorType *
SpectralSensitivityReader
::GetOutput() const
{
  if (this->GetNumberOfOutputs() < 1)
    {
    return 0;
    }
  return static_cast<const WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));
}

void
SpectralSensitivityReader
::FindFileName()
{
  if (m_Image.IsNull())
    {
    itkExceptionMacro(<< "An input image has to be set or set directly the filename");
    }

  ossimString        sensor("");
  itk::OStringStream oss;

  try
    {
    SpotImageMetadataInterface::Pointer lImageMetadata = SpotImageMetadataInterface::New();
    sensor = ossimString(lImageMetadata->GetSensorID());
    sensor.upcase();
    // Suppress spaces
    for (unsigned int i = 0; i < sensor.size() - 1; i++)
      {
      if (sensor.compare(i, 1, " ") == 0)
        {
        sensor.erase(i, 1);
        i--;
        }
      }

    oss.str("");
    oss << lImageMetadata->GetInstrument();
    oss << lImageMetadata->GetInstrumentIndex();
    }
  catch (itk::ExceptionObject& err)
    {
    itkExceptionMacro(<< "Invalid input image");
    }

  std::string instrument = oss.str();

  oss.str("");
  oss << m_DataPath;
  oss << "/";
  oss << sensor;
  oss << "/";
  oss << instrument;
  oss << "/rep6S.dat";

  m_FileName = oss.str();
}

void
SpectralSensitivityReader
::GenerateData()
{
  if (m_FileName == "") this->FindFileName();

  WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();

  ossimFilename fname(m_FileName);
  if (!fname.exists()) itkExceptionMacro(<< m_FileName << " does not exist.");

  std::ifstream file(fname.c_str());
  if (!file) itkExceptionMacro(<< "Enable to read " << fname << " file.");

  std::string line;
  ossimString separator = " ";
  double      mini = 0;
  double      maxi = 0.;
  bool        firstLine = true;

  unsigned int nbBands = 0;
  // used to store the coef
  std::vector<ValuesVectorType> valuesVector;

  while (std::getline(file, line))
    {
    ossimString osLine(line);

    // Suppress multiple spaces
    for (unsigned int i = 0; i < osLine.size() - 1; i++)
      {
      if (osLine.compare(i, 1, " ") == 0 && osLine.compare(i + 1, 1, " ") == 0)
        {
        osLine.erase(i + 1, 1);
        i--;
        }
      }
    // if the first character is a space, erase it
    if (osLine.compare(0, 1, " ") == 0) osLine.erase(0, 1);

    std::vector<ossimString> keywordStrings = osLine.split(separator);

    if (keywordStrings.size() < 3) itkExceptionMacro(<< "Invalid file format");

    // Store min wavelength
    if (firstLine)
      {
      mini = keywordStrings[0].toDouble();
      nbBands = keywordStrings.size() - 2;
      for (unsigned int j = 0; j < nbBands; j++)
        {
        wavelengthSpectralBand->PushBack(FilterFunctionValues::New());
        ValuesVectorType temp;
        valuesVector.push_back(temp);
        }
      firstLine = false;
      }

    if (nbBands != keywordStrings.size() - 2) itkExceptionMacro(<< "Invalid file format");

    for (unsigned int i = 0; i < nbBands; i++)
      {
      valuesVector[i].push_back(keywordStrings[i + 2].toDouble());
      }

    maxi = keywordStrings[0].toDouble();
    } //while ( std::getline( file, line ) )

  for (unsigned int j = 0; j < nbBands; j++)
    {
    wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(valuesVector[j]);
    wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(mini);
    wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(maxi);
    }
}

/**PrintSelf method */
void
SpectralSensitivityReader
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  os << "DataPath: " << m_DataPath << std::endl;
  if (m_FileName != "") os << "FileName: " << m_FileName << std::endl;

  // Function values print :
  const WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();
  os << "Filter function values: " << std::endl;
  for (unsigned int i = 0; i < wavelengthSpectralBand->Size(); ++i)
    {
    os << indent << "Channel " << i + 1 << " : " << std::endl;
    os << indent << wavelengthSpectralBand->GetNthElement(i) << std::endl;
    }
}

} // end namespace otb
<commit_msg>BUG: side effect of MetadataInterface redesign<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSpectralSensitivityReader.h"

#include "base/ossimFilename.h"
#include <fstream>
#include "otbSpotImageMetadataInterface.h"
#include "itkExceptionObject.h"

namespace otb
{
SpectralSensitivityReader
::SpectralSensitivityReader() :
  m_FileName(""),
  m_DataPath("")
{
  this->Superclass::SetNumberOfRequiredOutputs(1);
  this->Superclass::SetNthOutput(0, WavelengthSpectralBandVectorType::New().GetPointer());
  m_Image = ImageType::New();
}

SpectralSensitivityReader
::~SpectralSensitivityReader()
{
}

SpectralSensitivityReader::WavelengthSpectralBandVectorType *
SpectralSensitivityReader
::GetOutput()
{
  if (this->GetNumberOfOutputs() < 1)
    {
    return 0;
    }
  return static_cast<WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));
}

const SpectralSensitivityReader::WavelengthSpectralBandVectorType *
SpectralSensitivityReader
::GetOutput() const
{
  if (this->GetNumberOfOutputs() < 1)
    {
    return 0;
    }
  return static_cast<const WavelengthSpectralBandVectorType *> (this->ProcessObject::GetOutput(0));
}

void
SpectralSensitivityReader
::FindFileName()
{
  if (m_Image.IsNull())
    {
    itkExceptionMacro(<< "An input image has to be set or set directly the filename");
    }

  ossimString        sensor("");
  itk::OStringStream oss;

  try
    {
    SpotImageMetadataInterface::Pointer lImageMetadata = SpotImageMetadataInterface::New();
    lImageMetadata->SetMetaDataDictionary(m_Image->GetMetaDataDictionary());
    sensor = ossimString(lImageMetadata->GetSensorID());
    sensor.upcase();
    // Suppress spaces
    for (unsigned int i = 0; i < sensor.size() - 1; i++)
      {
      if (sensor.compare(i, 1, " ") == 0)
        {
        sensor.erase(i, 1);
        i--;
        }
      }

    oss.str("");
    oss << lImageMetadata->GetInstrument();
    oss << lImageMetadata->GetInstrumentIndex();
    }
  catch (itk::ExceptionObject& err)
    {
    itkExceptionMacro(<< "Invalid input image");
    }

  std::string instrument = oss.str();

  oss.str("");
  oss << m_DataPath;
  oss << "/";
  oss << sensor;
  oss << "/";
  oss << instrument;
  oss << "/rep6S.dat";

  m_FileName = oss.str();
}

void
SpectralSensitivityReader
::GenerateData()
{
  if (m_FileName == "") this->FindFileName();

  WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();

  ossimFilename fname(m_FileName);
  if (!fname.exists()) itkExceptionMacro(<< m_FileName << " does not exist.");

  std::ifstream file(fname.c_str());
  if (!file) itkExceptionMacro(<< "Enable to read " << fname << " file.");

  std::string line;
  ossimString separator = " ";
  double      mini = 0;
  double      maxi = 0.;
  bool        firstLine = true;

  unsigned int nbBands = 0;
  // used to store the coef
  std::vector<ValuesVectorType> valuesVector;

  while (std::getline(file, line))
    {
    ossimString osLine(line);

    // Suppress multiple spaces
    for (unsigned int i = 0; i < osLine.size() - 1; i++)
      {
      if (osLine.compare(i, 1, " ") == 0 && osLine.compare(i + 1, 1, " ") == 0)
        {
        osLine.erase(i + 1, 1);
        i--;
        }
      }
    // if the first character is a space, erase it
    if (osLine.compare(0, 1, " ") == 0) osLine.erase(0, 1);

    std::vector<ossimString> keywordStrings = osLine.split(separator);

    if (keywordStrings.size() < 3) itkExceptionMacro(<< "Invalid file format");

    // Store min wavelength
    if (firstLine)
      {
      mini = keywordStrings[0].toDouble();
      nbBands = keywordStrings.size() - 2;
      for (unsigned int j = 0; j < nbBands; j++)
        {
        wavelengthSpectralBand->PushBack(FilterFunctionValues::New());
        ValuesVectorType temp;
        valuesVector.push_back(temp);
        }
      firstLine = false;
      }

    if (nbBands != keywordStrings.size() - 2) itkExceptionMacro(<< "Invalid file format");

    for (unsigned int i = 0; i < nbBands; i++)
      {
      valuesVector[i].push_back(keywordStrings[i + 2].toDouble());
      }

    maxi = keywordStrings[0].toDouble();
    } //while ( std::getline( file, line ) )

  for (unsigned int j = 0; j < nbBands; j++)
    {
    wavelengthSpectralBand->GetNthElement(j)->SetFilterFunctionValues(valuesVector[j]);
    wavelengthSpectralBand->GetNthElement(j)->SetMinSpectralValue(mini);
    wavelengthSpectralBand->GetNthElement(j)->SetMaxSpectralValue(maxi);
    }
}

/**PrintSelf method */
void
SpectralSensitivityReader
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  os << "DataPath: " << m_DataPath << std::endl;
  if (m_FileName != "") os << "FileName: " << m_FileName << std::endl;

  // Function values print :
  const WavelengthSpectralBandVectorType * wavelengthSpectralBand = this->GetOutput();
  os << "Filter function values: " << std::endl;
  for (unsigned int i = 0; i < wavelengthSpectralBand->Size(); ++i)
    {
    os << indent << "Channel " << i + 1 << " : " << std::endl;
    os << indent << wavelengthSpectralBand->GetNthElement(i) << std::endl;
    }
}

} // end namespace otb
<|endoftext|>


<commit_before>/*
 * HyperbolicGenerator.cpp
 *
 *  Created on: 20.05.2014
 *      Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu)
 * This generator is a simplified version of the model presented in
 * "Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010." by
 *   Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna
 *
 */

#include <cstdlib>
#include <random>
#include <math.h>
#include <assert.h>
#include <omp.h>

#include "../graph/GraphBuilder.h"
#include "HyperbolicGenerator.h"
#include "Quadtree/Quadtree.h"
#include "../auxiliary/Random.h"
#include "../auxiliary/ProgressMeter.h"

namespace NetworKit {

HyperbolicGenerator::HyperbolicGenerator() {
	stretch = 1;
	alpha = 1;
	factor = 1;
	nodeCount = 10000;
	initialize();
}
/**
 * Construct a generator for n nodes and the parameters, t, alpha and s.
 */
HyperbolicGenerator::HyperbolicGenerator(count n, double distanceFactor, double alpha, double stretchradius) {
	nodeCount = n;
	stretch = stretchradius;
	factor = distanceFactor;
	this->alpha = alpha;
	initialize();
}
/**
 * Construct a generator for n nodes and m edges
 */
HyperbolicGenerator::HyperbolicGenerator(count n, count m) {
	nodeCount = n;
	double R = HyperbolicSpace::hyperbolicAreaToRadius(n);
	double targetR = 2*log(8*n / (M_PI*(m/n)*2));
	stretch = targetR / R;
	factor = 1;
	alpha = 1;
	initialize();
}

void HyperbolicGenerator::initialize() {
	capacity = 1000;
	theoreticalSplit = false;
	threadtimers.resize(omp_get_max_threads());
}

Graph HyperbolicGenerator::generate() {
	return generate(nodeCount, factor, alpha, stretch);
}

Graph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius) {
	double R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n);
	vector<double> angles(n);
	vector<double> radii(n);
	double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
	//sample points randomly

	HyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha);
	vector<index> permutation(n);

	index p = 0;
	std::generate(permutation.begin(), permutation.end(), [&p](){return p++;});

	//can probably be parallelized easily, but doesn't bring much benefit
	std::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);});

	vector<double> anglecopy(n);
	vector<double> radiicopy(n);

	#pragma omp parallel for
	for (index j = 0; j < n; j++) {
		anglecopy[j] = angles[permutation[j]];
		radiicopy[j] = radii[permutation[j]];
	}

	INFO("Generated Points");
	return generate(anglecopy, radiicopy, r, R*distanceFactor);
}

double HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) {
	double R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n);
	return (8 / M_PI) * n * exp(-R/2)*(n/2);
}

Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double R, double thresholdDistance) {
	Aux::Timer timer;
	timer.start();
	index n = angles.size();
	assert(radii.size() == n);
	Quadtree<index> quad(R, theoreticalSplit, alpha, capacity);

	//initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap
	for (index i = 0; i < n; i++) {
		assert(radii[i] < R);
		quad.addContent(i, angles[i], radii[i]);
	}

	quad.trim();
	timer.stop();
	INFO("Filled Quadtree, took ", timer.elapsedMilliseconds(), " milliseconds.");

	return generate(angles, radii, quad, thresholdDistance);
}

Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) {
	index n = angles.size();
	assert(radii.size() == n);
	Aux::Timer timer;
	timer.start();
	vector<double> empty;
	GraphBuilder result(n, false, false, true);

	Aux::ProgressMeter progress(n, 10000);
	#pragma omp parallel
	{
		index id = omp_get_thread_num();
		threadtimers[id].start();
		#pragma omp for schedule(dynamic) nowait
		for (index i = 0; i < n; i++) {
			//get neighbours for node i
			count expectedDegree = (4/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])/2);
			vector<index> near;
			near.reserve(expectedDegree*1.1);
			quad.getElementsInHyperbolicCircle(i, HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, near);
			//count realDegree = near.size();
			//std::swap(expectedDegree, realDegree);//dummy statement for debugging
			//result.swapNeighborhood(i, near, empty, false);

			if (i % 10000 == 0) {
				#pragma omp critical (progress)
				{
					progress.signal(i);
				}
			}
		}
		threadtimers[id].stop();
	}

	timer.stop();
	INFO("Generating Edges took ", timer.elapsedMilliseconds(), " milliseconds.");
	return result.toGraph(true);
}
}
<commit_msg>Don't forget to build actual graph<commit_after>/*
 * HyperbolicGenerator.cpp
 *
 *  Created on: 20.05.2014
 *      Author: Moritz v. Looz (moritz.looz-corswarem@kit.edu)
 * This generator is a simplified version of the model presented in
 * "Hyperbolic geometry of complex networks. Physical Review E, 82:036106, Sep 2010." by
 *   Dmitri Krioukov, Fragkiskos Papadopoulos, Maksim Kitsak, Amin Vahdat, and Marian Boguna
 *
 */

#include <cstdlib>
#include <random>
#include <math.h>
#include <assert.h>
#include <omp.h>

#include "../graph/GraphBuilder.h"
#include "HyperbolicGenerator.h"
#include "Quadtree/Quadtree.h"
#include "../auxiliary/Random.h"
#include "../auxiliary/ProgressMeter.h"

namespace NetworKit {

HyperbolicGenerator::HyperbolicGenerator() {
	stretch = 1;
	alpha = 1;
	factor = 1;
	nodeCount = 10000;
	initialize();
}
/**
 * Construct a generator for n nodes and the parameters, t, alpha and s.
 */
HyperbolicGenerator::HyperbolicGenerator(count n, double distanceFactor, double alpha, double stretchradius) {
	nodeCount = n;
	stretch = stretchradius;
	factor = distanceFactor;
	this->alpha = alpha;
	initialize();
}
/**
 * Construct a generator for n nodes and m edges
 */
HyperbolicGenerator::HyperbolicGenerator(count n, count m) {
	nodeCount = n;
	double R = HyperbolicSpace::hyperbolicAreaToRadius(n);
	double targetR = 2*log(8*n / (M_PI*(m/n)*2));
	stretch = targetR / R;
	factor = 1;
	alpha = 1;
	initialize();
}

void HyperbolicGenerator::initialize() {
	capacity = 1000;
	theoreticalSplit = false;
	threadtimers.resize(omp_get_max_threads());
}

Graph HyperbolicGenerator::generate() {
	return generate(nodeCount, factor, alpha, stretch);
}

Graph HyperbolicGenerator::generate(count n, double distanceFactor, double alpha, double stretchradius) {
	double R = stretchradius*HyperbolicSpace::hyperbolicAreaToRadius(n);
	vector<double> angles(n);
	vector<double> radii(n);
	double r = HyperbolicSpace::hyperbolicRadiusToEuclidean(R);
	//sample points randomly

	HyperbolicSpace::fillPoints(angles, radii, stretchradius, alpha);
	vector<index> permutation(n);

	index p = 0;
	std::generate(permutation.begin(), permutation.end(), [&p](){return p++;});

	//can probably be parallelized easily, but doesn't bring much benefit
	std::sort(permutation.begin(), permutation.end(), [&angles,&radii](index i, index j){return angles[i] < angles[j] || (angles[i] == angles[j] && radii[i] < radii[j]);});

	vector<double> anglecopy(n);
	vector<double> radiicopy(n);

	#pragma omp parallel for
	for (index j = 0; j < n; j++) {
		anglecopy[j] = angles[permutation[j]];
		radiicopy[j] = radii[permutation[j]];
	}

	INFO("Generated Points");
	return generate(anglecopy, radiicopy, r, R*distanceFactor);
}

double HyperbolicGenerator::expectedNumberOfEdges(count n, double stretch) {
	double R = stretch*HyperbolicSpace::hyperbolicAreaToRadius(n);
	return (8 / M_PI) * n * exp(-R/2)*(n/2);
}

Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, double R, double thresholdDistance) {
	Aux::Timer timer;
	timer.start();
	index n = angles.size();
	assert(radii.size() == n);
	Quadtree<index> quad(R, theoreticalSplit, alpha, capacity);

	//initialize a graph builder for n nodes and an undirected, unweighted graph with direct swap
	for (index i = 0; i < n; i++) {
		assert(radii[i] < R);
		quad.addContent(i, angles[i], radii[i]);
	}

	quad.trim();
	timer.stop();
	INFO("Filled Quadtree, took ", timer.elapsedMilliseconds(), " milliseconds.");

	return generate(angles, radii, quad, thresholdDistance);
}

Graph HyperbolicGenerator::generate(const vector<double> &angles, const vector<double> &radii, Quadtree<index> &quad, double thresholdDistance) {
	index n = angles.size();
	assert(radii.size() == n);
	Aux::Timer timer;
	timer.start();
	vector<double> empty;
	GraphBuilder result(n, false, false, true);

	Aux::ProgressMeter progress(n, 10000);
	#pragma omp parallel
	{
		index id = omp_get_thread_num();
		threadtimers[id].start();
		#pragma omp for schedule(dynamic) nowait
		for (index i = 0; i < n; i++) {
			//get neighbours for node i
			count expectedDegree = (4/M_PI)*n*exp(-HyperbolicSpace::EuclideanRadiusToHyperbolic(radii[i])/2);
			vector<index> near;
			near.reserve(expectedDegree*1.1);
			quad.getElementsInHyperbolicCircle(i, HyperbolicSpace::polarToCartesian(angles[i], radii[i]), thresholdDistance, near);
			//count realDegree = near.size();
			//std::swap(expectedDegree, realDegree);//dummy statement for debugging
			result.swapNeighborhood(i, near, empty, false);

			if (i % 10000 == 0) {
				#pragma omp critical (progress)
				{
					progress.signal(i);
				}
			}
		}
		threadtimers[id].stop();
	}

	timer.stop();
	INFO("Generating Edges took ", timer.elapsedMilliseconds(), " milliseconds.");
	return result.toGraph(true);
}
}
<|endoftext|>