<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <limits>
#include <algorithm>

#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/graphicalmodel/graphicalmodel_hdf5.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/functions/explicit_function.hxx>

// remove leading and ending spaces of given input as this might screw up parsing the input
void removeSpaces(std::string& input);

// compute log of input as network types of type MARKOV store conditional probabilities
template <class T>
void logTransform(T& input);

// sort vector in non descending and compute corresponding permutation vector
template<class T, class U>
void sortingPermutation(const T& values, U& permutation);

// check if vector is in non descending order
template <class T>
bool vecIsSorted(const T& vector);

// transfomrs linear index to subscript values
template <class T, class U, class V>
void ind2sub(T& sub, const U ind, const V& sizes);

int main(int argc, const char* argv[] ) {
   if(argc != 3) {
      std::cerr << "Two input arguments required" << std::endl;
      return 1;
   }

   typedef double ValueType;
   typedef size_t IndexType;
   typedef size_t LabelType;
   typedef opengm::Adder OperatorType;
   typedef opengm::Minimizer AccumulatorType;
   typedef opengm::DiscreteSpace<IndexType, LabelType> SpaceType;

   // Set functions for graphical model
   typedef opengm::meta::TypeListGenerator<
      opengm::ExplicitFunction<ValueType, IndexType, LabelType>
   >::type FunctionTypeList;

   typedef opengm::GraphicalModel<
      ValueType,
      OperatorType,
      FunctionTypeList,
      SpaceType
   > GmType;

   GmType gm;
   std::string opengmfile = argv[1];
   std::string uaifile    = argv[2];

   // open uai file
   std::ifstream myuaifile(uaifile.c_str());
   if(!myuaifile.is_open()) {
      std::cerr << "Could not open file " << uaifile << std::endl;
      return 1;
   }

   // temp storage for current line of uai file
   std::string currentLine;

   // check if type of network is MARKOV
   std::getline(myuaifile, currentLine);
   removeSpaces(currentLine);
   if(currentLine != "MARKOV") {
      std::cerr << "Unsupported network type: \"" << currentLine <<"\". Only networks of type MARKOV are supported by now." << std::endl;
      return 1;
   }

   // get number of variables
   IndexType numVariables;
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (Number of variables is missing)." << std::endl;
      return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      converter >> numVariables;
   }

   // add variables
   if(myuaifile.eof()) {
         std::cerr << "Bad file format: Preamble is incomplete (Cardinalities of variables is missing)." << std::endl;
         return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      IndexType numVariablesAdded = 0;
      while(!converter.eof()) {
         LabelType currentNumberOfStates;
         converter >> currentNumberOfStates;
         gm.addVariable(currentNumberOfStates);
         numVariablesAdded++;
      }
      if(numVariablesAdded != numVariables) {
         std::cerr << "Bad file format: Number of cardinalities (" << numVariablesAdded << ") does not match number of variables (" << numVariables << "))." << std::endl;
         return 1;
      }
   }

   // get number of factors
   IndexType numFactors;
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (Number of factors is missing)." << std::endl;
      return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      converter >> numFactors;
   }

   // get factors;
   std::vector<std::vector<IndexType> > factors(numFactors);
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (factors are missing)." << std::endl;
      return 1;
   } else {
      IndexType numFactorsAdded = 0;
      while(!myuaifile.eof()) {
         std::getline(myuaifile, currentLine);
         removeSpaces(currentLine);
         if(currentLine.length() == 0) {
            // end of factors reached
            break;
         }
         IndexType numFactorVariables;
         std::stringstream converter(currentLine);
         converter >> numFactorVariables;
         factors[numFactorsAdded].resize(numFactorVariables);
         IndexType numFactorVariablesAdded = 0;
         while(!converter.eof()) {
            converter >> factors[numFactorsAdded][numFactorVariablesAdded];
            numFactorVariablesAdded++;
         }
         if(numFactorVariablesAdded != numFactorVariables) {
            std::cerr << "Bad file format: Number of stated variables of factor " << numFactorsAdded << " does not match number of variables of this factor." << std::endl;
            return 1;
         }
         numFactorsAdded++;
      }
      if(numFactorsAdded != numFactors) {
         std::cerr << "Bad file format: Number of stated factors does not match number of factors." << std::endl;
         return 1;
      }
   }

   // add functions to gm
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Function tables are missing." << std::endl;
      return 1;
   } else {
      IndexType numFunctionsAdded = 0;
      while(!myuaifile.eof()) {
         std::getline(myuaifile, currentLine);
         removeSpaces(currentLine);
         if(currentLine.length() == 0) {
            // ignore empty lines
            continue;
         }
         IndexType numFunctionValues;
         std::stringstream converter(currentLine);
         converter >> numFunctionValues;

         // get shape of function
         std::vector<LabelType> currentShape;
         currentShape.reserve(factors[numFunctionsAdded].size());

         for(IndexType i = 0; i < factors[numFunctionsAdded].size(); i++) {
            IndexType currentVariable = factors[numFunctionsAdded][i];
            LabelType currentVariableDimension = gm.space().numberOfLabels(currentVariable);
            currentShape.push_back(currentVariableDimension);
         }

         marray::Marray<ValueType> currentFunctionValues(currentShape.begin(), currentShape.end());

         // check for matching size
         OPENGM_ASSERT(currentFunctionValues.size() == numFunctionValues);

         // set function values
         if(myuaifile.eof()) {
            std::cerr << "Bad file format: Function values are missing." << std::endl;
            return 1;
         } else {
            IndexType numFunctionValuesAdded = 0;
            do {
               std::getline(myuaifile, currentLine);
               removeSpaces(currentLine);
            } while(currentLine.length() == 0 && !myuaifile.eof());
            if(myuaifile.eof()) {
               std::cerr << "Bad file format: Function values are missing." << std::endl;
               return 1;
            }
            converter.clear();
            converter.str(currentLine);
            while(!converter.eof()) {
               ValueType currentValue;
               converter >> currentValue;
               // transform current value as network type is MARKOV
               logTransform(currentValue);
               std::vector<LabelType> index;
               ind2sub(index, numFunctionValuesAdded, currentShape);
               currentFunctionValues(index.begin()) = currentValue;
               numFunctionValuesAdded++;
            }
            if(numFunctionValuesAdded != numFunctionValues) {
               std::cerr << "Bad file format: Number of stated values does not match number of factor values." << std::endl;
               return 1;
            }
         }

         opengm::ExplicitFunction<ValueType, IndexType, LabelType> currentFunction(currentShape.begin(), currentShape.end());

         // copy function values to function
         // compute permutation vector, if variables are stored in non descending order
         std::vector<size_t> permutation;
         sortingPermutation(factors[numFunctionsAdded], permutation);
         bool isSorted = vecIsSorted(permutation);
         if(!isSorted) {
            std::cout << "permutation detected!" << std::endl;
            // sort variables and permute function
            std::sort(factors[numFunctionsAdded].begin(), factors[numFunctionsAdded].end());
            marray::Marray<ValueType>::base currentFunctionValuesView(currentFunctionValues);
            currentFunctionValuesView.permute(permutation.begin());
            for(size_t i = 0; i < currentFunctionValuesView.size(); i++) {
               currentFunction(i) = currentFunctionValuesView(i);
            }
         } else {
            for(size_t i = 0; i < currentFunctionValues.size(); i++) {
               currentFunction(i) = currentFunctionValues(i);
            }
         }

         // add function to gm
         GmType::FunctionIdentifier currentFunctionIndex = gm.addSharedFunction(currentFunction);

         // add corresponding factor
         gm.addFactor(currentFunctionIndex, factors[numFunctionsAdded].begin(), factors[numFunctionsAdded].end());

         numFunctionsAdded++;
         //converter >> factors[numFactorsAdded][numFactorVariablesAdded];
      }
      if(numFunctionsAdded != numFactors) {
         std::cerr << "Bad file format: Number of stated factors does not match number of factors." << std::endl;
         return 1;
      }
   }

   // close uai file
   myuaifile.close();

   // store gm
   opengm::hdf5::save(gm, opengmfile,"gm");

   return 0;
}

void removeSpaces(std::string& input) {
   if(input.length() == 0) {
      return;
   } else {
      // remove leading spaces
      while(input[0] == ' ') {
         input.erase(0, 1);
         if(input.length() == 0) {
            return;
         }
      }
      // remove ending spaces
      while(input[input.length() - 1] == ' ') {
         input.erase(input.length() - 1, 1);
         if(input.length() == 0) {
            return;
         }
      }
   }
}

template <class T>
void logTransform(T& input) {
   OPENGM_ASSERT(input >= 0);
   if(input == 0) {
      input = std::numeric_limits<T>::infinity();
   } else {
      input = -log(input);
   }
}

template<class T>
struct CmpPairs{
  CmpPairs(const T& vectorIn): vector(vectorIn) {}
  const T& vector;
  bool operator()(int a, int b){ return vector[a] < vector[b]; }
};

