<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;
         }

         int coverages[numIndividuals];
         double *majorAlleleFreqs = new 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] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

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

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

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

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
                         threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (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;
         }

         int coverages[numIndividuals];
         double *majorAlleleFreqs = new 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] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1

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

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

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

                         threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
                         threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (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 2011, 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <GL/freeglut.h>

#include "WindowImp.h"
#include "Test.util.h"
#include "http/HTTPConnection.h"

using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;

extern html::Window window;

void reshape(int w, int h)
{
    glViewport(0, 0, w, h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, w, h, 0, -1000.0, 1.0);

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->setSize(w, h);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->render();
    glutSwapBuffers();  // This would block until the sync happens
}

unsigned getCharKeyCode(int key)
{
    // US Qwerty
    static unsigned map[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,
        32, 49 /* ! */, 222 /* " */, 51 /* # */, 52 /* $ */, 53 /* % */, 55 /* & */, 222 /* ' */,
        57 /* ( */, 48 /* ) */, 56 /* * */, 187 /* + */, 188 /* , */, 189 /* - */, 190 /* . */, 191 /* / */,
        48 /* 0 */, 49 /* 1 */, 50 /* 2 */, 51 /* 3 */, 52 /* 4 */, 53 /* 5 */, 54 /* 6 */, 55 /* 7 */,
        56 /* 8 */, 57 /* 9 */, 186 /* : */, 186 /* ; */, 188 /* < */, 187 /* = */, 190 /* > */, 191 /* ? */,
        50 /* @ */, 65 /* A */, 66 /* B */, 67 /* C */, 68 /* D */, 69 /* E */, 70 /* F */, 71 /* G */,
        72 /* H */, 73 /* I */, 74 /* J */, 75 /* K */, 76 /* L */, 77 /* M */, 78 /* N */, 79 /* O */,
        80 /* P */, 81 /* Q */, 82 /* R */, 83 /* S */, 84 /* T */, 85 /* U */, 86 /* V */, 87 /* W */,
        88 /* X */, 89 /* Y */, 90 /* Z */, 219 /* [ */, 220 /* \ */, 221 /* ] */, 54 /* ^ */, 189 /* _ */,
        192 /* ` */, 65 /* a */, 66 /* b */, 67 /* c */, 68 /* d */, 69 /* e */, 70 /* f */, 71 /* g */,
        72 /* h */, 73 /* i */, 74 /* j */, 75 /* k */, 76 /* l */, 77 /* m */, 78 /* n */, 79 /* o */,
        80 /* p */, 81 /* q */, 82 /* r */, 83 /* s */, 84 /* t */, 85 /* u */, 86 /* v */, 87 /* w */,
        88 /* x */, 89 /* y */, 90 /* z */, 219 /* { */, 220 /* | */, 221 /* } */, 192 /* ~ */, 46 /* DEL */
    };
    static_assert(sizeof map /sizeof map[0] == 128, "invalid map");
    return (0 <= key && key <= 127) ? map[key] : 0;
}

void keyboard(unsigned char key, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->keydown(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());
}

void keyboardUp(unsigned char key, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->keyup(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());
}

unsigned getSpecialKeyCode(int key)
{
    switch (key) {
    case GLUT_KEY_F1:
        return 112;
    case GLUT_KEY_F2:
        return 113;
    case GLUT_KEY_F3:
        return 114;
    case GLUT_KEY_F4:
        return 115;
    case GLUT_KEY_F5:
        return 116;
    case GLUT_KEY_F6:
        return 117;
    case GLUT_KEY_F7:
        return 118;
    case GLUT_KEY_F8:
        return 119;
    case GLUT_KEY_F9:
        return 120;
    case GLUT_KEY_F10:
        return 121;
    case GLUT_KEY_F11:
        return 122;
    case GLUT_KEY_F12:
        return 123;
    case GLUT_KEY_LEFT:
        return 37;
    case GLUT_KEY_UP:
        return 38;
    case GLUT_KEY_RIGHT:
        return 39;
    case GLUT_KEY_DOWN:
        return 40;
    case GLUT_KEY_PAGE_UP:
        return 33;
    case GLUT_KEY_PAGE_DOWN:
        return 34;
    case GLUT_KEY_HOME:
        return 36;
    case GLUT_KEY_END:
        return 35;
    case GLUT_KEY_INSERT:
        return 45;
    case 109:  // Num Lock
        return 144;
    default:
        return 0;
    }
}

void special(int key, int x, int y)
{
    unsigned keycode = getSpecialKeyCode(key);
    if (keycode) {
        if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
            imp->keydown(0, keycode, glutGetModifiers());
    }
}

void specialUp(int key, int x, int y)
{
    unsigned keycode = getSpecialKeyCode(key);
    if (keycode) {
        if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
            imp->keyup(0, keycode, glutGetModifiers());
    }
}

void mouse(int button, int state, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->mouse(button, state, x, y, glutGetModifiers());
}

void mouseMove(int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->mouseMove(x, y, glutGetModifiers());
}

void timer(int value)
{
    HttpConnectionManager::getInstance().poll();    // TODO: This line should not be necessary.
    if (WindowImp* imp = static_cast<WindowImp*>(window.self())) {
        if (imp->poll())
            glutPostRedisplay();
    }
    glutTimerFunc(50, timer, 0);
    // TODO: do GC here or maybe in the idle proc
}

void init(int* argc, char* argv[])
{
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(816, 1056);
    glutCreateWindow(argv[0]);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glClearColor(1.0, 1.0, 1.0, 1.0);
    glEnable(GL_TEXTURE_2D);
    glDepthFunc(GL_LEQUAL);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_ALPHA_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glutKeyboardFunc(keyboard);
    glutKeyboardUpFunc(keyboardUp);
    glutSpecialFunc(special);
    glutSpecialUpFunc(specialUp);
    glutMouseFunc(mouse);
    glutMotionFunc(mouseMove);
    glutPassiveMotionFunc(mouseMove);
    glutTimerFunc(50, timer, 0);
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);

#ifndef NDEBUG
    GLint stencilBits;
    glGetIntegerv(GL_STENCIL_BITS, &stencilBits);
    std::cout << "GL_STENCIL_BITS: " << stencilBits << '\n';
#endif
    // TODO: assuming 8 <= stencilBits for now
    glClearStencil(0x00);
    glEnable(GL_STENCIL_TEST);
}
<commit_msg>(init) : Check GL_STENCIL_BITS.<commit_after>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <GL/freeglut.h>

#include "WindowImp.h"
#include "Test.util.h"
#include "http/HTTPConnection.h"

using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;

extern html::Window window;

void reshape(int w, int h)
{
    glViewport(0, 0, w, h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, w, h, 0, -1000.0, 1.0);

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->setSize(w, h);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->render();
    glutSwapBuffers();  // This would block until the sync happens
}

