<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 "src/cctz_libc.h"

#include <chrono>
#include <cstdint>
#include <ctime>

namespace cctz {

TimeZoneLibC::TimeZoneLibC(const std::string& name) {
  local_ = (name == "localtime");
  if (!local_) {
    // TODO: Support "UTC-05:00", for example.
    offset_ = 0;
    abbr_ = "UTC";
  }
}

Breakdown TimeZoneLibC::BreakTime(const time_point<seconds64>& tp) const {
  Breakdown bd;
  std::time_t t = ToUnixSeconds(tp);
  std::tm tm;
  if (local_) {
    localtime_r(&t, &tm);
    bd.abbr = tm.tm_zone;
  } else {
    gmtime_r(&t, &tm);
    tm.tm_gmtoff += offset_;
    bd.abbr = abbr_;
  }
  bd.year = tm.tm_year + 1900;
  bd.month = tm.tm_mon + 1;
  bd.day = tm.tm_mday;
  bd.hour = tm.tm_hour;
  bd.minute = tm.tm_min;
  bd.second = tm.tm_sec;
  bd.weekday = (tm.tm_wday ? tm.tm_wday : 7);
  bd.yearday = tm.tm_yday + 1;
  bd.is_dst = tm.tm_isdst;
  bd.offset = tm.tm_gmtoff;
  return bd;
}

namespace {

// Normalize *val so that 0 <= *val < base, returning any carry.
int NormalizeField(int base, int* val, bool* normalized) {
  int carry = *val / base;
  *val %= base;
  if (*val < 0) {
    carry -= 1;
    *val += base;
  }
  if (carry != 0) *normalized = true;
  return carry;
}

bool IsLeap(int64_t year) {
  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

// The month lengths in non-leap and leap years respectively.
const int kDaysPerMonth[2][1+12] = {
  {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

// The number of days in non-leap and leap years respectively.
const int kDaysPerYear[2] = {365, 366};

// Map a (normalized) Y/M/D to the number of days before/after 1970-01-01.
// See http://howardhinnant.github.io/date_algorithms.html#days_from_civil.
std::time_t DayOrdinal(int64_t year, int month, int day) {
  year -= (month <= 2 ? 1 : 0);
  const std::time_t era = (year >= 0 ? year : year - 399) / 400;
  const int yoe = year - era * 400;
  const int doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1;
  const int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  return era * 146097 + doe - 719468;  // shift epoch to 1970-01-01
}

}  // namespace

TimeInfo TimeZoneLibC::MakeTimeInfo(int64_t year, int mon, int day,
                                    int hour, int min, int sec) const {
  bool normalized = false;
  std::time_t t;
  if (local_) {
    // Does not handle SKIPPED/AMBIGUOUS or huge years.
    std::tm tm;
    tm.tm_year = static_cast<int>(year - 1900);
    tm.tm_mon = mon - 1;
    tm.tm_mday = day;
    tm.tm_hour = hour;
    tm.tm_min = min;
    tm.tm_sec = sec;
    tm.tm_isdst = -1;
    t = std::mktime(&tm);
    if (tm.tm_year != year - 1900 || tm.tm_mon != mon - 1 ||
        tm.tm_mday != day || tm.tm_hour != hour ||
        tm.tm_min != min || tm.tm_sec != sec) {
      normalized = true;
    }
  } else {
    min += NormalizeField(60, &sec, &normalized);
    hour += NormalizeField(60, &min, &normalized);
    day += NormalizeField(24, &hour, &normalized);
    mon -= 1;  // months are one-based
    year += NormalizeField(12, &mon, &normalized);
    mon += 1;  // restore [1:12]
    year += (mon > 2 ? 1 : 0);
    int year_len = kDaysPerYear[IsLeap(year)];
    while (day > year_len) {
      day -= year_len;
      year += 1;
      year_len = kDaysPerYear[IsLeap(year)];
    }
    while (day <= 0) {
      year -= 1;
      day += kDaysPerYear[IsLeap(year)];
    }
    year -= (mon > 2 ? 1 : 0);
    bool leap_year = IsLeap(year);
    while (day > kDaysPerMonth[leap_year][mon]) {
      day -= kDaysPerMonth[leap_year][mon];
      if (++mon > 12) {
        mon = 1;
        year += 1;
        leap_year = IsLeap(year);
      }
    }
    t = ((((DayOrdinal(year, mon, day) * 24) + hour) * 60) + min) * 60 + sec;
  }
  TimeInfo ti;
  ti.kind = TimeInfo::Kind::UNIQUE;
  ti.pre = ti.trans = ti.post = FromUnixSeconds(t);
  ti.normalized = normalized;
  return ti;
}

}  // namespace cctz
<commit_msg>Make TimeZoneLibC portable by adding OFFSET(tm) and ABBR(tm).<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 "src/cctz_libc.h"

#include <chrono>
#include <cstdint>
#include <ctime>

// Define OFFSET(tm) and ABBR(tm) for your platform to return the UTC
// offset and zone abbreviation after a call to localtime_r().
#if defined(linux)
# if defined(__USE_BSD)
#  define OFFSET(tm) ((tm).tm_gmtoff)
#  define ABBR(tm)   ((tm).tm_zone)
# else
#  define OFFSET(tm) ((tm).__tm_gmtoff)
#  define ABBR(tm)   ((tm).__tm_zone)
# endif
#elif defined(__APPLE__)
# define OFFSET(tm) ((tm).tm_gmtoff)
# define ABBR(tm)   ((tm).tm_zone)
#elif defined(__sun)
# define OFFSET(tm) ((tm).tm_isdst > 0 ? altzone : timezone)
# define ABBR(tm)   (tzname[(tm).tm_isdst > 0])
#else
# define OFFSET(tm) (timezone + ((tm).tm_isdst > 0 ? 60 * 60 : 0))
# define ABBR(tm)   (tzname[(tm).tm_isdst > 0])
#endif

namespace cctz {

TimeZoneLibC::TimeZoneLibC(const std::string& name) {
  local_ = (name == "localtime");
  if (!local_) {
    // TODO: Support "UTC-05:00", for example.
    offset_ = 0;
    abbr_ = "UTC";
  }
}

Breakdown TimeZoneLibC::BreakTime(const time_point<seconds64>& tp) const {
  Breakdown bd;
  std::time_t t = ToUnixSeconds(tp);
  std::tm tm;
  if (local_) {
    localtime_r(&t, &tm);
    bd.offset = OFFSET(tm);
    bd.abbr = ABBR(tm);
  } else {
    gmtime_r(&t, &tm);
    bd.offset = offset_;
    bd.abbr = abbr_;
  }
  bd.year = tm.tm_year + 1900;
  bd.month = tm.tm_mon + 1;
  bd.day = tm.tm_mday;
  bd.hour = tm.tm_hour;
  bd.minute = tm.tm_min;
  bd.second = tm.tm_sec;
  bd.weekday = (tm.tm_wday ? tm.tm_wday : 7);
  bd.yearday = tm.tm_yday + 1;
  bd.is_dst = tm.tm_isdst > 0;
  return bd;
}

namespace {

// Normalize *val so that 0 <= *val < base, returning any carry.
int NormalizeField(int base, int* val, bool* normalized) {
  int carry = *val / base;
  *val %= base;
  if (*val < 0) {
    carry -= 1;
    *val += base;
  }
  if (carry != 0) *normalized = true;
  return carry;
}

bool IsLeap(int64_t year) {
  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

// The month lengths in non-leap and leap years respectively.
const int kDaysPerMonth[2][1+12] = {
  {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  {-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

// The number of days in non-leap and leap years respectively.
const int kDaysPerYear[2] = {365, 366};

// Map a (normalized) Y/M/D to the number of days before/after 1970-01-01.
// See http://howardhinnant.github.io/date_algorithms.html#days_from_civil.
std::time_t DayOrdinal(int64_t year, int month, int day) {
  year -= (month <= 2 ? 1 : 0);
  const std::time_t era = (year >= 0 ? year : year - 399) / 400;
  const int yoe = year - era * 400;
  const int doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1;
  const int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  return era * 146097 + doe - 719468;  // shift epoch to 1970-01-01
}

}  // namespace

TimeInfo TimeZoneLibC::MakeTimeInfo(int64_t year, int mon, int day,
                                    int hour, int min, int sec) const {
  bool normalized = false;
  std::time_t t;
  if (local_) {
    // Does not handle SKIPPED/AMBIGUOUS or huge years.
    std::tm tm;
    tm.tm_year = static_cast<int>(year - 1900);
    tm.tm_mon = mon - 1;
    tm.tm_mday = day;
    tm.tm_hour = hour;
    tm.tm_min = min;
    tm.tm_sec = sec;
    tm.tm_isdst = -1;
    t = std::mktime(&tm);
    if (tm.tm_year != year - 1900 || tm.tm_mon != mon - 1 ||
        tm.tm_mday != day || tm.tm_hour != hour ||
        tm.tm_min != min || tm.tm_sec != sec) {
      normalized = true;
    }
  } else {
    min += NormalizeField(60, &sec, &normalized);
    hour += NormalizeField(60, &min, &normalized);
    day += NormalizeField(24, &hour, &normalized);
    mon -= 1;  // months are one-based
    year += NormalizeField(12, &mon, &normalized);
    mon += 1;  // restore [1:12]
    year += (mon > 2 ? 1 : 0);
    int year_len = kDaysPerYear[IsLeap(year)];
    while (day > year_len) {
      day -= year_len;
      year += 1;
      year_len = kDaysPerYear[IsLeap(year)];
    }
    while (day <= 0) {
      year -= 1;
      day += kDaysPerYear[IsLeap(year)];
    }
    year -= (mon > 2 ? 1 : 0);
    bool leap_year = IsLeap(year);
    while (day > kDaysPerMonth[leap_year][mon]) {
      day -= kDaysPerMonth[leap_year][mon];
      if (++mon > 12) {
        mon = 1;
        year += 1;
        leap_year = IsLeap(year);
      }
    }
    t = ((((DayOrdinal(year, mon, day) * 24) + hour) * 60) + min) * 60 + sec;
  }
  TimeInfo ti;
  ti.kind = TimeInfo::Kind::UNIQUE;
  ti.pre = ti.trans = ti.post = FromUnixSeconds(t);
  ti.normalized = normalized;
  return ti;
}

}  // namespace cctz
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: sb $ $Date: 2002-12-06 10:48:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  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.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "interact.hxx"

#include "com/sun/star/java/JavaDisabledException.hpp"
#include "com/sun/star/java/JavaVMCreationFailureException.hpp"
#include "com/sun/star/task/XInteractionAbort.hpp"
#include "com/sun/star/task/XInteractionRetry.hpp"
#include "com/sun/star/task/XInteractionContinuation.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/mutex.hxx"

namespace css = com::sun::star;

using stoc_javavm::InteractionRequest;

namespace {

class AbortContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionAbort >
{
public:
    inline AbortContinuation() {}

    virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}

private:
    AbortContinuation(AbortContinuation &); // not implemented
    void operator =(AbortContinuation); // not implemented

    virtual inline ~AbortContinuation() {}
};

}

class InteractionRequest::RetryContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionRetry >
{
public:
    inline RetryContinuation(): m_bSelected(false) {}

    virtual void SAL_CALL select() throw (css::uno::RuntimeException);

    bool isSelected() const;

private:
    RetryContinuation(RetryContinuation &); // not implemented
    void operator =(RetryContinuation); // not implemented

    virtual inline ~RetryContinuation() {}

    mutable osl::Mutex m_aMutex;
    bool m_bSelected;
};

void SAL_CALL InteractionRequest::RetryContinuation::select()
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard aGuard(m_aMutex);
    m_bSelected = true;
}

bool InteractionRequest::RetryContinuation::isSelected() const
{
    osl::MutexGuard aGuard(m_aMutex);
    return m_bSelected;
}

InteractionRequest::InteractionRequest(css::uno::Any const & rRequest):
    m_aRequest(rRequest)
{
    bool bRetry;
#if defined LINUX
    // Only if Java is disabled we allow retry:
    bRetry = m_aRequest.isExtractableTo(
        getCppuType(static_cast< css::java::JavaDisabledException * >(0)));
#else // LINUX
    // If the creation of the JVM failed then do not offer retry, because Java
    // might crash next time:
    bRetry = !m_aRequest.isExtractableTo(
        getCppuType(
            static_cast< css::java::JavaVMCreationFailureException * >(0)));
#endif // LINUX
    m_aContinuations.realloc(bRetry ? 2 : 1);
    m_aContinuations[0] = new AbortContinuation;
    if (bRetry)
    {
        m_xRetryContinuation = new RetryContinuation;
        m_aContinuations[1] = m_xRetryContinuation.get();
    }
}

css::uno::Any SAL_CALL InteractionRequest::getRequest()
    throw (css::uno::RuntimeException)
{
    return m_aRequest;
}

css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations()
    throw (css::uno::RuntimeException)
{
    return m_aContinuations;
}

bool InteractionRequest::retry() const
{
    return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();
}

InteractionRequest::~InteractionRequest()
{}
<commit_msg>INTEGRATION: CWS mh11rc (1.4.50); FILE MERGED 2003/06/06 08:16:55 mh 1.4.50.1: join: from beta2<commit_after>/*************************************************************************
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2003-06-12 11:08:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  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.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "interact.hxx"

#include "com/sun/star/java/JavaDisabledException.hpp"
#include "com/sun/star/java/JavaVMCreationFailureException.hpp"
#include "com/sun/star/task/XInteractionAbort.hpp"
#include "com/sun/star/task/XInteractionRetry.hpp"
#include "com/sun/star/task/XInteractionContinuation.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/mutex.hxx"

namespace css = com::sun::star;

using stoc_javavm::InteractionRequest;

namespace {

class AbortContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionAbort >
{
public:
    inline AbortContinuation() {}

    virtual inline void SAL_CALL select() throw (css::uno::RuntimeException) {}

private:
    AbortContinuation(AbortContinuation &); // not implemented
    void operator =(AbortContinuation); // not implemented

    virtual inline ~AbortContinuation() {}
};

}

class InteractionRequest::RetryContinuation:
    public cppu::WeakImplHelper1< css::task::XInteractionRetry >
{
public:
    inline RetryContinuation(): m_bSelected(false) {}

    virtual void SAL_CALL select() throw (css::uno::RuntimeException);

    bool isSelected() const;

private:
    RetryContinuation(RetryContinuation &); // not implemented
    void operator =(RetryContinuation); // not implemented

    virtual inline ~RetryContinuation() {}

    mutable osl::Mutex m_aMutex;
    bool m_bSelected;
};

void SAL_CALL InteractionRequest::RetryContinuation::select()
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard aGuard(m_aMutex);
    m_bSelected = true;
}

bool InteractionRequest::RetryContinuation::isSelected() const
{
    osl::MutexGuard aGuard(m_aMutex);
    return m_bSelected;
}

InteractionRequest::InteractionRequest(css::uno::Any const & rRequest):
    m_aRequest(rRequest)
{
    bool bRetry;
#if defined LINUX || defined FREEBSD
    // Only if Java is disabled we allow retry:
    bRetry = m_aRequest.isExtractableTo(
        getCppuType(static_cast< css::java::JavaDisabledException * >(0)));
#else // LINUX
    // If the creation of the JVM failed then do not offer retry, because Java
    // might crash next time:
    bRetry = !m_aRequest.isExtractableTo(
        getCppuType(
            static_cast< css::java::JavaVMCreationFailureException * >(0)));
#endif // LINUX
    m_aContinuations.realloc(bRetry ? 2 : 1);
    m_aContinuations[0] = new AbortContinuation;
    if (bRetry)
    {
        m_xRetryContinuation = new RetryContinuation;
        m_aContinuations[1] = m_xRetryContinuation.get();
    }
}

css::uno::Any SAL_CALL InteractionRequest::getRequest()
    throw (css::uno::RuntimeException)
{
    return m_aRequest;
}

css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations()
    throw (css::uno::RuntimeException)
{
    return m_aContinuations;
}

bool InteractionRequest::retry() const
{
    return m_xRetryContinuation.is() && m_xRetryContinuation->isSelected();
}

InteractionRequest::~InteractionRequest()
{}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: interact.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: sb $ $Date: 2002-12-06 10:48:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  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.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if !defined INCLUDED_STOC_JAVAVM_INTERACT_HXX
#define INCLUDED_STOC_JAVAVM_INTERACT_HXX

#include "com/sun/star/task/XInteractionRequest.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "cppuhelper/implbase1.hxx"
#include "rtl/ref.hxx"

namespace com { namespace sun { namespace star { namespace task {
    class XInteractionContinuation;
} } } }

namespace stoc_javavm {

class InteractionRequest:
    public cppu::WeakImplHelper1< com::sun::star::task::XInteractionRequest >
{
public:
    explicit InteractionRequest(com::sun::star::uno::Any const & rRequest);

    virtual com::sun::star::uno::Any SAL_CALL getRequest()
        throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< com::sun::star::uno::Reference<
        com::sun::star::task::XInteractionContinuation > > SAL_CALL
    getContinuations() throw (com::sun::star::uno::RuntimeException);

    bool retry() const;

private:
    class RetryContinuation;

    InteractionRequest(InteractionRequest &); // not implemented
    void operator =(InteractionRequest); // not implemented

    virtual ~InteractionRequest();

    com::sun::star::uno::Any m_aRequest;
    com::sun::star::uno::Sequence< com::sun::star::uno::Reference<
        com::sun::star::task::XInteractionContinuation > > m_aContinuations;
    rtl::Reference< RetryContinuation > m_xRetryContinuation;
};

}

#endif // INCLUDED_STOC_JAVAVM_INTERACT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.188); FILE MERGED 2005/09/05 17:10:55 rt 1.2.188.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: interact.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:58:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#if !defined INCLUDED_STOC_JAVAVM_INTERACT_HXX
#define INCLUDED_STOC_JAVAVM_INTERACT_HXX

#include "com/sun/star/task/XInteractionRequest.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "cppuhelper/implbase1.hxx"
#include "rtl/ref.hxx"

namespace com { namespace sun { namespace star { namespace task {
    class XInteractionContinuation;
} } } }

namespace stoc_javavm {

class InteractionRequest:
    public cppu::WeakImplHelper1< com::sun::star::task::XInteractionRequest >
{
public:
    explicit InteractionRequest(com::sun::star::uno::Any const & rRequest);

    virtual com::sun::star::uno::Any SAL_CALL getRequest()
        throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< com::sun::star::uno::Reference<
        com::sun::star::task::XInteractionContinuation > > SAL_CALL
    getContinuations() throw (com::sun::star::uno::RuntimeException);

    bool retry() const;

private:
    class RetryContinuation;

    InteractionRequest(InteractionRequest &); // not implemented
    void operator =(InteractionRequest); // not implemented

    virtual ~InteractionRequest();

    com::sun::star::uno::Any m_aRequest;
    com::sun::star::uno::Sequence< com::sun::star::uno::Reference<
        com::sun::star::task::XInteractionContinuation > > m_aContinuations;
    rtl::Reference< RetryContinuation > m_xRetryContinuation;
};

}

#endif // INCLUDED_STOC_JAVAVM_INTERACT_HXX
<|endoftext|>


<commit_before><commit_msg>Deserialize UMA flag on histograms moving from renderer to browsers<commit_after><|endoftext|>


<commit_before>// $Id: createSpectrumProcessor.C,v 1.11 2001/06/14 11:37:14 oliver Exp $

#include <BALL/NMR/createSpectrumProcessor.h>
#include <BALL/NMR/shiftModule.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/atom.h>

using namespace std;

namespace BALL
{

	CreateSpectrumProcessor::CreateSpectrumProcessor()
		:	width_(1.0),
			use_averaging_(true),
			use_ignore_table_(true),
			expression_("element(H)")
	{
	}

	CreateSpectrumProcessor::~CreateSpectrumProcessor ()
		throw()
	{
	}

	bool CreateSpectrumProcessor::start()
		throw()
	{
		// clear the contents of the old peak list
		peaklist_.clear();

		return valid_;
	}

	void CreateSpectrumProcessor::init()
		throw()
	{
		valid_ = false;

		// read the contents of the ignore set
		// this hash set contains all quickly exchanging protons
		// -- thos protons are not seen in the spectrum and do
		// thus not produce a paek in the peak list.
		ignore_atoms_.clear();
		Path path;
		String filename = path.find("NMR/ignore_atoms.dat");
		if (filename == "")
		{
			Log.warn() << "CreateSpectrumProcessor::start: could not open atom ignore file NMR/ignore_atoms.dat" << endl;
			return;
		}

		ifstream infile(filename.c_str());
		String name;
		while (infile.good())
		{
			infile >> name;
			if (name != "")
			{
				ignore_atoms_.insert(name);
			}
		}
		infile.close();
		infile.clear();

		// read the list of equivalent protons
		filename = path.find("NMR/equivalent_atoms.dat");
		if (filename == "")
		{
			Log.warn() << "CreateSpectrumProcessor::start: could not open atom equivalency file NMR/equivalent_atoms.dat" << endl;
			return;
		}

		// clear old contents
		equivalency_residues_.clear();
		equivalency_atoms_.clear();

		ifstream eqfile(filename.c_str());
		while (eqfile.good())
		{
			String residue, atoms;
			vector<String> equivalencies;
			eqfile >> residue >> atoms;
			if ((residue != "") && (atoms != ""))
			{
				atoms.split(equivalencies, ",");
				equivalency_residues_.push_back(residue);
				equivalency_atoms_.push_back(equivalencies);
			}
		}
		eqfile.close();

		// initialization successful
		valid_ = true;

		return;
	}

	Processor::Result CreateSpectrumProcessor::operator () (Composite& composite)
		throw()
	{
		// Collect all atoms with assigned chemical shifts
		Atom* atom = dynamic_cast<Atom*>(&composite);
		if (atom != 0)
		{
			if (atom->hasProperty(ShiftModule::PROPERTY__SHIFT))
			{
				float shift = atom->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
				// if the atom is in the ignore table, skip it
				if ((!(ignore_atoms_.has(atom->getFullName())
							 || ignore_atoms_.has("*:" + atom->getName()))
						 || !use_ignore_table_)
						&& (expression_(*atom) == true)
						&& (shift != 0.0))
				{
					Peak1D peak;
					peak.setAtom(atom);
					peak.setPosition(shift);
					peak.setWidth(width_);
					peak.setIntensity(1.0);
					peaklist_.push_back(peak);
				}
			}
		}

		if (use_averaging_ == true)
		{
			// average the shifts of chemically equivalent nuclei
			// in a residue
			Residue* residue = dynamic_cast<Residue*>(&composite);
			if (residue != 0)
			{
				String residue_name = residue->getName();

				for (Position i = 0; i < equivalency_residues_.size(); i++)
				{
					if (residue_name == equivalency_residues_[i])
					{
						float shift = 0.0;
						list<Atom*> atoms;
						for (AtomIterator it = residue->beginAtom(); +it; ++it)
						{
							for (Position j = 0; j < equivalency_atoms_[i].size(); j++)
							{
								if (equivalency_atoms_[i][j] == it->getName())
								{
									atoms.push_back(&*it);
									shift += it->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
									break;
								}
							}
						}
						if (atoms.size() != 0)
						{
							shift /= (float)atoms.size();
							list<Atom*>::const_iterator list_it = atoms.begin();
							for (; list_it != atoms.end(); ++list_it)
							{
								(*list_it)->setProperty(ShiftModule::PROPERTY__SHIFT, shift);
							}
						}
					}
				}
			}
		}

		return Processor::CONTINUE;
	}

	const list<Peak1D>& CreateSpectrumProcessor::getPeakList() const
	{
		return peaklist_;
	}

	void CreateSpectrumProcessor::setWidth(float width)
		throw()
	{
		width_ = width;
	}

	float CreateSpectrumProcessor::getWidth() const
		throw()
	{
		return width_;
	}

	void CreateSpectrumProcessor::enableAveraging(bool flag)
		throw()
	{
		use_averaging_ = flag;
	}

	void CreateSpectrumProcessor::enableIgnoreTable(bool flag)
		throw()
	{
		use_ignore_table_ = flag;
	}

	void CreateSpectrumProcessor::setExpression(const String& expression)
		throw()
	{
		expression_.setExpression(expression);
	}
}	// namespace BALL
<commit_msg>adapted: to PeakList type<commit_after>// $Id: createSpectrumProcessor.C,v 1.12 2001/07/14 23:01:30 oliver Exp $

#include <BALL/NMR/createSpectrumProcessor.h>
#include <BALL/NMR/shiftModule.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/atom.h>

using namespace std;

namespace BALL
{

	CreateSpectrumProcessor::CreateSpectrumProcessor()
		:	width_(1.0),
			use_averaging_(true),
			use_ignore_table_(true),
			expression_("element(H)")
	{
	}

	CreateSpectrumProcessor::~CreateSpectrumProcessor ()
		throw()
	{
	}

	bool CreateSpectrumProcessor::start()
		throw()
	{
		// clear the contents of the old peak list
		peaklist_.clear();

		return valid_;
	}

	void CreateSpectrumProcessor::init()
		throw()
	{
		valid_ = false;

		// read the contents of the ignore set
		// this hash set contains all quickly exchanging protons
		// -- thos protons are not seen in the spectrum and do
		// thus not produce a paek in the peak list.
		ignore_atoms_.clear();
		Path path;
		String filename = path.find("NMR/ignore_atoms.dat");
		if (filename == "")
		{
			Log.warn() << "CreateSpectrumProcessor::start: could not open atom ignore file NMR/ignore_atoms.dat" << endl;
			return;
		}

		ifstream infile(filename.c_str());
		String name;
		while (infile.good())
		{
			infile >> name;
			if (name != "")
			{
				ignore_atoms_.insert(name);
			}
		}
		infile.close();
		infile.clear();

		// read the list of equivalent protons
		filename = path.find("NMR/equivalent_atoms.dat");
		if (filename == "")
		{
			Log.warn() << "CreateSpectrumProcessor::start: could not open atom equivalency file NMR/equivalent_atoms.dat" << endl;
			return;
		}

		// clear old contents
		equivalency_residues_.clear();
		equivalency_atoms_.clear();

		ifstream eqfile(filename.c_str());
		while (eqfile.good())
		{
			String residue, atoms;
			vector<String> equivalencies;
			eqfile >> residue >> atoms;
			if ((residue != "") && (atoms != ""))
			{
				atoms.split(equivalencies, ",");
				equivalency_residues_.push_back(residue);
				equivalency_atoms_.push_back(equivalencies);
			}
		}
		eqfile.close();

		// initialization successful
		valid_ = true;

		return;
	}

	Processor::Result CreateSpectrumProcessor::operator () (Composite& composite)
		throw()
	{
		// Collect all atoms with assigned chemical shifts
		Atom* atom = dynamic_cast<Atom*>(&composite);
		if (atom != 0)
		{
			if (atom->hasProperty(ShiftModule::PROPERTY__SHIFT))
			{
				float shift = atom->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
				// if the atom is in the ignore table, skip it
				if ((!(ignore_atoms_.has(atom->getFullName())
							 || ignore_atoms_.has("*:" + atom->getName()))
						 || !use_ignore_table_)
						&& (expression_(*atom) == true)
						&& (shift != 0.0))
				{
					Peak1D peak;
					peak.setAtom(atom);
					peak.setPosition(shift);
					peak.setWidth(width_);
					peak.setIntensity(1.0);
					peaklist_.push_back(peak);
				}
			}
		}

		if (use_averaging_ == true)
		{
			// average the shifts of chemically equivalent nuclei
			// in a residue
			Residue* residue = dynamic_cast<Residue*>(&composite);
			if (residue != 0)
			{
				String residue_name = residue->getName();

				for (Position i = 0; i < equivalency_residues_.size(); i++)
				{
					if (residue_name == equivalency_residues_[i])
					{
						float shift = 0.0;
						list<Atom*> atoms;
						for (AtomIterator it = residue->beginAtom(); +it; ++it)
						{
							for (Position j = 0; j < equivalency_atoms_[i].size(); j++)
							{
								if (equivalency_atoms_[i][j] == it->getName())
								{
									atoms.push_back(&*it);
									shift += it->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
									break;
								}
							}
						}
						if (atoms.size() != 0)
						{
							shift /= (float)atoms.size();
							list<Atom*>::const_iterator list_it = atoms.begin();
							for (; list_it != atoms.end(); ++list_it)
							{
								(*list_it)->setProperty(ShiftModule::PROPERTY__SHIFT, shift);
							}
						}
					}
				}
			}
		}

		return Processor::CONTINUE;
	}

	const PeakList1D& CreateSpectrumProcessor::getPeakList() const
	{
		return peaklist_;
	}

	void CreateSpectrumProcessor::setWidth(float width)
		throw()
	{
		width_ = width;
	}

	float CreateSpectrumProcessor::getWidth() const
		throw()
	{
		return width_;
	}

	void CreateSpectrumProcessor::enableAveraging(bool flag)
		throw()
	{
		use_averaging_ = flag;
	}

	void CreateSpectrumProcessor::enableIgnoreTable(bool flag)
		throw()
	{
		use_ignore_table_ = flag;
	}

	void CreateSpectrumProcessor::setExpression(const String& expression)
		throw()
	{
		expression_.setExpression(expression);
	}
}	// namespace BALL
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: VRMLRenderer.C,v 1.6.20.1 2007-03-25 21:57:01 oliver Exp $
// modified by Annette Treichel (2008.09.12)
//

#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/VIEW/KERNEL/stage.h>

#include <BALL/VIEW/PRIMITIVES/label.h>
#include <BALL/VIEW/PRIMITIVES/line.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>
#include <BALL/VIEW/PRIMITIVES/point.h>
#include <BALL/VIEW/PRIMITIVES/box.h>
#include <BALL/VIEW/PRIMITIVES/simpleBox.h>
#include <BALL/VIEW/PRIMITIVES/sphere.h>
#include <BALL/VIEW/PRIMITIVES/tube.h>
#include <BALL/VIEW/PRIMITIVES/disc.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredLine.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredTube.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>

#include <BALL/MATHS/surface.h>

using std::endl;

namespace BALL
{
	namespace VIEW
	{

VRMLRenderer::VRMLRenderer()
	throw()
	: Renderer(),
		outfile_(),
		current_indent_(0)
{
}

VRMLRenderer::VRMLRenderer(const String& name)
	throw(Exception::FileNotFound)
	: Renderer(),
		width(600),
		height(600),
		current_indent_(0)
{
	outfile_.open(name, std::ios::out);

	out_("#VRML V2.0 utf8");
	out_("");
}

VRMLRenderer::~VRMLRenderer()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "Destructing object " << (void *)this
			<< " of class " << RTTI::getName<VRMLRenderer>() << std::endl;
	#endif
}

void VRMLRenderer::clear()
	throw()
{
	outfile_.clear();
	current_indent_ = 0;
}

void VRMLRenderer::setFileName(const String& name)
	throw(Exception::FileNotFound)
{
	outfile_.open(name, std::ios::out);
	current_indent_ = 0;

	out_("#VRML V2.0 utf8");
	out_("");
}

String VRMLRenderer::VRMLColorRGBA(const ColorRGBA& input)
	throw()
{
	return
		String((float) input.getRed())   + " " +
		String((float) input.getGreen()) + " " +
		String((float) input.getBlue());
}

String VRMLRenderer::VRMLVector3(Vector3 input)
	throw()
{
	// we convert into the new coordinate system: the camera looks
	// down the negative z axis and sits at (0,0,0)
	/*
	input += origin_;
	input  = rotation_ * input;
	*/
	String output = "";
	output+=String(input.x);
	output+=" ";
	output+=String(input.y);
	output+=" ";
	output+=String(input.z);

	return output;
}

// init must be called right before the rendering starts, since
// we need to fix the camera, light sources, etc...
bool VRMLRenderer::init(const Stage& stage)
	throw()
{
	#ifdef BALL_VIEW_DEBUG_PROCESSORS
		Log.info() << "Start the VRMLRender output..." << std::endl;
	#endif

	stage_ = &stage;
/*
	// Find out the position of the camera.
	const Camera& camera = stage_->getCamera();

	view_point           = camera.getViewPoint();
	Vector3 up_vector    = camera.getLookUpVector();
	Vector3 right_vector = camera.getRightVector();
	Vector3 look_at      = camera.getLookAtPosition();// camera.getLookAtPosition();
*/

	//prepatation for use of sclaing
	scalingUsed = false;

	return true;
}

bool VRMLRenderer::finish()
	throw()
{
	//before finishing we write the scaling if was used
	String infos = "# Biggest Values: (" + (String)(bigX) + "|"+ (String)(bigY) + "|"+ (String)(bigZ) + "); Smallest Values: (" + (String)smallX + "|"+ (String)smallY + "|"+ (String)smallZ +")";
	String scaling = "# Boxsize: " + (String)(bigX - smallX) + " "+ (String)(bigY - smallY) + " "+ (String)(bigZ - smallZ) + "; Volume (unscaled, [mm^3]): "+ String((bigX - smallX)*(bigY - smallY)*(bigZ - smallZ));
	out_(infos);
	out_(scaling);

	outfile_.close();
	current_indent_ = 0;

	return true;
}

void VRMLRenderer::header_(const Vector3& translation, const ColorRGBA& color,
													 const String& rotation)
	throw()
{
	outheader_("Transform {");
 	if (rotation != "")
	{
 		outheader_("rotation " + rotation);
	}
	outheader_("translation " + VRMLVector3(translation));
	outheader_("children [");

	outheader_("Shape {");

	VRMLColor(color);
}

void VRMLRenderer::footer_()
	throw()
{
	current_indent_ --;
	outfinish_("}");
	outfinish_("}");
	outfinish_("]");
	out_("}");
}

void VRMLRenderer::renderSphere_(const Sphere& sphere)
	throw()
{
	header_(sphere.getPosition(), sphere.getColor());
	outheader_("geometry Sphere {");
	out_("radius " + String(sphere.getRadius()));
	footer_();
}

void VRMLRenderer::renderLine_(const Line& miniTube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = miniTube.getVertex2() - miniTube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	header_(miniTube.getVertex1() + v / 2.0, miniTube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String(v.getLength()));
	out_("radius " + String((v.getLength() / 100.0)));
	footer_();
}

void VRMLRenderer::renderTwoColoredLine_(const TwoColoredLine& miniTube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = miniTube.getVertex2() - miniTube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	//erste halbe linie:
	header_(miniTube.getVertex1() + v / 4.0, miniTube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String((v.getLength() / 100.0)));
	footer_();

	//zweite halbe Linie:
	header_(miniTube.getVertex1() + v / (4.0 / 3.0), miniTube.getColor2(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String((v.getLength() / 100.0 )));
	footer_();
}

void VRMLRenderer::renderTube_(const Tube& tube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = tube.getVertex2() - tube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	header_(tube.getVertex1() + v / 2.0, tube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String(v.getLength()));
	out_("radius " + String(tube.getRadius()));
	footer_();
}

void VRMLRenderer::renderTwoColoredTube_(const TwoColoredTube& tube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = tube.getVertex2() - tube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	//erstes halbes rohr:
	header_(tube.getVertex1() + v / 4.0, tube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String(tube.getRadius()));
	footer_();

	//zweites halbes rohr:
	header_(tube.getVertex1() + v / (4.0 / 3.0), tube.getColor2(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String(tube.getRadius()));
	footer_();
}

void VRMLRenderer::VRMLColor(const ColorRGBA& color)
	throw()
{
	outheader_("appearance Appearance {");
	outheader_("material Material {");
	out_("diffuseColor " + VRMLColorRGBA(color));

	out_("shininess 0.5");
	current_indent_ --;
	outfinish_("}");
	outfinish_("}");
}

void VRMLRenderer::renderMesh_(const Mesh& mesh)
	throw()
{
	// so we should let VRMLRay know...
	outheader_("Shape {");
	outheader_("geometry IndexedFaceSet {");
	out_("normalPerVertex TRUE");
	outheader_("coord Coordinate {");
	outheader_("point [");

	// print vertices
	vector<Vector3>::const_iterator itv = mesh.vertex.begin();
	for (; itv != mesh.vertex.end(); itv++)
	{
		String out = VRMLVector3(*itv);
		if (itv != mesh.vertex.end())
		{
			out += ",";
		}
		out_(out);

		//scaling max and min search
		if(scalingUsed)
		{
			//X value:
			if (smallX > (*itv).x)
			{
				smallX = (*itv).x;
			}
			if (bigX < (*itv).x)
			{
				bigX = (*itv).x;
			}

			//Y value:
			if (smallY > (*itv).y)
			{
				smallY = (*itv).y;
			}
			if (bigY < (*itv).y)
			{
				bigY = (*itv).y;
			}

			//Z value:
			if (smallZ > (*itv).z)
			{
				smallZ = (*itv).z;
			}
			if (bigZ < (*itv).z)
			{
				bigZ = (*itv).z;
			}
		}
		else
		{
			//als initiationswerte werden einfach die ersten Koordinaten genommen
			smallX = (*itv).x;
			bigX = (*itv).x;
			smallY = (*itv).y;
			bigY = (*itv).y;
			smallZ = (*itv).z;
			bigZ = (*itv).z;
			scalingUsed = true;
		}
	}
	current_indent_ --;
	outfinish_("]");
	out_("}"); // correct

	// print triangles =====================================
	outheader_("coordIndex [");

	vector<Surface::Triangle>::const_iterator itt = mesh.triangle.begin();
	for (; itt != mesh.triangle.end(); itt++)
	{
  	String out = (String((*itt).v1) + " "
						 + String((*itt).v2) + " "
						 + String((*itt).v3) + ", -1");

		if (itt != mesh.triangle.end())
		{
			out +=  ",";
		}
		out_(out);
	}
	outfinish_("]");

	// print normals =====================================
	//Normals are not needed for printing and increase amount of data therefore I take them away
/*	outheader_("normal Normal {");
	outheader_("vector [");
	itv = mesh.normal.begin();
	for (; itv != mesh.normal.end(); itv++)
	{
		String out = VRMLVector3(*itv);
		if (itv != mesh.normal.end())
		{
			out += ",";
		}
		out_(out);
	}
	outfinish_("]");
	outfinish_("}");
*/
	/*
	outheader_("normalIndex [");
	for (Position i = 0; i < mesh.vertex.size(); i++)
	{
		String si(i);
		out_(si + ", " + si + ", " + si);
	}
	outfinish_("]");
	*/
// print colors ========================================
	outheader_("color Color {");
	outheader_("color [");
	if (mesh.colors.size() == 0)
	{
		out_(VRMLColorRGBA(ColorRGBA(1.,1,1)));
	}
	else
	{
		vector<ColorRGBA>::const_iterator itc = mesh.colors.begin();
		for (; itc != mesh.colors.end(); itc++)
		{
			String out = VRMLColorRGBA(*itc);
			if (itc != mesh.colors.end())
			{
				out += ",";
			}
			out_(out);
		}
	}
	current_indent_ --;
	outfinish_("]");
	out_("}");

	if (mesh.colors.size() > 1)
	{
		outfinish_("colorPerVertex TRUE");
	}
	else
	{
		outfinish_("colorPerVertex FALSE");
	}
	outfinish_("}");
	outfinish_("}");
}

void VRMLRenderer::out_(const String& data)
	throw()
{
	if (current_indent_ < 0)
	{
//   		BALLVIEW_DEBUG
	}
	String out;
	for (Index p=0; p< current_indent_; p++)
	{
		out += " ";
	}
	out += data;
	outfile_ << out << std::endl;
}

} } // namespaces
<commit_msg>Fixed VRML export of one colored meshes<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: VRMLRenderer.C,v 1.6.20.1 2007-03-25 21:57:01 oliver Exp $
// modified by Annette Treichel (2008.09.12)
//

#include <BALL/VIEW/RENDERING/VRMLRenderer.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/VIEW/KERNEL/stage.h>

#include <BALL/VIEW/PRIMITIVES/label.h>
#include <BALL/VIEW/PRIMITIVES/line.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>
#include <BALL/VIEW/PRIMITIVES/point.h>
#include <BALL/VIEW/PRIMITIVES/box.h>
#include <BALL/VIEW/PRIMITIVES/simpleBox.h>
#include <BALL/VIEW/PRIMITIVES/sphere.h>
#include <BALL/VIEW/PRIMITIVES/tube.h>
#include <BALL/VIEW/PRIMITIVES/disc.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredLine.h>
#include <BALL/VIEW/PRIMITIVES/twoColoredTube.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>

#include <BALL/MATHS/surface.h>

using std::endl;

namespace BALL
{
	namespace VIEW
	{

VRMLRenderer::VRMLRenderer()
	throw()
	: Renderer(),
		outfile_(),
		current_indent_(0)
{
}

VRMLRenderer::VRMLRenderer(const String& name)
	throw(Exception::FileNotFound)
	: Renderer(),
		width(600),
		height(600),
		current_indent_(0)
{
	outfile_.open(name, std::ios::out);

	out_("#VRML V2.0 utf8");
	out_("");
}

VRMLRenderer::~VRMLRenderer()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.info() << "Destructing object " << (void *)this
			<< " of class " << RTTI::getName<VRMLRenderer>() << std::endl;
	#endif
}

void VRMLRenderer::clear()
	throw()
{
	outfile_.clear();
	current_indent_ = 0;
}

void VRMLRenderer::setFileName(const String& name)
	throw(Exception::FileNotFound)
{
	outfile_.open(name, std::ios::out);
	current_indent_ = 0;

	out_("#VRML V2.0 utf8");
	out_("");
}

String VRMLRenderer::VRMLColorRGBA(const ColorRGBA& input)
	throw()
{
	return
		String((float) input.getRed())   + " " +
		String((float) input.getGreen()) + " " +
		String((float) input.getBlue());
}

String VRMLRenderer::VRMLVector3(Vector3 input)
	throw()
{
	// we convert into the new coordinate system: the camera looks
	// down the negative z axis and sits at (0,0,0)
	/*
	input += origin_;
	input  = rotation_ * input;
	*/
	String output = "";
	output+=String(input.x);
	output+=" ";
	output+=String(input.y);
	output+=" ";
	output+=String(input.z);

	return output;
}

// init must be called right before the rendering starts, since
// we need to fix the camera, light sources, etc...
bool VRMLRenderer::init(const Stage& stage)
	throw()
{
	#ifdef BALL_VIEW_DEBUG_PROCESSORS
		Log.info() << "Start the VRMLRender output..." << std::endl;
	#endif

	stage_ = &stage;
/*
	// Find out the position of the camera.
	const Camera& camera = stage_->getCamera();

	view_point           = camera.getViewPoint();
	Vector3 up_vector    = camera.getLookUpVector();
	Vector3 right_vector = camera.getRightVector();
	Vector3 look_at      = camera.getLookAtPosition();// camera.getLookAtPosition();
*/

	//prepatation for use of sclaing
	scalingUsed = false;

	return true;
}

bool VRMLRenderer::finish()
	throw()
{
	//before finishing we write the scaling if was used
	String infos = "# Biggest Values: (" + (String)(bigX) + "|"+ (String)(bigY) + "|"+ (String)(bigZ) + "); Smallest Values: (" + (String)smallX + "|"+ (String)smallY + "|"+ (String)smallZ +")";
	String scaling = "# Boxsize: " + (String)(bigX - smallX) + " "+ (String)(bigY - smallY) + " "+ (String)(bigZ - smallZ) + "; Volume (unscaled, [mm^3]): "+ String((bigX - smallX)*(bigY - smallY)*(bigZ - smallZ));
	out_(infos);
	out_(scaling);

	outfile_.close();
	current_indent_ = 0;

	return true;
}

void VRMLRenderer::header_(const Vector3& translation, const ColorRGBA& color,
													 const String& rotation)
	throw()
{
	outheader_("Transform {");
 	if (rotation != "")
	{
 		outheader_("rotation " + rotation);
	}
	outheader_("translation " + VRMLVector3(translation));
	outheader_("children [");

	outheader_("Shape {");

	VRMLColor(color);
}

void VRMLRenderer::footer_()
	throw()
{
	current_indent_ --;
	outfinish_("}");
	outfinish_("}");
	outfinish_("]");
	out_("}");
}

void VRMLRenderer::renderSphere_(const Sphere& sphere)
	throw()
{
	header_(sphere.getPosition(), sphere.getColor());
	outheader_("geometry Sphere {");
	out_("radius " + String(sphere.getRadius()));
	footer_();
}

void VRMLRenderer::renderLine_(const Line& miniTube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = miniTube.getVertex2() - miniTube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	header_(miniTube.getVertex1() + v / 2.0, miniTube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String(v.getLength()));
	out_("radius " + String((v.getLength() / 100.0)));
	footer_();
}

void VRMLRenderer::renderTwoColoredLine_(const TwoColoredLine& miniTube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = miniTube.getVertex2() - miniTube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	//erste halbe linie:
	header_(miniTube.getVertex1() + v / 4.0, miniTube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String((v.getLength() / 100.0)));
	footer_();

	//zweite halbe Linie:
	header_(miniTube.getVertex1() + v / (4.0 / 3.0), miniTube.getColor2(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String((v.getLength() / 100.0 )));
	footer_();
}

void VRMLRenderer::renderTube_(const Tube& tube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = tube.getVertex2() - tube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	header_(tube.getVertex1() + v / 2.0, tube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String(v.getLength()));
	out_("radius " + String(tube.getRadius()));
	footer_();
}

void VRMLRenderer::renderTwoColoredTube_(const TwoColoredTube& tube)
	throw()
{
	static Vector3 default_angle(0,1,0);

	Vector3 v = tube.getVertex2() - tube.getVertex1();

	float f = v.getAngle(default_angle);
	Vector3 a = default_angle % v;

	String r;
	if (!Maths::isZero(a.getSquareLength()))
	{
		a.normalize();
		r = String(a.x) + " " +
				String(a.y) + " " +
				String(a.z) + " ";

		r += String(f);
	}

	//erstes halbes rohr:
	header_(tube.getVertex1() + v / 4.0, tube.getColor(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String(tube.getRadius()));
	footer_();

	//zweites halbes rohr:
	header_(tube.getVertex1() + v / (4.0 / 3.0), tube.getColor2(), r);
	outheader_("geometry Cylinder {");
	out_("height " + String((v.getLength() / 2.0)));
	out_("radius " + String(tube.getRadius()));
	footer_();
}

void VRMLRenderer::VRMLColor(const ColorRGBA& color)
	throw()
{
	outheader_("appearance Appearance {");
	outheader_("material Material {");
	out_("diffuseColor " + VRMLColorRGBA(color));

	out_("shininess 0.5");
	current_indent_ --;
	outfinish_("}");
	outfinish_("}");
}

void VRMLRenderer::renderMesh_(const Mesh& mesh)
	throw()
{
	// so we should let VRMLRay know...
	outheader_("Shape {");
	// if we have no or only a single color, we need an apearance node for the whole mesh
	if (mesh.colors.size() == 0)
	{
		VRMLColor(ColorRGBA(1.,1,1));
	}
	else if (mesh.colors.size() == 1)
	{
		VRMLColor(mesh.colors[0]);
	}

	outheader_("geometry IndexedFaceSet {");
	out_("normalPerVertex TRUE");
	outheader_("coord Coordinate {");
	outheader_("point [");

	// print vertices
	vector<Vector3>::const_iterator itv = mesh.vertex.begin();
	for (; itv != mesh.vertex.end(); itv++)
	{
		String out = VRMLVector3(*itv);
		if (itv != mesh.vertex.end())
		{
			out += ",";
		}
		out_(out);

		//scaling max and min search
		if(scalingUsed)
		{
			//X value:
			if (smallX > (*itv).x)
			{
				smallX = (*itv).x;
			}
			if (bigX < (*itv).x)
			{
				bigX = (*itv).x;
			}

			//Y value:
			if (smallY > (*itv).y)
			{
				smallY = (*itv).y;
			}
			if (bigY < (*itv).y)
			{
				bigY = (*itv).y;
			}

			//Z value:
			if (smallZ > (*itv).z)
			{
				smallZ = (*itv).z;
			}
			if (bigZ < (*itv).z)
			{
				bigZ = (*itv).z;
			}
		}
		else
		{
			//als initiationswerte werden einfach die ersten Koordinaten genommen
			smallX = (*itv).x;
			bigX = (*itv).x;
			smallY = (*itv).y;
			bigY = (*itv).y;
			smallZ = (*itv).z;
			bigZ = (*itv).z;
			scalingUsed = true;
		}
	}
	current_indent_ --;
	outfinish_("]");
	out_("}"); // correct

	// print triangles =====================================
	outheader_("coordIndex [");

	vector<Surface::Triangle>::const_iterator itt = mesh.triangle.begin();
	for (; itt != mesh.triangle.end(); itt++)
	{
  	String out = (String((*itt).v1) + " "
						 + String((*itt).v2) + " "
						 + String((*itt).v3) + ", -1");

		if (itt != mesh.triangle.end())
		{
			out +=  ",";
		}
		out_(out);
	}
	outfinish_("]");

	// print normals =====================================
	//Normals are not needed for printing and increase amount of data therefore I take them away
/*	outheader_("normal Normal {");
	outheader_("vector [");
	itv = mesh.normal.begin();
	for (; itv != mesh.normal.end(); itv++)
	{
		String out = VRMLVector3(*itv);
		if (itv != mesh.normal.end())
		{
			out += ",";
		}
		out_(out);
	}
	outfinish_("]");
	outfinish_("}");
*/
	/*
	outheader_("normalIndex [");
	for (Position i = 0; i < mesh.vertex.size(); i++)
	{
		String si(i);
		out_(si + ", " + si + ", " + si);
	}
	outfinish_("]");
	*/
// print colors ========================================
	outheader_("color Color {");
	outheader_("color [");
	if (mesh.colors.size() > 1)
	{
		vector<ColorRGBA>::const_iterator itc = mesh.colors.begin();
		for (; itc != mesh.colors.end(); itc++)
		{
			String out = VRMLColorRGBA(*itc);
			if (itc != mesh.colors.end())
			{
				out += ",";
			}
			out_(out);
		}
	}
	current_indent_ --;
	outfinish_("]");
	out_("}");

	if (mesh.colors.size() > 1)
	{
		outfinish_("colorPerVertex TRUE");
	}
	else
	{
		outfinish_("colorPerVertex FALSE");
	}
	outfinish_("}");
	outfinish_("}");
}

void VRMLRenderer::out_(const String& data)
	throw()
{
	if (current_indent_ < 0)
	{
//   		BALLVIEW_DEBUG
	}
	String out;
	for (Index p=0; p< current_indent_; p++)
	{
		out += " ";
	}
	out += data;
	outfile_ << out << std::endl;
}

} } // namespaces
<|endoftext|>


<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "autocomplete.h"
#include "type/pt_data.h"
namespace navitia { namespace autocomplete {

void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) {
    for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){
        for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){
            if(admin->level == 8){
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_way(type::PT_Data&, georef::GeoRef &georef) {
    for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){
        for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){
            if (admin->level == 8){
                //georef.fl_way.ac_list.at(it->first).score = georef.fl_admin.ac_list.at(admin->idx).score;
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) {
    //Récupérer le score de son admin du niveau 8 dans le autocomplete: georef.fl_admin
    for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){
        for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){
            if (admin->level == 8){
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_stop_area(type::PT_Data & pt_data){
    //Calculate de maximum stop-point count;
    unsigned int max_score = 0;
    for (navitia::type::StopArea* sa : pt_data.stop_areas){
        max_score = std::max(max_score, sa->stop_point_list.size());
    }

    //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score)
    if (max_score > 0){
        for (auto it = pt_data.stop_area_autocomplete.word_quality_list.begin(); it != pt_data.stop_area_autocomplete.word_quality_list.end(); ++it){
            it->second.score = (pt_data.stop_areas[it->first]->stop_point_list.size() * 100)/max_score;
        }
    }
}

void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) {
    int max_score = 0;
    //Pour chaque stop_point incrémenter le score de son admin de niveau 8 par 1.
    for (navitia::type::StopPoint* sp : pt_data.stop_points){
        for (navitia::georef::Admin * admin : sp->admin_list){
            if (admin->level == 8){
                georef.fl_admin.word_quality_list.at(admin->idx).score++;
            }
        }
    }
    //Calculer le max_score des admins
    for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){
        max_score = ((it->second).score > max_score)?(it->second).score:max_score;
    }

    //Ajuster le score de chaque admin an utilisant le max_score.
    for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){
        (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score;
    }
}

void compute_score_line(type::PT_Data&, georef::GeoRef&) {
}

template<>
void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef,
                   const type::Type_e type) {
    switch(type){
        case type::Type_e::StopArea:
            compute_score_stop_area(pt_data);
            break;
        case type::Type_e::StopPoint:
            compute_score_stop_point(pt_data, georef);
            break;
        case type::Type_e::Line:
            compute_score_line(pt_data, georef);
            break;
        case type::Type_e::Admin:
            compute_score_admin(pt_data, georef);
            break;
        case type::Type_e::Way:
            compute_score_way(pt_data, georef);
            break;
        case type::Type_e::POI:
            compute_score_poi(pt_data, georef);
            break;
        default:
            break;
    }
}

}}
<commit_msg>Autocomplete : Correction after remark.<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "autocomplete.h"
#include "type/pt_data.h"
namespace navitia { namespace autocomplete {

void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) {
    for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){
        for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){
            if(admin->level == 8){
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_way(type::PT_Data&, georef::GeoRef &georef) {
    for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){
        for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){
            if (admin->level == 8){
                //georef.fl_way.ac_list.at(it->first).score = georef.fl_admin.ac_list.at(admin->idx).score;
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) {
    //Récupérer le score de son admin du niveau 8 dans le autocomplete: georef.fl_admin
    for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){
        for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){
            if (admin->level == 8){
                (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score;
            }
        }
    }
}

void compute_score_stop_area(type::PT_Data & pt_data){
    //Calculate de maximum stop-point count;
    size_t max_score = 0;
    for (navitia::type::StopArea* sa : pt_data.stop_areas){
        max_score = std::max(max_score, sa->stop_point_list.size());
    }

    //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score)
    if (max_score > 0){
        for (auto & it : pt_data.stop_area_autocomplete.word_quality_list){
            it.second.score = (pt_data.stop_areas[it.first]->stop_point_list.size() * 100)/max_score;
        }
    }
}

void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) {
    int max_score = 0;
    //Pour chaque stop_point incrémenter le score de son admin de niveau 8 par 1.
    for (navitia::type::StopPoint* sp : pt_data.stop_points){
        for (navitia::georef::Admin * admin : sp->admin_list){
            if (admin->level == 8){
                georef.fl_admin.word_quality_list.at(admin->idx).score++;
            }
        }
    }
    //Calculer le max_score des admins
    for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){
        max_score = ((it->second).score > max_score)?(it->second).score:max_score;
    }

    //Ajuster le score de chaque admin an utilisant le max_score.
    for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){
        (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score;
    }
}

void compute_score_line(type::PT_Data&, georef::GeoRef&) {
}

template<>
void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef,
                   const type::Type_e type) {
    switch(type){
        case type::Type_e::StopArea:
            compute_score_stop_area(pt_data);
            break;
        case type::Type_e::StopPoint:
            compute_score_stop_point(pt_data, georef);
            break;
        case type::Type_e::Line:
            compute_score_line(pt_data, georef);
            break;
        case type::Type_e::Admin:
            compute_score_admin(pt_data, georef);
            break;
        case type::Type_e::Way:
            compute_score_way(pt_data, georef);
            break;
        case type::Type_e::POI:
            compute_score_poi(pt_data, georef);
            break;
        default:
            break;
    }
}

}}
<|endoftext|>


<commit_before>#include <cppassert/details/DebugPrint.hpp>
#include <cppassert/details/StackTrace.hpp>
#include <stdexcept>
#include <memory>
#include <mutex>
#include <cstdlib>
#include <Windows.h>
#include <DbgHelp.h>
#include <strsafe.h>

namespace cppassert
{
    namespace internal
    {

        /**
         * Displays error message related to last occured error
         *
         */
        void DisplayLastError(LPTSTR lpszFunction)
        {
            // Retrieve the system error message for the last-error code

            LPVOID lpMsgBuf;
            LPVOID lpDisplayBuf;
            DWORD dw = GetLastError();

            FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                dw,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR)&lpMsgBuf,
                0, NULL);

            // Display the error message and exit the process

            lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
                (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));

            StringCchPrintf((LPTSTR)lpDisplayBuf,
                LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                TEXT("%s failed with error %d: %s"),
                lpszFunction, dw, lpMsgBuf);

            PrintMessageToStdErr((LPCSTR)lpDisplayBuf);

            LocalFree(lpMsgBuf);
            LocalFree(lpDisplayBuf);
        }

        /**
        * Provides windows implementation of stack trace collection.
        */
        class StackTraceImpl
        {
            StackTraceImpl(const StackTraceImpl &) = delete;
            StackTraceImpl &operator=(const StackTraceImpl &) = delete;
            struct BacktraceSymbol : public StackTrace::StackFrame
            {
                BacktraceSymbol() = default;

                BacktraceSymbol(const void *frameAddr, const char *name)
                {
                    address_ = frameAddr;
                    setSymbol(name);
                }

                void setAddress(const void *frameAddress)
                {
                    address_ = frameAddress;
                }

                void setSymbol(const char *name)
                {
                    if (name && name[0])
                    {
                        strcpy_s(symbolName_, MaxSymbolNameSize, name);
                        symbolName_[MaxSymbolNameSize - 1] = '\0';
                    }
                    else
                    {
                        symbolName_[0] = '\0';
                    }
                    symbol_ = symbolName_;
                }

                enum { MaxSymbolNameSize = MAX_SYM_NAME + 1 };
                char symbolName_[MaxSymbolNameSize];
            };
        public:
            StackTraceImpl()
            {
            }

            ~StackTraceImpl()
            {
            }

            void collect()
            {
                HANDLE              process;
                ULONG               frame;
                PSYMBOL_INFO        symbol;
                DWORD64             displacement;
                PVOID               frames[cFramesSize];
                enum {              MaxNameLen = MAX_SYM_NAME + 1 };
                enum {              BufferSize = sizeof(SYMBOL_INFO)
                                                + MaxNameLen * sizeof(TCHAR) };

                char buffer[BufferSize] = { '\0' };

                symbol = static_cast<PSYMBOL_INFO>(static_cast<void *>(buffer));

                std::memset(symbol, 0, BufferSize);
                std::memset(frames, 0, sizeof(frames));

                symbol->MaxNameLen = MaxNameLen-1;
                symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

                process = GetCurrentProcess();
                displacement = 0;

                symInitialize(process);
                capturedFrames_ = CaptureStackBackTrace(cFramesToSkip
                                            , cFramesSize
                                            , frames
                                            , NULL);

                if (capturedFrames_ > cFramesSize)
                {
                    capturedFrames_ = cFramesSize;
                }

                for (frame = 0; frame<capturedFrames_; frame++)
                {
                    DWORD64 frameAddr = (DWORD64)(frames[frame]);
                    frames_[frame].setAddress(frames[frame]);
                    std::unique_lock<std::mutex> lock(mutex_);
                    if (SymFromAddr(process, frameAddr, &displacement, symbol)
                                    == TRUE)
                    {
                        frames_[frame].setSymbol(symbol->Name);
                    }
                    else
                    {
                        char buffer[512];
                        sprintf_s(buffer, sizeof(buffer)
                                , "Error getting symbol from addr: 0x%016llX 0x%016p\n"
                                , frameAddr
                                , frames[frame]);
                        buffer[sizeof(buffer)-1] = '\0';
                        PrintMessageToStdErr(buffer);
                        DisplayLastError("SymFromAddr");
                    }
                }
            }

            /**
             * Call to this function should
             */
            void symInitialize(HANDLE process)
            {
                std::unique_lock<std::mutex> lock(mutex_);
                static bool symbolsInitialized = false;
                if(symbolsInitialized==false)
                {
                    //should be only called once
                    if (SymInitialize(process, NULL, TRUE) != TRUE)
                    {
                        DisplayLastError("SymInitialize");
                        return;
                    }
                }
                symbolsInitialized = true;
            }

            /**
            * Returns number of captured frames
            * @return number of captured frames
            */
            std::size_t size() const
            {
                return capturedFrames_;
            }

            /**
             * Returns StackFrame at position \p pos. If pos
             * is outside range (0, size()) throws std::out_of_range exception.
             */
            const StackTrace::StackFrame &at(std::uint32_t pos) const
            {
                if (pos<capturedFrames_)
                {
                    return frames_[pos];
                }
                throw std::out_of_range("StackTrace::at(pos) out of range");
            }

        private:
            //all dbhelp library functions are not thread safe
            //thats why we need a mutext to protect calls to
            //them
            static std::mutex mutex_;
            enum
            {
                cFramesToSkip = 2
            };

            enum
            {
                cFramesSize = 1024
            };
            BacktraceSymbol frames_[cFramesSize];
            std::uint32_t capturedFrames_ = 0;
        };

        std::mutex StackTraceImpl::mutex_;

    } //internal
} //asrt

<commit_msg>Added pointer size info<commit_after>#include <cppassert/details/DebugPrint.hpp>
#include <cppassert/details/StackTrace.hpp>
#include <stdexcept>
#include <memory>
#include <mutex>
#include <cstdlib>
#include <Windows.h>
#include <DbgHelp.h>
#include <strsafe.h>

namespace cppassert
{
    namespace internal
    {