template<class T>
CmpPairs<T> CreateCmpPairs(const T& vector) { return CmpPairs<T>(vector); }

template<class T, class U>
void sortingPermutation(const T& values, U& permutation){
   permutation.clear();
   permutation.reserve(values.size());
   for(size_t i = 0; i < values.size(); i++) {
      permutation.push_back(i);
   }
   std::sort(permutation.begin(), permutation.end(), CreateCmpPairs(values));
}

template <class T>
bool vecIsSorted(const T& vector) {
   if(vector.size() <= 1) {
      return true;
   } else {
      for(size_t i = 0; i < vector.size() - 1; i++) {
         if(vector[i] > vector[i + 1]) {
            return false;
         }
      }
      return true;
   }
}

template <class T, class U, class V>
void ind2sub(T& sub, const U ind, const V& sizes) {
   sub.clear();
   sub.reserve(sizes.size());
   U remainingInd = ind;
   for(size_t i = 0; i < sizes.size() - 1; i++) {
      size_t numSubentries = 1;
      for(size_t j = i + 1; j < sizes.size(); j++) {
         numSubentries *= sizes[j];
      }
      size_t currentIndex = remainingInd / numSubentries;
      remainingInd -= currentIndex * numSubentries;
      sub.push_back(currentIndex);
   }
   sub.push_back(remainingInd);
}
<commit_msg>removed debug output<commit_after>#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>
#include <limits>
#include <algorithm>

#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/graphicalmodel/graphicalmodel_hdf5.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/functions/explicit_function.hxx>

// remove leading and ending spaces of given input as this might screw up parsing the input
void removeSpaces(std::string& input);

// compute log of input as network types of type MARKOV store conditional probabilities
template <class T>
void logTransform(T& input);

// sort vector in non descending and compute corresponding permutation vector
template<class T, class U>
void sortingPermutation(const T& values, U& permutation);

// check if vector is in non descending order
template <class T>
bool vecIsSorted(const T& vector);

// transfomrs linear index to subscript values
template <class T, class U, class V>
void ind2sub(T& sub, const U ind, const V& sizes);

int main(int argc, const char* argv[] ) {
   if(argc != 3) {
      std::cerr << "Two input arguments required" << std::endl;
      return 1;
   }

   typedef double ValueType;
   typedef size_t IndexType;
   typedef size_t LabelType;
   typedef opengm::Adder OperatorType;
   typedef opengm::Minimizer AccumulatorType;
   typedef opengm::DiscreteSpace<IndexType, LabelType> SpaceType;

   // Set functions for graphical model
   typedef opengm::meta::TypeListGenerator<
      opengm::ExplicitFunction<ValueType, IndexType, LabelType>
   >::type FunctionTypeList;

   typedef opengm::GraphicalModel<
      ValueType,
      OperatorType,
      FunctionTypeList,
      SpaceType
   > GmType;

   GmType gm;
   std::string opengmfile = argv[1];
   std::string uaifile    = argv[2];

   // open uai file
   std::ifstream myuaifile(uaifile.c_str());
   if(!myuaifile.is_open()) {
      std::cerr << "Could not open file " << uaifile << std::endl;
      return 1;
   }

   // temp storage for current line of uai file
   std::string currentLine;

   // check if type of network is MARKOV
   std::getline(myuaifile, currentLine);
   removeSpaces(currentLine);
   if(currentLine != "MARKOV") {
      std::cerr << "Unsupported network type: \"" << currentLine <<"\". Only networks of type MARKOV are supported by now." << std::endl;
      return 1;
   }

   // get number of variables
   IndexType numVariables;
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (Number of variables is missing)." << std::endl;
      return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      converter >> numVariables;
   }

   // add variables
   if(myuaifile.eof()) {
         std::cerr << "Bad file format: Preamble is incomplete (Cardinalities of variables is missing)." << std::endl;
         return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      IndexType numVariablesAdded = 0;
      while(!converter.eof()) {
         LabelType currentNumberOfStates;
         converter >> currentNumberOfStates;
         gm.addVariable(currentNumberOfStates);
         numVariablesAdded++;
      }
      if(numVariablesAdded != numVariables) {
         std::cerr << "Bad file format: Number of cardinalities (" << numVariablesAdded << ") does not match number of variables (" << numVariables << "))." << std::endl;
         return 1;
      }
   }

   // get number of factors
   IndexType numFactors;
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (Number of factors is missing)." << std::endl;
      return 1;
   } else {
      std::getline(myuaifile, currentLine);
      removeSpaces(currentLine);
      std::stringstream converter(currentLine);
      converter >> numFactors;
   }

   // get factors;
   std::vector<std::vector<IndexType> > factors(numFactors);
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Preamble is incomplete (factors are missing)." << std::endl;
      return 1;
   } else {
      IndexType numFactorsAdded = 0;
      while(!myuaifile.eof()) {
         std::getline(myuaifile, currentLine);
         removeSpaces(currentLine);
         if(currentLine.length() == 0) {
            // end of factors reached
            break;
         }
         IndexType numFactorVariables;
         std::stringstream converter(currentLine);
         converter >> numFactorVariables;
         factors[numFactorsAdded].resize(numFactorVariables);
         IndexType numFactorVariablesAdded = 0;
         while(!converter.eof()) {
            converter >> factors[numFactorsAdded][numFactorVariablesAdded];
            numFactorVariablesAdded++;
         }
         if(numFactorVariablesAdded != numFactorVariables) {
            std::cerr << "Bad file format: Number of stated variables of factor " << numFactorsAdded << " does not match number of variables of this factor." << std::endl;
            return 1;
         }
         numFactorsAdded++;
      }
      if(numFactorsAdded != numFactors) {
         std::cerr << "Bad file format: Number of stated factors does not match number of factors." << std::endl;
         return 1;
      }
   }

   // add functions to gm
   if(myuaifile.eof()) {
      std::cerr << "Bad file format: Function tables are missing." << std::endl;
      return 1;
   } else {
      IndexType numFunctionsAdded = 0;
      while(!myuaifile.eof()) {
         std::getline(myuaifile, currentLine);
         removeSpaces(currentLine);
         if(currentLine.length() == 0) {
            // ignore empty lines
            continue;
         }
         IndexType numFunctionValues;
         std::stringstream converter(currentLine);
         converter >> numFunctionValues;

         // get shape of function
         std::vector<LabelType> currentShape;
         currentShape.reserve(factors[numFunctionsAdded].size());

         for(IndexType i = 0; i < factors[numFunctionsAdded].size(); i++) {
            IndexType currentVariable = factors[numFunctionsAdded][i];
            LabelType currentVariableDimension = gm.space().numberOfLabels(currentVariable);
            currentShape.push_back(currentVariableDimension);
         }

         marray::Marray<ValueType> currentFunctionValues(currentShape.begin(), currentShape.end());

         // check for matching size
         OPENGM_ASSERT(currentFunctionValues.size() == numFunctionValues);

         // set function values
         if(myuaifile.eof()) {
            std::cerr << "Bad file format: Function values are missing." << std::endl;
            return 1;
         } else {
            IndexType numFunctionValuesAdded = 0;
            do {
               std::getline(myuaifile, currentLine);
               removeSpaces(currentLine);
            } while(currentLine.length() == 0 && !myuaifile.eof());
            if(myuaifile.eof()) {
               std::cerr << "Bad file format: Function values are missing." << std::endl;
               return 1;
            }
            converter.clear();
            converter.str(currentLine);
            while(!converter.eof()) {
               ValueType currentValue;
               converter >> currentValue;
               // transform current value as network type is MARKOV
               logTransform(currentValue);
               std::vector<LabelType> index;
               ind2sub(index, numFunctionValuesAdded, currentShape);
               currentFunctionValues(index.begin()) = currentValue;
               numFunctionValuesAdded++;
            }
            if(numFunctionValuesAdded != numFunctionValues) {
               std::cerr << "Bad file format: Number of stated values does not match number of factor values." << std::endl;
               return 1;
            }
         }

         opengm::ExplicitFunction<ValueType, IndexType, LabelType> currentFunction(currentShape.begin(), currentShape.end());

         // copy function values to function
         // compute permutation vector, if variables are stored in non descending order
         std::vector<size_t> permutation;
         sortingPermutation(factors[numFunctionsAdded], permutation);
         bool isSorted = vecIsSorted(permutation);
         if(!isSorted) {
            // sort variables and permute function
            std::sort(factors[numFunctionsAdded].begin(), factors[numFunctionsAdded].end());
            marray::Marray<ValueType>::base currentFunctionValuesView(currentFunctionValues);
            currentFunctionValuesView.permute(permutation.begin());
            for(size_t i = 0; i < currentFunctionValuesView.size(); i++) {
               currentFunction(i) = currentFunctionValuesView(i);
            }
         } else {
            for(size_t i = 0; i < currentFunctionValues.size(); i++) {
               currentFunction(i) = currentFunctionValues(i);
            }
         }

         // add function to gm
         GmType::FunctionIdentifier currentFunctionIndex = gm.addSharedFunction(currentFunction);

         // add corresponding factor
         gm.addFactor(currentFunctionIndex, factors[numFunctionsAdded].begin(), factors[numFunctionsAdded].end());

         numFunctionsAdded++;
         //converter >> factors[numFactorsAdded][numFactorVariablesAdded];
      }
      if(numFunctionsAdded != numFactors) {
         std::cerr << "Bad file format: Number of stated factors does not match number of factors." << std::endl;
         return 1;
      }
   }

   // close uai file
   myuaifile.close();

   // store gm
   opengm::hdf5::save(gm, opengmfile,"gm");

   return 0;
}

