<commit_before>#ifdef _WIN32

#include "native.h"
#include "generic.h"
#include "win.h"
#include <process.h>
#include <list>
#include <vector>
#include <string>

using namespace std;

// TODO Find the right size for this
#define EVENT_BUFFER_SIZE (16*1024)

#define CREATE_SHARE (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
#define CREATE_FLAGS (FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED)
#define EVENT_MASK (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \
                    FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE)

jstring wstring_to_java(JNIEnv* env, const wstring &string) {
    return env->NewString((jchar*) (string.c_str()), string.length());
}

class Server;
class WatchPoint;

class WatchPoint {
public:
    WatchPoint(Server *server, wstring path) {
        this->server = server;
        this->path = path;
        ZeroMemory(&this->overlapped, sizeof(OVERLAPPED));
        this->overlapped.hEvent = this;
        this->directoryHandle = CreateFileW(
            path.c_str(),                       // pointer to the file name
            GENERIC_READ,                       // access (read/write) mode
            CREATE_SHARE,                       // share mode
            NULL,                               // security descriptor
            OPEN_EXISTING,                      // how to create
            CREATE_FLAGS,                       // file attributes
            NULL                                // file with attributes to copy
        );

        // TODO Error handling
    }

    void close();
    void listen();

private:
    Server *server;
    wstring path;
    HANDLE directoryHandle;
    OVERLAPPED overlapped;
    char buffer[EVENT_BUFFER_SIZE];

    void handleEvent(DWORD errorCode, DWORD bytesTransfered);
    void handlePathChanged(FILE_NOTIFY_INFORMATION *info);
    friend static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransfered, LPOVERLAPPED overlapped);
};

class Server {
public:
    Server(
        JavaVM *jvm,
        JNIEnv *env,
        jobject watcherCallback
    ) {
        this->jvm = jvm;
        this->watcherCallback = env->NewGlobalRef(watcherCallback);
        this->stopEventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
        this->threadHandle = (HANDLE)_beginthreadex(
            NULL,                   // default security attributes
            0,                      // use default stack size
            EventProcessingThread,  // thread function name
            this,                   // argument to thread function
            0,                      // use default creation flags
            NULL                    // the thread identifier
        );
        SetThreadPriority(this->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
    }

    void startWatching(wchar_t *path);
    void reportEvent(jint type, const wstring changedPath);
    void reportFinished(const WatchPoint* watchPoint);

    void close(JNIEnv *env);

private:
    struct StartWatchRequest {
        Server *server;
        wstring path;
    };
    friend static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg);

    JavaVM *jvm;
    list<WatchPoint> watchPoints;
    jobject watcherCallback;

    HANDLE stopEventHandle;
    HANDLE threadHandle;
    bool terminate = false;

    friend static unsigned CALLBACK EventProcessingThread(void* data);
    void run();
};

void WatchPoint::close() {
    CancelIo(directoryHandle);
    CloseHandle(directoryHandle);
}

void WatchPoint::listen() {
    BOOL success = ReadDirectoryChangesW(
        directoryHandle,                    // handle to directory
        buffer,                             // read results buffer
        sizeof(buffer),                     // length of buffer
        TRUE,                               // monitoring option
        EVENT_MASK,                         // filter conditions
        NULL,                               // bytes returned
        &overlapped,                        // overlapped buffer
        &handleEventCallback                // completion routine
    );
}

static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransfered, LPOVERLAPPED overlapped) {
    WatchPoint* watchPoint = (WatchPoint*)overlapped->hEvent;
    watchPoint->handleEvent(errorCode, bytesTransfered);
}

void WatchPoint::handleEvent(DWORD errorCode, DWORD bytesTransfered) {
    if (errorCode == ERROR_OPERATION_ABORTED){
        server->reportFinished(this);
        delete this;
        return;
    }

    if (bytesTransfered == 0) {
        // don't send dirty too much, everything is changed anyway
        // TODO Understand what this does
        // if (WaitForSingleObject(stopEventHandle, 500) == WAIT_OBJECT_0)
        //    break;

        // Got a buffer overflow => current changes lost => send INVALIDATE on root
        server->reportEvent(FILE_EVENT_INVALIDATE, path);
    } else {
        FILE_NOTIFY_INFORMATION *info = (FILE_NOTIFY_INFORMATION *)buffer;
        do {
            info = (FILE_NOTIFY_INFORMATION *)((char *)info + info->NextEntryOffset);
        } while (info->NextEntryOffset != 0);
    }

    // Get the new read issued as fast as possible. The documentation
    // says that the original OVERLAPPED structure will not be used
    // again once the completion routine is called.
    listen();
}

void WatchPoint::handlePathChanged(FILE_NOTIFY_INFORMATION *info) {
    wstring changedPath = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t));
    changedPath.insert(0, path);

    wprintf(L"~~~~ Changed: 0x%x %ls\n", info->Action, changedPath.c_str());

    jint type;
    if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
        type = FILE_EVENT_CREATED;
    } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
        type = FILE_EVENT_REMOVED;
    } else if (info->Action == FILE_ACTION_MODIFIED) {
        type = FILE_EVENT_MODIFIED;
    } else {
        wprintf(L"~~~~ Unknown event 0x%x for %ls\n", info->Action, changedPath.c_str());
        type = FILE_EVENT_UNKNOWN;
    }

    server->reportEvent(type, changedPath);
}

void Server::startWatching(wchar_t *path) {
    Server::StartWatchRequest request = { this, path };
    QueueUserAPC(&startWatchCallback, threadHandle, ULONG_PTR (&request));
}

// Called by QueueUserAPC to add another directory.
static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg) {
    Server::StartWatchRequest *request = (Server::StartWatchRequest*)arg;
    request->server->watchPoints.emplace_back(request->server, request->path);
    // watchPoint.listen();
}

void Server::reportFinished(const WatchPoint *watchPoint) {
    // watchPoints.remove(*watchPoint);
}

static JNIEnv* getThreadEnv(JavaVM *jvm) {
    JNIEnv* env;
    jint ret = jvm->GetEnv((void **) &(env), NULL);
    if (ret != JNI_OK) {
        printf("Failed to attach JNI to current thread: %d\n", ret);
        return NULL;
    }
    return env;
}

void Server::reportEvent(jint type, const wstring changedPath) {
    JNIEnv* env = getThreadEnv(jvm);
    jstring changedPathJava = wstring_to_java(env, changedPath);
    jclass callback_class = env->GetObjectClass(watcherCallback);
    jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V");
    env->CallVoidMethod(watcherCallback, methodCallback, type, changedPathJava);
}

static unsigned CALLBACK EventProcessingThread(void* data) {
    Server *server = (Server*) data;
    server->run();
    return 0;
}

void Server::run() {
    printf("~~~~ Starting thread\n");

    // TODO Extract this logic to some shared function
    JNIEnv* env;
    jint statAttach = jvm->AttachCurrentThreadAsDaemon((void **) &(env), NULL);
    if (statAttach != JNI_OK) {
        printf("Failed to attach JNI to current thread: %d\n", statAttach);
        return;
    }

    while (!terminate || watchPoints.size() > 0) {
        SleepEx(INFINITE, true);
    }

    printf("~~~~ Stopping thread\n");

    // TODO Extract this logic to some shared function
    jint statDetach = jvm->DetachCurrentThread();
    if (statDetach != JNI_OK) {
        printf("Failed to detach JNI from current thread: %d\n", statAttach);
        return;
    }
}

void Server::close(JNIEnv *env) {
    for (auto &watchPoint : watchPoints) {
        watchPoint.close();
    }
    SetEvent(this->stopEventHandle);
    WaitForSingleObject(this->threadHandle, INFINITE);
    CloseHandle(this->threadHandle);
    CloseHandle(this->stopEventHandle);
    env->DeleteGlobalRef(this->watcherCallback);
}

JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) {

    printf("\n~~~~ Configuring...\n");

    JavaVM* jvm;
    int jvmStatus = env->GetJavaVM(&jvm);
    if (jvmStatus != JNI_OK) {
        mark_failed_with_errno(env, "Could not store jvm instance.", result);
        return NULL;
    }

    int watchPointCount = env->GetArrayLength(paths);
    if (watchPointCount == 0) {
        mark_failed_with_errno(env, "No paths given to watch.", result);
        return NULL;
    }

    Server* server = new Server(jvm, env, javaCallback);

    for (int i = 0; i < watchPointCount; i++) {
        jstring path = (jstring) env->GetObjectArrayElement(paths, i);
        wchar_t* watchPoint = java_to_wchar_path(env, path, result);
        int watchPointLen = wcslen(watchPoint);
        if (watchPointLen > 240 || watchPoint[0] == L'\\') {
            mark_failed_with_errno(env, "Cannot watch long paths for now.", result);
            return NULL;
        }
        wprintf(L"~~~~ Watching %ls\n", watchPoint);
        server->startWatching(watchPoint);
        free(watchPoint);
    }

    jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl");
    jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V");
    return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(server, sizeof(server)));
}

JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {
    Server* server = (Server*)env->GetDirectBufferAddress(detailsObj);
    server->close(env);
    delete server;
}

#endif
<commit_msg>Third step to refactor to use completion routines<commit_after>#ifdef _WIN32

#include "native.h"
#include "generic.h"
#include "win.h"
#include <process.h>
#include <list>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

// TODO Find the right size for this
#define EVENT_BUFFER_SIZE (16*1024)

#define CREATE_SHARE (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
#define CREATE_FLAGS (FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED)
#define EVENT_MASK (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | \
                    FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE)

jstring wstring_to_java(JNIEnv* env, const wstring &string) {
    return env->NewString((jchar*) (string.c_str()), string.length());
}

class Server;
class WatchPoint;

class WatchPoint {
public:
    WatchPoint(Server *server, wstring path) {
        wcerr << "~~~~ Server: " << server << "\n";
        wcerr << "~~~~ Path: " << path << "\n";
        this->server = server;
        this->path = path;
        ZeroMemory(&this->overlapped, sizeof(OVERLAPPED));
        this->overlapped.hEvent = this;
        this->directoryHandle = CreateFileW(
            path.c_str(),                       // pointer to the file name
            GENERIC_READ,                       // access (read/write) mode
            CREATE_SHARE,                       // share mode
            NULL,                               // security descriptor
            OPEN_EXISTING,                      // how to create
            CREATE_FLAGS,                       // file attributes
            NULL                                // file with attributes to copy
        );

        // TODO Error handling
    }