unsigned getCharKeyCode(int key)
{
    // US Qwerty
    static unsigned map[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 12, 13, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 27, 0, 0, 0, 0,
        32, 49 /* ! */, 222 /* " */, 51 /* # */, 52 /* $ */, 53 /* % */, 55 /* & */, 222 /* ' */,
        57 /* ( */, 48 /* ) */, 56 /* * */, 187 /* + */, 188 /* , */, 189 /* - */, 190 /* . */, 191 /* / */,
        48 /* 0 */, 49 /* 1 */, 50 /* 2 */, 51 /* 3 */, 52 /* 4 */, 53 /* 5 */, 54 /* 6 */, 55 /* 7 */,
        56 /* 8 */, 57 /* 9 */, 186 /* : */, 186 /* ; */, 188 /* < */, 187 /* = */, 190 /* > */, 191 /* ? */,
        50 /* @ */, 65 /* A */, 66 /* B */, 67 /* C */, 68 /* D */, 69 /* E */, 70 /* F */, 71 /* G */,
        72 /* H */, 73 /* I */, 74 /* J */, 75 /* K */, 76 /* L */, 77 /* M */, 78 /* N */, 79 /* O */,
        80 /* P */, 81 /* Q */, 82 /* R */, 83 /* S */, 84 /* T */, 85 /* U */, 86 /* V */, 87 /* W */,
        88 /* X */, 89 /* Y */, 90 /* Z */, 219 /* [ */, 220 /* \ */, 221 /* ] */, 54 /* ^ */, 189 /* _ */,
        192 /* ` */, 65 /* a */, 66 /* b */, 67 /* c */, 68 /* d */, 69 /* e */, 70 /* f */, 71 /* g */,
        72 /* h */, 73 /* i */, 74 /* j */, 75 /* k */, 76 /* l */, 77 /* m */, 78 /* n */, 79 /* o */,
        80 /* p */, 81 /* q */, 82 /* r */, 83 /* s */, 84 /* t */, 85 /* u */, 86 /* v */, 87 /* w */,
        88 /* x */, 89 /* y */, 90 /* z */, 219 /* { */, 220 /* | */, 221 /* } */, 192 /* ~ */, 46 /* DEL */
    };
    static_assert(sizeof map /sizeof map[0] == 128, "invalid map");
    return (0 <= key && key <= 127) ? map[key] : 0;
}

void keyboard(unsigned char key, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->keydown(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());
}

void keyboardUp(unsigned char key, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->keyup(isprint(key) ? key : 0, getCharKeyCode(key), glutGetModifiers());
}

unsigned getSpecialKeyCode(int key)
{
    switch (key) {
    case GLUT_KEY_F1:
        return 112;
    case GLUT_KEY_F2:
        return 113;
    case GLUT_KEY_F3:
        return 114;
    case GLUT_KEY_F4:
        return 115;
    case GLUT_KEY_F5:
        return 116;
    case GLUT_KEY_F6:
        return 117;
    case GLUT_KEY_F7:
        return 118;
    case GLUT_KEY_F8:
        return 119;
    case GLUT_KEY_F9:
        return 120;
    case GLUT_KEY_F10:
        return 121;
    case GLUT_KEY_F11:
        return 122;
    case GLUT_KEY_F12:
        return 123;
    case GLUT_KEY_LEFT:
        return 37;
    case GLUT_KEY_UP:
        return 38;
    case GLUT_KEY_RIGHT:
        return 39;
    case GLUT_KEY_DOWN:
        return 40;
    case GLUT_KEY_PAGE_UP:
        return 33;
    case GLUT_KEY_PAGE_DOWN:
        return 34;
    case GLUT_KEY_HOME:
        return 36;
    case GLUT_KEY_END:
        return 35;
    case GLUT_KEY_INSERT:
        return 45;
    case 109:  // Num Lock
        return 144;
    default:
        return 0;
    }
}

void special(int key, int x, int y)
{
    unsigned keycode = getSpecialKeyCode(key);
    if (keycode) {
        if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
            imp->keydown(0, keycode, glutGetModifiers());
    }
}

void specialUp(int key, int x, int y)
{
    unsigned keycode = getSpecialKeyCode(key);
    if (keycode) {
        if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
            imp->keyup(0, keycode, glutGetModifiers());
    }
}

void mouse(int button, int state, int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->mouse(button, state, x, y, glutGetModifiers());
}

void mouseMove(int x, int y)
{
    if (WindowImp* imp = static_cast<WindowImp*>(window.self()))
        imp->mouseMove(x, y, glutGetModifiers());
}

void timer(int value)
{
    HttpConnectionManager::getInstance().poll();    // TODO: This line should not be necessary.
    if (WindowImp* imp = static_cast<WindowImp*>(window.self())) {
        if (imp->poll())
            glutPostRedisplay();
    }
    glutTimerFunc(50, timer, 0);
    // TODO: do GC here or maybe in the idle proc
}

void init(int* argc, char* argv[])
{
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(816, 1056);
    glutCreateWindow(argv[0]);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glClearColor(1.0, 1.0, 1.0, 1.0);
    glEnable(GL_TEXTURE_2D);
    glDepthFunc(GL_LEQUAL);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_ALPHA_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glutKeyboardFunc(keyboard);
    glutKeyboardUpFunc(keyboardUp);
    glutSpecialFunc(special);
    glutSpecialUpFunc(specialUp);
    glutMouseFunc(mouse);
    glutMotionFunc(mouseMove);
    glutPassiveMotionFunc(mouseMove);
    glutTimerFunc(50, timer, 0);
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);

    GLint stencilBits;
    glGetIntegerv(GL_STENCIL_BITS, &stencilBits);
    if (stencilBits < 8) {
        std::cout << "error: The number of the OpenGL stencil bits needs to be greater than or equal to 8. Current: " << stencilBits << ".\n";
        exit(EXIT_FAILURE);
    }
    glClearStencil(0x00);
    glEnable(GL_STENCIL_TEST);
}
<|endoftext|>


<commit_before>/*
 * Main routine and function for the startd.
 */

#include "condor_common.h"

/*
 * System include files.
 */
#include <netdb.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <netinet/in.h>
#if !defined(LINUX) && !defined(HPUX9)
#include <sys/select.h>
#endif

/*
 * Condor include files.
 */
#include "debug.h"
#include "trace.h"
#include "except.h"
#include "sched.h"
#include "condor_types.h"
#include "expr.h"
#include "clib.h"
#include "util_lib_proto.h"
#include "condor_uid.h"

#include "resource.h"
#include "resmgr.h"

#include "CondorPrefExps.h"

/*
 * Polling vars.
 */
static int	polling_freq;
static int	owner_polling_freq;
int	polls_per_update;
static int	polls_per_update_kbdd; // never used!
static int	polls_per_update_load; // never used!

/*
 * Flags from the commandline.
 */
int	fgflag;
int	tflag;

/*
 * Paths.
 */
char		*log_path=NULL;
char		*spool_path=NULL;
char		*exec_path=NULL;
char		*mail_path=NULL;
char		*AccountantHost=NULL;

/*
 * Hosts.
 */
char	*collector_host=NULL;
char	*alt_collector_host=NULL;

/*
 * Others.
 */
int	last_timeout;
int	capab_timeout;
int	memory;
extern int	Termlog;
char	*MyName;
char	*admin;
int run_benchmarks;

ClassAd* template_ClassAd;

char	*PrimaryStarter=NULL;
char	*AlternateStarter[10];
char	*Starter=NULL;
char	*IP=NULL;

static char *_FileName_ = __FILE__;

extern volatile int want_reconfig;
extern int HasSigchldHandler;
extern bool owner_state;		// see event.C

/*
 * XXX these should not be global.
 */
int coll_sock, intcp_sock, inudp_sock;

/*
 * XXX this should not be needed. Messy include files.
 */

extern char *get_host_cell();

extern void event_sigint(int);
extern void event_sigquit(int);
extern void event_sighup(int);
extern void event_sigterm(int);
extern void event_sigchld(int);

/*
 * Prototypes of static functions.
 */