void removeSpaces(std::string& input) {
   if(input.length() == 0) {
      return;
   } else {
      // remove leading spaces
      while(input[0] == ' ') {
         input.erase(0, 1);
         if(input.length() == 0) {
            return;
         }
      }
      // remove ending spaces
      while(input[input.length() - 1] == ' ') {
         input.erase(input.length() - 1, 1);
         if(input.length() == 0) {
            return;
         }
      }
   }
}

template <class T>
void logTransform(T& input) {
   OPENGM_ASSERT(input >= 0);
   if(input == 0) {
      input = std::numeric_limits<T>::infinity();
   } else {
      input = -log(input);
   }
}

template<class T>
struct CmpPairs{
  CmpPairs(const T& vectorIn): vector(vectorIn) {}
  const T& vector;
  bool operator()(int a, int b){ return vector[a] < vector[b]; }
};

template<class T>
CmpPairs<T> CreateCmpPairs(const T& vector) { return CmpPairs<T>(vector); }

template<class T, class U>
void sortingPermutation(const T& values, U& permutation){
   permutation.clear();
   permutation.reserve(values.size());
   for(size_t i = 0; i < values.size(); i++) {
      permutation.push_back(i);
   }
   std::sort(permutation.begin(), permutation.end(), CreateCmpPairs(values));
}

template <class T>
bool vecIsSorted(const T& vector) {
   if(vector.size() <= 1) {
      return true;
   } else {
      for(size_t i = 0; i < vector.size() - 1; i++) {
         if(vector[i] > vector[i + 1]) {
            return false;
         }
      }
      return true;
   }
}

template <class T, class U, class V>
void ind2sub(T& sub, const U ind, const V& sizes) {
   sub.clear();
   sub.reserve(sizes.size());
   U remainingInd = ind;
   for(size_t i = 0; i < sizes.size() - 1; i++) {
      size_t numSubentries = 1;
      for(size_t j = i + 1; j < sizes.size(); j++) {
         numSubentries *= sizes[j];
      }
      size_t currentIndex = remainingInd / numSubentries;
      remainingInd -= currentIndex * numSubentries;
      sub.push_back(currentIndex);
   }
   sub.push_back(remainingInd);
}
<|endoftext|>


<commit_before>//
//  MCMD5.cpp
//  hermes
//
//  Created by DINH Viêt Hoà on 4/11/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCMD5.h"

#include <inttypes.h>
#include <string.h>

using namespace mailcore;

static int is_big_endian(void) {
    static const int n = 1;
    return ((char *) &n)[0] == 0;
}

typedef struct MD5Context {
    uint32_t buf[4];
    uint32_t bits[2];
    unsigned char in[64];
} MD5_CTX;

static void byteReverse(unsigned char *buf, unsigned longs) {
    uint32_t t;

    // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
    if (is_big_endian()) {
        do {
            t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
            ((unsigned) buf[1] << 8 | buf[0]);
            * (uint32_t *) buf = t;
            buf += 4;
        } while (--longs);
    }
}

#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )

static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
    register uint32_t a, b, c, d;

    a = buf[0];
    b = buf[1];
    c = buf[2];
    d = buf[3];

    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

    buf[0] += a;
    buf[1] += b;
    buf[2] += c;
    buf[3] += d;
}

// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
// initialization constants.
static void MD5Init(MD5_CTX *ctx) {
    ctx->buf[0] = 0x67452301;
    ctx->buf[1] = 0xefcdab89;
    ctx->buf[2] = 0x98badcfe;
    ctx->buf[3] = 0x10325476;

    ctx->bits[0] = 0;
    ctx->bits[1] = 0;
}

static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
    uint32_t t;

    t = ctx->bits[0];
    if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
        ctx->bits[1]++;
    ctx->bits[1] += len >> 29;

    t = (t >> 3) & 0x3f;

    if (t) {
        unsigned char *p = (unsigned char *) ctx->in + t;

        t = 64 - t;
        if (len < t) {
            memcpy(p, buf, len);
            return;
        }
        memcpy(p, buf, t);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        buf += t;
        len -= t;
    }

    while (len >= 64) {
        memcpy(ctx->in, buf, 64);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        buf += 64;
        len -= 64;
    }

    memcpy(ctx->in, buf, len);
}

static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
    unsigned count;
    unsigned char *p;
    uint32_t *a;

    count = (ctx->bits[0] >> 3) & 0x3F;

    p = ctx->in + count;
    *p++ = 0x80;
    count = 64 - 1 - count;
    if (count < 8) {
        memset(p, 0, count);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        memset(ctx->in, 0, 56);
    } else {
        memset(p, 0, count - 8);
    }
    byteReverse(ctx->in, 14);

    a = (uint32_t *)ctx->in;
    a[14] = ctx->bits[0];
    a[15] = ctx->bits[1];

    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    byteReverse((unsigned char *) ctx->buf, 4);
    memcpy(digest, ctx->buf, 16);
    memset((char *) ctx, 0, sizeof(*ctx));
}

Data * mailcore::md5Data(Data * data)
{
    MD5Context ctx;
    unsigned char digest[16];
    Data * result = Data::dataWithCapacity(sizeof(digest));

    MD5Init(&ctx);
    MD5Update(&ctx, (unsigned char const *) data->bytes(), data->length());
    MD5Final(digest, &ctx);

    memcpy(result->bytes(), digest, sizeof(digest));

    return result;
}

String * mailcore::md5String(Data * data)
{
    Data * md5data = md5Data(data);
    String * result = String::string();
    for(unsigned int i = 0 ; i < md5data->length() ; i ++) {
        result->appendUTF8Format("%02x", (unsigned char) md5data->bytes()[i]);
    }
    return result;
}

<commit_msg>Fixed MD5.<commit_after>//
//  MCMD5.cpp
//  hermes
//
//  Created by DINH Viêt Hoà on 4/11/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCMD5.h"

#include <inttypes.h>
#include <string.h>

using namespace mailcore;

static int is_big_endian(void) {
    static const int n = 1;
    return ((char *) &n)[0] == 0;
}

typedef struct MD5Context {
    uint32_t buf[4];
    uint32_t bits[2];
    unsigned char in[64];
} MD5_CTX;

static void byteReverse(unsigned char *buf, unsigned longs) {
    uint32_t t;

    // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
    if (is_big_endian()) {
        do {
            t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
            ((unsigned) buf[1] << 8 | buf[0]);
            * (uint32_t *) buf = t;
            buf += 4;
        } while (--longs);
    }
}

#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )

static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
    register uint32_t a, b, c, d;

    a = buf[0];
    b = buf[1];
    c = buf[2];
    d = buf[3];

    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

    buf[0] += a;
    buf[1] += b;
    buf[2] += c;
    buf[3] += d;
}

// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
// initialization constants.
static void MD5Init(MD5_CTX *ctx) {
    ctx->buf[0] = 0x67452301;
    ctx->buf[1] = 0xefcdab89;
    ctx->buf[2] = 0x98badcfe;
    ctx->buf[3] = 0x10325476;

    ctx->bits[0] = 0;
    ctx->bits[1] = 0;
}

static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
    uint32_t t;

    t = ctx->bits[0];
    if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
        ctx->bits[1]++;
    ctx->bits[1] += len >> 29;

    t = (t >> 3) & 0x3f;

    if (t) {
        unsigned char *p = (unsigned char *) ctx->in + t;

        t = 64 - t;
        if (len < t) {
            memcpy(p, buf, len);
            return;
        }
        memcpy(p, buf, t);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        buf += t;
        len -= t;
    }

    while (len >= 64) {
        memcpy(ctx->in, buf, 64);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        buf += 64;
        len -= 64;
    }

    memcpy(ctx->in, buf, len);
}

