<commit_before>#include "permuter.h"
#include <sys/stat.h>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <boost/algorithm/string.hpp>
#include <codecvt>
#include <locale>
#include <clocale>
#include <cstdlib>

#define ENDL "\n"

Permuter::Permuter() {}

bool Permuter::allGood() {
    return true ||
        (this->fileExists(this->sourceFile) &&
                this->canWriteToFile(this->targetFile));
}

/**
 * @brief Checks if a file exists
 * @details Does not check if the file is readable
 * @param sourceFile std::wstring
 * @return bool true if the file exists
 */
bool Permuter::fileExists(std::string sourceFile) {
    struct stat buffer;
    if (stat (sourceFile.c_str(), &buffer) == 0) {
        std::cout << "fileExists(" << sourceFile << ") -> true" << ENDL;
        return true;
    }
    return false;
}

bool Permuter::canWriteToFile(std::string targetFile) {
    FILE * pFile;
    const char* param = targetFile.c_str();
    pFile = fopen(param, "w");
    return pFile != NULL;
}

void Permuter::setWord(std::wstring word) {}

/**
 * @brief Counts lines in a file
 * @details [long description]
 *
 * @param pathToFile The path to the file to count lines from
 * @return int The number of lines in a file
 */
int Permuter::countLinesInFile(std::string pathToFile) {
    std::ifstream sFile(pathToFile);
    std::string line;
    int total = 0;
    for (; std::getline(sFile, line); ++total);
    return total;
}

void Permuter::setSourceFile(std::string sourceFile) { this->sourceFile = sourceFile; }
void Permuter::setTargetFile(std::string targetFile) { this->targetFile = targetFile; }

std::vector<std::wstring> Permuter::fileToVector(std::string sourceFile) {
    std::vector<std::wstring> originalWords;

    std::ifstream hFile(sourceFile);
    if (hFile.is_open()) {
        // typedef std::codecvt_utf8<wchar_t> converter_type;
        // const std::locale empty_locale = std::locale();
        // const converter_type* converter = new converter_type;
        // const std::locale utf8_locale = std::locale(empty_locale, converter);
        std::wifstream stream(sourceFile);
        // stream.imbue(utf8_locale);

        std::wstring line;
        while (stream.good()) {
            std::getline(stream, line);
            // getline(hFile, line);
            originalWords.push_back(line);
        }
    }
    return originalWords;
}

bool Permuter::hasLowerCase(std::wstring toCheck) {
    return std::any_of(toCheck.begin(), toCheck.end(), ::islower);
}
/**
 * @details Takes the original word and returns a vector of all combinations with different cases
 *
 * @param original string of the original word to permute
 * @return [Chess, CHESS, chess, CHess, CHEss, CHESs, CHESS, cHess, cHEss, cHESs,...]
 */
std::vector<std::wstring> Permuter::mixCases(std::wstring original) {
    std::vector<std::wstring> mixedCases;
    // start with an upper case word
    std::wstring upper = boost::to_upper_copy<std::wstring>(original);

    mixedCases.push_back(upper);
    mixedCases.push_back(original);
    mixedCases.push_back(boost::to_lower_copy<std::wstring>(original));

    // std::vector<std::wstring>::iterator ite = mixedCases.begin();
    std::vector<std::wstring> lower_cases = this->mixOfLowerCases(original);
    // std::cout << "Added " << upper << " and " << original << ENDL;
    // std::cout << mixedCases[0] << ENDL;

    mixedCases = this->mergeVectors(mixedCases, lower_cases);
    // There shouldn't be any duplicates but lets make sure
    this->uniqueVector(mixedCases);
    return mixedCases;
}

/**
 * @brief Returns every combination of upper and lower case
 * @details [long description]
 *
 * @param original [description]
 * @return [Chess, CHess, cHess, cHEss,...]
 */
std::vector<std::wstring> Permuter::mixOfLowerCases(std::wstring original) {
    std::vector<std::wstring> lowerCases;
    std::wstring debug1 = std::wstring(L"mixOfLowerCases(") + original + std::wstring(L");");
    std::wcout << debug1 << ENDL;
    // int boundChecker = 0;
    //por cada posicion
    //    convierta esa posicion a mayuscula --> Chess, cHess, chEss

    std::wstring upper = this->to_upper(original);
    // for (std::wstring::iterator ite = original.begin(); ite < original.end(); ite++) {
    // for(std::wstring::size_type char_pos = 0; char_pos < temp.size(); ++char_pos) {
    for (std::wstring::iterator it = upper.begin(); it != upper.end(); it++) {
        for(std::wstring::size_type iteration = 0; iteration < original.size(); ++iteration) {
            std::wcout << "Testing upper[" <<  *it << "]" <<  ENDL;
            // std::cout << boost::algorithm::to_lower(*ite) << ENDL;
            // std::wcout << "Testing original[" << iteration << "," << char_pos << "] = " << original[char_pos] << ENDL;
        }
    }

    /*while(this->hasLowerCase(original) && boundChecker < 10) {
        boundChecker++;
        //original = original.
    }*/
    return lowerCases;
}

std::wstring Permuter::to_upper(std::wstring original) {
    for (std::wstring::iterator it = original.begin(); it != original.end(); it++) {
        *it = towupper(*it);
    }
    return original;
}

/**
 * @brief Removes duplicate entries in an std::vector
 *
 * @param originalVector vector of string
 */
void Permuter::uniqueVector(std::vector<std::wstring> &originalVector) {
    sort( originalVector.begin(), originalVector.end() );
    originalVector.erase( unique( originalVector.begin(), originalVector.end() ), originalVector.end() );
}

/**
 * @brief Merges vectors
 *
 * @return A new array with the unique contents of arrays a and b
 */
std::vector<std::wstring> Permuter::mergeVectors(std::vector<std::wstring> a, std::vector<std::wstring> b) {
    std::vector<std::wstring> merged;
    merged.insert(merged.end(), a.begin(), a.end());
    merged.insert(merged.end(), b.begin(), b.end());
    this->uniqueVector(merged);
    return merged;
}

std::vector<std::wstring> Permuter::getPermutations(std::wstring original) {
    std::vector<std::wstring> permutations;
    std::vector<std::wstring> mixedCases = this->mixCases(original);

    // Merge vectors
    permutations.insert(permutations.end(), mixedCases.begin(), mixedCases.end());

    // Remove duplicates
    this->uniqueVector(permutations);

    return permutations;
}

void Permuter::savePermutationsToFile(std::vector<std::wstring> words) {
    // std::cout << "savePermutationsToFile() -> "
    std::wofstream store;
    store.open(this->targetFile);

    for (std::vector<std::wstring>::iterator ite = words.begin(); ite != words.end(); ite++) {
        std::wcout << std::wstring(L"savePermutationsToFile(vector<string>) -> Storing: ") << *ite << ENDL;
        store << *ite << ENDL;
    }
    store.close();
}

void Permuter::run() {
    if (true || this->fileExists(this->sourceFile) == true) {
        std::vector<std::wstring> permutations;
        std::cout << this->sourceFile << " <--> " << this->targetFile << ENDL;
        // this->sourceWords = this->fileToVector(this->sourceFile);
        this->sourceWords.push_back(L"Tjäna");
        std::cout << "Total words to permute: " << this->sourceWords.size() << ENDL;
        for (std::vector<std::wstring>::iterator ite = this->sourceWords.begin(); ite != this->sourceWords.end(); ite++ ) {
             std::wcout << std::wstring(L"run() -> ") << *ite << ENDL;
             permutations = this->getPermutations(*ite);
             this->savePermutationsToFile(permutations);
        }

        // std::cout << "permutations[0]: " << permutations[0] << ENDL;
    } else {
        std::cout << "Not everything is ok" << ENDL;
    }

}<commit_msg>Feature 0.2 complete<commit_after>#include "permuter.h"
#include <sys/stat.h>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <boost/algorithm/string.hpp>
#include <codecvt>
#include <locale>
#include <clocale>
#include <cstdlib>

#define ENDL "\n"

Permuter::Permuter() {}

bool Permuter::allGood() {
    return true ||
        (this->fileExists(this->sourceFile) &&
                this->canWriteToFile(this->targetFile));
}

/**
 * @brief Checks if a file exists
 * @details Does not check if the file is readable
 * @param sourceFile std::wstring
 * @return bool true if the file exists
 */
bool Permuter::fileExists(std::string sourceFile) {
    struct stat buffer;
    if (stat (sourceFile.c_str(), &buffer) == 0) {
        std::cout << "fileExists(" << sourceFile << ") -> true" << ENDL;
        return true;
    }
    return false;
}

bool Permuter::canWriteToFile(std::string targetFile) {
    FILE * pFile;
    const char* param = targetFile.c_str();
    pFile = fopen(param, "w");
    return pFile != NULL;
}

void Permuter::setWord(std::wstring word) {}

/**
 * @brief Counts lines in a file
 * @details [long description]
 *
 * @param pathToFile The path to the file to count lines from
 * @return int The number of lines in a file
 */
int Permuter::countLinesInFile(std::string pathToFile) {
    std::ifstream sFile(pathToFile);
    std::string line;
    int total = 0;
    for (; std::getline(sFile, line); ++total);
    return total;
}

void Permuter::setSourceFile(std::string sourceFile) { this->sourceFile = sourceFile; }
void Permuter::setTargetFile(std::string targetFile) { this->targetFile = targetFile; }

std::vector<std::wstring> Permuter::fileToVector(std::string sourceFile) {
    std::vector<std::wstring> originalWords;

    std::ifstream hFile(sourceFile);
    if (hFile.is_open()) {
        std::wifstream stream(sourceFile);
        std::wstring line;
        while (stream.good()) {
            std::getline(stream, line);
            // getline(hFile, line);
            originalWords.push_back(line);
        }
    }
    return originalWords;
}

bool Permuter::hasLowerCase(std::wstring toCheck) {
    return std::any_of(toCheck.begin(), toCheck.end(), ::islower);
}
/**
 * @details Takes the original word and returns a vector of all combinations with different cases
 *
 * @param original string of the original word to permute
 * @return [Chess, CHESS, chess, CHess, CHEss, CHESs, CHESS, cHess, cHEss, cHESs,...]
 */