static void usage(const char *s);
static void init_params(void);
static void mainloop(void);
static char *get_full_hostname(void);
static int res_config_context(resource_info_t *);

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

	if (argc > 3) {
		usage(argv[0]);
		exit(1);
	}

	MyName = argv[0];

	// run as condor.condor at all times unless root privilege is needed
	set_condor_priv();

	while (*++argv) {
		if (*argv[0] != '-') {
			usage(argv[0]);
			exit(1);
		}
		switch(argv[0][1]) {
		case 'f':
			fgflag = 1;
			break;
		case 't':
			Termlog++;
			break;
		default:
			usage(argv[0]);
			exit(1);
		}
	}

	// build the classAd, create a hash table
	template_ClassAd = new ClassAd();
	config( template_ClassAd );

	dprintf_config("STARTD", 2);

	dprintf(D_ALWAYS, "************************************************\n");
	dprintf(D_ALWAYS, "***       CONDOR_STARTD STARTING UP          ***\n");
	dprintf(D_ALWAYS, "************************************************\n");
	dprintf(D_ALWAYS, "\n");

	CondorPrefExps::Initialize(template_ClassAd);

	resmgr_init();
	init_params();
	resource_init();

	event_timeout();

	if (chdir(log_path) < 0) {
		EXCEPT("chdir to log directory %s", log_path);
	}

	if (!fgflag) {
		if (fork())
			exit(0);
	}

	/*
	 * XXX Use DaemonCore for signal handling.
	 */
	install_sig_handler(SIGINT, event_sigint);
	install_sig_handler(SIGQUIT, event_sigquit);
	install_sig_handler(SIGHUP, event_sighup);
	install_sig_handler(SIGTERM, event_sigterm);
	install_sig_handler(SIGCHLD, event_sigchld);
	install_sig_handler(SIGPIPE, SIG_IGN );
	HasSigchldHandler = 1;	/* XXX yucky */

	intcp_sock = create_tcpsock("condor_startd", START_PORT);
	inudp_sock = create_udpsock("condor_startd", START_UDP_PORT);
	coll_sock = udp_unconnect();

	/*
	 * XXX replace with DaemonCore
	 */

	mainloop();

	return 0;
}

static int res_config_context(resource_info_t* rip)
{
	config( rip->r_context );
}

static void usage(const char* s)
{
	dprintf(D_ALWAYS, "Usage: %s [-f] [-t]\n", s);
}

static void mainloop()
{
	fd_set readfds;
	int count;
	struct timeval timer;

	for (;;) {
		FD_ZERO(&readfds);
		resmgr_setsocks(&readfds);
		timer.tv_usec = 0;

		if (owner_state) {
			timer.tv_sec = owner_polling_freq -
				((int)time((time_t *)0) - last_timeout);
			if (timer.tv_sec > owner_polling_freq)
				timer.tv_sec = 0;
		} else {
			timer.tv_sec = polling_freq -
				((int)time((time_t *)0) - last_timeout);
			if (timer.tv_sec > polling_freq)
				timer.tv_sec = 0;
		}

		if(timer.tv_sec < 0)
			timer.tv_sec = 0;

#if defined(AIX31) || defined(AIX32)
		errno = EINTR;
#endif
		count = select(FD_SETSIZE, &readfds, (fd_set *)0, (fd_set *)0,
			       &timer);

		if (want_reconfig) {
			dprintf( D_ALWAYS, "Re reading config file\n" );
			dprintf_config("STARTD", 2);
			resmgr_walk(res_config_context);
			init_params();
			want_reconfig = 0;
		}

		if (count < 0) {
			if (errno == EINTR)
				continue;
			else {
				EXCEPT("select(FD_SETSIZE,0%o,0,0,%d sec)",
					readfds, timer.tv_sec);
			}
		}

		if (NFDS(count) == 0)
			event_timeout();
		else
			resmgr_call(&readfds);
	}
}

static void init_params()
{
	char *tmp, *pval, buf[1024];
	int i;

	if (log_path)
		free(log_path);
	log_path = param("LOG");
	if (log_path == NULL) {
		EXCEPT("No log directory specified in config file");
	}

	if (exec_path)
		free(exec_path);
	exec_path = param("EXECUTE");
	if (exec_path == NULL) {
		EXCEPT("No Execute file specified in config file");
	}

	if (collector_host)
		free(collector_host);
	collector_host = param("COLLECTOR_HOST");
	if (collector_host == NULL) {
		EXCEPT("No Collector host specified in config file");
	}

	if (alt_collector_host)
		free(alt_collector_host);
	alt_collector_host = param("CONDOR_VIEW_HOST");

	tmp = param("POLLING_FREQUENCY");
	if (tmp == NULL) {
		polling_freq = 30;
	} else {
		polling_freq = atoi(tmp);
		free(tmp);
	}

	tmp = param("OWNER_POLLING_FREQUENCY");
	if (tmp == NULL) {
		owner_polling_freq = polling_freq;
	} else {
		owner_polling_freq = atoi(tmp);
		free(tmp);
	}

	tmp = param("POLLS_PER_UPDATE");
	if (tmp == NULL) {
		polls_per_update = 4;
	} else {
		polls_per_update = atoi(tmp);
	}

	tmp = param("POLLS_PER_UPDATE_KBDD");
	if (tmp == NULL) {
		polls_per_update_kbdd = 6;
	} else {
		polls_per_update_kbdd = atoi(tmp);
		free(tmp);
	}

	tmp = param( "POLLS_PER_UPDATE_LOAD" );
	if(tmp == NULL) {
		polls_per_update_load = 12;
	} else {
		polls_per_update_load = atoi( tmp );
		free(tmp);
	}

	tmp = param("STARTD_DEBUG");
	if (tmp == NULL ) {
		EXCEPT("STARTD_DEBUG not defined in config file");
	}
	free(tmp);
	if (!fgflag)
		fgflag = boolean("STARTD_DEBUG", "Foreground");

	if (admin)
		free(admin);
	admin = param("CONDOR_ADMIN");
	if (admin == NULL ) {
		EXCEPT("CONDOR_ADMIN not specified in config file");
	}

	tmp = param("MEMORY");
	if (tmp != NULL) {
		memory = atoi(tmp);
		free(tmp);
	}
	if (memory <= 0) {
		memory =  DEFAULT_MEMORY;
	}

	if (spool_path)
		free(spool_path);
	spool_path = param("SPOOL");
	if (spool_path == NULL) {
		EXCEPT("SPOOL not specified in config file");
	}

	if (mail_path)
		free(mail_path);
	mail_path = param("MAIL");
	if (mail_path == NULL) {
		EXCEPT("MAIL not specified in config file");
	}

	PrimaryStarter = param("STARTER");
	if (PrimaryStarter == NULL) {
		EXCEPT("No Starter file specified in config file\n");
	}
	Starter = PrimaryStarter;

	for (i = 0; i < 10; i++ ) {
		sprintf(buf, "ALTERNATE_STARTER_%d", i);
		AlternateStarter[i] = param(buf);
	}

	if (IP)
		free(IP);
	IP = param("STARTD_IP");

	if (AccountantHost)
		free(AccountantHost);
	AccountantHost = param("ACCOUNTANT_HOST");

	tmp = param("CAPABILITY_TIMEOUT");
	if (!tmp)
		capab_timeout = 120;
	else {
		capab_timeout = atoi(tmp);
		free(tmp);
	}

	tmp = param("RUN_BENCHMARKS");
	if (!tmp)
		run_benchmarks = 1;	  // default to True !
	else {
		if ( *tmp == 'T' || *tmp == 't' )
			run_benchmarks = 1;
		else
			run_benchmarks = 0;
		free(tmp);
	}
}

<commit_msg>stash errno after select call in case reconfig tramples the errno value<commit_after>/*
 * Main routine and function for the startd.
 */

#include "condor_common.h"

/*
 * System include files.
 */
#include <netdb.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <netinet/in.h>
#if !defined(LINUX) && !defined(HPUX9)
#include <sys/select.h>
#endif

/*
 * Condor include files.
 */
#include "debug.h"
#include "trace.h"
#include "except.h"
#include "sched.h"
#include "condor_types.h"
#include "expr.h"
#include "clib.h"
#include "util_lib_proto.h"
#include "condor_uid.h"

#include "resource.h"
#include "resmgr.h"

#include "CondorPrefExps.h"

/*
 * Polling vars.
 */
static int	polling_freq;
static int	owner_polling_freq;
int	polls_per_update;
static int	polls_per_update_kbdd; // never used!
static int	polls_per_update_load; // never used!

