<commit_before>// str.cpp            see license.txt for copyright and terms of use
// code for str.h
// Scott McPeak, 1995-2000  This file is public domain.

#include "str.h"            // this module

#include <stdlib.h>         // atoi
#include <stdio.h>          // sprintf
#include <ctype.h>          // isspace
#include <string.h>         // strcmp
#include <iostream.h>       // ostream << char*
#include <assert.h>         // assert
#include <unistd.h>         // write

#include "xassert.h"        // xassert
#include "ckheap.h"         // checkHeapNode
#include "flatten.h"        // Flatten
#include "nonport.h"        // vnprintf
#include "array.h"          // Array

// ----------------------- string ---------------------

// put the empty string itself in read-only memory
char const nul_byte = 0;

// deliberately cast away the constness; I cannot declare
// 'emptyString' to be const because it gets assigned to 's', but it
// is nevertheless the intent that I never modify 'nul_byte'
char * const string::emptyString = const_cast<char*>(&nul_byte);

string::string(char const *src, int length, SmbaseStringFunc)
{
  s=emptyString;
  setlength(length);       // setlength already has the +1; sets final NUL
  memcpy(s, src, length);
}

void string::dup(char const *src)
{
  // std::string does not accept NULL pointers
  xassert(src != NULL);

  if (src[0]==0) {
    s = emptyString;
  }
  else {
    s = new char[ strlen(src) + 1 ];
    xassert(s);
    strcpy(s, src);
  }
}

void string::kill()
{
  if (s != emptyString) {
    delete s;
  }
}

string::string(Flatten&)
  : s(emptyString)
{}

void string::xfer(Flatten &flat)
{
  flat.xferCharString(s);
}

int string::length() const
{
  xassert(s);
  return strlen(s);
}

bool string::contains(char c) const
{
  xassert(s);
  return !!strchr(s, c);
}

string string::substring(int startIndex, int len) const
{
  xassert(startIndex >= 0 &&
          len >= 0 &&
          startIndex + len <= length());

  return ::substring(s+startIndex, len);
}

string &string::setlength(int length)
{
  kill();
  if (length > 0) {
    s = new char[ length+1 ];
    xassert(s);
    s[length] = 0;      // final NUL in expectation of 'length' chars
    s[0] = 0;           // in case we just wanted to set allocated length
  }
  else {
    xassert(length == 0);     // negative wouldn't make sense
    s = emptyString;
  }
  return *this;
}

int string::compareTo(string const &src) const
{
  return compareTo(src.s);
}

int string::compareTo(char const *src) const
{
  if (src == NULL) {
    src = emptyString;
  }
  return strcmp(s, src);
}

string string::operator&(string const &tail) const
{
  string dest(length() + tail.length(), SMBASE_STRING_FUNC);
  strcpy(dest.s, s);
  strcat(dest.s, tail.s);
  return dest;
}

string& string::operator&=(string const &tail)
{
  return *this = *this & tail;
}

void string::readdelim(istream &is, char const *delim)
{
  stringBuilder sb;
  sb.readdelim(is, delim);
  operator= (sb);
}

void string::write(ostream &os) const
{
  os << s;     // standard char* writing routine
}

void string::selfCheck() const
{
  if (s != emptyString) {
    checkHeapNode(s);
  }
}

// ----------------------- rostring ---------------------
int strcmp(rostring s1, rostring s2)
  { return strcmp(s1.c_str(), s2.c_str()); }
int strcmp(rostring s1, char const *s2)
  { return strcmp(s1.c_str(), s2); }
int strcmp(char const *s1, rostring s2)
  { return strcmp(s1, s2.c_str()); }

char const *strstr(rostring haystack, char const *needle)
{
  return strstr(haystack.c_str(), needle);
}

int atoi(rostring s)
{
  return atoi(toCStr(s));
}

string substring(char const *p, int n)
{
  return string(p, n, SMBASE_STRING_FUNC);
}

// --------------------- stringBuilder ------------------
stringBuilder::stringBuilder(int len)
{
  init(len);
}

void stringBuilder::init(int initSize)
{
  size = initSize + EXTRA_SPACE + 1;     // +1 to be like string::setlength
  s = new char[size];
  end = s;
  end[initSize] = 0;
}

void stringBuilder::dup(char const *str)
{
  int len = strlen(str);
  init(len);
  strcpy(s, str);
  end += len;
}

stringBuilder::stringBuilder(char const *str)
{
  dup(str);
}

stringBuilder::stringBuilder(char const *str, int len)
{
  init(len);
  memcpy(s, str, len);
  end += len;
}

stringBuilder& stringBuilder::operator=(char const *src)
{
  if (s != src) {
    kill();
    dup(src);
  }
  return *this;
}

stringBuilder& stringBuilder::setlength(int newlen)
{
  kill();
  init(newlen);
  return *this;
}

void stringBuilder::adjustend(char* newend)
{
  xassert(s <= newend  &&  newend < s + size);

  end = newend;
  *end = 0;        // sm 9/29/00: maintain invariant
}

stringBuilder& stringBuilder::operator&= (char const *tail)
{
  append(tail, strlen(tail));
  return *this;
}

void stringBuilder::append(char const *tail, int len)
{
  ensure(length() + len);

  memcpy(end, tail, len);
  end += len;
  *end = 0;
}

stringBuilder& stringBuilder::indent(int amt)
{
  xassert(amt >= 0);
  ensure(length() + amt);

  memset(end, ' ', amt);
  end += amt;
  *end = 0;

  return *this;
}

void stringBuilder::grow(int newMinLength)
{
  // I want at least EXTRA_SPACE extra
  int newMinSize = newMinLength + EXTRA_SPACE + 1;         // compute resulting allocated size

  // I want to grow at the rate of at least 50% each time
  int suggest = size * 3 / 2;

  // see which is bigger
  newMinSize = max(newMinSize, suggest);

  // remember old length..
  int len = length();

  // realloc s to be newMinSize bytes
  char *temp = new char[newMinSize];
  xassert(len+1 <= newMinSize);    // prevent overrun
  memcpy(temp, s, len+1);          // copy null too
  delete[] s;
  s = temp;

  // adjust other variables
  end = s + len;
  size = newMinSize;
}

stringBuilder& stringBuilder::operator<< (char c)
{
  ensure(length() + 1);
  *(end++) = c;
  *end = 0;
  return *this;
}

#define MAKE_LSHIFT(Argtype, fmt)                        \
  stringBuilder& stringBuilder::operator<< (Argtype arg) \
  {                                                      \
    char buf[60];      /* big enough for all types */    \
    int len = sprintf(buf, fmt, arg);                    \
    if (len >= 60) {					 \
      abort();    /* too big */                          \
    }                                                    \
    return *this << buf;                                 \
  }

MAKE_LSHIFT(long, "%ld")
MAKE_LSHIFT(unsigned long, "%lu")
MAKE_LSHIFT(double, "%g")
MAKE_LSHIFT(void*, "%p")

#undef MAKE_LSHIFT

stringBuilder& stringBuilder::operator<< (
  stringBuilder::Hex const &h)
{
  char buf[32];        // should only need 19 for 64-bit word..
  int len = sprintf(buf, "0x%lX", h.value);
  if (len >= 20) {
    abort();
  }
  return *this << buf;

  // the length check above isn't perfect because we only find out there is
  // a problem *after* trashing the environment.  it is for this reason I
  // use 'assert' instead of 'xassert' -- the former calls abort(), while the
  // latter throws an exception in anticipation of recoverability
}

stringBuilder& stringBuilder::operator<< (Manipulator manip)
{
  return manip(*this);
}

// slow but reliable
void stringBuilder::readdelim(istream &is, char const *delim)
{
  char c;
  is.get(c);
  while (!is.eof() &&
         (!delim || !strchr(delim, c))) {
    *this << c;
    is.get(c);
  }
}

// ---------------------- toString ---------------------
#define TOSTRING(type)        \
  string toString(type val)   \
  {                           \
    return stringc << val;    \
  }

TOSTRING(int)
TOSTRING(unsigned)
TOSTRING(char)
TOSTRING(long)
TOSTRING(float)

#undef TOSTRING

// this one is more liberal than 'stringc << null' because it gets
// used by the PRINT_GENERIC macro in my astgen tool
string toString(char const *str)
{
  if (!str) {
    return string("(null)");
  }
  else {
    return string(str);
  }
}

// ------------------- stringf -----------------
string stringf(char const *format, ...)
{
  va_list args;
  va_start(args, format);
  string ret = vstringf(format, args);
  va_end(args);
  return ret;
}

// this should eventually be put someplace more general...
#ifndef va_copy
  #ifdef __va_copy
    #define va_copy(a,b) __va_copy(a,b)
  #else
    #define va_copy(a,b) (a)=(b)
  #endif
#endif

string vstringf(char const *format, va_list args)
{
  // estimate string length
  va_list args2;
  va_copy(args2, args);
  int est = vnprintf(format, args2);
  va_end(args2);

  // allocate space
  Array<char> buf(est+1);

  // render the string
  int len = vsprintf(buf, format, args);

  // check the estimate, and fail *hard* if it was low, to avoid any
  // possibility that this might become exploitable in some context
  // (do *not* turn this check off in an NDEGUG build)
  if (len > est) {
    // don't go through fprintf, etc., because the state of memory
    // makes that risky
    static char const msg[] =
      "fatal error: vnprintf failed to provide a conservative estimate,\n"
      "memory is most likely corrupted\n";
    write(2 /*stderr*/, msg, strlen(msg));
    abort();
  }

  // happy
  return string(buf);
}

// ------------------ test code --------------------
#ifdef TEST_STR

#include <iostream.h>    // cout

void test(unsigned long val)
{
  //cout << stringb(val << " in hex: 0x" << stringBuilder::Hex(val)) << endl;

  cout << stringb(val << " in hex: " << SBHex(val)) << endl;
}

int main()
{
  // for the moment I just want to test the hex formatting
  test(64);
  test(0xFFFFFFFF);
  test(0);
  test((unsigned long)(-1));
  test(1);

  cout << "stringf: " << stringf("int=%d hex=%X str=%s char=%c float=%f",
                                 5, 0xAA, "hi", 'f', 3.4) << endl;

  cout << "tests passed\n";

  return 0;
}

