<commit_before>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::cout << "Number of threads: " << numThreads << std::endl;
    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        std::cout << "Initialized the 3d vectors" << std::endl;

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;

        //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
        unsigned long long int lociPerThread;
        if (numLoci == 0) {
            lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
        } else {
            lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
        }

        std::cout << "Initialized lociPerThread with " << numLoci << std::endl;

        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
            unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
            unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
            std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;

            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
        }

        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
            std::cout << "Joined thread " << i << std::endl;
        }
        std::cout << "All threads completed running" << std::endl;

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
        std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));

        for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
            for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                for (int threadVector = 0; threadVector < numThreads; threadVector++) {
                    weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
                    pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
                }
            }
        }

        std::cout << "Finished summing the threads vectors" << std::endl;

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::fixed;
                        std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::scientific;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
         if (locus % 100000 == 0) {
             std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
         }

         unsigned long long coverages[numIndividuals];
         long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

         for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
             unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
             unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

             coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
             if ( coverages[tortoise] > 0 ) {
                 //std::cout << "Made it to line 222 for locus " << locus << std::endl;
                 majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

                 if (coverages[tortoise] > 1) {
                     unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1));
                     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads

                     //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0);
                     threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise]));

                     //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1)
                 }

                 for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
                     if (coverages[comparisonTortoise] > 0) {
                         long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
                         threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));
                    }
                }
            }
        }
        delete[] majorAlleleFreqs; // Needed to avoid memory leaks
    }
    std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
    return 0;
}

<commit_msg>Minor changes<commit_after>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::cout << "Number of threads: " << numThreads << std::endl;
    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        std::cout << "Initialized the 3d vectors" << std::endl;

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;

        //unsigned long long int lociPerThread = (readCounts.size()-1)/numThreads; // loci starts with 0, so need to subtract 1 from numLoci
        unsigned long long int lociPerThread;
        if (numLoci == 0) {
            lociPerThread = (unsigned long long)(size/(numIndividuals*2))/(unsigned long long)numThreads;
        } else {
            lociPerThread = (unsigned long long)numLoci/(unsigned long long)numThreads;
        }

        std::cout << "Initialized lociPerThread with " << numLoci << std::endl;

        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            std::cout << "Got to the function call. Running thread # " << threadRunning << std::endl;
            unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
            unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
            std::cout << "Set firstLocus to " << firstLocus << " and finishingLocus to " << finishingLocus << std::endl;

            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
        }

        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
            std::cout << "Joined thread " << i << std::endl;
        }
        std::cout << "All threads completed running" << std::endl;

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));
        std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));

        for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
            for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                for (int threadVector = 0; threadVector < numThreads; threadVector++) {
                    weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
                    pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];
                }
            }
        }

        std::cout << "Finished summing the threads vectors" << std::endl;

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::fixed;
                        std::cout << "Weightings for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << weightingsSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << "PWP for tortoise " << tortoise << " and comparisonTortoise " << comparisonTortoise << " : " << pwpSum[tortoise][comparisonTortoise] << std::endl;
                        std::cout << std::scientific;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
         if (locus % 100000 == 0) {
             std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
         }

         unsigned long long coverages[numIndividuals];
         long double *majorAlleleFreqs = new long double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

         for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
             unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
             unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

             coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
             if ( coverages[tortoise] > 0 ) {
                 //std::cout << "Made it to line 222 for locus " << locus << std::endl;
                 majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] / (long double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

                 if (coverages[tortoise] > 1) {
                     unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1));
                     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads

                     //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise])-(long double)1.0);

                     //Cancel out the "coverages[tortoise]-1"
                     threadPWP[tortoise][tortoise] += (long double)(coverages[tortoise]) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])));
                     //threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) / (long double)((coverages[tortoise]));

                     //threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) / (coverages[tortoise]-1)
                 }

                 for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
                     if (coverages[comparisonTortoise] > 0) {
                         long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;

                         threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));
                    }
                }
            }
        }
        delete[] majorAlleleFreqs; // Needed to avoid memory leaks
    }
    std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
    return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "base/mac/libdispatch_task_runner.h"

#include "base/bind.h"
#include "base/mac/bind_objc_block.h"
#include "base/message_loop.h"
#include "base/stringprintf.h"
#include "testing/gtest/include/gtest/gtest.h"

class LibDispatchTaskRunnerTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    task_runner_ = new base::mac::LibDispatchTaskRunner(
        "org.chromium.LibDispatchTaskRunnerTest");
  }

  // DispatchLastTask is used to run the main test thread's MessageLoop until
  // all non-delayed tasks are run on the LibDispatchTaskRunner.
  void DispatchLastTask() {
    dispatch_async(task_runner_->GetDispatchQueue(), ^{
        (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure());
    });
    message_loop_.Run();
  }

  // VerifyTaskOrder takes the expectations from TaskOrderMarkers and compares
  // them against the recorded values.
  void VerifyTaskOrder(const char* const expectations[],
                       size_t num_expectations) {
    size_t actual_size = task_order_.size();

    for (size_t i = 0; i < num_expectations; ++i) {
      if (i >= actual_size) {
        EXPECT_LT(i, actual_size) << "Expected " << expectations[i];
        continue;
      }

      EXPECT_EQ(expectations[i], task_order_[i]);
    }

    if (actual_size > num_expectations) {
      EXPECT_LE(actual_size, num_expectations) << "Extra tasks were run:";
      for (size_t i = num_expectations; i < actual_size; ++i) {
        EXPECT_EQ("<none>", task_order_[i]) << " (i=" << i << ")";
      }
    }
  }

  // The message loop for the test main thread.
  MessageLoop message_loop_;

  // The task runner under test.
  scoped_refptr<base::mac::LibDispatchTaskRunner> task_runner_;

  // Vector that records data from TaskOrderMarker.
  std::vector<std::string> task_order_;
};

// Scoper that records the beginning and end of a running task.
class TaskOrderMarker {
 public:
  TaskOrderMarker(LibDispatchTaskRunnerTest* test, const std::string& name)
      : test_(test),
        name_(name) {
    test->task_order_.push_back(std::string("BEGIN ") + name);
  }
  ~TaskOrderMarker() {
    test_->task_order_.push_back(std::string("END ") + name_);
  }

 private:
  LibDispatchTaskRunnerTest* test_;
  std::string name_;
};

void RecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) {
  TaskOrderMarker marker(test, name);
}

// Returns a closure that records the task order.
base::Closure BoundRecordTaskOrder(LibDispatchTaskRunnerTest* test,
                                   const std::string& name) {
  return base::Bind(&RecordTaskOrder, base::Unretained(test), name);
}

TEST_F(LibDispatchTaskRunnerTest, PostTask) {
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Basic Task"));
  DispatchLastTask();
  const char* const expectations[] = {
    "BEGIN Basic Task",
    "END Basic Task"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, PostTaskWithinTask) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "Outer");
      task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Inner"));
  }));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN Outer",
    "END Outer",
    "BEGIN Inner",
    "END Inner"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, NoMessageLoop) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this,
          base::StringPrintf("MessageLoop = %p", MessageLoop::current()));
  }));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN MessageLoop = 0x0",
    "END MessageLoop = 0x0"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, DispatchAndPostTasks) {
  dispatch_async(task_runner_->GetDispatchQueue(), ^{
      TaskOrderMarker marker(this, "First Block");
      task_runner_->PostTask(FROM_HERE,
          BoundRecordTaskOrder(this, "Second Task"));
  });
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First Task"));
  dispatch_async(task_runner_->GetDispatchQueue(), ^{
      TaskOrderMarker marker(this, "Second Block");
  });
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN First Block",
    "END First Block",
    "BEGIN First Task",
    "END First Task",
    "BEGIN Second Block",
    "END Second Block",
    "BEGIN Second Task",
    "END Second Task",
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, NonNestable) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "First");
      task_runner_->PostNonNestableTask(FROM_HERE, base::BindBlock(^{
          TaskOrderMarker marker(this, "Third NonNestable");
      }));
  }));
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second"));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN First",
    "END First",
    "BEGIN Second",
    "END Second",
    "BEGIN Third NonNestable",
    "END Third NonNestable"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, PostDelayed) {
  base::TimeTicks post_time;
  __block base::TimeTicks run_time;
  const base::TimeDelta delta = base::TimeDelta::FromMilliseconds(50);

  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First"));
  post_time = base::TimeTicks::Now();
  task_runner_->PostDelayedTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "Timed");
      run_time = base::TimeTicks::Now();
      (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }), delta);
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second"));
  message_loop_.Run();

  const char* const expectations[] = {
    "BEGIN First",
    "END First",
    "BEGIN Second",
    "END Second",
    "BEGIN Timed",
    "END Timed",
  };
  VerifyTaskOrder(expectations, arraysize(expectations));

  EXPECT_GE(run_time, post_time + delta);
}
<commit_msg>Mark LibDispatchTaskRunnerTest.DispatchAndPostTasks as flaky<commit_after>// Copyright (c) 2012 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 "base/mac/libdispatch_task_runner.h"