static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
    unsigned count;
    unsigned char *p;
    uint32_t *a;

    count = (ctx->bits[0] >> 3) & 0x3F;

    p = ctx->in + count;
    *p++ = 0x80;
    count = 64 - 1 - count;
    if (count < 8) {
        memset(p, 0, count);
        byteReverse(ctx->in, 16);
        MD5Transform(ctx->buf, (uint32_t *) ctx->in);
        memset(ctx->in, 0, 56);
    } else {
        memset(p, 0, count - 8);
    }
    byteReverse(ctx->in, 14);

    a = (uint32_t *)ctx->in;
    a[14] = ctx->bits[0];
    a[15] = ctx->bits[1];

    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    byteReverse((unsigned char *) ctx->buf, 4);
    memcpy(digest, ctx->buf, 16);
    memset((char *) ctx, 0, sizeof(*ctx));
}

Data * mailcore::md5Data(Data * data)
{
    MD5Context ctx;
    unsigned char digest[16];
    Data * result = Data::dataWithCapacity(sizeof(digest));

    MD5Init(&ctx);
    MD5Update(&ctx, (unsigned char const *) data->bytes(), data->length());
    MD5Final(digest, &ctx);

    result->appendBytes((const char *) digest, sizeof(digest));

    return result;
}

String * mailcore::md5String(Data * data)
{
    Data * md5data = md5Data(data);
    String * result = String::string();
    for(unsigned int i = 0 ; i < md5data->length() ; i ++) {
        result->appendUTF8Format("%02x", (unsigned char) md5data->bytes()[i]);
    }
    return result;
}

<|endoftext|>