    void close();
    void listen();

private:
    Server *server;
    friend static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg);
    wstring path;
    HANDLE directoryHandle;
    OVERLAPPED overlapped;
    char buffer[EVENT_BUFFER_SIZE];

    void handleEvent(DWORD errorCode, DWORD bytesTransfered);
    void handlePathChanged(FILE_NOTIFY_INFORMATION *info);
    friend static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransfered, LPOVERLAPPED overlapped);
};

class Server {
public:
    Server(
        JavaVM *jvm,
        JNIEnv *env,
        jobject watcherCallback
    ) {
        this->jvm = jvm;
        this->watcherCallback = env->NewGlobalRef(watcherCallback);
        this->stopEventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
        this->threadHandle = (HANDLE)_beginthreadex(
            NULL,                   // default security attributes
            0,                      // use default stack size
            EventProcessingThread,  // thread function name
            this,                   // argument to thread function
            0,                      // use default creation flags
            NULL                    // the thread identifier
        );
        // TODO Error handling
        SetThreadPriority(this->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
    }

    void startWatching(wchar_t *path);
    void reportEvent(jint type, const wstring changedPath);
    void reportFinished(WatchPoint* watchPoint);

    void close(JNIEnv *env);

private:
    struct StartWatchRequest {
        Server *server;
        wstring path;
    };
    friend static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg);

    JavaVM *jvm;
    list<WatchPoint*> watchPoints;
    jobject watcherCallback;

    HANDLE stopEventHandle;
    HANDLE threadHandle;
    bool terminate = false;

    friend static unsigned CALLBACK EventProcessingThread(void* data);
    void run();
};

void WatchPoint::close() {
    CancelIo(directoryHandle);
    CloseHandle(directoryHandle);
}

void WatchPoint::listen() {
    wcerr << "~~~~ Listening " << directoryHandle << " with buffer " << sizeof(buffer) << "\n";
    DWORD bytesReturned = 0;
    BOOL success = ReadDirectoryChangesW(
        directoryHandle,                    // handle to directory
        buffer,                             // read results buffer
        sizeof(buffer),                     // length of buffer
        TRUE,                               // include children
        EVENT_MASK,                         // filter conditions
        &bytesReturned,                     // bytes returned
        &overlapped,                        // overlapped buffer
        &handleEventCallback                // completion routine
    );
    wcerr << "~~~~ Success: " << success << " / " << GetLastError() << "\n";
}

static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransfered, LPOVERLAPPED overlapped) {
    WatchPoint* watchPoint = (WatchPoint*)overlapped->hEvent;
    watchPoint->handleEvent(errorCode, bytesTransfered);
}

void WatchPoint::handleEvent(DWORD errorCode, DWORD bytesTransfered) {
    wcerr << "~~~~ Callback called: " << errorCode << " / " << bytesTransfered << ", path: " << path << "\n";
    if (errorCode == ERROR_OPERATION_ABORTED){
        server->reportFinished(this);
        delete this;
        return;
    }

    if (bytesTransfered == 0) {
        // don't send dirty too much, everything is changed anyway
        // TODO Understand what this does
        // if (WaitForSingleObject(stopEventHandle, 500) == WAIT_OBJECT_0)
        //    break;

        // Got a buffer overflow => current changes lost => send INVALIDATE on root
        server->reportEvent(FILE_EVENT_INVALIDATE, path);
    } else {
        FILE_NOTIFY_INFORMATION *info = (FILE_NOTIFY_INFORMATION *)buffer;
        do {
            info = (FILE_NOTIFY_INFORMATION *)((char *)info + info->NextEntryOffset);
        } while (info->NextEntryOffset != 0);
    }

    // Get the new read issued as fast as possible. The documentation
    // says that the original OVERLAPPED structure will not be used
    // again once the completion routine is called.
    listen();
}

void WatchPoint::handlePathChanged(FILE_NOTIFY_INFORMATION *info) {
    wstring changedPath = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t));
    changedPath.insert(0, path);

    wprintf(L"~~~~ Changed: 0x%x %ls\n", info->Action, changedPath.c_str());

    jint type;
    if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
        type = FILE_EVENT_CREATED;
    } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
        type = FILE_EVENT_REMOVED;
    } else if (info->Action == FILE_ACTION_MODIFIED) {
        type = FILE_EVENT_MODIFIED;
    } else {
        wprintf(L"~~~~ Unknown event 0x%x for %ls\n", info->Action, changedPath.c_str());
        type = FILE_EVENT_UNKNOWN;
    }

    server->reportEvent(type, changedPath);
}

void Server::startWatching(wchar_t *path) {
    WatchPoint* watchPoint = new WatchPoint(this, wstring(path));
    QueueUserAPC(&startWatchCallback, threadHandle, (ULONG_PTR) watchPoint);
}

// Called by QueueUserAPC to add another directory.
static void CALLBACK startWatchCallback(_In_ ULONG_PTR arg) {
    WatchPoint* watchPoint = (WatchPoint*)arg;
    watchPoint->server->watchPoints.push_back(watchPoint);
    watchPoint->listen();
}

void Server::reportFinished(WatchPoint* watchPoint) {
    watchPoints.remove(watchPoint);
}

static JNIEnv* getThreadEnv(JavaVM *jvm) {
    JNIEnv* env;
    jint ret = jvm->GetEnv((void **) &(env), NULL);
    if (ret != JNI_OK) {
        printf("Failed to attach JNI to current thread: %d\n", ret);
        return NULL;
    }
    return env;
}

void Server::reportEvent(jint type, const wstring changedPath) {
    JNIEnv* env = getThreadEnv(jvm);
    jstring changedPathJava = wstring_to_java(env, changedPath);
    jclass callback_class = env->GetObjectClass(watcherCallback);
    jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V");
    env->CallVoidMethod(watcherCallback, methodCallback, type, changedPathJava);
}

static unsigned CALLBACK EventProcessingThread(void* data) {
    Server *server = (Server*) data;
    server->run();
    return 0;
}

void Server::run() {
    printf("~~~~ Starting thread\n");

    // TODO Extract this logic to some shared function
    JNIEnv* env;
    jint statAttach = jvm->AttachCurrentThreadAsDaemon((void **) &(env), NULL);
    if (statAttach != JNI_OK) {
        printf("Failed to attach JNI to current thread: %d\n", statAttach);
        return;
    }

    while (!terminate || watchPoints.size() > 0) {
        SleepEx(INFINITE, true);
    }

    printf("~~~~ Stopping thread\n");

    // TODO Extract this logic to some shared function
    jint statDetach = jvm->DetachCurrentThread();
    if (statDetach != JNI_OK) {
        printf("Failed to detach JNI from current thread: %d\n", statAttach);
        return;
    }
}

void Server::close(JNIEnv *env) {
    for (auto &watchPoint : watchPoints) {
        watchPoint->close();
    }
    SetEvent(this->stopEventHandle);
    WaitForSingleObject(this->threadHandle, INFINITE);
    CloseHandle(this->threadHandle);
    CloseHandle(this->stopEventHandle);
    env->DeleteGlobalRef(this->watcherCallback);
}

JNIEXPORT jobject JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, jobject javaCallback, jobject result) {

    printf("\n~~~~ Configuring...\n");

    JavaVM* jvm;
    int jvmStatus = env->GetJavaVM(&jvm);
    if (jvmStatus != JNI_OK) {
        mark_failed_with_errno(env, "Could not store jvm instance.", result);
        return NULL;
    }

    int watchPointCount = env->GetArrayLength(paths);
    if (watchPointCount == 0) {
        mark_failed_with_errno(env, "No paths given to watch.", result);
        return NULL;
    }

    Server* server = new Server(jvm, env, javaCallback);

    for (int i = 0; i < watchPointCount; i++) {
        jstring path = (jstring) env->GetObjectArrayElement(paths, i);
        wchar_t* watchPoint = java_to_wchar_path(env, path, result);
        int watchPointLen = wcslen(watchPoint);
        if (watchPointLen > 240 || watchPoint[0] == L'\\') {
            mark_failed_with_errno(env, "Cannot watch long paths for now.", result);
            return NULL;
        }
        wprintf(L"~~~~ Watching %ls\n", watchPoint);
        server->startWatching(watchPoint);
        free(watchPoint);
    }

    jclass clsWatch = env->FindClass("net/rubygrapefruit/platform/internal/jni/WindowsFileEventFunctions$WatcherImpl");
    jmethodID constructor = env->GetMethodID(clsWatch, "<init>", "(Ljava/lang/Object;)V");
    return env->NewObject(clsWatch, constructor, env->NewDirectByteBuffer(server, sizeof(server)));
}

JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) {
    Server* server = (Server*)env->GetDirectBufferAddress(detailsObj);
    server->close(env);
    delete server;
}

#endif
<|endoftext|>


<commit_before><commit_msg>fdo#39468: Translated German comments in sc/source/core/tool<commit_after><|endoftext|>


<commit_before><commit_msg>Remove more duplicated code blocks.<commit_after><|endoftext|>


<commit_before><commit_msg>Skia: Fix skia compile error with newer gcc versions.<commit_after><|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include <typeinfo>

#include "request_message.h"
#include "requests.pb.h"

class TypeVisitor : public traffic::RequestVisitor
{
public:
	enum Type {
		SUMMARY,
		STATISTIC,
		ERROR,
		NOTSET
	};

private:
	Type _t;

protected:
	void visit(traffic::StatisticRequest const &) { _t = STATISTIC; }
	void visit(traffic::SummaryRequest const &) { _t = SUMMARY; }
	void visit(traffic::ErrorRequest const &) { _t = ERROR; }

public:
	TypeVisitor() : _t(NOTSET) { }

	Type visited() const { return _t; }
};

std::string summary_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Summary *summary(req.mutable_summary());
	summary->mutable_range()->set_start(1UL);
	summary->mutable_range()->set_end(2UL);

	summary->add_addresses("peng1");
	summary->add_addresses("peng2");
	summary->add_addresses("peng3");
	summary->add_addresses("peng4");

	return req.SerializeAsString();
}

std::string statistic_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Statistic *statistic(req.mutable_statistic());
	statistic->mutable_range()->set_start(1UL);
	statistic->mutable_range()->set_end(2UL);

	statistic->set_address("peng");
	statistic->set_data_interval(requests::Statistic::HOUR);

	return req.SerializeAsString();
}