std::vector<std::wstring> Permuter::mixCases(std::wstring original) {
    std::vector<std::wstring> mixedCases;
    // start with an upper case word
    std::wstring upper = boost::to_upper_copy<std::wstring>(original);

    mixedCases.push_back(upper);
    mixedCases.push_back(original);
    mixedCases.push_back(boost::to_lower_copy<std::wstring>(original));

    // std::vector<std::wstring>::iterator ite = mixedCases.begin();
    std::vector<std::wstring> lower_cases = this->mixOfLowerCases(original);
    // std::cout << "Added " << upper << " and " << original << ENDL;
    // std::cout << mixedCases[0] << ENDL;

    mixedCases = this->mergeVectors(mixedCases, lower_cases);
    // There shouldn't be any duplicates but lets make sure
    this->uniqueVector(mixedCases);
    return mixedCases;
}

/**
 * @brief Returns every combination of upper and lower case
 * @details [long description]
 *
 * @param original [description]
 * @return [Chess, CHess, cHess, cHEss,...]
 */
std::vector<std::wstring> Permuter::mixOfLowerCases(std::wstring original) {
    std::vector<std::wstring> lower_cases;

    std::wstring upper = this->to_upper(original);
    std::wstring temp_string;
    int original_size = original.size();

    for(std::wstring::size_type current_char = 0; current_char <= original_size; ++current_char) {
        temp_string = upper;
        for(std::wstring::size_type iteration = 0; iteration <= (original_size); ++iteration) {
            // This routine creates duplicated entries, it can certainly be improved
            temp_string[current_char] = towlower(temp_string[current_char]);
            lower_cases.push_back(temp_string);
            temp_string[current_char + iteration] = towlower(temp_string[current_char + iteration]);
            lower_cases.push_back(temp_string);
        }
    }

    this->uniqueVector(lower_cases);

    return lower_cases;
}

void Permuter::printVector(std::vector<std::wstring> original) {
    for (std::vector<std::wstring>::iterator i = original.begin(); i != original.end(); i++) {
        std::wcout << *i << ENDL;
    }
}

std::wstring Permuter::to_upper(std::wstring original) {
    for (std::wstring::iterator it = original.begin(); it != original.end(); it++) {
        *it = towupper(*it);
    }
    return original;
}

/**
 * @brief Removes duplicate entries in an std::vector
 *
 * @param originalVector vector of string
 */
void Permuter::uniqueVector(std::vector<std::wstring> &originalVector) {
    sort( originalVector.begin(), originalVector.end() );
    originalVector.erase( unique( originalVector.begin(), originalVector.end() ), originalVector.end() );
}

/**
 * @brief Merges vectors
 *
 * @return A new array with the unique contents of arrays a and b
 */
std::vector<std::wstring> Permuter::mergeVectors(std::vector<std::wstring> a, std::vector<std::wstring> b) {
    std::vector<std::wstring> merged;
    merged.insert(merged.end(), a.begin(), a.end());
    merged.insert(merged.end(), b.begin(), b.end());
    this->uniqueVector(merged);
    return merged;
}

std::vector<std::wstring> Permuter::getPermutations(std::wstring original) {
    std::vector<std::wstring> permutations;
    std::vector<std::wstring> mixedCases = this->mixCases(original);

    // Merge vectors
    permutations.insert(permutations.end(), mixedCases.begin(), mixedCases.end());

    // Remove duplicates
    this->uniqueVector(permutations);

    return permutations;
}

void Permuter::savePermutationsToFile(std::vector<std::wstring> words) {
    // std::cout << "savePermutationsToFile() -> "
    std::wofstream store;
    store.open(this->targetFile);

    for (std::vector<std::wstring>::iterator ite = words.begin(); ite != words.end(); ite++) {
        std::wcout << std::wstring(L"savePermutationsToFile(vector<string>) -> Storing: ") << *ite << ENDL;
        store << *ite << ENDL;
    }
    store.close();
}

void Permuter::run() {
    if (true || this->fileExists(this->sourceFile) == true) {
        std::vector<std::wstring> permutations;
        std::cout << this->sourceFile << " <--> " << this->targetFile << ENDL;
        // this->sourceWords = this->fileToVector(this->sourceFile);
        this->sourceWords.push_back(L"Tjäna");
        std::cout << "Total words to permute: " << this->sourceWords.size() << ENDL;
        for (std::vector<std::wstring>::iterator ite = this->sourceWords.begin(); ite != this->sourceWords.end(); ite++ ) {
             std::wcout << std::wstring(L"run() -> ") << *ite << ENDL;
             permutations = this->getPermutations(*ite);
             this->savePermutationsToFile(permutations);
        }

        // std::cout << "permutations[0]: " << permutations[0] << ENDL;
    } else {
        std::cout << "Not everything is ok" << ENDL;
    }

}<|endoftext|>


<commit_before>#include <Python.h>

int main(int argc, char *argv[])
{
    using wchar_p = wchar_t*;
    wchar_p wargv[argc];
    for (int i = 0; i < argc; ++i) {
        wargv[i] = Py_DecodeLocale(argv[i], NULL);
    }

    int res = Py_Main(argc, wargv);

    for (int i = 0; i < argc; ++i) {
        PyMem_RawFree(wargv[i]);
    }

    return res;
}
<commit_msg>Remove unecessary for brackets<commit_after>#include <Python.h>

int main(int argc, char *argv[])
{
    using wchar_p = wchar_t*;
    wchar_p wargv[argc];
    for (int i = 0; i < argc; ++i)
        wargv[i] = Py_DecodeLocale(argv[i], NULL);

    int res = Py_Main(argc, wargv);

    for (int i = 0; i < argc; ++i)
        PyMem_RawFree(wargv[i]);

    return res;
}
<|endoftext|>


<commit_before>/*******************************************************************************/
/* Bela Csound Rendering functions                                             */
/*                                                                           */
/*******************************************************************************/

#include <Bela.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>

static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
			int nbytes);

struct csChan {
  std::vector<MYFLT> data;
  std::stringstream name;
};

struct csData{
  Csound *csound;
  int blocksize;
  int res;
  int count;
  std::vector<csChan> channel;
};

struct csMIDI {
  Midi midi;
};

csData* gCsData;

bool setup(BelaContext *context, void *userData)
{
  Csound *csound = new Csound();
  const char *csdfile = "my.csd"; /* CSD name */
  const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
  int numArgs = 8;
  const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
		   "--realtime", "--daemon", midiDev};

  gCsData  = new csData;
  csound->SetHostImplementedAudioIO(1,0);
  csound->SetHostImplementedMIDIIO(1);
  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
  csound->SetExternalMidiReadCallback(ReadMidiData);
  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
  gCsData->res = csound->Compile(numArgs, args);
  gCsData->csound = csound;
  gCsData->blocksize =
    csound->GetKsmps()*userData->csound->GetNchnls();
  gCsData->count = 0;

  /* set up the channels */
  gCsData->channel.resize(context->analogInChannels);
  for(int i; i < context->analogInChannels; i++) {
    gCsData->channel[i].data.resize(csound->GetKsmps());
    gCsData->channel[i].name << "analogue" << i+1;
  }

  if(gCsData->res != 0) return false;
  else return true;
}

void render(BelaContext *context, void *Data)
{
  csData *userData = gCsData;
  if(gCsData->res == 0) {
    int n,i,k,count, frmcount,blocksize,res;
    CSOUND *csound = userData->csound;
    MYFLT scal = csound->Get0dBFS();
    MYFLT* audioIn = csound->GetSpin();
    MYFLT* audioOut = csound->GetSpout();
    int nchnls = csound->GetNchnls();
    int chns = nchnls;
    int an_chns = context->analogInChannels;
    csChan *channel = &(userData->channel[0]);
    float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames;
    int an_chans = context->analogInChannels;
    count = userData->count;
    blocksize = userData->blocksize;

    /* this is called when Csound is not running */
    if(count < 0) {
      for(n = 0; n < context->audioFrames; n++){
	for(i = 0; i < context->audioOutChannels; i++){
	  audioWrite(context,n,i,0);
	}
      }
      return;
    }

    if(chns > context->audioOutChannels)
      chns = context->audioOutChannels;

    /* this is where Csound is called */
    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
      if(count == blocksize) {
	/* set the channels */
	for(i = 0; i < an_chns; i++) {
          csound->SetChannel(channel[i].name.str().c_str(),
			     &(channel[i].data[0]));
	}
	/* run csound */
	if((res = csound->PerformKsmps()) == 0) count = 0;
	else {
	  count = -1;
	  break;
	}
      }
      /* read/write audio data */
      for(i = 0; i < chns; i++){
	audioIn[count+i] = audioRead(context,n,i);
	audioWrite(context,n,i,audioOut[count+i]/scal);
      }

      /* read analogue data
         analogue frame pos gets incremented according to the
         ratio analogFrames/audioFrames.
      */
      frmcount = count/nchnls;
      for(i = 0; i < an_chns; i++) {
	k = (int) frm;
        channel[i].data[frmcount] = analogRead(context,k,i);
      }
    }
    gCsData->res = res;
    userData->count = count;
  }
}

void cleanup(BelaContext *context, void *Data)
{
  csData *userData = gCsData;
  delete userData->csound;
  delete userData;
}

/** MIDI Input functions
 */
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
  csMIDI *midiData = new CsMIDI;
  Midi &midi = midiData->midi;
  midi.readFrom(dev);
  midi.enableParser(false);
  *userData = (void *) midiData;
}

int CloseMidiInDevice(CSOUND *csound, void *userData) {
  csMIDI *midiData = (CsMIDI *) userData;
  delete midiData;
}

int ReadMidiData(CSOUND *csound, void *userData,
		 unsigned char *mbuf, int nbytes) {
  int n = 0;
  csMIDI *midiData = (CsMIDI *) userData;
  Midi &midi = midiData->midi;

  while((byte = midi.getInput()) >= 0) {
    *mbuf++ = (unsigned char) byte;
    if(++n == nbytes) break;
  }

  return n;
}
<commit_msg>header<commit_after>/*******************************************************************************/
/* Bela Csound Rendering functions                                             */
/*                                                                             */
/*******************************************************************************/

#include <Bela.h>
#include <csound/csound.hpp>
#include <vector>
#include <sstream>

static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
			int nbytes);

struct csChan {
  std::vector<MYFLT> data;
  std::stringstream name;
};

struct csData{
  Csound *csound;
  int blocksize;
  int res;
  int count;
  std::vector<csChan> channel;
};

struct csMIDI {
  Midi midi;
};

csData* gCsData;

