<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: syshelp.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 11:58:53 $
 *
 *  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
 *
 ************************************************************************/

#ifndef X2C_SYSHELP_HXX
#define X2C_SYSHELP_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <iosfwd>

class Simstr;
template <class XY> class List;

#ifdef WNT
const char   C_sSLASH[] = "\\";
const char   C_cSLASH = '\\';
#elif defined(UNX)
const char   C_sSLASH[] = "/";
const char   C_cSLASH = '/';
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif

enum E_LinkType
{
    lt_nolink = 0,
    lt_idl,
    lt_html
};

void                WriteName(
                        std::ostream &      o_rFile,
                        const Simstr &      i_rIdlDocuBaseDir,
                        const Simstr &      i_rName,
                        E_LinkType          i_eLinkType );

void                WriteStr(
                        std::ostream &      o_rFile,
                        const char *        i_sStr );
void                WriteStr(
                        std::ostream &      o_rFile,
                        const Simstr &      i_sStr );

void                GatherFileNames(
                        List<Simstr> &      o_sFiles,
                        const char *        i_sSrcDirectory );
void                GatherSubDirectories(
                        List<Simstr> &      o_sSubDirectories,
                        const char *        i_sParentdDirectory );

#endif

<commit_msg>INTEGRATION: CWS os2port02 (1.7.40); FILE MERGED 2007/10/04 19:45:25 ydario 1.7.40.1: Issue number: i82034 Submitted by: ydario Reviewed by:  ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: syshelp.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 12:55:47 $
 *
 *  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
 *
 ************************************************************************/

#ifndef X2C_SYSHELP_HXX
#define X2C_SYSHELP_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <iosfwd>

class Simstr;
template <class XY> class List;

#if defined(WNT) || defined(OS2)
const char   C_sSLASH[] = "\\";
const char   C_cSLASH = '\\';
#elif defined(UNX)
const char   C_sSLASH[] = "/";
const char   C_cSLASH = '/';
#else
#error Must run under unix or windows, please define UNX or WNT.
#endif

enum E_LinkType
{
    lt_nolink = 0,
    lt_idl,
    lt_html
};

void                WriteName(
                        std::ostream &      o_rFile,
                        const Simstr &      i_rIdlDocuBaseDir,
                        const Simstr &      i_rName,
                        E_LinkType          i_eLinkType );

void                WriteStr(
                        std::ostream &      o_rFile,
                        const char *        i_sStr );
void                WriteStr(
                        std::ostream &      o_rFile,
                        const Simstr &      i_sStr );

void                GatherFileNames(
                        List<Simstr> &      o_sFiles,
                        const char *        i_sSrcDirectory );
void                GatherSubDirectories(
                        List<Simstr> &      o_sSubDirectories,
                        const char *        i_sParentdDirectory );

#endif

<|endoftext|>


<commit_before><commit_msg>coverity#704111: Unchecked return value<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/file/DimensionFS.hpp>

using namespace std;
using namespace nix::base;

namespace nix {
namespace file {

DimensionType dimensionTypeFromStr(const string &str) {
    if (str == "set") {
        return DimensionType::Set;
    } else if (str == "range") {
        return DimensionType::Range;
    } else if (str == "sample") {
        return DimensionType::Sample;
    } else {
        throw runtime_error("Not a valid dimension name");
    }
}

std::string dimensionTypeToStr(DimensionType dim) {

    //The way this switch + string.empty() checking is
    // done here might seem a bit convoluted, but the
    // idea behind it is:
    // a) have no default case in the switch to get a
    //    compile warning in case a new element is
    //    added to the enum
    // b) still be safe and throw an exception in case
    //    not all enum cases are handled properly

    std::string dimType;

    switch (dim) {
        case DimensionType::Set:
            dimType = "set";
            break;
        case DimensionType::Range:
            dimType = "range";
            break;
        case DimensionType::Sample:
            dimType = "sample";
            break;
    }

    if (dimType.empty()) {
        throw runtime_error("Not a valid dimension type");
    }

    return dimType;
}

shared_ptr<IDimension> openDimensionFS(const string &loc, size_t index, FileMode mode) {
    AttributesFS attr(loc, mode);
    string type_name;
    attr.get("dimension_type", type_name);

    DimensionType type = dimensionTypeFromStr(type_name);
    shared_ptr<IDimension> dim;

    switch (type) {
        case DimensionType::Set:
            dim = make_shared<SetDimensionFS>(loc, index, mode);
            break;
        case DimensionType::Range:
            dim = make_shared<RangeDimensionFS>(loc, index, mode);
            break;
        case DimensionType::Sample:
            dim = make_shared<SampledDimensionFS>(loc, index, mode);
            break;
    }
    return dim;
}

// Implementation of Dimension

DimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)
    : DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)
{
    this->index(index);
}

void DimensionFS::index(size_t index) {
    setAttr("index", index);
}

size_t DimensionFS::index() const {
    size_t idx;
    if (hasAttr("index"))
        getAttr("index", idx);
    return idx;
}

void DimensionFS::setType() {
    if (!hasAttr("dimension_type"))
        setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}

bool DimensionFS::operator==(const DimensionFS &other) const {
    return location() == other.location();
}

bool DimensionFS::operator!=(const DimensionFS &other) const {
    return !(*this == other);
}

DimensionFS::~DimensionFS() {}

//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------

SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
}

SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)
    : SampledDimensionFS(loc, index, mode)
{
    setType();
    this->samplingInterval(sampling_interval);
}

DimensionType SampledDimensionFS::dimensionType() const {
    return DimensionType::Sample;
}

boost::optional<std::string> SampledDimensionFS::label() const {
    boost::optional<std::string> ret;
    string label;
    if (hasAttr("label")) {
        getAttr("label", label);
        ret = label;
    }
    return ret;
}

void SampledDimensionFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    } else {
        setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionFS::label(const none_t t) {
    if (hasAttr("label")) {
        removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> SampledDimensionFS::unit() const {
    boost::optional<std::string> ret;
    string unit;
    if (hasAttr("unit")) {
        getAttr("unit", unit);
        ret = unit;
    }
    return ret;
}

void SampledDimensionFS::unit(const string &unit) {
    if (unit.empty()) {
        throw EmptyString("unit");
    } else {
        setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionFS::unit(const none_t t) {
    if (hasAttr("unit")) {
        removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

double SampledDimensionFS::samplingInterval() const {
    double sampling_interval;
    if (hasAttr("sampling_interval")) {
        getAttr("sampling_interval", sampling_interval);
        return sampling_interval;
    } else {
        throw MissingAttr("sampling_interval");
    }
}

void SampledDimensionFS::samplingInterval(double sampling_interval) {
    setAttr("sampling_interval", sampling_interval);
}

boost::optional<double> SampledDimensionFS::offset() const {
    boost::optional<double> ret;
    double offset = 0;
    if (hasAttr("offset")) {
        getAttr("offset", offset);
        ret = offset;
    }
    return ret;
}

void SampledDimensionFS::offset(double offset) {
    setAttr("offset", offset);
}

void SampledDimensionFS::offset(const none_t t) {
    if (hasAttr("offset")) {
        removeAttr("offset");
    }
}

SampledDimensionFS::~SampledDimensionFS() {}

//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------

SetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
    setType();
}

DimensionType SetDimensionFS::dimensionType() const {
    return DimensionType::Set;
}

vector<string> SetDimensionFS::labels() const {
    vector<string> labels;
    getAttr("labels", labels);
    return labels;
}

void SetDimensionFS::labels(const vector<string> &labels) {
    setAttr("labels", labels);
}

void SetDimensionFS::labels(const none_t t) {
    if (hasAttr("labels")) {
        removeAttr("labels");
    }
}

SetDimensionFS::~SetDimensionFS() {}

//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
}

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector<double> ticks, FileMode mode)
    : RangeDimensionFS(loc, index, mode)
{
    setType();
    this->ticks(ticks);
}

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)
    :RangeDimensionFS(loc, index, mode)
{
    setType();
    // this->group.createLink(array.group(), array.id()); FIXME
}

DimensionType RangeDimensionFS::dimensionType() const {
    return DimensionType::Range;
}

string RangeDimensionFS::redirectGroup() const {
    /*
    Group g;
    if (alias()) {
        string group_name = group.objectName(0);
        g = group.openGroup(group_name, false);
    } else {
        g = group;
    }
    return g;
    */
    return "";
}

boost::optional<std::string> RangeDimensionFS::label() const {
    boost::optional<std::string> ret;
    string label;
    /*
    Group g = redirectGroup();
    bool have_attr = g.getAttr("label", label);
    if (have_attr) {
        ret = label;
    }
    */
    return ret;
}

void RangeDimensionFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    }
    /*
    Group g = redirectGroup();
    g.setAttr("label", label);
    // NOTE: forceUpdatedAt() not possible since not reachable from here
    */
    // FIXME
}

void RangeDimensionFS::label(const none_t t) {
    /*
    Group g = redirectGroup();
    if (g.hasAttr("label")) {
        g.removeAttr("label");
    }
     */
    // FIXME
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> RangeDimensionFS::unit() const {
    boost::optional<std::string> ret;
    string unit;
    /*
    Group g = redirectGroup();
    bool have_attr = g.getAttr("unit", unit);
    if (have_attr) {
        ret = unit;
    }
    */ // FIXME
    return ret;
}

void RangeDimensionFS::unit(const string &unit) {
    if (unit.empty()) {
        throw EmptyString("unit");
    } else {
        // Group g = redirectGroup(); FIXME
        // g.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionFS::unit(const none_t t) {
    // Group g = redirectGroup();
    // if (g.hasAttr("unit")) {
    //     g.removeAttr("unit");
    //  } FIXME
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

bool RangeDimensionFS::alias() const {
    return false;
    // return group.objectCount() > 0 && !group.hasData("ticks");FIXME
}

vector<double> RangeDimensionFS::ticks() const {
    vector<double> ticks;
    /*
    Group g = redirectGroup();
    if (g.hasData("ticks")) {
        g.getData("ticks", ticks);
        return ticks;
    } else if (g.hasData("data")) {
        g.getData("data", ticks);
        return ticks;
    } else {
        throw MissingAttr("ticks");
    }
    */ // FIXME
    return ticks;
}

void RangeDimensionFS::ticks(const vector<double> &ticks) {
    /*
    Group g = redirectGroup();
    if (!alias()) {
        g.setData("ticks", ticks);
    } else if (g.hasData("data")) {
        NDSize extent(1, ticks.size());
        DataSet ds = g.openData("data");
        ds.setExtent(extent);
        ds.write(nix::DataType::Double, extent, ticks.data());
    } else {
        throw MissingAttr("ticks");
    }
    */ //FIXME
}

RangeDimensionFS::~RangeDimensionFS() {}

} // ns nix::file
} // ns nix

<commit_msg>[file_backend/Dimensions] setType always(!) resets the dime type<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/file/DimensionFS.hpp>

using namespace std;
using namespace nix::base;

namespace nix {
namespace file {

DimensionType dimensionTypeFromStr(const string &str) {
    if (str == "set") {
        return DimensionType::Set;
    } else if (str == "range") {
        return DimensionType::Range;
    } else if (str == "sample") {
        return DimensionType::Sample;
    } else {
        throw runtime_error("Not a valid dimension name");
    }
}

std::string dimensionTypeToStr(DimensionType dim) {

    //The way this switch + string.empty() checking is
    // done here might seem a bit convoluted, but the
    // idea behind it is:
    // a) have no default case in the switch to get a
    //    compile warning in case a new element is
    //    added to the enum
    // b) still be safe and throw an exception in case
    //    not all enum cases are handled properly

    std::string dimType;

    switch (dim) {
        case DimensionType::Set:
            dimType = "set";
            break;
        case DimensionType::Range:
            dimType = "range";
            break;
        case DimensionType::Sample:
            dimType = "sample";
            break;
    }

    if (dimType.empty()) {
        throw runtime_error("Not a valid dimension type");
    }

    return dimType;
}

shared_ptr<IDimension> openDimensionFS(const string &loc, size_t index, FileMode mode) {
    AttributesFS attr(loc, mode);
    string type_name;
    attr.get("dimension_type", type_name);

    DimensionType type = dimensionTypeFromStr(type_name);
    shared_ptr<IDimension> dim;

    switch (type) {
        case DimensionType::Set:
            dim = make_shared<SetDimensionFS>(loc, index, mode);
            break;
        case DimensionType::Range:
            dim = make_shared<RangeDimensionFS>(loc, index, mode);
            break;
        case DimensionType::Sample:
            dim = make_shared<SampledDimensionFS>(loc, index, mode);
            break;
    }
    return dim;
}

// Implementation of Dimension

DimensionFS::DimensionFS(const string &loc, size_t index, FileMode mode)
    : DirectoryWithAttributes(loc + boost::filesystem::path::preferred_separator + util::numToStr(index), mode)
{
    this->index(index);
}

void DimensionFS::index(size_t index) {
    setAttr("index", index);
}

size_t DimensionFS::index() const {
    size_t idx;
    if (hasAttr("index"))
        getAttr("index", idx);
    return idx;
}

void DimensionFS::setType() {
    setAttr("dimension_type", dimensionTypeToStr(dimensionType()));
}

bool DimensionFS::operator==(const DimensionFS &other) const {
    return location() == other.location();
}

bool DimensionFS::operator!=(const DimensionFS &other) const {
    return !(*this == other);
}

DimensionFS::~DimensionFS() {}

//--------------------------------------------------------------
// Implementation of SampledDimension
//--------------------------------------------------------------

SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
}

SampledDimensionFS::SampledDimensionFS(const string &loc, size_t index, double sampling_interval, FileMode mode)
    : SampledDimensionFS(loc, index, mode)
{
    setType();
    this->samplingInterval(sampling_interval);
}

DimensionType SampledDimensionFS::dimensionType() const {
    return DimensionType::Sample;
}

boost::optional<std::string> SampledDimensionFS::label() const {
    boost::optional<std::string> ret;
    string label;
    if (hasAttr("label")) {
        getAttr("label", label);
        ret = label;
    }
    return ret;
}

void SampledDimensionFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    } else {
        setAttr("label", label);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionFS::label(const none_t t) {
    if (hasAttr("label")) {
        removeAttr("label");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> SampledDimensionFS::unit() const {
    boost::optional<std::string> ret;
    string unit;
    if (hasAttr("unit")) {
        getAttr("unit", unit);
        ret = unit;
    }
    return ret;
}

void SampledDimensionFS::unit(const string &unit) {
    if (unit.empty()) {
        throw EmptyString("unit");
    } else {
        setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void SampledDimensionFS::unit(const none_t t) {
    if (hasAttr("unit")) {
        removeAttr("unit");
    }
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

double SampledDimensionFS::samplingInterval() const {
    double sampling_interval;
    if (hasAttr("sampling_interval")) {
        getAttr("sampling_interval", sampling_interval);
        return sampling_interval;
    } else {
        throw MissingAttr("sampling_interval");
    }
}

void SampledDimensionFS::samplingInterval(double sampling_interval) {
    setAttr("sampling_interval", sampling_interval);
}

boost::optional<double> SampledDimensionFS::offset() const {
    boost::optional<double> ret;
    double offset = 0;
    if (hasAttr("offset")) {
        getAttr("offset", offset);
        ret = offset;
    }
    return ret;
}

void SampledDimensionFS::offset(double offset) {
    setAttr("offset", offset);
}

void SampledDimensionFS::offset(const none_t t) {
    if (hasAttr("offset")) {
        removeAttr("offset");
    }
}

SampledDimensionFS::~SampledDimensionFS() {}

//--------------------------------------------------------------
// Implementation of SetDimensionHDF5
//--------------------------------------------------------------

SetDimensionFS::SetDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
    setType();
}

DimensionType SetDimensionFS::dimensionType() const {
    return DimensionType::Set;
}

vector<string> SetDimensionFS::labels() const {
    vector<string> labels;
    getAttr("labels", labels);
    return labels;
}

void SetDimensionFS::labels(const vector<string> &labels) {
    setAttr("labels", labels);
}

void SetDimensionFS::labels(const none_t t) {
    if (hasAttr("labels")) {
        removeAttr("labels");
    }
}

SetDimensionFS::~SetDimensionFS() {}

//--------------------------------------------------------------
// Implementation of RangeDimensionHDF5
//--------------------------------------------------------------

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, FileMode mode)
    : DimensionFS(loc, index, mode)
{
}

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, vector<double> ticks, FileMode mode)
    : RangeDimensionFS(loc, index, mode)
{
    setType();
    this->ticks(ticks);
}

RangeDimensionFS::RangeDimensionFS(const string &loc, size_t index, const DataArrayFS &array, FileMode mode)
    :RangeDimensionFS(loc, index, mode)
{
    setType();
    // this->group.createLink(array.group(), array.id()); FIXME
}

DimensionType RangeDimensionFS::dimensionType() const {
    return DimensionType::Range;
}

string RangeDimensionFS::redirectGroup() const {
    /*
    Group g;
    if (alias()) {
        string group_name = group.objectName(0);
        g = group.openGroup(group_name, false);
    } else {
        g = group;
    }
    return g;
    */
    return "";
}

boost::optional<std::string> RangeDimensionFS::label() const {
    boost::optional<std::string> ret;
    string label;
    /*
    Group g = redirectGroup();
    bool have_attr = g.getAttr("label", label);
    if (have_attr) {
        ret = label;
    }
    */
    return ret;
}

void RangeDimensionFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    }
    /*
    Group g = redirectGroup();
    g.setAttr("label", label);
    // NOTE: forceUpdatedAt() not possible since not reachable from here
    */
    // FIXME
}

void RangeDimensionFS::label(const none_t t) {
    /*
    Group g = redirectGroup();
    if (g.hasAttr("label")) {
        g.removeAttr("label");
    }
     */
    // FIXME
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

boost::optional<std::string> RangeDimensionFS::unit() const {
    boost::optional<std::string> ret;
    string unit;
    /*
    Group g = redirectGroup();
    bool have_attr = g.getAttr("unit", unit);
    if (have_attr) {
        ret = unit;
    }
    */ // FIXME
    return ret;
}

void RangeDimensionFS::unit(const string &unit) {
    if (unit.empty()) {
        throw EmptyString("unit");
    } else {
        // Group g = redirectGroup(); FIXME
        // g.setAttr("unit", unit);
        // NOTE: forceUpdatedAt() not possible since not reachable from here
    }
}

void RangeDimensionFS::unit(const none_t t) {
    // Group g = redirectGroup();
    // if (g.hasAttr("unit")) {
    //     g.removeAttr("unit");
    //  } FIXME
    // NOTE: forceUpdatedAt() not possible since not reachable from here
}

bool RangeDimensionFS::alias() const {
    return false;
    // return group.objectCount() > 0 && !group.hasData("ticks");FIXME
}

vector<double> RangeDimensionFS::ticks() const {
    vector<double> ticks;
    /*
    Group g = redirectGroup();
    if (g.hasData("ticks")) {
        g.getData("ticks", ticks);
        return ticks;
    } else if (g.hasData("data")) {
        g.getData("data", ticks);
        return ticks;
    } else {
        throw MissingAttr("ticks");
    }
    */ // FIXME
    return ticks;
}

void RangeDimensionFS::ticks(const vector<double> &ticks) {
    /*
    Group g = redirectGroup();
    if (!alias()) {
        g.setData("ticks", ticks);
    } else if (g.hasData("data")) {
        NDSize extent(1, ticks.size());
        DataSet ds = g.openData("data");
        ds.setExtent(extent);
        ds.write(nix::DataType::Double, extent, ticks.data());
    } else {
        throw MissingAttr("ticks");
    }
    */ //FIXME
}

RangeDimensionFS::~RangeDimensionFS() {}

} // ns nix::file
} // ns nix

<|endoftext|>


<commit_before>#include "ngraph.h"
#include <stdint.h>
#include <iostream>
#include <cstring>
#include <engpar_support.h>
#include "Iterators/PinIterator.h"
#include "Iterators/GraphIterator.h"

namespace agi {

  void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {
    agi::PinIterator* pitr = pins(e);
    agi::GraphVertex* vtx;
    lid_t deg = degree(e);
    for (lid_t i=0;i<deg;i++) {
      vtx = iterate(pitr);
      residence.insert(owner(vtx));
    }
    destroy(pitr);
  }

  wgt_t Ngraph::weight(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    if (isHyperGraph)
      return edge_weights[type][edge_list[type][id]];
    return edge_weights[type][id];
  }

  lid_t Ngraph::localID(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    return id/num_types;
  }

  gid_t Ngraph::globalID(GraphEdge* edge) const {
    if (!isHyperGraph)
      return localID(edge);
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    return edge_unmap[type][id/num_types];
  }

  lid_t Ngraph::u(lid_t e, etype t) const {
    bool found = false;
    lid_t index = 0;
    lid_t bound_low=0;
    lid_t bound_high = numLocalVtxs();
    while (!found) {
      index = (bound_high+bound_low)/2;
      if (degree_list[t][index]<= e&& degree_list[t][index+1]>e)
        found=true;
      else if (degree_list[t][index]<=e)
        bound_low=index;
      else
        bound_high=index;

    }
    return index;
  }
  GraphVertex* Ngraph::u(GraphEdge* edge) const {
    lid_t lid = (uintptr_t)(edge)-1;
    etype type = lid%num_types;
    lid/=num_types;
    lid_t vid = u(lid,type);
    return reinterpret_cast<GraphVertex*>(vid+1);
  }

  GraphVertex* Ngraph::v(GraphEdge* edge) const {
    if (isHyperGraph) {
      fprintf(stderr,"v(edge) not supported in hypergraph mode");
      return NULL;
    }
    if (edge==NULL)
      return NULL;
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1);
  }

  lid_t  Ngraph::degree(GraphEdge* edge) const {
    if (!isHyperGraph)
      return 2;
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    return pin_degree_list[type][id+1]-pin_degree_list[type][id];
  }

  PinIterator* Ngraph::pins(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    if (!isHyperGraph) {
      return new PinIterator(reinterpret_cast<lid_t*>(u(edge)),
                             reinterpret_cast<lid_t*>((char*)(edge_list[type]
                                                              [id]+1)));
    }
    return new PinIterator((pin_list[type]+pin_degree_list[type][id]),
                           pin_list[type]+pin_degree_list[type][id+1]);
  }

  void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) {
    assert(!edge_weights[t]);
    if (wgts.size()==0) {
      edge_weights[t] = new wgt_t[num_local_edges[t]];
      for (gid_t i=0;i<num_local_edges[t];i++)
        edge_weights[t][i]=1;
      return;
    }
    assert(wgts.size()==num_local_edges[t]);
    edge_weights[t] = new wgt_t[num_local_edges[t]];
    memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t));
  }

  //Protected functions

  void Ngraph::makeEdgeArray(etype t, int count) {
    edge_unmap[t] = new gid_t[count];
    edge_weights[t] = new wgt_t[count];
  }

  void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) {
    edge_unmap[t][lid] = gid;
    edge_weights[t][lid] = w;
    edge_mapping[t][gid]=lid;

  }

}
<commit_msg>Whoops... Deleted something that was needed<commit_after>#include "ngraph.h"
#include <stdint.h>
#include <iostream>
#include <cstring>
#include <engpar_support.h>
#include "Iterators/PinIterator.h"
#include "Iterators/GraphIterator.h"

