Set-up of SSHD for Mac OS X 10.7.2

I like to log-in remotely, but sshd was disabled by default on Mac’s boot. I googled around and found: “Apple Icon -> System Preferences -> Sharing (part of Internet&Wireless”, and there I have to enable “Remote Login”.

This procedure was not successfully in my case!

I tried it manually: $ sudo /usr/sbin/sshd

I got the message:
Could not load host key: /etc/ssh_host_rsa_key
Could not load host key: /etc/ssh_host_dsa_key

You can start sshd manually by: $ /usr/libexec/sshd-keygen-wrapper -i
which starts by taking care of creating the necessary keys needed for encrypting the connections if they don’t exist and subsequently start the sshd daemon.

Posted in Mac OS X | Tagged , , , , | Leave a comment

boost::serialization Serializes Base Class Members over Methods (setter/getter reference)

When your base class has no serialization functionalities but a method for reference access then you can use this reference for your boost::serialization, e.g. when thousands of classes are generated and you do not like to have serialization facilities for all classes to avoid code blowing and thereupon and huge executable.

A code snippet follows, you can combine it with previous posted code (ref1, ref2). Of course, the reference access does not return a const-reference.

class FileTypeBase {
private:
  std::string _name;
public:
  FileTypeBase(std::string name) : _name(name) {}
  std::string & name() {
    return _name;
  }
};

class FileType : public FileTypeBase {
public:
  FileType() : FileTypeBase("FileType uses FileTypeBase") {}

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    using boost::serialization::make_nvp;
    ar & make_nvp("name", name());
  }
};
Posted in Boost, C/C++, Programming | Leave a comment

boost::serialization & boost::variant + arbitrary datatypes

What if you have a class specification with one or more associations to other classes, these are not PODs (plain-old datatypes), and you like to serialize them? I tried to implement this with boost::any, but it wasn’t successfully. Fact is boost::any is a template-based approach to do type checking during compile-time, and not during run-time. This makes it really hard – maybe impossible – to use boost::serialize for serialization/deserialization of user defined types (ref).

Nevertheless, it was necessary to have a mechanism for serialization of arbitrary user defined datatypes, e.g. a class specifications with several attributes and to add them to one external class.

boost::variant can help.

/* Christian Benjamin Ries
 * www.christianbenjaminries.de
 * February 2012
 */
// C++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

// Boost
#include <boost/variant.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/variant.hpp>
#include <boost/serialization/scoped_ptr.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/nvp.hpp>

class FileType {
public:
  std::string name;
  FileType() : name("FileType") {}

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
  ar & BOOST_SERIALIZATION_NVP(name);
}
};

class Data {
public:
  std::string name;
  std::vector<std::string> values;

  boost::variant<int, std::string, float> v1;
  boost::variant<int, std::string, float> v2;
  boost::variant<int, std::string, float> v3;
  boost::variant<FileType> v4;

  Data() {
    v1 = 10; v2 = "C.B.Ries"; v3 = 102.12f;
    boost::get<FileType>(&v4)->name = "FileType Test";
  }

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & BOOST_SERIALIZATION_NVP(name);
    ar & BOOST_SERIALIZATION_NVP(values);
    ar & BOOST_SERIALIZATION_NVP(v1);
    ar & BOOST_SERIALIZATION_NVP(v2);
    ar & BOOST_SERIALIZATION_NVP(v3);
    ar & BOOST_SERIALIZATION_NVP(v4);
  }
};

BOOST_CLASS_EXPORT(Data)

void save() {
  boost::shared_ptr<Data> myDataObject(new Data());
  myDataObject->name = "Christian Benjamin Ries";
  myDataObject->values.push_back("Hello");
  myDataObject->values.push_back("World");

  std::ofstream ofs("myDataObject.xml");
  boost::archive::xml_oarchive oa(ofs);
  oa << BOOST_SERIALIZATION_NVP(myDataObject);
  ofs.close();
}

void load() {
  std::ifstream ifs("myDataObject.xml");
  boost::archive::xml_iarchive ia(ifs);
  boost::shared_ptr<Data> anotherName;
  ia >> BOOST_SERIALIZATION_NVP(anotherName);
  ifs.close();
}

int main(int argc, char **argv) {
  save(); load();
  return 0;
}

