<commit_before>/*
* Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
* Released to public domain under terms of the BSD Simplified license.
*
* 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.
*   * Neither the name of the organization nor the names of its contributors
*     may be used to endorse or promote products derived from this software
*     without specific prior written permission.
*
*   See <http://www.opensource.org/licenses/bsd-license>
*/

#include "opencv2/core/core.hpp"
#include <opencv2/face.hpp>
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <fstream>
#include <sstream>

using namespace cv;
using namespace std;

static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
  std::ifstream file(filename.c_str(), ifstream::in);
  if (!file) {
      string error_message = "No valid input file was given, please check the given filename.";
      CV_Error(CV_StsBadArg, error_message);
  }
  string line, path, classlabel;
  while (getline(file, line)) {
      stringstream liness(line);
      getline(liness, path, separator);
      getline(liness, classlabel);
      if(!path.empty() && !classlabel.empty()) {
          images.push_back(imread(path, 0));
          labels.push_back(atoi(classlabel.c_str()));
      }
  }
}

int main(int argc, const char *argv[]) {
  // Check for valid command line arguments, print usage
  // if no arguments were given.
  if (argc != 2) {
      cout << "usage: " << argv[0] << " <csv.ext>" << endl;
      exit(1);
  }
  // Get the path to your CSV.
  string fn_csv = string(argv[1]);
  // These vectors hold the images and corresponding labels.
  vector<Mat> images;
  vector<int> labels;
  // Read in the data. This can fail if no valid
  // input filename is given.
  try {
      read_csv(fn_csv, images, labels);
  } catch (cv::Exception& e) {
      cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
      // nothing more we can do
      exit(1);
  }
  // Quit if there are not enough images for this demo.
  if(images.size() <= 1) {
      string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
      CV_Error(CV_StsError, error_message);
  }
  // Get the height from the first image. We'll need this
  // later in code to reshape the images to their original
  // size:
  int height = images[0].rows;
  // The following lines simply get the last images from
  // your dataset and remove it from the vector. This is
  // done, so that the training data (which we learn the
  // cv::FaceRecognizer on) and the test data we test
  // the model with, do not overlap.
  Mat testSample = images[images.size() - 1];
  int testLabel = labels[labels.size() - 1];
  images.pop_back();
  labels.pop_back();
  // The following lines create an LBPH model for
  // face recognition and train it with the images and
  // labels read from the given CSV file.
  //
  // The LBPHFaceRecognizer uses Extended Local Binary Patterns
  // (it's probably configurable with other operators at a later
  // point), and has the following default values
  //
  //      radius = 1
  //      neighbors = 8
  //      grid_x = 8
  //      grid_y = 8
  //
  // So if you want a LBPH FaceRecognizer using a radius of
  // 2 and 16 neighbors, call the factory method with:
  //
  //      cv::createLBPHFaceRecognizer(2, 16);
  //
  // And if you want a threshold (e.g. 123.0) call it with its default values:
  //
  //      cv::createLBPHFaceRecognizer(1,8,8,8,123.0)
  //
  Ptr<FaceRecognizer> model = createLBPHFaceRecognizer();
  model->train(images, labels);
  // The following line predicts the label of a given
  // test image:
  int predictedLabel = model->predict(testSample);
  //
  // To get the confidence of a prediction call the model with:
  //
  //      int predictedLabel = -1;
  //      double confidence = 0.0;
  //      model->predict(testSample, predictedLabel, confidence);
  //
  string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
  cout << result_message << endl;
  // Sometimes you'll need to get/set internal model data,
  // which isn't exposed by the public cv::FaceRecognizer.
  // Since each cv::FaceRecognizer is derived from a
  // cv::Algorithm, you can query the data.
  //
  // First we'll use it to set the threshold of the FaceRecognizer
  // to 0.0 without retraining the model. This can be useful if
  // you are evaluating the model:
  //
  model->set("threshold", 0.0);
  // Now the threshold of this model is set to 0.0. A prediction
  // now returns -1, as it's impossible to have a distance below
  // it
  predictedLabel = model->predict(testSample);
  cout << "Predicted class = " << predictedLabel << endl;
  // Show some informations about the model, as there's no cool
  // Model data to display as in Eigenfaces/Fisherfaces.
  // Due to efficiency reasons the LBP images are not stored
  // within the model:
  cout << "Model Information:" << endl;
  string model_info = format("\tLBPH(radius=%i, neighbors=%i, grid_x=%i, grid_y=%i, threshold=%.2f)",
          model->getInt("radius"),
          model->getInt("neighbors"),
          model->getInt("grid_x"),
          model->getInt("grid_y"),
          model->getDouble("threshold"));
  cout << model_info << endl;
  // We could get the histograms for example:
  vector<Mat> histograms = model->getMatVector("histograms");
  // But should I really visualize it? Probably the length is interesting:
  cout << "Size of the histograms: " << histograms[0].total() << endl;
  return 0;
}
<commit_msg>After fixing local libraries of OpenCV and downloading the latest version of the Facemapper tutorial it finally works<commit_after>/*
 * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
 * Released to public domain under terms of the BSD Simplified license.
 *
 * 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.
 *   * Neither the name of the organization nor the names of its contributors
 *     may be used to endorse or promote products derived from this software
 *     without specific prior written permission.
 *
 *   See <http://www.opensource.org/licenses/bsd-license>
 */
#include "opencv2/core.hpp"
#include "opencv2/face.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace cv;
using namespace cv::face;
using namespace std;
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
    std::ifstream file(filename.c_str(), ifstream::in);
    if (!file) {
        string error_message = "No valid input file was given, please check the given filename.";
        CV_Error(Error::StsBadArg, error_message);
    }
    string line, path, classlabel;
    while (getline(file, line)) {
        stringstream liness(line);
        getline(liness, path, separator);
        getline(liness, classlabel);
        if(!path.empty() && !classlabel.empty()) {
            images.push_back(imread(path, 0));
            labels.push_back(atoi(classlabel.c_str()));
        }
    }
}
int main(int argc, const char *argv[]) {
    // Check for valid command line arguments, print usage
    // if no arguments were given.
    if (argc != 2) {
        cout << "usage: " << argv[0] << " <csv.ext>" << endl;
        exit(1);
    }
    // Get the path to your CSV.
    string fn_csv = string(argv[1]);
    // These vectors hold the images and corresponding labels.
    vector<Mat> images;
    vector<int> labels;
    // Read in the data. This can fail if no valid
    // input filename is given.
    try {
        read_csv(fn_csv, images, labels);
    } catch (cv::Exception& e) {
        cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
        // nothing more we can do
        exit(1);
    }
    // Quit if there are not enough images for this demo.
    if(images.size() <= 1) {
        string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
        CV_Error(Error::StsError, error_message);
    }
    // The following lines simply get the last images from
    // your dataset and remove it from the vector. This is
    // done, so that the training data (which we learn the
    // cv::LBPHFaceRecognizer on) and the test data we test
    // the model with, do not overlap.
    Mat testSample = images[images.size() - 1];
    int testLabel = labels[labels.size() - 1];
    images.pop_back();
    labels.pop_back();
    // The following lines create an LBPH model for
    // face recognition and train it with the images and
    // labels read from the given CSV file.
    //
    // The LBPHFaceRecognizer uses Extended Local Binary Patterns
    // (it's probably configurable with other operators at a later
    // point), and has the following default values
    //
    //      radius = 1
    //      neighbors = 8
    //      grid_x = 8
    //      grid_y = 8
    //
    // So if you want a LBPH FaceRecognizer using a radius of
    // 2 and 16 neighbors, call the factory method with:
    //
    //      cv::createLBPHFaceRecognizer(2, 16);
    //
    // And if you want a threshold (e.g. 123.0) call it with its default values:
    //
    //      cv::createLBPHFaceRecognizer(1,8,8,8,123.0)
    //
    Ptr<LBPHFaceRecognizer> model = createLBPHFaceRecognizer();
    model->train(images, labels);
    // The following line predicts the label of a given
    // test image:
    int predictedLabel = model->predict(testSample);
    //
    // To get the confidence of a prediction call the model with:
    //
    //      int predictedLabel = -1;
    //      double confidence = 0.0;
    //      model->predict(testSample, predictedLabel, confidence);
    //
    string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
    cout << result_message << endl;
    // First we'll use it to set the threshold of the LBPHFaceRecognizer
    // to 0.0 without retraining the model. This can be useful if
    // you are evaluating the model:
    //
    model->setThreshold(0.0);
    // Now the threshold of this model is set to 0.0. A prediction
    // now returns -1, as it's impossible to have a distance below
    // it
    predictedLabel = model->predict(testSample);
    cout << "Predicted class = " << predictedLabel << endl;
    // Show some informations about the model, as there's no cool
    // Model data to display as in Eigenfaces/Fisherfaces.
    // Due to efficiency reasons the LBP images are not stored
    // within the model:
    cout << "Model Information:" << endl;
    string model_info = format("\tLBPH(radius=%i, neighbors=%i, grid_x=%i, grid_y=%i, threshold=%.2f)",
            model->getRadius(),
            model->getNeighbors(),
            model->getGridX(),
            model->getGridY(),
            model->getThreshold());
    cout << model_info << endl;
    // We could get the histograms for example:
    vector<Mat> histograms = model->getHistograms();
    // But should I really visualize it? Probably the length is interesting:
    cout << "Size of the histograms: " << histograms[0].total() << endl;
    return 0;
}
<|endoftext|>