<commit_before>#include "base.hpp"
#include "Client.hpp"
#include "CommonData.hpp"
#include "Config.hpp"
#include "FlagStatus.hpp"
#include "VirtualKey.hpp"
#include "RemapUtil.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  void
  VirtualKey::initialize(IOWorkLoop& workloop)
  {
    Handle_VK_JIS_TEMPORARY::initialize(workloop);
  }

  void
  VirtualKey::terminate(void)
  {
    Handle_VK_JIS_TEMPORARY::terminate();
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_LOCK::handle(const Params_KeyboardEventCallBack& params)
  {
    Flags flags(0);
    bool force_on = false;
    bool force_off = false;

    if (params.key == KeyCode::VK_LOCK_FN) {
      flags.add(ModifierFlag::FN);
    } else if (params.key == KeyCode::VK_LOCK_FN_FORCE_OFF) {
      flags.add(ModifierFlag::FN);
      force_off = true;
    } else if (params.key == KeyCode::VK_LOCK_COMMAND_R) {
      flags.add(ModifierFlag::COMMAND_R);
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L) {
      flags.add(ModifierFlag::SHIFT_L);
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L_FORCE_ON) {
      flags.add(ModifierFlag::SHIFT_L);
      force_on = true;
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L_FORCE_OFF) {
      flags.add(ModifierFlag::SHIFT_L);
      force_off = true;

    } else if (params.key == KeyCode::VK_LOCK_ALL_FORCE_OFF) {
      FlagStatus::lock_clear();
      return true;
    } else {
      return false;
    }

    if (params.eventType == EventType::DOWN && params.repeat == false) {
      if (force_off) {
        FlagStatus::lock_decrease(flags);
      } else if (force_on) {
        FlagStatus::lock_increase(flags);
      } else {
        FlagStatus::lock_toggle(flags);
      }
    }

    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_LAZY::handle(const Params_KeyboardEventCallBack& params)
  {
    ModifierFlag f = ModifierFlag::NONE;

    if (params.key == KeyCode::VK_LAZY_SHIFT_L) {
      f = ModifierFlag::SHIFT_L;
    }
    if (params.key == KeyCode::VK_LAZY_SHIFT_R) {
      f = ModifierFlag::SHIFT_R;
    }

    if (f == ModifierFlag::NONE) return false;

    // ----------------------------------------
    if (params.eventType == EventType::DOWN && params.repeat == false) {
      FlagStatus::increase(f);
    } else {
      FlagStatus::decrease(f);
    }

    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_CHANGE_INPUTMODE::handle(const Params_KeyboardEventCallBack& params)
  {
    KeyRemap4MacBook_bridge::ChangeInputMode::Request request;
    if (params.key == KeyCode::VK_CHANGE_INPUTMODE_ENGLISH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_ENGLISH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_FRENCH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_FRENCH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_GERMAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_GERMAN;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_JAPANESE) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_JAPANESE;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_SWEDISH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_SWEDISH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_CANADIAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_CANADIAN;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_RUSSIAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_RUSSIAN;
    } else {
      return false;
    }

    if (params.eventType == EventType::DOWN && params.repeat == false) {
      KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_CHANGE_INPUTMODE, &request, sizeof(request), NULL, 0);
    }
    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_CONFIG::handle(const Params_KeyboardEventCallBack& params)
  {
    int* configitem = NULL;

    enum Type {
      TYPE_TOGGLE,
      TYPE_FORCE_ON,
      TYPE_FORCE_OFF,
    } type = TYPE_TOGGLE;

#include "config/output/include.remapcode_vk_config.cpp"

    if (configitem == NULL) {
      return false;
    }

    // ------------------------------------------------------------
    if (params.eventType == EventType::DOWN && params.repeat == false) {
      switch (type) {
        case TYPE_TOGGLE:
          *configitem = ! *configitem;
          break;
        case TYPE_FORCE_ON:
          *configitem = 1;
          break;
        case TYPE_FORCE_OFF:
          *configitem = 0;
          break;
      }
      refresh_remapfunc();
    }
    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_JIS_TOGGLE_EISUU_KANA::handle(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_TOGGLE_EISUU_KANA) return false;

    if (params.eventType == EventType::DOWN) {
      if (CommonData::getcurrent_workspacedata().inputmode == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE) {
        newkeycode_ = KeyCode::JIS_EISUU;
      } else {
        newkeycode_ = KeyCode::JIS_KANA;
      }
    }

    params.key = newkeycode_;
    RemapUtil::fireKey(params);
    return true;
  }

  KeyCode Handle_VK_JIS_TOGGLE_EISUU_KANA::newkeycode_;

  // ----------------------------------------------------------------------
  bool
  handle_VK_JIS_EISUU_x2(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_EISUU_x2) return false;

    if (params.eventType == EventType::DOWN) {
      for (int i = 0; i < 2; ++i) {
        RemapUtil::fireKey_downup(params.flags, KeyCode::JIS_EISUU, params.keyboardType);
      }
    }
    return true;
  }

  bool
  handle_VK_JIS_KANA_x2(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_KANA_x2) return false;

    if (params.eventType == EventType::DOWN) {
      for (int i = 0; i < 2; ++i) {
        RemapUtil::fireKey_downup(params.flags, KeyCode::JIS_KANA, params.keyboardType);
      }
    }
    return true;
  }

  bool
  handle_VK_JIS_BACKSLASH(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_BACKSLASH) return false;

    params.key = KeyCode::BACKSLASH;
    params.keyboardType = KeyboardType::MACBOOK;
    RemapUtil::fireKey(params);
    return true;
  }

  bool
  handle_VK_JIS_YEN(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_YEN) return false;

    params.key = KeyCode::JIS_YEN;
    params.keyboardType = KeyboardType::JIS_MACBOOK_2008;
    RemapUtil::fireKey(params);
    return true;
  }

  // ----------------------------------------------------------------------
  void
  Handle_VK_JIS_TEMPORARY::initialize(IOWorkLoop& workloop)
  {
    timer_.initialize(&workloop, NULL, Handle_VK_JIS_TEMPORARY::fire);
    fireKeyInfo_.active = false;
  }

  void
  Handle_VK_JIS_TEMPORARY::terminate(void)
  {
    timer_.terminate();
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle_core(const Params_KeyboardEventCallBack& params,
                                       KeyCode key,
                                       const KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail& inputmodedetail)
  {
    if (params.key != key) return false;

    if (params.eventType == EventType::DOWN) {
      if (savedinputmodedetail_ == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) {
        savedinputmodedetail_ = CommonData::getcurrent_workspacedata().inputmodedetail;
        currentinputmodedetail_ = CommonData::getcurrent_workspacedata().inputmodedetail;
      }
      firekeytoinputdetail(params, inputmodedetail);
    }

    return true;
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle_RESTORE(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_TEMPORARY_RESTORE) return false;

    if (params.eventType == EventType::DOWN) {
      if (savedinputmodedetail_ != KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) {
        firekeytoinputdetail(params, savedinputmodedetail_);
        savedinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
        currentinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
      }
    }

    return true;
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle(Params_KeyboardEventCallBack& params)
  {
    // ------------------------------------------------------------
    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_ROMAN,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN)) return true;

    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_HIRAGANA,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA)) return true;

    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_KATAKANA,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA)) return true;

    // OK, Ainu is not Japanese.
    // But the input source of Ainu is Kotoeri, we need to handle it here.
    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_AINU,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_AINU)) return true;

    // ------------------------------------------------------------
    if (handle_RESTORE(params)) return true;

    // ------------------------------------------------------------
    // flash keyevent
    if (fireKeyInfo_.active) {
      IOLockWrapper::ScopedLock lk(timer_.getlock());
      timer_.cancelTimeout();
      fire_nolock();
    }

    return false;
  }

  void
  Handle_VK_JIS_TEMPORARY::firekeytoinputdetail(const Params_KeyboardEventCallBack& params,
                                                KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail inputmodedetail)
  {
    IOLockWrapper::ScopedLock lk(timer_.getlock());

    inputmodedetail = normalize(inputmodedetail);
    currentinputmodedetail_ = normalize(currentinputmodedetail_);

    // ------------------------------------------------------------
    if (inputmodedetail == currentinputmodedetail_) return;
    if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) return;

    currentinputmodedetail_ = inputmodedetail;

    // ------------------------------------------------------------
    if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN) {
      fireKeyInfo_.flags = Flags(0);
      fireKeyInfo_.key = KeyCode::JIS_EISUU;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA) {
      fireKeyInfo_.flags = Flags(0);
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA) {
      fireKeyInfo_.flags = ModifierFlag::SHIFT_L;
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_AINU) {
      fireKeyInfo_.flags = ModifierFlag::OPTION_L;
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else {
      return;
    }

    fireKeyInfo_.keyboardType = params.keyboardType;
    fireKeyInfo_.active = true;

    timer_.setTimeoutMS(KEYEVENT_DELAY_MS);
  }

  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail
  Handle_VK_JIS_TEMPORARY::normalize(const KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail& imd)
  {
    if (imd == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE) {
      return KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;
    }
    return imd;
  }

  void
  Handle_VK_JIS_TEMPORARY::fire(OSObject* notuse_owner, IOTimerEventSource* notuse_sender)
  {
    IOLockWrapper::ScopedLock lk(timer_.getlock());
    fire_nolock();
  }

  void
  Handle_VK_JIS_TEMPORARY::fire_nolock(void)
  {
    if (! fireKeyInfo_.active) return;
    fireKeyInfo_.active = false;
    RemapUtil::fireKey_downup(fireKeyInfo_.flags, fireKeyInfo_.key, fireKeyInfo_.keyboardType);
  }

  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail Handle_VK_JIS_TEMPORARY::savedinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail Handle_VK_JIS_TEMPORARY::currentinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
  Handle_VK_JIS_TEMPORARY::FireKeyInfo Handle_VK_JIS_TEMPORARY::fireKeyInfo_;
  TimerWrapper Handle_VK_JIS_TEMPORARY::timer_;
}
<commit_msg>fix Handle_VK_LAZY<commit_after>#include "base.hpp"
#include "Client.hpp"
#include "CommonData.hpp"
#include "Config.hpp"
#include "FlagStatus.hpp"
#include "VirtualKey.hpp"
#include "RemapUtil.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  void
  VirtualKey::initialize(IOWorkLoop& workloop)
  {
    Handle_VK_JIS_TEMPORARY::initialize(workloop);
  }

  void
  VirtualKey::terminate(void)
  {
    Handle_VK_JIS_TEMPORARY::terminate();
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_LOCK::handle(const Params_KeyboardEventCallBack& params)
  {
    Flags flags(0);
    bool force_on = false;
    bool force_off = false;

    if (params.key == KeyCode::VK_LOCK_FN) {
      flags.add(ModifierFlag::FN);
    } else if (params.key == KeyCode::VK_LOCK_FN_FORCE_OFF) {
      flags.add(ModifierFlag::FN);
      force_off = true;
    } else if (params.key == KeyCode::VK_LOCK_COMMAND_R) {
      flags.add(ModifierFlag::COMMAND_R);
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L) {
      flags.add(ModifierFlag::SHIFT_L);
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L_FORCE_ON) {
      flags.add(ModifierFlag::SHIFT_L);
      force_on = true;
    } else if (params.key == KeyCode::VK_LOCK_SHIFT_L_FORCE_OFF) {
      flags.add(ModifierFlag::SHIFT_L);
      force_off = true;

    } else if (params.key == KeyCode::VK_LOCK_ALL_FORCE_OFF) {
      FlagStatus::lock_clear();
      return true;
    } else {
      return false;
    }

    if (params.eventType == EventType::DOWN && params.repeat == false) {
      if (force_off) {
        FlagStatus::lock_decrease(flags);
      } else if (force_on) {
        FlagStatus::lock_increase(flags);
      } else {
        FlagStatus::lock_toggle(flags);
      }
    }

    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_LAZY::handle(const Params_KeyboardEventCallBack& params)
  {
    ModifierFlag f = ModifierFlag::NONE;

    if (params.key == KeyCode::VK_LAZY_SHIFT_L) {
      f = ModifierFlag::SHIFT_L;
    }
    if (params.key == KeyCode::VK_LAZY_SHIFT_R) {
      f = ModifierFlag::SHIFT_R;
    }

    if (f == ModifierFlag::NONE) return false;

    // ----------------------------------------
    if (params.repeat) return true;

    if (params.eventType == EventType::DOWN) {
      FlagStatus::increase(f);
    } else if (params.eventType == EventType::UP) {
      FlagStatus::decrease(f);
    } else {
      IOLog("KeyRemap4MacBook --Warning-- Handle_VK_LAZY invalid EventType.\n");
    }

    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_CHANGE_INPUTMODE::handle(const Params_KeyboardEventCallBack& params)
  {
    KeyRemap4MacBook_bridge::ChangeInputMode::Request request;
    if (params.key == KeyCode::VK_CHANGE_INPUTMODE_ENGLISH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_ENGLISH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_FRENCH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_FRENCH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_GERMAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_GERMAN;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_JAPANESE) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_JAPANESE;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_SWEDISH) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_SWEDISH;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_CANADIAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_CANADIAN;
    } else if (params.key == KeyCode::VK_CHANGE_INPUTMODE_RUSSIAN) {
      request.inputmode = KeyRemap4MacBook_bridge::ChangeInputMode::INPUTMODE_RUSSIAN;
    } else {
      return false;
    }

    if (params.eventType == EventType::DOWN && params.repeat == false) {
      KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::REQUEST_CHANGE_INPUTMODE, &request, sizeof(request), NULL, 0);
    }
    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_CONFIG::handle(const Params_KeyboardEventCallBack& params)
  {
    int* configitem = NULL;

    enum Type {
      TYPE_TOGGLE,
      TYPE_FORCE_ON,
      TYPE_FORCE_OFF,
    } type = TYPE_TOGGLE;

#include "config/output/include.remapcode_vk_config.cpp"

    if (configitem == NULL) {
      return false;
    }

    // ------------------------------------------------------------
    if (params.eventType == EventType::DOWN && params.repeat == false) {
      switch (type) {
        case TYPE_TOGGLE:
          *configitem = ! *configitem;
          break;
        case TYPE_FORCE_ON:
          *configitem = 1;
          break;
        case TYPE_FORCE_OFF:
          *configitem = 0;
          break;
      }
      refresh_remapfunc();
    }
    return true;
  }

  // ----------------------------------------------------------------------
  bool
  Handle_VK_JIS_TOGGLE_EISUU_KANA::handle(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_TOGGLE_EISUU_KANA) return false;

    if (params.eventType == EventType::DOWN) {
      if (CommonData::getcurrent_workspacedata().inputmode == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE) {
        newkeycode_ = KeyCode::JIS_EISUU;
      } else {
        newkeycode_ = KeyCode::JIS_KANA;
      }
    }

    params.key = newkeycode_;
    RemapUtil::fireKey(params);
    return true;
  }

  KeyCode Handle_VK_JIS_TOGGLE_EISUU_KANA::newkeycode_;

  // ----------------------------------------------------------------------
  bool
  handle_VK_JIS_EISUU_x2(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_EISUU_x2) return false;

    if (params.eventType == EventType::DOWN) {
      for (int i = 0; i < 2; ++i) {
        RemapUtil::fireKey_downup(params.flags, KeyCode::JIS_EISUU, params.keyboardType);
      }
    }
    return true;
  }

  bool
  handle_VK_JIS_KANA_x2(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_KANA_x2) return false;

    if (params.eventType == EventType::DOWN) {
      for (int i = 0; i < 2; ++i) {
        RemapUtil::fireKey_downup(params.flags, KeyCode::JIS_KANA, params.keyboardType);
      }
    }
    return true;
  }

  bool
  handle_VK_JIS_BACKSLASH(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_BACKSLASH) return false;

    params.key = KeyCode::BACKSLASH;
    params.keyboardType = KeyboardType::MACBOOK;
    RemapUtil::fireKey(params);
    return true;
  }

  bool
  handle_VK_JIS_YEN(Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_YEN) return false;

    params.key = KeyCode::JIS_YEN;
    params.keyboardType = KeyboardType::JIS_MACBOOK_2008;
    RemapUtil::fireKey(params);
    return true;
  }

  // ----------------------------------------------------------------------
  void
  Handle_VK_JIS_TEMPORARY::initialize(IOWorkLoop& workloop)
  {
    timer_.initialize(&workloop, NULL, Handle_VK_JIS_TEMPORARY::fire);
    fireKeyInfo_.active = false;
  }

  void
  Handle_VK_JIS_TEMPORARY::terminate(void)
  {
    timer_.terminate();
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle_core(const Params_KeyboardEventCallBack& params,
                                       KeyCode key,
                                       const KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail& inputmodedetail)
  {
    if (params.key != key) return false;

    if (params.eventType == EventType::DOWN) {
      if (savedinputmodedetail_ == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) {
        savedinputmodedetail_ = CommonData::getcurrent_workspacedata().inputmodedetail;
        currentinputmodedetail_ = CommonData::getcurrent_workspacedata().inputmodedetail;
      }
      firekeytoinputdetail(params, inputmodedetail);
    }

    return true;
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle_RESTORE(const Params_KeyboardEventCallBack& params)
  {
    if (params.key != KeyCode::VK_JIS_TEMPORARY_RESTORE) return false;

    if (params.eventType == EventType::DOWN) {
      if (savedinputmodedetail_ != KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) {
        firekeytoinputdetail(params, savedinputmodedetail_);
        savedinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
        currentinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
      }
    }

    return true;
  }

  bool
  Handle_VK_JIS_TEMPORARY::handle(Params_KeyboardEventCallBack& params)
  {
    // ------------------------------------------------------------
    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_ROMAN,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN)) return true;

    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_HIRAGANA,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA)) return true;

    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_KATAKANA,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA)) return true;

    // OK, Ainu is not Japanese.
    // But the input source of Ainu is Kotoeri, we need to handle it here.
    if (handle_core(params,
                    KeyCode::VK_JIS_TEMPORARY_AINU,
                    KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_AINU)) return true;

    // ------------------------------------------------------------
    if (handle_RESTORE(params)) return true;

    // ------------------------------------------------------------
    // flash keyevent
    if (fireKeyInfo_.active) {
      IOLockWrapper::ScopedLock lk(timer_.getlock());
      timer_.cancelTimeout();
      fire_nolock();
    }

    return false;
  }

  void
  Handle_VK_JIS_TEMPORARY::firekeytoinputdetail(const Params_KeyboardEventCallBack& params,
                                                KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail inputmodedetail)
  {
    IOLockWrapper::ScopedLock lk(timer_.getlock());

    inputmodedetail = normalize(inputmodedetail);
    currentinputmodedetail_ = normalize(currentinputmodedetail_);

    // ------------------------------------------------------------
    if (inputmodedetail == currentinputmodedetail_) return;
    if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE) return;

    currentinputmodedetail_ = inputmodedetail;

    // ------------------------------------------------------------
    if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN) {
      fireKeyInfo_.flags = Flags(0);
      fireKeyInfo_.key = KeyCode::JIS_EISUU;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA) {
      fireKeyInfo_.flags = Flags(0);
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA) {
      fireKeyInfo_.flags = ModifierFlag::SHIFT_L;
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else if (inputmodedetail == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_AINU) {
      fireKeyInfo_.flags = ModifierFlag::OPTION_L;
      fireKeyInfo_.key = KeyCode::JIS_KANA;

    } else {
      return;
    }

    fireKeyInfo_.keyboardType = params.keyboardType;
    fireKeyInfo_.active = true;

    timer_.setTimeoutMS(KEYEVENT_DELAY_MS);
  }

  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail
  Handle_VK_JIS_TEMPORARY::normalize(const KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail& imd)
  {
    if (imd == KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE) {
      return KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;
    }
    return imd;
  }

  void
  Handle_VK_JIS_TEMPORARY::fire(OSObject* notuse_owner, IOTimerEventSource* notuse_sender)
  {
    IOLockWrapper::ScopedLock lk(timer_.getlock());
    fire_nolock();
  }

  void
  Handle_VK_JIS_TEMPORARY::fire_nolock(void)
  {
    if (! fireKeyInfo_.active) return;
    fireKeyInfo_.active = false;
    RemapUtil::fireKey_downup(fireKeyInfo_.flags, fireKeyInfo_.key, fireKeyInfo_.keyboardType);
  }

  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail Handle_VK_JIS_TEMPORARY::savedinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
  KeyRemap4MacBook_bridge::GetWorkspaceData::InputModeDetail Handle_VK_JIS_TEMPORARY::currentinputmodedetail_ = KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_NONE;
  Handle_VK_JIS_TEMPORARY::FireKeyInfo Handle_VK_JIS_TEMPORARY::fireKeyInfo_;
  TimerWrapper Handle_VK_JIS_TEMPORARY::timer_;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    // These enumerate all the registers for dependence tracking.
    enum DependenceTags {
        //The number of microcode registers needs to be added to this
        FP_Base_DepTag = 16,
        Ctrl_Base_DepTag =
            FP_Base_DepTag +
            //mmx/x87 registers
            8 +
            //xmm registers
            16
    };

    // semantically meaningful register indices
    //There is no such register in X86
    const int ZeroReg = 0;
    const int StackPointerReg = 4; //RSP
    //X86 doesn't seem to have a link register
    const int ReturnAddressReg = 0;
    const int ReturnValueReg = 0; //RAX
    const int FramePointerReg = 5; //RBP
    const int ArgumentReg0 = 7; //RDI
    const int ArgumentReg1 = 6; //RSI
    const int ArgumentReg2 = 2; //RDX
    const int ArgumentReg3 = 1; //RCX
    const int ArgumentReg4 = 8; //R8W
    const int ArgumentReg5 = 9; //R9W

    // Some OS syscalls use a second register (rdx) to return a second
    // value
    const int SyscallPseudoReturnReg = 2; //RDX

    //XXX These numbers are bogus
    const int MaxInstSrcRegs = 10;
    const int MaxInstDestRegs = 10;

    //4k. This value is not constant on x86.
    const int LogVmPageSize = 12;
    const int VMPageSize = (1 << LogVmPageSize);

    const int BranchPredAddrShiftAmt = 0;
};

