<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS 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
 * KEVIN B. HENDRICKS 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.
 */
#ifndef MYSPELLMGR_HXX_
#define MYSPELLMGR_HXX_

#include "hunvisapi.h"
#include "w_char.hxx"
#include "atypes.hxx"
#include <string>
#include <vector>

#define SPELL_XML "<?xml?>"

#define MAXSUGGESTION 15
#define MAXSHARPS 5
#define MAXWORDLEN 176

#if defined __GNUC__ && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
#  define H_DEPRECATED __attribute__((__deprecated__))
#elif defined(_MSC_VER) && (_MSC_VER >= 1300)
#  define H_DEPRECATED __declspec(deprecated)
#else
#  define H_DEPRECATED
#endif

class HunspellImpl;

class LIBHUNSPELL_DLL_EXPORTED Hunspell {
 private:
  Hunspell(const Hunspell&);
  Hunspell& operator=(const Hunspell&);

 private:
  HunspellImpl* m_Impl;

 public:
  /* Hunspell(aff, dic) - constructor of Hunspell class
   * input: path of affix file and dictionary file
   *
   * In WIN32 environment, use UTF-8 encoded paths started with the long path
   * prefix \\\\?\\ to handle system-independent character encoding and very
   * long path names (without the long path prefix Hunspell will use fopen()
   * with system-dependent character encoding instead of _wfopen()).
   */
  Hunspell(const char* affpath, const char* dpath, const char* key = NULL);
  ~Hunspell();

  /* load extra dictionaries (only dic files) */
  int add_dic(const char* dpath, const char* key = NULL);

  /* spell(word) - spellcheck word
   * output: false = bad word, true = good word
   *
   * plus output:
   *   info: information bit array, fields:
   *     SPELL_COMPOUND  = a compound word
   *     SPELL_FORBIDDEN = an explicit forbidden word
   *   root: root (stem), when input is a word with affix(es)
   */
  bool spell(const std::string& word, int* info = NULL, std::string* root = NULL);
  H_DEPRECATED int spell(const char* word, int* info = NULL, char** root = NULL);

  /* suggest(suggestions, word) - search suggestions
   * input: pointer to an array of strings pointer and the (bad) word
   *   array of strings pointer (here *slst) may not be initialized
   * output: number of suggestions in string array, and suggestions in
   *   a newly allocated array of strings (*slts will be NULL when number
   *   of suggestion equals 0.)
   */
  std::vector<std::string> suggest(const std::string& word);
  H_DEPRECATED int suggest(char*** slst, const char* word);

  /* Suggest words from suffix rules
   * suffix_suggest(suggestions, root_word)
   * input: pointer to an array of strings pointer and the  word
   *   array of strings pointer (here *slst) may not be initialized
   * output: number of suggestions in string array, and suggestions in
   *   a newly allocated array of strings (*slts will be NULL when number
   *   of suggestion equals 0.)
   */
  std::vector<std::string> suffix_suggest(const std::string& root_word);
  H_DEPRECATED int suffix_suggest(char*** slst, const char* root_word);

  /* deallocate suggestion lists */
  H_DEPRECATED void free_list(char*** slst, int n);

  const std::string& get_dict_encoding() const;
  char* get_dic_encoding();

  /* morphological functions */

  /* analyze(result, word) - morphological analysis of the word */
  std::vector<std::string> analyze(const std::string& word);
  H_DEPRECATED int analyze(char*** slst, const char* word);

  /* stem(word) - stemmer function */
  std::vector<std::string> stem(const std::string& word);
  H_DEPRECATED int stem(char*** slst, const char* word);

  /* stem(analysis, n) - get stems from a morph. analysis
   * example:
   * char ** result, result2;
   * int n1 = analyze(&result, "words");
   * int n2 = stem(&result2, result, n1);
   */
  std::vector<std::string> stem(const std::vector<std::string>& morph);
  H_DEPRECATED int stem(char*** slst, char** morph, int n);

  /* generate(result, word, word2) - morphological generation by example(s) */
  std::vector<std::string> generate(const std::string& word, const std::string& word2);
  H_DEPRECATED int generate(char*** slst, const char* word, const char* word2);

  /* generate(result, word, desc, n) - generation by morph. description(s)
   * example:
   * char ** result;
   * char * affix = "is:plural"; // description depends from dictionaries, too
   * int n = generate(&result, "word", &affix, 1);
   * for (int i = 0; i < n; i++) printf("%s\n", result[i]);
   */
  std::vector<std::string> generate(const std::string& word, const std::vector<std::string>& pl);
  H_DEPRECATED int generate(char*** slst, const char* word, char** desc, int n);

  /* functions for run-time modification of the dictionary */

  /* add word to the run-time dictionary */

  int add(const std::string& word);

  /* add word to the run-time dictionary with affix flags of
   * the example (a dictionary word): Hunspell will recognize
   * affixed forms of the new word, too.
   */

  int add_with_affix(const std::string& word, const std::string& example);

  /* remove word from the run-time dictionary */

  int remove(const std::string& word);

  /* other */

  /* get extra word characters definied in affix file for tokenization */
  const char* get_wordchars() const;
  const std::string& get_wordchars_cpp() const;
  const std::vector<w_char>& get_wordchars_utf16() const;

  struct cs_info* get_csconv();

  const char* get_version() const;
  const std::string& get_version_cpp() const;

  int get_langnum() const;

  /* need for putdic */
  bool input_conv(const std::string& word, std::string& dest);
  H_DEPRECATED int input_conv(const char* word, char* dest, size_t destsize);
};

#endif
<commit_msg>Lower MAXWORDLEN to 100 for performance reasons. Issue #445. Optionally the preprocesor value can be customized at build time using -D switch.<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Hunspell, based on MySpell.
 *
 * The Initial Developers of the Original Code are
 * Kevin Hendricks (MySpell) and Németh László (Hunspell).
 * Portions created by the Initial Developers are Copyright (C) 2002-2005
 * the Initial Developers. All Rights Reserved.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS 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
 * KEVIN B. HENDRICKS 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.
 */
#ifndef MYSPELLMGR_HXX_
#define MYSPELLMGR_HXX_

#include "hunvisapi.h"
#include "w_char.hxx"
#include "atypes.hxx"
#include <string>
#include <vector>

#define SPELL_XML "<?xml?>"

#define MAXSUGGESTION 15
#define MAXSHARPS 5

#ifndef MAXWORDLEN
#define MAXWORDLEN 100
#endif

#if defined __GNUC__ && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
#  define H_DEPRECATED __attribute__((__deprecated__))
#elif defined(_MSC_VER) && (_MSC_VER >= 1300)
#  define H_DEPRECATED __declspec(deprecated)
#else
#  define H_DEPRECATED
#endif

class HunspellImpl;

class LIBHUNSPELL_DLL_EXPORTED Hunspell {
 private:
  Hunspell(const Hunspell&);
  Hunspell& operator=(const Hunspell&);

 private:
  HunspellImpl* m_Impl;

 public:
  /* Hunspell(aff, dic) - constructor of Hunspell class
   * input: path of affix file and dictionary file
   *
   * In WIN32 environment, use UTF-8 encoded paths started with the long path
   * prefix \\\\?\\ to handle system-independent character encoding and very
   * long path names (without the long path prefix Hunspell will use fopen()
   * with system-dependent character encoding instead of _wfopen()).
   */
  Hunspell(const char* affpath, const char* dpath, const char* key = NULL);
  ~Hunspell();

  /* load extra dictionaries (only dic files) */
  int add_dic(const char* dpath, const char* key = NULL);

  /* spell(word) - spellcheck word
   * output: false = bad word, true = good word
   *
   * plus output:
   *   info: information bit array, fields:
   *     SPELL_COMPOUND  = a compound word
   *     SPELL_FORBIDDEN = an explicit forbidden word
   *   root: root (stem), when input is a word with affix(es)
   */
  bool spell(const std::string& word, int* info = NULL, std::string* root = NULL);
  H_DEPRECATED int spell(const char* word, int* info = NULL, char** root = NULL);

  /* suggest(suggestions, word) - search suggestions
   * input: pointer to an array of strings pointer and the (bad) word
   *   array of strings pointer (here *slst) may not be initialized
   * output: number of suggestions in string array, and suggestions in
   *   a newly allocated array of strings (*slts will be NULL when number
   *   of suggestion equals 0.)
   */
  std::vector<std::string> suggest(const std::string& word);
  H_DEPRECATED int suggest(char*** slst, const char* word);

  /* Suggest words from suffix rules
   * suffix_suggest(suggestions, root_word)
   * input: pointer to an array of strings pointer and the  word
   *   array of strings pointer (here *slst) may not be initialized
   * output: number of suggestions in string array, and suggestions in
   *   a newly allocated array of strings (*slts will be NULL when number
   *   of suggestion equals 0.)
   */
  std::vector<std::string> suffix_suggest(const std::string& root_word);
  H_DEPRECATED int suffix_suggest(char*** slst, const char* root_word);