/*
 * Flags from the commandline.
 */
int	fgflag;
int	tflag;

/*
 * Paths.
 */
char		*log_path=NULL;
char		*spool_path=NULL;
char		*exec_path=NULL;
char		*mail_path=NULL;
char		*AccountantHost=NULL;

/*
 * Hosts.
 */
char	*collector_host=NULL;
char	*alt_collector_host=NULL;

/*
 * Others.
 */
int	last_timeout;
int	capab_timeout;
int	memory;
extern int	Termlog;
char	*MyName;
char	*admin;
int run_benchmarks;

ClassAd* template_ClassAd;

char	*PrimaryStarter=NULL;
char	*AlternateStarter[10];
char	*Starter=NULL;
char	*IP=NULL;

static char *_FileName_ = __FILE__;

extern volatile int want_reconfig;
extern int HasSigchldHandler;
extern bool owner_state;		// see event.C

/*
 * XXX these should not be global.
 */
int coll_sock, intcp_sock, inudp_sock;

/*
 * XXX this should not be needed. Messy include files.
 */

extern char *get_host_cell();

extern void event_sigint(int);
extern void event_sigquit(int);
extern void event_sighup(int);
extern void event_sigterm(int);
extern void event_sigchld(int);

/*
 * Prototypes of static functions.
 */

static void usage(const char *s);
static void init_params(void);
static void mainloop(void);
static char *get_full_hostname(void);
static int res_config_context(resource_info_t *);

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

	if (argc > 3) {
		usage(argv[0]);
		exit(1);
	}

	MyName = argv[0];

	// run as condor.condor at all times unless root privilege is needed
	set_condor_priv();

	while (*++argv) {
		if (*argv[0] != '-') {
			usage(argv[0]);
			exit(1);
		}
		switch(argv[0][1]) {
		case 'f':
			fgflag = 1;
			break;
		case 't':
			Termlog++;
			break;
		default:
			usage(argv[0]);
			exit(1);
		}
	}

	// build the classAd, create a hash table
	template_ClassAd = new ClassAd();
	config( template_ClassAd );

	dprintf_config("STARTD", 2);

	dprintf(D_ALWAYS, "************************************************\n");
	dprintf(D_ALWAYS, "***       CONDOR_STARTD STARTING UP          ***\n");
	dprintf(D_ALWAYS, "************************************************\n");
	dprintf(D_ALWAYS, "\n");

	CondorPrefExps::Initialize(template_ClassAd);

	init_params();
	resmgr_init();
	resource_init();

	event_timeout();

	if (chdir(log_path) < 0) {
		EXCEPT("chdir to log directory %s", log_path);
	}

	if (!fgflag) {
		if (fork())
			exit(0);
	}

	/*
	 * XXX Use DaemonCore for signal handling.
	 */
	install_sig_handler(SIGINT, event_sigint);
	install_sig_handler(SIGQUIT, event_sigquit);
	install_sig_handler(SIGHUP, event_sighup);
	install_sig_handler(SIGTERM, event_sigterm);
	install_sig_handler(SIGCHLD, event_sigchld);
	install_sig_handler(SIGPIPE, SIG_IGN );
	HasSigchldHandler = 1;	/* XXX yucky */

	intcp_sock = create_tcpsock("condor_startd", START_PORT);
	inudp_sock = create_udpsock("condor_startd", START_UDP_PORT);
	coll_sock = udp_unconnect();

	/*
	 * XXX replace with DaemonCore
	 */

	mainloop();

	return 0;
}

static int res_config_context(resource_info_t* rip)
{
	config( rip->r_context );
}

static void usage(const char* s)
{
	dprintf(D_ALWAYS, "Usage: %s [-f] [-t]\n", s);
}

static void mainloop()
{
	fd_set readfds;
	int count;
	struct timeval timer;
	int stashed_errno;

	for (;;) {
		FD_ZERO(&readfds);
		resmgr_setsocks(&readfds);
		timer.tv_usec = 0;

		if (owner_state) {
			timer.tv_sec = owner_polling_freq -
				((int)time((time_t *)0) - last_timeout);
			if (timer.tv_sec > owner_polling_freq)
				timer.tv_sec = 0;
		} else {
			timer.tv_sec = polling_freq -
				((int)time((time_t *)0) - last_timeout);
			if (timer.tv_sec > polling_freq)
				timer.tv_sec = 0;
		}

		if(timer.tv_sec < 0)
			timer.tv_sec = 0;

#if defined(AIX31) || defined(AIX32)
		errno = EINTR;
#endif
		count = select(FD_SETSIZE, &readfds, (fd_set *)0, (fd_set *)0,
			       &timer);
		stashed_errno = errno;	// reconfig will trample our errno

		if (want_reconfig) {
			dprintf( D_ALWAYS, "Re reading config file\n" );
			dprintf_config("STARTD", 2);
			resmgr_walk(res_config_context);
			init_params();
			want_reconfig = 0;
		}

		if (count < 0) {
			if (stashed_errno == EINTR)
				continue;
			else {
				EXCEPT("select(FD_SETSIZE,0%o,0,0,%d sec)",
					readfds, timer.tv_sec);
			}
		}

		if (NFDS(count) == 0)
			event_timeout();
		else
			resmgr_call(&readfds);
	}
}

static void init_params()
{
	char *tmp, *pval, buf[1024];
	int i;

	if (log_path)
		free(log_path);
	log_path = param("LOG");
	if (log_path == NULL) {
		EXCEPT("No log directory specified in config file");
	}

	if (exec_path)
		free(exec_path);
	exec_path = param("EXECUTE");
	if (exec_path == NULL) {
		EXCEPT("No Execute file specified in config file");
	}

	if (collector_host)
		free(collector_host);
	collector_host = param("COLLECTOR_HOST");
	if (collector_host == NULL) {
		EXCEPT("No Collector host specified in config file");
	}

	if (alt_collector_host)
		free(alt_collector_host);
	alt_collector_host = param("CONDOR_VIEW_HOST");

	tmp = param("POLLING_FREQUENCY");
	if (tmp == NULL) {
		polling_freq = 30;
	} else {
		polling_freq = atoi(tmp);
		free(tmp);
	}

	tmp = param("OWNER_POLLING_FREQUENCY");
	if (tmp == NULL) {
		owner_polling_freq = polling_freq;
	} else {
		owner_polling_freq = atoi(tmp);
		free(tmp);
	}

	tmp = param("POLLS_PER_UPDATE");
	if (tmp == NULL) {
		polls_per_update = 4;
	} else {
		polls_per_update = atoi(tmp);
	}

	tmp = param("POLLS_PER_UPDATE_KBDD");
	if (tmp == NULL) {
		polls_per_update_kbdd = 6;
	} else {
		polls_per_update_kbdd = atoi(tmp);
		free(tmp);
	}

	tmp = param( "POLLS_PER_UPDATE_LOAD" );
	if(tmp == NULL) {
		polls_per_update_load = 12;
	} else {
		polls_per_update_load = atoi( tmp );
		free(tmp);
	}

	tmp = param("STARTD_DEBUG");
	if (tmp == NULL ) {
		EXCEPT("STARTD_DEBUG not defined in config file");
	}
	free(tmp);
	if (!fgflag)
		fgflag = boolean("STARTD_DEBUG", "Foreground");

	if (admin)
		free(admin);
	admin = param("CONDOR_ADMIN");
	if (admin == NULL ) {
		EXCEPT("CONDOR_ADMIN not specified in config file");
	}

	tmp = param("MEMORY");
	if (tmp != NULL) {
		memory = atoi(tmp);
		free(tmp);
	}
	if (memory <= 0) {
		memory =  DEFAULT_MEMORY;
	}

	if (spool_path)
		free(spool_path);
	spool_path = param("SPOOL");
	if (spool_path == NULL) {
		EXCEPT("SPOOL not specified in config file");
	}

	if (mail_path)
		free(mail_path);
	mail_path = param("MAIL");
	if (mail_path == NULL) {
		EXCEPT("MAIL not specified in config file");
	}

	PrimaryStarter = param("STARTER");
	if (PrimaryStarter == NULL) {
		EXCEPT("No Starter file specified in config file\n");
	}
	Starter = PrimaryStarter;

	for (i = 0; i < 10; i++ ) {
		sprintf(buf, "ALTERNATE_STARTER_%d", i);
		AlternateStarter[i] = param(buf);
	}

	if (IP)
		free(IP);
	IP = param("STARTD_IP");

	if (AccountantHost)
		free(AccountantHost);
	AccountantHost = param("ACCOUNTANT_HOST");

	tmp = param("CAPABILITY_TIMEOUT");
	if (!tmp)
		capab_timeout = 120;
	else {
		capab_timeout = atoi(tmp);
		free(tmp);
	}

	tmp = param("RUN_BENCHMARKS");
	if (!tmp)
		run_benchmarks = 1;	  // default to True !
	else {
		if ( *tmp == 'T' || *tmp == 't' )
			run_benchmarks = 1;
		else
			run_benchmarks = 0;
		free(tmp);
	}
}