#endif // __ARCH_X86_ISATRAITS_HH__
<commit_msg>Include the x86 specific traits file.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

#include "arch/x86/x86_traits.hh"

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    // These enumerate all the registers for dependence tracking.
    enum DependenceTags {
        //The number of microcode registers needs to be added to this
        FP_Base_DepTag = 16,
        Ctrl_Base_DepTag =
            FP_Base_DepTag +
            //mmx/x87 registers
            8 +
            //xmm registers
            16
    };

    // semantically meaningful register indices
    //There is no such register in X86
    const int ZeroReg = 0;
    const int StackPointerReg = 4; //RSP
    //X86 doesn't seem to have a link register
    const int ReturnAddressReg = 0;
    const int ReturnValueReg = 0; //RAX
    const int FramePointerReg = 5; //RBP
    const int ArgumentReg0 = 7; //RDI
    const int ArgumentReg1 = 6; //RSI
    const int ArgumentReg2 = 2; //RDX
    const int ArgumentReg3 = 1; //RCX
    const int ArgumentReg4 = 8; //R8W
    const int ArgumentReg5 = 9; //R9W

    // Some OS syscalls use a second register (rdx) to return a second
    // value
    const int SyscallPseudoReturnReg = 2; //RDX

    //XXX These numbers are bogus
    const int MaxInstSrcRegs = 10;
    const int MaxInstDestRegs = 10;

    //4k. This value is not constant on x86.
    const int LogVmPageSize = 12;
    const int VMPageSize = (1 << LogVmPageSize);

    const int BranchPredAddrShiftAmt = 0;
};

#endif // __ARCH_X86_ISATRAITS_HH__
<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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.1 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <sstream>

#include "vvdebugmsg.h"
#include "vvsocketmonitor.h"
#include "vvtcpserver.h"
#include "vvtcpsocket.h"

vvTcpServer::vvTcpServer(const ushort port)
{
#ifdef _WIN32
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
    vvDebugMsg::msg(1, "WSAStartup failed!");
#endif

#ifdef _WIN32
  char optval=1;
#else
  int optval=1;
#endif

  if ((_sockfd = socket(AF_INET, SOCK_STREAM, 0 )) < 0)
  {
    vvDebugMsg::msg(1, "Error: socket()", true);
    _sockfd = -1;
    return;
  }

  if (setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval,sizeof(optval)))
  {
    vvDebugMsg::msg(1, "Error: setsockopt()");
    _sockfd = -1;
    return;
  }

  memset((char *) &_hostAddr, 0, sizeof(_hostAddr));
  _hostAddr.sin_family = AF_INET;
  _hostAddr.sin_port = htons((unsigned short)port);
  _hostAddr.sin_addr.s_addr = INADDR_ANY;
  _hostAddrlen = sizeof(_hostAddr);
  if  (bind(_sockfd, (struct sockaddr *)&_hostAddr, _hostAddrlen))
  {
    vvDebugMsg::msg(1, "Error: bind()");
    _sockfd = -1;
    return;
  }

  if (listen(_sockfd, 1))
  {
    vvDebugMsg::msg(1, "Error: listen()");
    _sockfd = -1;
    return;
  }
}