  /* deallocate suggestion lists */
  H_DEPRECATED void free_list(char*** slst, int n);

  const std::string& get_dict_encoding() const;
  char* get_dic_encoding();

  /* morphological functions */

  /* analyze(result, word) - morphological analysis of the word */
  std::vector<std::string> analyze(const std::string& word);
  H_DEPRECATED int analyze(char*** slst, const char* word);

  /* stem(word) - stemmer function */
  std::vector<std::string> stem(const std::string& word);
  H_DEPRECATED int stem(char*** slst, const char* word);

  /* stem(analysis, n) - get stems from a morph. analysis
   * example:
   * char ** result, result2;
   * int n1 = analyze(&result, "words");
   * int n2 = stem(&result2, result, n1);
   */
  std::vector<std::string> stem(const std::vector<std::string>& morph);
  H_DEPRECATED int stem(char*** slst, char** morph, int n);

  /* generate(result, word, word2) - morphological generation by example(s) */
  std::vector<std::string> generate(const std::string& word, const std::string& word2);
  H_DEPRECATED int generate(char*** slst, const char* word, const char* word2);

  /* generate(result, word, desc, n) - generation by morph. description(s)
   * example:
   * char ** result;
   * char * affix = "is:plural"; // description depends from dictionaries, too
   * int n = generate(&result, "word", &affix, 1);
   * for (int i = 0; i < n; i++) printf("%s\n", result[i]);
   */
  std::vector<std::string> generate(const std::string& word, const std::vector<std::string>& pl);
  H_DEPRECATED int generate(char*** slst, const char* word, char** desc, int n);

  /* functions for run-time modification of the dictionary */

  /* add word to the run-time dictionary */

  int add(const std::string& word);

  /* add word to the run-time dictionary with affix flags of
   * the example (a dictionary word): Hunspell will recognize
   * affixed forms of the new word, too.
   */

  int add_with_affix(const std::string& word, const std::string& example);

  /* remove word from the run-time dictionary */

  int remove(const std::string& word);

  /* other */

  /* get extra word characters definied in affix file for tokenization */
  const char* get_wordchars() const;
  const std::string& get_wordchars_cpp() const;
  const std::vector<w_char>& get_wordchars_utf16() const;

  struct cs_info* get_csconv();

  const char* get_version() const;
  const std::string& get_version_cpp() const;

  int get_langnum() const;

  /* need for putdic */
  bool input_conv(const std::string& word, std::string& dest);
  H_DEPRECATED int input_conv(const char* word, char* dest, size_t destsize);
};

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

static void printHelp() {
    cout << "required arguments:" << endl;
    cout << "- square size in meters" << endl;
    cout << endl;
    cout << "optional arguments:" << endl;
    cout << "- device" << endl;
}

int main(int argc, char *argv[]) {
    cout << argc << endl;

    if (argc < 1) {
        printHelp();

        return 1;
    }

    return 0;
}<commit_msg>argument handling<commit_after>#include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

#define DEVICE_STRLEN   255

static float square_size = 0.0f;
static char device[DEVICE_STRLEN];
static bool all_devices = true;

static void printHelp() {
    cout << "required arguments:" << endl;
    cout << "- square size in meters" << endl;
    cout << endl;
    cout << "optional arguments:" << endl;
    cout << "- device" << endl;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printHelp();

        return 1;
    }

    square_size = (float)strtod(argv[1], NULL);

    if (square_size <= 0.0f) {
        cout << "unable to parse first argument as square size" << endl;
        printHelp();

        return 2;
    }

    if (argc >= 3) {
        strncpy(device, argv[2], DEVICE_STRLEN);
        all_devices = false;
    }

    cout << "using square size of " << square_size << " meters" << endl;
    cout << "generating camera intrinsics for ";
    if (all_devices)
        cout << "all devices" << endl;
    else
        cout << "device '" << device << "'" << endl;

    return 0;
}<|endoftext|>


<commit_before>#include "lutil.h"
#include <GL/freeglut.h>

// Camera position
GLfloat gCameraX = 0.0f, gCameraY = 0.0f;

// Solar System
solarsystem ss(1, 3);

// Fot font rendering
unsigned char image[SCREEN_WIDTH][SCREEN_HEIGHT];

bool initGL()
{
/*	NOTES
	 *
	 * The projection and model view matrices are both matrices
	 * that geometry data is multiplied against before rendering.
	 *
	 * By setting them both to the identity matrix,
	 * what every geometry is sent through is what is
	 * rendered since the identity matrix simply returns
	 * the same vector back when you multiply against it.
	 *
	 * */

	// Set the view port
	glViewport(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT);

	// Initialize projection matrix
	glMatrixMode(GL_PROJECTION);

	// Loads identity matrix into current matrix
	glLoadIdentity();

	// Multiplies the current matrix against an ortho perspectice matrix
	// with the left, right, bottom, top, near, and far values in the arguments.
	glOrtho(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 1.0f, -1.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Save the default modelview matrix
	glPushMatrix();

	// Set color when 'glClear()' is called (Uses RGBA format, currently black)
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	// Check for any OpenGL errors that may occur during initialization
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		printf("Error initializing OpenGL! %s\n", gluErrorString(error));
		return false;
	}

	return true;
}

// Return true if successful, false otherwise
bool loadMedia()
{
	return true;
}

void update()
{
	ss.rotatePlanets();
}

void render()
{
	// Clear the color buffer (pixels on the screen)
	glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();

	// Pop default matrix onto current matrix
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	// Save default matrix again
	glPushMatrix();

	// Move projection view to center of screen
	glTranslatef(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f, 0.0f);

	// Text
	renderText(-300, -200, "Basic Solar System Simulation");
	renderText(-300, -180, "Press Spacebar to randomize parameters");

	/*
	 * NOTES
	 *
	 * VERTEX ORDER MATTERS
	 * You can either go in a clockwise or counterclock wise direction.
	 * For this, I go counterclockwise.
	 *
	 * This is because each vertex correlates with a face of the quad.
	 * The first and second points are one side, second and third another,
	 * third and fourth another, and fourth and first another, making
	 * 4 sides.
	 * */

	// Render solar system
	ss.renderSolarSystem();

	/*
	 * NOTES
	 *
	 * This program uses a double buffered window.
	 *
	 * There are two buffers: front buffer and back buffer
	 * The front buffer is what the user sees and the back
	 * buffer is in memory.
	 *
	 * For a double buffered window:
	 * When we make render calls, all of that is rendered in the back buffer.
	 * After we're done rendering what we want to show the user, we
	 * swap the front and back buffer.
	 *
	 * When there is a single window buffer,
	 * the user will see geometry as it's being rendered.
	 * This may cause unfinished rendering and tearing.
	 *
	 * Holy fuck, I had no clue!
	 * */

	// Render text
	//glColor3f(0, 0.5f, 0.5f);
	//glutStrokeCharacter(GLUT_STROKE_ROMAN, 'H');

	// Update GLUT buffer (our second buffer)
	glutSwapBuffers();

}

void renderText(int xPos, int yPos, std::string inputText)
{
	// Position text (0, 0) = Center of screen
	glRasterPos2i(xPos, yPos);

	const unsigned char *c;
	for (int i = 0; i < inputText.size(); ++i)
	{
		glutBitmapCharacter(GLUT_BITMAP_9_BY_15, inputText[i]);
	}
}

void handleKeys(unsigned char key, int x, int y)
{
	if (key == ' ')
	{
		ss.shuffle();
	}
}

<commit_msg>Updated comments<commit_after>#include "lutil.h"
#include <GL/freeglut.h>

// Camera position
GLfloat gCameraX = 0.0f, gCameraY = 0.0f;

// Solar System
solarsystem ss(1, 3);

// Fot font rendering
unsigned char image[SCREEN_WIDTH][SCREEN_HEIGHT];

bool initGL()
{
/*	NOTES
	 *
	 * The projection and model view matrices are both matrices
	 * that geometry data is multiplied against before rendering.
	 *
	 * By setting them both to the identity matrix,
	 * what every geometry is sent through is what is
	 * rendered since the identity matrix simply returns
	 * the same vector back when you multiply against it.
	 *
	 * */

	// Set the view port
	glViewport(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT);

	// Initialize projection matrix
	glMatrixMode(GL_PROJECTION);

	// Loads identity matrix into current matrix
	glLoadIdentity();

	// Multiplies the current matrix against an ortho perspectice matrix
	// with the left, right, bottom, top, near, and far values in the arguments.
	glOrtho(0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f, 1.0f, -1.0f);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Save the default modelview matrix
	glPushMatrix();

	// Set color when 'glClear()' is called (Uses RGBA format, currently black)
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

	// Check for any OpenGL errors that may occur during initialization
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		printf("Error initializing OpenGL! %s\n", gluErrorString(error));
		return false;
	}

	return true;
}

// Return true if successful, false otherwise
bool loadMedia()
{
	return true;
}

