<commit_before>#include "level.hpp"

#include <iostream>
#include <utility>

namespace core
{

int& Level::get_tile(int pos_x, int pos_y, int layer)
{
    return const_cast<int&>(
        const_cast<const Level*>(this)->get_tile(pos_x, pos_y, layer));
}

const int& Level::get_tile(int pos_x, int pos_y, int layer) const
{
    const int* p_ret_val = nullptr;
    if (pos_x > m_size_x || pos_x < 0 || pos_y > m_size_y || pos_y < 0)
    {
        p_ret_val = &m_default_tile;
    }
    else
    {
        p_ret_val = &(m_p_tiles[pos_x + (pos_y * m_size_x) +
            (layer * m_size_y * m_size_x)]);
    }
    return *p_ret_val;
}

Level::Level(int size_x, int size_y, int layers, float scale, int default_tile)
    : m_size_x(size_x),
      m_size_y(size_y),
      m_layers(layers),
      m_scale(scale),
      m_default_tile(default_tile)
{
    m_p_tiles = new int[size_x * size_y * layers];
    for (int layer = 0; layer < layers; layer++)
    {
        for (int pos_x = 0; pos_x < size_x; pos_x++)
        {
            for (int pos_y = 0; pos_y < size_y; pos_y++)
            {
                set(pos_x, pos_y, layer, -1);
            }
        }
    }
    m_sp_logger = logging_get_logger("level");
}

Level::~Level()
{
    delete[] m_p_tiles;
    m_p_tiles = nullptr;
}

float Level::get_scale() const
{
    return m_scale;
}

void Level::get_size(int& x, int& y, int& layers) const
{
    x = m_size_x;
    y = m_size_y;
    layers = m_layers;
}

void Level::get_tile_coords(
    float world_x, float world_y, int& tile_x, int& tile_y) const
{
    // TODO(Keegan): Don't think it's actually quite this simple
    tile_x = world_x / m_scale;
    tile_y = world_y / m_scale;
}

LevelTileSet* Level::get_tileset() const
{
    return (m_up_tileset.get());
}

unsigned int LevelTileSet::get_tilecount() const
{
    return m_tilecount;
}
void Level::print() const
{
    for (int layer = 0; layer < m_layers; layer++)
    {
        std::cout << "layer " << layer << std::endl;
        for (int pos_y = 0; pos_y < m_size_y; pos_y++)
        {
            for (int pos_x = 0; pos_x < m_size_x; pos_x++)
            {
                auto currtile = get_tile(pos_x, pos_y, layer);
                std::cout << '[' << currtile << ']';
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
}

void Level::set(int pos_x, int pos_y, int layer, int tile_id)
{
    auto& tile = get_tile(pos_x, pos_y, layer);
    tile = tile_id;
}

void Level::set_tileset(LevelTileSet* p_tileset)
{
    m_up_tileset = std::unique_ptr<LevelTileSet>(p_tileset);
}

LevelTileSet::LevelTileSet(std::string name,
    std::string filename,
    unsigned int columns,
    unsigned int tilecount,
    unsigned int tilewidth,
    unsigned int tileheight,
    unsigned int spacing,
    unsigned int margin)
    : m_name(std::move(name)),
      m_filename(std::move(filename)),
      m_columns(columns),
      m_tilecount(tilecount),
      m_tilewidth(tilewidth),
      m_tileheight(tileheight),
      m_spacing(spacing),
      m_margin(margin)
{
    m_sp_logger = logging_get_logger("level");
}

bool LevelTileSet::getTileClipping(
    int tile_id, int& x, int& y, int& w, int& h) const
{
    int tilecoord_x = (tile_id - 1) % m_columns;
    int tilecoord_y = (tile_id - 1) / m_columns;

    x = m_margin + (m_tilewidth + m_spacing) * tilecoord_x;
    y = m_margin + (m_tileheight + m_spacing) * tilecoord_y;
    w = m_tilewidth;
    h = m_tileheight;

    return false;
}

std::string LevelTileSet::get_filename() const
{
    return m_filename;
}

sdl_wrap::Texture* LevelTileSet::get_texture()
{
    return m_sp_texture.get();
}

void LevelTileSet::set_texture(std::shared_ptr<sdl_wrap::Texture> sp_texture)
{
    m_sp_texture = sp_texture;
}
} // namespace core
<commit_msg>Level: Fix get tile range check<commit_after>#include "level.hpp"

#include <iostream>
#include <utility>

namespace core
{

int& Level::get_tile(int pos_x, int pos_y, int layer)
{
    return const_cast<int&>(
        const_cast<const Level*>(this)->get_tile(pos_x, pos_y, layer));
}

const int& Level::get_tile(int pos_x, int pos_y, int layer) const
{
    const int* p_ret_val = nullptr;
    if (pos_x >= m_size_x || pos_x < 0 || pos_y >= m_size_y || pos_y < 0)
    {
        p_ret_val = &m_default_tile;
    }
    else
    {
        p_ret_val = &(m_p_tiles[pos_x + (pos_y * m_size_x) +
            (layer * m_size_y * m_size_x)]);
    }
    return *p_ret_val;
}

Level::Level(int size_x, int size_y, int layers, float scale, int default_tile)
    : m_size_x(size_x),
      m_size_y(size_y),
      m_layers(layers),
      m_scale(scale),
      m_default_tile(default_tile)
{
    m_p_tiles = new int[size_x * size_y * layers];
    for (int layer = 0; layer < layers; layer++)
    {
        for (int pos_x = 0; pos_x < size_x; pos_x++)
        {
            for (int pos_y = 0; pos_y < size_y; pos_y++)
            {
                set(pos_x, pos_y, layer, -1);
            }
        }
    }
    m_sp_logger = logging_get_logger("level");
}

Level::~Level()
{
    delete[] m_p_tiles;
    m_p_tiles = nullptr;
}

float Level::get_scale() const
{
    return m_scale;
}

void Level::get_size(int& x, int& y, int& layers) const
{
    x = m_size_x;
    y = m_size_y;
    layers = m_layers;
}

void Level::get_tile_coords(
    float world_x, float world_y, int& tile_x, int& tile_y) const
{
    // TODO(Keegan): Don't think it's actually quite this simple
    tile_x = world_x / m_scale;
    tile_y = world_y / m_scale;
}

LevelTileSet* Level::get_tileset() const
{
    return (m_up_tileset.get());
}

unsigned int LevelTileSet::get_tilecount() const
{
    return m_tilecount;
}
void Level::print() const
{
    for (int layer = 0; layer < m_layers; layer++)
    {
        std::cout << "layer " << layer << std::endl;
        for (int pos_y = 0; pos_y < m_size_y; pos_y++)
        {
            for (int pos_x = 0; pos_x < m_size_x; pos_x++)
            {
                auto currtile = get_tile(pos_x, pos_y, layer);
                std::cout << '[' << currtile << ']';
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
}

void Level::set(int pos_x, int pos_y, int layer, int tile_id)
{
    auto& tile = get_tile(pos_x, pos_y, layer);
    tile = tile_id;
}

void Level::set_tileset(LevelTileSet* p_tileset)
{
    m_up_tileset = std::unique_ptr<LevelTileSet>(p_tileset);
}

LevelTileSet::LevelTileSet(std::string name,
    std::string filename,
    unsigned int columns,
    unsigned int tilecount,
    unsigned int tilewidth,
    unsigned int tileheight,
    unsigned int spacing,
    unsigned int margin)
    : m_name(std::move(name)),
      m_filename(std::move(filename)),
      m_columns(columns),
      m_tilecount(tilecount),
      m_tilewidth(tilewidth),
      m_tileheight(tileheight),
      m_spacing(spacing),
      m_margin(margin)
{
    m_sp_logger = logging_get_logger("level");
}

bool LevelTileSet::getTileClipping(
    int tile_id, int& x, int& y, int& w, int& h) const
{
    int tilecoord_x = (tile_id - 1) % m_columns;
    int tilecoord_y = (tile_id - 1) / m_columns;

    x = m_margin + (m_tilewidth + m_spacing) * tilecoord_x;
    y = m_margin + (m_tileheight + m_spacing) * tilecoord_y;
    w = m_tilewidth;
    h = m_tileheight;

    return false;
}

std::string LevelTileSet::get_filename() const
{
    return m_filename;
}

sdl_wrap::Texture* LevelTileSet::get_texture()
{
    return m_sp_texture.get();
}

void LevelTileSet::set_texture(std::shared_ptr<sdl_wrap::Texture> sp_texture)
{
    m_sp_texture = sp_texture;
}
} // namespace core
<|endoftext|>


<commit_before>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2012, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "heuristic_weight.hh"
#include "helper.hh"
#include <cstdlib>
#include <cstring>
#include <algorithm>

#include "random.hh"

#include "dparse.h"
extern "C" {
  extern D_ParserTables parser_tables_weight;
}

extern Heuristic_weight* Hw;

Heuristic_weight::Heuristic_weight(Log& l,const std::string& params) :
  Heuristic(l), r(NULL)
{
  std::vector<std::string> subs;
  commalist(params,subs);
  switch (subs.size()) {
  case 2:
    prm=subs[0];
    r=new_random(subs[1]);

    if (!r) {
      status=false;
      errormsg="Can't create random "+subs[1];
    } else {
      if (!r->status) {
	status=false;
	errormsg=r->errormsg;
      }
    }

    break;
  case 1:
    prm=subs[0];
    r=Random::default_random();
    break;
  default:
    status=false;
    errormsg="Illegal amount of parameters ("+to_string((unsigned int)subs.size())+"). Expecting 1 or 2";
  }

}

Heuristic_weight::~Heuristic_weight()
{
  if (r)
    r->unref();
}

float Heuristic_weight::getCoverage() {
  if (my_coverage==NULL) {
    return 0.0;
  }
  return my_coverage->getCoverage();
}

void Heuristic_weight::add(std::vector<std::string*> p,
			   std::vector<std::string*> a,
			   int w,int o)
{
  static int weight_id = 0;
  std::vector<int> props;
  std::vector<int> actions;
  std::vector<int>::iterator it;

  for(unsigned i=0;i<p.size();i++) {
    regexpmatch(*(p[i]),model->getSPNames(),props,false);
    delete p[i];
  }

  for(unsigned i=0;i<a.size();i++) {
    regexpmatch(*(a[i]),model->getActionNames(),actions,false,1,1);
    delete a[i];
  }

  // Remove duplicate matches
  std::sort(actions.begin(), actions.end());
  it = std::unique(actions.begin(), actions.end());
  actions.resize(it - actions.begin());

  std::sort(props.begin(), props.end());
  it = std::unique(props.begin(), props.end());
  props.resize(it - props.begin());

  // List of required propositions is empty =>
  // don't care about propositions, match all states
  if (p.empty())
    props.push_back(-1);

  if (actions.empty()) {
    return;
  }

  for(unsigned i=0;i<props.size();i++) {
    for(unsigned j=0;j<actions.size();j++) {
      switch (o) {
      case 1:
	weights[std::pair<int,int>(props[i],actions[j])]=w;
	break;
      default:
	weights[std::pair<int,int>(props[i],actions[j])]+=w;
      }
      weight_ids[std::pair<int,int>(props[i],actions[j])]=weight_id;
    }
  }
  weight_id++;
}

int Heuristic_weight::weight_select(int i,int* actions)
{
  int* props;
  int p=model->getprops(&props);
  float total=0;
  std::vector<float> f;
  std::map< std::pair<int,int>, bool > seen_weight_ids;

  f.resize(i);

  // Go through props
  for(int j=0;j<p;j++) {
    // Go through actions
    for(int k=0;k<i;k++) {
      // Make sure every weight spec has an effect to each enabled
      // action at most once - even if a weight spec matches to this
      // state because of multiple state tag hits.
      std::pair<int,int> pa(props[j],actions[k]);
      float ff = weights[pa];
      int id = weight_ids[pa];
      if (ff != 0.0 && !seen_weight_ids[std::pair<int,int>(actions[k],id)]) {
        f[k]+=ff;
        seen_weight_ids[std::pair<int,int>(actions[k],id)] = true;
      }
    }
  }

  // And then without prop
  // Go through actions
  for(int k=0;k<i;k++) {
    float ff=weights[std::pair<int,int>(-1,actions[k])];
    f[k]+=ff;
  }

  // Make sure there are no negative weights
  for (int k=0; k<i; k++) {
    if (f[k] < 0.0) f[k] = 0.0;
    total += f[k];
  }

  // Total weight 0?
  if (total==0.0) {
    return r->drand48()*i;
  }

  float cut=r->drand48()*total;
  int pos;
  for(pos=0;cut>f[pos];cut-=f[pos],pos++);

  return pos;
}

int Heuristic_weight::getAction()
{
  int* actions;
  int i;

  i=model->getActions(&actions);

  if (i==0) {
    // DEADLOCK
    return Alphabet::DEADLOCK;
  }

  int pos=weight_select(i,actions);

  return actions[pos];
}

int Heuristic_weight::getIAction()
{
  int* actions;
  int i;

  i=model->getIActions(&actions);

  if (i==0) {
    // Ok.. no output actions
    i=model->getActions(&actions);
    if (i==0) {
      return Alphabet::DEADLOCK;
    }
    return Alphabet::OUTPUT_ONLY;
  }

  int pos=weight_select(i,actions);

  return actions[pos];
}

void Heuristic_weight::set_model(Model* _model)
{
  Heuristic::set_model(_model);

  char* s=readfile(prm.c_str());
  if (s) {
    Heuristic_weight* h=Hw;
    Hw=this;
    D_Parser *p = new_D_Parser(&parser_tables_weight, 512);
    p->loc.pathname = prm.c_str();
    bool ret=dparse(p,s,std::strlen(s));
    ret=p->syntax_errors==0 && ret;
    free_D_Parser(p);
    free(s);
    status=ret;
    if (!ret) {
      errormsg="parse error";
    }
    Hw=h;
  } else {
    status=false;
    errormsg="Can't read inputfile";
  }
}

void Heuristic_weight::set_coverage(Coverage* c)
{
  Heuristic::set_coverage(c);
}

FACTORY_DEFAULT_CREATOR(Heuristic, Heuristic_weight, "weight")
<commit_msg>remember to ref<commit_after>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2012, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "heuristic_weight.hh"
#include "helper.hh"
#include <cstdlib>
#include <cstring>
#include <algorithm>

#include "random.hh"

#include "dparse.h"
extern "C" {
  extern D_ParserTables parser_tables_weight;
}

extern Heuristic_weight* Hw;

Heuristic_weight::Heuristic_weight(Log& l,const std::string& params) :
  Heuristic(l), r(NULL)
{
  std::vector<std::string> subs;
  commalist(params,subs);
  switch (subs.size()) {
  case 2:
    prm=subs[0];
    r=new_random(subs[1]);

    if (!r) {
      status=false;
      errormsg="Can't create random "+subs[1];
    } else {
      r->ref();
      if (!r->status) {
	status=false;
	errormsg=r->errormsg;
      }
    }

    break;
  case 1:
    prm=subs[0];
    r=Random::default_random();
    r->ref();
    break;
  default:
    status=false;
    errormsg="Illegal amount of parameters ("+to_string((unsigned int)subs.size())+"). Expecting 1 or 2";
  }

}

Heuristic_weight::~Heuristic_weight()
{
  if (r)
    r->unref();
}

float Heuristic_weight::getCoverage() {
  if (my_coverage==NULL) {
    return 0.0;
  }
  return my_coverage->getCoverage();
}

void Heuristic_weight::add(std::vector<std::string*> p,
			   std::vector<std::string*> a,
			   int w,int o)
{
  static int weight_id = 0;
  std::vector<int> props;
  std::vector<int> actions;
  std::vector<int>::iterator it;

  for(unsigned i=0;i<p.size();i++) {
    regexpmatch(*(p[i]),model->getSPNames(),props,false);
    delete p[i];
  }

  for(unsigned i=0;i<a.size();i++) {
    regexpmatch(*(a[i]),model->getActionNames(),actions,false,1,1);
    delete a[i];
  }

  // Remove duplicate matches
  std::sort(actions.begin(), actions.end());
  it = std::unique(actions.begin(), actions.end());
  actions.resize(it - actions.begin());

  std::sort(props.begin(), props.end());
  it = std::unique(props.begin(), props.end());
  props.resize(it - props.begin());

  // List of required propositions is empty =>
  // don't care about propositions, match all states
  if (p.empty())
    props.push_back(-1);

  if (actions.empty()) {
    return;
  }

  for(unsigned i=0;i<props.size();i++) {
    for(unsigned j=0;j<actions.size();j++) {
      switch (o) {
      case 1:
	weights[std::pair<int,int>(props[i],actions[j])]=w;
	break;
      default:
	weights[std::pair<int,int>(props[i],actions[j])]+=w;
      }
      weight_ids[std::pair<int,int>(props[i],actions[j])]=weight_id;
    }
  }
  weight_id++;
}

int Heuristic_weight::weight_select(int i,int* actions)
{
  int* props;
  int p=model->getprops(&props);
  float total=0;
  std::vector<float> f;
  std::map< std::pair<int,int>, bool > seen_weight_ids;

  f.resize(i);

  // Go through props
  for(int j=0;j<p;j++) {
    // Go through actions
    for(int k=0;k<i;k++) {
      // Make sure every weight spec has an effect to each enabled
      // action at most once - even if a weight spec matches to this
      // state because of multiple state tag hits.
      std::pair<int,int> pa(props[j],actions[k]);
      float ff = weights[pa];
      int id = weight_ids[pa];
      if (ff != 0.0 && !seen_weight_ids[std::pair<int,int>(actions[k],id)]) {
        f[k]+=ff;
        seen_weight_ids[std::pair<int,int>(actions[k],id)] = true;
      }
    }
  }

  // And then without prop
  // Go through actions
  for(int k=0;k<i;k++) {
    float ff=weights[std::pair<int,int>(-1,actions[k])];
    f[k]+=ff;
  }

  // Make sure there are no negative weights
  for (int k=0; k<i; k++) {
    if (f[k] < 0.0) f[k] = 0.0;
    total += f[k];
  }

  // Total weight 0?
  if (total==0.0) {
    return r->drand48()*i;
  }

  float cut=r->drand48()*total;
  int pos;
  for(pos=0;cut>f[pos];cut-=f[pos],pos++);

  return pos;
}

int Heuristic_weight::getAction()
{
  int* actions;
  int i;

  i=model->getActions(&actions);

  if (i==0) {
    // DEADLOCK
    return Alphabet::DEADLOCK;
  }

  int pos=weight_select(i,actions);

  return actions[pos];
}

int Heuristic_weight::getIAction()
{
  int* actions;
  int i;

  i=model->getIActions(&actions);

  if (i==0) {
    // Ok.. no output actions
    i=model->getActions(&actions);
    if (i==0) {
      return Alphabet::DEADLOCK;
    }
    return Alphabet::OUTPUT_ONLY;
  }

  int pos=weight_select(i,actions);

  return actions[pos];
}

void Heuristic_weight::set_model(Model* _model)
{
  Heuristic::set_model(_model);

  char* s=readfile(prm.c_str());
  if (s) {
    Heuristic_weight* h=Hw;
    Hw=this;
    D_Parser *p = new_D_Parser(&parser_tables_weight, 512);
    p->loc.pathname = prm.c_str();
    bool ret=dparse(p,s,std::strlen(s));
    ret=p->syntax_errors==0 && ret;
    free_D_Parser(p);
    free(s);
    status=ret;
    if (!ret) {
      errormsg="parse error";
    }
    Hw=h;
  } else {
    status=false;
    errormsg="Can't read inputfile";
  }
}

void Heuristic_weight::set_coverage(Coverage* c)
{
  Heuristic::set_coverage(c);
}

FACTORY_DEFAULT_CREATOR(Heuristic, Heuristic_weight, "weight")
<|endoftext|>


<commit_before>#ifndef _GOOGLER_H
#define _GOOGLER_H

#include <string>
#include "./json.hpp"

namespace Googler {

	/*
		Formats num_res_to_show results into

		title -> link
	*/
	void do_google_search(const std::string& query,
	                      const size_t& num_res_to_show,
						  std::vector<std::string>& res_vec);
};

#endif
<commit_msg>document googler<commit_after>#ifndef _GOOGLER_H
#define _GOOGLER_H

#include <string>
#include "./json.hpp"

namespace Googler {

	/*
		Performs a google search and then formats the results.

		@param query the query to google for. It's URI encoded inside the function,
			meaning that a human-readable query should be passed.
		@param num_res_to_show the number of google results desired.
		@res_vec a string vector in which the results are stored. "Title -> ShortenedLink"
	*/
	void do_google_search(const std::string& query,
	                      const size_t& num_res_to_show,
						  std::vector<std::string>& res_vec);
};

#endif
<|endoftext|>


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

  FILE:  LASwriteitemraw.hpp

  CONTENTS:

    Implementation of LASwriteItemRaw for *all* items that compose a point.

  PROGRAMMERS:

    martin.isenburg@gmail.com

  COPYRIGHT:

    (c) 2010-2011, Martin Isenburg, LASSO - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    10 January 2011 -- licensing change for LGPL release and liblas integration
    7 January 2011 -- introduced swap buffers to reduce number of fwrite calls
    12 December 2010 -- refactored after watching two movies with silke

===============================================================================
*/
#ifndef LAS_WRITE_ITEM_RAW_H
#define LAS_WRITE_ITEM_RAW_H

#include "laswriteitem.hpp"

#include <assert.h>

class LASwriteItemRaw_POINT10_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_POINT10_LE(){};
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 20);
  };
};

class LASwriteItemRaw_POINT10_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_POINT10_BE(){};
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_32(&item[ 0], &swapped[ 0]);    // x
    ENDIAN_SWAP_32(&item[ 4], &swapped[ 4]);    // y
    ENDIAN_SWAP_32(&item[ 8], &swapped[ 8]);    // z
    ENDIAN_SWAP_16(&item[12], &swapped[12]);    // intensity
    *((U32*)&swapped[14]) = *((U32*)&item[14]); // bitfield, classification, scan_angle_rank, user_data
    ENDIAN_SWAP_16(&item[18], &swapped[18]);    // point_source_ID
    return outstream->putBytes(swapped, 20);
  };
private:
  U8 swapped[20];
};

class LASwriteItemRaw_GPSTIME11_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_GPSTIME11_LE() {};
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 8);
  };
};