#include "base/bind.h"
#include "base/mac/bind_objc_block.h"
#include "base/message_loop.h"
#include "base/stringprintf.h"
#include "testing/gtest/include/gtest/gtest.h"

class LibDispatchTaskRunnerTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    task_runner_ = new base::mac::LibDispatchTaskRunner(
        "org.chromium.LibDispatchTaskRunnerTest");
  }

  // DispatchLastTask is used to run the main test thread's MessageLoop until
  // all non-delayed tasks are run on the LibDispatchTaskRunner.
  void DispatchLastTask() {
    dispatch_async(task_runner_->GetDispatchQueue(), ^{
        (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure());
    });
    message_loop_.Run();
  }

  // VerifyTaskOrder takes the expectations from TaskOrderMarkers and compares
  // them against the recorded values.
  void VerifyTaskOrder(const char* const expectations[],
                       size_t num_expectations) {
    size_t actual_size = task_order_.size();

    for (size_t i = 0; i < num_expectations; ++i) {
      if (i >= actual_size) {
        EXPECT_LT(i, actual_size) << "Expected " << expectations[i];
        continue;
      }

      EXPECT_EQ(expectations[i], task_order_[i]);
    }

    if (actual_size > num_expectations) {
      EXPECT_LE(actual_size, num_expectations) << "Extra tasks were run:";
      for (size_t i = num_expectations; i < actual_size; ++i) {
        EXPECT_EQ("<none>", task_order_[i]) << " (i=" << i << ")";
      }
    }
  }

  // The message loop for the test main thread.
  MessageLoop message_loop_;

  // The task runner under test.
  scoped_refptr<base::mac::LibDispatchTaskRunner> task_runner_;

  // Vector that records data from TaskOrderMarker.
  std::vector<std::string> task_order_;
};

// Scoper that records the beginning and end of a running task.
class TaskOrderMarker {
 public:
  TaskOrderMarker(LibDispatchTaskRunnerTest* test, const std::string& name)
      : test_(test),
        name_(name) {
    test->task_order_.push_back(std::string("BEGIN ") + name);
  }
  ~TaskOrderMarker() {
    test_->task_order_.push_back(std::string("END ") + name_);
  }

 private:
  LibDispatchTaskRunnerTest* test_;
  std::string name_;
};

void RecordTaskOrder(LibDispatchTaskRunnerTest* test, const std::string& name) {
  TaskOrderMarker marker(test, name);
}

// Returns a closure that records the task order.
base::Closure BoundRecordTaskOrder(LibDispatchTaskRunnerTest* test,
                                   const std::string& name) {
  return base::Bind(&RecordTaskOrder, base::Unretained(test), name);
}

TEST_F(LibDispatchTaskRunnerTest, PostTask) {
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Basic Task"));
  DispatchLastTask();
  const char* const expectations[] = {
    "BEGIN Basic Task",
    "END Basic Task"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, PostTaskWithinTask) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "Outer");
      task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Inner"));
  }));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN Outer",
    "END Outer",
    "BEGIN Inner",
    "END Inner"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, NoMessageLoop) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this,
          base::StringPrintf("MessageLoop = %p", MessageLoop::current()));
  }));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN MessageLoop = 0x0",
    "END MessageLoop = 0x0"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

// This test is flaky, see http://crbug.com/165117.
TEST_F(LibDispatchTaskRunnerTest, FLAKY_DispatchAndPostTasks) {
  dispatch_async(task_runner_->GetDispatchQueue(), ^{
      TaskOrderMarker marker(this, "First Block");
      task_runner_->PostTask(FROM_HERE,
          BoundRecordTaskOrder(this, "Second Task"));
  });
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First Task"));
  dispatch_async(task_runner_->GetDispatchQueue(), ^{
      TaskOrderMarker marker(this, "Second Block");
  });
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN First Block",
    "END First Block",
    "BEGIN First Task",
    "END First Task",
    "BEGIN Second Block",
    "END Second Block",
    "BEGIN Second Task",
    "END Second Task",
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, NonNestable) {
  task_runner_->PostTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "First");
      task_runner_->PostNonNestableTask(FROM_HERE, base::BindBlock(^{
          TaskOrderMarker marker(this, "Third NonNestable");
      }));
  }));
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second"));
  DispatchLastTask();

  const char* const expectations[] = {
    "BEGIN First",
    "END First",
    "BEGIN Second",
    "END Second",
    "BEGIN Third NonNestable",
    "END Third NonNestable"
  };
  VerifyTaskOrder(expectations, arraysize(expectations));
}

TEST_F(LibDispatchTaskRunnerTest, PostDelayed) {
  base::TimeTicks post_time;
  __block base::TimeTicks run_time;
  const base::TimeDelta delta = base::TimeDelta::FromMilliseconds(50);

  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "First"));
  post_time = base::TimeTicks::Now();
  task_runner_->PostDelayedTask(FROM_HERE, base::BindBlock(^{
      TaskOrderMarker marker(this, "Timed");
      run_time = base::TimeTicks::Now();
      (&message_loop_)->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  }), delta);
  task_runner_->PostTask(FROM_HERE, BoundRecordTaskOrder(this, "Second"));
  message_loop_.Run();

  const char* const expectations[] = {
    "BEGIN First",
    "END First",
    "BEGIN Second",
    "END Second",
    "BEGIN Timed",
    "END Timed",
  };
  VerifyTaskOrder(expectations, arraysize(expectations));

  EXPECT_GE(run_time, post_time + delta);
}
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2011 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygencairocontext.h"
#include "oxygencairoutils.h"
#include "oxygengtkutils.h"
#include "oxygenmetrics.h"
#include "oxygenrgba.h"
#include "oxygenshadowhelper.h"

#include <iostream>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <gdk/gdkx.h>
#include <X11/Xatom.h>

namespace Oxygen
{

    //______________________________________________
    ShadowHelper::ShadowHelper( void ):
        _size(0),
        _atom(0),
        _hooksInitialized( false )
    {}

    //______________________________________________
    ShadowHelper::~ShadowHelper( void )
    { reset(); }

    //______________________________________________
    void ShadowHelper::reset( void )
    {
        GdkScreen* screen = gdk_screen_get_default();
        Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );

        // round pixmaps
        for( PixmapList::const_iterator iter = _roundPixmaps.begin(); iter != _roundPixmaps.end(); ++iter )
        { XFreePixmap(display, *iter); }
        _roundPixmaps.clear();