namespace agi {

  void Ngraph::getResidence(GraphEdge* e, Peers& residence) const {
    agi::PinIterator* pitr = pins(e);
    agi::GraphVertex* vtx;
    lid_t deg = degree(e);
    for (lid_t i=0;i<deg;i++) {
      vtx = iterate(pitr);
      residence.insert(owner(vtx));
    }
    destroy(pitr);
  }

  wgt_t Ngraph::weight(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    if (isHyperGraph)
      return edge_weights[type][edge_list[type][id]];
    return edge_weights[type][id];
  }

  lid_t Ngraph::localID(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    return id/num_types;
  }

  gid_t Ngraph::globalID(GraphEdge* edge) const {
    if (!isHyperGraph)
      return localID(edge);
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    return edge_unmap[type][id/num_types];
  }

  lid_t Ngraph::u(lid_t e, etype t) const {
    bool found = false;
    lid_t index = 0;
    lid_t bound_low=0;
    lid_t bound_high = numLocalVtxs();
    while (!found) {
      index = (bound_high+bound_low)/2;
      if (degree_list[t][index]<= e&& degree_list[t][index+1]>e)
        found=true;
      else if (degree_list[t][index]<=e)
        bound_low=index;
      else
        bound_high=index;

    }
    return index;
  }
  GraphVertex* Ngraph::u(GraphEdge* edge) const {
    lid_t lid = (uintptr_t)(edge)-1;
    etype type = lid%num_types;
    lid/=num_types;
    lid_t vid = u(lid,type);
    return reinterpret_cast<GraphVertex*>(vid+1);
  }

  GraphVertex* Ngraph::v(GraphEdge* edge) const {
    if (isHyperGraph) {
      fprintf(stderr,"v(edge) not supported in hypergraph mode");
      return NULL;
    }
    if (edge==NULL)
      return NULL;
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1);
  }

  lid_t  Ngraph::degree(GraphEdge* edge) const {
    if (!isHyperGraph)
      return 2;
    if (edge==NULL)
      return 0;
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    return pin_degree_list[type][id+1]-pin_degree_list[type][id];
  }

  PinIterator* Ngraph::pins(GraphEdge* edge) const {
    uintptr_t id = (uintptr_t)(edge)-1;
    etype type = id%num_types;
    id/=num_types;
    if (!isHyperGraph) {
      return new PinIterator(reinterpret_cast<lid_t*>(u(edge)),
                   reinterpret_cast<lid_t*>((char*)(edge_list[type][id]+1)));
    }
    return new PinIterator((pin_list[type]+pin_degree_list[type][id]),
                           pin_list[type]+pin_degree_list[type][id+1]);
  }

  void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) {
    assert(!edge_weights[t]);
    if (wgts.size()==0) {
      edge_weights[t] = new wgt_t[num_local_edges[t]];
      for (gid_t i=0;i<num_local_edges[t];i++)
        edge_weights[t][i]=1;
      return;
    }
    assert(wgts.size()==num_local_edges[t]);
    edge_weights[t] = new wgt_t[num_local_edges[t]];
    memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t));
  }

  //Protected functions

  void Ngraph::makeEdgeArray(etype t, int count) {
    edge_unmap[t] = new gid_t[count];
    edge_weights[t] = new wgt_t[count];
  }

  void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) {
    edge_unmap[t][lid] = gid;
    edge_weights[t][lid] = w;
    edge_mapping[t][gid]=lid;

  }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shapetransitionfactory.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-10-11 08:45:36 $
 *
 *  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
 *
 ************************************************************************/

#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <canvas/debug.hxx>
#include <transitionfactory.hxx>
#include <transitiontools.hxx>
#include <parametricpolypolygonfactory.hxx>
#include <animationfactory.hxx>
#include <clippingfunctor.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>

#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif

using namespace ::com::sun::star;

namespace presentation {
namespace internal {

/***************************************************
 ***                                             ***
 ***          Shape Transition Effects           ***
 ***                                             ***
 ***************************************************/

namespace {

class ClippingAnimation : public NumberAnimation
{
public:
    ClippingAnimation(
        const ParametricPolyPolygonSharedPtr&   rPolygon,
        const LayerManagerSharedPtr&            rLayerManager,
        const TransitionInfo&                   rTransitionInfo,
        bool                                    bDirectionForward,
        bool                                    bModeIn );

    ~ClippingAnimation();

    // Animation interface
    // -------------------
    virtual void start( const AnimatableShapeSharedPtr&     rShape,
                        const ShapeAttributeLayerSharedPtr& rAttrLayer );
    virtual void end();

    // NumberAnimation interface
    // -----------------------
    virtual bool operator()( double nValue );
    virtual double getUnderlyingValue() const;

private:
    void end_();