class LASwriteItemRaw_GPSTIME11_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_GPSTIME11_BE() {};
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_64(item, swapped);
    return outstream->putBytes(swapped, 8);
  };
private:
  U8 swapped[8];
};

class LASwriteItemRaw_RGB12_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGB12_LE(){}
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 6);
  };
};

class LASwriteItemRaw_RGB12_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGB12_BE(){}
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_32(&item[ 0], &swapped[ 0]); // R
    ENDIAN_SWAP_32(&item[ 2], &swapped[ 2]); // G
    ENDIAN_SWAP_32(&item[ 4], &swapped[ 4]); // B
    return outstream->putBytes(swapped, 6);
  };
private:
  U8 swapped[6];
};

class LASwriteItemRaw_WAVEPACKET13_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_WAVEPACKET13_LE(){}
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 29);
  };
};

class LASwriteItemRaw_WAVEPACKET13_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_WAVEPACKET13_BE(){}
  inline BOOL write(const U8* item)
  {
    swapped[0] = item[0];                    // wavepacket descriptor index
    ENDIAN_SWAP_64(&item[ 1], &swapped[ 1]); // byte offset to waveform data
    ENDIAN_SWAP_32(&item[ 9], &swapped[ 9]); // waveform packet size in bytes
    ENDIAN_SWAP_32(&item[13], &swapped[13]); // return point waveform location
    ENDIAN_SWAP_32(&item[17], &swapped[17]); // X(t)
    ENDIAN_SWAP_32(&item[21], &swapped[21]); // Y(t)
    ENDIAN_SWAP_32(&item[25], &swapped[25]); // Z(t)
    return outstream->putBytes(swapped, 29);
  };