#endif // TEST_STR

// bork!
<commit_msg>seems to work<commit_after>// str.cpp            see license.txt for copyright and terms of use
// code for str.h
// Scott McPeak, 1995-2000  This file is public domain.

#include "str.h"            // this module

#include <stdlib.h>         // atoi
#include <stdio.h>          // sprintf
#include <ctype.h>          // isspace
#include <string.h>         // strcmp
#include <iostream.h>       // ostream << char*
#include <assert.h>         // assert
#include <unistd.h>         // write

#include "xassert.h"        // xassert
#include "ckheap.h"         // checkHeapNode
#include "flatten.h"        // Flatten
#include "nonport.h"        // vnprintf
#include "array.h"          // Array

// ----------------------- string ---------------------

// put the empty string itself in read-only memory
char const nul_byte = 0;

// deliberately cast away the constness; I cannot declare
// 'emptyString' to be const because it gets assigned to 's', but it
// is nevertheless the intent that I never modify 'nul_byte'
char * const string::emptyString = const_cast<char*>(&nul_byte);

string::string(char const *src, int length, SmbaseStringFunc)
{
  s=emptyString;
  setlength(length);       // setlength already has the +1; sets final NUL
  memcpy(s, src, length);
}

void string::dup(char const *src)
{
  // std::string does not accept NULL pointers
  xassert(src != NULL);

  if (src[0]==0) {
    s = emptyString;
  }
  else {
    s = new char[ strlen(src) + 1 ];
    xassert(s);
    strcpy(s, src);
  }
}

void string::kill()
{
  if (s != emptyString) {
    delete s;
  }
}

string::string(Flatten&)
  : s(emptyString)
{}

void string::xfer(Flatten &flat)
{
  flat.xferCharString(s);
}

int string::length() const
{
  xassert(s);
  return strlen(s);
}

bool string::contains(char c) const
{
  xassert(s);
  return !!strchr(s, c);
}

string string::substring(int startIndex, int len) const
{
  xassert(startIndex >= 0 &&
          len >= 0 &&
          startIndex + len <= length());

  return ::substring(s+startIndex, len);
}

string &string::setlength(int length)
{
  kill();
  if (length > 0) {
    s = new char[ length+1 ];
    xassert(s);
    s[length] = 0;      // final NUL in expectation of 'length' chars
    s[0] = 0;           // in case we just wanted to set allocated length
  }
  else {
    xassert(length == 0);     // negative wouldn't make sense
    s = emptyString;
  }
  return *this;
}

int string::compareTo(string const &src) const
{
  return compareTo(src.s);
}

int string::compareTo(char const *src) const
{
  if (src == NULL) {
    src = emptyString;
  }
  return strcmp(s, src);
}

string string::operator&(string const &tail) const
{
  string dest(length() + tail.length(), SMBASE_STRING_FUNC);
  strcpy(dest.s, s);
  strcat(dest.s, tail.s);
  return dest;
}

string& string::operator&=(string const &tail)
{
  return *this = *this & tail;
}

void string::readdelim(istream &is, char const *delim)
{
  stringBuilder sb;
  sb.readdelim(is, delim);
  operator= (sb);
}

void string::write(ostream &os) const
{
  os << s;     // standard char* writing routine
}

void string::selfCheck() const
{
  if (s != emptyString) {
    checkHeapNode(s);
  }
}

// ----------------------- rostring ---------------------
int strcmp(rostring s1, rostring s2)
  { return strcmp(s1.c_str(), s2.c_str()); }
int strcmp(rostring s1, char const *s2)
  { return strcmp(s1.c_str(), s2); }
int strcmp(char const *s1, rostring s2)
  { return strcmp(s1, s2.c_str()); }

char const *strstr(rostring haystack, char const *needle)
{
  return strstr(haystack.c_str(), needle);
}

int atoi(rostring s)
{
  return atoi(toCStr(s));
}

string substring(char const *p, int n)
{
  return string(p, n, SMBASE_STRING_FUNC);
}

// --------------------- stringBuilder ------------------
stringBuilder::stringBuilder(int len)
{
  init(len);
}

void stringBuilder::init(int initSize)
{
  size = initSize + EXTRA_SPACE + 1;     // +1 to be like string::setlength
  s = new char[size];
  end = s;
  end[initSize] = 0;
}

void stringBuilder::dup(char const *str)
{
  int len = strlen(str);
  init(len);
  strcpy(s, str);
  end += len;
}

stringBuilder::stringBuilder(char const *str)
{
  dup(str);
}

stringBuilder::stringBuilder(char const *str, int len)
{
  init(len);
  memcpy(s, str, len);
  end += len;
}

stringBuilder& stringBuilder::operator=(char const *src)
{
  if (s != src) {
    kill();
    dup(src);
  }
  return *this;
}

stringBuilder& stringBuilder::setlength(int newlen)
{
  kill();
  init(newlen);
  return *this;
}

void stringBuilder::adjustend(char* newend)
{
  xassert(s <= newend  &&  newend < s + size);

  end = newend;
  *end = 0;        // sm 9/29/00: maintain invariant
}

stringBuilder& stringBuilder::operator&= (char const *tail)
{
  append(tail, strlen(tail));
  return *this;
}

void stringBuilder::append(char const *tail, int len)
{
  ensure(length() + len);

  memcpy(end, tail, len);
  end += len;
  *end = 0;
}

stringBuilder& stringBuilder::indent(int amt)
{
  xassert(amt >= 0);
  ensure(length() + amt);

  memset(end, ' ', amt);
  end += amt;
  *end = 0;

  return *this;
}

void stringBuilder::grow(int newMinLength)
{
  // I want at least EXTRA_SPACE extra
  int newMinSize = newMinLength + EXTRA_SPACE + 1;         // compute resulting allocated size

  // I want to grow at the rate of at least 50% each time
  int suggest = size * 3 / 2;

  // see which is bigger
  newMinSize = max(newMinSize, suggest);

  // remember old length..
  int len = length();

  // realloc s to be newMinSize bytes
  char *temp = new char[newMinSize];
  xassert(len+1 <= newMinSize);    // prevent overrun
  memcpy(temp, s, len+1);          // copy null too
  delete[] s;
  s = temp;

  // adjust other variables
  end = s + len;
  size = newMinSize;
}

stringBuilder& stringBuilder::operator<< (char c)
{
  ensure(length() + 1);
  *(end++) = c;
  *end = 0;
  return *this;
}

#define MAKE_LSHIFT(Argtype, fmt)                        \
  stringBuilder& stringBuilder::operator<< (Argtype arg) \
  {                                                      \
    char buf[60];      /* big enough for all types */    \
    int len = sprintf(buf, fmt, arg);                    \
    if (len >= 60) {					 \
      abort();    /* too big */                          \
    }                                                    \
    return *this << buf;                                 \
  }

MAKE_LSHIFT(long, "%ld")
MAKE_LSHIFT(unsigned long, "%lu")
MAKE_LSHIFT(double, "%g")
MAKE_LSHIFT(void*, "%p")

#undef MAKE_LSHIFT

stringBuilder& stringBuilder::operator<< (
  stringBuilder::Hex const &h)
{
  char buf[32];        // should only need 19 for 64-bit word..
  int len = sprintf(buf, "0x%lX", h.value);
  if (len >= 20) {
    abort();
  }
  return *this << buf;

  // the length check above isn't perfect because we only find out there is
  // a problem *after* trashing the environment.  it is for this reason I
  // use 'assert' instead of 'xassert' -- the former calls abort(), while the
  // latter throws an exception in anticipation of recoverability
}

stringBuilder& stringBuilder::operator<< (Manipulator manip)
{
  return manip(*this);
}

// slow but reliable
void stringBuilder::readdelim(istream &is, char const *delim)
{
  char c;
  is.get(c);
  while (!is.eof() &&
         (!delim || !strchr(delim, c))) {
    *this << c;
    is.get(c);
  }
}

// ---------------------- toString ---------------------
#define TOSTRING(type)        \
  string toString(type val)   \
  {                           \
    return stringc << val;    \
  }

TOSTRING(int)
TOSTRING(unsigned)
TOSTRING(char)
TOSTRING(long)
TOSTRING(float)

#undef TOSTRING

// this one is more liberal than 'stringc << null' because it gets
// used by the PRINT_GENERIC macro in my astgen tool
string toString(char const *str)
{
  if (!str) {
    return string("(null)");
  }
  else {
    return string(str);
  }
}

// ------------------- stringf -----------------
string stringf(char const *format, ...)
{
  va_list args;
  va_start(args, format);
  string ret = vstringf(format, args);
  va_end(args);
  return ret;
}

// this should eventually be put someplace more general...
#ifndef va_copy
  #ifdef __va_copy
    #define va_copy(a,b) __va_copy(a,b)
  #else
    #define va_copy(a,b) (a)=(b)
  #endif
#endif

string vstringf(char const *format, va_list args)
{
  // estimate string length
  va_list args2;
  va_copy(args2, args);
  int est = vnprintf(format, args2);
  va_end(args2);

  // allocate space
  Array<char> buf(est+1);

  // render the string
  int len = vsprintf(buf, format, args);

  // check the estimate, and fail *hard* if it was low, to avoid any
  // possibility that this might become exploitable in some context
  // (do *not* turn this check off in an NDEGUG build)
  if (len > est) {
    // don't go through fprintf, etc., because the state of memory
    // makes that risky
    static char const msg[] =
      "fatal error: vnprintf failed to provide a conservative estimate,\n"
      "memory is most likely corrupted\n";
    write(2 /*stderr*/, msg, strlen(msg));
    abort();
  }

  // happy
  return string(buf);
}

// ------------------ test code --------------------
#ifdef TEST_STR

#include <iostream.h>    // cout

void test(unsigned long val)
{
  //cout << stringb(val << " in hex: 0x" << stringBuilder::Hex(val)) << endl;

  cout << stringb(val << " in hex: " << SBHex(val)) << endl;
}