    AnimatableShapeSharedPtr           mpShape;
    ShapeAttributeLayerSharedPtr       mpAttrLayer;
    LayerManagerSharedPtr              mpLayerManager;
    ClippingFunctor                    maClippingFunctor;
    bool                               mbSpriteActive;
};

ClippingAnimation::ClippingAnimation(
    const ParametricPolyPolygonSharedPtr&   rPolygon,
    const LayerManagerSharedPtr&            rLayerManager,
    const TransitionInfo&                   rTransitionInfo,
    bool                                    bDirectionForward,
    bool                                    bModeIn ) :
        mpShape(),
        mpAttrLayer(),
        mpLayerManager( rLayerManager ),
        maClippingFunctor( rPolygon,
                           rTransitionInfo,
                           bDirectionForward,
                           bModeIn ),
        mbSpriteActive(false)
{
    ENSURE_AND_THROW(
        rLayerManager.get(),
        "ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}

ClippingAnimation::~ClippingAnimation()
{
    end_();
}

void ClippingAnimation::start( const AnimatableShapeSharedPtr&      rShape,
                               const ShapeAttributeLayerSharedPtr&  rAttrLayer )
{
    OSL_ENSURE( !mpShape.get(),
                "ClippingAnimation::start(): Shape already set" );
    OSL_ENSURE( !mpAttrLayer.get(),
                "ClippingAnimation::start(): Attribute layer already set" );

    mpShape = rShape;
    mpAttrLayer = rAttrLayer;

    ENSURE_AND_THROW( rShape.get(),
                      "ClippingAnimation::start(): Invalid shape" );
    ENSURE_AND_THROW( rAttrLayer.get(),
                      "ClippingAnimation::start(): Invalid attribute layer" );

    mpShape = rShape;
    mpAttrLayer = rAttrLayer;

    if( !mbSpriteActive )
    {
        mpLayerManager->enterAnimationMode( mpShape );
        mbSpriteActive = true;
    }
}

void ClippingAnimation::end()
{
    end_();
}

void ClippingAnimation::end_()
{
    if( mbSpriteActive )
    {
        mbSpriteActive = false;
        mpLayerManager->leaveAnimationMode( mpShape );

        if( mpShape->isUpdateNecessary() )
            mpLayerManager->notifyShapeUpdate( mpShape );
    }
}

bool ClippingAnimation::operator()( double nValue )
{
    ENSURE_AND_RETURN(
        mpAttrLayer.get() && mpShape.get(),
        "ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );

    // set new clip
    mpAttrLayer->setClip( maClippingFunctor( nValue,
                                             mpShape->getUpdateArea().getRange() ) );

    if( mpShape->isUpdateNecessary() )
        mpLayerManager->notifyShapeUpdate( mpShape );

    return true;
}

double ClippingAnimation::getUnderlyingValue() const
{
    ENSURE_AND_THROW(
        mpAttrLayer.get(),
        "ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );

    return 0.0;     // though this should be used in concert with
                    // ActivitiesFactory::createSimpleActivity, better
                    // explicitely name our start value.
                    // Permissible range for operator() above is [0,1]
}

} // anon namespace

AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
    const ActivitiesFactory::CommonParameters&          rParms,
    const AnimatableShapeSharedPtr&                     rShape,
    const LayerManagerSharedPtr&                        rLayerManager,
    uno::Reference< animations::XTransitionFilter > const& xTransition )
{
    return createShapeTransition( rParms,
                                  rShape,
                                  rLayerManager,
                                  xTransition,
                                  xTransition->getTransition(),
                                  xTransition->getSubtype() );
}

AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
    const ActivitiesFactory::CommonParameters&              rParms,
    const AnimatableShapeSharedPtr&                         rShape,
    const LayerManagerSharedPtr&                            rLayerManager,
    ::com::sun::star::uno::Reference<
        ::com::sun::star::animations::XTransitionFilter > const& xTransition,
    sal_Int16                                               nType,
    sal_Int16                                               nSubType )
{
    ENSURE_AND_THROW(
        xTransition.is(),
        "TransitionFactory::createShapeTransition(): Invalid XTransition" );

    const TransitionInfo* pTransitionInfo(
        getTransitionInfo( nType, nSubType ) );

    AnimationActivitySharedPtr pGeneratedActivity;
    if( pTransitionInfo != NULL )
    {
        switch( pTransitionInfo->meTransitionClass )
        {
            default:
            case TransitionInfo::TRANSITION_INVALID:
                OSL_ENSURE( false,
                            "TransitionFactory::createShapeTransition(): Invalid transition type. "
                            "Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
                return AnimationActivitySharedPtr();

            case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
            {
                // generate parametric poly-polygon
                ParametricPolyPolygonSharedPtr pPoly(
                    ParametricPolyPolygonFactory::createClipPolyPolygon(
                        nType, nSubType ) );

                // create a clip activity from that
                pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                    rParms,
                    NumberAnimationSharedPtr(
                        new ClippingAnimation(
                            pPoly,
                            rLayerManager,
                            *pTransitionInfo,
                            xTransition->getDirection(),
                            xTransition->getMode() ) ),
                    true );
            }
            break;

            case TransitionInfo::TRANSITION_SPECIAL:
            {
                switch( nType )
                {
                    case animations::TransitionType::RANDOM:
                    {
                        // select randomly one of the effects from the
                        // TransitionFactoryTable

                        const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );

                        ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
                                          "TransitionFactory::createShapeTransition(): Got invalid random transition info" );

                        ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
                                          "TransitionFactory::createShapeTransition(): Got random again for random input!" );

                        // and recurse
                        pGeneratedActivity = createShapeTransition( rParms,
                                                                    rShape,
                                                                    rLayerManager,
                                                                    xTransition,
                                                                    pRandomTransitionInfo->mnTransitionType,
                                                                    pRandomTransitionInfo->mnTransitionSubType );
                    }
                    break;

                    // TODO(F3): Implement slidewipe for shape
                    case animations::TransitionType::SLIDEWIPE:
                    {
                        sal_Int16 nBarWipeSubType(0);
                        bool      bDirectionForward(true);

                        // map slidewipe to BARWIPE, for now
                        switch( nSubType )
                        {
                            case animations::TransitionSubType::FROMLEFT:
                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
                                bDirectionForward = true;
                                break;

                            case animations::TransitionSubType::FROMRIGHT:
                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
                                bDirectionForward = false;
                                break;

                            case animations::TransitionSubType::FROMTOP:
                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
                                bDirectionForward = true;
                                break;

                            case animations::TransitionSubType::FROMBOTTOM:
                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
                                bDirectionForward = false;
                                break;

                            default:
                                ENSURE_AND_THROW( false,
                                                  "TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
                                break;
                        }

                        // generate parametric poly-polygon
                        ParametricPolyPolygonSharedPtr pPoly(
                            ParametricPolyPolygonFactory::createClipPolyPolygon(
                                animations::TransitionType::BARWIPE,
                                nBarWipeSubType ) );

                        // create a clip activity from that
                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                            rParms,
                            NumberAnimationSharedPtr(
                                new ClippingAnimation(
                                    pPoly,
                                    rLayerManager,
                                    *getTransitionInfo( animations::TransitionType::BARWIPE,
                                                        nBarWipeSubType ),
                                    bDirectionForward,
                                    xTransition->getMode() ) ),
                            true );
                    }
                    break;

                    default:
                    {
                        // TODO(F1): Check whether there's anything left, anyway,
                        // for _shape_ transitions. AFAIK, there are no special
                        // effects for shapes...

                        // for now, map all to fade effect
                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                            rParms,
                            AnimationFactory::createNumberPropertyAnimation(
                                ::rtl::OUString(
                                    RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
                                rShape,
                                rLayerManager ),
                            xTransition->getMode() );
                    }
                    break;
                }
            }
            break;
        }
    }

    if( !pGeneratedActivity.get() )
    {
        // No animation generated, maybe no table entry for given
        // transition?
        OSL_TRACE(
            "TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
            "combination encountered",
            xTransition->getTransition(),
            xTransition->getSubtype() );
        OSL_ENSURE(
            false,
            "TransitionFactory::createShapeTransition(): Unknown type/subtype "
            "combination encountered" );
    }

    return pGeneratedActivity;
}

}
}
<commit_msg>INTEGRATION: CWS canvas02 (1.2.34); FILE MERGED 2005/10/17 12:21:07 thb 1.2.34.3: RESYNC: (1.3-1.4); FILE MERGED 2005/10/09 04:21:18 thb 1.2.34.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/01 14:01:29 thb 1.2.34.1: #122302# Using new Shape::getDOMBounds() method to determine size of the clip polygon, instead of the former getUpdateArea(). This is because, the sprite clip is transformed by the sprite transformation, which in turn contains the _full_ shape transform, relative to the DOM values<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shapetransitionfactory.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-11-02 14:04:54 $
 *
 *  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
 *
 ************************************************************************/

#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <canvas/debug.hxx>
#include <transitionfactory.hxx>
#include <transitiontools.hxx>
#include <parametricpolypolygonfactory.hxx>
#include <animationfactory.hxx>
#include <clippingfunctor.hxx>
#include <com/sun/star/animations/TransitionType.hpp>
#include <com/sun/star/animations/TransitionSubType.hpp>

#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif

using namespace ::com::sun::star;