// Test that summary message processing work
TEST(MessagesRequest, deserialize_summary_request) {
	std::string bytes(summary_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::SummaryRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::SUMMARY, v.visited());

	traffic::SummaryRequest* summary(dynamic_cast<traffic::SummaryRequest*>(msg.get()));

	ASSERT_NE(nullptr, summary);
	EXPECT_EQ(1, summary->range().start());
	EXPECT_EQ(2, summary->range().end());

	ASSERT_EQ(4U, summary->addresses().size());
	EXPECT_EQ("peng1", summary->addresses().at(0));
	EXPECT_EQ("peng2", summary->addresses().at(1));
	EXPECT_EQ("peng3", summary->addresses().at(2));
	EXPECT_EQ("peng4", summary->addresses().at(3));

}

// Test that statistic message processing work
TEST(MessagesRequest, deserialize_statistic_request) {
	std::string bytes(statistic_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::StatisticRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::STATISTIC, v.visited());

	traffic::StatisticRequest* stat(dynamic_cast<traffic::StatisticRequest*>(msg.get()));

	ASSERT_NE(nullptr, stat);
	EXPECT_EQ(1, stat->range().start());
	EXPECT_EQ(2, stat->range().end());

	EXPECT_EQ("peng", stat->address());
	EXPECT_EQ(traffic::StatisticRequest::HOUR, stat->interval());
}

/**
 * Shut down the protobuf library after the tests to make valgrind happy
 */
namespace {

class ShutdownEnvironment : public ::testing::Environment
{
public:
	void TearDown()
	{
		google::protobuf::ShutdownProtobufLibrary();
	}
};

#ifndef NDEBUG
::testing::Environment* const shutdown_env =
	::testing::AddGlobalTestEnvironment(new ShutdownEnvironment);
#endif
}
<commit_msg>Add test vor parsing garbage data<commit_after>#include "gtest/gtest.h"

#include <typeinfo>

#include "request_message.h"
#include "requests.pb.h"

class TypeVisitor : public traffic::RequestVisitor
{
public:
	enum Type {
		SUMMARY,
		STATISTIC,
		ERROR,
		NOTSET
	};

private:
	Type _t;

protected:
	void visit(traffic::StatisticRequest const &) { _t = STATISTIC; }
	void visit(traffic::SummaryRequest const &) { _t = SUMMARY; }
	void visit(traffic::ErrorRequest const &) { _t = ERROR; }

public:
	TypeVisitor() : _t(NOTSET) { }

	Type visited() const { return _t; }
};

std::string summary_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Summary *summary(req.mutable_summary());
	summary->mutable_range()->set_start(1UL);
	summary->mutable_range()->set_end(2UL);

	summary->add_addresses("peng1");
	summary->add_addresses("peng2");
	summary->add_addresses("peng3");
	summary->add_addresses("peng4");

	return req.SerializeAsString();
}

std::string statistic_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Statistic *statistic(req.mutable_statistic());
	statistic->mutable_range()->set_start(1UL);
	statistic->mutable_range()->set_end(2UL);

	statistic->set_address("peng");
	statistic->set_data_interval(requests::Statistic::HOUR);

	return req.SerializeAsString();
}

// Test that summary message processing work
TEST(MessagesRequest, deserialize_summary_request) {
	std::string bytes(summary_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::SummaryRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::SUMMARY, v.visited());

	traffic::SummaryRequest* summary(dynamic_cast<traffic::SummaryRequest*>(msg.get()));

	ASSERT_NE(nullptr, summary);
	EXPECT_EQ(1, summary->range().start());
	EXPECT_EQ(2, summary->range().end());

	ASSERT_EQ(4U, summary->addresses().size());
	EXPECT_EQ("peng1", summary->addresses().at(0));
	EXPECT_EQ("peng2", summary->addresses().at(1));
	EXPECT_EQ("peng3", summary->addresses().at(2));
	EXPECT_EQ("peng4", summary->addresses().at(3));

}

// Test that statistic message processing work
TEST(MessagesRequest, deserialize_statistic_request) {
	std::string bytes(statistic_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::StatisticRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::STATISTIC, v.visited());

	traffic::StatisticRequest* stat(dynamic_cast<traffic::StatisticRequest*>(msg.get()));

	ASSERT_NE(nullptr, stat);
	EXPECT_EQ(1, stat->range().start());
	EXPECT_EQ(2, stat->range().end());

	EXPECT_EQ("peng", stat->address());
	EXPECT_EQ(traffic::StatisticRequest::HOUR, stat->interval());
}

// Test garbage processing
TEST(MessagesRequest, deserialize_garbage_request) {
	std::string bytes("aoajfiepojfiewifhewdkewifwü+fewpwzfrfjewfqqäsadfpoewjf");

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::ErrorRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::ERROR, v.visited());

	traffic::ErrorRequest* stat(dynamic_cast<traffic::ErrorRequest*>(msg.get()));

	ASSERT_NE(nullptr, stat);
}

/**
 * Shut down the protobuf library after the tests to make valgrind happy
 */
namespace {

class ShutdownEnvironment : public ::testing::Environment
{
public:
	void TearDown()
	{
		google::protobuf::ShutdownProtobufLibrary();
	}
};

#ifndef NDEBUG
::testing::Environment* const shutdown_env =
	::testing::AddGlobalTestEnvironment(new ShutdownEnvironment);
#endif
}
<|endoftext|>


<commit_before>#include "../test_batchnorm.hpp"
#include "../test_module.hpp"
#include "nnlib/nn/batchnorm.hpp"
#include "nnlib/math/math.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestClassImpl(BatchNorm)
{
    NNRunAbstractTest(Module, BatchNorm, new BatchNorm<T>(10));

    NNTestMethod(BatchNorm)
    {
        NNTestParams(size_t)
        {
            BatchNorm<T> module(5);
            NNTest(module.isTraining());
            NNTestEquals(module.inputShape()[1], 5);
        }
    }

    NNTestMethod(operator=)
    {
        NNTestParams(BatchNorm)
        {
            BatchNorm<T> orig(10);
            BatchNorm<T> copy(25);
            copy = orig;

            NNTestEquals(orig.inputShape(), copy.inputShape());
            NNTestEquals(orig.outputShape(), copy.outputShape());

            forEach([&](T orig, T copy)
            {
                NNTestAlmostEquals(orig, copy, 1e-12);
            }, orig.params(), copy.params());
        }
    }

    NNTestMethod(reset)
    {
        NNTestParams()
        {
            BatchNorm<T> module(10);
            module.weights().fill(10);
            module.bias().fill(5);
            module.reset();

            forEach([&](T weight)
            {
                NNTestGreaterThanOrEquals(weight, -1);
                NNTestLessThanOrEquals(weight, 1);
            }, module.weights());

            forEach([&](T bias)
            {
                NNTestAlmostEquals(bias, 0, 1e-12);
            }, module.bias());
        }
    }

    NNTestMethod(momentum)
    {
        NNTestParams(T)
        {
            BatchNorm<T> module(10);
            module.momentum(0.5);
            NNTestAlmostEquals(module.momentum(), 0.5, 1e-12);
            module.momentum(0.1);
            NNTestAlmostEquals(module.momentum(), 0.1, 1e-12);
        }
    }

    NNTestMethod(training)
    {
        NNTestParams(bool)
        {
            BatchNorm<T> module(10);
            NNTest(module.isTraining());
            module.training(false);
            NNTest(!module.isTraining());
            module.training(true);
            NNTest(module.isTraining());
        }
    }

    NNTestMethod(save)
    {
        NNTestParams(Serialized &)
        {
            BatchNorm<T> module(10);
            module.weights().fill(1);
            module.bias().fill(2);
            module.momentum(0.125);
            module.training(false);

            Serialized s;
            module.save(s);

            forEach([&](T weight)
            {
                NNTestAlmostEquals(weight, 1, 1e-12);
            }, s.get<Tensor<T>>("weights"));

            forEach([&](T bias)
            {
                NNTestAlmostEquals(bias, 2, 1e-12);
            }, s.get<Tensor<T>>("biases"));

            NNTestAlmostEquals(s.get<T>("momentum"), 0.125, 1e-12);
            NNTest(!s.get<bool>("training"));
        }
    }

    NNTestMethod(forward)
    {
        NNTestParams(const Tensor &)
        {
            auto input = Tensor<T>({ 3, 6, 9, -1, 5, 4, 12, 5, 11 }).resize(3, 3);

            BatchNorm<T> module(3);
            module.weights().ones();
            module.bias().zeros();
            module.momentum(1.0);

            module.forward(input);
            for(size_t i = 0; i < 3; ++i)
            {
                NNTestAlmostEquals(math::mean(module.output().select(1, i)), 0, 1e-9);
                NNTestAlmostEquals(math::variance(module.output().select(1, i)), 1, 1e-9);
            }

            module.training(false);

            module.forward(input);
            for(size_t i = 0; i < 3; ++i)
            {
                NNTestAlmostEquals(math::mean(module.output().select(1, i)), 0, 1e-9);
                NNTestAlmostEquals(math::variance(module.output().select(1, i).scale(sqrt(3) / sqrt(2))), 1, 1e-9);
            }
        }
    }

    NNTestMethod(backward)
    {
        NNTestParams(const Tensor &, const Tensor &)
        {

        }
    }

    NNTestMethod(paramsList)
    {
        NNTestParams()
        {
            // weights, biases
        }
    }

    NNTestMethod(gradList)
    {
        NNTestParams()
        {
            // weightsGrad, biasesGrad
        }
    }

    NNTestMethod(stateList)
    {
        NNTestParams()
        {
            // means, invStds, runningMeans, runningVars
        }
    }
}