        // square pixmaps
        for( PixmapList::const_iterator iter = _squarePixmaps.begin(); iter != _squarePixmaps.end(); ++iter )
        { XFreePixmap(display, *iter); }
        _squarePixmaps.clear();

    }

    //______________________________________________
    void ShadowHelper::initializeHooks( void )
    {
       if( _hooksInitialized ) return;

        // install hooks
        _realizeHook.connect( "realize", (GSignalEmissionHook)realizeHook, this );
        _hooksInitialized = true;

    }

    //______________________________________________
    void ShadowHelper::initialize( const ColorUtils::Rgba& color, const WindowShadow& shadow )
    {
        reset();
        _size = int(shadow.shadowSize()) - WindowShadow::Overlap;

        // round tiles
        WindowShadowKey key;
        key.hasTopBorder = true;
        key.hasBottomBorder = true;
        _roundTiles = shadow.tileSet( color, key );

        // square tiles
        key.hasTopBorder = false;
        key.hasBottomBorder = false;
        _squareTiles = shadow.tileSet( color, key );

        // re-install shadows for all windowId
        for( WidgetMap::const_iterator iter = _widgets.begin(); iter != _widgets.end(); ++iter )
        { installX11Shadows( iter->first ); }

    }

    //______________________________________________
    bool ShadowHelper::registerWidget( GtkWidget* widget )
    {

        // check widget
        if( !( widget && GTK_IS_WINDOW( widget ) ) ) return false;

        // make sure that widget is not already registered
        if( _widgets.find( widget ) != _widgets.end() ) return false;

        // check if window is accepted
        if( !acceptWindow( GTK_WINDOW( widget )  ) ) return false;

        // try install shadows
        installX11Shadows( widget );

        // register in map and returns success
        WidgetData data;
        data._destroyId.connect( G_OBJECT( widget ), "destroy", G_CALLBACK( destroyNotifyEvent ), this );
        _widgets.insert( std::make_pair( widget, data ) );

        return true;

    }

    //______________________________________________
    void ShadowHelper::unregisterWidget( GtkWidget* widget )
    {
        // find matching data in map
        WidgetMap::iterator iter( _widgets.find( widget ) );
        if( iter == _widgets.end() ) return;

        // disconnect
        iter->second._destroyId.disconnect();

        // remove from map
        _widgets.erase( iter );
    }

    //______________________________________________
    void ShadowHelper::createPixmapHandles( void )
    {

        // create atom
        if( !_atom )
        {
            GdkScreen* screen = gdk_screen_get_default();
            Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );
            _atom = XInternAtom( display, "_KDE_NET_WM_SHADOW", False);
        }

        // make sure size is valid
        if( _size <= 0 ) return;

        // make sure pixmaps are not already initialized
        if( _roundPixmaps.empty() )
        {

            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 1 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 2 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 5 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 8 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 7 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 6 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 3 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 0 ) ) );

        }

        if( _squarePixmaps.empty() )
        {

            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 1 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 2 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 5 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 8 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 7 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 6 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 3 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 0 ) ) );

        }

    }

    //______________________________________________
    Pixmap ShadowHelper::createPixmap( const Cairo::Surface& surface ) const
    {
        assert( surface.isValid() );
        const int width( cairo_surface_get_width( surface ) );
        const int height( cairo_surface_get_height( surface ) );

        GdkScreen* screen = gdk_screen_get_default();
        Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );
        Window root( GDK_WINDOW_XID( gdk_screen_get_root_window( screen ) ) );
        Pixmap pixmap = XCreatePixmap( display, root, width, height, 32 );

        // create surface for pixmap
        {
            Cairo::Surface dest( cairo_xlib_surface_create( display, pixmap, GDK_VISUAL_XVISUAL( gdk_screen_get_rgba_visual( screen ) ), width, height ) );
            Cairo::Context context( dest );
            cairo_set_operator( context, CAIRO_OPERATOR_SOURCE );

            cairo_rectangle( context, 0, 0, width, height );
            cairo_set_source_surface( context, surface, 0, 0 );
            cairo_fill( context );
        }

        return pixmap;

    }

    //______________________________________________
    void ShadowHelper::installX11Shadows( GtkWidget* widget )
    {

        // check screen composited
        // TODO: check whether this is necessary
        // if( !Gtk::gdk_default_screen_is_composited() ) return;

        // make sure handles and atom are defined
        createPixmapHandles();

        // check data size
        if( _roundPixmaps.size() != numPixmaps )
        {
            std::cerr << "ShadowHelper::installX11Shadows - incorrect _roundPixmaps size: " << _roundPixmaps.size() << std::endl;
            return;
        }

        GdkWindow  *window = gtk_widget_get_window( widget );
        GdkDisplay *display = gtk_widget_get_display( widget );

        std::vector<unsigned long> data;
        const bool isMenu( this->isMenu( widget ) );
        if( _applicationName.isOpenOffice() || ( isMenu && _applicationName.isMozilla( widget ) ) )
        {

            data = _squarePixmaps;
            data.push_back( _size );
            data.push_back( _size );
            data.push_back( _size );
            data.push_back( _size );

        } else {

            data = _roundPixmaps;
            if( isMenu )
            {

                /*
                for menus, need to shrink top and bottom shadow size, since body is done likely with respect to real size
                in painting method (Oxygen::Style::renderMenuBackground)
                */
                data.push_back( _size - Menu_VerticalOffset );
                data.push_back( _size );
                data.push_back( _size - Menu_VerticalOffset );
                data.push_back( _size );

            } else {

                // all sides have same sizz
                data.push_back( _size );
                data.push_back( _size );
                data.push_back( _size );
                data.push_back( _size );

            }

        }

        // change property
        XChangeProperty(
            GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom, XA_CARDINAL, 32, PropModeReplace,
            reinterpret_cast<const unsigned char *>(&data[0]), data.size() );

    }

    //_______________________________________________________
    void ShadowHelper::uninstallX11Shadows( GtkWidget* widget ) const
    {

        if( !widget ) return;

        GdkWindow  *window = gtk_widget_get_window( widget );
        GdkDisplay *display = gtk_widget_get_display( widget );
        XDeleteProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom);

    }

    //_______________________________________________________
    gboolean ShadowHelper::realizeHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )
    {

        // get widget from params
        GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );

        // check type
        if( !GTK_IS_WIDGET( widget ) ) return FALSE;
        static_cast<ShadowHelper*>(data)->registerWidget( widget );
        return TRUE;
    }

    //____________________________________________________________________________________________
    gboolean ShadowHelper::destroyNotifyEvent( GtkWidget* widget, gpointer data )
    {
        static_cast<ShadowHelper*>(data)->unregisterWidget( widget );
        return FALSE;
    }

}
<commit_msg>cleanup.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2011 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygencairocontext.h"
#include "oxygencairoutils.h"
#include "oxygengtkutils.h"
#include "oxygenmetrics.h"
#include "oxygenrgba.h"
#include "oxygenshadowhelper.h"

#include <iostream>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <gdk/gdkx.h>
#include <X11/Xatom.h>

namespace Oxygen
{

    //______________________________________________
    ShadowHelper::ShadowHelper( void ):
        _size(0),
        _atom(0),
        _hooksInitialized( false )
    {}

    //______________________________________________
    ShadowHelper::~ShadowHelper( void )
    { reset(); }

    //______________________________________________
    void ShadowHelper::reset( void )
    {

        GdkScreen* screen = gdk_screen_get_default();
        Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );

        // round pixmaps
        for( PixmapList::const_iterator iter = _roundPixmaps.begin(); iter != _roundPixmaps.end(); ++iter )
        { XFreePixmap(display, *iter); }
        _roundPixmaps.clear();

        // square pixmaps
        for( PixmapList::const_iterator iter = _squarePixmaps.begin(); iter != _squarePixmaps.end(); ++iter )
        { XFreePixmap(display, *iter); }
        _squarePixmaps.clear();