namespace presentation {
namespace internal {

/***************************************************
 ***                                             ***
 ***          Shape Transition Effects           ***
 ***                                             ***
 ***************************************************/

namespace {

class ClippingAnimation : public NumberAnimation
{
public:
    ClippingAnimation(
        const ParametricPolyPolygonSharedPtr&   rPolygon,
        const LayerManagerSharedPtr&            rLayerManager,
        const TransitionInfo&                   rTransitionInfo,
        bool                                    bDirectionForward,
        bool                                    bModeIn );

    ~ClippingAnimation();

    // Animation interface
    // -------------------
    virtual void start( const AnimatableShapeSharedPtr&     rShape,
                        const ShapeAttributeLayerSharedPtr& rAttrLayer );
    virtual void end();

    // NumberAnimation interface
    // -----------------------
    virtual bool operator()( double nValue );
    virtual double getUnderlyingValue() const;

private:
    void end_();

    AnimatableShapeSharedPtr           mpShape;
    ShapeAttributeLayerSharedPtr       mpAttrLayer;
    LayerManagerSharedPtr              mpLayerManager;
    ClippingFunctor                    maClippingFunctor;
    bool                               mbSpriteActive;
};

ClippingAnimation::ClippingAnimation(
    const ParametricPolyPolygonSharedPtr&   rPolygon,
    const LayerManagerSharedPtr&            rLayerManager,
    const TransitionInfo&                   rTransitionInfo,
    bool                                    bDirectionForward,
    bool                                    bModeIn ) :
        mpShape(),
        mpAttrLayer(),
        mpLayerManager( rLayerManager ),
        maClippingFunctor( rPolygon,
                           rTransitionInfo,
                           bDirectionForward,
                           bModeIn ),
        mbSpriteActive(false)
{
    ENSURE_AND_THROW(
        rLayerManager.get(),
        "ClippingAnimation::ClippingAnimation(): Invalid LayerManager" );
}

ClippingAnimation::~ClippingAnimation()
{
    end_();
}

void ClippingAnimation::start( const AnimatableShapeSharedPtr&      rShape,
                               const ShapeAttributeLayerSharedPtr&  rAttrLayer )
{
    OSL_ENSURE( !mpShape.get(),
                "ClippingAnimation::start(): Shape already set" );
    OSL_ENSURE( !mpAttrLayer.get(),
                "ClippingAnimation::start(): Attribute layer already set" );

    mpShape = rShape;
    mpAttrLayer = rAttrLayer;

    ENSURE_AND_THROW( rShape.get(),
                      "ClippingAnimation::start(): Invalid shape" );
    ENSURE_AND_THROW( rAttrLayer.get(),
                      "ClippingAnimation::start(): Invalid attribute layer" );

    mpShape = rShape;
    mpAttrLayer = rAttrLayer;

    if( !mbSpriteActive )
    {
        mpLayerManager->enterAnimationMode( mpShape );
        mbSpriteActive = true;
    }
}

void ClippingAnimation::end()
{
    end_();
}

void ClippingAnimation::end_()
{
    if( mbSpriteActive )
    {
        mbSpriteActive = false;
        mpLayerManager->leaveAnimationMode( mpShape );

        if( mpShape->isUpdateNecessary() )
            mpLayerManager->notifyShapeUpdate( mpShape );
    }
}

bool ClippingAnimation::operator()( double nValue )
{
    ENSURE_AND_RETURN(
        mpAttrLayer.get() && mpShape.get(),
        "ClippingAnimation::operator(): Invalid ShapeAttributeLayer" );

    // set new clip
    mpAttrLayer->setClip( maClippingFunctor( nValue,
                                             mpShape->getDOMBounds().getRange() ) );

    if( mpShape->isUpdateNecessary() )
        mpLayerManager->notifyShapeUpdate( mpShape );

    return true;
}

double ClippingAnimation::getUnderlyingValue() const
{
    ENSURE_AND_THROW(
        mpAttrLayer.get(),
        "ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer" );

    return 0.0;     // though this should be used in concert with
                    // ActivitiesFactory::createSimpleActivity, better
                    // explicitely name our start value.
                    // Permissible range for operator() above is [0,1]
}

} // anon namespace

AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
    const ActivitiesFactory::CommonParameters&          rParms,
    const AnimatableShapeSharedPtr&                     rShape,
    const LayerManagerSharedPtr&                        rLayerManager,
    uno::Reference< animations::XTransitionFilter > const& xTransition )
{
    return createShapeTransition( rParms,
                                  rShape,
                                  rLayerManager,
                                  xTransition,
                                  xTransition->getTransition(),
                                  xTransition->getSubtype() );
}

AnimationActivitySharedPtr TransitionFactory::createShapeTransition(
    const ActivitiesFactory::CommonParameters&              rParms,
    const AnimatableShapeSharedPtr&                         rShape,
    const LayerManagerSharedPtr&                            rLayerManager,
    ::com::sun::star::uno::Reference<
        ::com::sun::star::animations::XTransitionFilter > const& xTransition,
    sal_Int16                                               nType,
    sal_Int16                                               nSubType )
{
    ENSURE_AND_THROW(
        xTransition.is(),
        "TransitionFactory::createShapeTransition(): Invalid XTransition" );

    const TransitionInfo* pTransitionInfo(
        getTransitionInfo( nType, nSubType ) );

    AnimationActivitySharedPtr pGeneratedActivity;
    if( pTransitionInfo != NULL )
    {
        switch( pTransitionInfo->meTransitionClass )
        {
            default:
            case TransitionInfo::TRANSITION_INVALID:
                OSL_ENSURE( false,
                            "TransitionFactory::createShapeTransition(): Invalid transition type. "
                            "Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!" );
                return AnimationActivitySharedPtr();

            case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:
            {
                // generate parametric poly-polygon
                ParametricPolyPolygonSharedPtr pPoly(
                    ParametricPolyPolygonFactory::createClipPolyPolygon(
                        nType, nSubType ) );

                // create a clip activity from that
                pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                    rParms,
                    NumberAnimationSharedPtr(
                        new ClippingAnimation(
                            pPoly,
                            rLayerManager,
                            *pTransitionInfo,
                            xTransition->getDirection(),
                            xTransition->getMode() ) ),
                    true );
            }
            break;

            case TransitionInfo::TRANSITION_SPECIAL:
            {
                switch( nType )
                {
                    case animations::TransitionType::RANDOM:
                    {
                        // select randomly one of the effects from the
                        // TransitionFactoryTable

                        const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );

                        ENSURE_AND_THROW( pRandomTransitionInfo != NULL,
                                          "TransitionFactory::createShapeTransition(): Got invalid random transition info" );

                        ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,
                                          "TransitionFactory::createShapeTransition(): Got random again for random input!" );

                        // and recurse
                        pGeneratedActivity = createShapeTransition( rParms,
                                                                    rShape,
                                                                    rLayerManager,
                                                                    xTransition,
                                                                    pRandomTransitionInfo->mnTransitionType,
                                                                    pRandomTransitionInfo->mnTransitionSubType );
                    }
                    break;

                    // TODO(F3): Implement slidewipe for shape
                    case animations::TransitionType::SLIDEWIPE:
                    {
                        sal_Int16 nBarWipeSubType(0);
                        bool      bDirectionForward(true);

                        // map slidewipe to BARWIPE, for now
                        switch( nSubType )
                        {
                            case animations::TransitionSubType::FROMLEFT:
                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
                                bDirectionForward = true;
                                break;

                            case animations::TransitionSubType::FROMRIGHT:
                                nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;
                                bDirectionForward = false;
                                break;

                            case animations::TransitionSubType::FROMTOP:
                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
                                bDirectionForward = true;
                                break;

                            case animations::TransitionSubType::FROMBOTTOM:
                                nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;
                                bDirectionForward = false;
                                break;

                            default:
                                ENSURE_AND_THROW( false,
                                                  "TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE" );
                                break;
                        }

                        // generate parametric poly-polygon
                        ParametricPolyPolygonSharedPtr pPoly(
                            ParametricPolyPolygonFactory::createClipPolyPolygon(
                                animations::TransitionType::BARWIPE,
                                nBarWipeSubType ) );

                        // create a clip activity from that
                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                            rParms,
                            NumberAnimationSharedPtr(
                                new ClippingAnimation(
                                    pPoly,
                                    rLayerManager,
                                    *getTransitionInfo( animations::TransitionType::BARWIPE,
                                                        nBarWipeSubType ),
                                    bDirectionForward,
                                    xTransition->getMode() ) ),
                            true );
                    }
                    break;

                    default:
                    {
                        // TODO(F1): Check whether there's anything left, anyway,
                        // for _shape_ transitions. AFAIK, there are no special
                        // effects for shapes...

                        // for now, map all to fade effect
                        pGeneratedActivity = ActivitiesFactory::createSimpleActivity(
                            rParms,
                            AnimationFactory::createNumberPropertyAnimation(
                                ::rtl::OUString(
                                    RTL_CONSTASCII_USTRINGPARAM("Opacity") ),
                                rShape,
                                rLayerManager ),
                            xTransition->getMode() );
                    }
                    break;
                }
            }
            break;
        }
    }

    if( !pGeneratedActivity.get() )
    {
        // No animation generated, maybe no table entry for given
        // transition?
        OSL_TRACE(
            "TransitionFactory::createShapeTransition(): Unknown type/subtype (%d/%d) "
            "combination encountered",
            xTransition->getTransition(),
            xTransition->getSubtype() );
        OSL_ENSURE(
            false,
            "TransitionFactory::createShapeTransition(): Unknown type/subtype "
            "combination encountered" );
    }

    return pGeneratedActivity;
}

}
}
<|endoftext|>