private:
  U8 swapped[29];
};

class LASwriteItemRaw_BYTE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_BYTE(U32 number)
  {
    this->number = number;
  }
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, number);
  };
private:
  U32 number;
};

#endif
<commit_msg>fix seeking without chunk table + LAS 1.4 stubs<commit_after>/*
===============================================================================

  FILE:  LASwriteitemraw.hpp

  CONTENTS:

    Implementation of LASwriteItemRaw for *all* items that compose a point.

  PROGRAMMERS:

    martin.isenburg@gmail.com

  COPYRIGHT:

    (c) 2010-2011, Martin Isenburg, LASSO - tools to catch reality

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  CHANGE HISTORY:

    10 January 2011 -- licensing change for LGPL release and liblas integration
    7 January 2011 -- introduced swap buffers to reduce number of fwrite calls
    12 December 2010 -- refactored after watching two movies with silke

===============================================================================
*/
#ifndef LAS_WRITE_ITEM_RAW_H
#define LAS_WRITE_ITEM_RAW_H

#include "laswriteitem.hpp"

#include <assert.h>

class LASwriteItemRaw_POINT10_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_POINT10_LE(){};
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 20);
  };
};

class LASwriteItemRaw_POINT10_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_POINT10_BE(){};
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_32(&item[ 0], &swapped[ 0]);    // x
    ENDIAN_SWAP_32(&item[ 4], &swapped[ 4]);    // y
    ENDIAN_SWAP_32(&item[ 8], &swapped[ 8]);    // z
    ENDIAN_SWAP_16(&item[12], &swapped[12]);    // intensity
    *((U32*)&swapped[14]) = *((U32*)&item[14]); // bitfield, classification, scan_angle_rank, user_data
    ENDIAN_SWAP_16(&item[18], &swapped[18]);    // point_source_ID
    return outstream->putBytes(swapped, 20);
  };
private:
  U8 swapped[20];
};

class LASwriteItemRaw_GPSTIME11_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_GPSTIME11_LE() {};
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 8);
  };
};

class LASwriteItemRaw_GPSTIME11_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_GPSTIME11_BE() {};
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_64(item, swapped);
    return outstream->putBytes(swapped, 8);
  };
private:
  U8 swapped[8];
};

class LASwriteItemRaw_RGB12_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGB12_LE(){}
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 6);
  };
};

class LASwriteItemRaw_RGB12_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGB12_BE(){}
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_32(&item[ 0], &swapped[ 0]); // R
    ENDIAN_SWAP_32(&item[ 2], &swapped[ 2]); // G
    ENDIAN_SWAP_32(&item[ 4], &swapped[ 4]); // B
    return outstream->putBytes(swapped, 6);
  };
private:
  U8 swapped[6];
};

class LASwriteItemRaw_WAVEPACKET13_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_WAVEPACKET13_LE(){}
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 29);
  };
};

class LASwriteItemRaw_WAVEPACKET13_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_WAVEPACKET13_BE(){}
  inline BOOL write(const U8* item)
  {
    swapped[0] = item[0];                    // wavepacket descriptor index
    ENDIAN_SWAP_64(&item[ 1], &swapped[ 1]); // byte offset to waveform data
    ENDIAN_SWAP_32(&item[ 9], &swapped[ 9]); // waveform packet size in bytes
    ENDIAN_SWAP_32(&item[13], &swapped[13]); // return point waveform location
    ENDIAN_SWAP_32(&item[17], &swapped[17]); // X(t)
    ENDIAN_SWAP_32(&item[21], &swapped[21]); // Y(t)
    ENDIAN_SWAP_32(&item[25], &swapped[25]); // Z(t)
    return outstream->putBytes(swapped, 29);
  };
private:
  U8 swapped[29];
};

class LASwriteItemRaw_BYTE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_BYTE(U32 number)
  {
    this->number = number;
  }
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, number);
  };
private:
  U32 number;
};

class LAStempWritePoint10
{
public:
  I32 x;
  I32 y;
  I32 z;
  U16 intensity;
  U8 return_number : 3;
  U8 number_of_returns_of_given_pulse : 3;
  U8 scan_direction_flag : 1;
  U8 edge_of_flight_line : 1;
  U8 classification;
  I8 scan_angle_rank;
  U8 user_data;
  U16 point_source_ID;
};

class LAStempWritePoint14
{
public:
  I32 x;
  I32 y;
  I32 z;
  U16 intensity;
  U8 return_number : 4;
  U8 number_of_returns_of_given_pulse : 4;
  U8 classification_flags : 4;
  U8 scanner_channel : 2;
  U8 scan_direction_flag : 1;
  U8 edge_of_flight_line : 1;
  U8 classification;
  U8 user_data;
  I16 scan_angle;
  U16 point_source_ID;
};

class LASwriteItemRaw_POINT14_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_POINT14_LE(){};
  inline BOOL write(const U8* item)
  {
    ((LAStempWritePoint14*)buffer)->x = ((LAStempWritePoint10*)item)->x;
    ((LAStempWritePoint14*)buffer)->y = ((LAStempWritePoint10*)item)->y;
    ((LAStempWritePoint14*)buffer)->z = ((LAStempWritePoint10*)item)->z;
    ((LAStempWritePoint14*)buffer)->intensity = ((LAStempWritePoint10*)item)->intensity;
    ((LAStempWritePoint14*)buffer)->return_number = ((LAStempWritePoint10*)item)->return_number;
    ((LAStempWritePoint14*)buffer)->number_of_returns_of_given_pulse = ((LAStempWritePoint10*)item)->number_of_returns_of_given_pulse;
    ((LAStempWritePoint14*)buffer)->classification_flags = (((LAStempWritePoint10*)item)->classification >> 5);
    ((LAStempWritePoint14*)buffer)->scanner_channel = 0;
    ((LAStempWritePoint14*)buffer)->scan_direction_flag = ((LAStempWritePoint10*)item)->scan_direction_flag;
    ((LAStempWritePoint14*)buffer)->edge_of_flight_line = ((LAStempWritePoint10*)item)->edge_of_flight_line;
    ((LAStempWritePoint14*)buffer)->classification = ((LAStempWritePoint10*)item)->classification & 31;
    ((LAStempWritePoint14*)buffer)->user_data = ((LAStempWritePoint10*)item)->user_data;
    ((LAStempWritePoint14*)buffer)->scan_angle = I16_QUANTIZE(((LAStempWritePoint10*)item)->scan_angle_rank/0.006f);
    ((LAStempWritePoint14*)buffer)->point_source_ID = ((LAStempWritePoint10*)item)->point_source_ID;
    *((F64*)&buffer[22]) = *((F64*)&item[24]);
    return outstream->putBytes(buffer, 30);
  }
private:
  U8 buffer[30];
};

class LASwriteItemRaw_RGBNIR14_LE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGBNIR14_LE(){}
  inline BOOL write(const U8* item)
  {
    return outstream->putBytes(item, 8);
  };
};