The XML file contains:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="9">
  <myDataObject class_id="0" tracking_level="0" version="1">
    <px class_id="1" tracking_level="1" version="0" object_id="_0">
      <name>Christian Benjamin Ries</name>
      <values class_id="2" tracking_level="0" version="0">
        <count>2</count>
        <item_version>0</item_version>
        <item>Hello</item>
        <item>World</item>
      </values>
      <v1 class_id="3" tracking_level="0" version="0">
        <which>0</which>
        <value>10</value>
      </v1>
      <v2>
        <which>1</which>
        <value>C.B.Ries</value>
      </v2>
      <v3>
        <which>2</which>
        <value>102.12</value>
      </v3>
      <v4 class_id="4" tracking_level="0" version="0">
        <which>0</which>
        <value class_id="5" tracking_level="0" version="0">
          <name>FileType Test</name>
        </value>
      </v4>
    </px>
  </myDataObject>
Posted in Boost, C/C++, Programming | Leave a comment

Conway’s Game of Life “42″, OpenGL + Qt

Next weekend (11st February) I will be on a codretreat event in Bielefeld. It is planned to “hack” a little bit around with Conway’s Game of Life. For this purpose I implemented a small engine to visualize my approaches with OpenGL and Qt.

You can find a nice video of my first result on Youtube, enjoy :-)

Conway’s Game of Life “42″, OpenGL + Qt

Posted in C/C++, OpenGL, Programming, Qt / QML, Simulation | Leave a comment

XML Serialization with Boost (tested with version 1.48)

It was hard to get a working sample for boost::serialization. There are a lot of examples around how you can do this with plain text as output format. But my wish was it to have XML output.

It is important to add the library “boost_serialization” to the linking process. The serialization library of Boost is not only header based! I compiled the listing at the end of this post with:

g++ -std=c++0x -o boostArchive boostArchive.cpp \
   -I/usr/local/include -L/usr/local/lib/ -lboost_serialization

This example is creating a XML (“myDataObject.xml”) and will load it afterwards. The format of the XML file is formatted by Boost and has the following format:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="9">
  <myDataObject class_id="0" tracking_level="0" version="1">
    <px class_id="1" tracking_level="1" version="0" object_id="_0">
      <Data class_id="2" tracking_level="1" version="0" object_id="_1">
        <name>Christian Benjamin Ries</name>
        <id>100</id>
        <pi>3.1400001</pi>
        <values class_id="3" tracking_level="0" version="0">
          <count>2</count>
          <item_version>0</item_version>
          <item>Hello</item>
          <item>World</item>
        </values>
      </Data>
      <city>Berlin</city>
    </px>
  </myDataObject>

This XML dialect has the format of our classes in the C++ listing below.

/* Christian Benjamin Ries
 * www.christianbenjaminries.de
 * February 2012
 */
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

// Boost
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/scoped_ptr.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/nvp.hpp>

class Data {
public:
  std::string name; int id;
  float pi; std::vector<std::string> values;

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    // You can store attributes with this macro:
    ar & BOOST_SERIALIZATION_NVP(name);
    ar & BOOST_SERIALIZATION_NVP(id);
    ar & BOOST_SERIALIZATION_NVP(pi);

    // You can store attributes as well with a Name-Value-Pair (NVP):
    // #include
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // ar & make_nvp("name", name);
    // ar & make_nvp("id", id);
    // ar & make_nvp("pi", pi);

    // Following for-loop will produce following without a hierarchy:
    // Hello
    // World
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //for(auto vIt : values) {
    //    ar & BOOST_SERIALIZATION_NVP(vIt);
    //}

    // A better solution is (which will create a hierarchy):
    ar & BOOST_SERIALIZATION_NVP(values);
  }
};

class MoreData : public Data {
public:
  std::string city;

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    using boost::serialization::make_nvp;

    // Following line does not work, runtime error: "Invalid XML tag name"
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //ar & BOOST_SERIALIZATION_NVP(boost::serialization::base_object(*this));
    //
    // It is necessary to define a name, here it is "Data":
    ar & make_nvp("Data", boost::serialization::base_object<Data>(*this));

    ar & BOOST_SERIALIZATION_NVP(city);
  }
};

// This is not working during my tests!
// An export is necessary to automatically create parent classes
// when you like to deserialize base classes with all available
// specializations. On my tests, I got a segmentation fault.
BOOST_CLASS_EXPORT(Data)
BOOST_CLASS_EXPORT(MoreData)