<commit_before><commit_msg>Update mongoUnsubscribeContext.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>added allreduct for testing<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

#pragma once

#include "begin_native.hpp"
#include <chrono>
#include <geode/util/chrono/duration.hpp>
#include "end_native.hpp"

namespace Apache
{
  namespace Geode
  {
    namespace Client
    {
      using namespace System;
      using namespace apache::geode::util::chrono::duration;

      using ticks = std::chrono::duration<long long, std::ratio<1, 10000000>>;

      class TimeUtils
      {
      public:
        template <class _Duration>
        inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)
        {
          return _ceil<_Duration>(TimeSpanToDuration(timeSpan));
        }

        inline static ticks TimeSpanToDuration(TimeSpan timespan)
        {
          return ticks(timespan.Ticks);
        }

        inline static TimeSpan DurationToTimeSpan(ticks duration)
        {
          return TimeSpan::FromTicks(duration.count());
        }

        inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {
          using namespace std::chrono;
          auto t = duration_cast<ticks>(timePoint.time_since_epoch());
          t += epochDifference;
          return DateTime(t.count());
        }

        inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {
          using namespace std::chrono;
          auto t = ticks(dateTime.Ticks);
          t -= epochDifference;
          return system_clock::time_point(t);
        }

      private:
        static constexpr auto epochDifference = ticks(621355968000000000);
      };
    }  // namespace Client
  }  // namespace Geode
}  // namespace Apache

<commit_msg>GEODE-4188: Fixes CLI inlude of internal duration header.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

#pragma once

#include "begin_native.hpp"
#include <chrono>
#include <geode/internal/chrono/duration.hpp>
#include "end_native.hpp"

namespace Apache
{
  namespace Geode
  {
    namespace Client
    {
      using namespace System;
      using namespace apache::geode::internal::chrono::duration;

      using ticks = std::chrono::duration<long long, std::ratio<1, 10000000>>;

      class TimeUtils
      {
      public:
        template <class _Duration>
        inline static _Duration TimeSpanToDurationCeil(TimeSpan timeSpan)
        {
          return _ceil<_Duration>(TimeSpanToDuration(timeSpan));
        }

        inline static ticks TimeSpanToDuration(TimeSpan timespan)
        {
          return ticks(timespan.Ticks);
        }

        inline static TimeSpan DurationToTimeSpan(ticks duration)
        {
          return TimeSpan::FromTicks(duration.count());
        }

        inline static DateTime TimePointToDateTime(std::chrono::system_clock::time_point timePoint) {
          using namespace std::chrono;
          auto t = duration_cast<ticks>(timePoint.time_since_epoch());
          t += epochDifference;
          return DateTime(t.count());
        }

        inline static std::chrono::system_clock::time_point DateTimeToTimePoint(DateTime dateTime) {
          using namespace std::chrono;
          auto t = ticks(dateTime.Ticks);
          t -= epochDifference;
          return system_clock::time_point(t);
        }

      private:
        static constexpr auto epochDifference = ticks(621355968000000000);
      };
    }  // namespace Client
  }  // namespace Geode
}  // namespace Apache

<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "Search.h"
#include "ICallback.h"
#include "SearchResultModel.h"
#include "YelpSearchQueryFactory.h"
#include "YelpSearchQuery.h"
#include "YelpSearchConstants.h"
#include "YelpCategoryModel.h"
#include "IAppCameraController.h"
#include "CameraState.h"
#include "RenderCamera.h"
#include "urlencode.h"
#include <sstream>
#include <iomanip>

namespace ExampleApp
{
    namespace Search
    {
        namespace Yelp
        {
            namespace SdkModel
            {
                namespace
                {

                    std::string UrlGetParamsEncoder(const std::map<std::string, std::string>& params)
                    {
                        std::string url;

                        for (std::map<std::string, std::string>::const_iterator it = params.begin();
                             it != params.end();
                             ++it)
                        {
                            url += it->first + "=" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + "&";
                        }

                        //remove trailing &
                        url[url.length() - 1] = '\0';

                        return url;
                    }

                    int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
                    {
                        const float SearchRadiusMin = 50.0f;
                        const float SearchRadiusMax = 40000.0f;
                        double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();
                        float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));
                        return static_cast<int>(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));
                    }

                }
                YelpSearchQueryFactory::YelpSearchQueryFactory(
                    const std::string& yelpApiKey,
                    SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,
                    Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,
                    ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
                : m_webRequestFactory(webRequestFactory)
                , m_cameraController(cameraController)
                , m_yelpApiKey(yelpApiKey)
                , m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)
                , m_apiUrl("https://api.yelp.com/v3/businesses/search")
                {

                }

                YelpSearchQueryFactory::~YelpSearchQueryFactory()
                {
                }

                SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,
                    Eegeo::Helpers::ICallback0 &completionCallback)
                {
                    std::string searchTerm = "";
                    YelpCategoryModel categoryFilter { "", true };
                    std::string searchLimit("20");

                    if (searchQuery.IsTag())
                    {
                        m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);
                        if(categoryFilter.skipYelpSearch == true)
                        {
                            searchLimit = "0";
                        }
                    }
                    else
                    {
                        searchTerm = searchQuery.Query();
                    }

                    std::map<std::string, std::string> params;
                    std::stringstream conversionStream;

                    conversionStream.setf(std::ios::fixed);
                    conversionStream << std::setprecision(17)
                                     << searchQuery.Location().GetLatitudeInDegrees();
                    std::string latitude = conversionStream.str();

                    conversionStream.clear();
                    conversionStream.str("");
                    conversionStream << std::setprecision(17)
                                     << searchQuery.Location().GetLongitudeInDegrees();
                    std::string longitude = conversionStream.str();

                    if (searchTerm.length() > 0)
                    {
                        params["term"] = searchTerm;
                    }

                    if (categoryFilter.yelpCategoryFilter.length() > 0)
                    {
                        params["categories"] = categoryFilter.yelpCategoryFilter;
                    }
                    params["latitude"] = latitude;
                    params["longitude"] = longitude;
                    params["limit"] = searchLimit;

                    int radius = GetSearchRadius(m_cameraController);
                    conversionStream.clear();
                    conversionStream.str("");
                    conversionStream << radius;
                    params["radius"] = conversionStream.str();

                    std::stringstream requestUrl;
                    requestUrl << m_apiUrl << "?" << UrlGetParamsEncoder(params);

                    return Eegeo_NEW(YelpSearchQuery)(
                        requestUrl.str(),
                        m_yelpApiKey,
                        completionCallback,
                        m_webRequestFactory);
                }

            }
        }
    }
}
<commit_msg>fix MPLY-10022 'Yelp searches only return results in the viewport rather than via radius'<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "Search.h"
#include "ICallback.h"
#include "SearchResultModel.h"
#include "YelpSearchQueryFactory.h"
#include "YelpSearchQuery.h"
#include "YelpSearchConstants.h"
#include "YelpCategoryModel.h"
#include "IAppCameraController.h"
#include "CameraState.h"
#include "RenderCamera.h"
#include "urlencode.h"
#include <sstream>
#include <iomanip>

namespace ExampleApp
{
    namespace Search
    {
        namespace Yelp
        {
            namespace SdkModel
            {
                namespace
                {

                    std::string UrlGetParamsEncoder(const std::map<std::string, std::string>& params)
                    {
                        std::string url;

                        for (std::map<std::string, std::string>::const_iterator it = params.begin();
                             it != params.end();
                             ++it)
                        {
                            url += it->first + "=" + urlencode(it->second, URLEncodeType::URLEncode_Everything) + "&";
                        }

                        //remove trailing &
                        url[url.length() - 1] = '\0';

                        return url;
                    }

                    int GetSearchRadius(ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
                    {
                        const float SearchRadiusMin = 250.0f;
                        const float SearchRadiusMax = 40000.0f;
                        double distanceToInterest = (cameraController.GetCameraState().InterestPointEcef() - cameraController.GetCameraState().LocationEcef()).Length();
                        float radius = (distanceToInterest * Eegeo::Math::Tan(cameraController.GetRenderCamera().GetFOV()));
                        return static_cast<int>(Eegeo::Clamp(radius, SearchRadiusMin, SearchRadiusMax));
                    }

                }
                YelpSearchQueryFactory::YelpSearchQueryFactory(
                    const std::string& yelpApiKey,
                    SdkModel::SearchTagToYelpCategoryMapper& searchTagToYelpCategoryMap,
                    Eegeo::Web::IWebLoadRequestFactory& webRequestFactory,
                    ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController)
                : m_webRequestFactory(webRequestFactory)
                , m_cameraController(cameraController)
                , m_yelpApiKey(yelpApiKey)
                , m_searchTagToYelpCategoryMap(searchTagToYelpCategoryMap)
                , m_apiUrl("https://api.yelp.com/v3/businesses/search")
                {

                }

                YelpSearchQueryFactory::~YelpSearchQueryFactory()
                {
                }