class LASwriteItemRaw_RGBNIR14_BE : public LASwriteItemRaw
{
public:
  LASwriteItemRaw_RGBNIR14_BE(){}
  inline BOOL write(const U8* item)
  {
    ENDIAN_SWAP_32(&item[ 0], &swapped[ 0]); // R
    ENDIAN_SWAP_32(&item[ 2], &swapped[ 2]); // G
    ENDIAN_SWAP_32(&item[ 4], &swapped[ 4]); // B
    ENDIAN_SWAP_32(&item[ 6], &swapped[ 6]); // NIR
    return outstream->putBytes(swapped, 8);
  };
private:
  U8 swapped[8];
};

#endif
<|endoftext|>


<commit_before>/**
   MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
   Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

**/
#include "abstractable.h"

using namespace mgl;
using namespace std;

#include "log.h"

#ifdef __APPLE__
#include <CFBundle.h>
#endif

#ifdef WIN32
#include <Windows.h>
#include <Shlobj.h>
#else
#include <sys/types.h>
#include <pwd.h>
#endif

#include <fstream>

std::ostream &MyComputer::log()
{
    return cout;
}

#ifdef QT_CORE_LIB
int FileSystemAbstractor::guarenteeDirectoryExists(const char* )//pathname  )
{
    Log::info() << "not supported on QT" << endl;
    return -1;
#else
int FileSystemAbstractor::guarenteeDirectoryExists(const char* pathname)
{
    int status = 0;

#ifdef WIN32
        DWORD attrib = GetFileAttributes(pathname);

        if (attrib == INVALID_FILE_ATTRIBUTES) {
            BOOL result = CreateDirectoryA(pathname, NULL);
            if (!result)
                status = -1; //creation fail
        }
        else if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
            status = -1;

#else //WIN32
        // mode_t does not work under QT
        mode_t mode =  (S_IREAD|S_IWRITE |S_IRGRP|S_IWGRP |S_IROTH);

		struct stat st;
		if(stat(pathname,&st) != 0){
			mode_t process_mask = umask(0);
			int result_code = mkdir(pathname, mode);
			umask(process_mask);
			if(result_code != 0)
				status = -1 ; //creation fail
		}
		else if (!S_ISDIR(st.st_mode))
			status = -1;
		return status;
#endif //!WIN32
#endif //!QT_CORE_LIB

}

string FileSystemAbstractor::pathJoin(string path, string filename) const
{
#ifdef WIN32
    return path  + "\\" + filename;
#else
	return path  + "/" + filename;
#endif
}

char FileSystemAbstractor::getPathSeparatorCharacter() const
{
#ifdef WIN32
    return '\\';
#else
    return '/'; // Linux & Mac, works on Windows most times
#endif
}

string FileSystemAbstractor::ExtractDirectory(const char *directoryPath) const
{
	const string path(directoryPath);
	return path.substr(0, path.find_last_of(getPathSeparatorCharacter()) + 1);
}

string FileSystemAbstractor::ExtractFilename(const char* filename) const
{
	std::string path(filename);
	return path.substr(path.find_last_of(getPathSeparatorCharacter()) + 1);
}

string FileSystemAbstractor::ChangeExtension(const char* filename, const char* extension) const
{
	const string path(filename);
	const string ext(extension);
	std::string filenameStr = ExtractFilename(path.c_str());
	return ExtractDirectory(path.c_str())
			+ filenameStr.substr(0, filenameStr.find_last_of('.')) + ext;
}

string FileSystemAbstractor::removeExtension(const char *filename) const
{
	const string path(filename);
	string filenameStr = ExtractFilename(path.c_str());
	return ExtractDirectory(path.c_str())
			+ filenameStr.substr(0, filenameStr.find_last_of('.'));
}

bool FileSystemAbstractor::fileReadable(const char *filename) const {
	ifstream testfile(filename, ifstream::in);
	bool readable = !testfile.fail();
	testfile.close();

	return readable;
}

string FileSystemAbstractor::getConfigFile(const char *filename) const {
	string found = getUserConfigFile(filename);
	if (found.length() > 0 && fileReadable(found.c_str()))
		return found;

	found = getSystemConfigFile(filename);
	if (found.length() > 0 && fileReadable(found.c_str()))
		return found;

	return string();
}

string FileSystemAbstractor::getSystemConfigFile(const char *filename) const {
#ifdef WIN32
    char app_path[1024];

	GetModuleFileNameA(0, app_path, sizeof(app_path) - 1);

	// Extract directory
	std::string app_dir = ExtractDirectory(app_path);
	return pathJoin(app_dir, filename);

#elif defined __APPLE__
	CFBundleRef mainBundle;

	mainBundle = CFBundleGetMainBundle();
	if(!mainBundle)
		return string();

	CFURLRef resourceURL;
	resourceURL =
		CFBundleCopyResourceURL(mainBundle,
					CFStringCreateWithCString(NULL,
											  filename,
											  kCFStringEncodingASCII),

								NULL,
								NULL);

	if (!resourceURL)
		return string();

	char fileurl[1024];
	if(!CFURLGetFileSystemRepresentation(resourceURL,
										 true,
										 (UInt8*)
										 fileurl,
										 1024)) {
		return string();
p	}

	return string(fileurl);
#else //linux

	return pathJoin(string("/etc/xdg/makerbot/"), filename);
#endif
}

string FileSystemAbstractor::getUserConfigFile(const char *filename) const {
#ifdef WIN32
	char app_data[1024];
	if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0,
								 app_data))) {
		return pathJoin(pathJoin(string(app_data), "Makerbot"),
						filename);
	}
#else //linux or apple
	char pwbuff[1024];
	struct passwd pw;
	struct passwd *tempptr;
	if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {

#ifdef __APPLE__
		return pathJoin(pathJoin(string(pw.pw_dir),
								 "Library/Preferences/Makerbot/Miracle-Grue"),
						filename);
#else //linux
		return pathJoin(pathJoin(string(pw.pw_dir), ".config/makerbot"),
						filename);
#endif //linux
	}

#endif //win32

	return string();
}

ProgressLog::ProgressLog(unsigned int count)
    :ProgressBar(count,"")
{
	reset(count);
	std::cout << ":";

}

void ProgressLog::onTick(const char* taskName, unsigned int count, unsigned int ticks)
{
	if (ticks == 0) {
		this->deltaTicks = 0;
		this->deltaProgress = 0;
		this->delta = count / 10;
		std::cout << taskName;
		Log::info() << " [" << deltaProgress * 10 << "%] ";
	}

	if (deltaTicks >= this->delta)
	{
		deltaProgress++;
		std::cout << " [" << deltaProgress * 10 << "%] ";
		std::cout.flush();
		Log::info() << " [" << deltaProgress * 10 << "%] ";
		this->deltaTicks = 0;

	}
	if ( ticks >= count -1  ) {

		string now = myPc.clock.now();
        Log::info() << now;
        std::cout << now << endl;
	}
	deltaTicks++;
}

<commit_msg>Stupid stray char snuck in there<commit_after>/**
   MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
   Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

**/
#include "abstractable.h"

using namespace mgl;
using namespace std;

#include "log.h"

#ifdef __APPLE__
#include <CFBundle.h>
#endif

#ifdef WIN32
#include <Windows.h>
#include <Shlobj.h>
#else
#include <sys/types.h>
#include <pwd.h>
#endif

#include <fstream>

std::ostream &MyComputer::log()
{
    return cout;
}

#ifdef QT_CORE_LIB
int FileSystemAbstractor::guarenteeDirectoryExists(const char* )//pathname  )
{
    Log::info() << "not supported on QT" << endl;
    return -1;
#else
int FileSystemAbstractor::guarenteeDirectoryExists(const char* pathname)
{
    int status = 0;

#ifdef WIN32
        DWORD attrib = GetFileAttributes(pathname);

        if (attrib == INVALID_FILE_ATTRIBUTES) {
            BOOL result = CreateDirectoryA(pathname, NULL);
            if (!result)
                status = -1; //creation fail
        }
        else if (!(attrib & FILE_ATTRIBUTE_DIRECTORY))
            status = -1;

#else //WIN32
        // mode_t does not work under QT
        mode_t mode =  (S_IREAD|S_IWRITE |S_IRGRP|S_IWGRP |S_IROTH);

		struct stat st;
		if(stat(pathname,&st) != 0){
			mode_t process_mask = umask(0);
			int result_code = mkdir(pathname, mode);
			umask(process_mask);
			if(result_code != 0)
				status = -1 ; //creation fail
		}
		else if (!S_ISDIR(st.st_mode))
			status = -1;
		return status;
#endif //!WIN32
#endif //!QT_CORE_LIB

}

string FileSystemAbstractor::pathJoin(string path, string filename) const
{
#ifdef WIN32
    return path  + "\\" + filename;
#else
	return path  + "/" + filename;
#endif
}

char FileSystemAbstractor::getPathSeparatorCharacter() const
{
#ifdef WIN32
    return '\\';
#else
    return '/'; // Linux & Mac, works on Windows most times
#endif
}

string FileSystemAbstractor::ExtractDirectory(const char *directoryPath) const
{
	const string path(directoryPath);
	return path.substr(0, path.find_last_of(getPathSeparatorCharacter()) + 1);
}

string FileSystemAbstractor::ExtractFilename(const char* filename) const
{
	std::string path(filename);
	return path.substr(path.find_last_of(getPathSeparatorCharacter()) + 1);
}

string FileSystemAbstractor::ChangeExtension(const char* filename, const char* extension) const
{
	const string path(filename);
	const string ext(extension);
	std::string filenameStr = ExtractFilename(path.c_str());
	return ExtractDirectory(path.c_str())
			+ filenameStr.substr(0, filenameStr.find_last_of('.')) + ext;
}

string FileSystemAbstractor::removeExtension(const char *filename) const
{
	const string path(filename);
	string filenameStr = ExtractFilename(path.c_str());
	return ExtractDirectory(path.c_str())
			+ filenameStr.substr(0, filenameStr.find_last_of('.'));
}

bool FileSystemAbstractor::fileReadable(const char *filename) const {
	ifstream testfile(filename, ifstream::in);
	bool readable = !testfile.fail();
	testfile.close();

	return readable;
}

string FileSystemAbstractor::getConfigFile(const char *filename) const {
	string found = getUserConfigFile(filename);
	if (found.length() > 0 && fileReadable(found.c_str()))
		return found;

	found = getSystemConfigFile(filename);
	if (found.length() > 0 && fileReadable(found.c_str()))
		return found;

	return string();
}

string FileSystemAbstractor::getSystemConfigFile(const char *filename) const {
#ifdef WIN32
    char app_path[1024];

	GetModuleFileNameA(0, app_path, sizeof(app_path) - 1);

	// Extract directory
	std::string app_dir = ExtractDirectory(app_path);
	return pathJoin(app_dir, filename);

#elif defined __APPLE__
	CFBundleRef mainBundle;

	mainBundle = CFBundleGetMainBundle();
	if(!mainBundle)
		return string();

	CFURLRef resourceURL;
	resourceURL =
		CFBundleCopyResourceURL(mainBundle,
					CFStringCreateWithCString(NULL,
											  filename,
											  kCFStringEncodingASCII),

								NULL,
								NULL);

	if (!resourceURL)
		return string();

	char fileurl[1024];
	if(!CFURLGetFileSystemRepresentation(resourceURL,
										 true,
										 (UInt8*)
										 fileurl,
										 1024)) {
		return string();
	}

	return string(fileurl);
#else //linux

	return pathJoin(string("/etc/xdg/makerbot/"), filename);
#endif
}

string FileSystemAbstractor::getUserConfigFile(const char *filename) const {
#ifdef WIN32
	char app_data[1024];
	if(SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0,
								 app_data))) {
		return pathJoin(pathJoin(string(app_data), "Makerbot"),
						filename);
	}