<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_rt_native.h"

HRESULT Library_nf_rt_native_System_Environment::get_TickCount64___STATIC__I8(CLR_RT_StackFrame &stack)
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    CLR_RT_HeapBlock &ref = stack.PushValue();

    // get pointer to object pushed to the stack
    // and set with value from EE
    ref.Dereference()->NumericByRef().s8 = CLR_RT_ExecutionEngine::GetUptime();

    NANOCLR_NOCLEANUP_NOLABEL();
}
<commit_msg>Fix Environment.TickCount64 (#2244)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_rt_native.h"

HRESULT Library_nf_rt_native_System_Environment::get_TickCount64___STATIC__I8(CLR_RT_StackFrame &stack)
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

    int64_t ticksValue = CLR_RT_ExecutionEngine::GetUptime();

    stack.SetResult_I8(ticksValue);

    NANOCLR_NOCLEANUP_NOLABEL();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>

#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>

using std::endl;
using test::Bytes;

/**
 * RPC Object with a single function that accepts a string
 */
class TestObject {
public:
    void fun(const std::string& words) {
    }

    void bytes_fun(const Bytes& bytes) {
    }

    bool finishing_call(int x) {
        return true;
    }

    REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};

struct exp_result {
    int num_nodes;
    long long unsigned int max_msg_size;
    unsigned int window_size;
    int count;
    double avg_msec;
    double avg_gbps;
    double avg_ops;

    void print(std::ofstream& fout) {
        fout << num_nodes << " "
             << max_msg_size << " " << window_size << " "
             << count << " "
             << avg_msec << " " << avg_gbps << " "
             << avg_ops << endl;
    }
};

#define DEFAULT_PROC_NAME "typed_bw_test"

int main(int argc, char* argv[]) {
    int dashdash_pos = argc - 1;
    while(dashdash_pos > 0) {
        if(strcmp(argv[dashdash_pos], "--") == 0) {
            break;
        }
        dashdash_pos--;
    }

    if((argc - dashdash_pos) < 3) {
        std::cout << "Invalid command line arguments." << std::endl;
        std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_of_nodes> <count> [proc_name]" << std::endl;
        std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
        return -1;
    }

    derecho::Conf::initialize(argc, argv);

    int num_of_nodes = std::stoi(argv[dashdash_pos + 1]);
    uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
    int count = std::stoi(argv[dashdash_pos + 2]);
    if(dashdash_pos + 3 < argc) {
        pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
    } else {
        pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
    }

    derecho::SubgroupInfo subgroup_info{[num_of_nodes](
                                                const std::vector<std::type_index>& subgroup_type_order,
                                                const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
        if(curr_view.num_members < num_of_nodes) {
            std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_of_nodes << std::endl;
            throw derecho::subgroup_provisioning_exception();
        }
        derecho::subgroup_shard_layout_t subgroup_layout(1);

        std::vector<uint32_t> members(num_of_nodes);
        for(int i = 0; i < num_of_nodes; i++) {
            members[i] = i;
        }

        subgroup_layout[0].emplace_back(curr_view.make_subview(members));
        curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_of_nodes);
        derecho::subgroup_allocation_map_t subgroup_allocation;
        subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
        return subgroup_allocation;
    }};

    auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };

    derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
    std::cout << "Finished constructing/joining Group" << std::endl;

    derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
    //std::string str_1k(max_msg_size, 'x');
    char* bbuf = (char*)malloc(max_msg_size);
    bzero(bbuf, max_msg_size);
    Bytes bytes(bbuf, max_msg_size);

    struct timespec t1, t2;
    clock_gettime(CLOCK_REALTIME, &t1);

    for(int i = 0; i < count; i++) {
        //handle.ordered_send<RPC_NAME(fun)>(str_1k);
        handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
    }

    auto members_order = group.get_members();
    uint32_t node_rank = group.get_my_rank();
    if(node_rank == 0) {
        derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
        std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
        decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
    }

    clock_gettime(CLOCK_REALTIME, &t2);
    free(bbuf);

    int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;
    double msec = (double)nsec / 1000000;
    double thp_gbps = ((double)count * max_msg_size * 8) / nsec;
    double thp_ops = ((double)count * 1000000000) / nsec;
    std::cout << "timespan:" << msec << " millisecond." << std::endl;
    std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
    std::cout << "throughput:" << thp_ops << "ops." << std::endl;

    // aggregate bandwidth from all nodes
    std::pair<double, double> bw_laten(thp_gbps,msec);

    bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);

    double avg_gbps = bw_laten.first;
    double avg_msec = bw_laten.second;

    if(node_rank == 0) {
        log_results(exp_result{num_of_nodes, max_msg_size,
                               derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
                               avg_msec, avg_gbps},
                    "data_derecho_typed_subgroup_bw");
    }

    group.barrier_sync();
    group.leave();
}
<commit_msg>Added num_sender_selecter to typed_subgroup_bw_test<commit_after>#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <time.h>
#include <vector>

#include "aggregate_bandwidth.cpp"
#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include <derecho/conf/conf.hpp>
#include <derecho/core/derecho.hpp>
#include <derecho/mutils-serialization/SerializationSupport.hpp>
#include <derecho/persistent/Persistent.hpp>
#include "partial_senders_allocator.hpp"

using std::endl;
using test::Bytes;

/**
 * RPC Object with a single function that accepts a string
 */
class TestObject {
public:
    void fun(const std::string& words) {
    }

    void bytes_fun(const Bytes& bytes) {
    }

    bool finishing_call(int x) {
        return true;
    }

    REGISTER_RPC_FUNCTIONS(TestObject, fun, bytes_fun, finishing_call);
};

struct exp_result {
    int num_nodes;
    uint32_t num_sender_sel;
    long long unsigned int max_msg_size;
    unsigned int window_size;
    uint32_t count;
    double avg_msec;
    double avg_gbps;
    double avg_ops;

    void print(std::ofstream& fout) {
        fout << num_nodes << " " << num_sender_sel
             << max_msg_size << " " << window_size << " "
             << count << " "
             << avg_msec << " " << avg_gbps << " "
             << avg_ops << endl;
    }
};

#define DEFAULT_PROC_NAME "typed_bw_test"