void save() {
  boost::shared_ptr<MoreData> myDataObject(new MoreData());
  myDataObject->city = "Berlin";
  myDataObject->name = "Christian Benjamin Ries";
  myDataObject->id = 100;
  myDataObject->pi = 3.14;
  myDataObject->values.push_back("Hello");
  myDataObject->values.push_back("World");

  std::ofstream ofs("myDataObject.xml");
  boost::archive::xml_oarchive oa(ofs);
  oa << BOOST_SERIALIZATION_NVP(myDataObject);
  ofs.close();
}

void load() {
  std::ifstream ifs("myDataObject.xml");
  boost::archive::xml_iarchive ia(ifs);
  boost::shared_ptr anotherName;
  ia >> BOOST_SERIALIZATION_NVP(anotherName);
  ifs.close();

  std::cout << "Name: " << anotherName->name << std::endl;
  std::cout << "City: " << anotherName->city << std::endl;
}

int main(int argc, char **argv) {
  save(); load();
  return 0;
}

More information is available: boost::serialization documentation

Posted in Boost, C/C++, Programming | Leave a comment

I like: operator {{datatype}}()

Just a code dump, last 5 minute hack:

/* Christian Benjamin Ries, February 2012
 * www.christianbenjaminries.de
 */
// C++
#include <iostream>
#include <string>

typedef std::string String;
typedef int        Integer;

class Ret {
public:
  virtual operator String()  { return "This is a string."; }
  virtual operator Integer() { return 10; }
};

class RetSpecial : public Ret {
public:
  operator String()          { return "This is a special string."; }
};

class RetProxy {
public:
  RetSpecial open() { return RetSpecial(); }
};

int main(int argc, char **argv) {
  RetProxy rp;
  std::cout << "Integer: " << (Integer) rp.open() << std::endl;
  std::cout << "String:  " << (String) rp.open() << std::endl;
}

Outputs:

Integer: 10
String:  This is a special string.
Posted in C/C++, Programming | Leave a comment

Modeling Sets of Data with Different Datatypes

The figure shows a simple model of datafields with optionally attributes, i.e. it can describe something like <pi iterations=”100″>3.14</pi>. Here, <pi> is a datafield and iterations=”" is an attribute. The value of pi is 3.14 but it is possible to add data with arbitrary types.

Small model of a datafield with optionally attributes.

You like to use Datafield::data with less of effort, as a result you like to have only one function to access this datafield, i.e. Datafield::open() : Filetype is defined for this purpose.

With the help of C++ method overloading, we can define a helper structure to weave the logically parts for our access invocations automatically during runtime. The following listing shows how we can access our Datafield::data – with arbitrary datatypes – only with one method. In this example, a fake file description is implemented and a simple std::string is used for demonstration.

/* Christian Benjamin Ries, January 2012
 * www.christianbenjaminries.de
 */
// C++
#include <iostream>

// C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct FileInfo {
  int bytes;
  char *data;
} FileInfo;

typedef FileInfo*   File;
typedef std::string String;

struct Filetype {
  operator File() {
    FileInfo *d = new FileInfo();
    d->data = (char*)malloc(sizeof(char) * 24);
    snprintf(d->data, 24, "Hello World!");
    d->bytes = strlen(d->data);
    return d;
  }

  operator String()    {
    return "Hello World!";
  }
};

Filetype open() { return Filetype(); }

int main(int argc, char **argv) {
  File dt1 = open();
  String dt2 = open();

  std::cout << "dt1: " << dt1->bytes << " - " << dt1->data << std::endl;
  std::cout << "dt2: " << dt2 << std::endl;
}
Posted in C/C++, Modeling, Programming, UML 2.x | Leave a comment

BOINC Multi-Thread Sample with C++11 Support

Recently I played a little bit around with C++11′s thread features. I just modified BOINC’s multi thread sample. In my opinion, C++11 enables me to create threads faster and more readable for Linux and Windows (I have no idea about Mac support). Attached you will find the source:

// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC.  If not, see <http://www.gnu.org/licenses/>.