/*
void TestBatchNorm()
{
    Tensor<NN_REAL_T> inp = Tensor<NN_REAL_T>({
         3,  6,  9,
        -1,  5,  4,
        12,  5, 11
    }).resize(3, 3);

    Tensor<NN_REAL_T> grad = Tensor<NN_REAL_T>({
         2,  3,  4,
        -2,  0,  4,
        10,  2,  4
    }).resize(3, 3);

    Tensor<NN_REAL_T> inGrad = Tensor<NN_REAL_T>({
         0.03596,  0.00000,  0,
        -0.02489, -2.12132,  0,
        -0.01106,  2.12132,  0
    }).resize(3, 3);

    Tensor<NN_REAL_T> paramGrad = Tensor<NN_REAL_T>({
        14.9606, 2.82843, 0,
        10, 5, 12
    });

    BatchNorm<NN_REAL_T> bn(3);
    bn.weights().ones();
    bn.bias().zeros();
    bn.momentum(1.0);

    bn.forward(inp);
    for(size_t i = 0; i < 3; ++i)
    {
        NNAssertLessThan(fabs(math::mean(bn.output().select(1, i))), 1e-9, "BatchNorm::forward failed! Non-zero mean!");
        NNAssertAlmostEquals(math::variance(bn.output().select(1, i)), 1, 1e-9, "BatchNorm::forward failed! Non-unit variance!");
    }

    bn.backward(inp, grad);
    NNAssertLessThan(math::sum(math::square(bn.grad() - paramGrad)), 1e-9, "BatchNorm::backward failed! Wrong parameter gradient!");
    NNAssertLessThan(math::sum(math::square(bn.inGrad() - inGrad)), 1e-9, "BatchNorm::backward failed! Wrong input gradient!");

    bn.training(false);

    paramGrad.copy({
        27.17588, 5.13783, 0,
        20, 10, 24
    });

    inGrad.copy({
         0.30038, 5.19615, 1.10940,
        -0.30038, 0.00000, 1.10940,
         1.50188, 3.46410, 1.10940
    });

    bn.forward(inp);
    for(size_t i = 0; i < 3; ++i)
    {
        NNAssertLessThan(fabs(math::mean(bn.output().select(1, i))), 1e-9, "BatchNorm::forward (inference) failed! Non-zero mean!");
        NNAssertAlmostEquals(
            math::variance(bn.output().select(1, i).scale(sqrt(3) / sqrt(2))), 1, 1e-9,
            "BatchNorm::forward (inference) failed! Non-unit variance!"
        );
    }

    bn.backward(inp, grad);
    NNAssertLessThan(math::sum(math::square(bn.grad() - paramGrad)), 1e-9, "BatchNorm::backward (inference) failed! Wrong parameter gradient!");
    NNAssertLessThan(math::sum(math::square(bn.inGrad() - inGrad)), 1e-9, "BatchNorm::backward (inference) failed! Wrong input gradient!");

    Tensor<NN_REAL_T> state = bn.state();
    state.fill(0);
    NNAssertAlmostEquals(math::sum(bn.output()), 0, 1e-12, "BatchNorm::state failed!");

    TestModule("BatchNorm", bn, inp);
}
*/
<commit_msg>Finished BatchNorm tests.<commit_after>#include "../test_batchnorm.hpp"
#include "../test_module.hpp"
#include "nnlib/nn/batchnorm.hpp"
#include "nnlib/math/math.hpp"
using namespace nnlib;
using T = NN_REAL_T;

NNTestClassImpl(BatchNorm)
{
    NNRunAbstractTest(Module, BatchNorm, new BatchNorm<T>(10));

    NNTestMethod(BatchNorm)
    {
        NNTestParams(size_t)
        {
            BatchNorm<T> module(5);
            NNTest(module.isTraining());
            NNTestEquals(module.inputShape()[1], 5);
        }
    }

    NNTestMethod(operator=)
    {
        NNTestParams(BatchNorm)
        {
            BatchNorm<T> orig(10);
            BatchNorm<T> copy(25);
            copy = orig;

            NNTestEquals(orig.inputShape(), copy.inputShape());
            NNTestEquals(orig.outputShape(), copy.outputShape());

            forEach([&](T orig, T copy)
            {
                NNTestAlmostEquals(orig, copy, 1e-12);
            }, orig.params(), copy.params());
        }
    }

    NNTestMethod(reset)
    {
        NNTestParams()
        {
            BatchNorm<T> module(10);
            module.weights().fill(10);
            module.bias().fill(5);
            module.reset();

            forEach([&](T weight)
            {
                NNTestGreaterThanOrEquals(weight, -1);
                NNTestLessThanOrEquals(weight, 1);
            }, module.weights());

            forEach([&](T bias)
            {
                NNTestAlmostEquals(bias, 0, 1e-12);
            }, module.bias());
        }
    }

    NNTestMethod(momentum)
    {
        NNTestParams(T)
        {
            BatchNorm<T> module(10);
            module.momentum(0.5);
            NNTestAlmostEquals(module.momentum(), 0.5, 1e-12);
            module.momentum(0.1);
            NNTestAlmostEquals(module.momentum(), 0.1, 1e-12);
        }
    }

    NNTestMethod(training)
    {
        NNTestParams(bool)
        {
            BatchNorm<T> module(10);
            NNTest(module.isTraining());
            module.training(false);
            NNTest(!module.isTraining());
            module.training(true);
            NNTest(module.isTraining());
        }
    }

    NNTestMethod(save)
    {
        NNTestParams(Serialized &)
        {
            BatchNorm<T> module(10);
            module.weights().fill(1);
            module.bias().fill(2);
            module.momentum(0.125);
            module.training(false);

            Serialized s;
            module.save(s);

            forEach([&](T weight)
            {
                NNTestAlmostEquals(weight, 1, 1e-12);
            }, s.get<Tensor<T>>("weights"));

            forEach([&](T bias)
            {
                NNTestAlmostEquals(bias, 2, 1e-12);
            }, s.get<Tensor<T>>("biases"));

            NNTestAlmostEquals(s.get<T>("momentum"), 0.125, 1e-12);
            NNTest(!s.get<bool>("training"));
        }
    }

    NNTestMethod(forward)
    {
        NNTestParams(const Tensor &)
        {
            auto input = Tensor<T>({ 3, 6, 9, -1, 5, 4, 12, 5, 11 }).resize(3, 3);

            BatchNorm<T> module(3);
            module.weights().ones();
            module.bias().zeros();
            module.momentum(1.0);

            module.forward(input);
            for(size_t i = 0; i < 3; ++i)
            {
                NNTestAlmostEquals(math::mean(module.output().select(1, i)), 0, 1e-9);
                NNTestAlmostEquals(math::variance(module.output().select(1, i)), 1, 1e-9);
            }

            module.training(false);

            module.forward(input);
            for(size_t i = 0; i < 3; ++i)
            {
                NNTestAlmostEquals(math::mean(module.output().select(1, i)), 0, 1e-9);
                NNTestAlmostEquals(math::variance(module.output().select(1, i).scale(sqrt(3) / sqrt(2))), 1, 1e-9);
            }
        }
    }

    NNTestMethod(backward)
    {
        NNTestParams(const Tensor &, const Tensor &)
        {
            auto input = Tensor<T>({ 3, 6, 9, -1, 5, 4, 12, 5, 11 }).resize(3, 3);
            auto blame = Tensor<T>({ 2, 3, 4, -2, 0, 4, 10, 2, 4 }).resize(3, 3);
            auto inGrad = Tensor<T>({ 0.03596, 0, 0, -0.02489, -2.12132, 0, -0.01106, 2.12132, 0 }).resize(3, 3);
            auto pGrad = Tensor<T>({ 14.9606, 2.82843, 0, 10, 5, 12 });

            BatchNorm<T> module(3);
            module.weights().ones();
            module.bias().zeros();
            module.momentum(1.0);

            module.forward(input);
            module.backward(input, blame);

            forEach([&](T actual, T target)
            {
                NNTestAlmostEquals(actual, target, 1e-3);
            }, module.inGrad(), inGrad);

            forEach([&](T actual, T target)
            {
                NNTestAlmostEquals(actual, target, 1e-3);
            }, module.grad(), pGrad);

            module.training(false);
            inGrad.copy({ 0.30038, 5.19615, 1.10940, -0.30038, 0, 1.10940, 1.50188, 3.46410, 1.10940 });
            pGrad.copy({ 27.17588, 5.13783, 0, 20, 10, 24 });

            module.forward(input);
            module.backward(input, blame);

            forEach([&](T actual, T target)
            {
                NNTestAlmostEquals(actual, target, 1e-3);
            }, module.inGrad(), inGrad);

            forEach([&](T actual, T target)
            {
                NNTestAlmostEquals(actual, target, 1e-3);
            }, module.grad(), pGrad);
        }
    }

    NNTestMethod(paramsList)
    {
        NNTestParams()
        {
            BatchNorm<T> module(10);
            module.params().fill(3.14);

            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 3.14, 1e-12);
            }, module.weights());

            forEach([&](T param)
            {
                NNTestAlmostEquals(param, 3.14, 1e-12);
            }, module.bias());
        }
    }
}
<|endoftext|>