int main(int argc, char* argv[]) {
    int dashdash_pos = argc - 1;
    while(dashdash_pos > 0) {
        if(strcmp(argv[dashdash_pos], "--") == 0) {
            break;
        }
        dashdash_pos--;
    }

    if((argc - dashdash_pos) < 4) {
        std::cout << "Invalid command line arguments." << std::endl;
        std::cout << "USAGE: " << argv[0] << " [ derecho-config-list -- ] <num_nodes> <count> <num_senders_selector>[proc_name]" << std::endl;
        std::cout << "Note: proc_name sets the process's name as displayed in ps and pkill commands, default is " DEFAULT_PROC_NAME << std::endl;
        return -1;
    }

    derecho::Conf::initialize(argc, argv);

    const int num_nodes = std::stoi(argv[dashdash_pos + 1]);
    const uint64_t max_msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);
    const uint32_t count = std::stoi(argv[dashdash_pos + 2]);
    const uint32_t num_senders_selector = std::stoi(argv[dashdash_pos + 3]);

    // Convert this integer to a more readable enum value
    const PartialSendMode senders_mode = num_senders_selector == 0
                                                 ? PartialSendMode::ALL_SENDERS
                                                 : (num_senders_selector == 1
                                                            ? PartialSendMode::HALF_SENDERS
                                                            : PartialSendMode::ONE_SENDER);

    if(dashdash_pos + 4 < argc) {
        pthread_setname_np(pthread_self(), argv[dashdash_pos + 3]);
    } else {
        pthread_setname_np(pthread_self(), DEFAULT_PROC_NAME);
    }

    derecho::SubgroupInfo subgroup_info{[num_nodes](
                                                const std::vector<std::type_index>& subgroup_type_order,
                                                const std::unique_ptr<derecho::View>& prev_view, derecho::View& curr_view) {
        if(curr_view.num_members < num_nodes) {
            std::cout << "not enough members yet:" << curr_view.num_members << " < " << num_nodes << std::endl;
            throw derecho::subgroup_provisioning_exception();
        }
        derecho::subgroup_shard_layout_t subgroup_layout(1);

        std::vector<uint32_t> members(num_nodes);
        for(int i = 0; i < num_nodes; i++) {
            members[i] = i;
        }

        subgroup_layout[0].emplace_back(curr_view.make_subview(members));
        curr_view.next_unassigned_rank = std::max(curr_view.next_unassigned_rank, num_nodes);
        derecho::subgroup_allocation_map_t subgroup_allocation;
        subgroup_allocation.emplace(std::type_index(typeid(TestObject)), std::move(subgroup_layout));
        return subgroup_allocation;
    }};

    auto ba_factory = [](persistent::PersistentRegistry*, derecho::subgroup_id_t) { return std::make_unique<TestObject>(); };

    derecho::Group<TestObject> group({}, subgroup_info, {}, std::vector<derecho::view_upcall_t>{}, ba_factory);
    std::cout << "Finished constructing/joining Group" << std::endl;

    derecho::Replicated<TestObject>& handle = group.get_subgroup<TestObject>();
    //std::string str_1k(max_msg_size, 'x');
    char* bbuf = (char*)malloc(max_msg_size);
    bzero(bbuf, max_msg_size);
    Bytes bytes(bbuf, max_msg_size);

    struct timespec t1, t2;
    clock_gettime(CLOCK_REALTIME, &t1);

    // this function sends all the messages
    auto send_all = [&]() {
        for(uint i = 0; i < count; i++) {
        //handle.ordered_send<RPC_NAME(fun)>(str_1k);
        handle.ordered_send<RPC_NAME(bytes_fun)>(bytes);
    }
    };

    int node_rank = group.get_my_rank();

    if(senders_mode == PartialSendMode::ALL_SENDERS) {
        send_all();
    } else if(senders_mode == PartialSendMode::HALF_SENDERS) {
        if(node_rank > (num_nodes - 1) / 2) {
            send_all();
        }
    } else {
        if(node_rank == num_nodes - 1) {
            send_all();
        }
    }

    if(node_rank == 0) {
        derecho::rpc::QueryResults<bool> results = handle.ordered_send<RPC_NAME(finishing_call)>(0);
        std::cout << "waiting for response..." << std::endl;
#pragma GCC diagnostic ignored "-Wunused-variable"
        decltype(results)::ReplyMap& replies = results.get();
#pragma GCC diagnostic pop
    }

    clock_gettime(CLOCK_REALTIME, &t2);
    free(bbuf);

    double thp_gbps;
    int64_t nsec = ((int64_t)t2.tv_sec - t1.tv_sec) * 1000000000 + t2.tv_nsec - t1.tv_nsec;

    if(senders_mode == PartialSendMode::ALL_SENDERS) {
        thp_gbps = ((double)count * max_msg_size * 8 * num_nodes) / nsec;
    } else if(senders_mode == PartialSendMode::HALF_SENDERS) {
        thp_gbps = ((double)count * max_msg_size * 8 * num_nodes/2) / nsec;
    } else {
        thp_gbps = ((double)count * max_msg_size * 8) / nsec;
    }

    double msec = (double)nsec / 1000000;
    double thp_ops = ((double)count * 1000000000) / nsec;
    std::cout << "timespan:" << msec << " millisecond." << std::endl;
    std::cout << "throughput:" << thp_gbps << "Gbit/s." << std::endl;
    std::cout << "throughput:" << thp_ops << "ops." << std::endl;

    // aggregate bandwidth from all nodes
    std::pair<double, double> bw_laten(thp_gbps,msec);

    auto members_order = group.get_members();
    bw_laten = aggregate_bandwidth(members_order, members_order[node_rank], bw_laten);

    double avg_gbps = bw_laten.first;
    double avg_msec = bw_laten.second;

    if(node_rank == 0) {
        log_results(exp_result{num_nodes, num_senders_selector, max_msg_size,
                               derecho::getConfUInt32(CONF_SUBGROUP_DEFAULT_WINDOW_SIZE), count,
                               avg_msec, avg_gbps},
                    "data_derecho_typed_subgroup_bw");
    }

    group.barrier_sync();
    group.leave();
}
<|endoftext|>


<commit_before>#pragma once

#include "blob_interface.hpp"
#include "ipmi_interface.hpp"

#include <memory>

namespace ipmiblob
{

class BlobHandler : public BlobInterface
{
  public:
    enum BlobOEMCommands
    {
        bmcBlobGetCount = 0,
        bmcBlobEnumerate = 1,
        bmcBlobOpen = 2,
        bmcBlobRead = 3,
        bmcBlobWrite = 4,
        bmcBlobCommit = 5,
        bmcBlobClose = 6,
        bmcBlobDelete = 7,
        bmcBlobStat = 8,
        bmcBlobSessionStat = 9,
        bmcBlobWriteMeta = 10,
    };

    /**
     * Create a BlobInterface pointer for use given an ipmi handler.
     *
     * @note This is a convenience method.
     * @return a BlobHandler wrapped as a BlobInterface pointer.
     */
    static std::unique_ptr<BlobInterface>
        CreateBlobHandler(std::unique_ptr<IpmiInterface> ipmi);

    explicit BlobHandler(std::unique_ptr<IpmiInterface> ipmi) :
        ipmi(std::move(ipmi)){};

    ~BlobHandler() = default;
    BlobHandler(const BlobHandler&) = delete;
    BlobHandler& operator=(const BlobHandler&) = delete;
    BlobHandler(BlobHandler&&) = default;
    BlobHandler& operator=(BlobHandler&&) = default;

    /**
     * Retrieve the blob count.
     *
     * @return the number of blob_ids found (0 on failure).
     */
    int getBlobCount();

    /**
     * Given an index into the list of blobs, return the name.
     *
     * @param[in] index - the index into the list of blob ids.
     * @return the name as a string or empty on failure.
     */
    std::string enumerateBlob(std::uint32_t index);

    /**
     * @throws BlobException.
     */
    void commit(std::uint16_t session,
                const std::vector<std::uint8_t>& bytes) override;

    /**
     * @throws BlobException.
     */
    void writeMeta(std::uint16_t session, std::uint32_t offset,
                   const std::vector<std::uint8_t>& bytes) override;

    /**
     * @throw BlobException.
     */
    void writeBytes(std::uint16_t session, std::uint32_t offset,
                    const std::vector<std::uint8_t>& bytes) override;

    std::vector<std::string> getBlobList() override;

    /**
     * @throws BlobException.
     */
    StatResponse getStat(const std::string& id) override;

    /**
     * @throws BlobException.
     */
    StatResponse getStat(std::uint16_t session) override;

    /**
     * @throws BlobException.
     */
    std::uint16_t openBlob(const std::string& id,
                           std::uint16_t handlerFlags) override;

    void closeBlob(std::uint16_t session) override;

    /**
     * @throws BlobException.
     */
    std::vector<std::uint8_t> readBytes(std::uint16_t session,
                                        std::uint32_t offset,
                                        std::uint32_t length) override;

  private:
    /**
     * Send the contents of the payload to IPMI, this method handles wrapping
     * with the OEN, subcommand and CRC.
     *
     * @param[in] command - the blob command.
     * @param[in] payload - the payload bytes.
     * @return the bytes returned from the ipmi interface.
     * @throws BlobException.
     */
    std::vector<std::uint8_t>
        sendIpmiPayload(BlobOEMCommands command,
                        const std::vector<std::uint8_t>& payload);

    /**
     * Generic blob byte writer.
     *
     * @param[in] command - the command associated with this write.
     * @param[in] session - the session id.
     * @param[in] offset - the offset for the metadata to write.
     * @param[in] bytes - the bytes to send.
     * @throws BlobException on failure.
     */
    void writeGeneric(BlobOEMCommands command, std::uint16_t session,
                      std::uint32_t offset,
                      const std::vector<std::uint8_t>& bytes);

    /**
     * Generic stat reader.
     *
     * @param[in] command - the command associated with this write.
     * @param[in] request - the bytes of the request
     * @return the metadata StatResponse
     * @throws BlobException on failure.
     */
    StatResponse statGeneric(BlobOEMCommands command,
                             const std::vector<std::uint8_t>& request);

    std::unique_ptr<IpmiInterface> ipmi;
};

} // namespace ipmiblob
<commit_msg>blob_handler: make commit data parameter optional<commit_after>#pragma once

#include "blob_interface.hpp"
#include "ipmi_interface.hpp"

#include <memory>

namespace ipmiblob
{

class BlobHandler : public BlobInterface
{
  public:
    enum BlobOEMCommands
    {
        bmcBlobGetCount = 0,
        bmcBlobEnumerate = 1,
        bmcBlobOpen = 2,
        bmcBlobRead = 3,
        bmcBlobWrite = 4,
        bmcBlobCommit = 5,
        bmcBlobClose = 6,
        bmcBlobDelete = 7,
        bmcBlobStat = 8,
        bmcBlobSessionStat = 9,
        bmcBlobWriteMeta = 10,
    };

    /**
     * Create a BlobInterface pointer for use given an ipmi handler.
     *
     * @note This is a convenience method.
     * @return a BlobHandler wrapped as a BlobInterface pointer.
     */
    static std::unique_ptr<BlobInterface>
        CreateBlobHandler(std::unique_ptr<IpmiInterface> ipmi);

    explicit BlobHandler(std::unique_ptr<IpmiInterface> ipmi) :
        ipmi(std::move(ipmi)){};

    ~BlobHandler() = default;
    BlobHandler(const BlobHandler&) = delete;
    BlobHandler& operator=(const BlobHandler&) = delete;
    BlobHandler(BlobHandler&&) = default;
    BlobHandler& operator=(BlobHandler&&) = default;