int main()
{
  // for the moment I just want to test the hex formatting
  test(64);
  test(0xFFFFFFFF);
  test(0);
  test((unsigned long)(-1));
  test(1);

  cout << "stringf: " << stringf("int=%d hex=%X str=%s char=%c float=%f",
                                 5, 0xAA, "hi", 'f', 3.4) << endl;

  cout << "tests passed\n";

  return 0;
}

#endif // TEST_STR
<|endoftext|>


<commit_before>/*
 * File:  tr_globals.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "term_globals.h"
#include "base.h"

// variables for parsing command line

int term_s_help = 0;
int term_l_help = 0;
int term_version = 0;

int show_time = 0;
int socket_port = 0;
int echo = 1;

char host[TERM_ARGSTRLEN+1];
char db_name[TERM_ARGSTRLEN+1];
char filename[TERM_ARGSTRLEN+1];
char query[TERM_ARGSTRLEN+1];
char login[TERM_ARGSTRLEN+1];
char password[TERM_ARGSTRLEN+1];
char output_file[TERM_ARGSTRLEN+1];
char echo_str[TERM_ARGSTRLEN+1];

const size_t narg = 13;

arg_rec term_argtable[] =
{
{"-help",            NULL,       arg_lit,   &term_s_help,                 "0",       "\t\t\t  display this help and exit"},
{"--help",           NULL,       arg_lit,   &term_l_help,                 "0",       "\t\t  display this help and exit"},
{"-version",         NULL,       arg_lit,   &term_version,                "0",       "\t\t  display product version and exit"},
{"-file",           " filename", arg_str,   &filename,                  "???",     "\t  file with an XQuery query\t\t\t  "},
{"-output",         " filename",     arg_str,   &output_file,               "STDOUT",  "\t  output file (default stdout)"},
{"-query",          " \"query\"",    arg_str,   &query,                   "???",     "\t  XQuery query to execute\t\t"},
{"-echo",           " on/off",   arg_str,   &echo_str,                      "???",      "\t\t  display se_term output  (default: on for interactive mode, off for batch mode)"},
{"-showtime",       " on/off",   arg_bool,  &show_time,                 "off",     "\t  show time of the latest query execution (default off)"},
{"-host",           " host",     arg_str,   &host,                      "???",     "\t\t  hostname of the machine with Sedna running (default localhost)\n\t\t"},
{"-port-number",    " port",     arg_int,   &socket_port,               "5050",    "\t  socket listening port  (default 5050)"},
{"-name",           " name",     arg_str,   &login,                     "???",  "\t\t  user name "},
{"-pswd",           " password", arg_str,   &password,                  "???", "\t  user password "},
{NULL,              " db-name",  arg_str,   &db_name,                   "???",     "\t\t  database name"}
};

bool on_error_stop = false;
SednaConnection conn = SEDNA_CONNECTION_INITIALIZER;
<commit_msg>dummy<commit_after>/*
 * File:  tr_globals.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include "term_globals.h"
#include "base.h"

// variables for parsing command line

int term_s_help = 0;
int term_l_help = 0;
int term_version = 0;

int show_time = 0;
int socket_port = 0;
int echo = 1;

char host[TERM_ARGSTRLEN+1];
char db_name[TERM_ARGSTRLEN+1];
char filename[TERM_ARGSTRLEN+1];
char query[TERM_ARGSTRLEN+1];
char login[TERM_ARGSTRLEN+1];
char password[TERM_ARGSTRLEN+1];
char output_file[TERM_ARGSTRLEN+1];
char echo_str[TERM_ARGSTRLEN+1];

const size_t narg = 13;

arg_rec term_argtable[] =
{
{"-help",            NULL,       arg_lit,   &term_s_help,                 "0",       "\t\t\t  display this help and exit"},
{"--help",           NULL,       arg_lit,   &term_l_help,                 "0",       "\t\t  display this help and exit"},
{"-version",         NULL,       arg_lit,   &term_version,                "0",       "\t\t  display product version and exit"},
{"-file",           " filename", arg_str,   &filename,                  "???",     "\t  file with an XQuery query\t\t\t  "},
{"-output",         " filename",     arg_str,   &output_file,               "STDOUT",  "\t  output file (default stdout)"},
{"-query",          " \"query\"",    arg_str,   &query,                   "???",     "\t  XQuery query to execute\t\t"},
{"-echo",           " on/off",   arg_str,   &echo_str,                      "???",      "\t\t  display se_term output  (default: on for interactive mode, off for batch mode)"},
{"-showtime",       " on/off",   arg_bool,  &show_time,                 "off",     "\t  show time of the latest query execution (default off)"},
{"-host",           " host",     arg_str,   &host,                      "???",     "\t\t  hostname of the machine with Sedna running (default localhost)\n\t\t"},
{"-port-number",    " port",     arg_int,   &socket_port,               "5050",    "\t  socket listening port  (default 5050)"},
{"-name",           " name",     arg_str,   &login,                     "???",  "\t\t  user name "},
{"-pswd",           " password", arg_str,   &password,                  "???", "\t  user password "},
{NULL,              " db-name",  arg_str,   &db_name,                   "???",     "\t\t  database name"}
};

bool on_error_stop = false;
SednaConnection conn = SEDNA_CONNECTION_INITIALIZER;
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "qtmaemo6styleeventfilter.h"
#include "qtmaemo6style_p.h"
#include "qtmaemo6windowdecoration.h"
#include "qtmaemo6dialogproxy.h"
#include "qtmaemo6comboboxpopup.h"

#include <QWidget>
#include <QEvent>
#include <QDebug>
#include <QMainWindow>
#include <QDialog>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QToolButton>
#include <QTreeView>
#include <QComboBox>

#include <DuiComponentData>
#include <duifeedbackplayer.h>
#include <duideviceprofile.h>
#include <DuiTheme>
#include <duibuttonstyle.h>
#include <DuiScalableImage>

//krazy:excludeall=qclasses

QtMaemo6StyleEventFilter::QtMaemo6StyleEventFilter(QtMaemo6TestStyle *parent)
    : QtMaemo6TestStyleEventFilter(parent)
{
}

bool QtMaemo6StyleEventFilter::eventFilter(QObject *obj, QEvent *event)
{
    QWidget *widget = qobject_cast<QWidget *>(obj);

    //unused
    //QWidget * parent = widget->parentWidget();

    switch (event->type()) {
    case QEvent::Show: {
        if (NULL != widget) {
            if (widget->isWindow()) {
                if (QDialog *dialog = qobject_cast<QDialog *>(widget)) {
                    qCritical() << "Generating and Showing DuiDialog";
                    QtMaemo6DialogProxy *dialogProxy = new QtMaemo6DialogProxy(dialog, m_style->m_windowDecoration);

                    dialogProxy->setTitle(widget->windowTitle());

                    const QPixmap *closePixmap = DuiTheme::pixmap("Icon-close", QSize(28, 28));
                    dialogProxy->setPixmap(*closePixmap);

                    dialogProxy->showFastMaximized();
                    QtMaemo6StylePrivate::drawWindowBackground(widget);
                    return true;
                }
                else if (!qobject_cast<QtMaemo6Window *>(widget)) {
                    qDebug() << "Generating and Showing DuiWindowDecoration";
                    m_style->m_windowDecoration = new QtMaemo6WindowDecoration(widget);
                    m_style->m_windowDecoration->showFastMaximized();
                    QtMaemo6StylePrivate::drawWindowBackground(m_style->m_windowDecoration);
                    return true;
                }
            }
            // Unfortunately this can't be safely done in polish:
            if (QDialogButtonBox *box = qobject_cast<QDialogButtonBox *>(widget)) {
                QPushButton *okButton = box->button(QDialogButtonBox::Ok);
                //~ uispec-document DirectUI_Common_Strings_UI_Specification_0.7.doc
                //: Command for confirmation
                //% "Done"
                if (okButton) okButton->setText(qtTrId("qtn_comm_command_done"));
                QPushButton *cancelButton = box->button(QDialogButtonBox::Cancel);
                if (cancelButton) cancelButton->hide();
            }
            if (QPushButton *button = qobject_cast<QPushButton *>(widget)) {
                QString okString = tr("OK");
                //~ uispec-document DirectUI_Common_Strings_UI_Specification_0.7.doc
                //: Command for confirmation
                //% "Done"
                QString doneString = qtTrId("qtn_comm_command_done");
                if (button->text() == okString) button->setText(doneString);
                QString cancelString = tr("Cancel");
                if (button->text() == cancelString) {
                    button->hide();
                }
            }
            if (QTreeView *treeWidget = qobject_cast<QTreeView *>(widget)) {
                //unfortunately this must be done in showEvent, because it's
                // a property of QTreeWidget, that can't be influenzed by the
                // style

                //FIXME: really bad to do all that in showEvent
                QToolButton button;
                QStyleOptionToolButton option;
                option.initFrom(&button);
                option.text = '+';
                QSize size = m_style->sizeFromContents(QStyle::CT_ToolButton, &option, QSize(), &button);

                //only set the indentation if the required buttonsize is bigger
                // than original indentation
                if (size.width() > treeWidget->indentation()) {
                    treeWidget->setIndentation(size.width());
                }
            }
        }

    }
    break;
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseButtonPress: {
        //qDebug( "eventFilter got mousePress" );

        // now send press feedback
        DuiFeedbackPlayer *feedbackPlayer = DuiComponentData::feedbackPlayer();

        if (feedbackPlayer) {
            feedbackPlayer->play(DuiFeedbackPlayer::Press);
        }
        if(QComboBox* comboBox = qobject_cast<QComboBox*>(widget)) {
            //done in mousePress, because in this way the original popup is completely suppressed
            QtMaemo6ComboBoxPopup *comboBoxPopup = new QtMaemo6ComboBoxPopup(comboBox, NULL);
            QtMaemo6DialogProxy* dialog = new QtMaemo6DialogProxy(comboBoxPopup, comboBox);
            dialog->showFastMaximized();
            dialog->setTitle(tr("Choose a value"));
            QtMaemo6StylePrivate::drawWindowBackground(comboBoxPopup);
            return true;
        }
    }
    break;
    case QEvent::MouseButtonRelease: {
        //qDebug( "eventFilter got mouseRelease" );

        // now send release feedback
        DuiFeedbackPlayer *feedbackPlayer = DuiComponentData::feedbackPlayer();

        if (feedbackPlayer) {
            feedbackPlayer->play(DuiFeedbackPlayer::Release);
        }
    }
    break;
    case QEvent::Wheel: {
        if(qobject_cast<QComboBox*>(widget)) {
            return true;
        }
    }
    break;
    default:
        break;
    }
    // standard event processing
    return QObject::eventFilter(obj, event);
}

<commit_msg>Changes: Also style menus when not called from QMenuBar<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "qtmaemo6styleeventfilter.h"
#include "qtmaemo6style_p.h"
#include "qtmaemo6windowdecoration.h"
#include "qtmaemo6dialogproxy.h"
#include "qtmaemo6comboboxpopup.h"
#include "qtmaemo6submenu.h"

#include <QWidget>
#include <QEvent>
#include <QDebug>
#include <QMainWindow>
#include <QDialog>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QToolButton>
#include <QTreeView>
#include <QComboBox>
#include <QMenu>

#include <DuiComponentData>
#include <duifeedbackplayer.h>
#include <duideviceprofile.h>
#include <DuiTheme>
#include <duibuttonstyle.h>
#include <DuiScalableImage>

//krazy:excludeall=qclasses

QtMaemo6StyleEventFilter::QtMaemo6StyleEventFilter(QtMaemo6TestStyle *parent)
    : QtMaemo6TestStyleEventFilter(parent)
{
}

bool QtMaemo6StyleEventFilter::eventFilter(QObject *obj, QEvent *event)
{
    QWidget *widget = qobject_cast<QWidget *>(obj);

    //unused
    //QWidget * parent = widget->parentWidget();

    switch (event->type()) {
    case QEvent::Show: {
        if (NULL != widget) {
            if (widget->isWindow()) {
                if (QDialog *dialog = qobject_cast<QDialog *>(widget)) {
                    qCritical() << "Generating and Showing DuiDialog";
                    QtMaemo6DialogProxy *dialogProxy = new QtMaemo6DialogProxy(dialog, m_style->m_windowDecoration);

                    dialogProxy->setTitle(widget->windowTitle());

                    const QPixmap *closePixmap = DuiTheme::pixmap("Icon-close", QSize(28, 28));
                    dialogProxy->setPixmap(*closePixmap);

                    dialogProxy->showFastMaximized();
                    QtMaemo6StylePrivate::drawWindowBackground(widget);
                    return true;
                } else if(QMenu* menu = qobject_cast<QMenu*>(widget)) {
                    //also show menus styled like dui menus, even if they are not called from a menubar
                    QtMaemo6SubMenu *subMenu = new QtMaemo6SubMenu(menu, NULL);
                    QtMaemo6WindowDecoration *decoration = new QtMaemo6WindowDecoration(subMenu, NULL);
                    decoration->showFastMaximized();
                    //these both must be done after the show, because the status- and
                    // menubar is added on show event
                    decoration->setStatusBar(NULL);
                    decoration->setMenuBar(NULL);
                    QtMaemo6StylePrivate::drawWindowBackground(decoration);
                } else if (!qobject_cast<QtMaemo6Window *>(widget)) {
                    qCritical() << "Generating and Showing DuiWindowDecoration";
                    m_style->m_windowDecoration = new QtMaemo6WindowDecoration(widget);
                    m_style->m_windowDecoration->showFastMaximized();
                    QtMaemo6StylePrivate::drawWindowBackground(m_style->m_windowDecoration);
                    return true;
                }
            }
            // Unfortunately this can't be safely done in polish:
            if (QDialogButtonBox *box = qobject_cast<QDialogButtonBox *>(widget)) {
                QPushButton *okButton = box->button(QDialogButtonBox::Ok);
                //~ uispec-document DirectUI_Common_Strings_UI_Specification_0.7.doc
                //: Command for confirmation
                //% "Done"
                if (okButton) okButton->setText(qtTrId("qtn_comm_command_done"));
                QPushButton *cancelButton = box->button(QDialogButtonBox::Cancel);
                if (cancelButton) cancelButton->hide();
            }
            if (QPushButton *button = qobject_cast<QPushButton *>(widget)) {
                QString okString = tr("OK");
                //~ uispec-document DirectUI_Common_Strings_UI_Specification_0.7.doc
                //: Command for confirmation
                //% "Done"
                QString doneString = qtTrId("qtn_comm_command_done");
                if (button->text() == okString) button->setText(doneString);
                QString cancelString = tr("Cancel");
                if (button->text() == cancelString) {
                    button->hide();
                }
            }
            if (QTreeView *treeWidget = qobject_cast<QTreeView *>(widget)) {
                //unfortunately this must be done in showEvent, because it's
                // a property of QTreeWidget, that can't be influenzed by the
                // style

                //FIXME: really bad to do all that in showEvent
                QToolButton button;
                QStyleOptionToolButton option;
                option.initFrom(&button);
                option.text = '+';
                QSize size = m_style->sizeFromContents(QStyle::CT_ToolButton, &option, QSize(), &button);

                //only set the indentation if the required buttonsize is bigger
                // than original indentation
                if (size.width() > treeWidget->indentation()) {
                    treeWidget->setIndentation(size.width());
                }
            }
        }

    }
    break;
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseButtonPress: {
        //qDebug( "eventFilter got mousePress" );

        // now send press feedback
        DuiFeedbackPlayer *feedbackPlayer = DuiComponentData::feedbackPlayer();

        if (feedbackPlayer) {
            feedbackPlayer->play(DuiFeedbackPlayer::Press);
        }
        if(QComboBox* comboBox = qobject_cast<QComboBox*>(widget)) {
            //done in mousePress, because in this way the original popup is completely suppressed
            QtMaemo6ComboBoxPopup *comboBoxPopup = new QtMaemo6ComboBoxPopup(comboBox, NULL);
            QtMaemo6DialogProxy* dialog = new QtMaemo6DialogProxy(comboBoxPopup, comboBox);
            dialog->showFastMaximized();
            dialog->setTitle(tr("Choose a value"));
            QtMaemo6StylePrivate::drawWindowBackground(comboBoxPopup);
            return true;
        }
    }
    break;
    case QEvent::MouseButtonRelease: {
        //qDebug( "eventFilter got mouseRelease" );

        // now send release feedback
        DuiFeedbackPlayer *feedbackPlayer = DuiComponentData::feedbackPlayer();

        if (feedbackPlayer) {
            feedbackPlayer->play(DuiFeedbackPlayer::Release);
        }
    }
    break;
    case QEvent::Wheel: {
        if(qobject_cast<QComboBox*>(widget)) {
            return true;
        }
    }
    break;
    default:
        break;
    }
    // standard event processing
    return QObject::eventFilter(obj, event);
}

<|endoftext|>


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

#include "rclcpp_lifecycle/lifecycle_node.hpp"

#include <string>
#include <map>
#include <memory>
#include <vector>
#include <utility>

#include "lifecycle_msgs/msg/state.hpp"
#include "lifecycle_msgs/msg/transition.hpp"

#include "rclcpp/exceptions.hpp"
#include "rclcpp/graph_listener.hpp"
#include "rclcpp/logger.hpp"
#include "rclcpp/node.hpp"
#include "rclcpp/node_interfaces/node_base.hpp"
#include "rclcpp/node_interfaces/node_clock.hpp"
#include "rclcpp/node_interfaces/node_graph.hpp"
#include "rclcpp/node_interfaces/node_logging.hpp"
#include "rclcpp/node_interfaces/node_parameters.hpp"
#include "rclcpp/node_interfaces/node_services.hpp"
#include "rclcpp/node_interfaces/node_timers.hpp"
#include "rclcpp/node_interfaces/node_topics.hpp"
#include "rclcpp/node_interfaces/node_waitables.hpp"
#include "rclcpp/parameter_service.hpp"

#include "lifecycle_node_interface_impl.hpp"  // implementation

namespace rclcpp_lifecycle
{

LifecycleNode::LifecycleNode(
  const std::string & node_name,
  const std::string & namespace_,
  bool use_intra_process_comms)
: LifecycleNode(
    node_name,
    namespace_,
    rclcpp::contexts::default_context::get_global_default_context(),
    {},
    {},
    true,
    use_intra_process_comms,
    true)
{}

LifecycleNode::LifecycleNode(
  const std::string & node_name,
  const std::string & namespace_,
  rclcpp::Context::SharedPtr context,
  const std::vector<std::string> & arguments,
  const std::vector<rclcpp::Parameter> & initial_parameters,
  bool use_global_arguments,
  bool use_intra_process_comms,
  bool start_parameter_services)
: node_base_(new rclcpp::node_interfaces::NodeBase(
      node_name, namespace_, context, arguments, use_global_arguments)),
  node_graph_(new rclcpp::node_interfaces::NodeGraph(node_base_.get())),
  node_logging_(new rclcpp::node_interfaces::NodeLogging(node_base_.get())),
  node_timers_(new rclcpp::node_interfaces::NodeTimers(node_base_.get())),
  node_topics_(new rclcpp::node_interfaces::NodeTopics(node_base_.get())),
  node_services_(new rclcpp::node_interfaces::NodeServices(node_base_.get())),
  node_clock_(new rclcpp::node_interfaces::NodeClock(
      node_base_,
      node_topics_,
      node_graph_,
      node_services_,
      node_logging_
    )),
  node_parameters_(new rclcpp::node_interfaces::NodeParameters(
      node_base_,
      node_topics_,
      node_services_,
      node_clock_,
      initial_parameters,
      use_intra_process_comms,
      start_parameter_services
    )),
  node_waitables_(new rclcpp::node_interfaces::NodeWaitables(node_base_.get())),
  use_intra_process_comms_(use_intra_process_comms),
  impl_(new LifecycleNodeInterfaceImpl(node_base_, node_services_))
{
  impl_->init();

  register_on_configure(std::bind(&LifecycleNodeInterface::on_configure, this,
    std::placeholders::_1));
  register_on_cleanup(std::bind(&LifecycleNodeInterface::on_cleanup, this, std::placeholders::_1));
  register_on_shutdown(std::bind(&LifecycleNodeInterface::on_shutdown, this,
    std::placeholders::_1));
  register_on_activate(std::bind(&LifecycleNodeInterface::on_activate, this,
    std::placeholders::_1));
  register_on_deactivate(std::bind(&LifecycleNodeInterface::on_deactivate, this,
    std::placeholders::_1));
  register_on_error(std::bind(&LifecycleNodeInterface::on_error, this, std::placeholders::_1));
}

LifecycleNode::~LifecycleNode()
{}

const char *
LifecycleNode::get_name() const
{
  return node_base_->get_name();
}

const char *
LifecycleNode::get_namespace() const
{
  return node_base_->get_namespace();
}

rclcpp::Logger
LifecycleNode::get_logger() const
{
  return node_logging_->get_logger();
}

rclcpp::callback_group::CallbackGroup::SharedPtr
LifecycleNode::create_callback_group(
  rclcpp::callback_group::CallbackGroupType group_type)
{
  return node_base_->create_callback_group(group_type);
}

bool
LifecycleNode::group_in_node(rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  return node_base_->callback_group_in_node(group);
}

std::vector<rcl_interfaces::msg::SetParametersResult>
LifecycleNode::set_parameters(
  const std::vector<rclcpp::Parameter> & parameters)
{
  return node_parameters_->set_parameters(parameters);
}

rcl_interfaces::msg::SetParametersResult
LifecycleNode::set_parameters_atomically(
  const std::vector<rclcpp::Parameter> & parameters)
{
  return node_parameters_->set_parameters_atomically(parameters);
}

std::vector<rclcpp::Parameter>
LifecycleNode::get_parameters(
  const std::vector<std::string> & names) const
{
  return node_parameters_->get_parameters(names);
}

rclcpp::Parameter
LifecycleNode::get_parameter(const std::string & name) const
{
  return node_parameters_->get_parameter(name);
}

bool LifecycleNode::get_parameter(
  const std::string & name,
  rclcpp::Parameter & parameter) const
{
  return node_parameters_->get_parameter(name, parameter);
}

std::vector<rcl_interfaces::msg::ParameterDescriptor>
LifecycleNode::describe_parameters(
  const std::vector<std::string> & names) const
{
  return node_parameters_->describe_parameters(names);
}

std::vector<uint8_t>
LifecycleNode::get_parameter_types(
  const std::vector<std::string> & names) const
{
  return node_parameters_->get_parameter_types(names);
}

rcl_interfaces::msg::ListParametersResult
LifecycleNode::list_parameters(
  const std::vector<std::string> & prefixes, uint64_t depth) const
{
  return node_parameters_->list_parameters(prefixes, depth);
}

std::vector<std::string>
LifecycleNode::get_node_names() const
{
  return node_graph_->get_node_names();
}

std::map<std::string, std::vector<std::string>>
LifecycleNode::get_topic_names_and_types(bool no_demangle) const
{
  return node_graph_->get_topic_names_and_types(no_demangle);
}

std::map<std::string, std::vector<std::string>>
LifecycleNode::get_service_names_and_types() const
{
  return node_graph_->get_service_names_and_types();
}

size_t
LifecycleNode::count_publishers(const std::string & topic_name) const
{
  return node_graph_->count_publishers(topic_name);
}

size_t
LifecycleNode::count_subscribers(const std::string & topic_name) const
{
  return node_graph_->count_subscribers(topic_name);
}

const std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> &
LifecycleNode::get_callback_groups() const
{
  return node_base_->get_callback_groups();
}

rclcpp::Event::SharedPtr
LifecycleNode::get_graph_event()
{
  return node_graph_->get_graph_event();
}

void
LifecycleNode::wait_for_graph_change(
  rclcpp::Event::SharedPtr event,
  std::chrono::nanoseconds timeout)
{
  node_graph_->wait_for_graph_change(event, timeout);
}

rclcpp::Clock::SharedPtr
LifecycleNode::get_clock()
{
  return node_clock_->get_clock();
}

rclcpp::Time
LifecycleNode::now()
{
  return node_clock_->get_clock()->now();
}

rclcpp::node_interfaces::NodeBaseInterface::SharedPtr
LifecycleNode::get_node_base_interface()
{
  return node_base_;
}

rclcpp::node_interfaces::NodeClockInterface::SharedPtr
LifecycleNode::get_node_clock_interface()
{
  return node_clock_;
}

rclcpp::node_interfaces::NodeGraphInterface::SharedPtr
LifecycleNode::get_node_graph_interface()
{
  return node_graph_;
}

rclcpp::node_interfaces::NodeTimersInterface::SharedPtr
LifecycleNode::get_node_timers_interface()
{
  return node_timers_;
}

rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr
LifecycleNode::get_node_topics_interface()
{
  return node_topics_;
}

rclcpp::node_interfaces::NodeServicesInterface::SharedPtr
LifecycleNode::get_node_services_interface()
{
  return node_services_;
}

rclcpp::node_interfaces::NodeParametersInterface::SharedPtr
LifecycleNode::get_node_parameters_interface()
{
  return node_parameters_;
}

rclcpp::node_interfaces::NodeWaitablesInterface::SharedPtr
LifecycleNode::get_node_waitables_interface()
{
  return node_waitables_;
}

////
bool
LifecycleNode::register_on_configure(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_CONFIGURING, fcn);
}

bool
LifecycleNode::register_on_cleanup(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_CLEANINGUP, fcn);
}

bool
LifecycleNode::register_on_shutdown(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_SHUTTINGDOWN, fcn);
}

bool
LifecycleNode::register_on_activate(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_ACTIVATING, fcn);
}

bool
LifecycleNode::register_on_deactivate(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_DEACTIVATING, fcn);
}

bool
LifecycleNode::register_on_error(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_ERRORPROCESSING, fcn);
}

const State &
LifecycleNode::get_current_state()
{
  return impl_->get_current_state();
}

std::vector<State>
LifecycleNode::get_available_states()
{
  return impl_->get_available_states();
}

std::vector<Transition>
LifecycleNode::get_available_transitions()
{
  return impl_->get_available_transitions();
}

const State &
LifecycleNode::trigger_transition(const Transition & transition)
{
  return trigger_transition(transition.id());
}

const State &
LifecycleNode::trigger_transition(
  const Transition & transition, LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return trigger_transition(transition.id(), cb_return_code);
}

const State &
LifecycleNode::trigger_transition(uint8_t transition_id)
{
  return impl_->trigger_transition(transition_id);
}

const State &
LifecycleNode::trigger_transition(
  uint8_t transition_id, LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(transition_id, cb_return_code);
}

const State &
LifecycleNode::configure()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE);
}

const State &
LifecycleNode::configure(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE, cb_return_code);
}

const State &
LifecycleNode::cleanup()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP);
}

const State &
LifecycleNode::cleanup(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP, cb_return_code);
}

const State &
LifecycleNode::activate()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE);
}

const State &
LifecycleNode::activate(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE, cb_return_code);
}

const State &
LifecycleNode::deactivate()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE);
}

const State &
LifecycleNode::deactivate(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE, cb_return_code);
}

const State &
LifecycleNode::shutdown()
{
  return impl_->trigger_transition(
    rcl_lifecycle_shutdown_label);
}

const State &
LifecycleNode::shutdown(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    rcl_lifecycle_shutdown_label, cb_return_code);
}

void
LifecycleNode::add_publisher_handle(
  std::shared_ptr<rclcpp_lifecycle::LifecyclePublisherInterface> pub)
{
  impl_->add_publisher_handle(pub);
}

void
LifecycleNode::add_timer_handle(std::shared_ptr<rclcpp::TimerBase> timer)
{
  impl_->add_timer_handle(timer);
}

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

#include "rclcpp_lifecycle/lifecycle_node.hpp"

#include <string>
#include <map>
#include <memory>
#include <vector>
#include <utility>

#include "lifecycle_msgs/msg/state.hpp"
#include "lifecycle_msgs/msg/transition.hpp"

#include "rclcpp/exceptions.hpp"
#include "rclcpp/graph_listener.hpp"
#include "rclcpp/logger.hpp"
#include "rclcpp/node.hpp"
#include "rclcpp/node_interfaces/node_base.hpp"
#include "rclcpp/node_interfaces/node_clock.hpp"
#include "rclcpp/node_interfaces/node_graph.hpp"
#include "rclcpp/node_interfaces/node_logging.hpp"
#include "rclcpp/node_interfaces/node_parameters.hpp"
#include "rclcpp/node_interfaces/node_services.hpp"
#include "rclcpp/node_interfaces/node_timers.hpp"
#include "rclcpp/node_interfaces/node_topics.hpp"
#include "rclcpp/node_interfaces/node_waitables.hpp"
#include "rclcpp/parameter_service.hpp"

#include "lifecycle_node_interface_impl.hpp"  // implementation

namespace rclcpp_lifecycle
{

LifecycleNode::LifecycleNode(
  const std::string & node_name,
  const std::string & namespace_,
  bool use_intra_process_comms)
: LifecycleNode(
    node_name,
    namespace_,
    rclcpp::contexts::default_context::get_global_default_context(),
    {},
    {},
    true,
    use_intra_process_comms,
    true)
{}

LifecycleNode::LifecycleNode(
  const std::string & node_name,
  const std::string & namespace_,
  rclcpp::Context::SharedPtr context,
  const std::vector<std::string> & arguments,
  const std::vector<rclcpp::Parameter> & initial_parameters,
  bool use_global_arguments,
  bool use_intra_process_comms,
  bool start_parameter_services)
: node_base_(new rclcpp::node_interfaces::NodeBase(
      node_name, namespace_, context, arguments, use_global_arguments)),
  node_graph_(new rclcpp::node_interfaces::NodeGraph(node_base_.get())),
  node_logging_(new rclcpp::node_interfaces::NodeLogging(node_base_.get())),
  node_timers_(new rclcpp::node_interfaces::NodeTimers(node_base_.get())),
  node_topics_(new rclcpp::node_interfaces::NodeTopics(node_base_.get())),
  node_services_(new rclcpp::node_interfaces::NodeServices(node_base_.get())),
  node_clock_(new rclcpp::node_interfaces::NodeClock(
      node_base_,
      node_topics_,
      node_graph_,
      node_services_,
      node_logging_
    )),
  node_parameters_(new rclcpp::node_interfaces::NodeParameters(
      node_base_,
      node_topics_,
      node_services_,
      node_clock_,
      initial_parameters,
      use_intra_process_comms,
      start_parameter_services
    )),
  node_waitables_(new rclcpp::node_interfaces::NodeWaitables(node_base_.get())),
  use_intra_process_comms_(use_intra_process_comms),
  impl_(new LifecycleNodeInterfaceImpl(node_base_, node_services_))
{
  impl_->init();

  register_on_configure(std::bind(&LifecycleNodeInterface::on_configure, this,
    std::placeholders::_1));
  register_on_cleanup(std::bind(&LifecycleNodeInterface::on_cleanup, this, std::placeholders::_1));
  register_on_shutdown(std::bind(&LifecycleNodeInterface::on_shutdown, this,
    std::placeholders::_1));
  register_on_activate(std::bind(&LifecycleNodeInterface::on_activate, this,
    std::placeholders::_1));
  register_on_deactivate(std::bind(&LifecycleNodeInterface::on_deactivate, this,
    std::placeholders::_1));
  register_on_error(std::bind(&LifecycleNodeInterface::on_error, this, std::placeholders::_1));
}

LifecycleNode::~LifecycleNode()
{}

const char *
LifecycleNode::get_name() const
{
  return node_base_->get_name();
}

const char *
LifecycleNode::get_namespace() const
{
  return node_base_->get_namespace();
}

rclcpp::Logger
LifecycleNode::get_logger() const
{
  return node_logging_->get_logger();
}

rclcpp::callback_group::CallbackGroup::SharedPtr
LifecycleNode::create_callback_group(
  rclcpp::callback_group::CallbackGroupType group_type)
{
  return node_base_->create_callback_group(group_type);
}

bool
LifecycleNode::group_in_node(rclcpp::callback_group::CallbackGroup::SharedPtr group)
{
  return node_base_->callback_group_in_node(group);
}

std::vector<rcl_interfaces::msg::SetParametersResult>
LifecycleNode::set_parameters(
  const std::vector<rclcpp::Parameter> & parameters)
{
  return node_parameters_->set_parameters(parameters);
}

rcl_interfaces::msg::SetParametersResult
LifecycleNode::set_parameters_atomically(
  const std::vector<rclcpp::Parameter> & parameters)
{
  return node_parameters_->set_parameters_atomically(parameters);
}

std::vector<rclcpp::Parameter>
LifecycleNode::get_parameters(
  const std::vector<std::string> & names) const
{
  return node_parameters_->get_parameters(names);
}

rclcpp::Parameter
LifecycleNode::get_parameter(const std::string & name) const
{
  return node_parameters_->get_parameter(name);
}

bool LifecycleNode::get_parameter(
  const std::string & name,
  rclcpp::Parameter & parameter) const
{
  return node_parameters_->get_parameter(name, parameter);
}

std::vector<rcl_interfaces::msg::ParameterDescriptor>
LifecycleNode::describe_parameters(
  const std::vector<std::string> & names) const
{
  return node_parameters_->describe_parameters(names);
}

std::vector<uint8_t>
LifecycleNode::get_parameter_types(
  const std::vector<std::string> & names) const
{
  return node_parameters_->get_parameter_types(names);
}

rcl_interfaces::msg::ListParametersResult
LifecycleNode::list_parameters(
  const std::vector<std::string> & prefixes, uint64_t depth) const
{
  return node_parameters_->list_parameters(prefixes, depth);
}

std::vector<std::string>
LifecycleNode::get_node_names() const
{
  return node_graph_->get_node_names();
}

std::map<std::string, std::vector<std::string>>
LifecycleNode::get_topic_names_and_types(bool no_demangle) const
{
  return node_graph_->get_topic_names_and_types(no_demangle);
}

std::map<std::string, std::vector<std::string>>
LifecycleNode::get_service_names_and_types() const
{
  return node_graph_->get_service_names_and_types();
}

size_t
LifecycleNode::count_publishers(const std::string & topic_name) const
{
  return node_graph_->count_publishers(topic_name);
}

size_t
LifecycleNode::count_subscribers(const std::string & topic_name) const
{
  return node_graph_->count_subscribers(topic_name);
}

const std::vector<rclcpp::callback_group::CallbackGroup::WeakPtr> &
LifecycleNode::get_callback_groups() const
{
  return node_base_->get_callback_groups();
}

rclcpp::Event::SharedPtr
LifecycleNode::get_graph_event()
{
  return node_graph_->get_graph_event();
}

void
LifecycleNode::wait_for_graph_change(
  rclcpp::Event::SharedPtr event,
  std::chrono::nanoseconds timeout)
{
  node_graph_->wait_for_graph_change(event, timeout);
}

rclcpp::Clock::SharedPtr
LifecycleNode::get_clock()
{
  return node_clock_->get_clock();
}

rclcpp::Time
LifecycleNode::now()
{
  return node_clock_->get_clock()->now();
}

rclcpp::node_interfaces::NodeBaseInterface::SharedPtr
LifecycleNode::get_node_base_interface()
{
  return node_base_;
}

rclcpp::node_interfaces::NodeClockInterface::SharedPtr
LifecycleNode::get_node_clock_interface()
{
  return node_clock_;
}

rclcpp::node_interfaces::NodeGraphInterface::SharedPtr
LifecycleNode::get_node_graph_interface()
{
  return node_graph_;
}

rclcpp::node_interfaces::NodeTimersInterface::SharedPtr
LifecycleNode::get_node_timers_interface()
{
  return node_timers_;
}

rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr
LifecycleNode::get_node_topics_interface()
{
  return node_topics_;
}

rclcpp::node_interfaces::NodeServicesInterface::SharedPtr
LifecycleNode::get_node_services_interface()
{
  return node_services_;
}

rclcpp::node_interfaces::NodeParametersInterface::SharedPtr
LifecycleNode::get_node_parameters_interface()
{
  return node_parameters_;
}

rclcpp::node_interfaces::NodeWaitablesInterface::SharedPtr
LifecycleNode::get_node_waitables_interface()
{
  return node_waitables_;
}

////
bool
LifecycleNode::register_on_configure(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_CONFIGURING, fcn);
}

bool
LifecycleNode::register_on_cleanup(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_CLEANINGUP, fcn);
}

bool
LifecycleNode::register_on_shutdown(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_SHUTTINGDOWN, fcn);
}

bool
LifecycleNode::register_on_activate(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_ACTIVATING, fcn);
}

bool
LifecycleNode::register_on_deactivate(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_DEACTIVATING, fcn);
}

bool
LifecycleNode::register_on_error(
  std::function<LifecycleNodeInterface::CallbackReturn(const State &)> fcn)
{
  return impl_->register_callback(
    lifecycle_msgs::msg::State::TRANSITION_STATE_ERRORPROCESSING, fcn);
}

const State &
LifecycleNode::get_current_state()
{
  return impl_->get_current_state();
}

std::vector<State>
LifecycleNode::get_available_states()
{
  return impl_->get_available_states();
}

std::vector<Transition>
LifecycleNode::get_available_transitions()
{
  return impl_->get_available_transitions();
}

const State &
LifecycleNode::trigger_transition(const Transition & transition)
{
  return trigger_transition(transition.id());
}

const State &
LifecycleNode::trigger_transition(
  const Transition & transition, LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return trigger_transition(transition.id(), cb_return_code);
}

const State &
LifecycleNode::trigger_transition(uint8_t transition_id)
{
  return impl_->trigger_transition(transition_id);
}

const State &
LifecycleNode::trigger_transition(
  uint8_t transition_id, LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(transition_id, cb_return_code);
}

const State &
LifecycleNode::configure()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE);
}

const State &
LifecycleNode::configure(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE, cb_return_code);
}

const State &
LifecycleNode::cleanup()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP);
}

const State &
LifecycleNode::cleanup(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_CLEANUP, cb_return_code);
}

const State &
LifecycleNode::activate()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE);
}

const State &
LifecycleNode::activate(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE, cb_return_code);
}

const State &
LifecycleNode::deactivate()
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE);
}

const State &
LifecycleNode::deactivate(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE, cb_return_code);
}

const State &
LifecycleNode::shutdown()
{
  return impl_->trigger_transition(
    rcl_lifecycle_shutdown_label);
}

const State &
LifecycleNode::shutdown(LifecycleNodeInterface::CallbackReturn & cb_return_code)
{
  return impl_->trigger_transition(
    rcl_lifecycle_shutdown_label, cb_return_code);
}

void
LifecycleNode::add_publisher_handle(
  std::shared_ptr<rclcpp_lifecycle::LifecyclePublisherInterface> pub)
{
  impl_->add_publisher_handle(pub);
}

void
LifecycleNode::add_timer_handle(std::shared_ptr<rclcpp::TimerBase> timer)
{
  impl_->add_timer_handle(timer);
}

}  // namespace rclcpp_lifecycle
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2010 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

#include "cachetable.h"
#include <inttypes.h>

/* Test for #2755.  The ft_loader is using too much VM. */
bool verbose=false;