void update()
{
	ss.rotatePlanets();
}

void render()
{
	// Clear the color buffer (pixels on the screen)
	glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();

	// Pop default matrix onto current matrix
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	// Save default matrix again
	glPushMatrix();

	// Move projection view to center of screen
	glTranslatef(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f, 0.0f);

	// Text
	renderText(-300, -200, "Basic Solar System Simulation");
	renderText(-300, -180, "Press Spacebar to randomize parameters");

	/*
	 * NOTES
	 *
	 * VERTEX ORDER MATTERS
	 * You can either go in a clockwise or counterclock wise direction.
	 * For this, I go counterclockwise.
	 *
	 * This is because each vertex correlates with a face of the quad.
	 * The first and second points are one side, second and third another,
	 * third and fourth another, and fourth and first another, making
	 * 4 sides.
	 * */

	// Render solar system
	ss.renderSolarSystem();

	/*
	 * NOTES
	 *
	 * This program uses a double buffered window.
	 *
	 * There are two buffers: front buffer and back buffer
	 * The front buffer is what the user sees and the back
	 * buffer is in memory.
	 *
	 * For a double buffered window:
	 * When we make render calls, all of that is rendered in the back buffer.
	 * After we're done rendering what we want to show the user, we
	 * swap the front and back buffer.
	 *
	 * When there is a single window buffer,
	 * the user will see geometry as it's being rendered.
	 * This may cause unfinished rendering and tearing.
	 *
	 *
	 * */

	// Render text
	//glColor3f(0, 0.5f, 0.5f);
	//glutStrokeCharacter(GLUT_STROKE_ROMAN, 'H');

	// Update GLUT buffer (our second buffer)
	glutSwapBuffers();

}

void renderText(int xPos, int yPos, std::string inputText)
{
	// Position text (0, 0) = Center of screen
	glRasterPos2i(xPos, yPos);

	const unsigned char *c;
	for (int i = 0; i < inputText.size(); ++i)
	{
		glutBitmapCharacter(GLUT_BITMAP_9_BY_15, inputText[i]);
	}
}

void handleKeys(unsigned char key, int x, int y)
{
	if (key == ' ')
	{
		ss.shuffle();
	}
}

<|endoftext|>


<commit_before>#include "Arduino.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "PubSubClient.h"
#include "Adafruit_Sensor.h"
#include "DHT.h"
#include "TSL2561.h"

// include the user configuration file
#include "config.h"

extern "C" {
#include "user_interface.h"

extern struct rst_info resetInfo;
}

struct {
  float ir;
  float full;
  float lux;
  float h;
  float t;
  uint16_t vdd;
  uint8_t count;
} rtc_mem;

// enable reading the Vcc voltage with the ADC
ADC_MODE(ADC_VCC);

// WiFi network and password
WiFiClient espClient;
void connectWifi();

// MQTT server & channel
PubSubClient mqttClient(espClient);
void reconnectMqtt();
void callback(char* topic, byte* payload, unsigned int length);

// DHT22 sensor pin & type declaration
DHT dht(DHTPIN, DHTTYPE);

// TSL2561 sensor pin declaration
TSL2561 tsl(TSL2561_ADDR_FLOAT, SDAPIN, SCLPIN);

unsigned long lastMsg = 0;
uint8_t measurements = 0;
void update();
void doMeasurements();
void resetRTC();

void setup(void) {
  Serial.begin(9600);

  dht.begin();

  if (tsl.begin()) {
   Serial.println("Found sensor");
  } else {
   Serial.println("No sensor?");
  }

  tsl.setGain(TSL2561_GAIN_0X);
  tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS);

  mqttClient.setServer(MQTTSERVER, 1883);
  mqttClient.setCallback(callback);

  // when NOT waking from deep sleep, reset RTC memory to 0 and wait for sensors to initialise
  Serial.println(ESP.getResetReason());
  if (resetInfo.reason != REASON_DEEP_SLEEP_AWAKE){
    resetRTC();
    delay(500);
  }
}

void loop() {
  #ifdef SLEEP
  doMeasurements();
  if(rtc_mem.count >= NUMMEASUREMENTS){
    if ((WiFi.status() != WL_CONNECTED)){
      connectWifi();
    }
    if (!mqttClient.connected()) {
      reconnectMqtt();
    }
    mqttClient.loop();

    update();
  }

  WiFi.disconnect(true);
  delay(50);

  if(rtc_mem.count >= NUMMEASUREMENTS-1){
    ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DEFAULT);
  }
  else{
    ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DISABLED);
  }
  #else
  if ((WiFi.status() != WL_CONNECTED)){
    connectWifi();
  }
  if (!mqttClient.connected()) {
    reconnectMqtt();
  }
  mqttClient.loop();

  unsigned long now = millis();
  if (now - lastMsg > MEASUREMENTINTERVAL*1000) {
    doMeasurements();
    lastMsg = millis();
    if(rtc_mem.count >= NUMMEASUREMENTS){
      update();
    }
  }
  #endif

  delay(50);
}

void doMeasurements(){
  tsl.enable();
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    h=0;
    t=0;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");

  //  Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  uint32_t lux = tsl.calculateLux(full, ir);

  //disable sensor
  tsl.disable();

  Serial.print("IR: "); Serial.print(ir);   Serial.print("\t\t");
  Serial.print("Full: "); Serial.print(full);   Serial.print("\t");
  Serial.print("Visible: "); Serial.print(full - ir);   Serial.print("\t");
  Serial.print("Lux: "); Serial.println(lux);

  // read Vdd voltage
  uint16_t vdd = ESP.getVcc();

  // get avg of previous measurements from RTC memory
  ESP.rtcUserMemoryRead(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));

  // re-calculate average
  rtc_mem.t = rtc_mem.t+(t/NUMMEASUREMENTS);
  rtc_mem.h = rtc_mem.h+(h/NUMMEASUREMENTS);
  rtc_mem.ir = rtc_mem.ir+((float)ir/NUMMEASUREMENTS);
  rtc_mem.full = rtc_mem.full+((float)full/NUMMEASUREMENTS);
  rtc_mem.lux = rtc_mem.lux+((float)lux/NUMMEASUREMENTS);
  rtc_mem.vdd = vdd;
  rtc_mem.count = rtc_mem.count + 1;

  // write to RTC mem
  ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}