    /**
     * Retrieve the blob count.
     *
     * @return the number of blob_ids found (0 on failure).
     */
    int getBlobCount();

    /**
     * Given an index into the list of blobs, return the name.
     *
     * @param[in] index - the index into the list of blob ids.
     * @return the name as a string or empty on failure.
     */
    std::string enumerateBlob(std::uint32_t index);

    /**
     * @throws BlobException.
     */
    void commit(std::uint16_t session,
                const std::vector<std::uint8_t>& bytes = {}) override;

    /**
     * @throws BlobException.
     */
    void writeMeta(std::uint16_t session, std::uint32_t offset,
                   const std::vector<std::uint8_t>& bytes) override;

    /**
     * @throw BlobException.
     */
    void writeBytes(std::uint16_t session, std::uint32_t offset,
                    const std::vector<std::uint8_t>& bytes) override;

    std::vector<std::string> getBlobList() override;

    /**
     * @throws BlobException.
     */
    StatResponse getStat(const std::string& id) override;

    /**
     * @throws BlobException.
     */
    StatResponse getStat(std::uint16_t session) override;

    /**
     * @throws BlobException.
     */
    std::uint16_t openBlob(const std::string& id,
                           std::uint16_t handlerFlags) override;

    void closeBlob(std::uint16_t session) override;

    /**
     * @throws BlobException.
     */
    std::vector<std::uint8_t> readBytes(std::uint16_t session,
                                        std::uint32_t offset,
                                        std::uint32_t length) override;

  private:
    /**
     * Send the contents of the payload to IPMI, this method handles wrapping
     * with the OEN, subcommand and CRC.
     *
     * @param[in] command - the blob command.
     * @param[in] payload - the payload bytes.
     * @return the bytes returned from the ipmi interface.
     * @throws BlobException.
     */
    std::vector<std::uint8_t>
        sendIpmiPayload(BlobOEMCommands command,
                        const std::vector<std::uint8_t>& payload);

    /**
     * Generic blob byte writer.
     *
     * @param[in] command - the command associated with this write.
     * @param[in] session - the session id.
     * @param[in] offset - the offset for the metadata to write.
     * @param[in] bytes - the bytes to send.
     * @throws BlobException on failure.
     */
    void writeGeneric(BlobOEMCommands command, std::uint16_t session,
                      std::uint32_t offset,
                      const std::vector<std::uint8_t>& bytes);

    /**
     * Generic stat reader.
     *
     * @param[in] command - the command associated with this write.
     * @param[in] request - the bytes of the request
     * @return the metadata StatResponse
     * @throws BlobException on failure.
     */
    StatResponse statGeneric(BlobOEMCommands command,
                             const std::vector<std::uint8_t>& request);

    std::unique_ptr<IpmiInterface> ipmi;
};

} // namespace ipmiblob
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_iconv.hxx"
#include "FacadeIstream.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <iconv.h>

#include <assert.h>
#include <errno.h>

class IconvIstream final : public FacadeIstream {
    static constexpr size_t BUFFER_SIZE = 1024;

    const iconv_t iconv;
    ForeignFifoBuffer<uint8_t> buffer;

public:
    IconvIstream(struct pool &p, struct istream &_input,
                 iconv_t _iconv)
        :FacadeIstream(p, _input,
                       MakeIstreamHandler<IconvIstream>::handler, this),
         iconv(_iconv),
         buffer(PoolAlloc<uint8_t>(p, BUFFER_SIZE), BUFFER_SIZE)
    {
    }

    ~IconvIstream() {
        buffer.SetNull();
        iconv_close(iconv);
    }

    bool IsOpen() const {
        return buffer.IsDefined();
    }

    /* virtual methods from class Istream */

    off_t GetAvailable(bool partial) override {
        if (partial)
            return buffer.GetAvailable();

        return -1;
    }

    void Read() override;
    void Close() override;

    /* handler */

    size_t OnData(const void *data, size_t length);

    ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
                     gcc_unused size_t max_length) {
        gcc_unreachable();
    }

    void OnEof();
    void OnError(GError *error);

private:
    size_t Feed(const char *data, size_t length);
};

gcc_const
static GQuark
iconv_quark(void)
{
    return g_quark_from_static_string("iconv");
}

static inline size_t
deconst_iconv(iconv_t cd,
              const char **inbuf, size_t *inbytesleft,
              char **outbuf, size_t *outbytesleft)
{
    char **inbuf2 = const_cast<char **>(inbuf);
    return iconv(cd, inbuf2, inbytesleft, outbuf, outbytesleft);
}

size_t
IconvIstream::Feed(const char *data, size_t length)
{
    const char *src = data;

    do {
        auto w = buffer.Write();
        if (w.IsEmpty()) {
            /* no space left in the buffer: attempt to flush it */

            size_t nbytes = SendFromBuffer(buffer);
            if (nbytes == 0) {
                if (!IsOpen())
                    return 0;
                break;
            }

            assert(IsOpen());

            continue;
        }

        char *const dest0 = (char *)w.data;
        char *dest = dest0;
        size_t dest_left = w.size;

        size_t ret = deconst_iconv(iconv, &src, &length, &dest, &dest_left);
        if (dest > dest0)
            buffer.Append(dest - dest0);

        if (ret == (size_t)-1) {
            switch (errno) {
                size_t nbytes;

            case EILSEQ:
                /* invalid sequence: skip this byte */
                ++src;
                --length;
                break;

            case EINVAL:
                /* incomplete sequence: leave it in the buffer */
                if (src == data) {
                    /* XXX we abort here, because we believe if the
                       incomplete sequence is at the start of the
                       buffer, this might be EOF; we should rather
                       buffer this incomplete sequence and report the
                       caller that we consumed it */
                    input.Close();

                    GError *error = g_error_new_literal(iconv_quark(), 0,
                                                        "incomplete sequence");
                    DestroyError(error);
                    return 0;
                }

                length = 0;
                break;

            case E2BIG:
                /* output buffer is full: flush dest */
                nbytes = SendFromBuffer(buffer);
                if (nbytes == 0) {
                    if (!IsOpen())
                        return 0;

                    /* reset length to 0, to make the loop quit
                       (there's no "double break" to break out of the
                       while loop in C) */
                    length = 0;
                    break;
                }

                assert(IsOpen());
                break;
            }
        }
    } while (length > 0);

    SendFromBuffer(buffer);
    if (!IsOpen())
        return 0;

    return src - data;
}

/*
 * istream handler
 *
 */

size_t
IconvIstream::OnData(const void *data, size_t length)
{
    assert(input.IsDefined());

    const ScopePoolRef ref(GetPool() TRACE_ARGS);
    return Feed((const char *)data, length);
}

void
IconvIstream::OnEof()
{
    assert(input.IsDefined());
    input.Clear();

    if (buffer.IsEmpty())
        DestroyEof();
}

void
IconvIstream::OnError(GError *error)
{
    assert(input.IsDefined());

    DestroyError(error);
}

/*
 * istream implementation
 *
 */

void
IconvIstream::Read()
{
    if (input.IsDefined())
        input.Read();
    else {
        size_t rest = ConsumeFromBuffer(buffer);
        if (rest == 0)
            DestroyEof();
    }
}

void
IconvIstream::Close()
{
    if (input.IsDefined())
        input.Close();
    Destroy();
}

/*
 * constructor
 *
 */

struct istream *
istream_iconv_new(struct pool *pool, struct istream *input,
                  const char *tocode, const char *fromcode)
{
    assert(input != nullptr);
    assert(!istream_has_handler(input));

    const iconv_t iconv = iconv_open(tocode, fromcode);
    if (iconv == (iconv_t)-1)
        return nullptr;

    return NewIstream<IconvIstream>(*pool, *input, iconv);
}
<commit_msg>istream/iconv: use "iconv!=-1" in IsOpen()<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_iconv.hxx"
#include "FacadeIstream.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <iconv.h>

#include <assert.h>
#include <errno.h>

class IconvIstream final : public FacadeIstream {
    static constexpr size_t BUFFER_SIZE = 1024;

    iconv_t iconv;
    ForeignFifoBuffer<uint8_t> buffer;

public:
    IconvIstream(struct pool &p, struct istream &_input,
                 iconv_t _iconv)
        :FacadeIstream(p, _input,
                       MakeIstreamHandler<IconvIstream>::handler, this),
         iconv(_iconv),
         buffer(PoolAlloc<uint8_t>(p, BUFFER_SIZE), BUFFER_SIZE)
    {
    }

    ~IconvIstream() {
        iconv_close(iconv);
        iconv = (iconv_t)-1;
    }

    bool IsOpen() const {
        return iconv != (iconv_t)-1;
    }

    /* virtual methods from class Istream */

    off_t GetAvailable(bool partial) override {
        if (partial)
            return buffer.GetAvailable();

        return -1;
    }

    void Read() override;
    void Close() override;

    /* handler */

    size_t OnData(const void *data, size_t length);

    ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
                     gcc_unused size_t max_length) {
        gcc_unreachable();
    }

    void OnEof();
    void OnError(GError *error);

private:
    size_t Feed(const char *data, size_t length);
};