bool setup(BelaContext *context, void *userData)
{
  Csound *csound = new Csound();
  const char *csdfile = "my.csd"; /* CSD name */
  const char *midiDev = "-Mhw:1,0,0"; /* MIDI device */
  int numArgs = 8;
  const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
		   "--realtime", "--daemon", midiDev};

  gCsData  = new csData;
  csound->SetHostImplementedAudioIO(1,0);
  csound->SetHostImplementedMIDIIO(1);
  csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
  csound->SetExternalMidiReadCallback(ReadMidiData);
  csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
  gCsData->res = csound->Compile(numArgs, args);
  gCsData->csound = csound;
  gCsData->blocksize =
    csound->GetKsmps()*userData->csound->GetNchnls();
  gCsData->count = 0;

  /* set up the channels */
  gCsData->channel.resize(context->analogInChannels);
  for(int i; i < context->analogInChannels; i++) {
    gCsData->channel[i].data.resize(csound->GetKsmps());
    gCsData->channel[i].name << "analogue" << i+1;
  }

  if(gCsData->res != 0) return false;
  else return true;
}

void render(BelaContext *context, void *Data)
{
  csData *userData = gCsData;
  if(gCsData->res == 0) {
    int n,i,k,count, frmcount,blocksize,res;
    CSOUND *csound = userData->csound;
    MYFLT scal = csound->Get0dBFS();
    MYFLT* audioIn = csound->GetSpin();
    MYFLT* audioOut = csound->GetSpout();
    int nchnls = csound->GetNchnls();
    int chns = nchnls;
    int an_chns = context->analogInChannels;
    csChan *channel = &(userData->channel[0]);
    float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames;
    int an_chans = context->analogInChannels;
    count = userData->count;
    blocksize = userData->blocksize;

    /* this is called when Csound is not running */
    if(count < 0) {
      for(n = 0; n < context->audioFrames; n++){
	for(i = 0; i < context->audioOutChannels; i++){
	  audioWrite(context,n,i,0);
	}
      }
      return;
    }

    if(chns > context->audioOutChannels)
      chns = context->audioOutChannels;

    /* this is where Csound is called */
    for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
      if(count == blocksize) {
	/* set the channels */
	for(i = 0; i < an_chns; i++) {
          csound->SetChannel(channel[i].name.str().c_str(),
			     &(channel[i].data[0]));
	}
	/* run csound */
	if((res = csound->PerformKsmps()) == 0) count = 0;
	else {
	  count = -1;
	  break;
	}
      }
      /* read/write audio data */
      for(i = 0; i < chns; i++){
	audioIn[count+i] = audioRead(context,n,i);
	audioWrite(context,n,i,audioOut[count+i]/scal);
      }

      /* read analogue data
         analogue frame pos gets incremented according to the
         ratio analogFrames/audioFrames.
      */
      frmcount = count/nchnls;
      for(i = 0; i < an_chns; i++) {
	k = (int) frm;
        channel[i].data[frmcount] = analogRead(context,k,i);
      }
    }
    gCsData->res = res;
    userData->count = count;
  }
}

void cleanup(BelaContext *context, void *Data)
{
  csData *userData = gCsData;
  delete userData->csound;
  delete userData;
}

/** MIDI Input functions
 */
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
  csMIDI *midiData = new CsMIDI;
  Midi &midi = midiData->midi;
  midi.readFrom(dev);
  midi.enableParser(false);
  *userData = (void *) midiData;
}

int CloseMidiInDevice(CSOUND *csound, void *userData) {
  csMIDI *midiData = (CsMIDI *) userData;
  delete midiData;
}

int ReadMidiData(CSOUND *csound, void *userData,
		 unsigned char *mbuf, int nbytes) {
  int n = 0;
  csMIDI *midiData = (CsMIDI *) userData;
  Midi &midi = midiData->midi;

  while((byte = midi.getInput()) >= 0) {
    *mbuf++ = (unsigned char) byte;
    if(++n == nbytes) break;
  }

  return n;
}
<|endoftext|>


<commit_before>//
// Created by volundr on 7/19/16.
//

#include <vector>
#include <iostream>
#include "Bno055Interface.h"

namespace bno055 {

    bool Bno055Interface::init(const char* bno055File) {

        #define REPORT_FAILURE(byteSent) std::cout << "Did not receive response after sending " byteSent "\n"; wasSuccess = false
        bool wasSuccess = true;
        if ( ! uart.openPort(bno055File, BNO055_BAUD_RATE) ) {
            std::cout << "Could not open serial connection to bno055!\n";
            wasSuccess = false;
        }
        if ( ! writeByte(OPR_MODE, CONFIG) ) {
            REPORT_FAILURE("OPR_MODE");
            wasSuccess = false;
        }
        if ( ! writeByte(PWR_MODE, NORMAL) ) {
            REPORT_FAILURE("PWR_MODE");
            wasSuccess = false;
        }
        if ( ! writeByte(Page_ID, 0) ) {
            REPORT_FAILURE("Page_ID");
            wasSuccess = false;
        }
        if ( ! writeByte(SYS_TRIGGER, 0) ) {
            REPORT_FAILURE("SYS_TRIGGER");
            wasSuccess = false;
        }
        if ( ! writeByte(UNIT_SEL, 0x83) ) {
            REPORT_FAILURE("UNIT_SEL");
            wasSuccess = false;
        }
        if ( ! writeByte(AXIS_MAP_CONFIG, 0x24) ) {
            REPORT_FAILURE("AXIS_MAP_CONFIG");
            wasSuccess = false;
        }
        if ( ! writeByte(AXIS_MAP_SIGN, 0x06) ) {
            REPORT_FAILURE("AXIS_MAP_SIGN");
            wasSuccess = false;
        }
        if ( ! writeByte(OPR_MODE, NDOF) ) {
            REPORT_FAILURE("OPR_MODE");
            wasSuccess = false;
        }
        #undef REPORT_FAILURE

        hasInit = wasSuccess;
        return wasSuccess;
    }

    bool Bno055Interface::write(uint8_t regAddr, uint8_t length, uint8_t* data) {
        RegisterWritePacket packetToSend(regAddr, length, data);
        uart.sendData(packetToSend.bytes(), packetToSend.length);
        ReceivedAck ack;
        int loopCount = 0;
        while (ack.readFrom(uart) != RECEIVED_EXPECTED) {
            if (++loopCount > 100) {
                std::cout << "ack reception timed out!\n";
                return false;
            }
        }
        std::cout << "ack received.\n";
        return (ack.isValidAck() && ! ack.isErrorStatus());
    }

    bool Bno055Interface::writeByte(uint8_t regAddr, uint8_t data) {
        return write(regAddr, 1, &data);
    }

    bool Bno055Interface::isLive() {
        return hasInit;
    }

}

<commit_msg>no message<commit_after>//
// Created by volundr on 7/19/16.
//

#include <vector>
#include <iostream>
#include "Bno055Interface.h"

namespace bno055 {

    bool Bno055Interface::init(const char* bno055File) {

        #define REPORT_FAILURE(byteSent) std::cout << "Did not receive response after sending " byteSent "\n"; wasSuccess = false
        bool wasSuccess = true;
        if ( ! uart.openPort(bno055File, BNO055_BAUD_RATE) ) {
            std::cout << "Could not open serial connection to bno055!\n";
            wasSuccess = false;
        }
        if ( ! writeByte(OPR_MODE, CONFIG) ) {
            REPORT_FAILURE("OPR_MODE");
            wasSuccess = false;
        }
        if ( ! writeByte(PWR_MODE, NORMAL) ) {
            REPORT_FAILURE("PWR_MODE");
            wasSuccess = false;
        }
        if ( ! writeByte(Page_ID, 0) ) {
            REPORT_FAILURE("Page_ID");
            wasSuccess = false;
        }
        if ( ! writeByte(SYS_TRIGGER, 0) ) {
            REPORT_FAILURE("SYS_TRIGGER");
            wasSuccess = false;
        }
        if ( ! writeByte(UNIT_SEL, 0x83) ) {
            REPORT_FAILURE("UNIT_SEL");
            wasSuccess = false;
        }
        if ( ! writeByte(AXIS_MAP_CONFIG, 0x24) ) {
            REPORT_FAILURE("AXIS_MAP_CONFIG");
            wasSuccess = false;
        }
        if ( ! writeByte(AXIS_MAP_SIGN, 0x06) ) {
            REPORT_FAILURE("AXIS_MAP_SIGN");
            wasSuccess = false;
        }
        if ( ! writeByte(OPR_MODE, NDOF) ) {
            REPORT_FAILURE("OPR_MODE");
            wasSuccess = false;
        }
        #undef REPORT_FAILURE

        hasInit = wasSuccess;
        return wasSuccess;
    }

    bool Bno055Interface::write(uint8_t regAddr, uint8_t length, uint8_t* data) {
        RegisterWritePacket packetToSend(regAddr, length, data);
        uart.sendData(packetToSend.bytes(), packetToSend.length);
        ReceivedAck ack;
        int loopCount = 0;
        while (ack.readFrom(uart) != RECEIVED_EXPECTED) {
            if (++loopCount > 1000) {
                std::cout << "ack reception timed out!\n";
                return false;
            }
        }
        std::cout << "ack received.\n";
        return (ack.isValidAck() && ! ack.isErrorStatus());
    }

    bool Bno055Interface::writeByte(uint8_t regAddr, uint8_t data) {
        return write(regAddr, 1, &data);
    }

    bool Bno055Interface::isLive() {
        return hasInit;
    }

}

<|endoftext|>


<commit_before>#include <iomanip>
#include <iostream>
#include <fstream>

#include "config.h"

void print_value_summary(const Config::Value v) {
    std::cout << "Summary of value:" << std::endl;
    try {
        std::string v_string = v.as_string();
        std::cout << "    Value as a string = [" << v_string << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a string." << std::endl;
    }
    try {
        int64_t v_integer = v.as_integer();
        std::cout << "    Value as an integer = [" << v_integer << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to an integer."
            << std::endl;
    }
    try {
        double v_float = v.as_float();
        std::cout << std::setprecision(9);
        std::cout << "    Value as a float = [" << v_float << "]" << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a float." << std::endl;
    }
    try {
        bool v_boolean = v.as_boolean();
        std::cout << std::boolalpha;
        std::cout << "    Value as a boolean = [" << v_boolean << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a boolean." << std::endl;
    }
}

// ============================================================================

void try_to_set(Config::Value& v, const std::string s) {
    try {
        std::cout << "Set value to [" << s << "]." << std::endl;
        v.set_from_string(s);
        print_value_summary(v);
        std::cout << "    serialize as [" << v.serialize() << "]" << std::endl;
    } catch(Config::ParseError& pe) {
        std::cout << "Could not compute valid Value from [" << s << "]: "
            << std::endl;
        std::cout << "    " << pe.what() << std::endl;
    }
}