<commit_before>//
// Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch
//                 PHOS  Yuri.Kharlov@cern.ch
//
AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE)
{
  // Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager.

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPartCorr", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPartCorr", "This task requires an input event handler");
    return NULL;
  }
  TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;

  // Configure analysis
  //===========================================================================

  //Reader
  //For this particular analysis few things done by the reader.
  //Nothing else needs to be set.
  AliCaloTrackReader * reader = 0x0;
  if     (data=="AOD") reader = new AliCaloTrackAODReader();
  else if(data=="ESD") reader = new AliCaloTrackESDReader();
  //reader->SetDebug(10);//10 for lots of messages
  reader->SwitchOnEMCALCells();
  reader->SwitchOnPHOSCells();
  reader->SwitchOnEMCAL();
  reader->SwitchOnPHOS();
  reader->SwitchOnCTS();
  reader->SetEMCALPtMin(0.);
  reader->SetPHOSPtMin (0.);
  reader->SetCTSPtMin  (0.);
  reader->SetZvertexCut(10.);

  if(kUseKinematics){
    if(inputDataType == "ESD"){
      reader->SwitchOnStack();
      reader->SwitchOffAODMCParticles();
    }
    else if(inputDataType == "AOD"){
      reader->SwitchOffStack();
      reader->SwitchOnAODMCParticles();
    }
  }
  //if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL");
  reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches.
  reader->SwitchOffWriteDeltaAOD()  ;
  if(oldAOD)         reader->SwitchOnOldAODs();
  if(kPrintSettings) reader->Print("");

  // *** Calorimeters Utils	***
  AliCalorimeterUtils *cu = new AliCalorimeterUtils;
  // Remove clusters close to borders, at least max energy cell is 1 cell away
  cu->SetNumberOfCellsFromEMCALBorder(1);
  cu->SetNumberOfCellsFromPHOSBorder(2);
  cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");
  // Remove EMCAL hottest channels for first LHC10 periods
  //cu->SwitchOnBadChannelsRemoval();
  // SM0
  //cu->SetEMCALChannelStatus(0,3,13);  cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13);
  //cu->SetEMCALChannelStatus(0,20,7);  cu->SetEMCALChannelStatus(0,38,2);
  // SM1
  //cu->SetEMCALChannelStatus(1,4,7);   cu->SetEMCALChannelStatus(1,4,13);  cu->SetEMCALChannelStatus(1,9,20);
  //cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23);
  //cu->SetEMCALChannelStatus(1,37,5);  cu->SetEMCALChannelStatus(1,40,1);  cu->SetEMCALChannelStatus(1,40,2);
  //cu->SetEMCALChannelStatus(1,40,5);  cu->SetEMCALChannelStatus(1,41,0);  cu->SetEMCALChannelStatus(1,41,1);
  //cu->SetEMCALChannelStatus(1,41,2);  cu->SetEMCALChannelStatus(1,41,4);
  // SM2
  //cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17);
  //cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21);
  //cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17);
  //cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21);
  //cu->SetEMCALChannelStatus(2,19,22);
  //SM3
  //cu->SetEMCALChannelStatus(3,4,7);

  //Recalibration
  //cu->SwitchOnRecalibration();
  //TFile * f = new TFile("RecalibrationFactors.root","read");
  //cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0"));
  //cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1"));
  //cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2"));
  //cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3"));

  cu->SetDebug(-1);
  if(kPrintSettings) cu->Print("");

  // ##### Analysis algorithm settings ####
  //AliFiducialCut * fidCut = new AliFiducialCut();
  //fidCut->DoCTSFiducialCut(kFALSE) ;
  //fidCut->DoEMCALFiducialCut(kTRUE) ;
  //fidCut->DoPHOSFiducialCut(kTRUE) ;

  AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA();
  //emcalQA->SetDebug(2); //10 for lots of messages
  emcalQA->SetCalorimeter("EMCAL");
  if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
  else  emcalQA->SwitchOffDataMC() ;
  emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name
  //emcalQA->SetFiducialCut(fidCut);
  emcalQA->SwitchOffFiducialCut();
  emcalQA->SwitchOffPlotsMaking();
  emcalQA->SwitchOnCorrelation();
  if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment
  //Set Histrograms bins and ranges
  emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
  emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
  emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 181*TMath::DegToRad(), 200) ;
  emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ;
  emcalQA->SetNumberOfModules(10);
  emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ;
  emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 );
  emcalQA->SetHistoPOverERangeAndNBins(0,10.,100);
  emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200);
  emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
  emcalQA->SetHistoTimeRangeAndNBins(300.,900,300);
  emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100);
  emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
  emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
  emcalQA->SetHistoXRangeAndNBins(-230,90,120);
  emcalQA->SetHistoYRangeAndNBins(370,450,40);
  emcalQA->SetHistoZRangeAndNBins(-400,400,200);
  emcalQA->SetHistoRRangeAndNBins(400,450,25);
  emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
  emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
  emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
  //emcalQA->GetMCAnalysisUtils()->SetDebug(10);

  if(kPrintSettings) emcalQA->Print("");

  AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA();
  //phosQA->SetDebug(2); //10 for lots of messages
  phosQA->SetCalorimeter("PHOS");
  if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
  else  phosQA->SwitchOffDataMC() ;
  phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name
  //phosQA->SetFiducialCut(fidCut);
  phosQA->SwitchOffFiducialCut();
  //phosQA->GetMCAnalysisUtils()->SetDebug(10);
  phosQA->SwitchOffPlotsMaking();
  //Set Histrograms bins and ranges
  phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
  phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
  phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ;
  phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ;
  phosQA->SetNumberOfModules(3); //PHOS first year
  phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ;
  phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ;
  phosQA->SetHistoPOverERangeAndNBins(0,10.,100);
  phosQA->SetHistodEdxRangeAndNBins(0.,200.,200);
  phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
  phosQA->SetHistoTimeRangeAndNBins(0.,300,300);
  phosQA->SetHistoRatioRangeAndNBins(0.,2.,100);
  phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
  phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
  phosQA->SetHistoXRangeAndNBins(-100,400,100);
  phosQA->SetHistoYRangeAndNBins(-490,-290,100);
  phosQA->SetHistoZRangeAndNBins(-80,80,100);
  phosQA->SetHistoRRangeAndNBins(440,480,80);
  phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
  phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
  phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);

  // #### Configure Maker ####
  AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();
  maker->SetReader(reader);//pointer to reader
  maker->SetCaloUtils(cu); //pointer to calorimeter utils
  maker->AddAnalysis(emcalQA,0);
  maker->AddAnalysis(phosQA,1);
  maker->SetAnaDebug(-1)  ; // 0 to at least print the event number
  maker->SwitchOnHistogramsMaker()  ;
  maker->SwitchOffAODsMaker()  ;
  if(kPrintSettings) maker->Print("");

  printf("======================== \n");
  printf(" End Configuration of Calorimeter QA \n");
  printf("======================== \n");

  // Create task
  //===========================================================================
  AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance");
  task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
  //task->SetDebugLevel(-1);
  task->SelectCollisionCandidates();
  task->SetAnalysisMaker(maker);
  mgr->AddTask(task);

  //Create containers
  //  AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(),
  //							   AliAnalysisManager::kOutputContainer, "Calo.Performance.root");

  if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cout_pc   = mgr->CreateContainer("CaloQA", TList::Class(),
                                                             AliAnalysisManager::kOutputContainer,
                                                             Form("%s:CaloQA",outputFile.Data()));

  AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(),
                                                             AliAnalysisManager::kParamContainer,
                                                             Form("%s:CaloQACuts",outputFile.Data()));
	//Form("%s:PartCorrCuts",outputfile.Data()));
  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (task, 1, cout_pc);
  mgr->ConnectOutput (task, 2, cout_cuts);

  return task;
}

<commit_msg>trick to fill missing histograms<commit_after>//
// Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch
//                 PHOS  Yuri.Kharlov@cern.ch
//
AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE)
{
  // Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager.

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPartCorr", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPartCorr", "This task requires an input event handler");
    return NULL;
  }
  TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;

  // Configure analysis
  //===========================================================================

  //Reader
  //For this particular analysis few things done by the reader.
  //Nothing else needs to be set.
  AliCaloTrackReader * reader = 0x0;
  if     (data=="AOD") reader = new AliCaloTrackAODReader();
  else if(data=="ESD") reader = new AliCaloTrackESDReader();
  //reader->SetDebug(10);//10 for lots of messages
  reader->SwitchOnEMCALCells();
  reader->SwitchOnPHOSCells();
  reader->SwitchOnEMCAL();
  reader->SwitchOnPHOS();
  reader->SwitchOnCTS();
  reader->SetEMCALPtMin(0.);
  reader->SetPHOSPtMin (0.);
  reader->SetCTSPtMin  (0.);
  reader->SetZvertexCut(10.);

  if(kUseKinematics){
    if(inputDataType == "ESD"){
      reader->SwitchOnStack();
      reader->SwitchOffAODMCParticles();
    }
    else if(inputDataType == "AOD"){
      reader->SwitchOffStack();
      reader->SwitchOnAODMCParticles();
    }
  }
  //if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL");
  reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches.
  reader->SwitchOffWriteDeltaAOD()  ;
  if(oldAOD)         reader->SwitchOnOldAODs();
  if(kPrintSettings) reader->Print("");

  // *** Calorimeters Utils	***
  AliCalorimeterUtils *cu = new AliCalorimeterUtils;
  // Remove clusters close to borders, at least max energy cell is 1 cell away
  cu->SetNumberOfCellsFromEMCALBorder(1);
  cu->SetNumberOfCellsFromPHOSBorder(2);
  cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");
  // Remove EMCAL hottest channels for first LHC10 periods
  cu->SwitchOnBadChannelsRemoval();
  // SM0
  //cu->SetEMCALChannelStatus(0,3,13);  cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13);
  //cu->SetEMCALChannelStatus(0,20,7);  cu->SetEMCALChannelStatus(0,38,2);
  // SM1
  //cu->SetEMCALChannelStatus(1,4,7);   cu->SetEMCALChannelStatus(1,4,13);  cu->SetEMCALChannelStatus(1,9,20);
  //cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23);
  //cu->SetEMCALChannelStatus(1,37,5);  cu->SetEMCALChannelStatus(1,40,1);  cu->SetEMCALChannelStatus(1,40,2);
  //cu->SetEMCALChannelStatus(1,40,5);  cu->SetEMCALChannelStatus(1,41,0);  cu->SetEMCALChannelStatus(1,41,1);
  //cu->SetEMCALChannelStatus(1,41,2);  cu->SetEMCALChannelStatus(1,41,4);
  // SM2
  //cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17);
  //cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21);
  //cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17);
  //cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21);
  //cu->SetEMCALChannelStatus(2,19,22);
  //SM3
  //cu->SetEMCALChannelStatus(3,4,7);

  //Recalibration
  //cu->SwitchOnRecalibration();
  //TFile * f = new TFile("RecalibrationFactors.root","read");
  //cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0"));
  //cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1"));
  //cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2"));
  //cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3"));

  cu->SetDebug(-1);
  if(kPrintSettings) cu->Print("");

  // ##### Analysis algorithm settings ####
  //AliFiducialCut * fidCut = new AliFiducialCut();
  //fidCut->DoCTSFiducialCut(kFALSE) ;
  //fidCut->DoEMCALFiducialCut(kTRUE) ;
  //fidCut->DoPHOSFiducialCut(kTRUE) ;

  AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA();
  //emcalQA->SetDebug(10); //10 for lots of messages
  emcalQA->SetCalorimeter("EMCAL");
  if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
  else  emcalQA->SwitchOffDataMC() ;
  emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name
  //emcalQA->SetFiducialCut(fidCut);
  emcalQA->SwitchOffFiducialCut();
  emcalQA->SwitchOffPlotsMaking();
  emcalQA->SwitchOnCorrelation();