//
// Contributor: Christian Benjamin Ries (mail@christianbenjaminries.de)
// This file is based on BOINC's basic thread example
// in samples/multi_thread. Here, this version is changed for
// the use of C++11 threads support.
// On some systems you have to enable C++0x support:
//   g++ -std=c++0x ...
//

// Example multi-thread BOINC application with the use of C++11 threads.
// This app defines its own classes (Worker, Threads) for managing C++11 threads.
// You can also use libraries such as OpenMP.
// Just make sure you call boinc_init_parallel().
//
// This app does 64 "units" of computation, where each units is about 1 GFLOP.
// It divides this among N "worker" threads.
// N is passed in the command line, and defaults to 1.
//
// Doesn't do checkpointing.

// C
#include <stdio.h>

// C++
#include <map>
#include <thread>
#include <sstream>
#include <iostream>

// Windows
#ifdef _WIN32
#include "boinc_win.h"
#endif

// BOINC
#include "util.h"
#include "str_util.h"
#include "boinc_api.h"

#define DEFAULT_NTHREADS 4
#define TOTAL_UNITS 16

class Worker {
private:
  int _unitsPerThread;
  int _unitsDone;
  bool _done;
public:
  Worker(int upt) : _unitsPerThread(upt), _done(false) {}
  int unitsDone() const { return _unitsDone; }
  bool done() const { return _done; }

  void operator()() {
    for (int i=0; i<_unitsPerThread; i++) {
      double x = do_a_giga_flop(i);
      _unitsDone++;

      char buf[256] {'\0'};
      std::stringstream s;
      s << boinc_msg_prefix(buf, sizeof(buf))
        << " thread " << std::this_thread::get_id()
        << " finished " << i << ": " << x << std::endl;
      std::cerr << s.str();
    }
    _done = true;
  }

  // do a billion floating-point ops
  // (note: I needed to add an arg to this;
  // otherwise the MS C++ compiler optimizes away
  // all but the first call to it!)
  //
  static double do_a_giga_flop(int foo) {
    double x = 3.14159*foo;
    int i;
    for (i=0; i<500000000; i++) {
      x += 5.12313123;
      x *= 0.5398394834;
    }
    return x;
  }
};

class Threads
  : public std::map<std::thread*, Worker*>
{
public:
  bool all_done() {
    for( auto it : *this) {
      if(!it.second->done())
        return false;
    }
    return true;
  }

  int units_done() {
    int count = 0;
    for(auto it : *this) {
      count += it.second->unitsDone();
    }
    return count;
  }

  void join() {
    for(auto it : *this) {
      it.first->join();
    }
  }
};

int main(int argc, char** argv) {
  auto i(0), nthreads(DEFAULT_NTHREADS);
  auto start_time = dtime();
  char buf[256] = {'\0'};

  BOINC_OPTIONS options;
  boinc_options_defaults(options);
  options.multi_thread = true;
  boinc_init_options(&options);

  for (i=1; i<argc; i++) {
    if (!strcmp(argv[i], "--nthreads")) {
      nthreads = atoi(argv[++i]);
    } else {
      fprintf(stderr, "%s unrecognized arg: %s\n",
        boinc_msg_prefix(buf, sizeof(buf)), argv[i]
      );
    }
  }

  auto units_per_thread = TOTAL_UNITS / nthreads;

  Threads threads;
  for (i=0; i<nthreads; i++) {
    auto w = Worker(units_per_thread);
    auto t = new std::thread(std::ref(w));
    threads[t] = &w;
  }

  while (1) {
    double f = threads.units_done()/((double)TOTAL_UNITS);
    boinc_fraction_done(f);
    if(threads.all_done()) break;
    boinc_sleep(1.0);
  }

  threads.join();

  auto elapsed_time = dtime() - start_time;
  std::stringstream s;
  s << boinc_msg_prefix(buf, sizeof(buf))
    << " All done. Used " << nthreads << " threads."
    << " Elapsed time " << elapsed_time << std::endl;
  std::cerr << s.str();

  boinc_finish(0);
}

#ifdef _WIN32
int WINAPI WinMain(
  HINSTANCE hInst,
  HINSTANCE hPrevInst,
  LPSTR Args,
  int WinMode
) {
  LPSTR command_line;
  char* argv[100];
  int argc;

  command_line = GetCommandLine();
  argc = parse_command_line( command_line, argv );
  return main(argc, argv);
}
#endif
Posted in BOINC, C/C++, Programming, Public Resource Computing, Unix/Linux, Windows | Leave a comment