                SdkModel::IYelpSearchQuery* YelpSearchQueryFactory::CreateYelpSearchForQuery(const Search::SdkModel::SearchQuery& searchQuery,
                    Eegeo::Helpers::ICallback0 &completionCallback)
                {
                    std::string searchTerm = "";
                    YelpCategoryModel categoryFilter { "", true };
                    std::string searchLimit("20");

                    if (searchQuery.IsTag())
                    {
                        m_searchTagToYelpCategoryMap.TryGetBestYelpCategoryForSearchTag(searchQuery.Query(), categoryFilter);
                        if(categoryFilter.skipYelpSearch == true)
                        {
                            searchLimit = "0";
                        }
                    }
                    else
                    {
                        searchTerm = searchQuery.Query();
                    }

                    std::map<std::string, std::string> params;
                    std::stringstream conversionStream;

                    conversionStream.setf(std::ios::fixed);
                    conversionStream << std::setprecision(17)
                                     << searchQuery.Location().GetLatitudeInDegrees();
                    std::string latitude = conversionStream.str();

                    conversionStream.clear();
                    conversionStream.str("");
                    conversionStream << std::setprecision(17)
                                     << searchQuery.Location().GetLongitudeInDegrees();
                    std::string longitude = conversionStream.str();

                    if (searchTerm.length() > 0)
                    {
                        params["term"] = searchTerm;
                    }

                    if (categoryFilter.yelpCategoryFilter.length() > 0)
                    {
                        params["categories"] = categoryFilter.yelpCategoryFilter;
                    }
                    params["latitude"] = latitude;
                    params["longitude"] = longitude;
                    params["limit"] = searchLimit;

                    int radius = GetSearchRadius(m_cameraController);
                    conversionStream.clear();
                    conversionStream.str("");
                    conversionStream << radius;
                    params["radius"] = conversionStream.str();

                    std::stringstream requestUrl;
                    requestUrl << m_apiUrl << "?" << UrlGetParamsEncoder(params);

                    return Eegeo_NEW(YelpSearchQuery)(
                        requestUrl.str(),
                        m_yelpApiKey,
                        completionCallback,
                        m_webRequestFactory);
                }

            }
        }
    }
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/prob/wishart_cholesky_rng.hpp>
#include <stan/math/prim/prob/wishart_rng.hpp>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Return a random Cholesky factor of a covariance matrix
 * of the specified dimensionality drawn
 * from the inverse Wishart distribution with the specified degrees of freedom
 * using the specified random number generator.
 *
 * @tparam RNG Random number generator type
 * @param[in] nu scalar degrees of freedom
 * @param[in] L_S lower Cholesky factor of the scale matrix
 * @param[in, out] rng random-number generator
 * @return random lower Cholesky factor drawn from the given inverse Wishart
 * distribution
 * @throw std::domain_error if the scale matrix is not a Cholesky factor
 * @throw std::domain_error if the degrees of freedom is greater than k - 1
 * where k is the dimension of L
 */
template <class RNG>
inline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,
                                                const Eigen::MatrixXd& L_S,
                                                RNG& rng) {
  using Eigen::MatrixXd;
  static const char* function = "inv_wishart_cholesky_rng";
  index_type_t<MatrixXd> k = L_S.rows();
  check_greater(function, "degrees of freedom > dims - 1", nu, k - 1);
  check_positive(function, "Cholesky Scale matrix", L_S.diagonal());
  check_positive(function, "columns of Cholesky Scale matrix", L_S.cols());

  MatrixXd L_Sinv = mdivide_left_tri<Eigen::Lower>(L_S);
  return mdivide_left_tri<Eigen::Lower>(wishart_cholesky_rng(nu, L_Sinv, rng));
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>Update inv_wishart_cholesky_rng.hpp<commit_after>#ifndef STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP
#define STAN_MATH_PRIM_PROB_INV_WISHART_CHOLESKY_RNG_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/prob/wishart_cholesky_rng.hpp>
#include <stan/math/prim/prob/wishart_rng.hpp>

namespace stan {
namespace math {

/** \ingroup multivar_dists
 * Return a random Cholesky factor of a covariance matrix
 * of the specified dimensionality drawn
 * from the inverse Wishart distribution with the specified degrees of freedom
 * using the specified random number generator.
 *
 * @tparam RNG Random number generator type
 * @param[in] nu scalar degrees of freedom
 * @param[in] L_S lower Cholesky factor of the scale matrix
 * @param[in, out] rng random-number generator
 * @return random lower Cholesky factor drawn from the given inverse Wishart
 * distribution
 * @throw std::domain_error if the scale matrix is not a Cholesky factor
 * @throw std::domain_error if the degrees of freedom is greater than k - 1
 * where k is the dimension of L
 */
template <class RNG>
inline Eigen::MatrixXd inv_wishart_cholesky_rng(double nu,
                                                const Eigen::MatrixXd& L_S,
                                                RNG& rng) {
  using Eigen::MatrixXd;
  static const char* function = "inv_wishart_cholesky_rng";
  index_type_t<MatrixXd> k = L_S.rows();
  check_greater(function, "degrees of freedom > dims - 1", nu, k - 1);
  check_positive(function, "Cholesky Scale matrix", L_S.diagonal());
  check_positive(function, "columns of Cholesky Scale matrix", L_S.cols());

  MatrixXd L_Sinv = stan::math::mdivide_left_tri<Eigen::Lower>(L_S);
  return stan::math::mdivide_left_tri<Eigen::Lower>(wishart_cholesky_rng(nu, L_Sinv, rng));
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>#include "regex.h"

#include <iostream>
#include <algorithm>
#include <map>

#include "document.h"
#include "prolog.h"
#include "pi.h"
#include "doctype.h"
#include "attribute.h"
#include "element.h"
#include "composite_element.h"
#include "content.h"

static std::string schema_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string simple_element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string complexe_type_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string choice_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string sequence_to_regex(CompositeElement *, std::map<std::string, std::string> &, bool mixed=false);

static const std::string re_string("[^<]*");
static const std::string re_date("[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?");
static const std::string re_mixed("[^<]*");
static const std::string re_blank("\\s*");
static const std::string re_S("(\\s+)");
static const std::string re_Eq(re_S + "?=" + re_S + "?");
static const std::string re_Name("[:A-Za-z\\200-\\377_][:A-Za-z\\200-\\377_0-9.-]*");
static const std::string re_AttValue("(\"[^<&\"]*\"|\'[^<&\"]*\')");
static const std::string re_Attr(re_Name + re_Eq + re_AttValue);
static const std::string re_version_info(re_S + "version" + re_Eq + "(\"1\\.[0-9]+\"|'1\\.[0-9]+')");
static const std::string re_encoding_decl(re_S + "encoding" + re_Eq + re_AttValue);
static const std::string re_sd_decl(re_S + re_Attr);
static const std::string re_xml_decl("<\\?xml(" +
    re_version_info + ")?(" +
    re_encoding_decl + ")?(" +
    re_sd_decl + ")? ?\\?>");
static const std::string re_comment("<!--([^-]|-[^-])*-->");
static const std::string re_PI("<\\?" + re_Name + "(" + re_S + re_Attr + ")*\\?>");
static const std::string re_Misc("(" + re_comment + "|" + re_PI + "|" + re_S + ")");
static const std::string re_doctype_decl("<!DOCTYPE" + re_S + re_Name + "(" + re_S + re_Name + ")?(" + re_S + re_AttValue + ")?" + re_S + "?>");
static const std::string re_prolog("(" + re_xml_decl + ")?" + re_Misc + "*(" + re_doctype_decl + re_Misc + "*)?");

std::string xsd_to_regex(Document * doc)
{
  // std::cout << "xml : " << re_xml_decl << std::endl;
  // std::cout << "doc : " << re_doctype_decl << std::endl;
  // std::cout << "com : " << re_comment << std::endl;
  // std::cout << "pi  : " << re_PI << std::endl;
  // std::cout << "pro : " << re_prolog << std::endl;
  CompositeElement * root = dynamic_cast<CompositeElement *>(doc->root());
  if (root == nullptr)
    return "^$";
  if (root->begin_tag() == "xsd:schema")
  {
    std::map<std::string, std::string> refs;
    std::string re("^" + re_prolog + schema_to_regex(root, refs) + re_Misc + "*$");
    std::cout << re << std::endl; // Mais oui c'est clair
    return re;
  }
  return "^$";
}

std::string schema_to_regex(CompositeElement * s,
    std::map<std::string, std::string> & refs)
{
  std::string r;
  for (auto c : s->content())
  {
    auto e = dynamic_cast<Element *>(c);
    if (e != nullptr && e->name() == "xsd:element")
      r += element_to_regex(e, refs) + "|";
  }
  r = r.substr(0, r.length() - 1);
  return "(" + r + ")";
}

std::string element_to_regex(Element * e,
    std::map<std::string, std::string> & refs)
{
  auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "name"; });
  if (it_name == e->attributes().end())
  {
    auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),
        [](Attribute * a) { return a->name() == "ref"; });
    if (it_ref == e->attributes().end())
      return "";

    auto ref = (*it_ref)->value();
    auto r = refs.find(ref);
    if (r == refs.end())
      return "";
    return r->second;
  }

  auto name = (*it_name)->value();
  const std::string begin("<" + name + "(" + re_S + re_Attr + ")*" + re_blank + ">");
  const std::string end("</" + name + re_blank + ">");

  auto ce = dynamic_cast<CompositeElement *>(e);
  if (ce != nullptr)
  {
    CompositeElement * cce = nullptr;
    if (ce->content().size() >= 1
        && (cce = dynamic_cast<CompositeElement *>(ce->content().front())) != nullptr
        && cce->begin_tag() == "xsd:complexType")
    {
      std::string r(begin + complexe_type_to_regex(cce, refs) + end);
      refs[name] = r;
      return r;
    }
  }
  else
  {
    std::string r( begin + simple_element_to_regex(e, refs) + end);
    refs[name] = r;
    return r;
  }
  return "";
}

std::string simple_element_to_regex(Element * e,
    std::map<std::string, std::string> &)
{
  auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "type"; });
  if (it_type == e->attributes().end())
    return "";

  auto type = (*it_type)->value();
  if (type == "xsd:string")
    return re_string;
  else if (type == "xsd:date")
    return re_date;
  return "";
}