#else //linux or apple
	char pwbuff[1024];
	struct passwd pw;
	struct passwd *tempptr;
	if (getpwuid_r(getuid(), &pw, pwbuff, 1024, &tempptr) == 0) {

#ifdef __APPLE__
		return pathJoin(pathJoin(string(pw.pw_dir),
								 "Library/Preferences/Makerbot/Miracle-Grue"),
						filename);
#else //linux
		return pathJoin(pathJoin(string(pw.pw_dir), ".config/makerbot"),
						filename);
#endif //linux
	}

#endif //win32

	return string();
}

ProgressLog::ProgressLog(unsigned int count)
    :ProgressBar(count,"")
{
	reset(count);
	std::cout << ":";

}

void ProgressLog::onTick(const char* taskName, unsigned int count, unsigned int ticks)
{
	if (ticks == 0) {
		this->deltaTicks = 0;
		this->deltaProgress = 0;
		this->delta = count / 10;
		std::cout << taskName;
		Log::info() << " [" << deltaProgress * 10 << "%] ";
	}

	if (deltaTicks >= this->delta)
	{
		deltaProgress++;
		std::cout << " [" << deltaProgress * 10 << "%] ";
		std::cout.flush();
		Log::info() << " [" << deltaProgress * 10 << "%] ";
		this->deltaTicks = 0;

	}
	if ( ticks >= count -1  ) {

		string now = myPc.clock.now();
        Log::info() << now;
        std::cout << now << endl;
	}
	deltaTicks++;
}

<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Ethereum client.
 */
#include <functional>
#include <libdevcore/Log.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/RLP.h>
#include <libdevcore/CommonIO.h>
#include <libp2p/All.h>
#include <libdevcore/RangeMask.h>
#include <libethereum/DownloadMan.h>
#include <libethereum/All.h>
#include <liblll/All.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace dev::p2p;
using namespace dev::shh;

#if 0
int main()
{
	DownloadMan man;
	DownloadSub s0(man);
	DownloadSub s1(man);
	DownloadSub s2(man);
	man.resetToChain(h256s({u256(0), u256(1), u256(2), u256(3), u256(4), u256(5), u256(6), u256(7), u256(8)}));
	assert((s0.nextFetch(2) == h256Set{(u256)7, (u256)8}));
	assert((s1.nextFetch(2) == h256Set{(u256)5, (u256)6}));
	assert((s2.nextFetch(2) == h256Set{(u256)3, (u256)4}));
	s0.noteBlock(u256(8));
	s0.doneFetch();
	assert((s0.nextFetch(2) == h256Set{(u256)2, (u256)7}));
	s1.noteBlock(u256(6));
	s1.noteBlock(u256(5));
	s1.doneFetch();
	assert((s1.nextFetch(2) == h256Set{(u256)0, (u256)1}));
	s0.doneFetch();				// TODO: check exact semantics of doneFetch & nextFetch. Not sure if they're right -> doneFetch calls resetFetch which kills all the info of past fetches.
	cdebug << s0.nextFetch(2);
	assert((s0.nextFetch(2) == h256Set{(u256)3, (u256)4}));

/*	RangeMask<unsigned> m(0, 100);
	cnote << m;
	m += UnsignedRange(3, 10);
	cnote << m;
	m += UnsignedRange(11, 16);
	cnote << m;
	m += UnsignedRange(10, 11);
	cnote << m;
	cnote << ~m;
	cnote << (~m).lowest(10);
	for (auto i: (~m).lowest(10))
		cnote << i;*/
	return 0;
}
#else
int main()
{
	KeyPair u = KeyPair::create();
	KeyPair cb = KeyPair::create();
	OverlayDB db;
	State s(cb.address(), db, BaseState::Empty);
	cnote << s.rootHash();
	s.addBalance(u.address(), 1 * ether);
	Address c = s.newContract(1000 * ether, compileLLL("(suicide (caller))"));
	s.commit();
	State before = s;
	cnote << "State before transaction: " << before;
	Transaction t(0, 10000, 10000, c, bytes(), 0, u.secret());
	cnote << "Transaction: " << t;
	cnote << s.balance(c);
	s.execute(t.rlp());
	cnote << "State after transaction: " << s;
	cnote << before.diff(s);
}
#endif

<commit_msg>ungly fix for compiling exp on mac<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * Ethereum client.
 */
#include <functional>
#include <libethereum/AccountDiff.h>
#include <libdevcore/Log.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/RLP.h>
#include <libdevcore/CommonIO.h>
#include <libp2p/All.h>
#include <libdevcore/RangeMask.h>
#include <libethereum/DownloadMan.h>
#include <libethereum/All.h>
#include <liblll/All.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace dev::p2p;
using namespace dev::shh;

#if 0
int main()
{
	DownloadMan man;
	DownloadSub s0(man);
	DownloadSub s1(man);
	DownloadSub s2(man);
	man.resetToChain(h256s({u256(0), u256(1), u256(2), u256(3), u256(4), u256(5), u256(6), u256(7), u256(8)}));
	assert((s0.nextFetch(2) == h256Set{(u256)7, (u256)8}));
	assert((s1.nextFetch(2) == h256Set{(u256)5, (u256)6}));
	assert((s2.nextFetch(2) == h256Set{(u256)3, (u256)4}));
	s0.noteBlock(u256(8));
	s0.doneFetch();
	assert((s0.nextFetch(2) == h256Set{(u256)2, (u256)7}));
	s1.noteBlock(u256(6));
	s1.noteBlock(u256(5));
	s1.doneFetch();
	assert((s1.nextFetch(2) == h256Set{(u256)0, (u256)1}));
	s0.doneFetch();				// TODO: check exact semantics of doneFetch & nextFetch. Not sure if they're right -> doneFetch calls resetFetch which kills all the info of past fetches.
	cdebug << s0.nextFetch(2);
	assert((s0.nextFetch(2) == h256Set{(u256)3, (u256)4}));

/*	RangeMask<unsigned> m(0, 100);
	cnote << m;
	m += UnsignedRange(3, 10);
	cnote << m;
	m += UnsignedRange(11, 16);
	cnote << m;
	m += UnsignedRange(10, 11);
	cnote << m;
	cnote << ~m;
	cnote << (~m).lowest(10);
	for (auto i: (~m).lowest(10))
		cnote << i;*/
	return 0;
}
#else
int main()
{
	KeyPair u = KeyPair::create();
	KeyPair cb = KeyPair::create();
	OverlayDB db;
	State s(cb.address(), db, BaseState::Empty);
	cnote << s.rootHash();
	s.addBalance(u.address(), 1 * ether);
	Address c = s.newContract(1000 * ether, compileLLL("(suicide (caller))"));
	s.commit();
	State before = s;
	cnote << "State before transaction: " << before;
	Transaction t(0, 10000, 10000, c, bytes(), 0, u.secret());
	cnote << "Transaction: " << t;
	cnote << s.balance(c);
	s.execute(t.rlp());
	cnote << "State after transaction: " << s;
	cnote << before.diff(s);
}
#endif

<|endoftext|>


<commit_before>/*
 * getopt_long() -- long options parser
 *
 * Portions Copyright (c) 1987, 1993, 1994
 * The Regents of the University of California.  All rights reserved.
 *
 * Portions Copyright (c) 2003
 * PostgreSQL Global Development Group
 *
 * 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. Neither the name of the University 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 REGENTS 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 REGENTS 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 "getopt.h"

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

#define BADCH  '?'
#define BADARG ':'
#define EMSG   ""

int opterr = 1,   /* if error message should be printed */
  optind = 1,   /* index into parent argv vector */
  optopt,     /* character checked for validity */
  optreset;   /* reset getopt */
char  *optarg;    /* argument associated with option */