Few Steps to g++ 4.6 on Ubuntu Systems

Just enter following commands and you will have gcc/g++ in version 4.6. Then it is possible to use some brilliant new C++11 features and dialect elements.

# This will add a new repository to your system:
# https://launchpad.net/~ubuntu-toolchain-r/+archive/test
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
# Check for available gcc/g++ versions
sudo apt-cache search "g\+\+"
sudo apt-get install gcc-4.6 g++-4.6
which  g++
ls -lh /usr/bin/g++*
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 \
                         --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --config gcc
g++ --version

You should have gcc/g++’s version 4.6 installed:

cr@visualgrid-4:~$ g++ --version
g++ (Ubuntu/Linaro 4.6.2-10ubuntu1~10.04.2) 4.6.2
Posted in Bashing, C/C++, Configurations, Programming, Unix/Linux | 2 Comments

15 Minutes “hack” of a Statemachine

In the moment I try to find out how a good code generation for state machine have to look like. I dumped a absolutely easiest method in one text-editor. You can search around the web and you will find a lot of several approaches. Most of them are not compile-time type safe. BUT, do I need this? Tomorrow, I will check how I can use a Domain-specific language (DSL) to generate code like this one:

/*
 * Christian Benjamin Ries, January 2012
 * mail@christianbenjaminries.de
 */
// C++
#include <iostream>

#define STATE_START 0
#define STATE_STOP 1

#define EVENT_START 0
#define EVENT_STOP 1

class State {
public:
  virtual ~State() {}
};

class StateStart : public State {
public:
  StateStart() {
    std::cout << "Entering StateStart..." << std::endl;
  }
  ~StateStart() {
    std::cout << "Leaving StateStart..." << std::endl;
  }
};

class StateStop : public State {
public:
  StateStop() {
    std::cout << "Entering StateStop..." << std::endl;
  }
  ~StateStop() {
    std::cout << "Leaving StateStop..." << std::endl;
  }
};

/**
 * @brief Base class for one Statemachine.
 */
class Statechart {
private:
  virtual bool check_event(int eventId) = 0;
protected:
  static int currentStateIdentifier;
  static State *currentState;
public:
  virtual ~Statechart() {}
  virtual void process_event(int eventId) = 0;
};

/**
 * @brief ...
 */
class StatechartClient : public Statechart {
private:
  bool check_event(int eventId) {
    switch(currentStateIdentifier) {
      case STATE_START: {
        if(eventId == EVENT_STOP) return true;
        // ...
      } break;
      case STATE_STOP: {
        if(eventId == EVENT_START) return true;
        // ...
      } break;
      default: return false;
    }
  }

public:
  StatechartClient() : Statechart() {
    // empty
  }

  ~StatechartClient() {
    if(currentState) delete currentState;
  }

  void process_event(int eventId) {
    if(check_event(eventId)) {
      delete currentState;
      currentState = NULL;

      switch(eventId) {
        case STATE_START: currentState = new StateStart();
        case STATE_STOP:  currentState = new StateStop();
      }
    }
  }
};

// Defines begin of a state machine.
int Statechart::currentStateIdentifier = STATE_START;
State *Statechart::currentState = new StateStart();

int main( int argc, char **argv ) {
  StatechartClient sc;
  sc.process_event(EVENT_STOP);
  sc.process_event(EVENT_START);
  sc.process_event(EVENT_STOP);
}
Posted in C/C++, DSL/DSML, Modeling, Programming | Leave a comment

Redirect stdout & stderr within C++ and Streams

During my current work it is necessary to redirect output messages, because of the fact that I can not verbose them. Unfortunately they are implemented in one underlying library, wonder why?! Followed is a small snippet of an example to redirect default output streams within C++’s STL streams:

// Redirect stdout to one std::string puffer.
std::streambuf *msgOutBuffer, *msgOutBufferBackup;
std::stringstream smessageOutput;
msgOutBufferBackup = std::cout.rdbuf();
msgOutBuffer = smessageOutput.rdbuf();
std::cout.rdbuf(msgOutBuffer);

// Redirect stderr to one std::string puffer.
std::streambuf *msgErrBuffer, *msgErrBufferBackup;
std::stringstream smessageError;
msgErrBufferBackup = std::cerr.rdbuf();
msgErrBuffer = smessageError.rdbuf();
std::cerr.rdbuf(msgErrBuffer);