        // reset size
        _size = 0;

    }

    //______________________________________________
    void ShadowHelper::initializeHooks( void )
    {
       if( _hooksInitialized ) return;

        // install hooks
        _realizeHook.connect( "realize", (GSignalEmissionHook)realizeHook, this );
        _hooksInitialized = true;

    }

    //______________________________________________
    void ShadowHelper::initialize( const ColorUtils::Rgba& color, const WindowShadow& shadow )
    {
        reset();
        _size = int(shadow.shadowSize()) - WindowShadow::Overlap;

        // round tiles
        WindowShadowKey key;
        key.hasTopBorder = true;
        key.hasBottomBorder = true;
        _roundTiles = shadow.tileSet( color, key );

        // square tiles
        key.hasTopBorder = false;
        key.hasBottomBorder = false;
        _squareTiles = shadow.tileSet( color, key );

        // re-install shadows for all windowId
        for( WidgetMap::const_iterator iter = _widgets.begin(); iter != _widgets.end(); ++iter )
        { installX11Shadows( iter->first ); }

    }

    //______________________________________________
    bool ShadowHelper::registerWidget( GtkWidget* widget )
    {

        // check widget
        if( !( widget && GTK_IS_WINDOW( widget ) ) ) return false;

        // make sure that widget is not already registered
        if( _widgets.find( widget ) != _widgets.end() ) return false;

        // check if window is accepted
        if( !acceptWindow( GTK_WINDOW( widget )  ) ) return false;

        // try install shadows
        installX11Shadows( widget );

        // register in map and returns success
        WidgetData data;
        data._destroyId.connect( G_OBJECT( widget ), "destroy", G_CALLBACK( destroyNotifyEvent ), this );
        _widgets.insert( std::make_pair( widget, data ) );

        return true;

    }

    //______________________________________________
    void ShadowHelper::unregisterWidget( GtkWidget* widget )
    {
        // find matching data in map
        WidgetMap::iterator iter( _widgets.find( widget ) );
        if( iter == _widgets.end() ) return;

        // disconnect
        iter->second._destroyId.disconnect();

        // remove from map
        _widgets.erase( iter );
    }

    //______________________________________________
    void ShadowHelper::createPixmapHandles( void )
    {

        // create atom
        if( !_atom )
        {
            GdkScreen* screen = gdk_screen_get_default();
            Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );
            _atom = XInternAtom( display, "_KDE_NET_WM_SHADOW", False);
        }

        // make sure size is valid
        if( _size <= 0 ) return;

        // make sure pixmaps are not already initialized
        if( _roundPixmaps.empty() )
        {

            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 1 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 2 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 5 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 8 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 7 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 6 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 3 ) ) );
            _roundPixmaps.push_back( createPixmap( _roundTiles.surface( 0 ) ) );

        }

        if( _squarePixmaps.empty() )
        {

            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 1 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 2 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 5 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 8 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 7 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 6 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 3 ) ) );
            _squarePixmaps.push_back( createPixmap( _squareTiles.surface( 0 ) ) );

        }

    }

    //______________________________________________
    Pixmap ShadowHelper::createPixmap( const Cairo::Surface& surface ) const
    {
        assert( surface.isValid() );
        const int width( cairo_surface_get_width( surface ) );
        const int height( cairo_surface_get_height( surface ) );

        GdkScreen* screen = gdk_screen_get_default();
        Display* display( GDK_DISPLAY_XDISPLAY( gdk_screen_get_display( screen ) ) );
        Window root( GDK_WINDOW_XID( gdk_screen_get_root_window( screen ) ) );
        Pixmap pixmap = XCreatePixmap( display, root, width, height, 32 );

        // create surface for pixmap
        {
            Cairo::Surface dest( cairo_xlib_surface_create( display, pixmap, GDK_VISUAL_XVISUAL( gdk_screen_get_rgba_visual( screen ) ), width, height ) );
            Cairo::Context context( dest );
            cairo_set_operator( context, CAIRO_OPERATOR_SOURCE );

            cairo_rectangle( context, 0, 0, width, height );
            cairo_set_source_surface( context, surface, 0, 0 );
            cairo_fill( context );
        }

        return pixmap;

    }

    //______________________________________________
    void ShadowHelper::installX11Shadows( GtkWidget* widget )
    {

        // make sure handles and atom are defined
        createPixmapHandles();

        GdkWindow  *window = gtk_widget_get_window( widget );
        GdkDisplay *display = gtk_widget_get_display( widget );

        std::vector<unsigned long> data;
        const bool isMenu( this->isMenu( widget ) );
        if( _applicationName.isOpenOffice() || ( isMenu && _applicationName.isMozilla( widget ) ) )
        {

            data = _squarePixmaps;
            data.push_back( _size );
            data.push_back( _size );
            data.push_back( _size );
            data.push_back( _size );

        } else {

            data = _roundPixmaps;
            if( isMenu )
            {

                /*
                for menus, need to shrink top and bottom shadow size, since body is done likely with respect to real size
                in painting method (Oxygen::Style::renderMenuBackground)
                */
                data.push_back( _size - Menu_VerticalOffset );
                data.push_back( _size );
                data.push_back( _size - Menu_VerticalOffset );
                data.push_back( _size );

            } else {

                // all sides have same sizz
                data.push_back( _size );
                data.push_back( _size );
                data.push_back( _size );
                data.push_back( _size );

            }

        }

        // change property
        XChangeProperty(
            GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom, XA_CARDINAL, 32, PropModeReplace,
            reinterpret_cast<const unsigned char *>(&data[0]), data.size() );

    }

    //_______________________________________________________
    void ShadowHelper::uninstallX11Shadows( GtkWidget* widget ) const
    {

        if( !widget ) return;

        GdkWindow  *window = gtk_widget_get_window( widget );
        GdkDisplay *display = gtk_widget_get_display( widget );
        XDeleteProperty( GDK_DISPLAY_XDISPLAY( display ), GDK_WINDOW_XID(window), _atom);

    }

    //_______________________________________________________
    gboolean ShadowHelper::realizeHook( GSignalInvocationHint*, guint, const GValue* params, gpointer data )
    {

        // get widget from params
        GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) );

        // check type
        if( !GTK_IS_WIDGET( widget ) ) return FALSE;
        static_cast<ShadowHelper*>(data)->registerWidget( widget );
        return TRUE;
    }

    //____________________________________________________________________________________________
    gboolean ShadowHelper::destroyNotifyEvent( GtkWidget* widget, gpointer data )
    {
        static_cast<ShadowHelper*>(data)->unregisterWidget( widget );
        return FALSE;
    }

}
<|endoftext|>


<commit_before>#include "forces.h"

int granular_force(iREAL n[3], iREAL vij[3], iREAL oij[3], iREAL depth, int i, int j, iREAL mass[], iREAL invm[], iREAL *iparam[NINT], int ij, iREAL f[3])
{
  iREAL ma;

  if (j >= 0) ma = 1.0 / (invm[i] + invm[j]);
  else ma = mass[i];

  iREAL kn = iparam[SPRING][ij];
  iREAL en = iparam[DAMPER][ij] * 2.0 * sqrt(kn*ma);
  iREAL vn = DOT(vij,n);
  iREAL fn = kn*depth + en*vn;

  f[0] = fn*n[0];
  f[1] = fn*n[1];
  f[2] = fn*n[2];

  /* TODO */
  return depth < 0.0 ? 1 : 0;
}

/* return pairing index based on (i,j) pairing of colors */
int pairing (int nummat, int pairs[], int i, int j)
{
  int p[2] = {i, j}, start = 1, end = nummat;

  if (i > j)
  {
    p[0] = j;
    p[1] = i;
  }

  while (start < end)
  {
    int mid = ((end-start)>>1) + start;
    if (p[0] > pairs[2*mid]) start = mid;
    else if(p[0] == pairs[2*mid])
    {
      if (p[1] > pairs[2*mid+1]) start = mid;
      else if (p[1] == pairs[2*mid+1]) return mid;
      else end = mid;
    }
    else end = mid;
  }

  return 0; /* default material */
}