int
getopt_long(int argc, char *const argv[],
            const char *optstring,
            const struct option * longopts, int *longindex)
{
  static char *place = EMSG; /* option letter processing */
  const char *oli;           /* option letter list index */

  if (!*place)
  { /* update scanning pointer */
    if (optind >= argc)
    {
      place = EMSG;
      return -1;
    }

    place = argv[optind];

    if (place[0] != '-')
    {
      place = EMSG;
      return -1;
    }

    place++;

    if (place[0] && place[0] == '-' && place[1] == '\0')
    { /* found "--" */
      ++optind;
      place = EMSG;
      return -1;
    }

    if (place[0] && place[0] == '-' && place[1])
    {
      /* long option */
      size_t namelen;
      int    i;

      place++;

      namelen = strcspn(place, "=");
      for (i = 0; longopts[i].name != NULL; i++)
      {
        if (strlen(longopts[i].name) == namelen
          && strncmp(place, longopts[i].name, namelen) == 0)
        {
          if (longopts[i].has_arg)
          {
            if (place[namelen] == '=')
              optarg = place + namelen + 1;
            else if (optind < argc - 1)
            {
              optind++;
              optarg = argv[optind];
            }
            else
            {
              if (optstring[0] == ':')
                return BADARG;
              if (opterr)
                fprintf(stderr,
                  "%s: option requires an argument -- %s\n",
                  argv[0], place);
              place = EMSG;
              optind++;
              return BADCH;
            }
          }
          else
          {
            optarg = NULL;
            if (place[namelen] != 0)
            {
              /* XXX error? */
            }
          }

          optind++;

          if (longindex)
            *longindex = i;

          place = EMSG;

          if (longopts[i].flag == NULL)
            return longopts[i].val;
          else
          {
            *longopts[i].flag = longopts[i].val;
            return 0;
          }
        }
      }

      if (opterr && optstring[0] != ':')
        fprintf(stderr,
          "%s: illegal option -- %s\n", argv[0], place);
      place = EMSG;
      optind++;
      return BADCH;
    }
  }

  /* short option */
  optopt = (int) *place++;

  oli = strchr(optstring, optopt);
  if (!oli)
  {
    if (!*place)
      ++optind;
    if (opterr && *optstring != ':')
      fprintf(stderr,
        "%s: illegal option -- %c\n", argv[0], optopt);
    return BADCH;
  }

  if (oli[1] != ':')
  { /* don't need argument */
    optarg = NULL;
    if (!*place)
      ++optind;
  }
  else
  { /* need an argument */
    if (*place) /* no white space */
      optarg = place;
    else if (argc <= ++optind)
    { /* no arg */
      place = EMSG;
      if (*optstring == ':')
        return BADARG;
      if (opterr)
        fprintf(stderr,
          "%s: option requires an argument -- %c\n",
          argv[0], optopt);
      return BADCH;
    }
    else
      /* white space */
      optarg = argv[optind];
    place = EMSG;
    ++optind;
  }
  return optopt;
}
<commit_msg>fix getopt_long compilation with VS 2017<commit_after>/*
 * getopt_long() -- long options parser
 *
 * Portions Copyright (c) 1987, 1993, 1994
 * The Regents of the University of California.  All rights reserved.
 *
 * Portions Copyright (c) 2003
 * PostgreSQL Global Development Group
 *
 * 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. Neither the name of the University 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 REGENTS 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 REGENTS 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 "getopt.h"

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

#define BADCH  '?'
#define BADARG ':'
#define EMSG   ""

int opterr = 1,   /* if error message should be printed */
  optind = 1,   /* index into parent argv vector */
  optopt,     /* character checked for validity */
  optreset;   /* reset getopt */
char  *optarg;    /* argument associated with option */

int
getopt_long(int argc, char *const argv[],
            const char *optstring,
            const struct option * longopts, int *longindex)
{
  static const char* place = EMSG; /* option letter processing */
  const char *oli;           /* option letter list index */

  if (!*place)
  { /* update scanning pointer */
    if (optind >= argc)
    {
      place = EMSG;
      return -1;
    }

    place = argv[optind];

    if (place[0] != '-')
    {
      place = EMSG;
      return -1;
    }

    place++;

    if (place[0] && place[0] == '-' && place[1] == '\0')
    { /* found "--" */
      ++optind;
      place = EMSG;
      return -1;
    }

    if (place[0] && place[0] == '-' && place[1])
    {
      /* long option */
      size_t namelen;
      int    i;

      place++;

      namelen = strcspn(place, "=");
      for (i = 0; longopts[i].name != NULL; i++)
      {
        if (strlen(longopts[i].name) == namelen
          && strncmp(place, longopts[i].name, namelen) == 0)
        {
          if (longopts[i].has_arg)
          {
            if (place[namelen] == '=')
              optarg = (char*)place + namelen + 1;
            else if (optind < argc - 1)
            {
              optind++;
              optarg = argv[optind];
            }
            else
            {
              if (optstring[0] == ':')
                return BADARG;
              if (opterr)
                fprintf(stderr,
                  "%s: option requires an argument -- %s\n",
                  argv[0], place);
              place = EMSG;
              optind++;
              return BADCH;
            }
          }
          else
          {
            optarg = NULL;
            if (place[namelen] != 0)
            {
              /* XXX error? */
            }
          }

          optind++;

          if (longindex)
            *longindex = i;

          place = EMSG;

          if (longopts[i].flag == NULL)
            return longopts[i].val;
          else
          {
            *longopts[i].flag = longopts[i].val;
            return 0;
          }
        }
      }

      if (opterr && optstring[0] != ':')
        fprintf(stderr,
          "%s: illegal option -- %s\n", argv[0], place);
      place = EMSG;
      optind++;
      return BADCH;
    }
  }

  /* short option */
  optopt = (int) *place++;

  oli = strchr(optstring, optopt);
  if (!oli)
  {
    if (!*place)
      ++optind;
    if (opterr && *optstring != ':')
      fprintf(stderr,
        "%s: illegal option -- %c\n", argv[0], optopt);
    return BADCH;
  }

  if (oli[1] != ':')
  { /* don't need argument */
    optarg = NULL;
    if (!*place)
      ++optind;
  }
  else
  { /* need an argument */
    if (*place) /* no white space */
      optarg = (char*)place;
    else if (argc <= ++optind)
    { /* no arg */
      place = EMSG;
      if (*optstring == ':')
        return BADARG;
      if (opterr)
        fprintf(stderr,
          "%s: option requires an argument -- %c\n",
          argv[0], optopt);
      return BADCH;
    }
    else
      /* white space */
      optarg = argv[optind];
    place = EMSG;
    ++optind;
  }
  return optopt;
}
<|endoftext|>


<commit_before>/**
 * @file
 *  Zenderer/Scripting/Lua.hpp - A wrapper around core Lua API interactions
 *  and embedding.
 *
 * @author      George Kudrayvtsev (halcyon)
 * @version     1.0
 * @copyright   Apache License v2.0
 *  Licensed under the Apache License, Version 2.0 (the "License").         \n
 *  You may not use this file except in compliance with the License.        \n
 *  You may obtain a copy of the License at:
 *  http://www.apache.org/licenses/LICENSE-2.0                              \n
 *  Unless required by applicable law or agreed to in writing, software     \n
 *  distributed under the License is distributed on an "AS IS" BASIS,       \n
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
 *  See the License for the specific language governing permissions and     \n
 *  limitations under the License.
 *
 * @addtogroup Scripting
 *  This module contains convenience functions and wrappers for embedding and
 *  communicating with Lua through the C API.
 *
 * @{
 **/

#ifndef ZENDERER__SCRIPTING__LUA_HPP
#define ZENDERER__SCRIPTING__LUA_HPP

#include "lua/lua.hpp"

#ifdef _WIN32
  #pragma comment(lib, "lua52.lib")
#endif

namespace zen
{

/// An abstraction layer over raw embedding of the Lua scripting environment.
namespace lua
{
    /// A shortcut for easily defining the `name -> loader` set.
    typedef std::map<string_t, lua_CFunction> luaLibs_t;

    /// Wrapper for the core Lua interpreter.
    class ZEN_API CLuaAPI : public CSubsystem
    {
    public:
        /**
         * Constructs a Lua interpreter instance.
         *  This will set up the configuration for the private Lua
         *  interpreter instance, storing the necessary libraries
         *  locally.
         *
         * @param   libraries   Libraries to use
         **/
        CLuaAPI(const luaLibs_t& libraries) :
            m_Libs(libraries), m_Lua(nullptr) {}

        /// Cleans up the interpreter instance.
        ~CLuaAPI()
        {
            this->Destroy();
        }

        /// Implicitly covert to `lua_State*` for `lua_` API calls.
        inline operator lua_State*() { return m_Lua; }

        /**
         * Loads the Lua interpreter with the given libraries.
         * @return  `true` if loaded successfully,
         *          `false` if already initialized.
         *
         * @see     IsInit()
         **/
        bool Init()
        {
            if(!m_init)
            {
                m_Lua = luaL_newstate();
                ZEN_ASSERT(m_Lua != nullptr);

                for(auto& i : m_Libs)
                {
                    luaL_requiref(m_Lua, i.first, i.second, 1);
                    lua_settop(m_Lua, 0);
                }

                return (m_init = true);
            }

            return false;
        }

        /// Cleans up the Lua interpreter instance.
        bool Destroy()
        {
            if(!m_init) return false;

            lua_close(m_Lua);
            m_Lua = nullptr;
            return true;
        }

        /**
         * Loads and executes a Lua script.
         *  This will execute the Lua script just as if you ran it
         *  from the command line using `lua filename`. Any function
         *  calls and other interactions can only be done after this
         *  has been run, but the setting of any variables must be
         *  done beforehand.
         *
         * @param   filename    Lua script path / filename
         *
         * @return  `true`  if the script ran without errors,
         *          `false` otherwise.
         *
         * @see     GetError()
         **/
        bool LoadFile(const string_t& filename)
        {
            return lua_loadfile(m_Lua, filename.c_str()) == 0 &&
                   lua_pcall(m_Lua, 0, LUA_MULTRET, 0) == 0;
        }

        /// Empties the Lua virtual stack
        inline bool ResetStack()
        {
            if(m_init) lua_settop(m_Lua, 0);
            return m_init;
        }

        /**
         * Retrieves the latest Lua error, if any.
         *
         * @return  The error string if it exists, a custom error
         *          if the interpreter has not been loaded, and
         *          a blank string if there is no error.
         *
         * @warning This should only be called if you are absolutely
         *          positive that the interpreter has generated an
         *          error, otherwise this may mess up the stack or
         *          conversion may fail.
         **/
        inline string_t GetError()
        {
            if(!m_init) return string_t("Lua interpreter not loaded");
            return string_t(lua_tostring(m_Lua, -1));
        }

    private:
        const luaLibs_t& m_Libraries;
        lua_State* m_Lua;
    };
}
}

#endif // ZENDERER__SCRIPTING__LUA_HPP

/** @} **/