// Redirected is done!

std::cout << "One standard message!";
std::cerr << "One error message!";

// Set to previous channels!
std::cout.rdbuf(msgOutBufferBackup);
std::cerr.rdbuf(msgErrBufferBackup);
// Yeah!
Posted in C/C++, Programming | Leave a comment

Dynamic 1-dim and 2-dim Arrays in C

Recently one of my colleagues asked me how 1-dim and 2-dim arrays can be created in a dynamically manner. My results are followed, first listing is the 1-dim implementation, and second listing shows the 2-dim magic stuff.

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

#define WORDS 10
#define WORDLEN 20

int main( int argc, char **argv ) {
  int i = 0;
  char **str = NULL;

  str = (char *) malloc( sizeof(char*) * WORDS );
  if(str == NULL) {
    perror("malloc failed");
    return 1;
  }

  for( i=0; i<WORDS; i++ ) {
    str[i] = (char*) malloc( sizeof(char) * WORDLEN );
    if(str[i] == NULL) {
      perror("malloc failed for str[i]");
      break;
    }
    snprintf( str[i], WORDLEN, "Hello world %02d!", i);
  }

  for( i=0; i<WORDS; i++ ) {
    printf("Word %02d: %s\n", i, str[i]);
  }
  return 0;
}

 

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

#define SPALTEN 2
#define ZEILEN 10
#define WORDLEN 20

int main( int argc, char **argv ) {
  int i = 0;
  int spalte = 0;
  char ***str = NULL;

  str = (char**) malloc( sizeof(char**) * SPALTEN );
  if( str == NULL) {
    perror("1: malloc failed for str");
    return 1;
  }

  for( spalte=0; spalte<SPALTEN; spalte++ ) {
    str[spalte] = (char*) malloc( sizeof(char*) * ZEILEN );
    if( str[spalte] == NULL ) {
      perror("2: malloc failed for str[spalte]");
      return 1;
    }

    for( i=0; i<ZEILEN; i++ ) {
      str[spalte][i] = (char*) malloc( sizeof(char) * WORDLEN );
      if( str[spalte][i] == NULL ) {
        perror("3: malloc failed for str[spalte][i]");
      }
      snprintf( str[spalte][i], WORDLEN, "Hello world %02d!", i);
    }
  }

  for( spalte=0; spalte<SPALTEN; spalte++ ) {
    for( i=0; i<ZEILEN; i++ ) {
      printf("str[%d][%d] => %s\n", spalte, i, str[spalte][i]);
    }
  }

  return 0;
}
Posted in C/C++, Programming | Leave a comment

OCL Expressions

Just few OCL statements for my future work which I found in different slides and tutorials. Nothing special :-)

Flatten:

context MyType
def: a : Set(Set(Integer)) = Set {Set{1, 2, 3}, Set{3, 4, 5}, Set{4, 5, 6}}
a->flatten() = Set{2, 3, 1, 5, 4, 6} — no order

Continue reading

Posted in Modeling, OCL | Leave a comment

OCL Shorthands for Collect

I started reading of the OCL Specification 2.2, chapter 7 (they call it clause) is “OCL Language Description”. Within the first 22 pages of this chapter they write a lot of times something like this: self.target.attr_of_target.

Here, self is a reference of one object to itself, target is a reference to another object, and attr_of_target is just one attribute of target’s object. But target has a multiplicity of [1..*], so I was always troubled with statements like the mentioned above, because I thought it is not possible and they do always a mistake. Fact is, for multiplicities which are more than one the arrow ‘->’ should be used, because it is a Collection.

On the 23rd page, it is explained! Why the hell not earlier or a reference to it?! Hmpf…

[quote]
Because navigation through many objects is very common, there is a shorthand notation for the collect that makes the OCL expressions more readable. Instead of

self.employee->collect(birthdate) we can also write: self.employee.birthdate.
[/quote]

Posted in Modeling, OCL | Leave a comment

Unlock Android-Screen with Commandline

Connect to your Android emulator:

cr@visualgrid-4:~/ telnet localhost 5554

Type one sequence which is shown in following figure and your emulator should be unlocked:

Posted in Android | Leave a comment