static void test_cachetable_reservation (long size) {
    CACHETABLE ct;
    {
        int r = toku_create_cachetable(&ct, size, ZERO_LSN, NULL);
        assert(r==0);
    }
    {
        uint64_t r0 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r0_bound = size/2 + size/16;
        uint64_t r1 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r1_bound = r0_bound/2;
        uint64_t r2 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r2_bound = r1_bound/2;
        if (verbose) printf("%10ld: r0=%10" PRIu64 " r1=%10" PRIu64 " r2=%10" PRIu64 "\n", size, r0, r1, r2);
        assert(r0 <= r0_bound);
        assert(r1 <= r1_bound);
        assert(r2 <= r2_bound);
        assert(r1 <= r0);
        assert(r2 <= r1);

        long unreservable_part = size * 0.25;
        assert(r0 <= (size - unreservable_part)*0.5);
        assert(r1 <= (size - unreservable_part - r0)*0.5);
        assert(r2 <= (size - unreservable_part - r0 -1)*0.5);
    }
    {
        int r = toku_cachetable_close(&ct);
        assert(r==0);
    }

}

int main (int argc __attribute__((__unused__)), char *argv[] __attribute__((__unused__))) {
    test_cachetable_reservation(1L<<28);
    test_cachetable_reservation(1LL<<33);
    test_cachetable_reservation(3L<<28);
    test_cachetable_reservation((3L<<28) - 107);
    return 0;
}
<commit_msg>closes #5406, fix test<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2010 Tokutek Inc.  All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