// ============================================================================

int main(int argc, char *argv[]) {
    Config::Value v;
    print_value_summary(v);

    try_to_set(v, "yes");
    try_to_set(v, "\"yes");
    try_to_set(v, "\"yes\"");
    try_to_set(v, "\"\\\"yes\\\" or \\\"no\\\"\"");
    try_to_set(v, "true");
    try_to_set(v, "false");
    try_to_set(v, "150");
    try_to_set(v, "0");
    try_to_set(v, "-73");
    try_to_set(v, ".01");
    try_to_set(v, "0.01");
    try_to_set(v, "3.141592654");
    try_to_set(v, "-2.718281828");
    try_to_set(v, "123456789.0");
    try_to_set(v, "   3.6e2");
    try_to_set(v, "9.87654321e5");
    try_to_set(v, "1.23456789E5");
    try_to_set(v, "12345678901234567.89    # this is a comment");
    try_to_set(v, "6.022e23");

    std::string file = "yes = \"yes\" # YES\nno=0\nmaybe    =0.5\nwhat=\"\\\"what\\nare\\byou\\ttalking\\nabout?\\\"\"";
    std::cout << std::endl;
    std::cout << "Parse [" << file << "]" << std::endl;
    Config::Group group;
    group.parse_string(file);
    std::vector<std::string> keys = group.scalar_keys();
    for (auto it = keys.begin(); it != keys.end(); it++) {
        std::cout << "    " << *it << " = " << group.get_scalar(*it)
            << std::endl;
    }
    keys = group.array_keys();
    for (auto it = keys.begin(); it != keys.end(); it++) {
        std::cout << "    " << *it << " = " << group.get_array(*it)
            << std::endl;
    }
    std::cout << "what (as a string) --> "
        << group.get_scalar("what").as_string() << std::endl;

    file = "parameters.config";
    std::cout << std::endl;
    std::cout << "Parse file \"" << file << "\"" << std::endl;
    group.parse_file(file);
    std::cout << group;

    return 0;
}
<commit_msg>Some tweaks to my test driver.<commit_after>#include <iomanip>
#include <iostream>
#include <fstream>

#include "config.h"

void print_value_summary(const Config::Value v) {
    std::cout << "Summary of value:" << std::endl;
    try {
        std::string v_string = v.as_string();
        std::cout << "    Value as a string = [" << v_string << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a string." << std::endl;
    }
    try {
        int64_t v_integer = v.as_integer();
        std::cout << "    Value as an integer = [" << v_integer << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to an integer."
            << std::endl;
    }
    try {
        double v_float = v.as_float();
        std::cout << std::setprecision(9);
        std::cout << "    Value as a float = [" << v_float << "]" << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a float." << std::endl;
    }
    try {
        bool v_boolean = v.as_boolean();
        std::cout << std::boolalpha;
        std::cout << "    Value as a boolean = [" << v_boolean << "]"
            << std::endl;
    } catch(Config::TypeError& te) {
        std::cout << "    Value is not conformable to a boolean." << std::endl;
    }
}

// ============================================================================

void try_to_set(Config::Value& v, const std::string s) {
    try {
        std::cout << "Set value to [" << s << "]." << std::endl;
        v.set_from_string(s);
        print_value_summary(v);
        std::cout << "    serialize as [" << v.serialize() << "]" << std::endl;
    } catch(Config::ParseError& pe) {
        std::cout << "Could not compute valid Value from [" << s << "]: "
            << std::endl;
        std::cout << "    " << pe.what() << std::endl;
    }
}

// ============================================================================

int main(int argc, char *argv[]) {
    Config::Value v;
    print_value_summary(v);

    try_to_set(v, "yes");
    try_to_set(v, "\"yes");
    try_to_set(v, "\"yes\"");
    try_to_set(v, "\"\\\"yes\\\" or \\\"no\\\"\"");
    try_to_set(v, "true");
    try_to_set(v, "false");
    try_to_set(v, "150");
    try_to_set(v, "0");
    try_to_set(v, "-73");
    try_to_set(v, ".01");
    try_to_set(v, "0.01");
    try_to_set(v, "3.141592654");
    try_to_set(v, "-2.718281828");
    try_to_set(v, "123456789.0");
    try_to_set(v, "   3.6e2");
    try_to_set(v, "9.87654321e5");
    try_to_set(v, "1.23456789E5");
    try_to_set(v, "12345678901234567.89    # this is a comment");
    try_to_set(v, "6.022e23");

    std::string file = "yes = \"yes\" # YES\nno=0\nmaybe    =0.5\nwhat=\"\\\"what\\nare\\byou\\ttalking\\nabout?\\\"\"";
    std::cout << std::endl;
    std::cout << "Parse [" << file << "]" << std::endl;
    Config::Group group;
    group.parse_string(file);
    std::cout << group;
    std::cout << "what (as a string) --> "
        << group.get_scalar("what").as_string() << std::endl;
    try {
        std::cout << "who --> " << group.get_scalar("who") << std::endl;
    } catch (std::out_of_range& err) {
        std::cout << "key \"who\" does not exist" << std::endl;
    }

    file = "parameters.config";
    std::cout << std::endl;
    std::cout << "Parse file \"" << file << "\"" << std::endl;
    group.parse_file(file);
    std::cout << group;

    std::cout << std::endl;
    std::cout << "Access of specific members:" << std::endl;
    std::cout << "    float2 -- > " << group.get_scalar("float2") << std::endl;
    std::cout << "    array_var --> " << group.get_array("array_var")
        << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "timer.h"
#include <QToolButton>
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <QApplication>

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

#pragma comment(lib, "ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define SERVER "127.0.0.1" //ip adress of udp server
#define PORT 8888
#define BUFLEN 512
struct sockaddr_in server, si_other;
SOCKET s;
int slen;
char buf[BUFLEN];
WSADATA wsa;

#define TestSize 1000
bool stop = false;
unsigned long startTime = 0;
std::pair<QPushButton*,QPushButton*> p300Array[TestSize];
int arr[TestSize];
bool arrcomplet = false;
int BSLEEPTIME = 80;
int ASLEEPTIME = 100;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Remote Home");
    this->setMinimumSize(927, 581);
    this->setMaximumSize(927, 581);

    ui->pushButton_2->setEnabled(false);
    ui->volume_widget->hide();
    ui->channel_widget->hide();

    ui->frequency_Bspin->setValue(BSLEEPTIME);
    ui->frequency_Aspin->setValue(ASLEEPTIME);

    slen = sizeof(si_other);

    if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    if ( (s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket clien failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::randomArray()
{
    if (!arrcomplet)
    {
        srand((unsigned)time(NULL));

        for (int i = 0; i < TestSize - 1; i++)
            arr[i] = 1 + rand() % 4;

        arrcomplet = true;
    }
    if (!(ui->home_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->volume,ui->power);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->channel,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->volume,ui->channel);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->power,ui->home);
        }
    else if (!(ui->volume_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->plus_volume,ui->mute_volume);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->minus_volume,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->plus_volume,ui->minus_volume);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->mute_volume,ui->home);
        }
    else if (!(ui->channel_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->plus_channel,ui->favorite_channel);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->minus_channel,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->plus_channel,ui->minus_channel);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->favorite_channel,ui->home);
        }

}

void MainWindow::start() {
    startTime = clock();
}
unsigned long MainWindow::elapsedTime() {
    return ((unsigned long) clock() - startTime) / (CLOCKS_PER_SEC/1000);
}

void MainWindow::p300Effect()
{
    using namespace std::this_thread; // sleep_for, sleep_until
    using namespace std::chrono; // nanoseconds, system_clock, seconds

    //    TO SEND : array au complet au debut, & la fr/quence(ex 80 + 120)

    std::string messageDebut = std::to_string(startTime) + " " + std::to_string(BSLEEPTIME)+ " " + std::to_string(ASLEEPTIME);
    const char* messageDebut_char = messageDebut.c_str();
    if (sendto(s, messageDebut_char, int(strlen(messageDebut_char)), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
    {
        printf("sendto() failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < TestSize - 1 && stop == false  ;i++)
    {
        start();
        // TOSEND: time a chaque je sais pas trop combien de temps et mon index (modulo nombre itteration).
        if (i%50 == 0) //a tous les 50, on envoie un message
        {
            std::string messageDebut = std::to_string(startTime) + " " + std::to_string(i);
            const char* messageDebut_char = messageDebut.c_str();
            if (sendto(s, messageDebut_char, int(strlen(messageDebut_char)), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
            {
                printf("sendto() failed with error code : %d", WSAGetLastError());
                exit(EXIT_FAILURE);
            }
        }

        p300Array[i].first->toggled(true);
        p300Array[i].second->toggled(true);
        qApp->processEvents();
        sleep_for(milliseconds(BSLEEPTIME));
        p300Array[i].first->toggled(false);
        p300Array[i].second->toggled(false);
        sleep_for(milliseconds(ASLEEPTIME));
    }
    stop = false;
}

void MainWindow::ButtonToggleFunction(QPushButton *button,bool checked, QString whitePic, QString blackPic)
{
    QIcon *ico;

    if (checked)
    {

        QPixmap pixW(whitePic);
        ico = new QIcon(pixW);
        button->setIcon(*ico);
        button->setIconSize(pixW.size());
    }
    else
    {
        QPixmap pixB(blackPic);
        ico = new QIcon(pixB);
        button->setIcon(*ico);
        button->setIconSize(pixB.size());
    }

    //button->setCheckable(true);
}

void MainWindow::on_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->volume, checked,":/Buttons/VolumeButtonWhite.png", ":/Buttons/VolumeButtonBlack.png");
}

void MainWindow::on_volume_clicked()
{
    ui->home_widget->hide();
    ui->channel_widget->hide();
    ui->volume_widget->show();
}

void MainWindow::on_home_clicked()
{
    ui->volume_widget->hide();
    ui->channel_widget->hide();
    ui->home_widget->show();
}

void MainWindow::on_channel_clicked()
{
    ui->home_widget->hide();
    ui->volume_widget->hide();
    ui->channel_widget->show();
}

void MainWindow::on_minus_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->minus_volume, checked,":/Buttons/MinusButtonWhite.png", ":/Buttons/MinusButtonBlack.png");
}

void MainWindow::on_mute_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->mute_volume, checked,":/Buttons/MuteButtonWhite.png", ":/Buttons/MuteButtonBlack.png");
}

void MainWindow::on_plus_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->plus_volume, checked,":/Buttons/PlusButtonWhite.png", ":/Buttons/PlusButtonBlack.png");
}