        /**
         * Displays error message related to last occured error
         *
         */
        void DisplayLastError(LPTSTR lpszFunction)
        {
            // Retrieve the system error message for the last-error code

            LPVOID lpMsgBuf;
            LPVOID lpDisplayBuf;
            DWORD dw = GetLastError();

            FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                dw,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPTSTR)&lpMsgBuf,
                0, NULL);

            // Display the error message and exit the process

            lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
                (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));

            StringCchPrintf((LPTSTR)lpDisplayBuf,
                LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                TEXT("%s failed with error %d: %s"),
                lpszFunction, dw, lpMsgBuf);

            PrintMessageToStdErr((LPCSTR)lpDisplayBuf);

            LocalFree(lpMsgBuf);
            LocalFree(lpDisplayBuf);
        }

        /**
        * Provides windows implementation of stack trace collection.
        */
        class StackTraceImpl
        {
            StackTraceImpl(const StackTraceImpl &) = delete;
            StackTraceImpl &operator=(const StackTraceImpl &) = delete;
            struct BacktraceSymbol : public StackTrace::StackFrame
            {
                BacktraceSymbol() = default;

                BacktraceSymbol(const void *frameAddr, const char *name)
                {
                    address_ = frameAddr;
                    setSymbol(name);
                }

                void setAddress(const void *frameAddress)
                {
                    address_ = frameAddress;
                }

                void setSymbol(const char *name)
                {
                    if (name && name[0])
                    {
                        strcpy_s(symbolName_, MaxSymbolNameSize, name);
                        symbolName_[MaxSymbolNameSize - 1] = '\0';
                    }
                    else
                    {
                        symbolName_[0] = '\0';
                    }
                    symbol_ = symbolName_;
                }

                enum { MaxSymbolNameSize = MAX_SYM_NAME + 1 };
                char symbolName_[MaxSymbolNameSize];
            };
        public:
            StackTraceImpl()
            {
            }

            ~StackTraceImpl()
            {
            }

            void collect()
            {
                HANDLE              process;
                ULONG               frame;
                PSYMBOL_INFO        symbol;
                DWORD64             displacement;
                PVOID               frames[cFramesSize];
                enum {              MaxNameLen = MAX_SYM_NAME + 1 };
                enum {              BufferSize = sizeof(SYMBOL_INFO)
                                                + MaxNameLen * sizeof(TCHAR) };

                char buffer[BufferSize] = { '\0' };

                symbol = static_cast<PSYMBOL_INFO>(static_cast<void *>(buffer));

                std::memset(symbol, 0, BufferSize);
                std::memset(frames, 0, sizeof(frames));

                symbol->MaxNameLen = MaxNameLen-1;
                symbol->SizeOfStruct = sizeof(SYMBOL_INFO);

                process = GetCurrentProcess();
                displacement = 0;

                symInitialize(process);
                capturedFrames_ = CaptureStackBackTrace(cFramesToSkip
                                            , cFramesSize
                                            , frames
                                            , NULL);

                if (capturedFrames_ > cFramesSize)
                {
                    capturedFrames_ = cFramesSize;
                }

                for (frame = 0; frame<capturedFrames_; frame++)
                {
                    DWORD64 frameAddr = (DWORD64)(frames[frame]);
                    frames_[frame].setAddress(frames[frame]);
                    std::unique_lock<std::mutex> lock(mutex_);
                    if (SymFromAddr(process, frameAddr, &displacement, symbol)
                                    == TRUE)
                    {
                        frames_[frame].setSymbol(symbol->Name);
                    }
                    else
                    {
                        char buffer[512];
                        sprintf_s(buffer, sizeof(buffer)
                                , "Error getting symbol from addr: 0x%016llX 0x%p address size %d\n"
                                , frameAddr
                                , frames[frame]
                                , sizeof(PVOID));
                        buffer[sizeof(buffer)-1] = '\0';
                        PrintMessageToStdErr(buffer);
                        DisplayLastError("SymFromAddr");
                    }
                }
            }

            /**
             * Call to this function should
             */
            void symInitialize(HANDLE process)
            {
                std::unique_lock<std::mutex> lock(mutex_);
                static bool symbolsInitialized = false;
                if(symbolsInitialized==false)
                {
                    //should be only called once
                    if (SymInitialize(process, NULL, TRUE) != TRUE)
                    {
                        DisplayLastError("SymInitialize");
                        return;
                    }
                }
                symbolsInitialized = true;
            }

            /**
            * Returns number of captured frames
            * @return number of captured frames
            */
            std::size_t size() const
            {
                return capturedFrames_;
            }

            /**
             * Returns StackFrame at position \p pos. If pos
             * is outside range (0, size()) throws std::out_of_range exception.
             */
            const StackTrace::StackFrame &at(std::uint32_t pos) const
            {
                if (pos<capturedFrames_)
                {
                    return frames_[pos];
                }
                throw std::out_of_range("StackTrace::at(pos) out of range");
            }

        private:
            //all dbhelp library functions are not thread safe
            //thats why we need a mutext to protect calls to
            //them
            static std::mutex mutex_;
            enum
            {
                cFramesToSkip = 2
            };

            enum
            {
                cFramesSize = 1024
            };
            BacktraceSymbol frames_[cFramesSize];
            std::uint32_t capturedFrames_ = 0;
        };

        std::mutex StackTraceImpl::mutex_;

    } //internal
} //asrt