gcc_const
static GQuark
iconv_quark(void)
{
    return g_quark_from_static_string("iconv");
}

static inline size_t
deconst_iconv(iconv_t cd,
              const char **inbuf, size_t *inbytesleft,
              char **outbuf, size_t *outbytesleft)
{
    char **inbuf2 = const_cast<char **>(inbuf);
    return iconv(cd, inbuf2, inbytesleft, outbuf, outbytesleft);
}

size_t
IconvIstream::Feed(const char *data, size_t length)
{
    const char *src = data;

    do {
        auto w = buffer.Write();
        if (w.IsEmpty()) {
            /* no space left in the buffer: attempt to flush it */

            size_t nbytes = SendFromBuffer(buffer);
            if (nbytes == 0) {
                if (!IsOpen())
                    return 0;
                break;
            }

            assert(IsOpen());

            continue;
        }

        char *const dest0 = (char *)w.data;
        char *dest = dest0;
        size_t dest_left = w.size;

        size_t ret = deconst_iconv(iconv, &src, &length, &dest, &dest_left);
        if (dest > dest0)
            buffer.Append(dest - dest0);

        if (ret == (size_t)-1) {
            switch (errno) {
                size_t nbytes;

            case EILSEQ:
                /* invalid sequence: skip this byte */
                ++src;
                --length;
                break;

            case EINVAL:
                /* incomplete sequence: leave it in the buffer */
                if (src == data) {
                    /* XXX we abort here, because we believe if the
                       incomplete sequence is at the start of the
                       buffer, this might be EOF; we should rather
                       buffer this incomplete sequence and report the
                       caller that we consumed it */
                    input.Close();

                    GError *error = g_error_new_literal(iconv_quark(), 0,
                                                        "incomplete sequence");
                    DestroyError(error);
                    return 0;
                }

                length = 0;
                break;

            case E2BIG:
                /* output buffer is full: flush dest */
                nbytes = SendFromBuffer(buffer);
                if (nbytes == 0) {
                    if (!IsOpen())
                        return 0;

                    /* reset length to 0, to make the loop quit
                       (there's no "double break" to break out of the
                       while loop in C) */
                    length = 0;
                    break;
                }

                assert(IsOpen());
                break;
            }
        }
    } while (length > 0);

    SendFromBuffer(buffer);
    if (!IsOpen())
        return 0;

    return src - data;
}

/*
 * istream handler
 *
 */

size_t
IconvIstream::OnData(const void *data, size_t length)
{
    assert(input.IsDefined());

    const ScopePoolRef ref(GetPool() TRACE_ARGS);
    return Feed((const char *)data, length);
}

void
IconvIstream::OnEof()
{
    assert(input.IsDefined());
    input.Clear();

    if (buffer.IsEmpty())
        DestroyEof();
}

void
IconvIstream::OnError(GError *error)
{
    assert(input.IsDefined());

    DestroyError(error);
}

/*
 * istream implementation
 *
 */

void
IconvIstream::Read()
{
    if (input.IsDefined())
        input.Read();
    else {
        size_t rest = ConsumeFromBuffer(buffer);
        if (rest == 0)
            DestroyEof();
    }
}

void
IconvIstream::Close()
{
    if (input.IsDefined())
        input.Close();
    Destroy();
}

/*
 * constructor
 *
 */

struct istream *
istream_iconv_new(struct pool *pool, struct istream *input,
                  const char *tocode, const char *fromcode)
{
    assert(input != nullptr);
    assert(!istream_has_handler(input));

    const iconv_t iconv = iconv_open(tocode, fromcode);
    if (iconv == (iconv_t)-1)
        return nullptr;

    return NewIstream<IconvIstream>(*pool, *input, iconv);
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mapplicationextensionloader.h"
#include "mapplicationextensioninterface.h"
#include "mapplicationextensionmetadata.h"
#include <MDebug>
#include <QPluginLoader>

MApplicationExtensionLoader::MApplicationExtensionLoader()
{
}

MApplicationExtensionInterface *MApplicationExtensionLoader::loadExtension(const MApplicationExtensionMetaData &metadata)
{
    QPluginLoader loader(metadata.extensionBinary());
    loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    QObject *object = loader.instance();

    if (object != NULL) {
        if (object->inherits(metadata.interface().toUtf8().constData())) {
            MApplicationExtensionInterface *extension = dynamic_cast<MApplicationExtensionInterface *>(object);
            if (extension != NULL) {
                if (extension->initialize(metadata.interface())) {
                    return extension;
                } else {
                    mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be initialized.";
                }
            } else {
                mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not implement MApplicationExtensionInterface.";
            }
        } else {
            mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not inherit" << metadata.interface();
        }
        delete object;
    } else {
        mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be loaded." << loader.errorString();
    }

    return false;
}
<commit_msg>Fixes: NB#211859 - White and red rectangles in Events view after device reboot<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mapplicationextensionloader.h"
#include "mapplicationextensioninterface.h"
#include "mapplicationextensionmetadata.h"
#include <MDebug>
#include <QPluginLoader>

MApplicationExtensionLoader::MApplicationExtensionLoader()
{
}

MApplicationExtensionInterface *MApplicationExtensionLoader::loadExtension(const MApplicationExtensionMetaData &metadata)
{
    QPluginLoader loader(metadata.extensionBinary());
    loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    QObject *object = loader.instance();

    if (object != NULL) {
        if (object->inherits(metadata.interface().toUtf8().constData())) {
            MApplicationExtensionInterface *extension = qobject_cast<MApplicationExtensionInterface *>(object);
            if (extension != NULL) {
                if (extension->initialize(metadata.interface())) {
                    return extension;
                } else {
                    mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be initialized.";
                }
            } else {
                mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not implement MApplicationExtensionInterface.";
            }
        } else {
            mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not inherit" << metadata.interface();
        }
        delete object;
    } else {
        mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be loaded." << loader.errorString();
    }

    return false;
}
<|endoftext|>


<commit_before>/* -*-  mode: c++; indent-tabs-mode: nil -*- */

/* -----------------------------------------------------------------------------
ATS

Authors: Ethan Coon (ecoon@lanl.gov)

FieldEvaluator for enthalpy.
----------------------------------------------------------------------------- */

#include "enthalpy_evaluator.hh"

namespace Amanzi {
namespace Energy {

EnthalpyEvaluator::EnthalpyEvaluator(Teuchos::ParameterList& plist) :
    SecondaryVariableFieldEvaluator(plist) {
  if (my_key_.empty()) {

    my_key_ = plist_.get<std::string>("enthalpy key", "surface-enthalpy_liquid");
  }

  // Set up my dependencies.
  std::string domain_name = Keys::getDomain(my_key_);
  include_work_ = plist_.get<bool>("include work term", true);

  // -- pressure
  if (include_work_) {
    pres_key_ = Keys::readKey(plist_, domain_name, "pressure", "pressure");
    dependencies_.insert(pres_key_);

    dens_key_ = Keys::readKey(plist_, domain_name, "molar density liquid", "molar_density_liquid");
    dependencies_.insert(dens_key_);
  }

  ie_key_ = Keys::readKey(plist_, domain_name, "internal energy liquid", "internal_energy_liquid");
  dependencies_.insert(ie_key_);

};

EnthalpyEvaluator::EnthalpyEvaluator(const EnthalpyEvaluator& other) :
    SecondaryVariableFieldEvaluator(other),
    pres_key_(other.pres_key_),
    dens_key_(other.dens_key_),
    ie_key_(other.ie_key_),
    include_work_(other.include_work_) {};

Teuchos::RCP<FieldEvaluator>
EnthalpyEvaluator::Clone() const {
  return Teuchos::rcp(new EnthalpyEvaluator(*this));
};

void EnthalpyEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
        const Teuchos::Ptr<CompositeVector>& result) {
  Teuchos::OSTab tab = vo_->getOSTab();
  Teuchos::RCP<const CompositeVector> u_l = S->GetFieldData(ie_key_);
  *result = *u_l;

  if (include_work_) {
    Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] += 1.e-6*pres_v[0][i]/nl_v[0][i];
      }
    }
  }
};

void EnthalpyEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
        Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
  // not implemented
  if (wrt_key == ie_key_) {
    result->PutScalar(1.);
  } else if (wrt_key ==pres_key_) {
    AMANZI_ASSERT(include_work_);

    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] = 1.e-6/nl_v[0][i];
      }
    }

  } else if (wrt_key ==dens_key_) {
    AMANZI_ASSERT(include_work_);

    Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] = -1.e-6*pres_v[0][i]/std::pow(nl_v[0][i], 2);
      }
    }
  }
};

} //namespace
} //namespace
<commit_msg>makes include work term default to no in enthalpy evaluators -- it is not useful in standard ATS simulations, and does wierd things in frozen conditions<commit_after>/* -*-  mode: c++; indent-tabs-mode: nil -*- */

/* -----------------------------------------------------------------------------
ATS

Authors: Ethan Coon (ecoon@lanl.gov)

FieldEvaluator for enthalpy.
----------------------------------------------------------------------------- */

#include "enthalpy_evaluator.hh"