void MainWindow::on_favorite_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->favorite_channel, checked,":/Buttons/FavoriteButtonWhite.png", ":/Buttons/FavoriteButtonBlack.png");
}

void MainWindow::on_minus_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->minus_channel, checked,":/Buttons/MinusButtonWhite.png", ":/Buttons/MinusButtonBlack.png");
}

void MainWindow::on_plus_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->plus_channel, checked,":/Buttons/PlusButtonWhite.png", ":/Buttons/PlusButtonBlack.png");
}
void MainWindow::on_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->channel, checked,":/Buttons/ChannelButtonWhite.png", ":/Buttons/ChannelButtonBlack.png");
}

void MainWindow::on_home_toggled(bool checked)
{
    ButtonToggleFunction(ui->home, checked,":/Buttons/HomeButtonWhite.png", ":/Buttons/HomeButtonBlack.png");
}

void MainWindow::on_power_toggled(bool checked)
{
    ButtonToggleFunction(ui->power, checked,":/Buttons/PowerButtonWhite.png", ":/Buttons/PowerButtonBlack.png");
}

void MainWindow::on_pushButton_pressed()
{
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(true);
    ui->frequency_Aspin->setEnabled(false);
    ui->frequency_Bspin->setEnabled(false);
    randomArray();
    p300Effect();
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
    ui->frequency_Aspin->setEnabled(true);
    ui->frequency_Bspin->setEnabled(true);
}

void MainWindow::on_pushButton_2_pressed()
{
    stop = true;
}

void MainWindow::on_frequency_Bspin_valueChanged()
{
    BSLEEPTIME = ui->frequency_Bspin->value();
}

void MainWindow::on_frequency_Aspin_valueChanged()
{
    ASLEEPTIME = ui->frequency_Aspin->value();
}
<commit_msg>udp frequency<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "timer.h"
#include <QToolButton>
#include <chrono>
#include <thread>
#include <algorithm>
#include <iostream>
#include <QApplication>

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

#pragma comment(lib, "ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define SERVER "127.0.0.1" //ip adress of udp server
#define PORT 8888
#define BUFLEN 512
struct sockaddr_in server, si_other;
SOCKET s;
int slen;
char buf[BUFLEN];
WSADATA wsa;

#define TestSize 1000
bool stop = false;
unsigned long startTime = 0;
std::pair<QPushButton*,QPushButton*> p300Array[TestSize];
int arr[TestSize];
bool arrcomplet = false;
int BSLEEPTIME = 80;
int ASLEEPTIME = 100;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Remote Home");
    this->setMinimumSize(927, 581);
    this->setMaximumSize(927, 581);

    ui->pushButton_2->setEnabled(false);
    ui->volume_widget->hide();
    ui->channel_widget->hide();

    ui->frequency_Bspin->setValue(BSLEEPTIME);
    ui->frequency_Aspin->setValue(ASLEEPTIME);

    slen = sizeof(si_other);

    if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    if ( (s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket clien failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::randomArray()
{
    if (!arrcomplet)
    {
        srand((unsigned)time(NULL));

        for (int i = 0; i < TestSize - 1; i++)
            arr[i] = 1 + rand() % 4;

        arrcomplet = true;
    }
    if (!(ui->home_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->volume,ui->power);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->channel,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->volume,ui->channel);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->power,ui->home);
        }
    else if (!(ui->volume_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->plus_volume,ui->mute_volume);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->minus_volume,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->plus_volume,ui->minus_volume);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->mute_volume,ui->home);
        }
    else if (!(ui->channel_widget->isHidden()))
        for (int j = 0; j < TestSize - 1;j++)
        {
            if (arr[j] == 1)
                p300Array[j] = std::make_pair(ui->plus_channel,ui->favorite_channel);
            else if (arr[j] == 2)
                p300Array[j] = std::make_pair(ui->minus_channel,ui->home);
            else if (arr[j] == 3)
                p300Array[j] = std::make_pair(ui->plus_channel,ui->minus_channel);
            else if (arr[j] == 4)
                p300Array[j] = std::make_pair(ui->favorite_channel,ui->home);
        }

}

void MainWindow::start() {
    startTime = clock();
}
unsigned long MainWindow::elapsedTime() {
    return ((unsigned long) clock() - startTime) / (CLOCKS_PER_SEC/1000);
}

void MainWindow::p300Effect()
{
    using namespace std::this_thread; // sleep_for, sleep_until
    using namespace std::chrono; // nanoseconds, system_clock, seconds

    //    TO SEND : array au complet au debut, & la fr/quence(ex 80 + 120)

    std::string messageDebut = std::to_string(startTime) + " " + std::to_string(BSLEEPTIME)+ " " + std::to_string(ASLEEPTIME);
    const char* messageDebut_char = messageDebut.c_str();
    if (sendto(s, messageDebut_char, int(strlen(messageDebut_char)), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
    {
        printf("sendto() failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < TestSize - 1 && stop == false  ;i++)
    {
        start();
        // TOSEND: time a chaque je sais pas trop combien de temps et mon index (modulo nombre itteration).
        if (i%5 == 0) //a tous les 50, on envoie un message
        {
            std::string messageDebut = std::to_string(startTime) + " " + std::to_string(i);
            const char* messageDebut_char = messageDebut.c_str();
            if (sendto(s, messageDebut_char, int(strlen(messageDebut_char)), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
            {
                printf("sendto() failed with error code : %d", WSAGetLastError());
                exit(EXIT_FAILURE);
            }
        }

        p300Array[i].first->toggled(true);
        p300Array[i].second->toggled(true);
        qApp->processEvents();
        sleep_for(milliseconds(BSLEEPTIME));
        p300Array[i].first->toggled(false);
        p300Array[i].second->toggled(false);
        sleep_for(milliseconds(ASLEEPTIME));
    }
    stop = false;
}

void MainWindow::ButtonToggleFunction(QPushButton *button,bool checked, QString whitePic, QString blackPic)
{
    QIcon *ico;

    if (checked)
    {

        QPixmap pixW(whitePic);
        ico = new QIcon(pixW);
        button->setIcon(*ico);
        button->setIconSize(pixW.size());
    }
    else
    {
        QPixmap pixB(blackPic);
        ico = new QIcon(pixB);
        button->setIcon(*ico);
        button->setIconSize(pixB.size());
    }

    //button->setCheckable(true);
}

void MainWindow::on_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->volume, checked,":/Buttons/VolumeButtonWhite.png", ":/Buttons/VolumeButtonBlack.png");
}

void MainWindow::on_volume_clicked()
{
    ui->home_widget->hide();
    ui->channel_widget->hide();
    ui->volume_widget->show();
}

void MainWindow::on_home_clicked()
{
    ui->volume_widget->hide();
    ui->channel_widget->hide();
    ui->home_widget->show();
}

void MainWindow::on_channel_clicked()
{
    ui->home_widget->hide();
    ui->volume_widget->hide();
    ui->channel_widget->show();
}

void MainWindow::on_minus_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->minus_volume, checked,":/Buttons/MinusButtonWhite.png", ":/Buttons/MinusButtonBlack.png");
}

void MainWindow::on_mute_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->mute_volume, checked,":/Buttons/MuteButtonWhite.png", ":/Buttons/MuteButtonBlack.png");
}

void MainWindow::on_plus_volume_toggled(bool checked)
{
    ButtonToggleFunction(ui->plus_volume, checked,":/Buttons/PlusButtonWhite.png", ":/Buttons/PlusButtonBlack.png");
}

void MainWindow::on_favorite_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->favorite_channel, checked,":/Buttons/FavoriteButtonWhite.png", ":/Buttons/FavoriteButtonBlack.png");
}

void MainWindow::on_minus_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->minus_channel, checked,":/Buttons/MinusButtonWhite.png", ":/Buttons/MinusButtonBlack.png");
}

void MainWindow::on_plus_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->plus_channel, checked,":/Buttons/PlusButtonWhite.png", ":/Buttons/PlusButtonBlack.png");
}
void MainWindow::on_channel_toggled(bool checked)
{
    ButtonToggleFunction(ui->channel, checked,":/Buttons/ChannelButtonWhite.png", ":/Buttons/ChannelButtonBlack.png");
}

void MainWindow::on_home_toggled(bool checked)
{
    ButtonToggleFunction(ui->home, checked,":/Buttons/HomeButtonWhite.png", ":/Buttons/HomeButtonBlack.png");
}

void MainWindow::on_power_toggled(bool checked)
{
    ButtonToggleFunction(ui->power, checked,":/Buttons/PowerButtonWhite.png", ":/Buttons/PowerButtonBlack.png");
}

void MainWindow::on_pushButton_pressed()
{
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(true);
    ui->frequency_Aspin->setEnabled(false);
    ui->frequency_Bspin->setEnabled(false);
    randomArray();
    p300Effect();
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
    ui->frequency_Aspin->setEnabled(true);
    ui->frequency_Bspin->setEnabled(true);
}

void MainWindow::on_pushButton_2_pressed()
{
    stop = true;
}

void MainWindow::on_frequency_Bspin_valueChanged()
{
    BSLEEPTIME = ui->frequency_Bspin->value();
}

void MainWindow::on_frequency_Aspin_valueChanged()
{
    ASLEEPTIME = ui->frequency_Aspin->value();
}
<|endoftext|>


<commit_before>/* json_parsing.cc
   Jeremy Barnes, 1 February 2012
   Copyright (c) 2012 Datacratic.  All rights reserved.

   Released under the MIT license.
*/

#include "json_parsing.h"
#include "jml/arch/format.h"

using namespace std;