/**
 * @class zen::lua::CLuaAPI
 *
 * @details
 *  This class provides a simple convenience wrapper around the `lua_State`
 *  variable required for the Lua intepreter. It automatically takes care
 *  of resource allocation and freeing of the interpreter instance.
 *  Scripting is merely a feature of the engine, and is not actually used
 *  in its core (yet). Thus, the file is not included by default in
 *  @ref Zenderer.hpp. If you wish to include it, be sure to add the
 *  appropriate linker commands to your compilation routine.
 *
 * @note    By default, the Visual Studio 11 library is linked when `_WIN32`
 *          is defined.
 *
 * @example Scripting
 *
 * @section usage       Lua Usage Examples
 * @subsection creation Instantiating a Lua wrapper
 *  This will create a Lua wrapper with some very barebones Lua libraries.
 *
 *  @code
 *  using namespace zen;
 *
 *  lua::luaLibs_t libs;
 *  libs["io"]  = lua_loadio;
 *  libs["base"]= lua_loadbase;
 *
 *  lua::CLua API(libs);
 *  @endcode
 *
 * @subsection obj Passing objects to Lua
 *  There comes a time where it's necessary to pass objects around to Lua,
 *  especially if Lua is referring back to a C function in your code. This
 *  will demonstrate a simple, flexible way to pass around the `this` pointer
 *  to the Lua interpreter, and back again.
 *
 *  Here is our example class.
 *  @code
 *  #include <iostream>
 *
 *  class Dummy
 *  {
 *      int m_f;
 *
 *  public:
 *      explicit Dummy(const int factor) : m_f(factor) {}
 *      inline int GetF() const
 *      {
 *          return m_f;
 *      }
 *
 *      inline void Talk()
 *      {
 *          std::cout << "Dummies can't talk!\n";
 *      }
 *  };
 *  @endcode
 *
 *  Here is our C function that will interact with the object. Let's assume
 *  that Lua gives us 2 numbers to add, and we return a value scaled with
 *  the `m_f` variable in the given object, and the 2 numbers added together.
 *
 *  @code
 *  int dummy_function(lua_State* Lua)
 *  {
 *      // Verify the proper amount of args.
 *      int argc = lua_gettop(Lua);
 *      if (argc < 3)
 *      {
 *          lua_pushstring(Lua, "Invalid argument count.");
 *          lua_pushnumber(Lua, 0);
 *          return 2;
 *      }
 *
 *      int a = lua_tonumber(Lua, 1);
 *      int b = lua_tonumber(Lua, 2);
 *      Dummy* pObject = static_cast<Dummy*>(lua_touserdata(Lua, 3));
 *
 *      lua_pushnumber(a * b * pObject->GetF());
 *      lua_pushnumber(a + b);
 *      return 2;
 *  }
 *  @endcode
 *
 *  Here is our Lua code, which just passes some arbitrary values to the
 *  C function (bound later).
 *
 *  @code{.lua}
 *  -- Example.lua
 *  local number1 = 55
 *  local number2 = 69
 *
 *  a, b = dummy_function()
 *  f, s = dummy_function(number1, number2, this)
 *
 *  print('Factors: ' .. a .. ', ' .. f)
 *  print('Sum: ' .. b .. ', ' .. s)
 *  @endcode
 *
 *  And finally, here is the host-side C++ code that will bind the Lua
 *  data appropriately.
 *
 *  @code
 *  #include "Zenderer/Core/Types.hpp"
 *  #include "Zenderer/Scripting/Lua.hpp"
 *
 *  using namespace zen;
 *
 *  luaLibs_t libs;
 *  libs["base"] = luaopen_base;
 *
 *  lua::CLuaAPI Lua(libs);
 *  Lua.Init();
 *
 *  Dummy Object(24);
 *
 *  lua_pushuserdata(Lua, static_cast<void*>(&Dummy));
 *  lua_setglobal(Lua, "this");
 *  lua_register(Lua, "dummy_function", dummy_function);
 *
 *  Lua.LoadFile("Sample.lua");
 *  @endcode
 *
 *  If all is well, the output of the program would be:
 *  @code{.txt}
 *  Invalid argument count., 91080
 *  0, 124
 *  @endcode
 **/
<commit_msg>Added Lua resources<commit_after>/**
 * @file
 *  Zenderer/Scripting/Lua.hpp - A wrapper around core Lua API interactions
 *  and embedding.
 *
 * @author      George Kudrayvtsev (halcyon)
 * @version     1.0
 * @copyright   Apache License v2.0
 *  Licensed under the Apache License, Version 2.0 (the "License").         \n
 *  You may not use this file except in compliance with the License.        \n
 *  You may obtain a copy of the License at:
 *  http://www.apache.org/licenses/LICENSE-2.0                              \n
 *  Unless required by applicable law or agreed to in writing, software     \n
 *  distributed under the License is distributed on an "AS IS" BASIS,       \n
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
 *  See the License for the specific language governing permissions and     \n
 *  limitations under the License.
 *
 * @addtogroup Scripting
 *  This module contains convenience functions and wrappers for embedding and
 *  communicating with Lua through the C API.
 *
 * @{
 **/

#ifndef ZENDERER__SCRIPTING__LUA_HPP
#define ZENDERER__SCRIPTING__LUA_HPP

#include "lua/lua.hpp"

#ifdef _WIN32
  #pragma comment(lib, "lua52.lib")
#endif

namespace zen
{

/// An abstraction layer over raw embedding of the Lua scripting environment.
namespace lua
{
    /// A shortcut for easily defining the `name -> loader` set.
    typedef std::map<string_t, lua_CFunction> luaLibs_t;

    /// Wrapper for the core Lua interpreter.
    class ZEN_API CLuaAPI : public CSubsystem
    {
    public:
        /**
         * Constructs a Lua interpreter instance.
         *  This will set up the configuration for the private Lua
         *  interpreter instance, storing the necessary libraries
         *  locally.
         *
         * @param   libraries   Libraries to use
         **/
        CLuaAPI(const luaLibs_t& libraries) :
            m_Libs(libraries), m_Lua(nullptr) {}

        /// Cleans up the interpreter instance.
        ~CLuaAPI()
        {
            this->Destroy();
        }

        /// Implicitly covert to `lua_State*` for `lua_` API calls.
        inline operator lua_State*() { return m_Lua; }

        /**
         * Loads the Lua interpreter with the given libraries.
         * @return  `true` if loaded successfully,
         *          `false` if already initialized.
         *
         * @see     IsInit()
         **/
        bool Init()
        {
            if(!m_init)
            {
                m_Lua = luaL_newstate();
                ZEN_ASSERT(m_Lua != nullptr);

                for(auto& i : m_Libs)
                {
                    luaL_requiref(m_Lua, i.first, i.second, 1);
                    lua_settop(m_Lua, 0);
                }

                return (m_init = true);
            }

            return false;
        }

        /// Cleans up the Lua interpreter instance.
        bool Destroy()
        {
            if(!m_init) return false;

            lua_close(m_Lua);
            m_Lua = nullptr;
            return true;
        }

        /**
         * Loads and executes a Lua script.
         *  This will execute the Lua script just as if you ran it
         *  from the command line using `lua filename`. Any function
         *  calls and other interactions can only be done after this
         *  has been run, but the setting of any variables must be
         *  done beforehand.
         *
         * @param   filename    Lua script path / filename
         *
         * @return  `true`  if the script ran without errors,
         *          `false` otherwise.
         *
         * @see     GetError()
         **/
        bool LoadFile(const string_t& filename)
        {
            return lua_loadfile(m_Lua, filename.c_str()) == 0 &&
                   lua_pcall(m_Lua, 0, LUA_MULTRET, 0) == 0;
        }

        /// Empties the Lua virtual stack
        inline bool ResetStack()
        {
            if(m_init) lua_settop(m_Lua, 0);
            return m_init;
        }

        /**
         * Retrieves the latest Lua error, if any.
         *
         * @return  The error string if it exists, a custom error
         *          if the interpreter has not been loaded, and
         *          a blank string if there is no error.
         *
         * @warning This should only be called if you are absolutely
         *          positive that the interpreter has generated an
         *          error, otherwise this may mess up the stack or
         *          conversion may fail.
         **/
        inline string_t GetError()
        {
            if(!m_init) return string_t("Lua interpreter not loaded");
            return string_t(lua_tostring(m_Lua, -1));
        }

    private:
        const luaLibs_t& m_Libraries;
        lua_State* m_Lua;
    };
}
}

#endif // ZENDERER__SCRIPTING__LUA_HPP

/** @} **/

/**
 * @class zen::lua::CLuaAPI
 *
 * @details
 *  This class provides a simple convenience wrapper around the `lua_State`
 *  variable required for the Lua intepreter. It automatically takes care
 *  of resource allocation and freeing of the interpreter instance.
 *  Scripting is merely a feature of the engine, and is not actually used
 *  in its core (yet). Thus, the file is not included by default in
 *  @ref Zenderer.hpp. If you wish to include it, be sure to add the
 *  appropriate linker commands to your compilation routine.
 *
 * @note    By default, the Visual Studio 11 library is linked when `_WIN32`
 *          is defined.
 *
 * @see     http://www.lua.org/manual/5.2/manual.html
 * @see     http://blog.acamara.es/2012/08/19/calling-c-functions-from-lua-5-2/
 * @see     http://csl.name/lua/
 *
 * @example Scripting
 *
 * @section usage       Lua Usage Examples
 * @subsection creation Instantiating a Lua wrapper
 *  This will create a Lua wrapper with some very barebones Lua libraries.
 *
 *  @code
 *  using namespace zen;
 *
 *  lua::luaLibs_t libs;
 *  libs["io"]  = lua_loadio;
 *  libs["base"]= lua_loadbase;
 *
 *  lua::CLua API(libs);
 *  @endcode
 *
 * @subsection obj Passing objects to Lua
 *  There comes a time where it's necessary to pass objects around to Lua,
 *  especially if Lua is referring back to a C function in your code. This
 *  will demonstrate a simple, flexible way to pass around the `this` pointer
 *  to the Lua interpreter, and back again.
 *
 *  Here is our example class.
 *  @code
 *  #include <iostream>
 *
 *  class Dummy
 *  {
 *      int m_f;
 *
 *  public:
 *      explicit Dummy(const int factor) : m_f(factor) {}
 *      inline int GetF() const
 *      {
 *          return m_f;
 *      }
 *
 *      inline void Talk()
 *      {
 *          std::cout << "Dummies can't talk!\n";
 *      }
 *  };
 *  @endcode
 *
 *  Here is our C function that will interact with the object. Let's assume
 *  that Lua gives us 2 numbers to add, and we return a value scaled with
 *  the `m_f` variable in the given object, and the 2 numbers added together.
 *
 *  @code
 *  int dummy_function(lua_State* Lua)
 *  {
 *      // Verify the proper amount of args.
 *      int argc = lua_gettop(Lua);
 *      if (argc < 3)
 *      {
 *          lua_pushstring(Lua, "Invalid argument count.");
 *          lua_pushnumber(Lua, 0);
 *          return 2;
 *      }
 *
 *      int a = lua_tonumber(Lua, 1);
 *      int b = lua_tonumber(Lua, 2);
 *      Dummy* pObject = static_cast<Dummy*>(lua_touserdata(Lua, 3));
 *
 *      lua_pushnumber(a * b * pObject->GetF());
 *      lua_pushnumber(a + b);
 *      return 2;
 *  }
 *  @endcode
 *
 *  Here is our Lua code, which just passes some arbitrary values to the
 *  C function (bound later).
 *
 *  @code{.lua}
 *  -- Example.lua
 *  local number1 = 55
 *  local number2 = 69
 *
 *  a, b = dummy_function()
 *  f, s = dummy_function(number1, number2, this)
 *
 *  print('Factors: ' .. a .. ', ' .. f)
 *  print('Sum: ' .. b .. ', ' .. s)
 *  @endcode
 *
 *  And finally, here is the host-side C++ code that will bind the Lua
 *  data appropriately.
 *
 *  @code
 *  #include "Zenderer/Core/Types.hpp"
 *  #include "Zenderer/Scripting/Lua.hpp"
 *
 *  using namespace zen;
 *
 *  luaLibs_t libs;
 *  libs["base"] = luaopen_base;
 *
 *  lua::CLuaAPI Lua(libs);
 *  Lua.Init();
 *
 *  Dummy Object(24);
 *
 *  lua_pushuserdata(Lua, static_cast<void*>(&Dummy));
 *  lua_setglobal(Lua, "this");
 *  lua_register(Lua, "dummy_function", dummy_function);
 *
 *  Lua.LoadFile("Sample.lua");
 *  @endcode
 *
 *  If all is well, the output of the program would be:
 *  @code{.txt}
 *  Invalid argument count., 91080
 *  0, 124
 *  @endcode
 **/