void forces (master_conpnt master[], slave_conpnt slave[],
  int nt, int nb, bd *b, iREAL * angular[6], iREAL * linear[3],
  iREAL mass[], iREAL invm[], int parmat[], iREAL * mparam[NMAT],
  int pairnum, int pairs[], int ikind[], iREAL * iparam[NINT])
{

  for (int i = 0; i < nt; i++)
  {
    iREAL oi[3], v[3], x[3];

    oi[0] = angular[3][i];
    oi[1] = angular[4][i];
    oi[2] = angular[5][i];

    v[0] = linear[0][i];
    v[1] = linear[1][i];
    v[2] = linear[2][i];

    x[0] = position[0][i];
    x[1] = position[1][i];
    x[2] = position[2][i];

    /* update contact forces */
    for (master_conpnt * con = &master[i]; con; con = con->next)
    {
      int gone[CONBUF];

      for(int k = 0; k<con->size; k++)
      {
        iREAL p[3], n[3], z[3], vi[3], vj[3], oj[3], vij[3], oij[3];

        p[0] = con->point[0][k];
        p[1] = con->point[1][k];
        p[2] = con->point[2][k];

        n[0] = con->normal[0][k];
        n[1] = con->normal[1][k];
        n[2] = con->normal[2][k];

        z[0] = p[0]-x[0];
        z[1] = p[1]-x[1];
        z[2] = p[2]-x[2];

        vi[0] = oi[1]*z[2]-oi[2]*z[1] + v[0];
        vi[1] = oi[2]*z[0]-oi[0]*z[2] + v[1];
        vi[2] = oi[0]*z[1]-oi[1]*z[0] + v[2];

        int j = con->slave[0][k];

        if (j >= 0) // particle-particle
        {
          z[0] = p[0]-position[0][j];
          z[1] = p[1]-position[1][j];
          z[2] = p[2]-position[2][j];

          oj[0] = angular[3][j];
          oj[1] = angular[4][j];
          oj[2] = angular[5][j];

          vj[0] = oj[1]*z[2]-oj[2]*z[1] + linear[0][j];
          vj[1] = oj[2]*z[0]-oj[0]*z[2] + linear[1][j];
          vj[2] = oj[0]*z[1]-oj[1]*z[0] + linear[2][j];
        }

        SUB (vj, vi, vij); // relative linear velocity
        SUB (oj, oi, oij); // relative angular velocity

        int ij = pairing (pairnum, pairs, con->color[0][k], con->color[1][k]);

        iREAL f[3];

        switch (ikind[ij])
        {
          case GRANULAR:
            gone[k] = granular_force (n, vij, oij, con->depth[k], i, j, mass, invm, iparam, ij, f);
            break;
          case BONDED:
            /* TODO */
            break;
          case UFORCE:
            /* TODO */
            break;
          default:
            //printf ("ERROR: invalid pairing kind");
            break;
        }

        con->force[0][k] = f[0];
        con->force[1][k] = f[1];
        con->force[2][k] = f[2];
      }
      int ngone = 0;

      for (int k = 0; k < con->size; k ++)
      {
        if (gone[k] != 0)
        {
          int j = k+1;
          while (j < con->size && gone[j] != 0) j ++;
          if (j < con->size)
          {
            con->master[k] = con->master[j];
            con->slave[0][k] = con->slave[0][j];
            con->slave[1][k] = con->slave[1][j];
            con->color[0][k] = con->color[0][j];
            con->color[1][k] = con->color[1][j];
            con->point[0][k] = con->point[0][j];
            con->point[1][k] = con->point[1][j];
            con->point[2][k] = con->point[2][j];
            con->normal[0][k] = con->normal[0][j];
            con->normal[1][k] = con->normal[1][j];
            con->normal[2][k] = con->normal[2][j];
            con->depth[k] = con->depth[j];
            con->force[0][k] = con->force[0][j];
            con->force[1][k] = con->force[1][j];
            con->force[2][k] = con->force[2][j];

            gone[j] = -1; // not to be used again
          }

        if (gone[k] > 0) ngone ++;
        }
      }

      con->size -= ngone;
    }

    master_conpnt * con = master[i].next;

    while (con && con->next) // delete empty items
    {
      master_conpnt * next = con->next;

      if (next->size == 0)
      {
        con->next = next->next;
        delete next;
      }

      con = con->next;
    }

    /* symmetrical copy into slave contact points */
    for (master_conpnt * con = &master[i]; con; con = con->next)
    {
      for (int j = 0; j < con->size; j ++)
      {
        slave_conpnt *ptr;
        int k=0;

        if (con->slave[0][j] >= 0) /* particle-particle contact */
        {
          ptr = newcon (&slave[con->slave[0][j]], &k);

          ptr->master[0][k] = i;
          ptr->master[1][k] = con->master[j];
          ptr->point[0][k] = con->point[0][j];
          ptr->point[1][k] = con->point[1][j];
          ptr->point[2][k] = con->point[2][j];
          ptr->force[0][k] = -con->force[0][j];
          ptr->force[1][k] = -con->force[1][j];
          ptr->force[2][k] = -con->force[2][j];
        }
      }
    }
  }
}

<commit_msg>master<commit_after>#include "forces.h"

int granular_force(iREAL n[3], iREAL vij[3], iREAL oij[3], iREAL depth, int i, int j, iREAL mass[], iREAL invm[], iREAL *iparam[NINT], int ij, iREAL f[3])
{
  iREAL ma;

  if (j >= 0) ma = 1.0 / (invm[i] + invm[j]);
  else ma = mass[i];

  iREAL kn = iparam[SPRING][ij];
  iREAL en = iparam[DAMPER][ij] * 2.0 * sqrt(kn*ma);
  iREAL vn = DOT(vij,n);
  iREAL fn = kn*depth + en*vn;

  f[0] = fn*n[0];
  f[1] = fn*n[1];
  f[2] = fn*n[2];

  /* TODO */
  return depth < 0.0 ? 1 : 0;
}

/* return pairing index based on (i,j) pairing of colors */
int pairing (int nummat, int pairs[], int i, int j)
{
  int p[2] = {i, j}, start = 1, end = nummat;

  if (i > j)
  {
    p[0] = j;
    p[1] = i;
  }

  while (start < end)
  {
    int mid = ((end-start)>>1) + start;
    if (p[0] > pairs[2*mid]) start = mid;
    else if(p[0] == pairs[2*mid])
    {
      if (p[1] > pairs[2*mid+1]) start = mid;
      else if (p[1] == pairs[2*mid+1]) return mid;
      else end = mid;
    }
    else end = mid;
  }

  return 0; /* default material */
}

void forces (master_conpnt master[], slave_conpnt slave[],
  int nt, int nb, bd *b, iREAL * angular[6], iREAL * linear[3],
  iREAL mass[], iREAL invm[], int parmat[], iREAL * mparam[NMAT],
  int pairnum, int pairs[], int ikind[], iREAL * iparam[NINT])
{

  for (int i = 0; i < nt; i++)
  {
    iREAL oi[3], v[3], x[3];

    oi[0] = angular[3][i];
    oi[1] = angular[4][i];
    oi[2] = angular[5][i];

    v[0] = linear[0][i];
    v[1] = linear[1][i];
    v[2] = linear[2][i];

    x[0] = position[0][i];
    x[1] = position[1][i];
    x[2] = position[2][i];

    /* update contact forces */
    for (master_conpnt * con = &master[i]; con; con = con->next)
    {
      int gone[CONBUF];

      for(int k = 0; k<con->size; k++)
      {
        iREAL p[3], n[3], z[3], vi[3], vj[3], oj[3], vij[3], oij[3];

        p[0] = con->point[0][k];
        p[1] = con->point[1][k];
        p[2] = con->point[2][k];

        n[0] = con->normal[0][k];
        n[1] = con->normal[1][k];
        n[2] = con->normal[2][k];

        z[0] = p[0]-x[0];
        z[1] = p[1]-x[1];
        z[2] = p[2]-x[2];

        vi[0] = oi[1]*z[2]-oi[2]*z[1] + v[0];
        vi[1] = oi[2]*z[0]-oi[0]*z[2] + v[1];
        vi[2] = oi[0]*z[1]-oi[1]*z[0] + v[2];

        int j = con->slave[0][k];

        if (j >= 0) // particle-particle
        {
          z[0] = p[0]-position[0][j];
          z[1] = p[1]-position[1][j];
          z[2] = p[2]-position[2][j];

          oj[0] = angular[3][j];
          oj[1] = angular[4][j];
          oj[2] = angular[5][j];

          vj[0] = oj[1]*z[2]-oj[2]*z[1] + linear[0][j];
          vj[1] = oj[2]*z[0]-oj[0]*z[2] + linear[1][j];
          vj[2] = oj[0]*z[1]-oj[1]*z[0] + linear[2][j];
        }

        SUB (vj, vi, vij); // relative linear velocity
        SUB (oj, oi, oij); // relative angular velocity

        int ij = pairing (pairnum, pairs, con->color[0][k], con->color[1][k]);

        iREAL f[3];

        switch (ikind[ij])
        {
          case GRANULAR:
            gone[k] = granular_force (n, vij, oij, con->depth[k], i, j, mass, invm, iparam, ij, f);
            break;
          case BONDED:
            /* TODO */
            break;
          case UFORCE:
            /* TODO */
            break;
          default:
            //printf ("ERROR: invalid pairing kind");
            break;
        }

        con->force[0][k] = f[0];
        con->force[1][k] = f[1];
        con->force[2][k] = f[2];
      }
      int ngone = 0;

      for (int k = 0; k < con->size; k ++)
      {
        if (gone[k] != 0)
        {
          int j = k+1;
          while (j < con->size && gone[j] != 0) j ++;
          if (j < con->size)
          {
            con->master[k] = con->master[j];
            con->slave[0][k] = con->slave[0][j];
            con->slave[1][k] = con->slave[1][j];
            con->color[0][k] = con->color[0][j];
            con->color[1][k] = con->color[1][j];
            con->point[0][k] = con->point[0][j];
            con->point[1][k] = con->point[1][j];
            con->point[2][k] = con->point[2][j];
            con->normal[0][k] = con->normal[0][j];
            con->normal[1][k] = con->normal[1][j];
            con->normal[2][k] = con->normal[2][j];
            con->depth[k] = con->depth[j];
            con->force[0][k] = con->force[0][j];
            con->force[1][k] = con->force[1][j];
            con->force[2][k] = con->force[2][j];

            gone[j] = -1; // not to be used again
          }

        if (gone[k] > 0) ngone ++;
        }
      }

      con->size -= ngone;
    }

    master_conpnt * con = master[i].next;

    while (con && con->next) // delete empty items
    {
      master_conpnt * next = con->next;

      if (next->size == 0)
      {
        con->next = next->next;
        delete next;
      }

      con = con->next;
    }

    /* symmetrical copy into slave contact points */
    for (master_conpnt * con = &master[i]; con; con = con->next)
    {
      for (int j = 0; j < con->size; j ++)
      {
        slave_conpnt *ptr;
        int k=0;

        if (con->slave[0][j] >= 0) /* particle-particle contact */
        {
          ptr = newcon (&slave[con->slave[0][j]], &k);

          ptr->master[0][k] = i;
          ptr->master[1][k] = con->master[j];
          ptr->point[0][k] = con->point[0][j];
          ptr->point[1][k] = con->point[1][j];
          ptr->point[2][k] = con->point[2][j];
          ptr->force[0][k] = -con->force[0][j];
          ptr->force[1][k] = -con->force[1][j];
          ptr->force[2][k] = -con->force[2][j];
        }
      }
    }
  }
}