//  if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment
  //Set Histrograms bins and ranges
  emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
  emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
  emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 181*TMath::DegToRad(), 200) ;
  emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ;
  emcalQA->SetNumberOfModules(10);
  emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ;
  emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 );
  emcalQA->SetHistoPOverERangeAndNBins(0,10.,100);
  emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200);
  emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
  emcalQA->SetHistoTimeRangeAndNBins(300.,900,300);
  emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100);
  emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
  emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
  emcalQA->SetHistoXRangeAndNBins(-230,90,120);
  emcalQA->SetHistoYRangeAndNBins(370,450,40);
  emcalQA->SetHistoZRangeAndNBins(-400,400,200);
  emcalQA->SetHistoRRangeAndNBins(400,450,25);
  emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
  emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
  emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);
  //emcalQA->GetMCAnalysisUtils()->SetDebug(10);

  if(kPrintSettings) emcalQA->Print("");

  AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA();
  //phosQA->SetDebug(2); //10 for lots of messages
  phosQA->SetCalorimeter("PHOS");
  if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
  else  phosQA->SwitchOffDataMC() ;
  phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name
  //phosQA->SetFiducialCut(fidCut);
  phosQA->SwitchOffFiducialCut();
  //phosQA->GetMCAnalysisUtils()->SetDebug(10);
  phosQA->SwitchOffPlotsMaking();
  //Set Histrograms bins and ranges
  phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ;
  phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
  phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ;
  phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ;
  phosQA->SetNumberOfModules(3); //PHOS first year
  phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ;
  phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ;
  phosQA->SetHistoPOverERangeAndNBins(0,10.,100);
  phosQA->SetHistodEdxRangeAndNBins(0.,200.,200);
  phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
  phosQA->SetHistoTimeRangeAndNBins(0.,300,300);
  phosQA->SetHistoRatioRangeAndNBins(0.,2.,100);
  phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500);
  phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500);
  phosQA->SetHistoXRangeAndNBins(-100,400,100);
  phosQA->SetHistoYRangeAndNBins(-490,-290,100);
  phosQA->SetHistoZRangeAndNBins(-80,80,100);
  phosQA->SetHistoRRangeAndNBins(440,480,80);
  phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500);
  phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
  phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);

  // #### Configure Maker ####
  AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();
  maker->SetReader(reader);//pointer to reader
  maker->SetCaloUtils(cu); //pointer to calorimeter utils
  maker->AddAnalysis(emcalQA,0);
  maker->AddAnalysis(phosQA,1);
  maker->SetAnaDebug(-1)  ; // 0 to at least print the event number
  maker->SwitchOnHistogramsMaker()  ;
  maker->SwitchOffAODsMaker()  ;
  if(kPrintSettings) maker->Print("");

  printf("======================== \n");
  printf(" End Configuration of Calorimeter QA \n");
  printf("======================== \n");

  // Create task
  //===========================================================================
  AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance");
  task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
  //task->SetDebugLevel(-1);
  task->SelectCollisionCandidates();
  task->SetAnalysisMaker(maker);
  mgr->AddTask(task);

  //Create containers
  //  AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(),
  //							   AliAnalysisManager::kOutputContainer, "Calo.Performance.root");

  if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName();

  AliAnalysisDataContainer *cout_pc   = mgr->CreateContainer("CaloQA", TList::Class(),
                                                             AliAnalysisManager::kOutputContainer,
                                                             Form("%s:CaloQA",outputFile.Data()));

  AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(),
                                                             AliAnalysisManager::kParamContainer,
                                                             Form("%s:CaloQACuts",outputFile.Data()));
	//Form("%s:PartCorrCuts",outputfile.Data()));
  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput (task, 1, cout_pc);
  mgr->ConnectOutput (task, 2, cout_cuts);

  return task;
}

<|endoftext|>


<commit_before>// Spark Interval Timer demo
//
// This demo will create several Interval Timers (3 on Core, 5 on Photon) to blink
// LEDs at different intervals.  The first timer will blink the onboard LED
// while extra LEDs (and small current limiting resistors) must be added
// by the user on pins D3 and D4 (Core) and additionally on D5 and D6 for Photon.
// After 100 blinks, Timer1 will reset to 1/4 of its interval and after 200 more
// blinks, Timer1 is shut down and will stop blinking.

#include "SparkIntervalTimer.h"

SYSTEM_MODE(MANUAL);		//For this demo, WiFi and Cloud connections are disabled

// Creat IntervalTimer objects
IntervalTimer myTimer;		// 3 for the Core
IntervalTimer myTimer2;
IntervalTimer myTimer3;
#if (PLATFORM_ID == 6)		// 2 more for the Photon
IntervalTimer myTimer4;
IntervalTimer myTimer5;
#endif

// Pre-define ISR callback functions
void blinkLED(void);
void blinkLED2(void);
void blinkLED3(void);
#if (PLATFORM_ID == 6)		// Extras for Photon
void blinkLED4(void);
void blinkLED5(void);
#endif

const uint8_t ledPin = D7;		// LED for first Interval Timer
const uint8_t ledPin2 = D3;		// LED for second Interval Timer
const uint8_t ledPin3 = D4;		// LED for third Interval Timer
#if (PLATFORM_ID == 6)			// Extras for Photon
const uint8_t ledPin4 = D5;
const uint8_t ledPin5 = D6;
#endif

void setup(void) {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
 #if (PLATFORM_ID == 6)			//Extras for Photon
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
#endif

  // AUTO allocate blinkLED to run every 500ms (1000 * .5ms period)
  myTimer.begin(blinkLED, 1000, hmSec);

  // Manually allocate blinkLED2 to hardware timer TIM4 to run every 250ms (500 * .5ms period)
  myTimer2.begin(blinkLED2, 500, hmSec);

  // Manually allocate blinkLED3 to hardware timer TIM3 blinkLED to run every 1000ms (2000 * .5ms period)
  myTimer3.begin(blinkLED3, 2000, hmSec);

#if (PLATFORM_ID == 6)
  // Manually allocate blinkLED4 to hardware timer TIM6 to run every 250ms (500 * .5ms period)
  myTimer4.begin(blinkLED4, 300, hmSec);

  // Manually allocate blinkLED5 to hardware timer TIM7 blinkLED to run every 1000ms (2000 * .5ms period)
  myTimer5.begin(blinkLED5, 3000, hmSec);
#endif
}

// The first TIMER interrupt will blink the LED, and keep
// track of how many times it has blinked.  The other
// timers only blink their LEDs

volatile unsigned long blinkCount = 0; // use volatile for shared variables

// functions called by IntervalTimer should be short, run as quickly as
// possible, and should avoid calling other functions if possible.

// Callback for Timer 1
void blinkLED(void) {
	digitalWrite(ledPin,!digitalRead(ledPin));
    blinkCount++;		// increase when LED turns on
}

// Callback for Timer 2
void blinkLED2(void) {
	digitalWrite(ledPin2,!digitalRead(ledPin2));
}

// Callback for Timer 3
void blinkLED3(void) {
	digitalWrite(ledPin3,!digitalRead(ledPin3));
}

 #if (PLATFORM_ID == 6)		// Extras for the Photon
// Callback for Timer 4
void blinkLED4(void) {
	digitalWrite(ledPin4,!digitalRead(ledPin4));
}

// Callback for Timer 5
void blinkLED5(void) {
	digitalWrite(ledPin5,!digitalRead(ledPin5));
}
#endif

void loop(void) {

  if (blinkCount == 200)	{			// After 100 blinks, shut down timer 1
    blinkCount++;						// increment count so IF does not keep passing
	myTimer.resetPeriod_SIT(250, hmSec);
	}
  else if (blinkCount >= 400) {			// After 100 blinks, shut down timer 1
	blinkCount = 0;						// reset count so IF does not keep passing
	myTimer.end();
	}
}
<commit_msg>Update SparkIntervalTimerDemo.cpp<commit_after>// Spark Interval Timer demo
//
// This demo will create several Interval Timers (3 on Core, 5 on Photon) to blink
// LEDs at different intervals.  The first timer will blink the onboard LED
// while extra LEDs (and small current limiting resistors) must be added
// by the user on pins D3 and D4 (Core) and additionally on D5 and D6 for Photon.
// After 100 blinks, Timer1 will reset to 1/4 of its interval and after 200 more
// blinks, Timer1 is shut down and will stop blinking.

#include "SparkIntervalTimer/SparkIntervalTimer.h"

SYSTEM_MODE(MANUAL);		//For this demo, WiFi and Cloud connections are disabled

// Creat IntervalTimer objects
IntervalTimer myTimer;		// 3 for the Core
IntervalTimer myTimer2;
IntervalTimer myTimer3;
#if (PLATFORM_ID == 6)		// 2 more for the Photon
IntervalTimer myTimer4;
IntervalTimer myTimer5;
#endif

// Pre-define ISR callback functions
void blinkLED(void);
void blinkLED2(void);
void blinkLED3(void);
#if (PLATFORM_ID == 6)		// Extras for Photon
void blinkLED4(void);
void blinkLED5(void);
#endif

const uint8_t ledPin = D7;		// LED for first Interval Timer
const uint8_t ledPin2 = D3;		// LED for second Interval Timer
const uint8_t ledPin3 = D4;		// LED for third Interval Timer
#if (PLATFORM_ID == 6)			// Extras for Photon
const uint8_t ledPin4 = D5;
const uint8_t ledPin5 = D6;
#endif

void setup(void) {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
 #if (PLATFORM_ID == 6)			//Extras for Photon
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
#endif

  // AUTO allocate blinkLED to run every 500ms (1000 * .5ms period)
  myTimer.begin(blinkLED, 1000, hmSec);

  // Manually allocate blinkLED2 to hardware timer TIM4 to run every 250ms (500 * .5ms period)
  myTimer2.begin(blinkLED2, 500, hmSec);

  // Manually allocate blinkLED3 to hardware timer TIM3 blinkLED to run every 1000ms (2000 * .5ms period)
  myTimer3.begin(blinkLED3, 2000, hmSec);

#if (PLATFORM_ID == 6)
  // Manually allocate blinkLED4 to hardware timer TIM6 to run every 250ms (500 * .5ms period)
  myTimer4.begin(blinkLED4, 300, hmSec);

  // Manually allocate blinkLED5 to hardware timer TIM7 blinkLED to run every 1000ms (2000 * .5ms period)
  myTimer5.begin(blinkLED5, 3000, hmSec);
#endif
}

// The first TIMER interrupt will blink the LED, and keep
// track of how many times it has blinked.  The other
// timers only blink their LEDs

volatile unsigned long blinkCount = 0; // use volatile for shared variables

// functions called by IntervalTimer should be short, run as quickly as
// possible, and should avoid calling other functions if possible.

// Callback for Timer 1
void blinkLED(void) {
	digitalWrite(ledPin,!digitalRead(ledPin));
    blinkCount++;		// increase when LED turns on
}

// Callback for Timer 2
void blinkLED2(void) {
	digitalWrite(ledPin2,!digitalRead(ledPin2));
}

// Callback for Timer 3
void blinkLED3(void) {
	digitalWrite(ledPin3,!digitalRead(ledPin3));
}

 #if (PLATFORM_ID == 6)		// Extras for the Photon