void update(){
  // TODO: get free heap memory

  String data = String("field1=" + String(rtc_mem.t, 1) + "&field2=" + String(rtc_mem.h, 1) + "&field3=" + String(rtc_mem.ir, 1)+ "&field4=" + String(rtc_mem.full, 1)+ "&field5=" + String(rtc_mem.lux, 1)+ "&field6=" + String(rtc_mem.vdd, DEC));
  int length = data.length();
  char msgBuffer[length];
  data.toCharArray(msgBuffer,length+1);

  String channel = String("channels/" + String(CHANNELID) +"/publish/"+String(APIKEY));
  length = channel.length();
  char chnlBuffer[length];

  channel.toCharArray(chnlBuffer, length+1);
  mqttClient.publish(chnlBuffer,msgBuffer);

  Serial.print(data);

  // give network some time to send data before proceding
  delay(1000);

  // set rtc to 0 for all fields and write to memory
  resetRTC();
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void resetRTC(){
  rtc_mem.t = 0.0;
  rtc_mem.h = 0.0;
  rtc_mem.ir = 0;
  rtc_mem.full = 0;
  rtc_mem.lux = 0;
  rtc_mem.vdd = 0;
  rtc_mem.count = 0;
  ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}

void connectWifi() {
  WiFi.disconnect(true);

  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnectMqtt(){
  uint8_t attempts = 0;
  while (!mqttClient.connected()) {
    if(attempts > 10){
      Serial.print("Could not connect to MQTT server. Restarting node.");
      delay(50);
      ESP.reset();
      break;
    }
    Serial.printf("(%d) Attempting MQTT connection...", attempts);
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if ((WiFi.status() != WL_CONNECTED)){
      connectWifi();
    }
    if (mqttClient.connect(clientId.c_str())) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
    attempts++;
  }

}
<commit_msg>Print total time awake to serial when running deepsleep<commit_after>#include "Arduino.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "PubSubClient.h"
#include "Adafruit_Sensor.h"
#include "DHT.h"
#include "TSL2561.h"

// include the user configuration file
#include "config.h"

extern "C" {
#include "user_interface.h"

extern struct rst_info resetInfo;
}

struct {
  float ir;
  float full;
  float lux;
  float h;
  float t;
  uint16_t vdd;
  uint8_t count;
} rtc_mem;

// enable reading the Vcc voltage with the ADC
ADC_MODE(ADC_VCC);

// WiFi network and password
WiFiClient espClient;
void connectWifi();

// MQTT server & channel
PubSubClient mqttClient(espClient);
void reconnectMqtt();
void callback(char* topic, byte* payload, unsigned int length);

// DHT22 sensor pin & type declaration
DHT dht(DHTPIN, DHTTYPE);

// TSL2561 sensor pin declaration
TSL2561 tsl(TSL2561_ADDR_FLOAT, SDAPIN, SCLPIN);

unsigned long lastMsg = 0;
uint8_t measurements = 0;
void update();
void doMeasurements();
void resetRTC();

unsigned long timet = 0;

void setup(void) {
  timet = millis();
  Serial.begin(9600);

  dht.begin();
  tsl.begin();

  tsl.setGain(TSL2561_GAIN_0X);
  tsl.setTiming(TSL2561_INTEGRATIONTIME_13MS);

  mqttClient.setServer(MQTTSERVER, 1883);
  mqttClient.setCallback(callback);

  // when NOT waking from deep sleep, reset RTC memory to 0 and wait for sensors to initialise
  Serial.println(ESP.getResetReason());
  if (resetInfo.reason != REASON_DEEP_SLEEP_AWAKE){
    resetRTC();
    delay(500);
  }
}

void loop() {
  #ifdef SLEEP
  doMeasurements();
  if(rtc_mem.count >= NUMMEASUREMENTS){
    if ((WiFi.status() != WL_CONNECTED)){
      connectWifi();
    }
    if (!mqttClient.connected()) {
      reconnectMqtt();
    }
    mqttClient.loop();

    update();
  }

  WiFi.disconnect(true);

  Serial.print("Done. Took a total of ");
  Serial.print(millis()-timet);
  Serial.println(" milliseconds");

  if(rtc_mem.count >= NUMMEASUREMENTS-1){
    ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DEFAULT);
  }
  else{
    ESP.deepSleep(MEASUREMENTINTERVAL*1000000, WAKE_RF_DISABLED);
  }
  #else
  if ((WiFi.status() != WL_CONNECTED)){
    connectWifi();
  }
  if (!mqttClient.connected()) {
    reconnectMqtt();
  }
  mqttClient.loop();

  unsigned long now = millis();
  if (now - lastMsg > MEASUREMENTINTERVAL*1000) {
    doMeasurements();
    lastMsg = millis();
    if(rtc_mem.count >= NUMMEASUREMENTS){
      update();
    }
  }
  #endif

  delay(50);
}

void doMeasurements(){
  tsl.enable();
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();

  // Check if any reads failed
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    h=0;
    t=0;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");

  //  Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  uint32_t lux = tsl.calculateLux(full, ir);

  //disable sensor
  tsl.disable();

  Serial.print("IR: "); Serial.print(ir);   Serial.print("\t\t");
  Serial.print("Full: "); Serial.print(full);   Serial.print("\t");
  Serial.print("Visible: "); Serial.print(full - ir);   Serial.print("\t");
  Serial.print("Lux: "); Serial.println(lux);

  // read Vdd voltage
  uint16_t vdd = ESP.getVcc();

  // get avg of previous measurements from RTC memory
  ESP.rtcUserMemoryRead(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));

  // re-calculate average
  rtc_mem.t = rtc_mem.t+(t/NUMMEASUREMENTS);
  rtc_mem.h = rtc_mem.h+(h/NUMMEASUREMENTS);
  rtc_mem.ir = rtc_mem.ir+((float)ir/NUMMEASUREMENTS);
  rtc_mem.full = rtc_mem.full+((float)full/NUMMEASUREMENTS);
  rtc_mem.lux = rtc_mem.lux+((float)lux/NUMMEASUREMENTS);
  rtc_mem.vdd = vdd;
  rtc_mem.count = rtc_mem.count + 1;

  // write to RTC mem
  ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}

void update(){
  // TODO: get free heap memory

  String data = String("field1=" + String(rtc_mem.t, 1) + "&field2=" + String(rtc_mem.h, 1) + "&field3=" + String(rtc_mem.ir, 1)+ "&field4=" + String(rtc_mem.full, 1)+ "&field5=" + String(rtc_mem.lux, 1)+ "&field6=" + String(rtc_mem.vdd, DEC));
  int length = data.length();
  char msgBuffer[length];
  data.toCharArray(msgBuffer,length+1);

  String channel = String("channels/" + String(CHANNELID) +"/publish/"+String(APIKEY));
  length = channel.length();
  char chnlBuffer[length];

  channel.toCharArray(chnlBuffer, length+1);
  mqttClient.publish(chnlBuffer,msgBuffer);

  Serial.print(data);

  // give network some time to send data before proceding
  delay(1000);

  // set rtc to 0 for all fields and write to memory
  resetRTC();
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void resetRTC(){
  rtc_mem.t = 0.0;
  rtc_mem.h = 0.0;
  rtc_mem.ir = 0;
  rtc_mem.full = 0;
  rtc_mem.lux = 0;
  rtc_mem.vdd = 0;
  rtc_mem.count = 0;
  ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtc_mem, sizeof(rtc_mem));
}