<|endoftext|>


<commit_before>/*****************************************************************************
*   Number Plate Recognition using SVM and Neural Networks
******************************************************************************
*   by David Milln Escriv, 5th Dec 2012
*   http://blog.damiles.com
******************************************************************************
*   Ch5 of the book "Mastering OpenCV with Practical Computer Vision Projects"
*   Copyright Packt Publishing 2012.
*   http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/

// Main entry code OpenCV

#include <cv.h>
#include <highgui.h>
#include <cvaux.h>

#include "OCR.h"

#include <iostream>
#include <vector>

using namespace std;
using namespace cv;

const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7};

int main ( int argc, char** argv )
{
    cout << "OpenCV Training OCR Automatic Number Plate Recognition\n";
    cout << "\n";

    char* path;

    //Check if user specify image to process
    if(argc >= 1 )
    {
        path= argv[1];

    }else{
        cout << "Usage:\n" << argv[0] << " <path to chars folders files> \n";
        return 0;
    }

    Mat classes;
    Mat trainingDataf5;
    Mat trainingDataf10;
    Mat trainingDataf15;
    Mat trainingDataf20;

    vector<int> trainingLabels;
    OCR ocr;

    for(int i=0; i< OCR::numCharacters; i++)
    {
        int numFiles=numFilesChars[i];
        for(int j=0; j< numFiles; j++){
            cout << "Character "<< OCR::strCharacters[i] << " file: " << j << "\n";
            stringstream ss(stringstream::in | stringstream::out);
            ss << path << OCR::strCharacters[i] << "/" << j << ".jpg";
            Mat img=imread(ss.str(), 0);
            Mat f5=ocr.features(img, 5);
            Mat f10=ocr.features(img, 10);
            Mat f15=ocr.features(img, 15);
            Mat f20=ocr.features(img, 20);

            trainingDataf5.push_back(f5);
            trainingDataf10.push_back(f10);
            trainingDataf15.push_back(f15);
            trainingDataf20.push_back(f20);
            trainingLabels.push_back(i);
        }
    }

    trainingDataf5.convertTo(trainingDataf5, CV_32FC1);
    trainingDataf10.convertTo(trainingDataf10, CV_32FC1);
    trainingDataf15.convertTo(trainingDataf15, CV_32FC1);
    trainingDataf20.convertTo(trainingDataf20, CV_32FC1);
    Mat(trainingLabels).copyTo(classes);

    FileStorage fs("OCR.xml", FileStorage::WRITE);
    fs << "TrainingDataF5" << trainingDataf5;
    fs << "TrainingDataF10" << trainingDataf10;
    fs << "TrainingDataF15" << trainingDataf15;
    fs << "TrainingDataF20" << trainingDataf20;
    fs << "classes" << classes;
    fs.release();

    return 0;
}
<commit_msg>OCR train<commit_after>/*****************************************************************************
*   Number Plate Recognition using SVM and Neural Networks
******************************************************************************
*/

// Main entry code OpenCV

#include <cv.h>
#include <highgui.h>
#include <cvaux.h>

#include "OCR.h"

#include <iostream>
#include <vector>

using namespace std;
using namespace cv;

const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7};

int main ( int argc, char** argv )
{
    cout << "OpenCV Training OCR Automatic Number Plate Recognition\n";
    cout << "\n";

    char* path;

    //Check if user specify image to process
    if(argc >= 1 )
    {
        path= argv[1];

    }else{
        cout << "Usage:\n" << argv[0] << " <path to chars folders files> \n";
        return 0;
    }

    Mat classes;
    Mat trainingDataf5;
    Mat trainingDataf10;
    Mat trainingDataf15;
    Mat trainingDataf20;

    vector<int> trainingLabels;
    OCR ocr;

    for(int i=0; i< OCR::numCharacters; i++)
    {
        int numFiles=numFilesChars[i];
        for(int j=0; j< numFiles; j++){
            cout << "Character "<< OCR::strCharacters[i] << " file: " << j << "\n";
            stringstream ss(stringstream::in | stringstream::out);
            ss << path << OCR::strCharacters[i] << "/" << j << ".jpg";
            Mat img=imread(ss.str(), 0);
            Mat f5=ocr.features(img, 5);
            Mat f10=ocr.features(img, 10);
            Mat f15=ocr.features(img, 15);
            Mat f20=ocr.features(img, 20);

            trainingDataf5.push_back(f5);
            trainingDataf10.push_back(f10);
            trainingDataf15.push_back(f15);
            trainingDataf20.push_back(f20);
            trainingLabels.push_back(i);
        }
    }

    trainingDataf5.convertTo(trainingDataf5, CV_32FC1);
    trainingDataf10.convertTo(trainingDataf10, CV_32FC1);
    trainingDataf15.convertTo(trainingDataf15, CV_32FC1);
    trainingDataf20.convertTo(trainingDataf20, CV_32FC1);
    Mat(trainingLabels).copyTo(classes);

    FileStorage fs("OCR.xml", FileStorage::WRITE);
    fs << "TrainingDataF5" << trainingDataf5;
    fs << "TrainingDataF10" << trainingDataf10;
    fs << "TrainingDataF15" << trainingDataf15;
    fs << "TrainingDataF20" << trainingDataf20;
    fs << "classes" << classes;
    fs.release();

    return 0;
}
<|endoftext|>


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

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

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

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//  INPUTS: {NDVI_2.hdr} , {NDVI_3.hdr}
//  OUTPUTS: {NDVIRAndNIRVegetationIndex.tif} , {pretty_Red.png} , {pretty_NIR.png} , {pretty_NDVIRAndNIRVegetationIndex.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// \index{otb::RAndNIRVegetationIndexImageFilter}
// \index{otb::VegetationIndex}
// \index{otb::VegetationIndex!header}
//
// The following example illustrates the use of the
// \doxygen{otb}{RAndNIRVegetationIndexImageFilter} with the use of the Normalized
// Difference Vegatation Index (NDVI).
// NDVI computes the difference between the NIR channel, noted $L_{NIR}$, and the red channel,
// noted $L_{r}$ radiances reflected from the surface and transmitted through the atmosphere:
//
// \begin{equation}
// \mathbf{NDVI} = \frac{L_{NIR}-L_{r}}{L_{NIR}+L_{r}}
// \end{equation}
//
// With the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} class the filter
// inputs are one channel images: one inmage represents the NIR channel, the
// the other the NIR channel.
//
// Let's look at the minimal code required to use this algorithm. First, the following header
// defining the \doxygen{otb}{RAndNIRVegetationIndexImageFilter}
// class must be included.
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbRAndNIRVegetationIndexImageFilter.h"
// Software Guide : EndCodeSnippet