namespace ML {

/*****************************************************************************/
/* JSON UTILITIES                                                            */
/*****************************************************************************/

void skipJsonWhitespace(Parse_Context & context)
{
    // Fast-path for the usual case for not EOF and no whitespace
    if (JML_LIKELY(!context.eof())) {
        char c = *context;
        if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
            return;
    }

    while (!context.eof()
           && (context.match_whitespace() || context.match_eol()));
}

char * jsonEscapeCore(const std::string & str, char * p, char * end)
{
    for (unsigned i = 0;  i < str.size();  ++i) {
        if (p + 4 >= end)
            return 0;

        char c = str[i];
        if (c >= ' ' && c < 127 && c != '\"' && c != '\\')
            *p++ = c;
        else {
            *p++ = '\\';
            switch (c) {
            case '\t': *p++ = ('t');  break;
            case '\n': *p++ = ('n');  break;
            case '\r': *p++ = ('r');  break;
            case '\b': *p++ = ('b');  break;
            case '\f': *p++ = ('f');  break;
            case '/':
            case '\\':
            case '\"': *p++ = (c);  break;
            default:
                throw Exception("invalid character in Json string");
            }
        }
    }

    return p;
}

std::string
jsonEscape(const std::string & str)
{
    size_t sz = str.size() * 4 + 4;
    char buf[sz];
    char * p = buf, * end = buf + sz;

    p = jsonEscapeCore(str, p, end);

    if (!p)
        throw ML::Exception("To fix: logic error in JSON escaping");

    return string(buf, p);
}

void jsonEscape(const std::string & str, std::ostream & stream)
{
    size_t sz = str.size() * 4 + 4;
    char buf[sz];
    char * p = buf, * end = buf + sz;

    p = jsonEscapeCore(str, p, end);

    if (!p)
        throw ML::Exception("To fix: logic error in JSON escaping");

    stream.write(buf, p - buf);
}

bool matchJsonString(Parse_Context & context, std::string & str)
{
    Parse_Context::Revert_Token token(context);

    skipJsonWhitespace(context);
    if (!context.match_literal('"')) return false;

    std::string result;

    while (!context.match_literal('"')) {
        if (context.eof()) return false;
        int c = *context++;
        //if (c < 0 || c >= 127)
        //    context.exception("invalid JSON string character");
        if (c != '\\') {
            result.push_back(c);
            continue;
        }
        c = *context++;
        switch (c) {
        case 't': result.push_back('\t');  break;
        case 'n': result.push_back('\n');  break;
        case 'r': result.push_back('\r');  break;
        case 'f': result.push_back('\f');  break;
        case '/': result.push_back('/');   break;
        case '\\':result.push_back('\\');  break;
        case '"': result.push_back('"');   break;
        case 'u': {
            int code = context.expect_int();
            if (code<0 || code>255)
            {
                return false;
            }
            result.push_back(code);
            break;
        }
        default:
            return false;
        }
    }

    token.ignore();
    str = result;
    return true;
}

std::string expectJsonStringAsciiPermissive(Parse_Context & context, char sub)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    char internalBuffer[4096];

    char * buffer = internalBuffer;
    size_t bufferSize = 4096;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < ' ' || c >= 127)
            c = sub;
        if (pos == bufferSize) {
            size_t newBufferSize = bufferSize * 8;
            char * newBuffer = new char[newBufferSize];
            std::copy(buffer, buffer + bufferSize, newBuffer);
            if (buffer != internalBuffer)
                delete[] buffer;
            buffer = newBuffer;
            bufferSize = newBufferSize;
        }
        buffer[pos++] = c;
    }

    string result(buffer, buffer + pos);
    if (buffer != internalBuffer)
        delete[] buffer;

    return result;
}

ssize_t expectJsonStringAscii(Parse_Context & context, char * buffer, size_t maxLength)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    size_t bufferSize = maxLength - 1;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                if (code<0 || code>255) {
                    context.exception(format("non 8bit char %d", code));
                }
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < 0 || c >= 127)
           context.exception("invalid JSON ASCII string character");
        if (pos == bufferSize) {
            return -1;
        }
        buffer[pos++] = c;
    }

    buffer[pos] = 0; // null terminator

    return pos;
}

std::string expectJsonStringAscii(Parse_Context & context)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    char internalBuffer[4096];

    char * buffer = internalBuffer;
    size_t bufferSize = 4096;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                if (code<0 || code>255) {
                    context.exception(format("non 8bit char %d", code));
                }
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < 0 || c >= 127)
           context.exception("invalid JSON ASCII string character");
        if (pos == bufferSize) {
            size_t newBufferSize = bufferSize * 8;
            char * newBuffer = new char[newBufferSize];
            std::copy(buffer, buffer + bufferSize, newBuffer);
            if (buffer != internalBuffer)
                delete[] buffer;
            buffer = newBuffer;
            bufferSize = newBufferSize;
        }
        buffer[pos++] = c;
    }

    string result(buffer, buffer + pos);
    if (buffer != internalBuffer)
        delete[] buffer;

    return result;
}