void connectWifi() {
  WiFi.disconnect(true);

  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnectMqtt(){
  uint8_t attempts = 0;
  while (!mqttClient.connected()) {
    if(attempts > 10){
      Serial.print("Could not connect to MQTT server. Restarting node.");
      delay(50);
      ESP.reset();
      break;
    }
    Serial.printf("(%d) Attempting MQTT connection...", attempts);
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if ((WiFi.status() != WL_CONNECTED)){
      connectWifi();
    }
    if (mqttClient.connect(clientId.c_str())) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
    attempts++;
  }

}
<|endoftext|>


<commit_before>/*
 * JeezyAI is a rap bot that emulates Young Jeezy.
 *
 * Given a bar, JeezyAI will return a rhyme on beat. The AI is trained on a
 * bank of Jeezy lyrics, so it spits like Jeezy.
 *
 * Cameron Matson, Clayton Gentry
 */

#include <iostream>
#include <fstream>
#include <string>

#include "battle.h"
#include "denouncer.h"
#include "model.h"
#include "nouncer.h"
#include "utils.h"
#include "word.h"
#include "wordList.h"

#define LYRICS_FILE "lyrics/lyrics.txt"
#define TEST_FILE   "lyrics/test.txt"

void rap(std::string bar, Model* model, Nouncer* nouncer, Denouncer* denouncer);
void parseFile(std::string filename, Model* model, Nouncer* nouncer, Denouncer* denouncer);
void parseLine(std::string in, Model* model, Nouncer* nouncer, Denouncer* denouncer);

int main(int argc, char *argv[]) {
  Model* model         = new Model();
  Nouncer* nouncer     = new Nouncer();
  Denouncer* denouncer = new Denouncer();

  parseFile(TEST_FILE, model, nouncer, denouncer);

  model->print("data/model.txt");
  denouncer->print("data/denounce.txt");

  std::string bar;
  std::cout << "Gimme a bar" << std::endl;
  std::getline(std::cin, bar);

  rap(bar, model, nouncer, denouncer);

  delete model;
  delete nouncer;
  delete denouncer;
}

/*
 * Defines the recursive functionality to consume a given bar and respond.
 */
void rap(std::string bar, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  if (bar == "exit") {
    delete model;
    delete nouncer;
    delete denouncer;

    return;
  }
  else {
    Battle* battle = new Battle(bar, model, nouncer, denouncer);
    battle->spit();
    delete battle;

    std::getline(std::cin, bar);
    rap(bar, model, nouncer, denouncer);

    delete battle;
  }
}

/*
 * Parses a text file of lyrics
 *
 * Iterates through each line of the file, passing references to
 * the data structures to be constructed during analysis.
 */
void parseFile(std::string filename, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  std::string line;
  std::ifstream file(filename);

  //add place holder: every word will be a "leader" of _NULL_
  Word* _NULL_ = new Word("_NULL_");
  model->addOrUpdate(_NULL_);
  delete _NULL_;

  if (file) {
    while(getline(file, line)) {
      parseLine(line, model, nouncer, denouncer);
    }

    file.close();
  }
  else {
    std::cerr << "Could not load lyrics file" << std::endl;
  }
  std::cout << "Model ready!" << std::endl;
}

/*
 * Parses a line
 *
 * Each new unique word is appended to the adjacency list
 * as a base word, and its preceding word is instantiated
 * as a node in its leaders vector. If the leader has already
 * been instantiated, its frequency is updated.
 *
 * Lines are processed individually to ensure the model
 * doesn't assume false positive adjacency between the
 * last word of a preceding line and the first word of
 * its successor.
 */
void parseLine(std::string in, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  std::istringstream ss(Utils::flip(in));
  std::string temp;
  std::string nounce;
  std::string encoded;

  // Word* current = nullptr;
  // Word* leader  = nullptr;

  Word current;
  Word leader;

  Word* _NULL_ = new Word("_NULL_");

  while (ss >> temp) {
    //preprocess temp
    temp = Utils::removePunc(temp);
    temp = Utils::noCaps(temp);

    //get pronunciation
    nounce = *(nouncer->lookUp(temp));

    //add pronunciation:word pair to denouncer
    denouncer->addNounce(nounce, temp);

    //pick off the word
    // current = new Word(temp);
    current = Word(temp);

    //add word to _NULL_
    WordList* list_ptr = model -> find(_NULL_);
    // (*list_ptr).add_leader(*current);
    (*list_ptr).add_leader(current);

    //add current to the model
    // model->addOrUpdate(current);
    model->addOrUpdate(&current);

    // if first word on (reversed) line => last word on a line => current not a leader
    // if (leader == nullptr) {
    if (leader.getVal() == "") {
      leader = current;
    }

    //other wise add current to leader's list
    else {
      // list_ptr = model -> find(leader);
      list_ptr = model -> find(&leader);

      //if leader is not in the model
      if (list_ptr != nullptr) {
        // (*list_ptr).add_leader(*current);
        (*list_ptr).add_leader(current);
        leader = current;
      }
      else {
        std::cerr << "Could not get leader." << std::endl;
      }
    }
    // delete current;
    // current = nullptr;
  }
  delete _NULL_;
}
<commit_msg>don't delete stuff twice<commit_after>/*
 * JeezyAI is a rap bot that emulates Young Jeezy.
 *
 * Given a bar, JeezyAI will return a rhyme on beat. The AI is trained on a
 * bank of Jeezy lyrics, so it spits like Jeezy.
 *
 * Cameron Matson, Clayton Gentry
 */

#include <iostream>
#include <fstream>
#include <string>

#include "battle.h"
#include "denouncer.h"
#include "model.h"
#include "nouncer.h"
#include "utils.h"
#include "word.h"
#include "wordList.h"

#define LYRICS_FILE "lyrics/lyrics.txt"
#define TEST_FILE   "lyrics/test.txt"

void rap(std::string bar, Model* model, Nouncer* nouncer, Denouncer* denouncer);
void parseFile(std::string filename, Model* model, Nouncer* nouncer, Denouncer* denouncer);
void parseLine(std::string in, Model* model, Nouncer* nouncer, Denouncer* denouncer);

int main(int argc, char *argv[]) {
  Model* model         = new Model();
  Nouncer* nouncer     = new Nouncer();
  Denouncer* denouncer = new Denouncer();

  parseFile(TEST_FILE, model, nouncer, denouncer);

  model->print("data/model.txt");
  denouncer->print("data/denounce.txt");

  std::string bar;
  std::cout << "Gimme a bar" << std::endl;
  std::getline(std::cin, bar);

  rap(bar, model, nouncer, denouncer);

  delete model;
  delete nouncer;
  delete denouncer;
}

/*
 * Defines the recursive functionality to consume a given bar and respond.
 */
void rap(std::string bar, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  if (bar == "exit") {
    return;
  }
  else {
    Battle* battle = new Battle(bar, model, nouncer, denouncer);
    battle->spit();

    std::getline(std::cin, bar);
    rap(bar, model, nouncer, denouncer);

    delete battle;
  }
}

/*
 * Parses a text file of lyrics
 *
 * Iterates through each line of the file, passing references to
 * the data structures to be constructed during analysis.
 */
void parseFile(std::string filename, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  std::string line;
  std::ifstream file(filename);

  //add place holder: every word will be a "leader" of _NULL_
  Word* _NULL_ = new Word("_NULL_");
  model->addOrUpdate(_NULL_);
  delete _NULL_;

  if (file) {
    while(getline(file, line)) {
      parseLine(line, model, nouncer, denouncer);
    }

    file.close();
  }
  else {
    std::cerr << "Could not load lyrics file" << std::endl;
  }
  std::cout << "Model ready!" << std::endl;
}

/*
 * Parses a line
 *
 * Each new unique word is appended to the adjacency list
 * as a base word, and its preceding word is instantiated
 * as a node in its leaders vector. If the leader has already
 * been instantiated, its frequency is updated.
 *
 * Lines are processed individually to ensure the model
 * doesn't assume false positive adjacency between the
 * last word of a preceding line and the first word of
 * its successor.
 */
void parseLine(std::string in, Model* model, Nouncer* nouncer, Denouncer* denouncer) {
  std::istringstream ss(Utils::flip(in));
  std::string temp;
  std::string nounce;
  std::string encoded;

  // Word* current = nullptr;
  // Word* leader  = nullptr;

  Word current;
  Word leader;

  Word* _NULL_ = new Word("_NULL_");

  while (ss >> temp) {
    //preprocess temp
    temp = Utils::removePunc(temp);
    temp = Utils::noCaps(temp);

    //get pronunciation
    nounce = *(nouncer->lookUp(temp));

    //add pronunciation:word pair to denouncer
    denouncer->addNounce(nounce, temp);

    //pick off the word
    // current = new Word(temp);
    current = Word(temp);

    //add word to _NULL_
    WordList* list_ptr = model -> find(_NULL_);
    // (*list_ptr).add_leader(*current);
    (*list_ptr).add_leader(current);

    //add current to the model
    // model->addOrUpdate(current);
    model->addOrUpdate(&current);

    // if first word on (reversed) line => last word on a line => current not a leader
    // if (leader == nullptr) {
    if (leader.getVal() == "") {
      leader = current;
    }

    //other wise add current to leader's list
    else {
      // list_ptr = model -> find(leader);
      list_ptr = model -> find(&leader);

      //if leader is not in the model
      if (list_ptr != nullptr) {
        // (*list_ptr).add_leader(*current);
        (*list_ptr).add_leader(current);
        leader = current;
      }
      else {
        std::cerr << "Could not get leader." << std::endl;
      }
    }
    // delete current;
    // current = nullptr;
  }
  delete _NULL_;
}
<|endoftext|>


<commit_before>//
// Created by kanairen on 2016/06/15.
//

#include "config.h"
#include "MNIST.h"
#include "Layer.h"
#include "ConvLayer.h"
#include "Model.h"
#include "optimizer.h"
#include "activation.h"

#ifdef CONV_NET_CPP_DEBUG

// コマンドライン引数にmnistへのパスを渡す
int main(int argc, char *argv[]) {

    float learning_rate = 0.01f;
    unsigned int batch_size = 50;
    unsigned int input_size = 28 * 28;
    unsigned int n_iter = 1000;
    unsigned int n_class = 10;

    // mnist
    MNIST mnist(argv[1], argv[2], argv[3], argv[4]);

    AbstractLayer *layer_1 = new ConvLayer2d(batch_size, 28, 28, 1, 16, 2, 2, 1,
                                             iden, g_iden);
    AbstractLayer *layer_2 = new Layer(batch_size, layer_1->get_n_out(),
                                       n_class, iden, g_iden);
    vector<AbstractLayer *> v{layer_1, layer_2};
//    AbstractLayer* layer_1 = new Layer(batch_size, mnist.xv_size(), 10, iden, g_iden);
//    AbstractLayer* layer_2 = new Layer(batch_size, 10, n_class, iden, g_iden);
//    vector<AbstractLayer*> v{layer_1,layer_2};

    // optimize
    optimize(mnist, v, learning_rate, batch_size, n_iter, n_class);

    // release
    delete (layer_1);

}

#endif<commit_msg>modify main<commit_after>//
// Created by kanairen on 2016/06/15.
//

#include "config.h"
#include "MNIST.h"
#include "Layer.h"
#include "ConvLayer.h"
#include "Model.h"
#include "optimizer.h"
#include "activation.h"

#ifdef CONV_NET_CPP_DEBUG

void mnist_full_connelct(char *argv[],
                         unsigned int batch_size,
                         unsigned int input_size,
                         unsigned int n_class,
                         unsigned int n_iter,
                         float learning_rate) {
    // mnist
    MNIST mnist(argv[1], argv[2], argv[3], argv[4]);

    AbstractLayer *layer_1 = new Layer(batch_size, input_size, n_class, iden,
                                       g_iden);
    vector<AbstractLayer *> v{layer_1};

    // optimize
    optimize(mnist, v, learning_rate, batch_size, n_iter, n_class);

    // release
    delete (layer_1);
}

void mnist_conv(char *argv[], unsigned int batch_size,
                unsigned int input_width, unsigned int input_height,
                unsigned int c_in, unsigned int c_out,
                unsigned int kw, unsigned int kh, unsigned int stride,
                unsigned int n_class, unsigned int n_iter,
                float learning_rate) {
    // mnist
    MNIST mnist(argv[1], argv[2], argv[3], argv[4]);

    AbstractLayer *layer_1 = new ConvLayer2d(batch_size,
                                             input_width, input_height,
                                             c_in, c_out, kw, kh, stride,
                                             iden, g_iden);

    AbstractLayer *layer_2 = new Layer(batch_size, layer_1->get_n_out(),
                                       n_class, iden, g_iden);

    vector<AbstractLayer *> v{layer_1, layer_2};

    // optimize
    optimize(mnist, v, learning_rate, batch_size, n_iter, n_class);

    // release
    delete (layer_1);
    delete (layer_2);

}

// コマンドライン引数にmnistへのパスを渡す
int main(int argc, char *argv[]) {

    const float LEARNING_RATE = 0.01f;

    const unsigned int BATCH_SIZE = 50;

    const unsigned int WIDTH = 28;
    const unsigned int HEIGHT = 28;
    const unsigned int INPUT_SIZE = WIDTH * HEIGHT;

    const unsigned int C_IN = 1;
    const unsigned int C_OUT = 16;

    const unsigned int KERNEL_WIDTH = 2;
    const unsigned int KERNEL_HEIGHT = 2;

    const unsigned int STRIDE = 1;

    const unsigned int N_ITERATION = 1000;
    const unsigned int N_CLASS = 10;

    mnist_conv(argv, BATCH_SIZE, WIDTH, HEIGHT, C_IN, C_OUT, KERNEL_WIDTH,
               KERNEL_HEIGHT, STRIDE, N_CLASS, N_ITERATION, LEARNING_RATE);

}

#endif<|endoftext|>


<commit_before>#include "headers/ph.hpp"

#include "headers/application.hpp"

#include "headers/code_generating_visitor.hpp"
#include "headers/code_generator.hpp"
#include "headers/semantic_analysis_visitor.hpp"
#include "headers/symbols_controller_factory.hpp"
#include "headers/type_data.hpp"

#include <boost/program_options.hpp>

#include <fstream>

namespace Framework
{

Application::Application()
{
}

int
Application::execute( int argc, char* argv[] )
{
	Semantics::FunctionsController & functionsController
		= Semantics::SymbolsControllerFactory::createFunctionsController();

	Semantics::StringsController & stringsController
		= Semantics::SymbolsControllerFactory::createStringsController();

	Semantics::TypesController & typesController
		= Semantics::SymbolsControllerFactory::createTypesController();

	Semantics::TypesController::Handler const voidHandler
		= typesController.insert( Semantics::TypeData( Semantics::BuildInType::create( "void" ) ) );

	Semantics::TypesController::Handler const stringHandler
		= typesController.insert( Semantics::TypeData( Semantics::BuildInType::create( "int" ) ) );

	Semantics::VariablesController & variablesController
		= Semantics::SymbolsControllerFactory::createVariablesController();

	m_parser.reset( new Syntax::Parser( new std::ifstream( argv[ 1 ] ), &std::cout ) );
	if( m_parser->yyparse() )
	{
		std::cerr << "Syntax error." << std::endl;
	}

	Semantics::SemanticAnalysisVisitor semanticAnalysisVisitor(
		functionsController,
		stringsController,
		typesController,
		variablesController );

	m_parser->getProgram()->Accept( semanticAnalysisVisitor );

	int const errorCount = semanticAnalysisVisitor.getErrorsCount();

	if ( ! errorCount )
	{
		CodeGenerating::CodeGeneratingVisitor codeGeneratingVisitor(
			functionsController,
			stringsController,
			typesController,
			variablesController );

		m_parser->getProgram()->Accept( codeGeneratingVisitor );
	}

// 	std::cerr
// 		<< "Compilation finished with... ["
// 		<< semanticAnalysisVisitor.getWarningsCount()
// 		<< "] warning(s), ["
// 		<< errorCount
// 		<< "] error(s)."
// 		<< std::endl;

	return errorCount ? 1 : 0;
}

}
<commit_msg>Print help message if no input file specified<commit_after>#include "headers/ph.hpp"

#include "headers/application.hpp"

#include "headers/code_generating_visitor.hpp"
#include "headers/code_generator.hpp"
#include "headers/semantic_analysis_visitor.hpp"
#include "headers/symbols_controller_factory.hpp"
#include "headers/type_data.hpp"

#include <boost/program_options.hpp>

#include <fstream>

namespace Framework
{

Application::Application()
{
}

int
Application::execute( int argc, char* argv[] )
{
    if( argc != 2 )
    {
        std::cerr << "Usage: " << argv[0] << " file" << std::endl;
        return 1;
    }

	Semantics::FunctionsController & functionsController
		= Semantics::SymbolsControllerFactory::createFunctionsController();

	Semantics::StringsController & stringsController
		= Semantics::SymbolsControllerFactory::createStringsController();

	Semantics::TypesController & typesController
		= Semantics::SymbolsControllerFactory::createTypesController();

	Semantics::TypesController::Handler const voidHandler
		= typesController.insert( Semantics::TypeData( Semantics::BuildInType::create( "void" ) ) );

	Semantics::TypesController::Handler const stringHandler
		= typesController.insert( Semantics::TypeData( Semantics::BuildInType::create( "int" ) ) );

	Semantics::VariablesController & variablesController
		= Semantics::SymbolsControllerFactory::createVariablesController();

	m_parser.reset( new Syntax::Parser( new std::ifstream( argv[ 1 ] ), &std::cout ) );
	if( m_parser->yyparse() )
	{
		std::cerr << "Syntax error." << std::endl;
	}

	Semantics::SemanticAnalysisVisitor semanticAnalysisVisitor(
		functionsController,
		stringsController,
		typesController,
		variablesController );

	m_parser->getProgram()->Accept( semanticAnalysisVisitor );

	int const errorCount = semanticAnalysisVisitor.getErrorsCount();

	if ( ! errorCount )
	{
		CodeGenerating::CodeGeneratingVisitor codeGeneratingVisitor(
			functionsController,
			stringsController,
			typesController,
			variablesController );

		m_parser->getProgram()->Accept( codeGeneratingVisitor );
	}

// 	std::cerr
// 		<< "Compilation finished with... ["
// 		<< semanticAnalysisVisitor.getWarningsCount()
// 		<< "] warning(s), ["
// 		<< errorCount
// 		<< "] error(s)."
// 		<< std::endl;

	return errorCount ? 1 : 0;
}

}
<|endoftext|>


<commit_before>#include <gc/gc_cpp.h>
#include "primops.hpp"

static void addPrimOp(nix::EvalState& state, nix::Value& v, const nix::Symbol & name, unsigned int arity, nix::PrimOpFun primOp) {
    nix::Value* vAttr = state.allocAttr(v, name);
    vAttr->type = nix::tPrimOp;
    vAttr->primOp = new (UseGC) nix::PrimOp(primOp, arity, name);
}

[[gnu::visibility ("default")]]
    extern "C" void initialize(nix::EvalState& state, nix::Value& v) {
    state.mkAttrs(v, 1);
    addPrimOp(state, v, state.symbols.create("readdir"), 1, prim_readdir);
}
<commit_msg>Attribute goes after linkage<commit_after>#include <gc/gc_cpp.h>
#include "primops.hpp"

static void addPrimOp(nix::EvalState& state, nix::Value& v, const nix::Symbol & name, unsigned int arity, nix::PrimOpFun primOp) {
    nix::Value* vAttr = state.allocAttr(v, name);
    vAttr->type = nix::tPrimOp;
    vAttr->primOp = new (UseGC) nix::PrimOp(primOp, arity, name);
}

extern "C" [[gnu::visibility ("default")]]
    void initialize(nix::EvalState& state, nix::Value& v) {
    state.mkAttrs(v, 1);
    addPrimOp(state, v, state.symbols.create("readdir"), 1, prim_readdir);
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <stack>
#include <vector>
#include <iostream>
#include <string>

#include "include/parser.h"
#include "include/error.h"
#include "include/env.h"
#include "include/token.h"
#include "include/object.h"

int main(int argc, const char * argv[]) {
   /* TODO: use an external library to parse command lines */
   if (argc == 1) {
      /* initialize the base global environment */
      SpEnv base_scope(NULL);

      /* initialize the object value stack */
      std::stack<SpObject *> ob_s;

      /* initialize native functions */

      /* start the REPL */
      std::string input;

      while (1) {
         /* print the prompt and ask for input */
         printf("=> ");
         getline(std::cin, input);

         /* evaluate this line */
         char first = input[0];
         SpParser parser(input.substr(1));
         SpError *err = NULL;

         /* check if an error was raised by parsing */
         if (first == '(')
            err = parser.parse_expr();
         else if(first == '[')
            err = parser.parse_function();
         else
            err = PARSE_ERROR("Expected '(' or '['");

         if (err) {
            printf("Parse Error: %s", err->message().c_str());
            delete err;
            continue;
         } else {
            printf("Successfully parsed %d tokens: ", (int)parser.num_tokens());
            for (auto it = parser.cbegin_token(); it != parser.cend_token(); ++it) {
               printf("%s ", (*it)->value().c_str());
            }
            printf("\n");
         }

         /* evaluate the bytecode
         err = eval_bytecode(ob_s, base_scope, opcodes);
         if (ob_s.size() == 1) {
            TObject *result = ob_s.top(); ob_s.pop();
            result->print_self();
         } else {
            err = RUNTIME_ERROR("Left-over objects in stacks");
         }*/

         /* check if there was any errors caused by the evaluation */
         /*if (err) {
            printf("Runtime Error: %s\n", err->message);
            continue;
         }*/
      }
   }

   return 0;
}
<commit_msg>Incorporate VM to REPL<commit_after>#include "include/parser.h"
#include "include/error.h"
#include "include/env.h"
#include "include/token.h"
#include "include/object.h"
#include "include/vm.h"

#include <cstdio>
#include <stack>
#include <vector>
#include <iostream>
#include <string>

int main(int argc, const char * argv[]) {
   /* TODO: use an external library to parse command lines */
   if (argc == 1) {
      /* initialize the parser and VM */
      SpParser parser;
      SpVM vm(&parser);

      /* initialize native functions */

      /* start the REPL */
      std::string input;

      while (1) {
         /* print the prompt and ask for input */
         printf("=> ");
         getline(std::cin, input);

         /* evaluate this line */
         char first = input[0];
         parser.load(input.substr(1));
         SpError *err = NULL;

         /* check if an error was raised by parsing */
         if (first == '(')
            err = parser.parse_expr();
         else if(first == '[')
            err = parser.parse_function();
         else
            err = PARSE_ERROR("Expected '(' or '['");

         if (err) {
            printf("Parse Error: %s\n", err->message().c_str());
            delete err;
            continue;
         } else {
            printf("Successfully parsed %d tokens: ", (int)parser.num_tokens());
            for (auto it = parser.cbegin_token(); it != parser.cend_token(); ++it) {
               printf("%s ", (*it)->value().c_str());
            }
            printf("\n");
         }

         /* evaluate the bytecode */
         err = vm.eval(parser.cbegin_token(), parser.cend_token());

         /* check if there was any errors caused by the evaluation */
         if (err) {
            printf("Runtime Error: %s\n", err->message().c_str());
            continue;
         }

         if (vm.top_object()) {
            SpObject *result = vm.top_object();
            result->print_self();
            vm.clear_objects();
         } else printf("NULL RETURN VALUE\n");
      }
   }

   return 0;
}
<|endoftext|>


<commit_before>// =================================================================== //
// Copyright (C) 2014-2015 Kimura Ryo                                  //
//                                                                     //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/.            //
// =================================================================== //

#include <QtCore/QLocale>
#include <QtWidgets/QApplication>

#include "MainWindow.h"

int main(int argc, char** argv)
{
    QLocale::setDefault(QLocale::system());

    QApplication app(argc, argv);
    MainWindow* mainWindow = new MainWindow(0);
    mainWindow->show();

    const QStringList arguments = app.arguments();

    if (arguments.size() > 1 && QFile::exists(arguments.last())) {
        mainWindow->openFile(arguments.last());
    }

    return app.exec();
}
<commit_msg>Enabled high DPI scaling in Qt<commit_after>// =================================================================== //
// Copyright (C) 2014-2015 Kimura Ryo                                  //
//                                                                     //
// This Source Code Form is subject to the terms of the Mozilla Public //
// License, v. 2.0. If a copy of the MPL was not distributed with this //
// file, You can obtain one at http://mozilla.org/MPL/2.0/.            //
// =================================================================== //

#include <QtCore/QLocale>
#include <QtWidgets/QApplication>

#include "MainWindow.h"

int main(int argc, char** argv)
{
    QLocale::setDefault(QLocale::system());
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv);
    MainWindow* mainWindow = new MainWindow(0);
    mainWindow->show();

    const QStringList arguments = app.arguments();

    if (arguments.size() > 1 && QFile::exists(arguments.last())) {
        mainWindow->openFile(arguments.last());
    }

    return app.exec();
}
<|endoftext|>


<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_
#define RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_

#include <memory>
#include <stdexcept>

#include "rcl/types.h"

#include "rclcpp/allocator/allocator_common.hpp"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/visibility_control.hpp"

#include "rcutils/logging_macros.h"

#include "rmw/serialized_message.h"

namespace rclcpp
{
namespace message_memory_strategy
{

/// Default allocation strategy for messages received by subscriptions.
/** A message memory strategy must be templated on the type of the subscription it belongs to. */
template<typename MessageT, typename Alloc = std::allocator<void>>
class MessageMemoryStrategy
{
public:
  RCLCPP_SMART_PTR_DEFINITIONS(MessageMemoryStrategy)

  using MessageAllocTraits = allocator::AllocRebind<MessageT, Alloc>;
  using MessageAlloc = typename MessageAllocTraits::allocator_type;
  using MessageDeleter = allocator::Deleter<MessageAlloc, MessageT>;

  using SerializedMessageAllocTraits = allocator::AllocRebind<rclcpp::SerializedMessage, Alloc>;
  using SerializedMessageAlloc = typename SerializedMessageAllocTraits::allocator_type;
  using SerializedMessageDeleter =
    allocator::Deleter<SerializedMessageAlloc, rclcpp::SerializedMessage>;

  using BufferAllocTraits = allocator::AllocRebind<char, Alloc>;
  using BufferAlloc = typename BufferAllocTraits::allocator_type;
  using BufferDeleter = allocator::Deleter<BufferAlloc, char>;

  MessageMemoryStrategy()
  {
    message_allocator_ = std::make_shared<MessageAlloc>();
    serialized_message_allocator_ = std::make_shared<SerializedMessageAlloc>();
    buffer_allocator_ = std::make_shared<BufferAlloc>();
    rcutils_allocator_ = allocator::get_rcl_allocator<char, BufferAlloc>(*buffer_allocator_.get());
  }

  explicit MessageMemoryStrategy(std::shared_ptr<Alloc> allocator)
  {
    message_allocator_ = std::make_shared<MessageAlloc>(*allocator.get());
    serialized_message_allocator_ = std::make_shared<SerializedMessageAlloc>(*allocator.get());
    buffer_allocator_ = std::make_shared<BufferAlloc>(*allocator.get());
    rcutils_allocator_ = allocator::get_rcl_allocator<char, BufferAlloc>(*buffer_allocator_.get());
  }

  virtual ~MessageMemoryStrategy() = default;

  /// Default factory method
  static SharedPtr create_default()
  {
    return std::make_shared<MessageMemoryStrategy<MessageT, Alloc>>(std::make_shared<Alloc>());
  }

  /// By default, dynamically allocate a new message.
  /** \return Shared pointer to the new message. */
  virtual std::shared_ptr<MessageT> borrow_message()
  {
    return std::allocate_shared<MessageT, MessageAlloc>(*message_allocator_.get());
  }

  virtual std::shared_ptr<rclcpp::SerializedMessage> borrow_serialized_message(size_t capacity)
  {
    return std::make_shared<rclcpp::SerializedMessage>(capacity);
  }

  virtual std::shared_ptr<rclcpp::SerializedMessage> borrow_serialized_message()
  {
    return borrow_serialized_message(default_buffer_capacity_);
  }

  virtual void set_default_buffer_capacity(size_t capacity)
  {
    default_buffer_capacity_ = capacity;
  }

  /// Release ownership of the message, which will deallocate it if it has no more owners.
  /** \param[in] msg Shared pointer to the message we are returning. */
  virtual void return_message(std::shared_ptr<MessageT> & msg)
  {
    msg.reset();
  }

  virtual void return_serialized_message(
    std::shared_ptr<rclcpp::SerializedMessage> & serialized_msg)
  {
    serialized_msg.reset();
  }

  std::shared_ptr<MessageAlloc> message_allocator_;
  MessageDeleter message_deleter_;

  std::shared_ptr<SerializedMessageAlloc> serialized_message_allocator_;
  SerializedMessageDeleter serialized_message_deleter_;

  std::shared_ptr<BufferAlloc> buffer_allocator_;
  BufferDeleter buffer_deleter_;
  size_t default_buffer_capacity_ = 0;

  rcutils_allocator_t rcutils_allocator_;
};

}  // namespace message_memory_strategy
}  // namespace rclcpp

#endif  // RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_
<commit_msg>Add serialized_message.hpp header (#1095)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_
#define RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_

#include <memory>
#include <stdexcept>

#include "rcl/types.h"

#include "rclcpp/allocator/allocator_common.hpp"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/serialized_message.hpp"
#include "rclcpp/visibility_control.hpp"

#include "rcutils/logging_macros.h"

#include "rmw/serialized_message.h"

namespace rclcpp
{
namespace message_memory_strategy
{

/// Default allocation strategy for messages received by subscriptions.
/** A message memory strategy must be templated on the type of the subscription it belongs to. */
template<typename MessageT, typename Alloc = std::allocator<void>>
class MessageMemoryStrategy
{
public:
  RCLCPP_SMART_PTR_DEFINITIONS(MessageMemoryStrategy)

  using MessageAllocTraits = allocator::AllocRebind<MessageT, Alloc>;
  using MessageAlloc = typename MessageAllocTraits::allocator_type;
  using MessageDeleter = allocator::Deleter<MessageAlloc, MessageT>;

  using SerializedMessageAllocTraits = allocator::AllocRebind<rclcpp::SerializedMessage, Alloc>;
  using SerializedMessageAlloc = typename SerializedMessageAllocTraits::allocator_type;
  using SerializedMessageDeleter =
    allocator::Deleter<SerializedMessageAlloc, rclcpp::SerializedMessage>;

  using BufferAllocTraits = allocator::AllocRebind<char, Alloc>;
  using BufferAlloc = typename BufferAllocTraits::allocator_type;
  using BufferDeleter = allocator::Deleter<BufferAlloc, char>;

  MessageMemoryStrategy()
  {
    message_allocator_ = std::make_shared<MessageAlloc>();
    serialized_message_allocator_ = std::make_shared<SerializedMessageAlloc>();
    buffer_allocator_ = std::make_shared<BufferAlloc>();
    rcutils_allocator_ = allocator::get_rcl_allocator<char, BufferAlloc>(*buffer_allocator_.get());
  }

  explicit MessageMemoryStrategy(std::shared_ptr<Alloc> allocator)
  {
    message_allocator_ = std::make_shared<MessageAlloc>(*allocator.get());
    serialized_message_allocator_ = std::make_shared<SerializedMessageAlloc>(*allocator.get());
    buffer_allocator_ = std::make_shared<BufferAlloc>(*allocator.get());
    rcutils_allocator_ = allocator::get_rcl_allocator<char, BufferAlloc>(*buffer_allocator_.get());
  }

  virtual ~MessageMemoryStrategy() = default;

  /// Default factory method
  static SharedPtr create_default()
  {
    return std::make_shared<MessageMemoryStrategy<MessageT, Alloc>>(std::make_shared<Alloc>());
  }

  /// By default, dynamically allocate a new message.
  /** \return Shared pointer to the new message. */
  virtual std::shared_ptr<MessageT> borrow_message()
  {
    return std::allocate_shared<MessageT, MessageAlloc>(*message_allocator_.get());
  }

  virtual std::shared_ptr<rclcpp::SerializedMessage> borrow_serialized_message(size_t capacity)
  {
    return std::make_shared<rclcpp::SerializedMessage>(capacity);
  }

  virtual std::shared_ptr<rclcpp::SerializedMessage> borrow_serialized_message()
  {
    return borrow_serialized_message(default_buffer_capacity_);
  }

  virtual void set_default_buffer_capacity(size_t capacity)
  {
    default_buffer_capacity_ = capacity;
  }

  /// Release ownership of the message, which will deallocate it if it has no more owners.
  /** \param[in] msg Shared pointer to the message we are returning. */
  virtual void return_message(std::shared_ptr<MessageT> & msg)
  {
    msg.reset();
  }

  virtual void return_serialized_message(
    std::shared_ptr<rclcpp::SerializedMessage> & serialized_msg)
  {
    serialized_msg.reset();
  }

  std::shared_ptr<MessageAlloc> message_allocator_;
  MessageDeleter message_deleter_;

  std::shared_ptr<SerializedMessageAlloc> serialized_message_allocator_;
  SerializedMessageDeleter serialized_message_deleter_;

  std::shared_ptr<BufferAlloc> buffer_allocator_;
  BufferDeleter buffer_deleter_;
  size_t default_buffer_capacity_ = 0;

  rcutils_allocator_t rcutils_allocator_;
};

}  // namespace message_memory_strategy
}  // namespace rclcpp

#endif  // RCLCPP__MESSAGE_MEMORY_STRATEGY_HPP_
<|endoftext|>


<commit_before>
#include "tests.hpp"

struct BufSizePlug : lvtk::Plugin<BufSizePlug, lvtk::BufSize> {
    BufSizePlug (const lvtk::Args& args) : Plugin (args) {}
};

class BufSize : public TestFixutre
{
    CPPUNIT_TEST_SUITE (BufSize);
    CPPUNIT_TEST (buffer_details);
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp() {
        details.min = 64;
        details.max = 4096;
        details.nominal = 128;
        details.sequence_size = 1024 * 8;

        subject = urid.map ("http://dummy.subject.org");
        type = urid.map ("http://www.w3.org/2001/XMLSchema#nonNegativeInteger");
        options.add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__minBlockLength),
            sizeof(uint32_t), type,
            &details.min
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__maxBlockLength),
            sizeof(uint32_t), type,
            &details.max
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__nominalBlockLength),
            sizeof(uint32_t), type,
            &details.nominal
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__sequenceSize),
            sizeof(uint32_t), type,
            &details.sequence_size
        );

        args.sample_rate = 44100.0;
        args.bundle = "/fake/bundle.lv2";
        options_feature.URI = LV2_OPTIONS__options;
        options_feature.data = const_cast<lvtk::Option*> (options.c_obj());
        args.features.push_back (options_feature);
        args.features.push_back (*urid.get_map_feature());
        if (details.bounded)
            args.features.push_back (bounded_feature);
    }