<|endoftext|>


<commit_before>#include <string>

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <esapp/segmenter.hpp>

namespace py = pybind11;

PYBIND11_PLUGIN(esapp_python) {
    py::module m("esapp_python");
    py::class_<esapp::segmenter>(m, "Segmenter")
        .def(py::init<double>())
        .def("fit", [](esapp::segmenter &seg, std::string const &s) {
            seg.fit(s.begin(), s.end());
        })
        .def("optimize", &esapp::segmenter::optimize)
        .def("segment", [](esapp::segmenter const &seg, std::string const &s) {
            return seg.segment(s.begin(), s.end());
        });

    return m.ptr();
}
<commit_msg>:zap: Refine python wrapper<commit_after>#include <string>
#include <utility>

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <esapp/segmenter.hpp>

namespace py = pybind11;

class py_list_inserter {
 public:
    explicit py_list_inserter(py::list &list)  // NOLINT(runtime/references)
        : list_(list) { /* do nothing */ }

    py_list_inserter &operator=(std::string &&s) {
        list_.append(std::move(s));
        return *this;
    }

    py_list_inserter &operator*()       { return *this; }
    py_list_inserter &operator++()      { return *this; }
    py_list_inserter &operator++(int)   { return *this; }

 private:
    py::list &list_;
};

PYBIND11_PLUGIN(esapp_python) {
    py::module m("esapp_python");
    py::class_<esapp::segmenter>(m, "Segmenter")
        .def(py::init<double>())
        .def("fit", [](esapp::segmenter &seg, std::string const &s) {
            seg.fit(s.begin(), s.end());
        })
        .def("optimize", &esapp::segmenter::optimize)
        .def("segment", [](esapp::segmenter const &seg, std::string const &s) {
            py::list list;
            seg.segment(s.begin(), s.end(), py_list_inserter(list));
            return list;
        });

    return m.ptr();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

//Get the implementations
#include "etl/impl/convmtx2.hpp"

namespace etl {

/*!
 * \brief Convmtx configurable expression, in two dimensions
 */
template <typename T, std::size_t K1, std::size_t K2, typename Impl>
struct basic_convmtx2_expr : impl_expr<basic_convmtx2_expr<T, K1, K2, Impl>> {
    static_assert(K1 > 0, "K1 must be greater than 0");
    static_assert(K2 > 0, "K2 must be greater than 0");

    using this_type  = basic_convmtx2_expr<T, K1, K2, Impl>; ///< The type of this expression
    using value_type = T;                                    ///< The value type

    /*!
     * \brief The result type for given sub types
     * \tparam A The sub expression type
     */
    template <typename A>
    using result_type = detail::expr_result_t<this_type, A>;

    /*!
     * \brief Apply the expression
     * \param a The sub expression
     * \param c The expression where to store the results
     */
    template <typename A, typename C>
    static void apply(A&& a, C&& c) {
        static_assert(all_etl_expr<A, C>::value, "convmtx2 only supported for ETL expressions");
        static_assert(decay_traits<A>::dimensions() == 2 && decay_traits<C>::dimensions() == 2, "convmtx2 needs 2D matrices");

        Impl::template apply<K1, K2>(
            make_temporary(std::forward<A>(a)),
            std::forward<C>(c));
    }

    /*!
     * \brief Returns a textual representation of the operation
     * \return a textual representation of the operation
     */
    static std::string desc() noexcept {
        return "convmtx2";
    }

    /*!
     * \brief Returns the DDth dimension of the expression
     * \tparam A The sub expression type
     * \tparam DD The dimension to get
     * \return the DDth dimension of the expression
     */
    template <typename A, std::size_t DD>
    static constexpr std::size_t dim() {
        return DD == 0 ? ((decay_traits<A>::template dim<0>() + K1 - 1) * (decay_traits<A>::template dim<1>() + K2 - 1))
                       : K1 * K2;
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param a The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    template <typename A>
    static std::size_t dim(const A& a, std::size_t d) {
        if (d == 0) {
            return (etl::dim<0>(a) + K1 - 1) * (etl::dim<1>(a) + K2 - 1);
        } else {
            return K1 * K2;
        }
    }

    /*!
     * \brief Returns the size of the expression
     * \param a The sub expression
     * \return the size of the expression
     */
    template <typename A>
    static std::size_t size(const A& a) {
        return (K1 * K2) * ((etl::dim<0>(a) + K1 - 1) * (etl::dim<1>(a) + K2 - 1));
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    template <typename A>
    static constexpr std::size_t size() {
        return this_type::template dim<A, 0>() * this_type::template dim<A, 1>();
    }

    /*!
     * \brief Returns the storage order of the expression.
     * \return the storage order of the expression
     */
    template <typename A>
    static constexpr etl::order order() {
        return etl::order::RowMajor;
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr std::size_t dimensions() {
        return 2;
    }
};

/*!
 * \brief Defaullt convmtx 2d expression
 */
template <typename T, std::size_t K1, std::size_t K2>
using direct_convmtx2_expr = basic_convmtx2_expr<T, K1, K2, detail::convmtx2_direct>;

} //end of namespace etl
<commit_msg>Add missing field<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

//Get the implementations
#include "etl/impl/convmtx2.hpp"

namespace etl {

/*!
 * \brief Convmtx configurable expression, in two dimensions
 */
template <typename T, std::size_t K1, std::size_t K2, typename Impl>
struct basic_convmtx2_expr : impl_expr<basic_convmtx2_expr<T, K1, K2, Impl>> {
    static_assert(K1 > 0, "K1 must be greater than 0");
    static_assert(K2 > 0, "K2 must be greater than 0");

    using this_type  = basic_convmtx2_expr<T, K1, K2, Impl>; ///< The type of this expression
    using value_type = T;                                    ///< The value type

    static constexpr const bool is_gpu = false; ///< Indicates if the expression runs on GPU

    /*!
     * \brief The result type for given sub types
     * \tparam A The sub expression type
     */
    template <typename A>
    using result_type = detail::expr_result_t<this_type, A>;

    /*!
     * \brief Apply the expression
     * \param a The sub expression
     * \param c The expression where to store the results
     */
    template <typename A, typename C>
    static void apply(A&& a, C&& c) {
        static_assert(all_etl_expr<A, C>::value, "convmtx2 only supported for ETL expressions");
        static_assert(decay_traits<A>::dimensions() == 2 && decay_traits<C>::dimensions() == 2, "convmtx2 needs 2D matrices");

        Impl::template apply<K1, K2>(
            make_temporary(std::forward<A>(a)),
            std::forward<C>(c));
    }

    /*!
     * \brief Returns a textual representation of the operation
     * \return a textual representation of the operation
     */
    static std::string desc() noexcept {
        return "convmtx2";
    }

    /*!
     * \brief Returns the DDth dimension of the expression
     * \tparam A The sub expression type
     * \tparam DD The dimension to get
     * \return the DDth dimension of the expression
     */
    template <typename A, std::size_t DD>
    static constexpr std::size_t dim() {
        return DD == 0 ? ((decay_traits<A>::template dim<0>() + K1 - 1) * (decay_traits<A>::template dim<1>() + K2 - 1))
                       : K1 * K2;
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param a The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    template <typename A>
    static std::size_t dim(const A& a, std::size_t d) {
        if (d == 0) {
            return (etl::dim<0>(a) + K1 - 1) * (etl::dim<1>(a) + K2 - 1);
        } else {
            return K1 * K2;
        }
    }

    /*!
     * \brief Returns the size of the expression
     * \param a The sub expression
     * \return the size of the expression
     */
    template <typename A>
    static std::size_t size(const A& a) {
        return (K1 * K2) * ((etl::dim<0>(a) + K1 - 1) * (etl::dim<1>(a) + K2 - 1));
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    template <typename A>
    static constexpr std::size_t size() {
        return this_type::template dim<A, 0>() * this_type::template dim<A, 1>();
    }

    /*!
     * \brief Returns the storage order of the expression.
     * \return the storage order of the expression
     */
    template <typename A>
    static constexpr etl::order order() {
        return etl::order::RowMajor;
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr std::size_t dimensions() {
        return 2;
    }
};

/*!
 * \brief Defaullt convmtx 2d expression
 */
template <typename T, std::size_t K1, std::size_t K2>
using direct_convmtx2_expr = basic_convmtx2_expr<T, K1, K2, detail::convmtx2_direct>;

} //end of namespace etl
<|endoftext|>