<|endoftext|>


<commit_before>#include "precomp.hpp"

#include <iostream>
#include <iomanip>

using namespace std;
using namespace cv;

void helpParser()
{
    printf("\nThe CommandLineParser class is designed for command line arguments parsing\n"
           "Keys map: \n"
           "Before you start to work with CommandLineParser you have to create a map for keys.\n"
           "    It will look like this\n"
           "    const char* keys =\n"
           "    {\n"
           "        {    s|  string|  123asd |string parameter}\n"
           "        {    d|  digit |  100    |digit parameter }\n"
           "        {    c|noCamera|false    |without camera  }\n"
           "        {    1|        |some text|help            }\n"
           "        {    2|        |333      |another help    }\n"
           "    };\n"
           "Usage syntax: \n"
           "    \"{\" - start of parameter string.\n"
           "    \"}\" - end of parameter string\n"
           "    \"|\" - separator between short name, full name, default value and help\n"
           "Supported syntax: \n"
           "    --key1=arg1  <If a key with '--' must has an argument\n"
           "                  you have to assign it through '=' sign.> \n"
           "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n"
           "    -key2=arg2   <If a key with '-' must has an argument \n"
           "                  you have to assign it through '=' sign.> \n"
           "If the key with '-' doesn't have any argument, it means that it is a bool key\n"
           "    key3                 <This key can't has any parameter> \n"
           "Usage: \n"
           "      Imagine that the input parameters are next:\n"
           "                -s=string_value --digit=250 --noCamera lena.jpg 10000\n"
           "    CommandLineParser parser(argc, argv, keys) - create a parser object\n"
           "    parser.get<string>(\"s\" or \"string\") will return you first parameter value\n"
           "    parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n"
           "                                                                without spaces in end and begin\n"
           "    parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n"
           "                    It also works with 'unsigned int', 'double', and 'float' types>\n"
           "    parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n"
           "                                If you enter this key in commandline>\n"
           "                                It return you false otherwise.\n"
           "    parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n"
           "    parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n"
           "                          It also works with 'unsigned int', 'double', and 'float' types \n"
           );
}

vector<string> split_string(const string& str, const string& delimiters)
{
	vector<string> res;

	string split_str = str;
	size_t pos_delim = split_str.find(delimiters);

	while ( pos_delim != string::npos)
	{
		if (pos_delim == 0)
		{
			res.push_back("");
			split_str.erase(0, 1);
		}
		else
		{
			res.push_back(split_str.substr(0, pos_delim));
			split_str.erase(0, pos_delim + 1);
		}

		pos_delim = split_str.find(delimiters);
	}

	res.push_back(split_str);

	return res;
}

CommandLineParser::CommandLineParser(int argc, const char* const argv[], const char* keys)
{
	std::string keys_buffer;
    std::string values_buffer;
    std::string buffer;
    std::string curName;
    std::vector<string> keysVector;
    std::vector<string> paramVector;
    std::map<std::string, std::vector<std::string> >::iterator it;
    size_t flagPosition;
    int currentIndex = 1;
    bool isFound = false;
    bool withNoKey = false;
    bool hasValueThroughEq = false;

    keys_buffer = keys;
    while (!keys_buffer.empty())
    {

        flagPosition = keys_buffer.find_first_of('}');
        flagPosition++;
        buffer = keys_buffer.substr(0, flagPosition);
        keys_buffer.erase(0, flagPosition);

        flagPosition = buffer.find('{');
        if (flagPosition != buffer.npos)
            buffer.erase(flagPosition, (flagPosition + 1));

        flagPosition = buffer.find('}');
        if (flagPosition != buffer.npos)
            buffer.erase(flagPosition);

        paramVector = split_string(buffer, "|");
		while (paramVector.size() < 4) paramVector.push_back("");

		buffer = paramVector[0];
		buffer += '|' + paramVector[1];

		//if (buffer == "") CV_ERROR(CV_StsBadArg, "In CommandLineParser need set short and full name");

		paramVector.erase(paramVector.begin(), paramVector.begin() + 2);
        data[buffer] = paramVector;
    }

    buffer.clear();
    keys_buffer.clear();
    paramVector.clear();
    for (int i = 1; i < argc; i++)
    {
        if (!argv[i])
            break;
        curName = argv[i];
        if (curName.find('-') == 0 && ((curName[1] < '0') || (curName[1] > '9')))
        {
            while (curName.find('-') == 0)
                curName.erase(curName.begin(), (curName.begin() + 1));
        }
            else
                withNoKey = true;
        if (curName.find('=') != curName.npos)
        {
            hasValueThroughEq = true;
            buffer = curName;
            curName.erase(curName.find('='));
            buffer.erase(0, (buffer.find('=') + 1));
        }

        for(it = data.begin(); it != data.end(); it++)
        {
            keys_buffer = it->first;
            keysVector = split_string(keys_buffer, "|");
            if (keysVector.size() == 1)
                keysVector.push_back("");
            values_buffer = it->second[0];
            if (((curName == keysVector[0]) || (curName == keysVector[1])) && hasValueThroughEq)
            {
                it->second[0] = buffer;
                isFound = true;
                break;
            }

            if (!hasValueThroughEq && (values_buffer.find("false") == values_buffer.npos) &&
                ((curName == keysVector[0]) || (curName == keysVector[1])))

            {
                it->second[0] = argv[++i];
                isFound = true;
                break;
            }

            if (!hasValueThroughEq &&  (values_buffer.find("false") != values_buffer.npos)
                && ((curName == keysVector[0]) || (curName == keysVector[1])))

            {
                it->second[0] = "true";
                isFound = true;
                break;
            }

            if (withNoKey)
            {
                std::string noKeyStr = it->first;
                if(atoi(noKeyStr.c_str()) == currentIndex)
                {
                    it->second[0] = curName;
                    currentIndex++;
                    isFound = true;
                    break;
                }
            }
        }

        withNoKey = false;
        hasValueThroughEq = false;
        if(!isFound)
            printf("The current parameter is not defined: %s\n", curName.c_str());
        isFound = false;
    }
}

string del_space(string name)
{
	while ((name.find_first_of(' ') == 0)  && (name.length() > 0))
		name.erase(0, 1);

	while ((name.find_last_of(' ') == (name.length() - 1)) && (name.length() > 0))
		name.erase(name.end() - 1, name.end());

	return name;
}

bool CommandLineParser::has(const std::string& keys)
{
    std::map<std::string, std::vector<std::string> >::iterator it;
    std::vector<string> keysVector;

    for(it = data.begin(); it != data.end(); it++)
    {
        keysVector = split_string(it->first, "|");
		for (int i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]);

        if (keysVector.size() == 1) keysVector.push_back("");

		if ((del_space(keys).compare(keysVector[0]) == 0) ||
			(del_space(keys).compare(keysVector[1]) == 0))
            return true;
    }

    return false;
}