protected:
    void buffer_details() {
        auto plugin = std::unique_ptr<BufSizePlug> (new BufSizePlug (args));
        const auto& pdetails = plugin->buffer_details();
        CPPUNIT_ASSERT_EQUAL (details.min,      pdetails.min);
        CPPUNIT_ASSERT_EQUAL (details.max,      pdetails.max);
        CPPUNIT_ASSERT_EQUAL (details.nominal,  pdetails.nominal);
        CPPUNIT_ASSERT_EQUAL (details.fixed,    pdetails.fixed);
        CPPUNIT_ASSERT_EQUAL (details.bounded,  pdetails.bounded);
        CPPUNIT_ASSERT_EQUAL (details.power_of_two,  pdetails.power_of_two);
        CPPUNIT_ASSERT_EQUAL (details.sequence_size,  pdetails.sequence_size);
    }

private:
    lvtk::Args args;
    LV2_Feature bounded_feature = { LV2_BUF_SIZE__boundedBlockLength, nullptr };
    LV2_Feature options_feature = { LV2_OPTIONS__options, nullptr };
    lvtk::BufferDetails details;
    lvtk::OptionArray options;
    lvtk::URIDirectory urid;
    uint32_t subject;
    uint32_t type;
};

CPPUNIT_TEST_SUITE_REGISTRATION(BufSize);
<commit_msg>Bounded check<commit_after>
#include "tests.hpp"