// Callback for Timer 4
void blinkLED4(void) {
	digitalWrite(ledPin4,!digitalRead(ledPin4));
}

// Callback for Timer 5
void blinkLED5(void) {
	digitalWrite(ledPin5,!digitalRead(ledPin5));
}
#endif

void loop(void) {

  if (blinkCount == 200)	{			// After 100 blinks, shut down timer 1
    blinkCount++;						// increment count so IF does not keep passing
	myTimer.resetPeriod_SIT(250, hmSec);
	}
  else if (blinkCount >= 400) {			// After 100 blinks, shut down timer 1
	blinkCount = 0;						// reset count so IF does not keep passing
	myTimer.end();
	}
}
<|endoftext|>


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

#include "app/gfx/font.h"

#include <gdk/gdk.h>
#include <pango/pango.h>

#include "app/gfx/canvas.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/sys_string_conversions.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/skia/include/core/SkPaint.h"

namespace {

// The font family name which is used when a user's application font for
// GNOME/KDE is a non-scalable one. The name should be listed in the
// IsFallbackFontAllowed function in skia/ext/SkFontHost_fontconfig_direct.cpp.
const char* kFallbackFontFamilyName = "sans";

// Pango scales font sizes. This returns the scale factor. See
// pango_cairo_context_set_resolution for details.
// NOTE: this isn't entirely accurate, in that Pango also consults the
// FC_PIXEL_SIZE first (see get_font_size in pangocairo-fcfont), but this
// seems to give us the same sizes as used by Pango for all our fonts in both
// English and Thia.
static double GetPangoScaleFactor() {
  static float scale_factor = 0;
  static bool determined_scale = false;
  if (!determined_scale) {
    PangoContext* context = gdk_pango_context_get();
    scale_factor = pango_cairo_context_get_resolution(context);
    g_object_unref(context);
    if (scale_factor <= 0)
      scale_factor = 1;
    else
      scale_factor /= 72.0;
  }
  return scale_factor;
}

}  // namespace