<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/statistics/LinearTimeMMD.h>
#include <shogun/statistics/MMDKernelSelectionCombMaxL2.h>
#include <shogun/features/streaming/StreamingFeatures.h>
#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/mathematics/Statistics.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(MMDKernelSelectionCombMaxL2, select_kernel)
{
	index_t m=8;
	index_t d=3;
	SGMatrix<float64_t> data(d,2*m);
	for (index_t i=0; i<2*d*m; ++i)
		data.matrix[i]=i;

	/* create data matrix for each features (appended is not supported) */
	SGMatrix<float64_t> data_p(d, m);
	memcpy(&(data_p.matrix[0]), &(data.matrix[0]), sizeof(float64_t)*d*m);

	SGMatrix<float64_t> data_q(d, m);
	memcpy(&(data_q.matrix[0]), &(data.matrix[d*m]), sizeof(float64_t)*d*m);

	/* normalise data to get some reasonable values for Q matrix */
	float64_t max_p=data_p.max_single();
	float64_t max_q=data_q.max_single();

	//SG_SPRINT("%f, %f\n", max_p, max_q);

	for (index_t i=0; i<d*m; ++i)
	{
		data_p.matrix[i]/=max_p;
		data_q.matrix[i]/=max_q;
	}

	//data_p.display_matrix("data_p");
	//data_q.display_matrix("data_q");

	CDenseFeatures<float64_t>* features_p=new CDenseFeatures<float64_t>(data_p);
	CDenseFeatures<float64_t>* features_q=new CDenseFeatures<float64_t>(data_q);

	/* create stremaing features from dense features */
	CStreamingFeatures* streaming_p=
			new CStreamingDenseFeatures<float64_t>(features_p);
	CStreamingFeatures* streaming_q=
			new CStreamingDenseFeatures<float64_t>(features_q);

	/* create kernels with sigmas 2^5 to 2^7 */
	CCombinedKernel* combined_kernel=new CCombinedKernel();
	for (index_t i=5; i<=7; ++i)
	{
		/* shoguns kernel width is different */
		float64_t sigma=CMath::pow(2, i);
		float64_t sq_sigma_twice=sigma*sigma*2;
		combined_kernel->append_kernel(new CGaussianKernel(10, sq_sigma_twice));
	}

	/* create MMD instance */
	CLinearTimeMMD* mmd=new CLinearTimeMMD(combined_kernel, streaming_p,
			streaming_q, m);

	/* kernel selection instance with regularisation term */
	CMMDKernelSelectionCombMaxL2* selection=new CMMDKernelSelectionCombMaxL2(
			mmd, 10E-5);

	/* start streaming features parser */
	streaming_p->start_parser();
	streaming_q->start_parser();

	CKernel* result=selection->select_kernel();
	CCombinedKernel* casted=dynamic_cast<CCombinedKernel*>(result);
	ASSERT(casted);
	SGVector<float64_t> weights=casted->get_subkernel_weights();
	//weights.display_vector("weights");

	/* assert weights against matlab */
//	w_l2 =
//	   0.761798188424313
//	   0.190556119182660
//	   0.047645692393028
	EXPECT_LE(CMath::abs(weights[0]-0.761798188424313), 10E-15);
	EXPECT_LE(CMath::abs(weights[1]-0.190556119182660), 10E-15);
	EXPECT_LE(CMath::abs(weights[2]-0.047645692393028), 10E-15);

	/* start streaming features parser */
	streaming_p->end_parser();
	streaming_q->end_parser();

	SG_UNREF(selection);
	SG_UNREF(result);
}
<commit_msg>made test compile again<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/statistics/LinearTimeMMD.h>
#include <shogun/statistics/MMDKernelSelectionCombMaxL2.h>
#include <shogun/features/streaming/StreamingFeatures.h>
#include <shogun/features/streaming/StreamingDenseFeatures.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/mathematics/Statistics.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(MMDKernelSelectionCombMaxL2, select_kernel)
{
	index_t m=8;
	index_t d=3;
	SGMatrix<float64_t> data(d,2*m);
	for (index_t i=0; i<2*d*m; ++i)
		data.matrix[i]=i;

	/* create data matrix for each features (appended is not supported) */
	SGMatrix<float64_t> data_p(d, m);
	memcpy(&(data_p.matrix[0]), &(data.matrix[0]), sizeof(float64_t)*d*m);

	SGMatrix<float64_t> data_q(d, m);
	memcpy(&(data_q.matrix[0]), &(data.matrix[d*m]), sizeof(float64_t)*d*m);

	/* normalise data to get some reasonable values for Q matrix */
	float64_t max_p=data_p.max_single();
	float64_t max_q=data_q.max_single();

	//SG_SPRINT("%f, %f\n", max_p, max_q);

	for (index_t i=0; i<d*m; ++i)
	{
		data_p.matrix[i]/=max_p;
		data_q.matrix[i]/=max_q;
	}

	//data_p.display_matrix("data_p");
	//data_q.display_matrix("data_q");

	CDenseFeatures<float64_t>* features_p=new CDenseFeatures<float64_t>(data_p);
	CDenseFeatures<float64_t>* features_q=new CDenseFeatures<float64_t>(data_q);

	/* create stremaing features from dense features */
	CStreamingFeatures* streaming_p=
			new CStreamingDenseFeatures<float64_t>(features_p);
	CStreamingFeatures* streaming_q=
			new CStreamingDenseFeatures<float64_t>(features_q);

	/* create kernels with sigmas 2^5 to 2^7 */
	CCombinedKernel* combined_kernel=new CCombinedKernel();
	for (index_t i=5; i<=7; ++i)
	{
		/* shoguns kernel width is different */
		float64_t sigma=CMath::pow(2, i);
		float64_t sq_sigma_twice=sigma*sigma*2;
		combined_kernel->append_kernel(new CGaussianKernel(10, sq_sigma_twice));
	}

	/* create MMD instance */
	CLinearTimeMMD* mmd=new CLinearTimeMMD(combined_kernel, streaming_p,
			streaming_q, m);

	/* kernel selection instance */
	CMMDKernelSelectionCombMaxL2* selection=new CMMDKernelSelectionCombMaxL2(
			mmd);

	/* start streaming features parser */
	streaming_p->start_parser();
	streaming_q->start_parser();

	CKernel* result=selection->select_kernel();
	CCombinedKernel* casted=dynamic_cast<CCombinedKernel*>(result);
	ASSERT(casted);
	SGVector<float64_t> weights=casted->get_subkernel_weights();
	//weights.display_vector("weights");

	/* assert weights against matlab */
//	w_l2 =
//	   0.761798188424313
//	   0.190556119182660
//	   0.047645692393028
	EXPECT_LE(CMath::abs(weights[0]-0.761798188424313), 10E-15);
	EXPECT_LE(CMath::abs(weights[1]-0.190556119182660), 10E-15);
	EXPECT_LE(CMath::abs(weights[2]-0.047645692393028), 10E-15);

	/* start streaming features parser */
	streaming_p->end_parser();
	streaming_q->end_parser();

	SG_UNREF(selection);
	SG_UNREF(result);
}
<|endoftext|>