struct BufSizePlug : lvtk::Plugin<BufSizePlug, lvtk::BufSize> {
    BufSizePlug (const lvtk::Args& args) : Plugin (args) {}
};

class BufSize : public TestFixutre
{
    CPPUNIT_TEST_SUITE (BufSize);
    CPPUNIT_TEST (buffer_details);
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp() {
        details.bounded = true;
        details.min = 64;
        details.max = 4096;
        details.nominal = 128;
        details.sequence_size = 1024 * 8;

        subject = urid.map ("http://dummy.subject.org");
        type = urid.map ("http://www.w3.org/2001/XMLSchema#nonNegativeInteger");
        options.add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__minBlockLength),
            sizeof(uint32_t), type,
            &details.min
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__maxBlockLength),
            sizeof(uint32_t), type,
            &details.max
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__nominalBlockLength),
            sizeof(uint32_t), type,
            &details.nominal
        ).add (
            LV2_OPTIONS_BLANK, subject,
            urid.map (LV2_BUF_SIZE__sequenceSize),
            sizeof(uint32_t), type,
            &details.sequence_size
        );

        args.sample_rate = 44100.0;
        args.bundle = "/fake/bundle.lv2";
        options_feature.URI = LV2_OPTIONS__options;
        options_feature.data = const_cast<lvtk::Option*> (options.c_obj());
        args.features.push_back (options_feature);
        args.features.push_back (*urid.get_map_feature());
        if (details.bounded)
            args.features.push_back (bounded_feature);
    }