namespace gfx {

Font::Font(const Font& other) {
  CopyFont(other);
}

Font& Font::operator=(const Font& other) {
  CopyFont(other);
  return *this;
}

Font::Font(SkTypeface* tf, const std::wstring& font_family, int font_size,
           int style)
    : typeface_helper_(new SkAutoUnref(tf)),
      typeface_(tf),
      font_family_(font_family),
      font_size_(font_size),
      style_(style) {
  tf->ref();
  calculateMetrics();
}

void Font::calculateMetrics() {
  SkPaint paint;
  SkPaint::FontMetrics metrics;
  PaintSetup(&paint);
  paint.getFontMetrics(&metrics);

  ascent_ = SkScalarCeil(-metrics.fAscent);
  height_ = ascent_ + SkScalarCeil(metrics.fDescent);
  // avg_width_ is calculated lazily, as it's expensive and not used often.
  avg_width_ = -1.0;

}

void Font::CopyFont(const Font& other) {
  typeface_helper_.reset(new SkAutoUnref(other.typeface_));
  typeface_ = other.typeface_;
  typeface_->ref();
  font_family_ = other.font_family_;
  font_size_ = other.font_size_;
  style_ = other.style_;
  height_ = other.height_;
  ascent_ = other.ascent_;
  avg_width_ = other.avg_width_;
}

int Font::height() const {
  return height_;
}

int Font::baseline() const {
  return ascent_;
}

int Font::ave_char_width() const {
  return SkScalarRound(const_cast<Font*>(this)->avg_width());
}

Font Font::CreateFont(const std::wstring& font_family, int font_size) {
  DCHECK_GT(font_size, 0);
  std::wstring fallback;

  SkTypeface* tf = SkTypeface::CreateFromName(
      base::SysWideToUTF8(font_family).c_str(), SkTypeface::kNormal);
  if (!tf) {
    // A non-scalable font such as .pcf is specified. Falls back to a default
    // scalable font.
    tf = SkTypeface::CreateFromName(
        kFallbackFontFamilyName, SkTypeface::kNormal);
    CHECK(tf) << "Could not find any font: "
              << base::SysWideToUTF8(font_family)
              << ", " << kFallbackFontFamilyName;
    fallback = base::SysUTF8ToWide(kFallbackFontFamilyName);
  }
  SkAutoUnref tf_helper(tf);

  return Font(
      tf, fallback.empty() ? font_family : fallback, font_size, NORMAL);
}

Font Font::DeriveFont(int size_delta, int style) const {
  // If the delta is negative, if must not push the size below 1
  if (size_delta < 0) {
    DCHECK_LT(-size_delta, font_size_);
  }

  if (style == style_) {
    // Fast path, we just use the same typeface at a different size
    return Font(typeface_, font_family_, font_size_ + size_delta, style_);
  }

  // If the style has changed we may need to load a new face
  int skstyle = SkTypeface::kNormal;
  if (BOLD & style)
    skstyle |= SkTypeface::kBold;
  if (ITALIC & style)
    skstyle |= SkTypeface::kItalic;

  SkTypeface* tf = SkTypeface::CreateFromName(
      base::SysWideToUTF8(font_family_).c_str(),
      static_cast<SkTypeface::Style>(skstyle));
  SkAutoUnref tf_helper(tf);

  return Font(tf, font_family_, font_size_ + size_delta, skstyle);
}

void Font::PaintSetup(SkPaint* paint) const {
  paint->setAntiAlias(false);
  paint->setSubpixelText(false);
  paint->setTextSize(SkFloatToScalar(font_size_ * GetPangoScaleFactor()));
  paint->setTypeface(typeface_);
  paint->setFakeBoldText((BOLD & style_) && !typeface_->isBold());
  paint->setTextSkewX((ITALIC & style_) && !typeface_->isItalic() ?
                      -SK_Scalar1/4 : 0);
}

int Font::GetStringWidth(const std::wstring& text) const {
  int width = 0, height = 0;

  Canvas::SizeStringInt(text, *this, &width, &height, 0);
  return width;
}

double Font::avg_width() {
  if (avg_width_ < 0) {
    // First get the pango based width
    PangoFontDescription* pango_desc = gfx::Font::PangoFontFromGfxFont(*this);
    PangoContext* context =
        gdk_pango_context_get_for_screen(gdk_screen_get_default());
    PangoFontMetrics* pango_metrics =
        pango_context_get_metrics(context,
                                  pango_desc,
                                  pango_language_get_default());
    double pango_width =
        pango_font_metrics_get_approximate_char_width(pango_metrics);
    pango_width /= PANGO_SCALE;

    // Yes, this is how Microsoft recommends calculating the dialog unit
    // conversions.
    int text_width = GetStringWidth(
        L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    double dialog_units = (text_width / 26 + 1) / 2;

    avg_width_ = std::min(pango_width, dialog_units);
  }
  return avg_width_;
}

int Font::GetExpectedTextWidth(int length) const {
  double char_width = const_cast<Font*>(this)->avg_width();
  return round(static_cast<float>(length) * char_width);
}

int Font::style() const {
  return style_;
}

std::wstring Font::FontName() {
  return font_family_;
}

int Font::FontSize() {
  return font_size_;
}

NativeFont Font::nativeFont() const {
  return typeface_;
}

}  // namespace gfx
<commit_msg>Plug a font leak.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/gfx/font.h"

#include <gdk/gdk.h>
#include <pango/pango.h>

#include "app/gfx/canvas.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/sys_string_conversions.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "third_party/skia/include/core/SkPaint.h"

namespace {

// The font family name which is used when a user's application font for
// GNOME/KDE is a non-scalable one. The name should be listed in the
// IsFallbackFontAllowed function in skia/ext/SkFontHost_fontconfig_direct.cpp.
const char* kFallbackFontFamilyName = "sans";

// Pango scales font sizes. This returns the scale factor. See
// pango_cairo_context_set_resolution for details.
// NOTE: this isn't entirely accurate, in that Pango also consults the
// FC_PIXEL_SIZE first (see get_font_size in pangocairo-fcfont), but this
// seems to give us the same sizes as used by Pango for all our fonts in both
// English and Thia.
static double GetPangoScaleFactor() {
  static float scale_factor = 0;
  static bool determined_scale = false;
  if (!determined_scale) {
    PangoContext* context = gdk_pango_context_get();
    scale_factor = pango_cairo_context_get_resolution(context);
    g_object_unref(context);
    if (scale_factor <= 0)
      scale_factor = 1;
    else
      scale_factor /= 72.0;
  }
  return scale_factor;
}

}  // namespace

namespace gfx {

Font::Font(const Font& other) {
  CopyFont(other);
}

Font& Font::operator=(const Font& other) {
  CopyFont(other);
  return *this;
}

Font::Font(SkTypeface* tf, const std::wstring& font_family, int font_size,
           int style)
    : typeface_helper_(new SkAutoUnref(tf)),
      typeface_(tf),
      font_family_(font_family),
      font_size_(font_size),
      style_(style) {
  tf->ref();
  calculateMetrics();
}

void Font::calculateMetrics() {
  SkPaint paint;
  SkPaint::FontMetrics metrics;
  PaintSetup(&paint);
  paint.getFontMetrics(&metrics);

  ascent_ = SkScalarCeil(-metrics.fAscent);
  height_ = ascent_ + SkScalarCeil(metrics.fDescent);
  // avg_width_ is calculated lazily, as it's expensive and not used often.
  avg_width_ = -1.0;

}

void Font::CopyFont(const Font& other) {
  typeface_helper_.reset(new SkAutoUnref(other.typeface_));
  typeface_ = other.typeface_;
  typeface_->ref();
  font_family_ = other.font_family_;
  font_size_ = other.font_size_;
  style_ = other.style_;
  height_ = other.height_;
  ascent_ = other.ascent_;
  avg_width_ = other.avg_width_;
}

int Font::height() const {
  return height_;
}

int Font::baseline() const {
  return ascent_;
}

int Font::ave_char_width() const {
  return SkScalarRound(const_cast<Font*>(this)->avg_width());
}

Font Font::CreateFont(const std::wstring& font_family, int font_size) {
  DCHECK_GT(font_size, 0);
  std::wstring fallback;

  SkTypeface* tf = SkTypeface::CreateFromName(
      base::SysWideToUTF8(font_family).c_str(), SkTypeface::kNormal);
  if (!tf) {
    // A non-scalable font such as .pcf is specified. Falls back to a default
    // scalable font.
    tf = SkTypeface::CreateFromName(
        kFallbackFontFamilyName, SkTypeface::kNormal);
    CHECK(tf) << "Could not find any font: "
              << base::SysWideToUTF8(font_family)
              << ", " << kFallbackFontFamilyName;
    fallback = base::SysUTF8ToWide(kFallbackFontFamilyName);
  }
  SkAutoUnref tf_helper(tf);

  return Font(
      tf, fallback.empty() ? font_family : fallback, font_size, NORMAL);
}

Font Font::DeriveFont(int size_delta, int style) const {
  // If the delta is negative, if must not push the size below 1
  if (size_delta < 0) {
    DCHECK_LT(-size_delta, font_size_);
  }

  if (style == style_) {
    // Fast path, we just use the same typeface at a different size
    return Font(typeface_, font_family_, font_size_ + size_delta, style_);
  }

  // If the style has changed we may need to load a new face
  int skstyle = SkTypeface::kNormal;
  if (BOLD & style)
    skstyle |= SkTypeface::kBold;
  if (ITALIC & style)
    skstyle |= SkTypeface::kItalic;

  SkTypeface* tf = SkTypeface::CreateFromName(
      base::SysWideToUTF8(font_family_).c_str(),
      static_cast<SkTypeface::Style>(skstyle));
  SkAutoUnref tf_helper(tf);

  return Font(tf, font_family_, font_size_ + size_delta, skstyle);
}

void Font::PaintSetup(SkPaint* paint) const {
  paint->setAntiAlias(false);
  paint->setSubpixelText(false);
  paint->setTextSize(SkFloatToScalar(font_size_ * GetPangoScaleFactor()));
  paint->setTypeface(typeface_);
  paint->setFakeBoldText((BOLD & style_) && !typeface_->isBold());
  paint->setTextSkewX((ITALIC & style_) && !typeface_->isItalic() ?
                      -SK_Scalar1/4 : 0);
}

int Font::GetStringWidth(const std::wstring& text) const {
  int width = 0, height = 0;

  Canvas::SizeStringInt(text, *this, &width, &height, 0);
  return width;
}

double Font::avg_width() {
  if (avg_width_ < 0) {
    // First get the pango based width
    PangoFontDescription* pango_desc = PangoFontFromGfxFont(*this);
    PangoContext* context =
        gdk_pango_context_get_for_screen(gdk_screen_get_default());
    PangoFontMetrics* pango_metrics =
        pango_context_get_metrics(context,
                                  pango_desc,
                                  pango_language_get_default());
    double pango_width =
        pango_font_metrics_get_approximate_char_width(pango_metrics);
    pango_width /= PANGO_SCALE;

    // Yes, this is how Microsoft recommends calculating the dialog unit
    // conversions.
    int text_width = GetStringWidth(
        L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    double dialog_units = (text_width / 26 + 1) / 2;

    avg_width_ = std::min(pango_width, dialog_units);
    pango_font_metrics_unref(pango_metrics);
    pango_font_description_free(pango_desc);
  }
  return avg_width_;
}

int Font::GetExpectedTextWidth(int length) const {
  double char_width = const_cast<Font*>(this)->avg_width();
  return round(static_cast<float>(length) * char_width);
}

int Font::style() const {
  return style_;
}

std::wstring Font::FontName() {
  return font_family_;
}

int Font::FontSize() {
  return font_size_;
}

NativeFont Font::nativeFont() const {
  return typeface_;
}

}  // namespace gfx
<|endoftext|>


<commit_before><commit_msg>Fix shipyard update<commit_after><|endoftext|>


<commit_before><commit_msg>Make sure interrupt value is flushed to table<commit_after><|endoftext|>


<commit_before>/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*   Cyril Bosselut (bosselut@b1project.com)                               *
*                                                                         *
*   Copyright (C) 2003-2005 by                                            *
*   Jason Kivlighn (jkivlighn@gmail.com)                                  *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "dependanciesdialog.h"
#include "datablocks/elementlist.h"

#include <kvbox.h>
//Added by qt3to4:
#include <QLabel>
#include <Q3ValueList>

#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>

DependanciesDialog::DependanciesDialog( QWidget *parent, const Q3ValueList<ListInfo> &lists, bool deps_are_deleted )
	: KDialog( parent ), m_depsAreDeleted(deps_are_deleted)
{
	init( lists );
}

DependanciesDialog::DependanciesDialog( QWidget *parent, const ListInfo &list, bool deps_are_deleted ) : KDialog( parent ),
	m_depsAreDeleted(deps_are_deleted)
{
	Q3ValueList<ListInfo> lists;
	lists << list;
	init( lists );
}

DependanciesDialog::~DependanciesDialog()
{}

void DependanciesDialog::init( const Q3ValueList<ListInfo> &lists )
{
	setModal(true);
	setDefaultButton(KDialog::Cancel);
	setButtons(KDialog::Ok | KDialog::Cancel);

	setCaption( i18n( "Element with Dependencies" ) );

	KVBox *page = new KVBox( this );
	setMainWidget( page );
	// Design the dialog

	instructionsLabel = new QLabel( page );
	instructionsLabel->setMinimumSize( QSize( 100, 30 ) );
	instructionsLabel->setMaximumSize( QSize( 10000, 10000 ) );
	instructionsLabel->setAlignment( Qt::AlignVCenter );
	instructionsLabel->setWordWrap(true);
	if ( m_depsAreDeleted ) {
		instructionsLabel->setText( i18n( "WARNING: The following will have to be removed also, since currently they use the element you have chosen to be removed." ) );
	}
	else {
		instructionsLabel->setText( i18n( "WARNING: The following currently use the element you have chosen to be removed." ) );
	}

	for ( Q3ValueList<ListInfo>::const_iterator list_it = lists.begin(); list_it != lists.end(); ++list_it ) {
		if ( !((*list_it).list).isEmpty() ) {
			Q3GroupBox *groupBox = new Q3GroupBox( 1, Qt::Vertical, (*list_it).name, page );
			K3ListBox *listBox = new K3ListBox( groupBox );
			loadList( listBox, (*list_it).list );
		}
	}

	setSizeGripEnabled( true );
}

void DependanciesDialog::loadList( K3ListBox* listBox, const ElementList &list )
{
	KConfigGroup config( KGlobal::config(), "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );

	for ( ElementList::const_iterator el_it = list.begin(); el_it != list.end(); ++el_it ) {
		QString name = ( *el_it ).name;
		if ( show_id )
			name += " (" + QString::number(( *el_it ).id) + ")";
		listBox->insertItem( name );
	}
}

void DependanciesDialog::accept()
{
	if ( !m_msg.isEmpty() ) {
		switch ( KMessageBox::warningYesNo(this,
			QString("%1

%2").arg(m_msg).arg(i18n("Are you sure you wish to proceed?")),
			QString::null,KStandardGuiItem::yes(),KStandardGuiItem::no(),"doubleCheckDelete") )
		{
		case KMessageBox::Yes: QDialog::accept(); break;
		case KMessageBox::No: QDialog::reject(); break;
		}
	}
	else
		QDialog::accept();
}
<commit_msg>s/QDialog/KDialog, it fixes krazy issues.<commit_after>/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*   Cyril Bosselut (bosselut@b1project.com)                               *
*                                                                         *
*   Copyright (C) 2003-2005 by                                            *
*   Jason Kivlighn (jkivlighn@gmail.com)                                  *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "dependanciesdialog.h"
#include "datablocks/elementlist.h"

#include <kvbox.h>
//Added by qt3to4:
#include <QLabel>
#include <Q3ValueList>

#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>

DependanciesDialog::DependanciesDialog( QWidget *parent, const Q3ValueList<ListInfo> &lists, bool deps_are_deleted )
	: KDialog( parent ), m_depsAreDeleted(deps_are_deleted)
{
	init( lists );
}

DependanciesDialog::DependanciesDialog( QWidget *parent, const ListInfo &list, bool deps_are_deleted ) : KDialog( parent ),
	m_depsAreDeleted(deps_are_deleted)
{
	Q3ValueList<ListInfo> lists;
	lists << list;
	init( lists );
}

DependanciesDialog::~DependanciesDialog()
{}

void DependanciesDialog::init( const Q3ValueList<ListInfo> &lists )
{
	setModal(true);
	setDefaultButton(KDialog::Cancel);
	setButtons(KDialog::Ok | KDialog::Cancel);

	setCaption( i18n( "Element with Dependencies" ) );

	KVBox *page = new KVBox( this );
	setMainWidget( page );
	// Design the dialog

	instructionsLabel = new QLabel( page );
	instructionsLabel->setMinimumSize( QSize( 100, 30 ) );
	instructionsLabel->setMaximumSize( QSize( 10000, 10000 ) );
	instructionsLabel->setAlignment( Qt::AlignVCenter );
	instructionsLabel->setWordWrap(true);
	if ( m_depsAreDeleted ) {
		instructionsLabel->setText( i18n( "WARNING: The following will have to be removed also, since currently they use the element you have chosen to be removed." ) );
	}
	else {
		instructionsLabel->setText( i18n( "WARNING: The following currently use the element you have chosen to be removed." ) );
	}

	for ( Q3ValueList<ListInfo>::const_iterator list_it = lists.begin(); list_it != lists.end(); ++list_it ) {
		if ( !((*list_it).list).isEmpty() ) {
			Q3GroupBox *groupBox = new Q3GroupBox( 1, Qt::Vertical, (*list_it).name, page );
			K3ListBox *listBox = new K3ListBox( groupBox );
			loadList( listBox, (*list_it).list );
		}
	}

	setSizeGripEnabled( true );
}

void DependanciesDialog::loadList( K3ListBox* listBox, const ElementList &list )
{
	KConfigGroup config( KGlobal::config(), "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );

	for ( ElementList::const_iterator el_it = list.begin(); el_it != list.end(); ++el_it ) {
		QString name = ( *el_it ).name;
		if ( show_id )
			name += " (" + QString::number(( *el_it ).id) + ")";
		listBox->insertItem( name );
	}
}

void DependanciesDialog::accept()
{
	if ( !m_msg.isEmpty() ) {
		switch ( KMessageBox::warningYesNo(this,
			QString("%1

%2").arg(m_msg).arg(i18n("Are you sure you wish to proceed?")),
			QString::null,KStandardGuiItem::yes(),KStandardGuiItem::no(),"doubleCheckDelete") )
		{
		case KMessageBox::Yes: KDialog::accept(); break;
		case KMessageBox::No: KDialog::reject(); break;
		}
	}
	else
		KDialog::accept();
}
<|endoftext|>