namespace Amanzi {
namespace Energy {

EnthalpyEvaluator::EnthalpyEvaluator(Teuchos::ParameterList& plist) :
    SecondaryVariableFieldEvaluator(plist) {
  if (my_key_.empty()) {

    my_key_ = plist_.get<std::string>("enthalpy key", "surface-enthalpy_liquid");
  }

  // Set up my dependencies.
  std::string domain_name = Keys::getDomain(my_key_);
  include_work_ = plist_.get<bool>("include work term", false);

  // -- pressure
  if (include_work_) {
    pres_key_ = Keys::readKey(plist_, domain_name, "pressure", "pressure");
    dependencies_.insert(pres_key_);

    dens_key_ = Keys::readKey(plist_, domain_name, "molar density liquid", "molar_density_liquid");
    dependencies_.insert(dens_key_);
  }

  ie_key_ = Keys::readKey(plist_, domain_name, "internal energy liquid", "internal_energy_liquid");
  dependencies_.insert(ie_key_);

};

EnthalpyEvaluator::EnthalpyEvaluator(const EnthalpyEvaluator& other) :
    SecondaryVariableFieldEvaluator(other),
    pres_key_(other.pres_key_),
    dens_key_(other.dens_key_),
    ie_key_(other.ie_key_),
    include_work_(other.include_work_) {};

Teuchos::RCP<FieldEvaluator>
EnthalpyEvaluator::Clone() const {
  return Teuchos::rcp(new EnthalpyEvaluator(*this));
};

void EnthalpyEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
        const Teuchos::Ptr<CompositeVector>& result) {
  Teuchos::OSTab tab = vo_->getOSTab();
  Teuchos::RCP<const CompositeVector> u_l = S->GetFieldData(ie_key_);
  *result = *u_l;

  if (include_work_) {
    Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] += 1.e-6*pres_v[0][i]/nl_v[0][i];
      }
    }
  }
};

void EnthalpyEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
        Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
  // not implemented
  if (wrt_key == ie_key_) {
    result->PutScalar(1.);
  } else if (wrt_key ==pres_key_) {
    AMANZI_ASSERT(include_work_);

    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] = 1.e-6/nl_v[0][i];
      }
    }

  } else if (wrt_key ==dens_key_) {
    AMANZI_ASSERT(include_work_);

    Teuchos::RCP<const CompositeVector> pres = S->GetFieldData(pres_key_);
    Teuchos::RCP<const CompositeVector> n_l = S->GetFieldData(dens_key_);

    for (CompositeVector::name_iterator comp=result->begin();
         comp!=result->end(); ++comp) {
      const Epetra_MultiVector& nl_v = *n_l->ViewComponent(*comp,false);
      const Epetra_MultiVector& pres_v = *pres->ViewComponent(*comp,false);
      Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);

      int ncomp = result->size(*comp, false);
      for (int i=0; i!=ncomp; ++i) {
        // 1.e-6 converts to MJoules
        result_v[0][i] = -1.e-6*pres_v[0][i]/std::pow(nl_v[0][i], 2);
      }
    }
  }
};

} //namespace
} //namespace
<|endoftext|>


<commit_before>#include "WordModifier.h"

WordModifier::WordModifier()
{
    //ctor
}
<commit_msg>Update WordModifier.cpp<commit_after>#include "WordModifier.h"

#include <string>

WordModifier::WordModifier(std::string form)
: form(form)
{
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "stateseditorview.h"
#include "stateseditormodel.h"
#include <customnotifications.h>

#include <QPainter>
#include <QTimerEvent>
#include <QDebug>

enum {
    debug = false
};

namespace QmlDesigner {
namespace Internal {

/**
  We always have 'one' current state, where we get updates from (see sceneChanged()). In case
  the current state is the base state, we render the base state + all other states.
  */
StatesEditorView::StatesEditorView(StatesEditorModel *editorModel, QObject *parent) :
        QmlModelView(parent),
        m_editorModel(editorModel)
{
    Q_ASSERT(m_editorModel);

    connect(nodeInstanceView(), SIGNAL(instanceRemoved(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(transformPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(parentPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(otherPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(updateItem(NodeInstance)), this, SLOT(sceneChanged()));
}

void StatesEditorView::setCurrentStateSilent(int index)
{
    // TODO
    QmlModelState state(m_modelStates.at(index));
    if (!state.isValid())
        return;
    if (state == currentState())
        return;
    QmlModelView::stateChanged(state, currentState());
}

void StatesEditorView::setCurrentState(int index)
{
    // TODO
    if (m_modelStates.indexOf(currentState()) == index)
        return;

    if (index >= m_modelStates.count())
        return;

    QmlModelState state(m_modelStates.at(index));
    Q_ASSERT(state.isValid());
    QmlModelView::setCurrentState(state);
}

void StatesEditorView::setBackCurrentState(int index, const QmlModelState &oldState)
{
    // TODO
    QmlModelState state(m_modelStates.at(index));
    if (!state.isValid())
        return;
    if (state == oldState)
        return;
    QmlModelView::stateChanged(oldState, state);
}

void StatesEditorView::createState(const QString &name)
{
    stateRootNode().states().addState(name);
}

void StatesEditorView::removeState(int index)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    m_modelStates.removeAll(state);
    m_editorModel->removeState(index);
    QmlModelView::setCurrentState(baseState());
    state.destroy();
}

void StatesEditorView::renameState(int index,const QString &newName)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    if (state.name() != newName) {
        // Jump to base state for the change
        QmlModelState oldState = currentState();
        setCurrentStateSilent(0);
        state.setName(newName);
        setBackCurrentState(0, oldState);
    }
}

void StatesEditorView::duplicateCurrentState(int index)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    QString newName = state.name();

    // Strip out numbers at the end of the string
    QRegExp regEx(QString("[0-9]+$"));
    int numberIndex = newName.indexOf(regEx);
    if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
        newName = newName.left(numberIndex);

    int i = 1;
    QStringList stateNames = state.stateGroup().names();
    while (stateNames.contains(newName + QString::number(i)))
        i++;
    state.duplicate(newName + QString::number(i));
}

void StatesEditorView::modelAttached(Model *model)
{
    if (model == QmlModelView::model())
        return;

    Q_ASSERT(model);
    QmlModelView::modelAttached(model);
    Q_ASSERT(m_editorModel->rowCount(QModelIndex()) == 0);

    // find top level states
    m_stateRootNode = QmlItemNode(rootModelNode());
    if (!m_stateRootNode.isValid())
        return;

    clearModelStates();

    // Add base state
    m_modelStates.insert(0, baseState());
    m_editorModel->insertState(0, baseState().name());

    // Add custom states
    for (int i = 0; i < m_stateRootNode.states().allStates().size(); ++i) {
        QmlModelState state = QmlItemNode(rootModelNode()).states().allStates().at(i);
        insertModelState(i, state);
    }
}

void StatesEditorView::modelAboutToBeDetached(Model *model)
{
    if (debug)
        qDebug() << __FUNCTION__;

    clearModelStates();

    QmlModelView::modelAboutToBeDetached(model);
}

void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
    foreach (const AbstractProperty &property, propertyList) {
        // remove all states except base state
        if ((property.name()=="states") && (property.parentModelNode().isRootNode())) {
            foreach (const QmlModelState &state, m_modelStates) {
                if (!state.isBaseState())
                    removeModelState(state);
            }
        } else {
            ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
            if (QmlModelState(node).isValid()) {
                startUpdateTimer(modelStateIndex(node) + 1, 0);
            }
        }
    }
}

void StatesEditorView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
    QmlModelView::propertiesRemoved(propertyList);
}

void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
    QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
    foreach (const VariantProperty &property, propertyList) {
        ModelNode node (property.parentModelNode());
        if (QmlModelState(node).isValid() && (property.name() == QLatin1String("name"))) {
            int index = m_modelStates.indexOf(node);
            if (index != -1)
                m_editorModel->renameState(index, property.value().toString());
        }
    }
    foreach (const AbstractProperty &property, propertyList) {
        ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
        if (QmlModelState(node).isValid()) {
            startUpdateTimer(modelStateIndex(node) + 1, 0);
        } else { //a change to the base state update all
            for (int i = 0; i < m_modelStates.count(); ++i)
                startUpdateTimer(i, 0);
        }
    }
}

void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
    if (removedNode.parentProperty().parentModelNode() == m_stateRootNode
          && QmlModelState(removedNode).isValid()) {
        removeModelState(removedNode);
    }
    QmlModelView::nodeAboutToBeRemoved(removedNode);
}

void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
    QmlModelView::nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);

    // this would be sliding
    Q_ASSERT(newPropertyParent != oldPropertyParent);

    if (QmlModelState(node).isValid()) {
        if (oldPropertyParent.parentModelNode() == m_stateRootNode) {
            if (oldPropertyParent.isNodeListProperty()
                && oldPropertyParent.name() == "states") {
                removeModelState(node);
            } else {
                qWarning() << "States Editor: Reparented model state was not in states property list";
            }
        }

        if (newPropertyParent.parentModelNode() == m_stateRootNode) {
            if (newPropertyParent.isNodeListProperty()
                && newPropertyParent.name() == "states") {
                NodeListProperty statesProperty = newPropertyParent.toNodeListProperty();
                int index = statesProperty.toModelNodeList().indexOf(node);
                Q_ASSERT(index >= 0);
                insertModelState(index, node);
            } else {
                qWarning() << "States Editor: Reparented model state is not in the states property list";
            }
        }
    }
}

void StatesEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int newIndex, int oldIndex)
{
    QmlModelView::nodeSlidedToIndex(listProperty, newIndex, oldIndex);
    if (listProperty.parentModelNode() == m_stateRootNode
        && listProperty.name() == "states") {
        int index = newIndex;
        if (oldIndex < newIndex)
            --index;
        QmlModelState state = listProperty.toModelNodeList().at(index);
        if (state.isValid()) {
            Q_ASSERT(oldIndex == modelStateIndex(state));
            removeModelState(state);
            insertModelState(newIndex, state);
            Q_ASSERT(newIndex == modelStateIndex(state));
        }
    }
}

void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
    QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);

    if (newQmlModelState.isBaseState())
        m_editorModel->emitChangedToState(0);
    else
        m_editorModel->emitChangedToState(m_modelStates.indexOf(newQmlModelState));
}

void StatesEditorView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
    QmlModelView::customNotification(view, identifier, nodeList, data);
    if (identifier == StartRewriterAmend) {
        m_oldRewriterAmendState = currentState();
        QmlModelView::setCurrentState(baseState());
    } else if (identifier == EndRewriterAmend) {
        if (m_oldRewriterAmendState.isValid())
            QmlModelView::setCurrentState(m_oldRewriterAmendState);
    }
}

QPixmap StatesEditorView::renderState(int i)
{
    Q_ASSERT(i >= 0 && i < m_modelStates.size());
    nodeInstanceView()->setBlockChangeSignal(true);
    QmlModelState oldState = currentState();
    setCurrentStateSilent(i);

    Q_ASSERT(nodeInstanceView());

    const int checkerbordSize= 10;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    QSize pixmapSize(nodeInstanceView()->sceneRect().size().toSize());
    if (pixmapSize.width() > 150 || pixmapSize.height() > 150) // sensible maximum size
        pixmapSize.scale(QSize(150, 150), Qt::KeepAspectRatio);
    QPixmap pixmap(pixmapSize);

    QPainter painter(&pixmap);
    painter.drawTiledPixmap(pixmap.rect(), tilePixmap);
    nodeInstanceView()->render(&painter, pixmap.rect(), nodeInstanceView()->sceneRect());

    setBackCurrentState(i, oldState);
    nodeInstanceView()->setBlockChangeSignal(false);
    Q_ASSERT(oldState == currentState());

    return pixmap;
}

void StatesEditorView::sceneChanged()
{
    // If we are in base state we have to update the pixmaps of all states
    // otherwise only the pixmpap for the current state

    if (currentState().isValid()) { //during setup we might get sceneChanged signals with an invalid currentState()
        if (currentState().isBaseState()) {
            for (int i = 0; i < m_modelStates.count(); ++i)
                startUpdateTimer(i, i * 80);
        } else {
            startUpdateTimer(modelStateIndex(currentState()) + 1, 0);
        }
    }
}

void StatesEditorView::startUpdateTimer(int i, int offset) {
    if (i < m_updateTimerIdList.size() && m_updateTimerIdList.at(i) != 0)
        return;
    // TODO: Add an offset so not all states are rendered at once
    Q_ASSERT(i >= 0 && i < m_modelStates.count());
    if (i < m_updateTimerIdList.size() && i > 0)
        if (m_updateTimerIdList.at(i))
            killTimer(m_updateTimerIdList.at(i));
    int j = i;

    while (m_updateTimerIdList.size() <= i) {
        m_updateTimerIdList.insert(j, 0);
        j++;
    }
    m_updateTimerIdList[i] =  startTimer(100 + offset);
}

// index without base state
void StatesEditorView::insertModelState(int i, const QmlModelState &state)
{
    Q_ASSERT(state.isValid());
    Q_ASSERT(!state.isBaseState());
    // For m_modelStates / m_editorModel, i=0 is base state
    m_modelStates.insert(i+1, state);
    m_editorModel->insertState(i+1, state.name());
}

void StatesEditorView::removeModelState(const QmlModelState &state)
{
    Q_ASSERT(state.isValid());
    Q_ASSERT(!state.isBaseState());
    int index = m_modelStates.indexOf(state);
    if (index != -1) {
        m_modelStates.removeOne(state);

        if (m_updateTimerIdList.contains(index)) {
            killTimer(m_updateTimerIdList[index]);
            m_updateTimerIdList[index] = 0;
        }
        m_editorModel->removeState(index);
    }
}

void StatesEditorView::clearModelStates()
{
    // For m_modelStates / m_editorModel, i=0 is base state
    while (m_modelStates.size()) {
        m_modelStates.removeFirst();
        m_editorModel->removeState(0);
    }
}

// index without base state
int StatesEditorView::modelStateIndex(const QmlModelState &state)
{
    return m_modelStates.indexOf(state) - 1;
}

void StatesEditorView::timerEvent(QTimerEvent *event)
{
    int index = m_updateTimerIdList.indexOf(event->timerId());
    if (index > -1) {
        event->accept();
        Q_ASSERT(index >= 0);
        if (index < m_modelStates.count()) //there might be updates for a state already deleted 100ms are long
            m_editorModel->updateState(index);
        killTimer(m_updateTimerIdList[index]);
       m_updateTimerIdList[index] = 0;
    } else {
        QmlModelView::timerEvent(event);
    }
}

} // namespace Internal
} // namespace QmlDesigner
<commit_msg>QmlDesigner.statesEditor:  updating of thumbnails when propertiesAboutToBeRemoved<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "stateseditorview.h"
#include "stateseditormodel.h"
#include <customnotifications.h>

#include <QPainter>
#include <QTimerEvent>
#include <QDebug>

enum {
    debug = false
};

namespace QmlDesigner {
namespace Internal {

/**
  We always have 'one' current state, where we get updates from (see sceneChanged()). In case
  the current state is the base state, we render the base state + all other states.
  */
StatesEditorView::StatesEditorView(StatesEditorModel *editorModel, QObject *parent) :
        QmlModelView(parent),
        m_editorModel(editorModel)
{
    Q_ASSERT(m_editorModel);

    connect(nodeInstanceView(), SIGNAL(instanceRemoved(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(transformPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(parentPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(otherPropertyChanged(NodeInstance)), this, SLOT(sceneChanged()));
    connect(nodeInstanceView(), SIGNAL(updateItem(NodeInstance)), this, SLOT(sceneChanged()));
}

void StatesEditorView::setCurrentStateSilent(int index)
{
    // TODO
    QmlModelState state(m_modelStates.at(index));
    if (!state.isValid())
        return;
    if (state == currentState())
        return;
    QmlModelView::stateChanged(state, currentState());
}

void StatesEditorView::setCurrentState(int index)
{
    // TODO
    if (m_modelStates.indexOf(currentState()) == index)
        return;

    if (index >= m_modelStates.count())
        return;

    QmlModelState state(m_modelStates.at(index));
    Q_ASSERT(state.isValid());
    QmlModelView::setCurrentState(state);
}

void StatesEditorView::setBackCurrentState(int index, const QmlModelState &oldState)
{
    // TODO
    QmlModelState state(m_modelStates.at(index));
    if (!state.isValid())
        return;
    if (state == oldState)
        return;
    QmlModelView::stateChanged(oldState, state);
}

void StatesEditorView::createState(const QString &name)
{
    stateRootNode().states().addState(name);
}

void StatesEditorView::removeState(int index)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    m_modelStates.removeAll(state);
    m_editorModel->removeState(index);
    QmlModelView::setCurrentState(baseState());
    state.destroy();
}

void StatesEditorView::renameState(int index,const QString &newName)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    if (state.name() != newName) {
        // Jump to base state for the change
        QmlModelState oldState = currentState();
        setCurrentStateSilent(0);
        state.setName(newName);
        setBackCurrentState(0, oldState);
    }
}

void StatesEditorView::duplicateCurrentState(int index)
{
    Q_ASSERT(index > 0 && index < m_modelStates.size());
    QmlModelState state = m_modelStates.at(index);
    Q_ASSERT(state.isValid());
    QString newName = state.name();

    // Strip out numbers at the end of the string
    QRegExp regEx(QString("[0-9]+$"));
    int numberIndex = newName.indexOf(regEx);
    if ((numberIndex != -1) && (numberIndex+regEx.matchedLength()==newName.length()))
        newName = newName.left(numberIndex);

    int i = 1;
    QStringList stateNames = state.stateGroup().names();
    while (stateNames.contains(newName + QString::number(i)))
        i++;
    state.duplicate(newName + QString::number(i));
}

void StatesEditorView::modelAttached(Model *model)
{
    if (model == QmlModelView::model())
        return;

    Q_ASSERT(model);
    QmlModelView::modelAttached(model);
    Q_ASSERT(m_editorModel->rowCount(QModelIndex()) == 0);

    // find top level states
    m_stateRootNode = QmlItemNode(rootModelNode());
    if (!m_stateRootNode.isValid())
        return;

    clearModelStates();

    // Add base state
    m_modelStates.insert(0, baseState());
    m_editorModel->insertState(0, baseState().name());

    // Add custom states
    for (int i = 0; i < m_stateRootNode.states().allStates().size(); ++i) {
        QmlModelState state = QmlItemNode(rootModelNode()).states().allStates().at(i);
        insertModelState(i, state);
    }
}

void StatesEditorView::modelAboutToBeDetached(Model *model)
{
    if (debug)
        qDebug() << __FUNCTION__;

    clearModelStates();

    QmlModelView::modelAboutToBeDetached(model);
}

void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
    QmlModelView::propertiesAboutToBeRemoved(propertyList);
    foreach (const AbstractProperty &property, propertyList) {
        // remove all states except base state
        if ((property.name()=="states") && (property.parentModelNode().isRootNode())) {
            foreach (const QmlModelState &state, m_modelStates) {
                if (!state.isBaseState())
                    removeModelState(state);
            }
        } else {
            ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
            if (QmlModelState(node).isValid()) {
                startUpdateTimer(modelStateIndex(node) + 1, 0);
            } else { //a change to the base state update all
                for (int i = 0; i < m_modelStates.count(); ++i)
                    startUpdateTimer(i, 0);
            }
        }
    }
}

void StatesEditorView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
{
    QmlModelView::propertiesRemoved(propertyList);
}

void StatesEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
    QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
    foreach (const VariantProperty &property, propertyList) {
        ModelNode node (property.parentModelNode());
        if (QmlModelState(node).isValid() && (property.name() == QLatin1String("name"))) {
            int index = m_modelStates.indexOf(node);
            if (index != -1)
                m_editorModel->renameState(index, property.value().toString());
        }
    }
    foreach (const AbstractProperty &property, propertyList) {
        ModelNode node (property.parentModelNode().parentProperty().parentModelNode());
        if (QmlModelState(node).isValid()) {
            startUpdateTimer(modelStateIndex(node) + 1, 0);
        } else { //a change to the base state update all
            for (int i = 0; i < m_modelStates.count(); ++i)
                startUpdateTimer(i, 0);
        }
    }
}

void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
    if (removedNode.parentProperty().parentModelNode() == m_stateRootNode
          && QmlModelState(removedNode).isValid()) {
        removeModelState(removedNode);
    }
    QmlModelView::nodeAboutToBeRemoved(removedNode);
}

void StatesEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
{
    QmlModelView::nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);