#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

int main( int argc, char *argv[] )
{
  if ( argc < 6 )
  {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " inputImage1 , inputImage2 , outputImage , prettyinputImage1 , prettyinputImage2 , prettyOutput" << std::endl;
    return 1;
  }

  //  Software Guide : BeginLatex
  //
  // The image types are now defined using pixel types the
  // dimension. Input and output images are defined as \doxygen{otb}{Image}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int                              Dimension = 2;
  typedef double                                  InputPixelType;
  typedef float                                   OutputPixelType;
  typedef otb::Image<InputPixelType,Dimension>    InputRImageType;
  typedef otb::Image<InputPixelType,Dimension>    InputNIRImageType;
  typedef otb::Image<OutputPixelType,Dimension>   OutputImageType;
  // Software Guide : EndCodeSnippet

  // We instantiate reader and writer types
  typedef otb::ImageFileReader<InputRImageType>   RReaderType;
  typedef otb::ImageFileReader<InputNIRImageType> NIRReaderType;
  typedef otb::ImageFileWriter<OutputImageType>   WriterType;

  //  Software Guide : BeginLatex
  //
  // The NDVI (Normalized Difference Vegetation Index) is instantiated using
  // the images pixel type as template parameters. It is
  // implemented as a functor class which will be passed as a
  // parameter to an \doxygen{otb}{RAndNIRVegetationIndexImageFilter}.
  // Note that we also can use other functors which operate with the
  // Red and Nir channels, such as PVI, RVI, SAVI, MSAVI, TSAVI, GEMI,
  // WDVI, IPVI, and TNDVI.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::Functor::NDVI< InputPixelType,
  InputPixelType,
  OutputPixelType>   FunctorType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // The \doxygen{otb}{RAndNIRVegetationIndexImageFilter} type is instantiated using the images
  // types and the NDVI functor as template parameters.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::RAndNIRVegetationIndexImageFilter<InputRImageType,
  InputNIRImageType,
  OutputImageType,
  FunctorType>
  RAndNIRVegetationIndexImageFilterType;
  // Software Guide : EndCodeSnippet

  // Instantiating object
  RAndNIRVegetationIndexImageFilterType::Pointer filter    = RAndNIRVegetationIndexImageFilterType::New();
  RReaderType::Pointer                           readerR   = RReaderType::New();
  NIRReaderType::Pointer                         readerNIR = NIRReaderType::New();
  WriterType::Pointer                            writer    = WriterType::New();

  //  Software Guide : BeginLatex
  //
  //  Now the input images are set and a name is given to the output image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  readerR->SetFileName( argv[1] );
  readerNIR->SetFileName( argv[2] );
  writer->SetFileName( argv[3]  );

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We set the processing pipeline: filter inputs are linked to
  // the reader output and the filter output is linked to the writer
  // input.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInputR( readerR->GetOutput() );
  filter->SetInputNIR( readerNIR->GetOutput() );

  writer->SetInput( filter->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Invocation of the \code{Update()} method on the writer triggers the
  // execution of the pipeline.  It is recommended to place \code{update()} calls in a
  // \code{try/catch} block in case errors occur and exceptions are thrown.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
  {
    writer->Update();
  }
  catch ( itk::ExceptionObject & excep )
  {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
  }
  // Software Guide : EndCodeSnippet
  catch ( ... )
  {
    std::cout << "Unknown exception !" << std::endl;
    return EXIT_FAILURE;
  }

  // Pretty image creation for the printing
  typedef otb::Image<unsigned char, Dimension>                                                  OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>                                           WriterPrettyType;
  typedef itk::RescaleIntensityImageFilter< OutputImageType, OutputPrettyImageType>             RescalerType;
  typedef itk::RescaleIntensityImageFilter< InputRImageType, OutputPrettyImageType>             RescalerRType;
  typedef itk::RescaleIntensityImageFilter< InputNIRImageType, OutputPrettyImageType>           RescalerNIRType;

  RescalerType::Pointer     rescaler     = RescalerType::New();
  WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New();
  rescaler->SetInput( filter->GetOutput() );
  rescaler->SetOutputMinimum(0);
  rescaler->SetOutputMaximum(255);
  prettyWriter->SetFileName( argv[6] );
  prettyWriter->SetInput( rescaler->GetOutput() );

  RescalerRType::Pointer     rescalerR     = RescalerRType::New();
  RescalerNIRType::Pointer     rescalerNIR     = RescalerNIRType::New();
  WriterPrettyType::Pointer prettyWriterR = WriterPrettyType::New();
  WriterPrettyType::Pointer prettyWriterNIR = WriterPrettyType::New();
  rescalerR->SetInput( readerR->GetOutput() );
  rescalerR->SetOutputMinimum(0);
  rescalerR->SetOutputMaximum(255);
  prettyWriterR->SetFileName( argv[4] );
  prettyWriterR->SetInput( rescalerR->GetOutput() );

  rescalerNIR->SetInput( readerNIR->GetOutput() );
  rescalerNIR->SetOutputMinimum(0);
  rescalerNIR->SetOutputMaximum(255);
  prettyWriterNIR->SetFileName( argv[5] );
  prettyWriterNIR->SetInput( rescalerNIR->GetOutput() );

  try
  {
    prettyWriter->Update();
    prettyWriterNIR->Update();
    prettyWriterR->Update();
  }
  catch ( itk::ExceptionObject & excep )
  {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
  }
  catch ( ... )
  {
    std::cout << "Unknown exception !" << std::endl;
    return EXIT_FAILURE;
  }

  // Software Guide : BeginLatex
  //
  // Let's now run this example using as input the images
  // \code{NDVI\_3.hdr} and  \code{NDVI\_4.hdr} (images kindly and free of charge given by SISA and CNES)
  // provided in the directory \code{Examples/Data}.
  //
  //
  // \begin{figure} \center
  // \includegraphics[width=0.24\textwidth]{pretty_Red.eps}
  // \includegraphics[width=0.24\textwidth]{pretty_NIR.eps}
  // \includegraphics[width=0.24\textwidth]{pretty_NDVIRAndNIRVegetationIndex.eps}
  // \itkcaption[ARVI Example]{NDVI input images on the left (Red channel and NIR channel), on the right the result of the algorithm.}
  // \label{fig:NDVIRAndNIRVegetationIndex}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;
}

<commit_msg>DOC: Added related classes to NDVI<commit_after>/*=========================================================================

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

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

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//  INPUTS: {NDVI_2.hdr} , {NDVI_3.hdr}
//  OUTPUTS: {NDVIRAndNIRVegetationIndex.tif} , {pretty_Red.png} , {pretty_NIR.png} , {pretty_NDVIRAndNIRVegetationIndex.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// \index{otb::RAndNIRVegetationIndexImageFilter}
// \index{otb::VegetationIndex}
// \index{otb::VegetationIndex!header}
//
// The following example illustrates the use of the
// \doxygen{otb}{RAndNIRVegetationIndexImageFilter} with the use of the Normalized
// Difference Vegatation Index (NDVI).
// NDVI computes the difference between the NIR channel, noted $L_{NIR}$, and the red channel,
// noted $L_{r}$ radiances reflected from the surface and transmitted through the atmosphere:
//
// \begin{equation}
// \mathbf{NDVI} = \frac{L_{NIR}-L_{r}}{L_{NIR}+L_{r}}
// \end{equation}
//
//  \relatedClasses
//  \begin{itemize}
//  \item \subdoxygen{otb}{Functor}{RVI}
//  \item \subdoxygen{otb}{Functor}{PVI}
//  \item \subdoxygen{otb}{Functor}{SAVI}
//  \item \subdoxygen{otb}{Functor}{TSAVI}
//  \item \subdoxygen{otb}{Functor}{MSAVI}
//  \item \subdoxygen{otb}{Functor}{GEMI}
//  \item \subdoxygen{otb}{Functor}{WDVI}
//  \item \subdoxygen{otb}{Functor}{IPVI}
//  \item \subdoxygen{otb}{Functor}{TNDVI}
//  \end{itemize}

// With the \doxygen{otb}{RAndNIRVegetationIndexImageFilter} class the filter
// inputs are one channel images: one inmage represents the NIR channel, the
// the other the NIR channel.
//
// Let's look at the minimal code required to use this algorithm. First, the following header
// defining the \doxygen{otb}{RAndNIRVegetationIndexImageFilter}
// class must be included.
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbRAndNIRVegetationIndexImageFilter.h"
// Software Guide : EndCodeSnippet

#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

int main( int argc, char *argv[] )
{
  if ( argc < 6 )
  {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " inputImage1 , inputImage2 , outputImage , prettyinputImage1 , prettyinputImage2 , prettyOutput" << std::endl;
    return 1;
  }

  //  Software Guide : BeginLatex
  //
  // The image types are now defined using pixel types the
  // dimension. Input and output images are defined as \doxygen{otb}{Image}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int                              Dimension = 2;
  typedef double                                  InputPixelType;
  typedef float                                   OutputPixelType;
  typedef otb::Image<InputPixelType,Dimension>    InputRImageType;
  typedef otb::Image<InputPixelType,Dimension>    InputNIRImageType;
  typedef otb::Image<OutputPixelType,Dimension>   OutputImageType;
  // Software Guide : EndCodeSnippet

  // We instantiate reader and writer types
  typedef otb::ImageFileReader<InputRImageType>   RReaderType;
  typedef otb::ImageFileReader<InputNIRImageType> NIRReaderType;
  typedef otb::ImageFileWriter<OutputImageType>   WriterType;

  //  Software Guide : BeginLatex
  //
  // The NDVI (Normalized Difference Vegetation Index) is instantiated using
  // the images pixel type as template parameters. It is
  // implemented as a functor class which will be passed as a
  // parameter to an \doxygen{otb}{RAndNIRVegetationIndexImageFilter}.
  // Note that we also can use other functors which operate with the
  // Red and Nir channels, such as PVI, RVI, SAVI, MSAVI, TSAVI, GEMI,
  // WDVI, IPVI, and TNDVI.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::Functor::NDVI< InputPixelType,
  InputPixelType,
  OutputPixelType>   FunctorType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  // The \doxygen{otb}{RAndNIRVegetationIndexImageFilter} type is instantiated using the images
  // types and the NDVI functor as template parameters.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::RAndNIRVegetationIndexImageFilter<InputRImageType,
  InputNIRImageType,
  OutputImageType,
  FunctorType>
  RAndNIRVegetationIndexImageFilterType;
  // Software Guide : EndCodeSnippet

  // Instantiating object
  RAndNIRVegetationIndexImageFilterType::Pointer filter    = RAndNIRVegetationIndexImageFilterType::New();
  RReaderType::Pointer                           readerR   = RReaderType::New();
  NIRReaderType::Pointer                         readerNIR = NIRReaderType::New();
  WriterType::Pointer                            writer    = WriterType::New();

  //  Software Guide : BeginLatex
  //
  //  Now the input images are set and a name is given to the output image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  readerR->SetFileName( argv[1] );
  readerNIR->SetFileName( argv[2] );
  writer->SetFileName( argv[3]  );

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We set the processing pipeline: filter inputs are linked to
  // the reader output and the filter output is linked to the writer
  // input.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetInputR( readerR->GetOutput() );
  filter->SetInputNIR( readerNIR->GetOutput() );

  writer->SetInput( filter->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Invocation of the \code{Update()} method on the writer triggers the
  // execution of the pipeline.  It is recommended to place \code{update()} calls in a
  // \code{try/catch} block in case errors occur and exceptions are thrown.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  try
  {
    writer->Update();
  }
  catch ( itk::ExceptionObject & excep )
  {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
  }
  // Software Guide : EndCodeSnippet
  catch ( ... )
  {
    std::cout << "Unknown exception !" << std::endl;
    return EXIT_FAILURE;
  }

  // Pretty image creation for the printing
  typedef otb::Image<unsigned char, Dimension>                                                  OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>                                           WriterPrettyType;
  typedef itk::RescaleIntensityImageFilter< OutputImageType, OutputPrettyImageType>             RescalerType;
  typedef itk::RescaleIntensityImageFilter< InputRImageType, OutputPrettyImageType>             RescalerRType;
  typedef itk::RescaleIntensityImageFilter< InputNIRImageType, OutputPrettyImageType>           RescalerNIRType;

  RescalerType::Pointer     rescaler     = RescalerType::New();
  WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New();
  rescaler->SetInput( filter->GetOutput() );
  rescaler->SetOutputMinimum(0);
  rescaler->SetOutputMaximum(255);
  prettyWriter->SetFileName( argv[6] );
  prettyWriter->SetInput( rescaler->GetOutput() );

  RescalerRType::Pointer     rescalerR     = RescalerRType::New();
  RescalerNIRType::Pointer     rescalerNIR     = RescalerNIRType::New();
  WriterPrettyType::Pointer prettyWriterR = WriterPrettyType::New();
  WriterPrettyType::Pointer prettyWriterNIR = WriterPrettyType::New();
  rescalerR->SetInput( readerR->GetOutput() );
  rescalerR->SetOutputMinimum(0);
  rescalerR->SetOutputMaximum(255);
  prettyWriterR->SetFileName( argv[4] );
  prettyWriterR->SetInput( rescalerR->GetOutput() );

  rescalerNIR->SetInput( readerNIR->GetOutput() );
  rescalerNIR->SetOutputMinimum(0);
  rescalerNIR->SetOutputMaximum(255);
  prettyWriterNIR->SetFileName( argv[5] );
  prettyWriterNIR->SetInput( rescalerNIR->GetOutput() );

  try
  {
    prettyWriter->Update();
    prettyWriterNIR->Update();
    prettyWriterR->Update();
  }
  catch ( itk::ExceptionObject & excep )
  {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
  }
  catch ( ... )
  {
    std::cout << "Unknown exception !" << std::endl;
    return EXIT_FAILURE;
  }

  // Software Guide : BeginLatex
  //
  // Let's now run this example using as input the images
  // \code{NDVI\_3.hdr} and  \code{NDVI\_4.hdr} (images kindly and free of charge given by SISA and CNES)
  // provided in the directory \code{Examples/Data}.
  //
  //
  // \begin{figure} \center
  // \includegraphics[width=0.24\textwidth]{pretty_Red.eps}
  // \includegraphics[width=0.24\textwidth]{pretty_NIR.eps}
  // \includegraphics[width=0.24\textwidth]{pretty_NDVIRAndNIRVegetationIndex.eps}
  // \itkcaption[ARVI Example]{NDVI input images on the left (Red channel and NIR channel), on the right the result of the algorithm.}
  // \label{fig:NDVIRAndNIRVegetationIndex}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "TypeDefinition.h"

fint fwcslen(fwchar_t* str)
{
	fint counter=0;
	fwchar_t* tmpstr = str;
	while(*tmpstr != 0)
	{
		tmpstr++;
		counter++;
	}
	return counter;
}

fint fwcscmp(fwchar_t* str1, fwchar_t* str2)
{
	fwchar_t* tmpstr1 = str1;
	fwchar_t* tmpstr2 = str2;
	while(*tmpstr1 != 0 || *tmpstr2 !=0)
	{
        if (*tmpstr1 != *tmpstr2)
			return -1;

		tmpstr1++;
		tmpstr2++;
	}

	return 0;
}<commit_msg>Fontlib crash on em64t fix<commit_after>#include "TypeDefinition.h"

fint fwcslen(fwchar_t* str)
{
    if (!str)
        return 0;

	fint counter=0;
	fwchar_t* tmpstr = str;
	while(*tmpstr != 0)
	{
		tmpstr++;
		counter++;
	}
	return counter;
}

fint fwcscmp(fwchar_t* str1, fwchar_t* str2)
{
    if (str1 == 0 || str2 == 0)
        return str1 - str2;

	fwchar_t* tmpstr1 = str1;
	fwchar_t* tmpstr2 = str2;
	while(*tmpstr1 != 0 || *tmpstr2 !=0)
	{
        if (*tmpstr1 != *tmpstr2)
			return -1;

		tmpstr1++;
		tmpstr2++;
	}

	return 0;
}<|endoftext|>