std::string complexe_type_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs)
{
  if (e->content().size() < 1)
    return "";

  CompositeElement * ce = dynamic_cast<CompositeElement *>(e->content().front());
  if (ce == nullptr)
    return "";

  bool mixed = false;
  auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "mixed"; });
  if (it_mixed != e->attributes().end()
      && (*it_mixed)->value() == "true")
    mixed = true;

  std::string s;
  if (ce->begin_tag() == "xsd:choice")
  {
    if (mixed)
      s += re_mixed;
    s += choice_to_regex(ce, refs);
    if (mixed)
      s += re_mixed;
  }
  else if (ce->begin_tag() == "xsd:sequence")
  {
    s += sequence_to_regex(ce, refs, mixed);
  }
  return s;
}

std::string choice_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs)
{
  std::string s;
  for (auto c : e->content())
  {
    auto ce = dynamic_cast<Element *>(c);
    if (ce)
    {
      s += element_to_regex(ce, refs);
      if (c != e->content().back())
        s += "|";
    }
  }
  return re_blank + "(" + s + ")" + re_blank;
}

std::string sequence_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs, bool mixed)
{
  std::string s;
  std::string space = mixed ? re_mixed : re_blank;
  for (auto c : e->content())
  {
    auto ce = dynamic_cast<Element *>(c);
    if (ce)
    {
      auto it_maxOccurs = std::find_if(ce->attributes().begin(),
          ce->attributes().end(),
          [](Attribute * a) { return a->name() == "maxOccurs"; });
      std::string maxOccurs("1");
      if (it_maxOccurs != ce->attributes().end())
        maxOccurs = (*it_maxOccurs)->value();
      s += "(" + element_to_regex(ce, refs) + "){1," + maxOccurs + "}" + space;
    }
  }
  return space + s;
}

<commit_msg>Tous les tests passe pour p et v<commit_after>#include "regex.h"

#include <iostream>
#include <algorithm>
#include <map>

#include "document.h"
#include "prolog.h"
#include "pi.h"
#include "doctype.h"
#include "attribute.h"
#include "element.h"
#include "composite_element.h"
#include "content.h"

static std::string schema_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string simple_element_to_regex(Element *, std::map<std::string, std::string> &);
static std::string complexe_type_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string choice_to_regex(CompositeElement *, std::map<std::string, std::string> &);
static std::string sequence_to_regex(CompositeElement *, std::map<std::string, std::string> &, bool mixed=false);

static const std::string re_string("[^<]*");
static const std::string re_date("[0-9]{4}-[0-9]{2}-[0-9]{2}(((\\+|-)[0-2][0-9]:[0-5][0-9])|Z)?");
static const std::string re_mixed("[^<]*");
static const std::string re_blank("\\s*");
static const std::string re_S("(\\s+)");
static const std::string re_Eq(re_S + "?=" + re_S + "?");
static const std::string re_Name("[:A-Za-z\\200-\\377_][:A-Za-z\\200-\\377_0-9.-]*");
static const std::string re_AttValue("(\"[^<&\"]*\"|\'[^<&\"]*\')");
static const std::string re_Attr(re_Name + re_Eq + re_AttValue);
static const std::string re_version_info(re_S + "version" + re_Eq + "(\"1\\.[0-9]+\"|'1\\.[0-9]+')");
static const std::string re_encoding_decl(re_S + "encoding" + re_Eq + re_AttValue);
static const std::string re_sd_decl(re_S + re_Attr);
static const std::string re_xml_decl("<\\?xml(" +
    re_version_info + ")?(" +
    re_encoding_decl + ")?(" +
    re_sd_decl + ")? ?\\?>");
static const std::string re_comment("<!--([^-]|-[^-])*-->");
static const std::string re_PI("<\\?" + re_Name + "(" + re_S + re_Attr + ")*\\?>");
static const std::string re_Misc("(" + re_comment + "|" + re_PI + "|" + re_S + ")");
static const std::string re_doctype_decl("<!DOCTYPE" + re_S + re_Name + "(" + re_S + re_Name + ")?(" + re_S + re_AttValue + ")?" + re_S + "?>");
static const std::string re_prolog("(" + re_xml_decl + ")?" + re_Misc + "*(" + re_doctype_decl + re_Misc + "*)?");

std::string xsd_to_regex(Document * doc)
{
  // std::cout << "xml : " << re_xml_decl << std::endl;
  // std::cout << "doc : " << re_doctype_decl << std::endl;
  // std::cout << "com : " << re_comment << std::endl;
  // std::cout << "pi  : " << re_PI << std::endl;
  // std::cout << "pro : " << re_prolog << std::endl;
  CompositeElement * root = dynamic_cast<CompositeElement *>(doc->root());
  if (root == nullptr)
    return "^$";
  if (root->begin_tag() == "xsd:schema")
  {
    std::map<std::string, std::string> refs;
    std::string re("^" + re_prolog + schema_to_regex(root, refs) + re_Misc + "*$");
    // std::cout << re << std::endl; // Mais oui c'est clair
    return re;
  }
  return "^$";
}

std::string schema_to_regex(CompositeElement * s,
    std::map<std::string, std::string> & refs)
{
  std::string r;
  for (auto c : s->content())
  {
    auto e = dynamic_cast<Element *>(c);
    if (e != nullptr && e->name() == "xsd:element")
      r += element_to_regex(e, refs) + "|";
  }
  r = r.substr(0, r.length() - 1);
  return "(" + r + ")";
}

std::string element_to_regex(Element * e,
    std::map<std::string, std::string> & refs)
{
  auto it_name = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "name"; });
  if (it_name == e->attributes().end())
  {
    auto it_ref = std::find_if(e->attributes().begin(), e->attributes().end(),
        [](Attribute * a) { return a->name() == "ref"; });
    if (it_ref == e->attributes().end())
      return "";

    auto ref = (*it_ref)->value();
    auto r = refs.find(ref);
    if (r == refs.end())
      return "";
    return r->second;
  }

  auto name = (*it_name)->value();
  const std::string begin("<" + name + "(" + re_S + re_Attr + ")*" + re_blank + ">");
  const std::string end("</" + name + re_blank + ">");

  auto ce = dynamic_cast<CompositeElement *>(e);
  if (ce != nullptr)
  {
    CompositeElement * cce = nullptr;
    if (ce->content().size() >= 1
        && (cce = dynamic_cast<CompositeElement *>(ce->content().front())) != nullptr
        && cce->begin_tag() == "xsd:complexType")
    {
      std::string r(begin + complexe_type_to_regex(cce, refs) + end);
      refs[name] = r;
      return r;
    }
  }
  else
  {
    std::string r( begin + simple_element_to_regex(e, refs) + end);
    refs[name] = r;
    return r;
  }
  return "";
}

std::string simple_element_to_regex(Element * e,
    std::map<std::string, std::string> &)
{
  auto it_type = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "type"; });
  if (it_type == e->attributes().end())
    return "";

  auto type = (*it_type)->value();
  if (type == "xsd:string")
    return re_string;
  else if (type == "xsd:date")
    return re_date;
  return "";
}

std::string complexe_type_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs)
{
  if (e->content().size() < 1)
    return "";

  CompositeElement * ce = dynamic_cast<CompositeElement *>(e->content().front());
  if (ce == nullptr)
    return "";

  bool mixed = false;
  auto it_mixed = std::find_if(e->attributes().begin(), e->attributes().end(),
      [](Attribute * a) { return a->name() == "mixed"; });
  if (it_mixed != e->attributes().end()
      && (*it_mixed)->value() == "true")
    mixed = true;

  std::string s;
  if (ce->begin_tag() == "xsd:choice")
  {
    if (mixed)
      s += re_mixed;
    s += choice_to_regex(ce, refs);
    if (mixed)
      s += re_mixed;
  }
  else if (ce->begin_tag() == "xsd:sequence")
  {
    s += sequence_to_regex(ce, refs, mixed);
  }
  return s;
}

std::string choice_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs)
{
  std::string s;
  for (auto c : e->content())
  {
    auto ce = dynamic_cast<Element *>(c);
    if (ce)
    {
      s += element_to_regex(ce, refs);
      if (c != e->content().back())
        s += "|";
    }
  }
  return re_blank + "(" + s + ")" + re_blank;
}

std::string sequence_to_regex(CompositeElement * e,
    std::map<std::string, std::string> & refs, bool mixed)
{
  std::string s;
  std::string space = mixed ? re_mixed : re_blank;
  for (auto c : e->content())
  {
    auto ce = dynamic_cast<Element *>(c);
    if (ce)
    {
      auto it_maxOccurs = std::find_if(ce->attributes().begin(),
          ce->attributes().end(),
          [](Attribute * a) { return a->name() == "maxOccurs"; });
      std::string reg = element_to_regex(ce, refs) + space;
      if (it_maxOccurs != ce->attributes().end())
      {
        int maxOccurs = atoi((*it_maxOccurs)->value().c_str());
        for (int i(0); i < maxOccurs; i++) {
          s += reg;
        }
      }
      else
      {
        s += reg;
      }
    }
  }
  return space + s;
}

<|endoftext|>