    // this would be sliding
    Q_ASSERT(newPropertyParent != oldPropertyParent);

    if (QmlModelState(node).isValid()) {
        if (oldPropertyParent.parentModelNode() == m_stateRootNode) {
            if (oldPropertyParent.isNodeListProperty()
                && oldPropertyParent.name() == "states") {
                removeModelState(node);
            } else {
                qWarning() << "States Editor: Reparented model state was not in states property list";
            }
        }

        if (newPropertyParent.parentModelNode() == m_stateRootNode) {
            if (newPropertyParent.isNodeListProperty()
                && newPropertyParent.name() == "states") {
                NodeListProperty statesProperty = newPropertyParent.toNodeListProperty();
                int index = statesProperty.toModelNodeList().indexOf(node);
                Q_ASSERT(index >= 0);
                insertModelState(index, node);
            } else {
                qWarning() << "States Editor: Reparented model state is not in the states property list";
            }
        }
    }
}

void StatesEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int newIndex, int oldIndex)
{
    QmlModelView::nodeSlidedToIndex(listProperty, newIndex, oldIndex);
    if (listProperty.parentModelNode() == m_stateRootNode
        && listProperty.name() == "states") {
        int index = newIndex;
        if (oldIndex < newIndex)
            --index;
        QmlModelState state = listProperty.toModelNodeList().at(index);
        if (state.isValid()) {
            Q_ASSERT(oldIndex == modelStateIndex(state));
            removeModelState(state);
            insertModelState(newIndex, state);
            Q_ASSERT(newIndex == modelStateIndex(state));
        }
    }
}

void StatesEditorView::stateChanged(const QmlModelState &newQmlModelState, const QmlModelState &oldQmlModelState)
{
    QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);

    if (newQmlModelState.isBaseState())
        m_editorModel->emitChangedToState(0);
    else
        m_editorModel->emitChangedToState(m_modelStates.indexOf(newQmlModelState));
}

void StatesEditorView::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
    QmlModelView::customNotification(view, identifier, nodeList, data);
    if (identifier == StartRewriterAmend) {
        m_oldRewriterAmendState = currentState();
        QmlModelView::setCurrentState(baseState());
    } else if (identifier == EndRewriterAmend) {
        if (m_oldRewriterAmendState.isValid())
            QmlModelView::setCurrentState(m_oldRewriterAmendState);
    }
}

QPixmap StatesEditorView::renderState(int i)
{
    Q_ASSERT(i >= 0 && i < m_modelStates.size());
    nodeInstanceView()->setBlockChangeSignal(true);
    QmlModelState oldState = currentState();
    setCurrentStateSilent(i);

    Q_ASSERT(nodeInstanceView());

    const int checkerbordSize= 10;
    QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
    tilePixmap.fill(Qt::white);
    QPainter tilePainter(&tilePixmap);
    QColor color(220, 220, 220);
    tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
    tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
    tilePainter.end();

    QSize pixmapSize(nodeInstanceView()->sceneRect().size().toSize());
    if (pixmapSize.width() > 150 || pixmapSize.height() > 150) // sensible maximum size
        pixmapSize.scale(QSize(150, 150), Qt::KeepAspectRatio);
    QPixmap pixmap(pixmapSize);

    QPainter painter(&pixmap);
    painter.drawTiledPixmap(pixmap.rect(), tilePixmap);
    nodeInstanceView()->render(&painter, pixmap.rect(), nodeInstanceView()->sceneRect());

    setBackCurrentState(i, oldState);
    nodeInstanceView()->setBlockChangeSignal(false);
    Q_ASSERT(oldState == currentState());

    return pixmap;
}

void StatesEditorView::sceneChanged()
{
    // If we are in base state we have to update the pixmaps of all states
    // otherwise only the pixmpap for the current state

    if (currentState().isValid()) { //during setup we might get sceneChanged signals with an invalid currentState()
        if (currentState().isBaseState()) {
            for (int i = 0; i < m_modelStates.count(); ++i)
                startUpdateTimer(i, i * 80);
        } else {
            startUpdateTimer(modelStateIndex(currentState()) + 1, 0);
        }
    }
}

void StatesEditorView::startUpdateTimer(int i, int offset) {
    if (i < m_updateTimerIdList.size() && m_updateTimerIdList.at(i) != 0)
        return;
    // TODO: Add an offset so not all states are rendered at once
    Q_ASSERT(i >= 0 && i < m_modelStates.count());
    if (i < m_updateTimerIdList.size() && i > 0)
        if (m_updateTimerIdList.at(i))
            killTimer(m_updateTimerIdList.at(i));
    int j = i;

    while (m_updateTimerIdList.size() <= i) {
        m_updateTimerIdList.insert(j, 0);
        j++;
    }
    m_updateTimerIdList[i] =  startTimer(100 + offset);
}

// index without base state
void StatesEditorView::insertModelState(int i, const QmlModelState &state)
{
    Q_ASSERT(state.isValid());
    Q_ASSERT(!state.isBaseState());
    // For m_modelStates / m_editorModel, i=0 is base state
    m_modelStates.insert(i+1, state);
    m_editorModel->insertState(i+1, state.name());
}

void StatesEditorView::removeModelState(const QmlModelState &state)
{
    Q_ASSERT(state.isValid());
    Q_ASSERT(!state.isBaseState());
    int index = m_modelStates.indexOf(state);
    if (index != -1) {
        m_modelStates.removeOne(state);

        if (m_updateTimerIdList.contains(index)) {
            killTimer(m_updateTimerIdList[index]);
            m_updateTimerIdList[index] = 0;
        }
        m_editorModel->removeState(index);
    }
}

void StatesEditorView::clearModelStates()
{
    // For m_modelStates / m_editorModel, i=0 is base state
    while (m_modelStates.size()) {
        m_modelStates.removeFirst();
        m_editorModel->removeState(0);
    }
}

// index without base state
int StatesEditorView::modelStateIndex(const QmlModelState &state)
{
    return m_modelStates.indexOf(state) - 1;
}

void StatesEditorView::timerEvent(QTimerEvent *event)
{
    int index = m_updateTimerIdList.indexOf(event->timerId());
    if (index > -1) {
        event->accept();
        Q_ASSERT(index >= 0);
        if (index < m_modelStates.count()) //there might be updates for a state already deleted 100ms are long
            m_editorModel->updateState(index);
        killTimer(m_updateTimerIdList[index]);
       m_updateTimerIdList[index] = 0;
    } else {
        QmlModelView::timerEvent(event);
    }
}

} // namespace Internal
} // namespace QmlDesigner
<|endoftext|>