#include "test.h"
#include "cachetable.h"
#include <inttypes.h>

/* Test for #2755.  The ft_loader is using too much VM. */
static void test_cachetable_reservation (long size) {
    CACHETABLE ct;
    {
        int r = toku_create_cachetable(&ct, size, ZERO_LSN, NULL);
        assert(r==0);
    }
    {
        uint64_t r0 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r0_bound = size/2 + size/16;
        uint64_t r1 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r1_bound = r0_bound/2;
        uint64_t r2 = toku_cachetable_reserve_memory(ct, 0.5);
        uint64_t r2_bound = r1_bound/2;
        if (verbose) printf("%10ld: r0=%10" PRIu64 " r1=%10" PRIu64 " r2=%10" PRIu64 "\n", size, r0, r1, r2);
        assert(r0 <= r0_bound);
        assert(r1 <= r1_bound);
        assert(r2 <= r2_bound);
        assert(r1 <= r0);
        assert(r2 <= r1);

        long unreservable_part = size * 0.25;
        assert(r0 <= (size - unreservable_part)*0.5);
        assert(r1 <= (size - unreservable_part - r0)*0.5);
        assert(r2 <= (size - unreservable_part - r0 -1)*0.5);
    }
    {
        int r = toku_cachetable_close(&ct);
        assert(r==0);
    }

}