protected:
    void buffer_details() {
        auto plugin = std::unique_ptr<BufSizePlug> (new BufSizePlug (args));
        const auto& pdetails = plugin->buffer_details();
        CPPUNIT_ASSERT_EQUAL (details.min,      pdetails.min);
        CPPUNIT_ASSERT_EQUAL (details.max,      pdetails.max);
        CPPUNIT_ASSERT_EQUAL (details.nominal,  pdetails.nominal);
        CPPUNIT_ASSERT_EQUAL (details.fixed,    pdetails.fixed);
        CPPUNIT_ASSERT_EQUAL (details.bounded,  pdetails.bounded);
        CPPUNIT_ASSERT_EQUAL (details.power_of_two,  pdetails.power_of_two);
        CPPUNIT_ASSERT_EQUAL (details.sequence_size,  pdetails.sequence_size);
    }

private:
    lvtk::Args args;
    LV2_Feature bounded_feature = { LV2_BUF_SIZE__boundedBlockLength, nullptr };
    LV2_Feature options_feature = { LV2_OPTIONS__options, nullptr };
    lvtk::BufferDetails details;
    lvtk::OptionArray options;
    lvtk::URIDirectory urid;
    uint32_t subject;
    uint32_t type;
};

CPPUNIT_TEST_SUITE_REGISTRATION(BufSize);
<|endoftext|>