void
expectJsonArray(Parse_Context & context,
                const std::function<void (int, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('[');
    skipJsonWhitespace(context);
    if (context.match_literal(']')) return;

    for (int i = 0;  ; ++i) {
        skipJsonWhitespace(context);

        onEntry(i, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal(']');
}

void
expectJsonObject(Parse_Context & context,
                 const std::function<void (std::string, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('{');

    skipJsonWhitespace(context);

    if (context.match_literal('}')) return;

    for (;;) {
        skipJsonWhitespace(context);

        string key = expectJsonStringAscii(context);

        skipJsonWhitespace(context);

        context.expect_literal(':');

        skipJsonWhitespace(context);

        onEntry(key, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal('}');
}

void
expectJsonObjectAscii(Parse_Context & context,
                      const std::function<void (const char *, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('{');

    skipJsonWhitespace(context);

    if (context.match_literal('}')) return;

    for (;;) {
        skipJsonWhitespace(context);

        char keyBuffer[1024];

        ssize_t done = expectJsonStringAscii(context, keyBuffer, 1024);
        if (done == -1)
            context.exception("JSON key is too long");

        skipJsonWhitespace(context);

        context.expect_literal(':');

        skipJsonWhitespace(context);

        onEntry(keyBuffer, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal('}');
}

bool
matchJsonObject(Parse_Context & context,
                const std::function<bool (std::string, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return true;

    if (!context.match_literal('{')) return false;
    skipJsonWhitespace(context);
    if (context.match_literal('}')) return true;

    for (;;) {
        skipJsonWhitespace(context);

        string key = expectJsonStringAscii(context);

        skipJsonWhitespace(context);
        if (!context.match_literal(':')) return false;
        skipJsonWhitespace(context);

        if (!onEntry(key, context)) return false;

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    if (!context.match_literal('}')) return false;

    return true;
}

} // namespace ML
<commit_msg>handle \b as required by certain badly formatted strings<commit_after>/* json_parsing.cc
   Jeremy Barnes, 1 February 2012
   Copyright (c) 2012 Datacratic.  All rights reserved.

   Released under the MIT license.
*/

#include "json_parsing.h"
#include "jml/arch/format.h"

using namespace std;

namespace ML {

/*****************************************************************************/
/* JSON UTILITIES                                                            */
/*****************************************************************************/

void skipJsonWhitespace(Parse_Context & context)
{
    // Fast-path for the usual case for not EOF and no whitespace
    if (JML_LIKELY(!context.eof())) {
        char c = *context;
        if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
            return;
    }

    while (!context.eof()
           && (context.match_whitespace() || context.match_eol()));
}

char * jsonEscapeCore(const std::string & str, char * p, char * end)
{
    for (unsigned i = 0;  i < str.size();  ++i) {
        if (p + 4 >= end)
            return 0;

        char c = str[i];
        if (c >= ' ' && c < 127 && c != '\"' && c != '\\')
            *p++ = c;
        else {
            *p++ = '\\';
            switch (c) {
            case '\t': *p++ = ('t');  break;
            case '\n': *p++ = ('n');  break;
            case '\r': *p++ = ('r');  break;
            case '\f': *p++ = ('f');  break;
            case '\b': *p++ = ('b');  break;
            case '/':
            case '\\':
            case '\"': *p++ = (c);  break;
            default:
                throw Exception("invalid character in Json string");
            }
        }
    }

    return p;
}

std::string
jsonEscape(const std::string & str)
{
    size_t sz = str.size() * 4 + 4;
    char buf[sz];
    char * p = buf, * end = buf + sz;

    p = jsonEscapeCore(str, p, end);

    if (!p)
        throw ML::Exception("To fix: logic error in JSON escaping");

    return string(buf, p);
}

void jsonEscape(const std::string & str, std::ostream & stream)
{
    size_t sz = str.size() * 4 + 4;
    char buf[sz];
    char * p = buf, * end = buf + sz;

    p = jsonEscapeCore(str, p, end);

    if (!p)
        throw ML::Exception("To fix: logic error in JSON escaping");

    stream.write(buf, p - buf);
}

bool matchJsonString(Parse_Context & context, std::string & str)
{
    Parse_Context::Revert_Token token(context);

    skipJsonWhitespace(context);
    if (!context.match_literal('"')) return false;

    std::string result;

    while (!context.match_literal('"')) {
        if (context.eof()) return false;
        int c = *context++;
        //if (c < 0 || c >= 127)
        //    context.exception("invalid JSON string character");
        if (c != '\\') {
            result.push_back(c);
            continue;
        }
        c = *context++;
        switch (c) {
        case 't': result.push_back('\t');  break;
        case 'n': result.push_back('\n');  break;
        case 'r': result.push_back('\r');  break;
        case 'f': result.push_back('\f');  break;
        case 'b': result.push_back('\b');  break;
        case '/': result.push_back('/');   break;
        case '\\':result.push_back('\\');  break;
        case '"': result.push_back('"');   break;
        case 'u': {
            int code = context.expect_int();
            if (code<0 || code>255)
            {
                return false;
            }
            result.push_back(code);
            break;
        }
        default:
            return false;
        }
    }

    token.ignore();
    str = result;
    return true;
}

std::string expectJsonStringAsciiPermissive(Parse_Context & context, char sub)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    char internalBuffer[4096];

    char * buffer = internalBuffer;
    size_t bufferSize = 4096;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case 'b': c = '\b';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < ' ' || c >= 127)
            c = sub;
        if (pos == bufferSize) {
            size_t newBufferSize = bufferSize * 8;
            char * newBuffer = new char[newBufferSize];
            std::copy(buffer, buffer + bufferSize, newBuffer);
            if (buffer != internalBuffer)
                delete[] buffer;
            buffer = newBuffer;
            bufferSize = newBufferSize;
        }
        buffer[pos++] = c;
    }

    string result(buffer, buffer + pos);
    if (buffer != internalBuffer)
        delete[] buffer;

    return result;
}

ssize_t expectJsonStringAscii(Parse_Context & context, char * buffer, size_t maxLength)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    size_t bufferSize = maxLength - 1;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case 'b': c = '\b';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                if (code<0 || code>255) {
                    context.exception(format("non 8bit char %d", code));
                }
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < 0 || c >= 127)
           context.exception("invalid JSON ASCII string character");
        if (pos == bufferSize) {
            return -1;
        }
        buffer[pos++] = c;
    }

    buffer[pos] = 0; // null terminator

    return pos;
}

std::string expectJsonStringAscii(Parse_Context & context)
{
    skipJsonWhitespace(context);
    context.expect_literal('"');

    char internalBuffer[4096];

    char * buffer = internalBuffer;
    size_t bufferSize = 4096;
    size_t pos = 0;

    // Try multiple times to make it fit
    while (!context.match_literal('"')) {
        int c = *context++;
        if (c == '\\') {
            c = *context++;
            switch (c) {
            case 't': c = '\t';  break;
            case 'n': c = '\n';  break;
            case 'r': c = '\r';  break;
            case 'f': c = '\f';  break;
            case 'b': c = '\b';  break;
            case '/': c = '/';   break;
            case '\\':c = '\\';  break;
            case '"': c = '"';   break;
            case 'u': {
                int code = context.expect_int();
                if (code<0 || code>255) {
                    context.exception(format("non 8bit char %d", code));
                }
                c = code;
                break;
            }
            default:
                context.exception("invalid escaped char");
            }
        }
        if (c < 0 || c >= 127)
           context.exception("invalid JSON ASCII string character");
        if (pos == bufferSize) {
            size_t newBufferSize = bufferSize * 8;
            char * newBuffer = new char[newBufferSize];
            std::copy(buffer, buffer + bufferSize, newBuffer);
            if (buffer != internalBuffer)
                delete[] buffer;
            buffer = newBuffer;
            bufferSize = newBufferSize;
        }
        buffer[pos++] = c;
    }

    string result(buffer, buffer + pos);
    if (buffer != internalBuffer)
        delete[] buffer;

    return result;
}

void
expectJsonArray(Parse_Context & context,
                const std::function<void (int, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('[');
    skipJsonWhitespace(context);
    if (context.match_literal(']')) return;

    for (int i = 0;  ; ++i) {
        skipJsonWhitespace(context);

        onEntry(i, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal(']');
}

void
expectJsonObject(Parse_Context & context,
                 const std::function<void (std::string, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('{');

    skipJsonWhitespace(context);

    if (context.match_literal('}')) return;

    for (;;) {
        skipJsonWhitespace(context);

        string key = expectJsonStringAscii(context);

        skipJsonWhitespace(context);

        context.expect_literal(':');

        skipJsonWhitespace(context);

        onEntry(key, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal('}');
}

void
expectJsonObjectAscii(Parse_Context & context,
                      const std::function<void (const char *, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return;

    context.expect_literal('{');

    skipJsonWhitespace(context);

    if (context.match_literal('}')) return;

    for (;;) {
        skipJsonWhitespace(context);

        char keyBuffer[1024];

        ssize_t done = expectJsonStringAscii(context, keyBuffer, 1024);
        if (done == -1)
            context.exception("JSON key is too long");

        skipJsonWhitespace(context);

        context.expect_literal(':');

        skipJsonWhitespace(context);

        onEntry(keyBuffer, context);

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    context.expect_literal('}');
}

bool
matchJsonObject(Parse_Context & context,
                const std::function<bool (std::string, Parse_Context &)> & onEntry)
{
    skipJsonWhitespace(context);

    if (context.match_literal("null"))
        return true;

    if (!context.match_literal('{')) return false;
    skipJsonWhitespace(context);
    if (context.match_literal('}')) return true;

    for (;;) {
        skipJsonWhitespace(context);

        string key = expectJsonStringAscii(context);

        skipJsonWhitespace(context);
        if (!context.match_literal(':')) return false;
        skipJsonWhitespace(context);

        if (!onEntry(key, context)) return false;

        skipJsonWhitespace(context);

        if (!context.match_literal(',')) break;
    }

    skipJsonWhitespace(context);
    if (!context.match_literal('}')) return false;

    return true;
}

} // namespace ML
<|endoftext|>


<commit_before>// $Id$
//
//  Copyright (c) 2014, Novartis Institutes for BioMedical Research Inc.
//  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Novartis Institutes for BioMedical Research Inc.
//       nor the names of its contributors may be used to endorse or promote
//       products derived from this software without specific prior written permission.
//
// 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.
//

#include <GraphMol/RDKitBase.h>
#include <DataStructs/ExplicitBitVect.h>
#include <DataStructs/BitOps.h>
#include <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/Fingerprints/Fingerprints.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include "GraphMol/ChemReactions/ReactionFingerprints.h"
#include <GraphMol/Fingerprints/MACCS.h>
#include <GraphMol/Fingerprints/MorganFingerprints.h>
#include <DataStructs/SparseIntVect.h>
#include <GraphMol/ChemReactions/ReactionUtils.h>

namespace{
  /*
ExplicitBitVect *concatenateBitsets(const ExplicitBitVect& first, const ExplicitBitVect& second)
{
	ExplicitBitVect *res = new ExplicitBitVect(first.size() + second.size());

	for(unsigned i = 0; i < first.size(); i++){
		if(first[i]){
			res->setBit(i);
		}
	}
	for(unsigned j = 0; j < second.size(); j++){
		if(second[j]){
			res->setBit(first.size()+j);
		}
	}
    return res;
}
  */
RDKit::SparseIntVect<boost::uint32_t> *generateFingerprint(RDKit::ROMol &mol,
		unsigned int fpSize,
		RDKit::FingerprintType t)
{
	mol.updatePropertyCache(false);
	RDKit::SparseIntVect<boost::uint32_t> *res;
	switch(t){
	case RDKit::AtomPairFP:
	{
		RDKit::SparseIntVect<boost::int32_t> *tmp1 =
				RDKit::AtomPairs::getHashedAtomPairFingerprint(mol, fpSize);
		res = new RDKit::SparseIntVect<boost::uint32_t>(fpSize);
        BOOST_FOREACH(RDKit::SparseIntVect<boost::int32_t>::StorageType::value_type val,tmp1->getNonzeroElements()){
        	res->setVal(static_cast<boost::uint32_t>(val.first),val.second);
        }
        delete tmp1;
	}
		break;
	case RDKit::TopologicalTorsion:
	{
		RDKit::SparseIntVect<boost::int64_t> *tmp2 =
				RDKit::AtomPairs::getHashedTopologicalTorsionFingerprint(mol, fpSize);
		res = new RDKit::SparseIntVect<boost::uint32_t>(fpSize);
		BOOST_FOREACH(RDKit::SparseIntVect<boost::int64_t>::StorageType::value_type val,tmp2->getNonzeroElements()){
		  res->setVal(static_cast<boost::uint32_t>(val.first),val.second);
		}
		delete tmp2;
	}
		break;
	case RDKit::MorganFP:
	{
		if(!mol.getRingInfo()->isInitialized()){
          mol.updatePropertyCache();
          RDKit::MolOps::findSSSR(mol);
		}
		res = RDKit::MorganFingerprints::getHashedFingerprint(mol, 2,fpSize);
	}
		break;
	default:
		std::stringstream err;
		err << ">> unsupported fingerprint type" << std::endl;
		throw RDKit::ChemicalReactionException(err.str());
	}
	return res;
}

ExplicitBitVect *generateFingerprintAsBitVect(RDKit::ROMol &mol,
		unsigned int fpSize,
		RDKit::FingerprintType t)
{
	mol.updatePropertyCache(false);
	ExplicitBitVect *res;
	switch(t){
	case RDKit::AtomPairFP:
		res = RDKit::AtomPairs::getHashedAtomPairFingerprintAsBitVect(mol, fpSize);
		break;
	case RDKit::RDKitFP:
		res = RDKit::RDKFingerprintMol(mol,1, 7, fpSize);
		break;
	case RDKit::TopologicalTorsion:
		res = RDKit::AtomPairs::getHashedTopologicalTorsionFingerprintAsBitVect(mol);
		break;
	case RDKit::MorganFP:
	{
		if(!mol.getRingInfo()->isInitialized()){
          mol.updatePropertyCache();
          RDKit::MolOps::findSSSR(mol);
		}
		res = RDKit::MorganFingerprints::getFingerprintAsBitVect(mol, 2, fpSize);
	}
		break;
	case RDKit::PatternFP:
		res = RDKit::PatternFingerprintMol(mol, fpSize);
		break;
	default:
		std::stringstream err;
		err << ">> unsupported fingerprint type" << std::endl;
		throw RDKit::ChemicalReactionException(err.str());
	}
	return res;
}

}

namespace RDKit{

SparseIntVect<boost::uint32_t> *generateFingerprintChemReactionAsCountVect(const ChemicalReaction &rxn,
		unsigned int fpSize,
		FingerprintType t,
		ReactionMoleculeType mt)
{
	PRECONDITION(fpSize!=0,"fpSize==0");

	SparseIntVect<boost::uint32_t> *result = new SparseIntVect<boost::uint32_t>(fpSize);
    RDKit::MOL_SPTR_VECT::const_iterator begin = getStartIterator(rxn, mt);
    RDKit::MOL_SPTR_VECT::const_iterator end = getEndIterator(rxn, mt);
    for(; begin != end; ++begin){
		SparseIntVect<boost::uint32_t> *tmp = generateFingerprint(**begin, fpSize, t);
		(*result) += *tmp;
		delete tmp;
	}
	return result;
}

ExplicitBitVect *generateFingerprintChemReactionAsBitVect(const ChemicalReaction &rxn,
		unsigned int fpSize,
		FingerprintType t,
		ReactionMoleculeType mt)
{
	PRECONDITION(fpSize!=0,"fpSize==0");

    ExplicitBitVect *result = new ExplicitBitVect(fpSize);
    RDKit::MOL_SPTR_VECT::const_iterator begin = getStartIterator(rxn, mt);
    RDKit::MOL_SPTR_VECT::const_iterator end = getEndIterator(rxn, mt);
    for(; begin != end; ++begin){
    	ExplicitBitVect *tmp = generateFingerprintAsBitVect(**begin, fpSize, t);
    	(*result) |= *tmp;
    	delete tmp;
    }
	return result;
}

// caller owns the result, it must be deleted
ExplicitBitVect *StructuralFingerprintChemReaction(const ChemicalReaction &rxn,
		const ReactionFingerprintParams &params)
{
	PRECONDITION(params.fpSize!=0,"fpSize==0");

	unsigned int fpSize_final = params.fpSize/2;
	if(params.includeAgents){
	  unsigned agent_fp_size = params.fpSize/3;
      if(params.bitRatioAgents < 1.0){
	    agent_fp_size = int(ceil(static_cast<double>(params.fpSize) * params.bitRatioAgents));
      }
	  unsigned scaling = !(agent_fp_size%2) ? agent_fp_size : agent_fp_size - 1;
	  fpSize_final = (params.fpSize - scaling)/2;
	}
	unsigned int fpSize_agent = params.fpSize - 2*fpSize_final;

    ExplicitBitVect *reactantFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_final, params.fpType, Reactant);
    ExplicitBitVect *productFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_final, params.fpType, Product);
    ExplicitBitVect *res = new ExplicitBitVect;
    /* concatenate the two bitvectors */
    (*res) = *reactantFP + *productFP;
    if(fpSize_agent > 0){
      ExplicitBitVect *agentFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_agent, params.fpType, Agent);
      (*res) += *agentFP;
      delete agentFP;
    }

    delete reactantFP;
    delete productFP;
	return res;
}

SparseIntVect<boost::uint32_t> *DifferenceFingerprintChemReaction(const ChemicalReaction &rxn,
		const ReactionFingerprintParams &params)
{
	PRECONDITION(params.fpSize!=0,"fpSize==0");
	PRECONDITION(params.fpType>0 & params.fpType<4 ,"Fingerprinttype not supported");

	SparseIntVect<boost::uint32_t> *reactantFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Reactant);
	SparseIntVect<boost::uint32_t> *productFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Product);
	SparseIntVect<boost::uint32_t>* res = new SparseIntVect<boost::uint32_t>;
	if(params.includeAgents){
	  SparseIntVect<boost::uint32_t> *agentFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Agent);
	  (*productFP) *= params.nonAgentWeight;
	  (*reactantFP) *= params.nonAgentWeight;
      (*agentFP) *= params.agentWeight;
  	  (*res) = *productFP - *reactantFP + *agentFP;
      delete agentFP;
	}
    /* subtract product FP from reactant FP */
	else{
	  (*res) = *productFP - *reactantFP;
	}

    delete reactantFP;
    delete productFP;
	return res;
}

}
<commit_msg>Fixes bug in precondition & -> &&<commit_after>// $Id$
//
//  Copyright (c) 2014, Novartis Institutes for BioMedical Research Inc.
//  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Novartis Institutes for BioMedical Research Inc.
//       nor the names of its contributors may be used to endorse or promote
//       products derived from this software without specific prior written permission.
//
// 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.
//

#include <GraphMol/RDKitBase.h>
#include <DataStructs/ExplicitBitVect.h>
#include <DataStructs/BitOps.h>
#include <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/Fingerprints/Fingerprints.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include "GraphMol/ChemReactions/ReactionFingerprints.h"
#include <GraphMol/Fingerprints/MACCS.h>
#include <GraphMol/Fingerprints/MorganFingerprints.h>
#include <DataStructs/SparseIntVect.h>
#include <GraphMol/ChemReactions/ReactionUtils.h>

namespace{
  /*
ExplicitBitVect *concatenateBitsets(const ExplicitBitVect& first, const ExplicitBitVect& second)
{
	ExplicitBitVect *res = new ExplicitBitVect(first.size() + second.size());

	for(unsigned i = 0; i < first.size(); i++){
		if(first[i]){
			res->setBit(i);
		}
	}
	for(unsigned j = 0; j < second.size(); j++){
		if(second[j]){
			res->setBit(first.size()+j);
		}
	}
    return res;
}
  */
RDKit::SparseIntVect<boost::uint32_t> *generateFingerprint(RDKit::ROMol &mol,
		unsigned int fpSize,
		RDKit::FingerprintType t)
{
	mol.updatePropertyCache(false);
	RDKit::SparseIntVect<boost::uint32_t> *res;
	switch(t){
	case RDKit::AtomPairFP:
	{
		RDKit::SparseIntVect<boost::int32_t> *tmp1 =
				RDKit::AtomPairs::getHashedAtomPairFingerprint(mol, fpSize);
		res = new RDKit::SparseIntVect<boost::uint32_t>(fpSize);
        BOOST_FOREACH(RDKit::SparseIntVect<boost::int32_t>::StorageType::value_type val,tmp1->getNonzeroElements()){
        	res->setVal(static_cast<boost::uint32_t>(val.first),val.second);
        }
        delete tmp1;
	}
		break;
	case RDKit::TopologicalTorsion:
	{
		RDKit::SparseIntVect<boost::int64_t> *tmp2 =
				RDKit::AtomPairs::getHashedTopologicalTorsionFingerprint(mol, fpSize);
		res = new RDKit::SparseIntVect<boost::uint32_t>(fpSize);
		BOOST_FOREACH(RDKit::SparseIntVect<boost::int64_t>::StorageType::value_type val,tmp2->getNonzeroElements()){
		  res->setVal(static_cast<boost::uint32_t>(val.first),val.second);
		}
		delete tmp2;
	}
		break;
	case RDKit::MorganFP:
	{
		if(!mol.getRingInfo()->isInitialized()){
          mol.updatePropertyCache();
          RDKit::MolOps::findSSSR(mol);
		}
		res = RDKit::MorganFingerprints::getHashedFingerprint(mol, 2,fpSize);
	}
		break;
	default:
		std::stringstream err;
		err << ">> unsupported fingerprint type" << std::endl;
		throw RDKit::ChemicalReactionException(err.str());
	}
	return res;
}

ExplicitBitVect *generateFingerprintAsBitVect(RDKit::ROMol &mol,
		unsigned int fpSize,
		RDKit::FingerprintType t)
{
	mol.updatePropertyCache(false);
	ExplicitBitVect *res;
	switch(t){
	case RDKit::AtomPairFP:
		res = RDKit::AtomPairs::getHashedAtomPairFingerprintAsBitVect(mol, fpSize);
		break;
	case RDKit::RDKitFP:
		res = RDKit::RDKFingerprintMol(mol,1, 7, fpSize);
		break;
	case RDKit::TopologicalTorsion:
		res = RDKit::AtomPairs::getHashedTopologicalTorsionFingerprintAsBitVect(mol);
		break;
	case RDKit::MorganFP:
	{
		if(!mol.getRingInfo()->isInitialized()){
          mol.updatePropertyCache();
          RDKit::MolOps::findSSSR(mol);
		}
		res = RDKit::MorganFingerprints::getFingerprintAsBitVect(mol, 2, fpSize);
	}
		break;
	case RDKit::PatternFP:
		res = RDKit::PatternFingerprintMol(mol, fpSize);
		break;
	default:
		std::stringstream err;
		err << ">> unsupported fingerprint type" << std::endl;
		throw RDKit::ChemicalReactionException(err.str());
	}
	return res;
}

}

namespace RDKit{

SparseIntVect<boost::uint32_t> *generateFingerprintChemReactionAsCountVect(const ChemicalReaction &rxn,
		unsigned int fpSize,
		FingerprintType t,
		ReactionMoleculeType mt)
{
	PRECONDITION(fpSize!=0,"fpSize==0");

	SparseIntVect<boost::uint32_t> *result = new SparseIntVect<boost::uint32_t>(fpSize);
    RDKit::MOL_SPTR_VECT::const_iterator begin = getStartIterator(rxn, mt);
    RDKit::MOL_SPTR_VECT::const_iterator end = getEndIterator(rxn, mt);
    for(; begin != end; ++begin){
		SparseIntVect<boost::uint32_t> *tmp = generateFingerprint(**begin, fpSize, t);
		(*result) += *tmp;
		delete tmp;
	}
	return result;
}

ExplicitBitVect *generateFingerprintChemReactionAsBitVect(const ChemicalReaction &rxn,
		unsigned int fpSize,
		FingerprintType t,
		ReactionMoleculeType mt)
{
	PRECONDITION(fpSize!=0,"fpSize==0");

    ExplicitBitVect *result = new ExplicitBitVect(fpSize);
    RDKit::MOL_SPTR_VECT::const_iterator begin = getStartIterator(rxn, mt);
    RDKit::MOL_SPTR_VECT::const_iterator end = getEndIterator(rxn, mt);
    for(; begin != end; ++begin){
    	ExplicitBitVect *tmp = generateFingerprintAsBitVect(**begin, fpSize, t);
    	(*result) |= *tmp;
    	delete tmp;
    }
	return result;
}

// caller owns the result, it must be deleted
ExplicitBitVect *StructuralFingerprintChemReaction(const ChemicalReaction &rxn,
		const ReactionFingerprintParams &params)
{
	PRECONDITION(params.fpSize!=0,"fpSize==0");

	unsigned int fpSize_final = params.fpSize/2;
	if(params.includeAgents){
	  unsigned agent_fp_size = params.fpSize/3;
      if(params.bitRatioAgents < 1.0){
	    agent_fp_size = int(ceil(static_cast<double>(params.fpSize) * params.bitRatioAgents));
      }
	  unsigned scaling = !(agent_fp_size%2) ? agent_fp_size : agent_fp_size - 1;
	  fpSize_final = (params.fpSize - scaling)/2;
	}
	unsigned int fpSize_agent = params.fpSize - 2*fpSize_final;

    ExplicitBitVect *reactantFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_final, params.fpType, Reactant);
    ExplicitBitVect *productFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_final, params.fpType, Product);
    ExplicitBitVect *res = new ExplicitBitVect;
    /* concatenate the two bitvectors */
    (*res) = *reactantFP + *productFP;
    if(fpSize_agent > 0){
      ExplicitBitVect *agentFP = generateFingerprintChemReactionAsBitVect(rxn, fpSize_agent, params.fpType, Agent);
      (*res) += *agentFP;
      delete agentFP;
    }

    delete reactantFP;
    delete productFP;
	return res;
}

SparseIntVect<boost::uint32_t> *DifferenceFingerprintChemReaction(const ChemicalReaction &rxn,
		const ReactionFingerprintParams &params)
{
	PRECONDITION(params.fpSize!=0,"fpSize==0");
	PRECONDITION(params.fpType>0 && params.fpType<4 ,"Fingerprinttype not supported");

	SparseIntVect<boost::uint32_t> *reactantFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Reactant);
	SparseIntVect<boost::uint32_t> *productFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Product);
	SparseIntVect<boost::uint32_t>* res = new SparseIntVect<boost::uint32_t>;
	if(params.includeAgents){
	  SparseIntVect<boost::uint32_t> *agentFP = generateFingerprintChemReactionAsCountVect(rxn, params.fpSize, params.fpType, Agent);
	  (*productFP) *= params.nonAgentWeight;
	  (*reactantFP) *= params.nonAgentWeight;
      (*agentFP) *= params.agentWeight;
  	  (*res) = *productFP - *reactantFP + *agentFP;
      delete agentFP;
	}
    /* subtract product FP from reactant FP */
	else{
	  (*res) = *productFP - *reactantFP;
	}

    delete reactantFP;
    delete productFP;
	return res;
}

}
<|endoftext|>