vvTcpServer::~vvTcpServer()
{
#ifdef _WIN32
  if(_sockfd >= 0)
    if(closesocket(_sockfd))
      if (WSAGetLastError() ==  WSAEWOULDBLOCK)
        vvDebugMsg::msg(1, "Linger time expires");
  WSACleanup();
#else
  if(_sockfd >= 0)
    if (close(_sockfd))
      if (errno ==  EWOULDBLOCK)
        vvDebugMsg::msg(1, "Linger time expires");
#endif
}

vvTcpSocket* vvTcpServer::nextConnection(double timeout)
{
  if(_sockfd < 0)
  {
    vvDebugMsg::msg(2, "vvTcpServer::nextConnection() error: server not correctly initialized");
  }

#ifdef _WIN32
  SOCKET n;
#else
  int n;
#endif

#ifndef _WIN32
  int flags = fcntl(_sockfd, F_GETFL, 0);
  if(flags < 0)
  {
    vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: Getting flags of server-socket failed");
    return NULL;
  }
#endif

  if (timeout < 0.0 ? false : true)
  {
#ifdef _WIN32
    unsigned long tru = 1;
    ioctlsocket(_sockfd, FIONBIO, &tru);
#else
    if(fcntl(_sockfd, F_SETFL, flags|O_NONBLOCK))
    {
      vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: setting O_NONBLOCK on server-socket failed");
    }
#endif
    vvTcpSocket sock;
    sock.setSockfd(_sockfd);

    std::vector<vvSocket*> socks;
    socks.push_back(&sock);

    vvSocketMonitor sm;
    sm.setReadFds(socks);

    vvSocket* ready;
    sm.wait(&ready, &timeout);

    sock.setSockfd(0);

    if(ready == NULL)
      return NULL;
  }
  else
  {
#ifdef _WIN32
    unsigned long tru = 0;
    ioctlsocket(_sockfd, FIONBIO, &tru);
#else
    if(fcntl(_sockfd, F_SETFL, flags & (~O_NONBLOCK)))
    {
      vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: removing O_NONBLOCK from server-socket failed.");
      return NULL;
    }
#endif
  }

  if ( (n = accept(_sockfd, (struct sockaddr *)&_hostAddr, &_hostAddrlen)) < 0)
  {
    vvDebugMsg::msg(1, "Error: accept()");
    return NULL;
  }

  vvTcpSocket *next = new vvTcpSocket();
  next->setSockfd(n);

  std::ostringstream errmsg;
  errmsg << "Incoming connection from " << inet_ntoa(_hostAddr.sin_addr);
  vvDebugMsg::msg(2, errmsg.str().c_str());

  return next;
}

// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<commit_msg>don't work with broken socket<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo 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.1 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 (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <sstream>

#include "vvdebugmsg.h"
#include "vvsocketmonitor.h"
#include "vvtcpserver.h"
#include "vvtcpsocket.h"

vvTcpServer::vvTcpServer(const ushort port)
{
#ifdef _WIN32
  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
    vvDebugMsg::msg(1, "WSAStartup failed!");
#endif

#ifdef _WIN32
  char optval=1;
#else
  int optval=1;
#endif

  if ((_sockfd = socket(AF_INET, SOCK_STREAM, 0 )) < 0)
  {
    vvDebugMsg::msg(1, "Error: socket()", true);
    _sockfd = -1;
    return;
  }

  if (setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval,sizeof(optval)))
  {
    vvDebugMsg::msg(1, "Error: setsockopt()");
    _sockfd = -1;
    return;
  }

  memset((char *) &_hostAddr, 0, sizeof(_hostAddr));
  _hostAddr.sin_family = AF_INET;
  _hostAddr.sin_port = htons((unsigned short)port);
  _hostAddr.sin_addr.s_addr = INADDR_ANY;
  _hostAddrlen = sizeof(_hostAddr);
  if  (bind(_sockfd, (struct sockaddr *)&_hostAddr, _hostAddrlen))
  {
    vvDebugMsg::msg(1, "Error: bind()");
    _sockfd = -1;
    return;
  }

  if (listen(_sockfd, 1))
  {
    vvDebugMsg::msg(1, "Error: listen()");
    _sockfd = -1;
    return;
  }
}

vvTcpServer::~vvTcpServer()
{
#ifdef _WIN32
  if(_sockfd >= 0)
    if(closesocket(_sockfd))
      if (WSAGetLastError() ==  WSAEWOULDBLOCK)
        vvDebugMsg::msg(1, "Linger time expires");
  WSACleanup();
#else
  if(_sockfd >= 0)
    if (close(_sockfd))
      if (errno ==  EWOULDBLOCK)
        vvDebugMsg::msg(1, "Linger time expires");
#endif
}

vvTcpSocket* vvTcpServer::nextConnection(double timeout)
{
  if(_sockfd < 0)
  {
    vvDebugMsg::msg(2, "vvTcpServer::nextConnection() error: server not correctly initialized");
    return NULL;
  }

#ifdef _WIN32
  SOCKET n;
#else
  int n;
#endif

#ifndef _WIN32
  int flags = fcntl(_sockfd, F_GETFL, 0);
  if(flags < 0)
  {
    vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: Getting flags of server-socket failed");
    return NULL;
  }
#endif

  if (timeout < 0.0 ? false : true)
  {
#ifdef _WIN32
    unsigned long tru = 1;
    ioctlsocket(_sockfd, FIONBIO, &tru);
#else
    if(fcntl(_sockfd, F_SETFL, flags|O_NONBLOCK))
    {
      vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: setting O_NONBLOCK on server-socket failed");
    }
#endif
    vvTcpSocket sock;
    sock.setSockfd(_sockfd);

    std::vector<vvSocket*> socks;
    socks.push_back(&sock);

    vvSocketMonitor sm;
    sm.setReadFds(socks);

    vvSocket* ready;
    sm.wait(&ready, &timeout);

    sock.setSockfd(0);

    if(ready == NULL)
      return NULL;
  }
  else
  {
#ifdef _WIN32
    unsigned long tru = 0;
    ioctlsocket(_sockfd, FIONBIO, &tru);
#else
    if(fcntl(_sockfd, F_SETFL, flags & (~O_NONBLOCK)))
    {
      vvDebugMsg::msg(1, "vvTcpServer::nextConnection() error: removing O_NONBLOCK from server-socket failed.");
      return NULL;
    }
#endif
  }

  if ( (n = accept(_sockfd, (struct sockaddr *)&_hostAddr, &_hostAddrlen)) < 0)
  {
    vvDebugMsg::msg(1, "Error: accept()");
    return NULL;
  }

  vvTcpSocket *next = new vvTcpSocket();
  next->setSockfd(n);

  std::ostringstream errmsg;
  errmsg << "Incoming connection from " << inet_ntoa(_hostAddr.sin_addr);
  vvDebugMsg::msg(2, errmsg.str().c_str());

  return next;
}

// vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "NetworkUtils.hpp"

#include "SubGraphSelector.hpp"

#include <armnn/Exceptions.hpp>

#include <backendsCommon/BackendRegistry.hpp>