std::string CommandLineParser::getString(const std::string& keys)
{
    std::map<std::string, std::vector<std::string> >::iterator it;
    std::vector<string> valueVector;

    for(it = data.begin(); it != data.end(); it++)
    {
        valueVector = split_string(it->first, "|");
		for (int i = 0; i < valueVector.size(); i++) valueVector[i] = del_space(valueVector[i]);

        if (valueVector.size() == 1) valueVector.push_back("");

		if ((del_space(keys).compare(valueVector[0]) == 0) ||
			(del_space(keys).compare(valueVector[1]) == 0))
            return it->second[0];
    }
    return string();
}

template<typename _Tp>
 _Tp CommandLineParser::fromStringNumber(const std::string& str)//the default conversion function for numbers
{
    return getData<_Tp>(str);
}

 void CommandLineParser::printParams()
 {
	std::map<std::string, std::vector<std::string> >::iterator it;
	std::vector<string> keysVector;
	std::string buf;
	for(it = data.begin(); it != data.end(); it++)
	{
		keysVector = split_string(it->first, "|");
		for (int i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]);

		cout << "  ";
		if (keysVector[0] != "")
		{
			buf = "-" + keysVector[0];
			if (keysVector[1] != "") buf += ", --" + keysVector[1];
		}
		else if (keysVector[1] != "") buf += "--" + keysVector[1];
		if (del_space(it->second[0]) != "") buf += "=[" + del_space(it->second[0]) + "]";

		cout << setw(28) << left << buf;

		buf = "";
		if (del_space(it->second[1]) != "") buf += del_space(it->second[1]);

		cout << setw(50) << left << buf << endl;
	}
 }

template<>
bool CommandLineParser::get<bool>(const std::string& name, bool space_delete)
{
    std::string str_buf = getString(name);

	if (space_delete && str_buf != "")
    {
		str_buf = del_space(str_buf);
    }

    if (str_buf == "true")
        return true;

    return false;
}
template<>
std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete)
{
    if (space_delete)
    {
		return del_space(str);
    }
    return str;
}

template<>
int CommandLineParser::analyzeValue<int>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<int>(str);
}

template<>
unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<unsigned int>(str);
}

template<>
uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<uint64>(str);
}

template<>
float CommandLineParser::analyzeValue<float>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<float>(str);
}

template<>
double CommandLineParser::analyzeValue<double>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<double>(str);
}
<commit_msg>fixed several bugs in CommandLineParser<commit_after>#include "precomp.hpp"

#include <iostream>
#include <iomanip>

using namespace std;
using namespace cv;

void helpParser()
{
    printf("\nThe CommandLineParser class is designed for command line arguments parsing\n"
           "Keys map: \n"
           "Before you start to work with CommandLineParser you have to create a map for keys.\n"
           "    It will look like this\n"
           "    const char* keys =\n"
           "    {\n"
           "        {    s|  string|  123asd |string parameter}\n"
           "        {    d|  digit |  100    |digit parameter }\n"
           "        {    c|noCamera|false    |without camera  }\n"
           "        {    1|        |some text|help            }\n"
           "        {    2|        |333      |another help    }\n"
           "    };\n"
           "Usage syntax: \n"
           "    \"{\" - start of parameter string.\n"
           "    \"}\" - end of parameter string\n"
           "    \"|\" - separator between short name, full name, default value and help\n"
           "Supported syntax: \n"
           "    --key1=arg1  <If a key with '--' must has an argument\n"
           "                  you have to assign it through '=' sign.> \n"
           "<If the key with '--' doesn't have any argument, it means that it is a bool key>\n"
           "    -key2=arg2   <If a key with '-' must has an argument \n"
           "                  you have to assign it through '=' sign.> \n"
           "If the key with '-' doesn't have any argument, it means that it is a bool key\n"
           "    key3                 <This key can't has any parameter> \n"
           "Usage: \n"
           "      Imagine that the input parameters are next:\n"
           "                -s=string_value --digit=250 --noCamera lena.jpg 10000\n"
           "    CommandLineParser parser(argc, argv, keys) - create a parser object\n"
           "    parser.get<string>(\"s\" or \"string\") will return you first parameter value\n"
           "    parser.get<string>(\"s\", false or \"string\", false) will return you first parameter value\n"
           "                                                                without spaces in end and begin\n"
           "    parser.get<int>(\"d\" or \"digit\") will return you second parameter value.\n"
           "                    It also works with 'unsigned int', 'double', and 'float' types>\n"
           "    parser.get<bool>(\"c\" or \"noCamera\") will return you true .\n"
           "                                If you enter this key in commandline>\n"
           "                                It return you false otherwise.\n"
           "    parser.get<string>(\"1\") will return you the first argument without parameter (lena.jpg) \n"
           "    parser.get<int>(\"2\") will return you the second argument without parameter (10000)\n"
           "                          It also works with 'unsigned int', 'double', and 'float' types \n"
           );
}

vector<string> split_string(const string& str, const string& delimiters)
{
	vector<string> res;

	string split_str = str;
	size_t pos_delim = split_str.find(delimiters);

	while ( pos_delim != string::npos)
	{
		if (pos_delim == 0)
		{
			res.push_back("");
			split_str.erase(0, 1);
		}
		else
		{
			res.push_back(split_str.substr(0, pos_delim));
			split_str.erase(0, pos_delim + 1);
		}

		pos_delim = split_str.find(delimiters);
	}

	res.push_back(split_str);

	return res;
}

string del_space(string name)
{
	while ((name.find_first_of(' ') == 0)  && (name.length() > 0))
		name.erase(0, 1);

	while ((name.find_last_of(' ') == (name.length() - 1)) && (name.length() > 0))
		name.erase(name.end() - 1, name.end());

	return name;
}

CommandLineParser::CommandLineParser(int argc, const char* const argv[], const char* keys)
{
	std::string keys_buffer;
    std::string values_buffer;
    std::string buffer;
    std::string curName;
    std::vector<string> keysVector;
    std::vector<string> paramVector;
    std::map<std::string, std::vector<std::string> >::iterator it;
    size_t flagPosition;
    int currentIndex = 1;
    bool isFound = false;
    bool withNoKey = false;
    bool hasValueThroughEq = false;

    keys_buffer = keys;
    while (!keys_buffer.empty())
    {

        flagPosition = keys_buffer.find_first_of('}');
        flagPosition++;
        buffer = keys_buffer.substr(0, flagPosition);
        keys_buffer.erase(0, flagPosition);

        flagPosition = buffer.find('{');
        if (flagPosition != buffer.npos)
            buffer.erase(flagPosition, (flagPosition + 1));

        flagPosition = buffer.find('}');
        if (flagPosition != buffer.npos)
            buffer.erase(flagPosition);

        paramVector = split_string(buffer, "|");
		while (paramVector.size() < 4) paramVector.push_back("");

		buffer = paramVector[0];
		buffer += '|' + paramVector[1];

		//if (buffer == "") CV_ERROR(CV_StsBadArg, "In CommandLineParser need set short and full name");

		paramVector.erase(paramVector.begin(), paramVector.begin() + 2);
        data[buffer] = paramVector;
    }

    buffer.clear();
    keys_buffer.clear();
    paramVector.clear();
    for (int i = 1; i < argc; i++)
    {
        if (!argv[i])
            break;
        curName = argv[i];
        if (curName.find('-') == 0 && ((curName[1] < '0') || (curName[1] > '9')))
        {
            while (curName.find('-') == 0)
                curName.erase(curName.begin(), (curName.begin() + 1));
        }
            else
                withNoKey = true;
        if (curName.find('=') != curName.npos)
        {
            hasValueThroughEq = true;
            buffer = curName;
            curName.erase(curName.find('='));
            buffer.erase(0, (buffer.find('=') + 1));
        }

		values_buffer = del_space(values_buffer);

        for(it = data.begin(); it != data.end(); it++)
        {
            keys_buffer = it->first;
            keysVector = split_string(keys_buffer, "|");

			for (int j = 0; j < keysVector.size(); j++) keysVector[j] = del_space(keysVector[j]);

            values_buffer = it->second[0];
            if (((curName == keysVector[0]) || (curName == keysVector[1])) && hasValueThroughEq)
            {
                it->second[0] = buffer;
                isFound = true;
                break;
            }

            if (!hasValueThroughEq && ((curName == keysVector[0]) || (curName == keysVector[1]))
				&& (
					values_buffer.find("false") != values_buffer.npos ||
					values_buffer == ""
				))
            {
                it->second[0] = "true";
                isFound = true;
                break;
            }

            if (!hasValueThroughEq && (values_buffer.find("false") == values_buffer.npos) &&
                ((curName == keysVector[0]) || (curName == keysVector[1])))
            {
                it->second[0] = argv[++i];
                isFound = true;
                break;
            }

            if (withNoKey)
            {
                std::string noKeyStr = it->first;
                if(atoi(noKeyStr.c_str()) == currentIndex)
                {
                    it->second[0] = curName;
                    currentIndex++;
                    isFound = true;
                    break;
                }
            }
        }

        withNoKey = false;
        hasValueThroughEq = false;
        if(!isFound)
            printf("The current parameter is not defined: %s\n", curName.c_str());
        isFound = false;
    }
}