int test_main (int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) {
    test_cachetable_reservation(1L<<28);
    test_cachetable_reservation(1LL<<33);
    test_cachetable_reservation(3L<<28);
    test_cachetable_reservation((3L<<28) - 107);
    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "maemo6tapsensor.h"

char const * const maemo6tapsensor::id("maemo6.tapsensor");
bool maemo6tapsensor::m_initDone = false;

maemo6tapsensor::maemo6tapsensor(QSensor *sensor)
    : maemo6sensorbase(sensor)
{
    const QString sensorName = "tapsensor";
    initSensor<TapSensorChannelInterface>(sensorName, m_initDone);

//    addOutputRange(0, 4, 1); // axes only, no direction
    sensor->setProperty("returnDoubleTapEvents", true); //by default doubles

    if (m_sensorInterface){
        if (!(QObject::connect(m_sensorInterface, SIGNAL(dataAvailable(const Tap&)),
                               this, SLOT(slotDataAvailable(const Tap&)))))
            qWarning() << "Unable to connect "<< sensorName;
    }
    else
        qWarning() << "Unable to initialize "<<sensorName;

    setReading<QTapReading>(&m_reading);
}

void maemo6tapsensor::start(){
    maemo6sensorbase::start();
    QVariant v = sensor()->property("returnDoubleTapEvents");
    m_isDoubleTapSensor =  v.isValid() && v.toBool()? true: false;
    // Set tap type (single/double)
    m_reading.setDoubleTap(m_isDoubleTapSensor);
}

void maemo6tapsensor::slotDataAvailable(const Tap& data)
{

    if (data.type() == TapData::DoubleTap){
        if (!m_isDoubleTapSensor) return;
    }
    else if (m_isDoubleTapSensor) return;

    // Set tap direction
    QTapReading::TapDirection o;
    switch (data.direction()) {
        case TapData::X:         o = QTapReading::X;         break;
        case TapData::Y:         o = QTapReading::Y;         break;
        case TapData::Z:         o = QTapReading::Z;         break;
        case TapData::LeftRight: o = QTapReading::X_Pos;     break;
        case TapData::RightLeft: o = QTapReading::X_Neg;     break;
        case TapData::TopBottom: o = QTapReading::Z_Neg;     break;
        case TapData::BottomTop: o = QTapReading::Z_Pos;     break;
        case TapData::FaceBack:  o = QTapReading::Y_Pos;     break;
        case TapData::BackFace:  o = QTapReading::Y_Neg;     break;
        default:                 o = QTapReading::Undefined;
    }
    m_reading.setTapDirection(o);
    m_reading.setTimestamp(data.tapData().timestamp_);
    newReadingAvailable();
}
<commit_msg>double set as default too early<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "maemo6tapsensor.h"

char const * const maemo6tapsensor::id("maemo6.tapsensor");
bool maemo6tapsensor::m_initDone = false;

maemo6tapsensor::maemo6tapsensor(QSensor *sensor)
    : maemo6sensorbase(sensor)
{
    const QString sensorName = "tapsensor";
    initSensor<TapSensorChannelInterface>(sensorName, m_initDone);

    QVariant v = sensor->property("returnDoubleTapEvents");
    if (!(v.isValid()))
        sensor->setProperty("returnDoubleTapEvents", true); //by default doubles

    m_isDoubleTapSensor =  v.toBool();

    if (m_sensorInterface){
        if (!(QObject::connect(m_sensorInterface, SIGNAL(dataAvailable(const Tap&)),
                               this, SLOT(slotDataAvailable(const Tap&)))))
            qWarning() << "Unable to connect "<< sensorName;
    }
    else
        qWarning() << "Unable to initialize "<<sensorName;

    setReading<QTapReading>(&m_reading);
}

void maemo6tapsensor::start(){

    maemo6sensorbase::start();
    // Set tap type (single/double)
    m_reading.setDoubleTap(m_isDoubleTapSensor);
}

void maemo6tapsensor::slotDataAvailable(const Tap& data)
{

    if (data.type() == TapData::DoubleTap){
        if (!m_isDoubleTapSensor) return;
    }
    else if (m_isDoubleTapSensor) return;

    // Set tap direction
    QTapReading::TapDirection o;
    switch (data.direction()) {
        case TapData::X:         o = QTapReading::X;         break;
        case TapData::Y:         o = QTapReading::Y;         break;
        case TapData::Z:         o = QTapReading::Z;         break;
        case TapData::LeftRight: o = QTapReading::X_Pos;     break;
        case TapData::RightLeft: o = QTapReading::X_Neg;     break;
        case TapData::TopBottom: o = QTapReading::Z_Neg;     break;
        case TapData::BottomTop: o = QTapReading::Z_Pos;     break;
        case TapData::FaceBack:  o = QTapReading::Y_Pos;     break;
        case TapData::BackFace:  o = QTapReading::Y_Neg;     break;
        default:                 o = QTapReading::Undefined;
    }

    m_reading.setTapDirection(o);
    m_reading.setTimestamp(data.tapData().timestamp_);
    newReadingAvailable();
}
<|endoftext|>


<commit_before>#include "ins_sdk.h"

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <gflags/gflags.h>
#include "common/logging.h"

DECLARE_string(cluster_members);
DECLARE_string(ins_cmd);
DECLARE_string(ins_key);
DECLARE_string(ins_value);

using namespace galaxy::ins::sdk;

int main(int argc, char* argv[]) {
    google::ParseCommandLineFlags(&argc, &argv, true);
    std::vector<std::string> members;
    boost::split(members, FLAGS_cluster_members,
                 boost::is_any_of(","), boost::token_compress_on);
    InsSDK sdk(members);
    galaxy::ins::sdk::SDKError ins_err;
    if (FLAGS_ins_cmd == "show") {
        std::vector<ClusterNodeInfo> cluster_info;
        sdk.ShowCluster(&cluster_info);
        std::vector<ClusterNodeInfo>::iterator it;
        std::cout << "server_addr \t term \t last_log_index \t last_log_term"
                  << std::endl
                  << "-------------------------------------------------------"
                  << std::endl;
        for(it = cluster_info.begin(); it != cluster_info.end(); it++ ) {
            std::string s_status = InsSDK::StatusToString(it->status);
            std::cout << it->server_id << "\t" << s_status
                      << "\t" << it->term
                      << "\t" << it->last_log_index
                      << "\t" << it->last_log_term
                      << std::endl;
        }
    }
    if (FLAGS_ins_cmd == "put") {
        std::string key = FLAGS_ins_key;
        std::string value = FLAGS_ins_value;
        LOG(INFO, "key: %s, value: %s", key.c_str(), value.c_str());
        if (sdk.Put(key, value, &ins_err)) {
            LOG(INFO, "put success");
        } else {
            LOG(FATAL, "put failed");
        }
    }

    if (FLAGS_ins_cmd == "delete") {
        std::string key = FLAGS_ins_key;
        LOG(INFO, "key: %s", key.c_str());
        if (sdk.Delete(key, &ins_err)) {
            LOG(INFO, "delete success");
        } else {
            LOG(FATAL, "delete failed");
        }
    }

    if (FLAGS_ins_cmd == "get") {
        std::string key = FLAGS_ins_key;
        std::string value;
        LOG(INFO, "key: %s", key.c_str());
        if (sdk.Get(key, &value, &ins_err)) {
            LOG(INFO, "get success");
            if (ins_err == kOK) {
                printf("value: %s\n", value.c_str());
            } else {
                printf("NOT FOUND\n");
            }
        } else {
            LOG(FATAL, "get failed");
        }
    }

    return 0;
}
<commit_msg>enhance cli format<commit_after>#include "ins_sdk.h"

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <gflags/gflags.h>
#include "common/logging.h"

DECLARE_string(cluster_members);
DECLARE_string(ins_cmd);
DECLARE_string(ins_key);
DECLARE_string(ins_value);

using namespace galaxy::ins::sdk;

int main(int argc, char* argv[]) {
    google::ParseCommandLineFlags(&argc, &argv, true);
    std::vector<std::string> members;
    boost::split(members, FLAGS_cluster_members,
                 boost::is_any_of(","), boost::token_compress_on);
    if (members.size() < 1) {
        LOG(FATAL, "invalid cluster size");
        exit(1);
    }
    InsSDK sdk(members);
    char cli_header[2048] = {'\0'};
    snprintf(cli_header, sizeof(cli_header),
             "%-*s\t%-*s\t%-*s\t%-*s\t%-*s",
             35, "server node",
             10, "role",
             15, "term",
             15, "last_log_index",
             15, "last_log_term");
    std::string header_line;
    header_line.resize(strlen(cli_header) + 8);
    std::fill(header_line.begin(), header_line.end(), '-');
    galaxy::ins::sdk::SDKError ins_err;
    if (FLAGS_ins_cmd == "show") {
        std::vector<ClusterNodeInfo> cluster_info;
        sdk.ShowCluster(&cluster_info);
        std::vector<ClusterNodeInfo>::iterator it;
        std::cout << cli_header
                  << std::endl
                  << header_line
                  << std::endl;
        for(it = cluster_info.begin(); it != cluster_info.end(); it++ ) {
            std::string s_status = InsSDK::StatusToString(it->status);
            char raw_info[1024] = {'\0'};
            snprintf(raw_info, sizeof(raw_info),
                     "%-*s\t%-*s\t%-*ld\t%-*ld\t%-*ld",
                     35, it->server_id.c_str(),
                     10, s_status.c_str(),
                     15, it->term,
                     15, it->last_log_index,
                     15, it->last_log_term);
            std::cout << raw_info
                      << std::endl;
        }
    }
    if (FLAGS_ins_cmd == "put") {
        std::string key = FLAGS_ins_key;
        std::string value = FLAGS_ins_value;
        LOG(INFO, "key: %s, value: %s", key.c_str(), value.c_str());
        if (sdk.Put(key, value, &ins_err)) {
            LOG(INFO, "put success");
        } else {
            LOG(FATAL, "put failed");
        }
    }

    if (FLAGS_ins_cmd == "delete") {
        std::string key = FLAGS_ins_key;
        LOG(INFO, "key: %s", key.c_str());
        if (sdk.Delete(key, &ins_err)) {
            LOG(INFO, "delete success");
        } else {
            LOG(FATAL, "delete failed");
        }
    }

    if (FLAGS_ins_cmd == "get") {
        std::string key = FLAGS_ins_key;
        std::string value;
        LOG(INFO, "key: %s", key.c_str());
        if (sdk.Get(key, &value, &ins_err)) {
            LOG(INFO, "get success");
            if (ins_err == kOK) {
                printf("value: %s\n", value.c_str());
            } else {
                printf("NOT FOUND\n");
            }
        } else {
            LOG(FATAL, "get failed");
        }
    }

    return 0;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkOpenGLCamera.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 <math.h>

#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLCamera.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"
#include "vtkOutputWindow.h"
#include "vtkgluPickMatrix.h"

//------------------------------------------------------------------------------
vtkOpenGLCamera* vtkOpenGLCamera::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLCamera");
  if(ret)
    {
    return (vtkOpenGLCamera*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLCamera;
}

// Implement base class method.
void vtkOpenGLCamera::Render(vtkRenderer *ren)
{
  float aspect[2];
  float *vport;
  int  *size, lowerLeft[2], upperRight[2];
  vtkMatrix4x4 *matrix = vtkMatrix4x4::New();

  // get the bounds of the window
  size = (ren->GetRenderWindow())->GetSize();

  // find out if we should stereo render
  this->Stereo = (ren->GetRenderWindow())->GetStereoRender();
  vport = ren->GetViewport();

  lowerLeft[0] = (int)(vport[0]*size[0] + 0.5);
  lowerLeft[1] = (int)(vport[1]*size[1] + 0.5);
  upperRight[0] = (int)(vport[2]*size[0] + 0.5);
  upperRight[1] = (int)(vport[3]*size[1] + 0.5);
  upperRight[0]--;
  upperRight[1]--;

  // if were on a stereo renderer draw to special parts of screen
  if (this->Stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
        if (this->LeftEye)
          {
          glDrawBuffer(GL_BACK_LEFT);
          }
        else
          {
          glDrawBuffer(GL_BACK_RIGHT);
          }
        break;
      case VTK_STEREO_LEFT:
	this->LeftEye = 1;
	break;
      case VTK_STEREO_RIGHT:
	this->LeftEye = 0;
	break;
      default:
        break;
      }
    }
  else
    {
    if (ren->GetRenderWindow()->GetDoubleBuffer())
      {
      glDrawBuffer(GL_BACK);
      }
    else
      {
      glDrawBuffer(GL_FRONT);
      }
    }

  glViewport(lowerLeft[0],lowerLeft[1],
	     (upperRight[0]-lowerLeft[0]+1),
	     (upperRight[1]-lowerLeft[1]+1));
  glEnable( GL_SCISSOR_TEST );
  glScissor(lowerLeft[0],lowerLeft[1],
	    (upperRight[0]-lowerLeft[0]+1),
	    (upperRight[1]-lowerLeft[1]+1));

  /* for stereo we have to fiddle with aspect */
  aspect[0] = (float)(upperRight[0]-lowerLeft[0]+1)/
    (float)(upperRight[1]-lowerLeft[1]+1);
  aspect[1] = 1.0;

  ren->SetAspect(aspect);

  glMatrixMode( GL_PROJECTION);
  matrix->DeepCopy(this->GetPerspectiveTransformMatrix(aspect[0]/aspect[1],
						       -1,1));
  matrix->Transpose();
  if(ren->GetIsPicking())
    {
    GLint viewport[4];
    glGetIntegerv( GL_VIEWPORT, viewport);
    glLoadIdentity();
    vtkgluPickMatrix(ren->GetPickX(), ren->GetPickY(), 1, 1, viewport);
    glMultMatrixd(matrix->Element[0]);
    }
  else
    {
    // insert camera view transformation
    glLoadMatrixd(matrix->Element[0]);
    }

  // push the model view matrix onto the stack, make sure we
  // adjust the mode first
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  matrix->DeepCopy(this->GetViewTransformMatrix());
  matrix->Transpose();

  // insert camera view transformation
  glMultMatrixd(matrix->Element[0]);

  if ((ren->GetRenderWindow())->GetErase())
    {
    ren->Clear();
    }

  // if we have a stereo renderer, draw other eye next time
  if (this->Stereo)
    {
    if (this->LeftEye)
      {
      this->LeftEye = 0;
      }
    else
      {
      this->LeftEye = 1;
      }
    }

  matrix->Delete();
}
<commit_msg>coordinate fixes<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenGLCamera.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 <math.h>

#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkOpenGLCamera.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"
#include "vtkOutputWindow.h"
#include "vtkgluPickMatrix.h"

//------------------------------------------------------------------------------
vtkOpenGLCamera* vtkOpenGLCamera::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkOpenGLCamera");
  if(ret)
    {
    return (vtkOpenGLCamera*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkOpenGLCamera;
}

// Implement base class method.
void vtkOpenGLCamera::Render(vtkRenderer *ren)
{
  float aspect[2];
  float *vport;
  int  *size, lowerLeft[2], upperRight[2];
  vtkMatrix4x4 *matrix = vtkMatrix4x4::New();

  // get the bounds of the window
  size = (ren->GetRenderWindow())->GetSize();

  // find out if we should stereo render
  this->Stereo = (ren->GetRenderWindow())->GetStereoRender();
  vport = ren->GetViewport();

  float vpu, vpv;
  vpu = vport[0];
  vpv = vport[1];
  ren->NormalizedDisplayToDisplay(vpu,vpv);
  lowerLeft[0] = (int)(vpu+0.5);
  lowerLeft[1] = (int)(vpv+0.5);
  float vpu2, vpv2;
  vpu2 = vport[2];
  vpv2 = vport[3];
  ren->NormalizedDisplayToDisplay(vpu2,vpv2);
  int usize = (int)(vpu2 + 0.5) - lowerLeft[0];
  int vsize = (int)(vpv2 + 0.5) - lowerLeft[1];

  // if were on a stereo renderer draw to special parts of screen
  if (this->Stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
        if (this->LeftEye)
          {
          glDrawBuffer(GL_BACK_LEFT);
          }
        else
          {
          glDrawBuffer(GL_BACK_RIGHT);
          }
        break;
      case VTK_STEREO_LEFT:
	this->LeftEye = 1;
	break;
      case VTK_STEREO_RIGHT:
	this->LeftEye = 0;
	break;
      default:
        break;
      }
    }
  else
    {
    if (ren->GetRenderWindow()->GetDoubleBuffer())
      {
      glDrawBuffer(GL_BACK);
      }
    else
      {
      glDrawBuffer(GL_FRONT);
      }
    }

  glViewport(lowerLeft[0],lowerLeft[1], usize, vsize);
  glEnable( GL_SCISSOR_TEST );
  glScissor(lowerLeft[0],lowerLeft[1], usize, vsize);

  /* for stereo we have to fiddle with aspect */
  aspect[0] = (float)(usize)/(float)(vsize);
  aspect[1] = 1.0;

  ren->SetAspect(aspect);

  glMatrixMode( GL_PROJECTION);
  matrix->DeepCopy(this->GetPerspectiveTransformMatrix(aspect[0]/aspect[1],
						       -1,1));
  matrix->Transpose();
  if(ren->GetIsPicking())
    {
    GLint viewport[4];
    glGetIntegerv( GL_VIEWPORT, viewport);
    glLoadIdentity();
    vtkgluPickMatrix(ren->GetPickX(), ren->GetPickY(), 1, 1, viewport);
    glMultMatrixd(matrix->Element[0]);
    }
  else
    {
    // insert camera view transformation
    glLoadMatrixd(matrix->Element[0]);
    }

  // push the model view matrix onto the stack, make sure we
  // adjust the mode first
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();

  matrix->DeepCopy(this->GetViewTransformMatrix());
  matrix->Transpose();

  // insert camera view transformation
  glMultMatrixd(matrix->Element[0]);

  if ((ren->GetRenderWindow())->GetErase())
    {
    ren->Clear();
    }

  // if we have a stereo renderer, draw other eye next time
  if (this->Stereo)
    {
    if (this->LeftEye)
      {
      this->LeftEye = 0;
      }
    else
      {
      this->LeftEye = 1;
      }
    }

  matrix->Delete();
}
<|endoftext|>