namespace armnn
{

std::vector<ConvertFp16ToFp32Layer*> InsertConvertFp16ToFp32LayersBefore(Graph& graph, Layer& layer)
{
    std::vector<ConvertFp16ToFp32Layer*> convertLayers;
    convertLayers.reserve(layer.GetNumInputSlots());

    for (auto&& inputSlot = layer.BeginInputSlots(); inputSlot != layer.EndInputSlots(); ++inputSlot)
    {
        // Insert FP16 to FP32 converter layer before the layer
        const std::string name =
            std::string("convert_fp16_to_fp32-" + std::to_string(inputSlot->GetSlotIndex()) + "-") + layer.GetName();
        ConvertFp16ToFp32Layer* convertLayer =
            graph.InsertNewLayer<ConvertFp16ToFp32Layer>(*inputSlot, name.c_str());

        // Sets output tensor info for the convert layer
        TensorInfo convertInfo = convertLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();
        convertInfo.SetDataType(DataType::Float32);

        convertLayer->GetOutputSlot().SetTensorInfo(convertInfo);

        convertLayers.emplace_back(convertLayer);
    }

    // Sets the output tensor info for the unsupported layer
    auto UpdateTensorInfo = [](auto& outputSlot)
    {
        // Copy original tensor info and change data type to FP32
        TensorInfo newTensorInfo = outputSlot.GetTensorInfo();
        newTensorInfo.SetDataType(DataType::Float32);

        outputSlot.SetTensorInfo(newTensorInfo);
    };

    std::for_each(layer.BeginOutputSlots(), layer.EndOutputSlots(), UpdateTensorInfo);

    return convertLayers;
}

std::vector<ConvertFp32ToFp16Layer*> InsertConvertFp32ToFp16LayersAfter(Graph& graph, Layer& layer)
{
    std::vector<ConvertFp32ToFp16Layer*> convertLayers;
    convertLayers.reserve(layer.GetNumOutputSlots());

    int index = 0;
    // Change outputs to DataType::Float16
    for (auto&& outputSlot = layer.BeginOutputSlots(); outputSlot != layer.EndOutputSlots(); ++outputSlot)
    {
        BOOST_ASSERT(outputSlot->GetTensorInfo().GetDataType() == DataType::Float32);

        // Insert FP32 to FP16 converter layer after the layer
        const std::string name =
            std::string("convert_fp32_to_fp16-" + std::to_string(index++) + "-") + layer.GetName();
        ConvertFp32ToFp16Layer* convertLayer =
            graph.InsertNewLayer<ConvertFp32ToFp16Layer>(*outputSlot, name.c_str());

        // Sets output tensor info for the convert layer.
        TensorInfo convertInfo = convertLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();
        convertInfo.SetDataType(DataType::Float16);

        convertLayer->GetOutputSlot().SetTensorInfo(convertInfo);

        convertLayers.emplace_back(convertLayer);
    }

    return convertLayers;
}

std::vector<DebugLayer*> InsertDebugLayerAfter(Graph& graph, Layer& layer)
{
    std::vector<DebugLayer*> debugLayers;
    debugLayers.reserve(layer.GetNumOutputSlots());

    // Change outputs to DataType::Float16
    for (auto&& outputSlot = layer.BeginOutputSlots(); outputSlot != layer.EndOutputSlots(); ++outputSlot)
    {
        // Insert debug layer after the layer
        const std::string name =
            std::string("DebugLayerAfter") + layer.GetName();

        const DebugDescriptor descriptor;

        DebugLayer* debugLayer =
            graph.InsertNewLayer<DebugLayer>(*outputSlot, descriptor, name.c_str());

        // Sets output tensor info for the debug layer.
        TensorInfo debugInfo = debugLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();

        debugLayer->GetOutputSlot().SetTensorInfo(debugInfo);

        // NOTE: It is OK to do this because DebugLayer is only supported on CpuRef
        debugLayer->SetBackendId(Compute::CpuRef);

        debugLayers.emplace_back(debugLayer);
    }

    return debugLayers;
}

} // namespace armnn
<commit_msg>IVGCVSW-2762 Fix missing layer name and output slot index in DebugLayer output<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "NetworkUtils.hpp"

#include "SubGraphSelector.hpp"

#include <armnn/Exceptions.hpp>

#include <backendsCommon/BackendRegistry.hpp>

namespace armnn
{

std::vector<ConvertFp16ToFp32Layer*> InsertConvertFp16ToFp32LayersBefore(Graph& graph, Layer& layer)
{
    std::vector<ConvertFp16ToFp32Layer*> convertLayers;
    convertLayers.reserve(layer.GetNumInputSlots());

    for (auto&& inputSlot = layer.BeginInputSlots(); inputSlot != layer.EndInputSlots(); ++inputSlot)
    {
        // Insert FP16 to FP32 converter layer before the layer
        const std::string name =
            std::string("convert_fp16_to_fp32-" + std::to_string(inputSlot->GetSlotIndex()) + "-") + layer.GetName();
        ConvertFp16ToFp32Layer* convertLayer =
            graph.InsertNewLayer<ConvertFp16ToFp32Layer>(*inputSlot, name.c_str());

        // Sets output tensor info for the convert layer
        TensorInfo convertInfo = convertLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();
        convertInfo.SetDataType(DataType::Float32);

        convertLayer->GetOutputSlot().SetTensorInfo(convertInfo);

        convertLayers.emplace_back(convertLayer);
    }

    // Sets the output tensor info for the unsupported layer
    auto UpdateTensorInfo = [](auto& outputSlot)
    {
        // Copy original tensor info and change data type to FP32
        TensorInfo newTensorInfo = outputSlot.GetTensorInfo();
        newTensorInfo.SetDataType(DataType::Float32);

        outputSlot.SetTensorInfo(newTensorInfo);
    };

    std::for_each(layer.BeginOutputSlots(), layer.EndOutputSlots(), UpdateTensorInfo);

    return convertLayers;
}

std::vector<ConvertFp32ToFp16Layer*> InsertConvertFp32ToFp16LayersAfter(Graph& graph, Layer& layer)
{
    std::vector<ConvertFp32ToFp16Layer*> convertLayers;
    convertLayers.reserve(layer.GetNumOutputSlots());

    int index = 0;
    // Change outputs to DataType::Float16
    for (auto&& outputSlot = layer.BeginOutputSlots(); outputSlot != layer.EndOutputSlots(); ++outputSlot)
    {
        BOOST_ASSERT(outputSlot->GetTensorInfo().GetDataType() == DataType::Float32);

        // Insert FP32 to FP16 converter layer after the layer
        const std::string name =
            std::string("convert_fp32_to_fp16-" + std::to_string(index++) + "-") + layer.GetName();
        ConvertFp32ToFp16Layer* convertLayer =
            graph.InsertNewLayer<ConvertFp32ToFp16Layer>(*outputSlot, name.c_str());

        // Sets output tensor info for the convert layer.
        TensorInfo convertInfo = convertLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();
        convertInfo.SetDataType(DataType::Float16);

        convertLayer->GetOutputSlot().SetTensorInfo(convertInfo);

        convertLayers.emplace_back(convertLayer);
    }

    return convertLayers;
}

std::vector<DebugLayer*> InsertDebugLayerAfter(Graph& graph, Layer& layer)
{
    std::vector<DebugLayer*> debugLayers;
    debugLayers.reserve(layer.GetNumOutputSlots());

    // Connect a DebugLayer to each output slot of the layer
    unsigned int outputSlotIndex = 0u;
    for (auto&& outputSlot = layer.BeginOutputSlots(); outputSlot != layer.EndOutputSlots(); ++outputSlot)
    {
        const std::string layerName(layer.GetName());
        const std::string debugName = std::string("DebugLayerAfter") + layerName;

        const DebugDescriptor descriptor(layerName, outputSlotIndex++);
        DebugLayer* debugLayer =
            graph.InsertNewLayer<DebugLayer>(*outputSlot, descriptor, debugName.c_str());

        // Sets output tensor info for the debug layer.
        TensorInfo debugInfo = debugLayer->GetInputSlot(0).GetConnectedOutputSlot()->GetTensorInfo();

        debugLayer->GetOutputSlot().SetTensorInfo(debugInfo);

        // NOTE: It is OK to do this because DebugLayer is only supported on CpuRef
        debugLayer->SetBackendId(Compute::CpuRef);

        debugLayers.emplace_back(debugLayer);
    }

    return debugLayers;
}

} // namespace armnn
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program 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.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "SqliteTools.h"

#include <algorithm>

namespace medialibrary
{

namespace sqlite
{
std::unordered_map<Connection::Handle,
                    std::unordered_map<std::string, Statement::CachedStmtPtr>> Statement::StatementsCache;

compat::Mutex Statement::StatementsCacheLock;

std::string Tools::sanitizePattern( const std::string& pattern )
{
    // This assumes the input pattern is a regular user input, ie. that it is not
    // supposed to contain anything that ressembles SQL. What this actually means
    // is that if the user provides an escaped double quote «""» it will result in 2
    // escaped double quotes («""""»)
    std::string res;
    res.reserve( pattern.size() + 3 );
    res.append( "\"" );
    for ( const auto c : pattern )
    {
        if ( c == '"' || c == '\'' )
            res += c;
        res += c;
    }
    res.append( "*\"" );
    return res;
}

}

}
<commit_msg>SqliteTools.cpp: Remove unneeded includes<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program 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.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "SqliteTools.h"

namespace medialibrary
{

namespace sqlite
{
std::unordered_map<Connection::Handle,
                    std::unordered_map<std::string, Statement::CachedStmtPtr>> Statement::StatementsCache;

compat::Mutex Statement::StatementsCacheLock;

std::string Tools::sanitizePattern( const std::string& pattern )
{
    // This assumes the input pattern is a regular user input, ie. that it is not
    // supposed to contain anything that ressembles SQL. What this actually means
    // is that if the user provides an escaped double quote «""» it will result in 2
    // escaped double quotes («""""»)
    std::string res;
    res.reserve( pattern.size() + 3 );
    res.append( "\"" );
    for ( const auto c : pattern )
    {
        if ( c == '"' || c == '\'' )
            res += c;
        res += c;
    }
    res.append( "*\"" );
    return res;
}

}

}
<|endoftext|>