bool CommandLineParser::has(const std::string& keys)
{
    std::map<std::string, std::vector<std::string> >::iterator it;
    std::vector<string> keysVector;

    for(it = data.begin(); it != data.end(); it++)
    {
        keysVector = split_string(it->first, "|");
		for (int i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]);

        if (keysVector.size() == 1) keysVector.push_back("");

		if ((del_space(keys).compare(keysVector[0]) == 0) ||
			(del_space(keys).compare(keysVector[1]) == 0))
            return true;
    }

    return false;
}

std::string CommandLineParser::getString(const std::string& keys)
{
    std::map<std::string, std::vector<std::string> >::iterator it;
    std::vector<string> valueVector;

    for(it = data.begin(); it != data.end(); it++)
    {
        valueVector = split_string(it->first, "|");
		for (int i = 0; i < valueVector.size(); i++) valueVector[i] = del_space(valueVector[i]);

        if (valueVector.size() == 1) valueVector.push_back("");

		if ((del_space(keys).compare(valueVector[0]) == 0) ||
			(del_space(keys).compare(valueVector[1]) == 0))
            return it->second[0];
    }
    return string();
}

template<typename _Tp>
 _Tp CommandLineParser::fromStringNumber(const std::string& str)//the default conversion function for numbers
{
    return getData<_Tp>(str);
}

 void CommandLineParser::printParams()
 {
	std::map<std::string, std::vector<std::string> >::iterator it;
	std::vector<string> keysVector;
	std::string buf;
	for(it = data.begin(); it != data.end(); it++)
	{
		keysVector = split_string(it->first, "|");
		for (int i = 0; i < keysVector.size(); i++) keysVector[i] = del_space(keysVector[i]);

		cout << "  ";
		if (keysVector[0] != "")
		{
			buf = "-" + keysVector[0];
			if (keysVector[1] != "") buf += ", --" + keysVector[1];
		}
		else if (keysVector[1] != "") buf += "--" + keysVector[1];
		if (del_space(it->second[0]) != "") buf += "=[" + del_space(it->second[0]) + "]";

		cout << setw(28) << left << buf;

		buf = "";
		if (del_space(it->second[1]) != "") buf += del_space(it->second[1]);

		cout << setw(50) << left << buf << endl;
	}
 }

template<>
bool CommandLineParser::get<bool>(const std::string& name, bool space_delete)
{
    std::string str_buf = getString(name);

	if (space_delete && str_buf != "")
    {
		str_buf = del_space(str_buf);
    }

    if (str_buf == "true")
        return true;

    return false;
}
template<>
std::string CommandLineParser::analyzeValue<std::string>(const std::string& str, bool space_delete)
{
    if (space_delete)
    {
		return del_space(str);
    }
    return str;
}

template<>
int CommandLineParser::analyzeValue<int>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<int>(str);
}

template<>
unsigned int CommandLineParser::analyzeValue<unsigned int>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<unsigned int>(str);
}

template<>
uint64 CommandLineParser::analyzeValue<uint64>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<uint64>(str);
}

template<>
float CommandLineParser::analyzeValue<float>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<float>(str);
}

template<>
double CommandLineParser::analyzeValue<double>(const std::string& str, bool /*space_delete*/)
{
    return fromStringNumber<double>(str);
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "skia/ext/bitmap_platform_device_linux.h"

#include "skia/ext/bitmap_platform_device_data.h"

#include <cairo/cairo.h>

namespace skia {

namespace {

void LoadMatrixToContext(cairo_t* context, const SkMatrix& matrix) {
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(matrix.getScaleX()),
                    SkScalarToFloat(matrix.getSkewY()),
                    SkScalarToFloat(matrix.getSkewX()),
                    SkScalarToFloat(matrix.getScaleY()),
                    SkScalarToFloat(matrix.getTranslateX()),
                    SkScalarToFloat(matrix.getTranslateY()));
  cairo_set_matrix(context, &cairo_matrix);
}

void LoadClipToContext(cairo_t* context, const SkRegion& clip) {
  cairo_reset_clip(context);

  // TODO(brettw) support non-rect clips.
  SkIRect bounding = clip.getBounds();
  cairo_rectangle(context, bounding.fLeft, bounding.fTop,
                  bounding.fRight - bounding.fLeft,
                  bounding.fBottom - bounding.fTop);
  cairo_clip(context);
}

}  // namespace

SkDevice* BitmapPlatformDeviceFactory::newDevice(SkBitmap::Config config,
                                                 int width, int height,
                                                 bool isOpaque,
                                                 bool isForLayer) {
  SkASSERT(config == SkBitmap::kARGB_8888_Config);
  return BitmapPlatformDevice::Create(width, height, isOpaque);
}

BitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData(
    cairo_surface_t* surface)
    : surface_(surface),
      config_dirty_(true) {  // Want to load the config next time.
  bitmap_context_ = cairo_create(surface);
}

BitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() {
  cairo_destroy(bitmap_context_);
  cairo_surface_destroy(surface_);
}

void BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip(
    const SkMatrix& transform,
    const SkRegion& region) {
  transform_ = transform;
  clip_region_ = region;
  config_dirty_ = true;
}

void BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() {
  if (!config_dirty_ || !bitmap_context_)
    return;  // Nothing to do.
  config_dirty_ = false;

  // Load the identity matrix since this is what our clip is relative to.
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init_identity(&cairo_matrix);
  cairo_set_matrix(bitmap_context_, &cairo_matrix);

  LoadClipToContext(bitmap_context_, clip_region_);
  LoadMatrixToContext(bitmap_context_, transform_);
}

// We use this static factory function instead of the regular constructor so
// that we can create the pixel data before calling the constructor. This is
// required so that we can call the base class' constructor with the pixel
// data.
BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque,
                                                   cairo_surface_t* surface) {
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height,
                   cairo_image_surface_get_stride(surface));
  bitmap.setPixels(cairo_image_surface_get_data(surface));
  bitmap.setIsOpaque(is_opaque);

  // The device object will take ownership of the graphics context.
  return new BitmapPlatformDevice
      (bitmap, new BitmapPlatformDeviceData(surface));
}

BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque) {
  cairo_surface_t* surface =
      cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
                                 width, height);

  BitmapPlatformDevice* device = Create(width, height, is_opaque, surface);

#ifndef NDEBUG
  if (is_opaque)  // Fill with bright bluish green
    device->eraseColor(SkColorSetARGB(255, 0, 255, 128));
#endif

  return device;
}

BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque,
                                                   uint8_t* data) {
  cairo_surface_t* surface = cairo_image_surface_create_for_data(
      data, CAIRO_FORMAT_ARGB32, width, height,
      cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width));

  return Create(width, height, is_opaque, surface);
}

// The device will own the bitmap, which corresponds to also owning the pixel
// data. Therefore, we do not transfer ownership to the SkDevice's bitmap.
BitmapPlatformDevice::BitmapPlatformDevice(
    const SkBitmap& bitmap,
    BitmapPlatformDeviceData* data)
    : PlatformDevice(bitmap),
      data_(data) {
}

BitmapPlatformDevice::BitmapPlatformDevice(
    const BitmapPlatformDevice& other)
    : PlatformDevice(const_cast<BitmapPlatformDevice&>(
                          other).accessBitmap(true)),
      data_(other.data_) {
}

BitmapPlatformDevice::~BitmapPlatformDevice() {
}

SkDeviceFactory* BitmapPlatformDevice::getDeviceFactory() {
  return SkNEW(BitmapPlatformDeviceFactory);
}

bool BitmapPlatformDevice::IsVectorial() {
  return false;
}

cairo_t* BitmapPlatformDevice::beginPlatformPaint() {
  data_->LoadConfig();
  cairo_t* cairo = data_->bitmap_context();
  // Tell Cairo that we've (probably) modified its pixel buffer without
  // its knowledge.
  cairo_surface_mark_dirty(cairo_get_target(cairo));
  return cairo;
}

void BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform,
                                         const SkRegion& region) {
  data_->SetMatrixClip(transform, region);
}

BitmapPlatformDevice& BitmapPlatformDevice::operator=(
    const BitmapPlatformDevice& other) {
  data_ = other.data_;
  return *this;
}

}  // namespace skia
<commit_msg>Flush the cairo surface before we try to write to it.<commit_after>// Copyright (c) 2010 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 "skia/ext/bitmap_platform_device_linux.h"

#include "skia/ext/bitmap_platform_device_data.h"

#include <cairo/cairo.h>

namespace skia {

namespace {

void LoadMatrixToContext(cairo_t* context, const SkMatrix& matrix) {
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(matrix.getScaleX()),
                    SkScalarToFloat(matrix.getSkewY()),
                    SkScalarToFloat(matrix.getSkewX()),
                    SkScalarToFloat(matrix.getScaleY()),
                    SkScalarToFloat(matrix.getTranslateX()),
                    SkScalarToFloat(matrix.getTranslateY()));
  cairo_set_matrix(context, &cairo_matrix);
}

void LoadClipToContext(cairo_t* context, const SkRegion& clip) {
  cairo_reset_clip(context);

  // TODO(brettw) support non-rect clips.
  SkIRect bounding = clip.getBounds();
  cairo_rectangle(context, bounding.fLeft, bounding.fTop,
                  bounding.fRight - bounding.fLeft,
                  bounding.fBottom - bounding.fTop);
  cairo_clip(context);
}

}  // namespace

SkDevice* BitmapPlatformDeviceFactory::newDevice(SkBitmap::Config config,
                                                 int width, int height,
                                                 bool isOpaque,
                                                 bool isForLayer) {
  SkASSERT(config == SkBitmap::kARGB_8888_Config);
  return BitmapPlatformDevice::Create(width, height, isOpaque);
}

BitmapPlatformDevice::BitmapPlatformDeviceData::BitmapPlatformDeviceData(
    cairo_surface_t* surface)
    : surface_(surface),
      config_dirty_(true) {  // Want to load the config next time.
  bitmap_context_ = cairo_create(surface);
}

BitmapPlatformDevice::BitmapPlatformDeviceData::~BitmapPlatformDeviceData() {
  cairo_destroy(bitmap_context_);
  cairo_surface_destroy(surface_);
}

void BitmapPlatformDevice::BitmapPlatformDeviceData::SetMatrixClip(
    const SkMatrix& transform,
    const SkRegion& region) {
  transform_ = transform;
  clip_region_ = region;
  config_dirty_ = true;
}

void BitmapPlatformDevice::BitmapPlatformDeviceData::LoadConfig() {
  if (!config_dirty_ || !bitmap_context_)
    return;  // Nothing to do.
  config_dirty_ = false;

  // Load the identity matrix since this is what our clip is relative to.
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init_identity(&cairo_matrix);
  cairo_set_matrix(bitmap_context_, &cairo_matrix);

  LoadClipToContext(bitmap_context_, clip_region_);
  LoadMatrixToContext(bitmap_context_, transform_);
}

// We use this static factory function instead of the regular constructor so
// that we can create the pixel data before calling the constructor. This is
// required so that we can call the base class' constructor with the pixel
// data.
BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque,
                                                   cairo_surface_t* surface) {
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height,
                   cairo_image_surface_get_stride(surface));
  bitmap.setPixels(cairo_image_surface_get_data(surface));
  bitmap.setIsOpaque(is_opaque);

  // The device object will take ownership of the graphics context.
  return new BitmapPlatformDevice
      (bitmap, new BitmapPlatformDeviceData(surface));
}

BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque) {
  cairo_surface_t* surface =
      cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
                                 width, height);

  BitmapPlatformDevice* device = Create(width, height, is_opaque, surface);

#ifndef NDEBUG
  if (is_opaque)  // Fill with bright bluish green
    device->eraseColor(SkColorSetARGB(255, 0, 255, 128));
#endif

  return device;
}

BitmapPlatformDevice* BitmapPlatformDevice::Create(int width, int height,
                                                   bool is_opaque,
                                                   uint8_t* data) {
  cairo_surface_t* surface = cairo_image_surface_create_for_data(
      data, CAIRO_FORMAT_ARGB32, width, height,
      cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width));

  return Create(width, height, is_opaque, surface);
}

// The device will own the bitmap, which corresponds to also owning the pixel
// data. Therefore, we do not transfer ownership to the SkDevice's bitmap.
BitmapPlatformDevice::BitmapPlatformDevice(
    const SkBitmap& bitmap,
    BitmapPlatformDeviceData* data)
    : PlatformDevice(bitmap),
      data_(data) {
}

BitmapPlatformDevice::BitmapPlatformDevice(
    const BitmapPlatformDevice& other)
    : PlatformDevice(const_cast<BitmapPlatformDevice&>(
                          other).accessBitmap(true)),
      data_(other.data_) {
}

BitmapPlatformDevice::~BitmapPlatformDevice() {
}

SkDeviceFactory* BitmapPlatformDevice::getDeviceFactory() {
  return SkNEW(BitmapPlatformDeviceFactory);
}

bool BitmapPlatformDevice::IsVectorial() {
  return false;
}

cairo_t* BitmapPlatformDevice::beginPlatformPaint() {
  data_->LoadConfig();
  cairo_t* cairo = data_->bitmap_context();
  cairo_surface_t* surface = cairo_get_target(cairo);
  // Tell cairo to flush anything it has pending.
  cairo_surface_flush(surface);
  // Tell Cairo that we (probably) modified (actually, will modify) its pixel
  // buffer directly.
  cairo_surface_mark_dirty(surface);
  return cairo;
}

void BitmapPlatformDevice::setMatrixClip(const SkMatrix& transform,
                                         const SkRegion& region) {
  data_->SetMatrixClip(transform, region);
}

BitmapPlatformDevice& BitmapPlatformDevice::operator=(
    const BitmapPlatformDevice& other) {
  data_ = other.data_;
  return *this;
}

}  // namespace skia
<|endoftext|>