<commit_before>// Copyright (c) 2011 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.

#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/ohdp/Defs.hpp>
#include <boost/functional/hash.hpp>
#include <boost/lexical_cast.hpp>

namespace Sirikata {
namespace OHDP {

#define NULL_NODE_ID 0
#define ANY_NODE_ID 0xFFFFFF

NodeID::NodeID()
 : mValue(NULL_NODE_ID)
{
}

NodeID::NodeID(uint32 rhs)
 : mValue(rhs)
{
}

NodeID::NodeID(const NodeID& rhs)
 : mValue(rhs.mValue)
{
}

const NodeID& NodeID::null() {
    static NodeID null_port(NULL_NODE_ID);
    return null_port;
}

const NodeID& NodeID::self() {
    return null();
}

const NodeID& NodeID::any() {
    static NodeID any_port(ANY_NODE_ID);
    return any_port;
}

NodeID& NodeID::operator=(const NodeID& rhs) {
    mValue = rhs.mValue;
    return *this;
}

NodeID& NodeID::operator=(uint32 rhs) {
    mValue = rhs;
    return *this;
}

NodeID::operator uint32() const {
    return mValue;
}

bool NodeID::operator==(const NodeID& rhs) const {
    return mValue == rhs.mValue;
}

bool NodeID::operator!=(const NodeID& rhs) const {
    return mValue != rhs.mValue;
}

bool NodeID::operator>(const NodeID& rhs) const {
    return mValue > rhs.mValue;
}

bool NodeID::operator>=(const NodeID& rhs) const {
    return mValue >= rhs.mValue;
}

bool NodeID::operator<(const NodeID& rhs) const {
    return mValue < rhs.mValue;
}

bool NodeID::operator<=(const NodeID& rhs) const {
    return mValue <= rhs.mValue;
}

String NodeID::toString() const {
    return boost::lexical_cast<String>(mValue);
}

bool NodeID::matches(const NodeID& rhs) const {
    return (
        mValue == rhs.mValue ||
        mValue == ANY_NODE_ID ||
        rhs.mValue == ANY_NODE_ID);
}

std::ostream& operator<<(std::ostream& os, const NodeID& rhs) {
    os << (uint32)rhs;
    return os;
}

SpaceNodeID::SpaceNodeID()
 : mSpace(SpaceID::null()),
   mNode(NodeID::null())
{
}

SpaceNodeID::SpaceNodeID(const SpaceID& s, const NodeID& n)
 : mSpace(s),
   mNode(n)
{
}

const SpaceNodeID::SpaceNodeID& null() {
    static SpaceNodeID n(SpaceID::null(), NodeID::null());
    return n;
}

bool SpaceNodeID::operator==(const SpaceNodeID& rhs) const {
    return (mSpace == rhs.mSpace && mNode == rhs.mNode);
}

bool SpaceNodeID::operator<(const SpaceNodeID& rhs) const {
    return (
        mSpace < rhs.mSpace ||
        (mSpace == rhs.mSpace && mNode < rhs.mNode)
    );
}

String SpaceNodeID::toString() const {
    return mSpace.toString() + ":" + mNode.toString();
}

size_t SpaceNodeID::Hasher::operator()(const SpaceNodeID& p) const {
    size_t seed = 0;
    boost::hash_combine(seed, p.mSpace.hash());
    boost::hash_combine(seed, p.mNode.hash());
    return seed;
}

std::ostream& operator<<(std::ostream& os, const SpaceNodeID& rhs) {
    os << rhs.space() << ":" << rhs.node();
    return os;
}

} // namespace OHDP
} // namespace Sirikata
<commit_msg>Fix typo in OHDP defs that caused errors in some compilers.<commit_after>// Copyright (c) 2011 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.

#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/ohdp/Defs.hpp>
#include <boost/functional/hash.hpp>
#include <boost/lexical_cast.hpp>

namespace Sirikata {
namespace OHDP {

#define NULL_NODE_ID 0
#define ANY_NODE_ID 0xFFFFFF

NodeID::NodeID()
 : mValue(NULL_NODE_ID)
{
}

NodeID::NodeID(uint32 rhs)
 : mValue(rhs)
{
}

NodeID::NodeID(const NodeID& rhs)
 : mValue(rhs.mValue)
{
}

const NodeID& NodeID::null() {
    static NodeID null_port(NULL_NODE_ID);
    return null_port;
}

const NodeID& NodeID::self() {
    return null();
}

const NodeID& NodeID::any() {
    static NodeID any_port(ANY_NODE_ID);
    return any_port;
}

NodeID& NodeID::operator=(const NodeID& rhs) {
    mValue = rhs.mValue;
    return *this;
}

NodeID& NodeID::operator=(uint32 rhs) {
    mValue = rhs;
    return *this;
}

NodeID::operator uint32() const {
    return mValue;
}

bool NodeID::operator==(const NodeID& rhs) const {
    return mValue == rhs.mValue;
}

bool NodeID::operator!=(const NodeID& rhs) const {
    return mValue != rhs.mValue;
}

bool NodeID::operator>(const NodeID& rhs) const {
    return mValue > rhs.mValue;
}

bool NodeID::operator>=(const NodeID& rhs) const {
    return mValue >= rhs.mValue;
}

bool NodeID::operator<(const NodeID& rhs) const {
    return mValue < rhs.mValue;
}

bool NodeID::operator<=(const NodeID& rhs) const {
    return mValue <= rhs.mValue;
}

String NodeID::toString() const {
    return boost::lexical_cast<String>(mValue);
}

bool NodeID::matches(const NodeID& rhs) const {
    return (
        mValue == rhs.mValue ||
        mValue == ANY_NODE_ID ||
        rhs.mValue == ANY_NODE_ID);
}

std::ostream& operator<<(std::ostream& os, const NodeID& rhs) {
    os << (uint32)rhs;
    return os;
}

SpaceNodeID::SpaceNodeID()
 : mSpace(SpaceID::null()),
   mNode(NodeID::null())
{
}

SpaceNodeID::SpaceNodeID(const SpaceID& s, const NodeID& n)
 : mSpace(s),
   mNode(n)
{
}

const SpaceNodeID& SpaceNodeID::null() {
    static SpaceNodeID n(SpaceID::null(), NodeID::null());
    return n;
}

bool SpaceNodeID::operator==(const SpaceNodeID& rhs) const {
    return (mSpace == rhs.mSpace && mNode == rhs.mNode);
}

bool SpaceNodeID::operator<(const SpaceNodeID& rhs) const {
    return (
        mSpace < rhs.mSpace ||
        (mSpace == rhs.mSpace && mNode < rhs.mNode)
    );
}

String SpaceNodeID::toString() const {
    return mSpace.toString() + ":" + mNode.toString();
}

size_t SpaceNodeID::Hasher::operator()(const SpaceNodeID& p) const {
    size_t seed = 0;
    boost::hash_combine(seed, p.mSpace.hash());
    boost::hash_combine(seed, p.mNode.hash());
    return seed;
}

std::ostream& operator<<(std::ostream& os, const SpaceNodeID& rhs) {
    os << rhs.space() << ":" << rhs.node();
    return os;
}

} // namespace OHDP
} // namespace Sirikata
<|endoftext|>


<commit_before>// $Id: FragmentDB_test.C,v 1.1 1999/08/26 08:02:36 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/KERNEL/fragmentDB.h>
#include <BALL/KERNEL/residue.h>
using namespace BALL;
///////////////////////////

START_TEST(class_name, "$Id: FragmentDB_test.C,v 1.1 1999/08/26 08:02:36 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

FragmentDB db("data/fragments/Fragments.db");
CHECK(getResidue(const String&))
const Residue* res = db.getResidue("GLY");
TEST_NOT_EQUAL(res, 0)
if (res != 0)
{
	TEST_EQUAL(res->isNTerminal(), false)
	TEST_EQUAL(res->isCTerminal(), false)
	AtomIterator it;
	for (it = res->beginAtom(); +it; ++it)
	{
		cout << it->getName() << endl;
	}
}

RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>modified due to the change in fragmentDB<commit_after>// $Id: FragmentDB_test.C,v 1.2 1999/09/17 11:18:07 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/KERNEL/residue.h>
using namespace BALL;
///////////////////////////

START_TEST(class_name, "$Id: FragmentDB_test.C,v 1.2 1999/09/17 11:18:07 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

FragmentDB db("data/fragments/Fragments.db");
CHECK(getResidue(const String&))
const Residue* res = db.getResidue("GLY");
TEST_NOT_EQUAL(res, 0)
if (res != 0)
{
	TEST_EQUAL(res->isNTerminal(), false)
	TEST_EQUAL(res->isCTerminal(), false)
	AtomIterator it;
	for (it = res->beginAtom(); +it; ++it)
	{
		cout << it->getName() << endl;
	}
}

RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * This istream filter wraps data inside AJPv13 packets.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_ajp_body.hxx"
#include "istream_internal.hxx"
#include "istream_forward.hxx"
#include "ajp_protocol.hxx"
#include "direct.h"
#include "util/Cast.hxx"
#include "util/ByteOrder.hxx"

#include <assert.h>

struct istream_ajp_body {
    struct istream output;
    struct istream *input;

    size_t requested, packet_remaining;

    gcc_packed struct {
        struct ajp_header header;
        uint16_t length;
    } header;
    size_t header_sent;
};

static void
ajp_body_start_packet(struct istream_ajp_body *ab, size_t length)
{
    assert(ab->requested > 0);
    assert(length > 0);

    if (length > ab->requested)
        length = ab->requested;

    if (length > 8192 - sizeof(ab->header))
        /* limit packets to 8 kB - up to 65535 might be possible,
           but has never been tested */
        length = 8192 - sizeof(ab->header);

    ab->packet_remaining = length;
    ab->requested -= length;

    ab->header.header.a = 0x12;
    ab->header.header.b = 0x34;
    ab->header.header.length =
        ToBE16(ab->packet_remaining + sizeof(ab->header.length));
    ab->header.length = ToBE16(ab->packet_remaining);
    ab->header_sent = 0;
}

/**
 * Returns true if the header is complete.
 */
static bool
ajp_body_write_header(struct istream_ajp_body *ab)
{
    size_t length, nbytes;
    const char *p;

    assert(ab->packet_remaining > 0);
    assert(ab->header_sent <= sizeof(ab->header));

    length = sizeof(ab->header) - ab->header_sent;
    if (length == 0)
        return true;

    p = (const char *)&ab->header;
    p += ab->header_sent;

    nbytes = istream_invoke_data(&ab->output, p, length);
    if (nbytes > 0)
        ab->header_sent += nbytes;

    return nbytes == length;
}

/**
 * Returns true if the caller may write the packet body.
 */
static bool
ajp_body_make_packet(struct istream_ajp_body *ab, size_t length)
{
    if (ab->packet_remaining == 0) {
        if (ab->requested == 0)
            return false;

        ajp_body_start_packet(ab, length);
    }

    return ajp_body_write_header(ab);
}

/*
 * istream handler
 *
 */

static size_t
ajp_body_input_data(const void *data, size_t length, void *ctx)
{
    auto *ab = (struct istream_ajp_body *)ctx;
    size_t nbytes;

    if (!ajp_body_make_packet(ab, length))
        return 0;

    if (length > ab->packet_remaining)
        length = ab->packet_remaining;

    nbytes = istream_invoke_data(&ab->output, data, length);
    if (nbytes > 0)
        ab->packet_remaining -= nbytes;

    return nbytes;
}

static ssize_t
ajp_body_input_direct(enum istream_direct type, int fd, size_t max_length,
                      void *ctx)
{
    auto *ab = (struct istream_ajp_body *)ctx;

    if (ab->packet_remaining == 0) {
        if (ab->requested == 0)
            return ISTREAM_RESULT_BLOCKING;

        /* start a new packet, size determined by
           direct_available() */
        ssize_t available = direct_available(fd, type, max_length);
        if (available <= 0)
            return available;

        ajp_body_start_packet(ab, available);
    }

    pool_ref(ab->output.pool);

    if (!ajp_body_write_header(ab)) {
        ssize_t ret = ab->input != NULL
            ? ISTREAM_RESULT_BLOCKING : ISTREAM_RESULT_CLOSED;
        pool_unref(ab->output.pool);
        return ret;
    }

    pool_unref(ab->output.pool);

    if (max_length > ab->packet_remaining)
        max_length = ab->packet_remaining;

    ssize_t nbytes = istream_invoke_direct(&ab->output, type, fd, max_length);
    if (nbytes > 0)
        ab->packet_remaining -= nbytes;

    return nbytes;
}

static const struct istream_handler ajp_body_input_handler = {
    .data = ajp_body_input_data,
    .direct = ajp_body_input_direct,
    .eof = istream_forward_eof,
    .abort = istream_forward_abort,
};

/*
 * istream implementation
 *
 */

static inline struct istream_ajp_body *
istream_to_ab(struct istream *istream)
{
    return &ContainerCast2(*istream, &istream_ajp_body::output);
}

static off_t
istream_ajp_body_available(struct istream *istream, bool partial)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    if (!partial)
        return -1;

    return istream_available(ab->input, partial);
}

static void
istream_ajp_body_read(struct istream *istream)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    if (ab->packet_remaining > 0 && !ajp_body_write_header(ab))
        return;

    if (ab->packet_remaining == 0 && ab->requested > 0) {
        /* start a new packet, as large as possible */
        off_t available = istream_available(ab->input, true);
        if (available > 0)
            ajp_body_start_packet(ab, available);
    }

    istream_handler_set_direct(ab->input, ab->output.handler_direct);
    istream_read(ab->input);
}

static void
istream_ajp_body_close(struct istream *istream)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    istream_free_handler(&ab->input);
    istream_deinit(&ab->output);
}

static constexpr struct istream_class istream_ajp_body = {
    .available = istream_ajp_body_available,
    .read = istream_ajp_body_read,
    .close = istream_ajp_body_close,
};

/*
 * constructor
 *
 */

struct istream *
istream_ajp_body_new(struct pool *pool, struct istream *input)
{
    struct istream_ajp_body *ab = istream_new_macro(pool, ajp_body);

    assert(input != NULL);
    assert(!istream_has_handler(input));

    ab->requested = 0;
    ab->packet_remaining = 0;

    istream_assign_handler(&ab->input, input,
                           &ajp_body_input_handler, ab,
                           0);

    return &ab->output;
}

void
istream_ajp_body_request(struct istream *istream, size_t length)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    /* we're not checking if this becomes larger than the request body
       - although Tomcat should know better, it requests more and
       more */
    ab->requested += length;
}
<commit_msg>istream_ajp_body: use NewFromPool()<commit_after>/*
 * This istream filter wraps data inside AJPv13 packets.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_ajp_body.hxx"
#include "istream_internal.hxx"
#include "istream_forward.hxx"
#include "ajp_protocol.hxx"
#include "direct.h"
#include "util/Cast.hxx"
#include "util/ByteOrder.hxx"

#include <assert.h>

struct istream_ajp_body {
    struct istream output;
    struct istream *input;

    size_t requested, packet_remaining;

    gcc_packed struct {
        struct ajp_header header;
        uint16_t length;
    } header;
    size_t header_sent;
};

static void
ajp_body_start_packet(struct istream_ajp_body *ab, size_t length)
{
    assert(ab->requested > 0);
    assert(length > 0);

    if (length > ab->requested)
        length = ab->requested;

    if (length > 8192 - sizeof(ab->header))
        /* limit packets to 8 kB - up to 65535 might be possible,
           but has never been tested */
        length = 8192 - sizeof(ab->header);

    ab->packet_remaining = length;
    ab->requested -= length;

    ab->header.header.a = 0x12;
    ab->header.header.b = 0x34;
    ab->header.header.length =
        ToBE16(ab->packet_remaining + sizeof(ab->header.length));
    ab->header.length = ToBE16(ab->packet_remaining);
    ab->header_sent = 0;
}

/**
 * Returns true if the header is complete.
 */
static bool
ajp_body_write_header(struct istream_ajp_body *ab)
{
    size_t length, nbytes;
    const char *p;

    assert(ab->packet_remaining > 0);
    assert(ab->header_sent <= sizeof(ab->header));

    length = sizeof(ab->header) - ab->header_sent;
    if (length == 0)
        return true;

    p = (const char *)&ab->header;
    p += ab->header_sent;

    nbytes = istream_invoke_data(&ab->output, p, length);
    if (nbytes > 0)
        ab->header_sent += nbytes;

    return nbytes == length;
}

/**
 * Returns true if the caller may write the packet body.
 */
static bool
ajp_body_make_packet(struct istream_ajp_body *ab, size_t length)
{
    if (ab->packet_remaining == 0) {
        if (ab->requested == 0)
            return false;

        ajp_body_start_packet(ab, length);
    }

    return ajp_body_write_header(ab);
}

/*
 * istream handler
 *
 */

static size_t
ajp_body_input_data(const void *data, size_t length, void *ctx)
{
    auto *ab = (struct istream_ajp_body *)ctx;
    size_t nbytes;

    if (!ajp_body_make_packet(ab, length))
        return 0;

    if (length > ab->packet_remaining)
        length = ab->packet_remaining;

    nbytes = istream_invoke_data(&ab->output, data, length);
    if (nbytes > 0)
        ab->packet_remaining -= nbytes;

    return nbytes;
}

static ssize_t
ajp_body_input_direct(enum istream_direct type, int fd, size_t max_length,
                      void *ctx)
{
    auto *ab = (struct istream_ajp_body *)ctx;

    if (ab->packet_remaining == 0) {
        if (ab->requested == 0)
            return ISTREAM_RESULT_BLOCKING;

        /* start a new packet, size determined by
           direct_available() */
        ssize_t available = direct_available(fd, type, max_length);
        if (available <= 0)
            return available;

        ajp_body_start_packet(ab, available);
    }

    pool_ref(ab->output.pool);

    if (!ajp_body_write_header(ab)) {
        ssize_t ret = ab->input != NULL
            ? ISTREAM_RESULT_BLOCKING : ISTREAM_RESULT_CLOSED;
        pool_unref(ab->output.pool);
        return ret;
    }

    pool_unref(ab->output.pool);

    if (max_length > ab->packet_remaining)
        max_length = ab->packet_remaining;

    ssize_t nbytes = istream_invoke_direct(&ab->output, type, fd, max_length);
    if (nbytes > 0)
        ab->packet_remaining -= nbytes;

    return nbytes;
}

static const struct istream_handler ajp_body_input_handler = {
    .data = ajp_body_input_data,
    .direct = ajp_body_input_direct,
    .eof = istream_forward_eof,
    .abort = istream_forward_abort,
};

/*
 * istream implementation
 *
 */

static inline struct istream_ajp_body *
istream_to_ab(struct istream *istream)
{
    return &ContainerCast2(*istream, &istream_ajp_body::output);
}

static off_t
istream_ajp_body_available(struct istream *istream, bool partial)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    if (!partial)
        return -1;

    return istream_available(ab->input, partial);
}

static void
istream_ajp_body_read(struct istream *istream)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    if (ab->packet_remaining > 0 && !ajp_body_write_header(ab))
        return;

    if (ab->packet_remaining == 0 && ab->requested > 0) {
        /* start a new packet, as large as possible */
        off_t available = istream_available(ab->input, true);
        if (available > 0)
            ajp_body_start_packet(ab, available);
    }

    istream_handler_set_direct(ab->input, ab->output.handler_direct);
    istream_read(ab->input);
}

static void
istream_ajp_body_close(struct istream *istream)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    istream_free_handler(&ab->input);
    istream_deinit(&ab->output);
}

static constexpr struct istream_class istream_ajp_body = {
    .available = istream_ajp_body_available,
    .read = istream_ajp_body_read,
    .close = istream_ajp_body_close,
};

/*
 * constructor
 *
 */

struct istream *
istream_ajp_body_new(struct pool *pool, struct istream *input)
{
    assert(input != NULL);
    assert(!istream_has_handler(input));

    auto *ab = NewFromPool<struct istream_ajp_body>(*pool);
    istream_init(&ab->output, &istream_ajp_body, pool);

    ab->requested = 0;
    ab->packet_remaining = 0;

    istream_assign_handler(&ab->input, input,
                           &ajp_body_input_handler, ab,
                           0);

    return &ab->output;
}

void
istream_ajp_body_request(struct istream *istream, size_t length)
{
    struct istream_ajp_body *ab = istream_to_ab(istream);

    /* we're not checking if this becomes larger than the request body
       - although Tomcat should know better, it requests more and
       more */
    ab->requested += length;
}
<|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.
 */

#include <string>

#include <mesos/mesos.hpp>

#include <stout/net.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>

#include "hdfs/hdfs.hpp"

using namespace mesos;

using std::string;

// Try to extract filename into directory. If filename is recognized as an
// archive it will be extracted and true returned; if not recognized then false
// will be returned. An Error is returned if the extraction command fails.
Try<bool> extract(const string& filename, const string& directory)
{
  string command;
  // Extract any .tgz, tar.gz, tar.bz2 or zip files.
  if (strings::endsWith(filename, ".tgz") ||
      strings::endsWith(filename, ".tar.gz") ||
      strings::endsWith(filename, ".tbz2") ||
      strings::endsWith(filename, ".tar.bz2") ||
      strings::endsWith(filename, ".txz") ||
      strings::endsWith(filename, ".tar.xz")) {
    command = "tar -C '" + directory + "' xJf";
  } else if (strings::endsWith(filename, ".zip")) {
    command = "unzip -d '" + directory + "'";
  } else {
    return false;
  }

  command += " '" + filename + "'";
  int status = os::system(command);
  if (status != 0) {
    return Error("Failed to extract: command " + command +
                 " exited with status: " + stringify(status));
  }

  LOG(INFO) << "Extracted resource '" << filename
            << "' into '" << directory << "'";

  return true;
}

// Fetch URI into directory.
Try<string> fetch(
    const string& uri,
    const string& directory)
{
  LOG(INFO) << "Fetching URI '" << uri << "'";

  // Some checks to make sure using the URI value in shell commands
  // is safe. TODO(benh): These should be pushed into the scheduler
  // driver and reported to the user.
  if (uri.find_first_of('\\') != string::npos ||
      uri.find_first_of('\'') != string::npos ||
      uri.find_first_of('\0') != string::npos) {
    LOG(ERROR) << "URI contains illegal characters, refusing to fetch";
    return Error("Illegal characters in URI");
  }

  // Grab the resource from HDFS if its path begins with hdfs:// or
  // hftp:
  // TODO(matei): Enforce some size limits on files we get from HDFS
  if (strings::startsWith(uri, "hdfs://") ||
      strings::startsWith(uri, "hftp://")) {
    Try<string> base = os::basename(uri);
    if (base.isError()) {
      LOG(ERROR) << "Invalid basename for URI: " << base.error();
      return Error("Invalid basename for URI");
    }
    string path = path::join(directory, base.get());

    HDFS hdfs;

    LOG(INFO) << "Downloading resource from '" << uri
              << "' to '" << path << "'";
    Try<Nothing> result = hdfs.copyToLocal(uri, path);
    if (result.isError()) {
      LOG(ERROR) << "HDFS copyToLocal failed: " << result.error();
      return Error(result.error());
    }

    return path;
  } else if (strings::startsWith(uri, "http://") ||
             strings::startsWith(uri, "https://") ||
             strings::startsWith(uri, "ftp://") ||
             strings::startsWith(uri, "ftps://")) {
    string path = uri.substr(uri.find("://") + 3);
    if (path.find("/") == string::npos ||
        path.size() <= path.find("/") + 1) {
      LOG(ERROR) << "Malformed URL (missing path)";
      return Error("Malformed URI");
    }

    path =  path::join(directory, path.substr(path.find_last_of("/") + 1));
    LOG(INFO) << "Downloading '" << uri << "' to '" << path << "'";
    Try<int> code = net::download(uri, path);
    if (code.isError()) {
      LOG(ERROR) << "Error downloading resource: " << code.error().c_str();
      return Error("Fetch of URI failed (" + code.error() + ")");
    } else if (code.get() != 200) {
      LOG(ERROR) << "Error downloading resource, received HTTP/FTP return code "
                 << code.get();
      return Error("HTTP/FTP error (" + stringify(code.get()) + ")");
    }

    return path;
  } else { // Copy the local resource.
    string local = uri;
    if (local.find_first_of("/") != 0) {
      // We got a non-Hadoop and non-absolute path.
      if (os::hasenv("MESOS_FRAMEWORKS_HOME")) {
        local = path::join(os::getenv("MESOS_FRAMEWORKS_HOME"), local);
        LOG(INFO) << "Prepended environment variable "
                  << "MESOS_FRAMEWORKS_HOME to relative path, "
                  << "making it: '" << local << "'";
      } else {
        LOG(ERROR) << "A relative path was passed for the resource but the "
                   << "environment variable MESOS_FRAMEWORKS_HOME is not set. "
                   << "Please either specify this config option "
                   << "or avoid using a relative path";
        return Error("Could not resolve relative URI");
      }
    }

    Try<string> base = os::basename(local);
    if (base.isError()) {
      LOG(ERROR) << base.error();
      return Error("Fetch of URI failed");
    }

    // Copy the resource to the directory.
    string path = path::join(directory, base.get());
    std::ostringstream command;
    command << "cp '" << local << "' '" << path << "'";
    LOG(INFO) << "Copying resource from '" << local
              << "' to '" << directory << "'";

    int status = os::system(command.str());
    if (status != 0) {
      LOG(ERROR) << "Failed to copy '" << local
                 << "' : Exit status " << status;
      return Error("Local copy failed");
    }

    return path;
  }
}

int main(int argc, char* argv[])
{
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  CommandInfo commandInfo;
  // Construct URIs from the encoded environment string.
  const std::string& uris = os::getenv("MESOS_EXECUTOR_URIS");
  foreach (const std::string& token, strings::tokenize(uris, " ")) {
    // Delimiter between URI and execute permission.
    size_t pos = token.rfind("+");
    CHECK(pos != std::string::npos)
      << "Invalid executor uri token in env " << token;

    CommandInfo::URI uri;
    uri.set_value(token.substr(0, pos));
    uri.set_executable(token.substr(pos + 1) == "1");

    commandInfo.add_uris()->MergeFrom(uri);
  }

  CHECK(os::hasenv("MESOS_WORK_DIRECTORY"))
    << "Missing MESOS_WORK_DIRECTORY environment variable";
  std::string directory = os::getenv("MESOS_WORK_DIRECTORY");

  // We cannot use Some in the ternary expression because the compiler needs to
  // be able to infer the type, thus the explicit Option<string>.
  // TODO(idownes): Add an os::hasenv that returns an Option<string>.
  Option<std::string> user = os::hasenv("MESOS_USER")
    ? Option<std::string>(os::getenv("MESOS_USER")) // Explicit so it compiles.
    : None();

  // Fetch each URI to a local file, chmod, then chown if a user is provided.
  foreach (const CommandInfo::URI& uri, commandInfo.uris()) {
    // Fetch the URI to a local file.
    Try<string> fetched = fetch(uri.value(), directory);
    if (fetched.isError()) {
      EXIT(1) << "Failed to fetch: " << uri.value();
    }

    // Chmod the fetched URI if it's executable, else assume it's an archive
    // that should be extracted.
    if (uri.executable()) {
      bool chmodded = os::chmod(
          fetched.get(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
      if (!chmodded) {
        EXIT(1) << "Failed to chmod: " << fetched.get();
      }
    } else {
      //TODO(idownes): Consider removing the archive once extracted.
      // Try to extract the file if it's recognized as an archive.
      Try<bool> extracted = extract(fetched.get(), directory);
      if (extracted.isError()) {
        EXIT(1) << "Failed to extract "
                << fetched.get() << ":" << extracted.error();
      }
    }

    // Recursively chown the directory if a user is provided.
    if (user.isSome()) {
      Try<Nothing> chowned = os::chown(user.get(), directory);
      if (chowned.isError()) {
        EXIT(1) << "Failed to chown " << directory << ": " << chowned.error();
      }
    }
  }

  return 0;
}
<commit_msg>Updated dash in front of flags for tar command in fetcher.<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.
 */

#include <string>

#include <mesos/mesos.hpp>

#include <stout/net.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/strings.hpp>

#include "hdfs/hdfs.hpp"

using namespace mesos;

using std::string;

// Try to extract filename into directory. If filename is recognized as an
// archive it will be extracted and true returned; if not recognized then false
// will be returned. An Error is returned if the extraction command fails.
Try<bool> extract(const string& filename, const string& directory)
{
  string command;
  // Extract any .tgz, tar.gz, tar.bz2 or zip files.
  if (strings::endsWith(filename, ".tgz") ||
      strings::endsWith(filename, ".tar.gz") ||
      strings::endsWith(filename, ".tbz2") ||
      strings::endsWith(filename, ".tar.bz2") ||
      strings::endsWith(filename, ".txz") ||
      strings::endsWith(filename, ".tar.xz")) {
    command = "tar -C '" + directory + "' -xJf";
  } else if (strings::endsWith(filename, ".zip")) {
    command = "unzip -d '" + directory + "'";
  } else {
    return false;
  }

  command += " '" + filename + "'";
  int status = os::system(command);
  if (status != 0) {
    return Error("Failed to extract: command " + command +
                 " exited with status: " + stringify(status));
  }

  LOG(INFO) << "Extracted resource '" << filename
            << "' into '" << directory << "'";

  return true;
}

// Fetch URI into directory.
Try<string> fetch(
    const string& uri,
    const string& directory)
{
  LOG(INFO) << "Fetching URI '" << uri << "'";

  // Some checks to make sure using the URI value in shell commands
  // is safe. TODO(benh): These should be pushed into the scheduler
  // driver and reported to the user.
  if (uri.find_first_of('\\') != string::npos ||
      uri.find_first_of('\'') != string::npos ||
      uri.find_first_of('\0') != string::npos) {
    LOG(ERROR) << "URI contains illegal characters, refusing to fetch";
    return Error("Illegal characters in URI");
  }

  // Grab the resource from HDFS if its path begins with hdfs:// or
  // hftp:
  // TODO(matei): Enforce some size limits on files we get from HDFS
  if (strings::startsWith(uri, "hdfs://") ||
      strings::startsWith(uri, "hftp://")) {
    Try<string> base = os::basename(uri);
    if (base.isError()) {
      LOG(ERROR) << "Invalid basename for URI: " << base.error();
      return Error("Invalid basename for URI");
    }
    string path = path::join(directory, base.get());

    HDFS hdfs;

    LOG(INFO) << "Downloading resource from '" << uri
              << "' to '" << path << "'";
    Try<Nothing> result = hdfs.copyToLocal(uri, path);
    if (result.isError()) {
      LOG(ERROR) << "HDFS copyToLocal failed: " << result.error();
      return Error(result.error());
    }

    return path;
  } else if (strings::startsWith(uri, "http://") ||
             strings::startsWith(uri, "https://") ||
             strings::startsWith(uri, "ftp://") ||
             strings::startsWith(uri, "ftps://")) {
    string path = uri.substr(uri.find("://") + 3);
    if (path.find("/") == string::npos ||
        path.size() <= path.find("/") + 1) {
      LOG(ERROR) << "Malformed URL (missing path)";
      return Error("Malformed URI");
    }

    path =  path::join(directory, path.substr(path.find_last_of("/") + 1));
    LOG(INFO) << "Downloading '" << uri << "' to '" << path << "'";
    Try<int> code = net::download(uri, path);
    if (code.isError()) {
      LOG(ERROR) << "Error downloading resource: " << code.error().c_str();
      return Error("Fetch of URI failed (" + code.error() + ")");
    } else if (code.get() != 200) {
      LOG(ERROR) << "Error downloading resource, received HTTP/FTP return code "
                 << code.get();
      return Error("HTTP/FTP error (" + stringify(code.get()) + ")");
    }

    return path;
  } else { // Copy the local resource.
    string local = uri;
    if (local.find_first_of("/") != 0) {
      // We got a non-Hadoop and non-absolute path.
      if (os::hasenv("MESOS_FRAMEWORKS_HOME")) {
        local = path::join(os::getenv("MESOS_FRAMEWORKS_HOME"), local);
        LOG(INFO) << "Prepended environment variable "
                  << "MESOS_FRAMEWORKS_HOME to relative path, "
                  << "making it: '" << local << "'";
      } else {
        LOG(ERROR) << "A relative path was passed for the resource but the "
                   << "environment variable MESOS_FRAMEWORKS_HOME is not set. "
                   << "Please either specify this config option "
                   << "or avoid using a relative path";
        return Error("Could not resolve relative URI");
      }
    }

    Try<string> base = os::basename(local);
    if (base.isError()) {
      LOG(ERROR) << base.error();
      return Error("Fetch of URI failed");
    }

    // Copy the resource to the directory.
    string path = path::join(directory, base.get());
    std::ostringstream command;
    command << "cp '" << local << "' '" << path << "'";
    LOG(INFO) << "Copying resource from '" << local
              << "' to '" << directory << "'";

    int status = os::system(command.str());
    if (status != 0) {
      LOG(ERROR) << "Failed to copy '" << local
                 << "' : Exit status " << status;
      return Error("Local copy failed");
    }

    return path;
  }
}

int main(int argc, char* argv[])
{
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  CommandInfo commandInfo;
  // Construct URIs from the encoded environment string.
  const std::string& uris = os::getenv("MESOS_EXECUTOR_URIS");
  foreach (const std::string& token, strings::tokenize(uris, " ")) {
    // Delimiter between URI and execute permission.
    size_t pos = token.rfind("+");
    CHECK(pos != std::string::npos)
      << "Invalid executor uri token in env " << token;

    CommandInfo::URI uri;
    uri.set_value(token.substr(0, pos));
    uri.set_executable(token.substr(pos + 1) == "1");

    commandInfo.add_uris()->MergeFrom(uri);
  }

  CHECK(os::hasenv("MESOS_WORK_DIRECTORY"))
    << "Missing MESOS_WORK_DIRECTORY environment variable";
  std::string directory = os::getenv("MESOS_WORK_DIRECTORY");

  // We cannot use Some in the ternary expression because the compiler needs to
  // be able to infer the type, thus the explicit Option<string>.
  // TODO(idownes): Add an os::hasenv that returns an Option<string>.
  Option<std::string> user = os::hasenv("MESOS_USER")
    ? Option<std::string>(os::getenv("MESOS_USER")) // Explicit so it compiles.
    : None();

  // Fetch each URI to a local file, chmod, then chown if a user is provided.
  foreach (const CommandInfo::URI& uri, commandInfo.uris()) {
    // Fetch the URI to a local file.
    Try<string> fetched = fetch(uri.value(), directory);
    if (fetched.isError()) {
      EXIT(1) << "Failed to fetch: " << uri.value();
    }

    // Chmod the fetched URI if it's executable, else assume it's an archive
    // that should be extracted.
    if (uri.executable()) {
      bool chmodded = os::chmod(
          fetched.get(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
      if (!chmodded) {
        EXIT(1) << "Failed to chmod: " << fetched.get();
      }
    } else {
      //TODO(idownes): Consider removing the archive once extracted.
      // Try to extract the file if it's recognized as an archive.
      Try<bool> extracted = extract(fetched.get(), directory);
      if (extracted.isError()) {
        EXIT(1) << "Failed to extract "
                << fetched.get() << ":" << extracted.error();
      }
    }

    // Recursively chown the directory if a user is provided.
    if (user.isSome()) {
      Try<Nothing> chowned = os::chown(user.get(), directory);
      if (chowned.isError()) {
        EXIT(1) << "Failed to chown " << directory << ": " << chowned.error();
      }
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
 * TTBlue Audio Object Base Class
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTAudioObject.h"
#include "TTEnvironment.h"

// This coeff is used in GainDataspace mapping MIDI to and from linear gain
// so that MIDI=100 equals 0 dB and MIDI = 127 equals +10 dB
static const double kGainMidiPower = log(pow(10.,10./20.))/log(127./100.);
static const double kGainMidiPowerInv = 1./kGainMidiPower;

/****************************************************************************************************/

TTAudioObject::TTAudioObject(const char* name, TTUInt16 newMaxNumChannels)
	: TTObject(name), attrMute(0)
{
	registerAttribute(TT("maxNumChannels"), kTypeUInt8,		&maxNumChannels,	(TTSetterMethod)&TTAudioObject::setMaxNumChannels);
	registerAttribute(TT("sr"),				kTypeUInt32,	&sr,				(TTSetterMethod)&TTAudioObject::setSr);
	registerAttribute(TT("bypass"),			kTypeBoolean,	&attrBypass,		(TTSetterMethod)&TTAudioObject::setBypass);
	registerAttribute(TT("mute"),			kTypeBoolean,	&attrMute,			(TTSetterMethod)&TTAudioObject::setMute);
	registerAttribute(TT("processInPlace"), kTypeBoolean,	&attrProcessInPlace);

	// Set Defaults...
	setAttributeValue(TT("maxNumChannels"),	newMaxNumChannels);
	setAttributeValue(TT("sr"),				ttEnvironment->sr);
	setProcess(&TTAudioObject::bypassProcess);
	setProcessWithSidechain(&TTAudioObject::bypassWithSidechainProcess);
	setAttributeValue(TT("bypass"),			*kTTBoolNo);
	setAttributeValue(TT("processInPlace"), *kTTBoolNo);
}

TTAudioObject::~TTAudioObject()
{
	;
}

TTErr TTAudioObject::setMaxNumChannels(const TTValue& newValue)
{
	TTValue	oldMaxNumChannels = maxNumChannels;

	maxNumChannels = newValue;
	sendMessage(TT("updateMaxNumChannels"), oldMaxNumChannels);
	return kTTErrNone;
}

TTErr TTAudioObject::setSr(const TTValue& newValue)
{
	sr = newValue;
	srInv = 1.0/sr;
	srMill = sr * 0.001;
	sendMessage(TT("updateSr"));
	return kTTErrNone;
}

TTErr TTAudioObject::bypassProcess(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSample,
	*outSample;
	short			numchannels = TTAudioSignal::getMinChannelCount(in, out);
	short			channel;

	for(channel=0; channel<numchannels; channel++){
		inSample = in.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::bypassWithSidechainProcess(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTUInt16		vs;
	TTSampleValue	*inSample,
	*outSample;
	TTUInt16		numChannelsMain = TTAudioSignal::getMinChannelCount(in1, out1);
	TTUInt16		numChannelsSidechain = TTAudioSignal::getMinChannelCount(in2, out2);
	TTUInt16		channel;

	for(channel=0; channel<numChannelsMain; channel++){
		inSample = in1.sampleVectors[channel];
		outSample = out1.sampleVectors[channel];
		vs = in1.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	for(channel=0; channel<numChannelsSidechain; channel++){
		inSample = in2.sampleVectors[channel];
		outSample = out2.sampleVectors[channel];
		vs = in2.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::muteProcess(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue*	outSample;
	short			numchannels = TTAudioSignal::getMinChannelCount(in, out);
	short			channel;

	for(channel=0; channel<numchannels; channel++){
		outSample = out.sampleVectors[channel];
		vs = out.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::muteWithSidechainProcess(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTUInt16		vs;
	TTSampleValue*	outSample;
	TTUInt16		numChannelsMain = TTAudioSignal::getMinChannelCount(in1, out1);
	TTUInt16		numChannelsSidechain = TTAudioSignal::getMinChannelCount(in2, out2);
	TTUInt16		channel;

	for(channel=0; channel<numChannelsMain; channel++){
		outSample = out1.sampleVectors[channel];
		vs = out1.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	for(channel=0; channel<numChannelsSidechain; channel++){
		outSample = out2.sampleVectors[channel];
		vs = out2.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::setProcess(TTProcessMethod newProcessMethod)
{
	processMethod = newProcessMethod;
	if(!attrBypass)
		currentProcessMethod = processMethod;
	return kTTErrNone;
}

TTErr TTAudioObject::setProcessWithSidechain(TTProcessWithSidechainMethod newProcessMethod)
{
	processWithSidechainMethod = newProcessMethod;
	if(!attrBypass)
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	return kTTErrNone;
}

TTErr TTAudioObject::setBypass(const TTValue& value)
{
	attrBypass = value;
	if(attrBypass){
		currentProcessMethod = &TTAudioObject::bypassProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::bypassWithSidechainProcess;
	}
	else if(attrMute){
		currentProcessMethod = &TTAudioObject::muteProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::muteWithSidechainProcess;
	}
	else{
		currentProcessMethod = processMethod;
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::setMute(const TTValue& value)
{
	attrBypass = value;
	if(attrBypass){
		currentProcessMethod = &TTAudioObject::bypassProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::bypassWithSidechainProcess;
	}
	else if(attrMute){
		currentProcessMethod = &TTAudioObject::muteProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::muteWithSidechainProcess;
	}
	else{
		currentProcessMethod = processMethod;
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::process(TTAudioSignal& in, TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessMethod)(in, out);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessMethod)(out, out);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessWithSidechainMethod)(in1, in2, out1, out2);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessWithSidechainMethod)(in1, in2, out, out);
	unlock();
	return err;
}

#if 0
#pragma mark -
#pragma mark Utilities
#endif

// RADIANS CONVERSIONS: cannot make static because of access to a member data element
// hz-to-radians conversion
TTFloat64 TTAudioObject::hertzToRadians(const TTFloat64 hz)			// NOTE: Be sure to set the sr before calling this function
{
	return(hz * (kTTPi / (sr * 0.5)));
}

// radians-to-hz conversion
TTFloat64 TTAudioObject::radiansToHertz(const TTFloat64 radians)	// NOTE: Be sure to set the sr before calling this function
{
	return((radians * sr) / kTTTwoPi);
}

// degrees-to-radians conversion
TTFloat64 TTAudioObject::degreesToRadians(const TTFloat64 degrees)
{
	return((degrees * kTTPi) / 180.);
}

// radians-to-degrees conversion
TTFloat64 TTAudioObject::radiansToDegrees(const TTFloat64 radians)
{
	return((radians * 180.) / kTTPi);
}

// Decay Time (seconds) to feedback coefficient conversion
TTFloat64 TTAudioObject::decayToFeedback(const TTFloat64 decay_time, TTFloat64 delay)
{
	TTFloat64 	fb;

	delay = delay * 0.001;			// convert delay from milliseconds to seconds
	if(decay_time < 0){
		fb = delay / -decay_time;
		fb = fb * -60.;
		fb = pow(10., (fb / 20.));
		fb *= -1.;
	}
	else{
		fb = delay / decay_time;
		fb = fb * -60.;
		fb = pow(10., (fb / 20.));
	}
	return(fb);
}

// return the decay time based on the feedback coefficient
TTFloat64 TTAudioObject::feedbackToDecay(const TTFloat64 feedback, const TTFloat64 delay)
{
	TTFloat64 	decay_time;

	if(feedback > 0){
		decay_time = 20. * (log10(feedback));
		decay_time = -60.0 / decay_time;
		decay_time = decay_time * (delay);
	}
	else if(feedback < 0){
		decay_time = 20. * (log10(fabs(feedback)));
		decay_time = -60.0 / decay_time;
		decay_time = decay_time * (-delay);
	}
	else
		decay_time = 0;

	return(decay_time);
}

// ************* DECIBEL CONVERSIONS **************

// Amplitude to decibels
TTFloat64 TTAudioObject::linearToDb(const TTFloat64 value)
{
	if(value >= 0)
		return(20. * (log10(value)));
	else
	 	return 0;
}

// Decibels to amplitude
TTFloat64 TTAudioObject::dbToLinear(TTFloat64 value)
{
	return(pow(10., (value / 20.)));
}

TTFloat64 TTAudioObject::midiToLinearGain(TTFloat64 value)
{
	return pow(value * 0.01, kGainMidiPower);
}

TTFloat64 TTAudioObject::linearGainToMidi(TTFloat64 value)
{
	return 100.0 * pow(value, kGainMidiPowerInv);
}

// Deviate
TTFloat64 TTAudioObject::deviate(TTFloat64 value)
{
	value += (2.0 * (TTFloat32(rand()) / TTFloat32(RAND_MAX))) - 1.0;	// randomize input with +1 to -1 ms
	value = value * 0.001 * sr;											// convert from ms to samples
	value = (TTFloat32)prime(TTUInt32(value));							// find the nearest prime number (in samples)
	value = (value / sr) * 1000.0;										// convert back to ms

	return value;
}

// Prime
TTUInt32 TTAudioObject::prime(TTUInt32 value)
{
	long	candidate, last, i, isPrime;

   	if(value < 2)
  		candidate = 2;
	else if(value == 2)
		candidate = 3;
	else{
		candidate = value;
		if (candidate % 2 == 0)								// Test only odd numbers
			candidate--;
		do{
			isPrime = true;									// Assume glorious success
			candidate += 2;									// Bump to the next number to test
			last = TTUInt32(sqrt((TTFloat32)candidate));  	// We'll check to see if candidate has any factors, from 2 to last
			for (i=3; (i <= last) && isPrime; i+=2){		// Loop through odd numbers only
				if((candidate % i) == 0)
				isPrime = false;
			}
		}
		while (!isPrime);
	}
	return candidate;
}

<commit_msg>Fixed bug in the 'mute' attribute setter where it instead controlled the bypass.<commit_after>/*
 * TTBlue Audio Object Base Class
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "TTAudioObject.h"
#include "TTEnvironment.h"

// This coeff is used in GainDataspace mapping MIDI to and from linear gain
// so that MIDI=100 equals 0 dB and MIDI = 127 equals +10 dB
static const double kGainMidiPower = log(pow(10.,10./20.))/log(127./100.);
static const double kGainMidiPowerInv = 1./kGainMidiPower;

/****************************************************************************************************/

TTAudioObject::TTAudioObject(const char* name, TTUInt16 newMaxNumChannels)
	: TTObject(name), attrMute(0)
{
	registerAttribute(TT("maxNumChannels"), kTypeUInt8,		&maxNumChannels,	(TTSetterMethod)&TTAudioObject::setMaxNumChannels);
	registerAttribute(TT("sr"),				kTypeUInt32,	&sr,				(TTSetterMethod)&TTAudioObject::setSr);
	registerAttribute(TT("bypass"),			kTypeBoolean,	&attrBypass,		(TTSetterMethod)&TTAudioObject::setBypass);
	registerAttribute(TT("mute"),			kTypeBoolean,	&attrMute,			(TTSetterMethod)&TTAudioObject::setMute);
	registerAttribute(TT("processInPlace"), kTypeBoolean,	&attrProcessInPlace);

	// Set Defaults...
	setAttributeValue(TT("maxNumChannels"),	newMaxNumChannels);
	setAttributeValue(TT("sr"),				ttEnvironment->sr);
	setProcess(&TTAudioObject::bypassProcess);
	setProcessWithSidechain(&TTAudioObject::bypassWithSidechainProcess);
	setAttributeValue(TT("bypass"),			*kTTBoolNo);
	setAttributeValue(TT("processInPlace"), *kTTBoolNo);
}

TTAudioObject::~TTAudioObject()
{
	;
}

TTErr TTAudioObject::setMaxNumChannels(const TTValue& newValue)
{
	TTValue	oldMaxNumChannels = maxNumChannels;

	maxNumChannels = newValue;
	sendMessage(TT("updateMaxNumChannels"), oldMaxNumChannels);
	return kTTErrNone;
}

TTErr TTAudioObject::setSr(const TTValue& newValue)
{
	sr = newValue;
	srInv = 1.0/sr;
	srMill = sr * 0.001;
	sendMessage(TT("updateSr"));
	return kTTErrNone;
}

TTErr TTAudioObject::bypassProcess(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue	*inSample,
	*outSample;
	short			numchannels = TTAudioSignal::getMinChannelCount(in, out);
	short			channel;

	for(channel=0; channel<numchannels; channel++){
		inSample = in.sampleVectors[channel];
		outSample = out.sampleVectors[channel];
		vs = in.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::bypassWithSidechainProcess(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTUInt16		vs;
	TTSampleValue	*inSample,
	*outSample;
	TTUInt16		numChannelsMain = TTAudioSignal::getMinChannelCount(in1, out1);
	TTUInt16		numChannelsSidechain = TTAudioSignal::getMinChannelCount(in2, out2);
	TTUInt16		channel;

	for(channel=0; channel<numChannelsMain; channel++){
		inSample = in1.sampleVectors[channel];
		outSample = out1.sampleVectors[channel];
		vs = in1.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	for(channel=0; channel<numChannelsSidechain; channel++){
		inSample = in2.sampleVectors[channel];
		outSample = out2.sampleVectors[channel];
		vs = in2.getVectorSize();
		while(vs--)
			*outSample++ = *inSample++;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::muteProcess(TTAudioSignal& in, TTAudioSignal& out)
{
	short			vs;
	TTSampleValue*	outSample;
	short			numchannels = TTAudioSignal::getMinChannelCount(in, out);
	short			channel;

	for(channel=0; channel<numchannels; channel++){
		outSample = out.sampleVectors[channel];
		vs = out.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::muteWithSidechainProcess(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTUInt16		vs;
	TTSampleValue*	outSample;
	TTUInt16		numChannelsMain = TTAudioSignal::getMinChannelCount(in1, out1);
	TTUInt16		numChannelsSidechain = TTAudioSignal::getMinChannelCount(in2, out2);
	TTUInt16		channel;

	for(channel=0; channel<numChannelsMain; channel++){
		outSample = out1.sampleVectors[channel];
		vs = out1.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	for(channel=0; channel<numChannelsSidechain; channel++){
		outSample = out2.sampleVectors[channel];
		vs = out2.getVectorSize();
		while(vs--)
			*outSample++ = 0.0;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::setProcess(TTProcessMethod newProcessMethod)
{
	processMethod = newProcessMethod;
	if(!attrBypass)
		currentProcessMethod = processMethod;
	return kTTErrNone;
}

TTErr TTAudioObject::setProcessWithSidechain(TTProcessWithSidechainMethod newProcessMethod)
{
	processWithSidechainMethod = newProcessMethod;
	if(!attrBypass)
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	return kTTErrNone;
}

TTErr TTAudioObject::setBypass(const TTValue& value)
{
	attrBypass = value;
	if(attrBypass){
		currentProcessMethod = &TTAudioObject::bypassProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::bypassWithSidechainProcess;
	}
	else if(attrMute){
		currentProcessMethod = &TTAudioObject::muteProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::muteWithSidechainProcess;
	}
	else{
		currentProcessMethod = processMethod;
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::setMute(const TTValue& value)
{
	attrMute = value;
	if(attrBypass){
		currentProcessMethod = &TTAudioObject::bypassProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::bypassWithSidechainProcess;
	}
	else if(attrMute){
		currentProcessMethod = &TTAudioObject::muteProcess;
		currentProcessWithSidechainMethod = &TTAudioObject::muteWithSidechainProcess;
	}
	else{
		currentProcessMethod = processMethod;
		currentProcessWithSidechainMethod = processWithSidechainMethod;
	}
	return kTTErrNone;
}

TTErr TTAudioObject::process(TTAudioSignal& in, TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessMethod)(in, out);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessMethod)(out, out);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out1, TTAudioSignal& out2)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessWithSidechainMethod)(in1, in2, out1, out2);
	unlock();
	return err;
}

TTErr TTAudioObject::process(TTAudioSignal& in1, TTAudioSignal& in2, TTAudioSignal& out)
{
	TTErr	err;

	lock();
	err = (this->*currentProcessWithSidechainMethod)(in1, in2, out, out);
	unlock();
	return err;
}

#if 0
#pragma mark -
#pragma mark Utilities
#endif

// RADIANS CONVERSIONS: cannot make static because of access to a member data element
// hz-to-radians conversion
TTFloat64 TTAudioObject::hertzToRadians(const TTFloat64 hz)			// NOTE: Be sure to set the sr before calling this function
{
	return(hz * (kTTPi / (sr * 0.5)));
}

// radians-to-hz conversion
TTFloat64 TTAudioObject::radiansToHertz(const TTFloat64 radians)	// NOTE: Be sure to set the sr before calling this function
{
	return((radians * sr) / kTTTwoPi);
}

// degrees-to-radians conversion
TTFloat64 TTAudioObject::degreesToRadians(const TTFloat64 degrees)
{
	return((degrees * kTTPi) / 180.);
}

// radians-to-degrees conversion
TTFloat64 TTAudioObject::radiansToDegrees(const TTFloat64 radians)
{
	return((radians * 180.) / kTTPi);
}

// Decay Time (seconds) to feedback coefficient conversion
TTFloat64 TTAudioObject::decayToFeedback(const TTFloat64 decay_time, TTFloat64 delay)
{
	TTFloat64 	fb;

	delay = delay * 0.001;			// convert delay from milliseconds to seconds
	if(decay_time < 0){
		fb = delay / -decay_time;
		fb = fb * -60.;
		fb = pow(10., (fb / 20.));
		fb *= -1.;
	}
	else{
		fb = delay / decay_time;
		fb = fb * -60.;
		fb = pow(10., (fb / 20.));
	}
	return(fb);
}

// return the decay time based on the feedback coefficient
TTFloat64 TTAudioObject::feedbackToDecay(const TTFloat64 feedback, const TTFloat64 delay)
{
	TTFloat64 	decay_time;

	if(feedback > 0){
		decay_time = 20. * (log10(feedback));
		decay_time = -60.0 / decay_time;
		decay_time = decay_time * (delay);
	}
	else if(feedback < 0){
		decay_time = 20. * (log10(fabs(feedback)));
		decay_time = -60.0 / decay_time;
		decay_time = decay_time * (-delay);
	}
	else
		decay_time = 0;

	return(decay_time);
}

// ************* DECIBEL CONVERSIONS **************

// Amplitude to decibels
TTFloat64 TTAudioObject::linearToDb(const TTFloat64 value)
{
	if(value >= 0)
		return(20. * (log10(value)));
	else
	 	return 0;
}

// Decibels to amplitude
TTFloat64 TTAudioObject::dbToLinear(TTFloat64 value)
{
	return(pow(10., (value / 20.)));
}

TTFloat64 TTAudioObject::midiToLinearGain(TTFloat64 value)
{
	return pow(value * 0.01, kGainMidiPower);
}

TTFloat64 TTAudioObject::linearGainToMidi(TTFloat64 value)
{
	return 100.0 * pow(value, kGainMidiPowerInv);
}

// Deviate
TTFloat64 TTAudioObject::deviate(TTFloat64 value)
{
	value += (2.0 * (TTFloat32(rand()) / TTFloat32(RAND_MAX))) - 1.0;	// randomize input with +1 to -1 ms
	value = value * 0.001 * sr;											// convert from ms to samples
	value = (TTFloat32)prime(TTUInt32(value));							// find the nearest prime number (in samples)
	value = (value / sr) * 1000.0;										// convert back to ms

	return value;
}

// Prime
TTUInt32 TTAudioObject::prime(TTUInt32 value)
{
	long	candidate, last, i, isPrime;

   	if(value < 2)
  		candidate = 2;
	else if(value == 2)
		candidate = 3;
	else{
		candidate = value;
		if (candidate % 2 == 0)								// Test only odd numbers
			candidate--;
		do{
			isPrime = true;									// Assume glorious success
			candidate += 2;									// Bump to the next number to test
			last = TTUInt32(sqrt((TTFloat32)candidate));  	// We'll check to see if candidate has any factors, from 2 to last
			for (i=3; (i <= last) && isPrime; i+=2){		// Loop through odd numbers only
				if((candidate % i) == 0)
				isPrime = false;
			}
		}
		while (!isPrime);
	}
	return candidate;
}

<|endoftext|>


<commit_before><commit_msg>Ash non-native cursor should fall back to default pointer cursor for custom cursor.<commit_after><|endoftext|>


<commit_before>#pragma once

#include <sam.h>

#include <boost/format.hpp>

#include <stdexcept>

class SamReader {
public:
    SamReader(char const* path, char const* mode)
        : path_(path)
        , fp_(hts_open(path, mode))
        , required_flags_(0)
        , skip_flags_(0)
        , record_count_(0)
    {
        using boost::format;
        if (!fp_ || !(header_ = sam_hdr_read(fp_))) {
            throw std::runtime_error(str(format(
                "Failed to open input file %1%"
                ) % path));
        }
    }

    ~SamReader() {
        if (header_)
            bam_hdr_destroy(header_);

        if (fp_)
            hts_close(fp_);
    }

    void required_flags(uint32_t flags) {
        required_flags_ = flags;
    }

    void skip_flags(uint32_t flags) {
        skip_flags_ = flags;
    }

    bool want(uint32_t flag) const {
        return (flag & required_flags_) == required_flags_
            && (flag & skip_flags_) == 0;
    }

    bool next(bam1_t* record) {
        while (sam_read1(fp_, header_, record) > 0) {
            if (want(record->core.flag)) {
                ++record_count_;
                return true;
            }
        }
        return false;
    }

    std::size_t record_count() const {
        return record_count_;
    }

    char const* path() const {
        return path_;
    }

private:
    char const* path_;
    htsFile* fp_;
    bam_hdr_t* header_;
    uint32_t required_flags_;
    uint32_t skip_flags_;
    std::size_t record_count_;
};
<commit_msg>count skipped records as well. Should help with basic sanity checking.<commit_after>#pragma once

#include <sam.h>

#include <boost/format.hpp>

#include <stdexcept>

class SamReader {
public:
    SamReader(char const* path, char const* mode)
        : path_(path)
        , fp_(hts_open(path, mode))
        , required_flags_(0)
        , skip_flags_(0)
        , record_count_(0)
        , skipped_count_(0)
    {
        using boost::format;
        if (!fp_ || !(header_ = sam_hdr_read(fp_))) {
            throw std::runtime_error(str(format(
                "Failed to open input file %1%"
                ) % path));
        }
    }

    ~SamReader() {
        if (header_)
            bam_hdr_destroy(header_);

        if (fp_)
            hts_close(fp_);
    }

    void required_flags(uint32_t flags) {
        required_flags_ = flags;
    }

    void skip_flags(uint32_t flags) {
        skip_flags_ = flags;
    }

    bool want(uint32_t flag) const {
        return (flag & required_flags_) == required_flags_
            && (flag & skip_flags_) == 0;
    }

    bool next(bam1_t* record) {
        while (sam_read1(fp_, header_, record) > 0) {
            if (want(record->core.flag)) {
                ++record_count_;
                return true;
            }
            else {
                ++skipped_count_;
            }
        }
        return false;
    }

    std::size_t record_count() const {
        return record_count_;
    }

    std::size_t skipped_count() const {
        return skipped_count_;
    }

    char const* path() const {
        return path_;
    }

private:
    char const* path_;
    htsFile* fp_;
    bam_hdr_t* header_;
    uint32_t required_flags_;
    uint32_t skip_flags_;
    std::size_t record_count_;
    std::size_t skipped_count_;
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/event_emitter_caller.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  v8::Local<v8::String> emit_name = StringToSymbol(isolate, "emit");
  v8::Local<v8::Value> emit = obj->Get(emit_name);
  if (emit.IsEmpty() || !emit->IsFunction()) {
    isolate->ThrowException(v8::Exception::TypeError(
        StringToV8(isolate, "\"emit\" is not a function")));
    return v8::Undefined(isolate);
  }

  v8::MaybeLocal<v8::Value> result = emit.As<v8::Function>()->Call(
      isolate->GetCurrentContext(), obj, args->size(), &args->front());
  if (result.IsEmpty()) {
    return v8::Undefined(isolate);
  }

  return result.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate
<commit_msg>Use node::MakeCallback to emit events in C++<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/event_emitter_caller.h"

#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  return node::MakeCallback(
      isolate, obj, "emit", args->size(), &args->front());
}

}  // namespace internal

}  // namespace mate
<|endoftext|>


<commit_before>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2006 Refractions Research Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: noding/ScaledNoder.java rev. 1.3 (JTS-1.7.1)
 *
 **********************************************************************/

#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h> // for apply and delete
#include <geos/geom/CoordinateFilter.h> // for inheritance
#include <geos/noding/ScaledNoder.h>
#include <geos/noding/SegmentString.h>
#include <geos/util/math.h>
#include <geos/util.h>

#include <functional>
#include <vector>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#include <string>
#endif

using namespace geos::geom;

namespace geos {
namespace noding { // geos.noding

namespace {

#if GEOS_DEBUG > 1
void
sqlPrint(const std::string& table, std::vector<SegmentString*>& ssv)
{
	std::cerr << "CREATE TABLE \"" << table
		<< "\" (id integer, geom geometry);" << std::endl;

	std::cerr << "COPY \"" << table
		<< "\" FROM stdin;" << std::endl;

	for (size_t i=0, n=ssv.size(); i<n; i++)
	{
		SegmentString* ss=ssv[i];
		geom::CoordinateSequence* cs = ss->getCoordinates();
		assert(cs);

		std::cerr << i << '\t' << "LINESTRING"
			<< *cs
			<< std::endl;
	}
	std::cerr << "\\." << std::endl;
}
#endif // GEOS_DEBUG > 1

} // anonym namespace

class ScaledNoder::Scaler : public geom::CoordinateFilter {
public:
	const ScaledNoder& sn;
	Scaler(const ScaledNoder&n): sn(n)
	{
#ifdef GEOS_DEBUG
		std::cerr << "Scaler: offsetX,Y: " << sn.offsetX << ","
			<< sn.offsetY << " scaleFactor: " << sn.scaleFactor
			<< std::endl;
#endif
	}

	//void filter_ro(const geom::Coordinate* c) { assert(0); }

	void filter_rw(geom::Coordinate* c) const {
		c->x = util::round( ( c->x - sn.offsetX ) * sn.scaleFactor );
		c->y = util::round( ( c->y - sn.offsetY ) * sn.scaleFactor );
	}

private:
    // Declare type as noncopyable
    ScaledNoder::Scaler(const ScaledNoder::Scaler& other);
    ScaledNoder::Scaler& operator=(const ScaledNoder::Scaler& rhs);
};

class ScaledNoder::ReScaler: public geom::CoordinateFilter {
public:
	const ScaledNoder& sn;
	ReScaler(const ScaledNoder&n): sn(n)
	{
#ifdef GEOS_DEBUG
		std::cerr << "ReScaler: offsetX,Y: " << sn.offsetX << ","
			<< sn.offsetY << " scaleFactor: " << sn.scaleFactor
			<< std::endl;
#endif
	}

	void filter_ro(const geom::Coordinate* c)
    {
        ::geos::ignore_unused_variable_warning(c);
        assert(0);
    }

	void filter_rw(geom::Coordinate* c) const {
		c->x = c->x / sn.scaleFactor + sn.offsetX;
		c->y = c->y / sn.scaleFactor + sn.offsetY;
	}

private:
    // Declare type as noncopyable
    ScaledNoder::ReScaler(const ScaledNoder::ReScaler& other);
    ScaledNoder::ReScaler& operator=(const ScaledNoder::ReScaler& rhs);
};

/*private*/
void
ScaledNoder::rescale(SegmentString::NonConstVect& segStrings) const
{
	ReScaler rescaler(*this);
	for (SegmentString::NonConstVect::const_iterator
		i0=segStrings.begin(), i0End=segStrings.end();
			i0!=i0End; ++i0)
	{

		SegmentString* ss=*i0;

		ss->getCoordinates()->apply_rw(&rescaler);

	}
}

/*private*/
void
ScaledNoder::scale(SegmentString::NonConstVect& segStrings) const
{
	Scaler scaler(*this);
	for (SegmentString::NonConstVect::const_iterator
		i0=segStrings.begin(), i0End=segStrings.end();
			i0!=i0End; ++i0)
	{
		SegmentString* ss=*i0;

		CoordinateSequence* cs=ss->getCoordinates();

#ifndef NDEBUG
		size_t npts = cs->size();
#endif
		cs->apply_rw(&scaler);
		assert(cs->size() == npts);

		// Actually, we should be creating *new*
		// SegmentStrings here, but who's going
		// to delete them then ? And is it worth
		// the memory cost ?
		cs->removeRepeatedPoints();

	}
}

ScaledNoder::~ScaledNoder()
{
	for (std::vector<geom::CoordinateSequence*>::const_iterator
		it=newCoordSeq.begin(), end=newCoordSeq.end();
		it != end;
		++it)
	{
		delete *it;
	}
}

/*public*/
SegmentString::NonConstVect*
ScaledNoder::getNodedSubstrings() const
{
	SegmentString::NonConstVect* splitSS = noder.getNodedSubstrings();

#if GEOS_DEBUG > 1
	sqlPrint("nodedSegStr", *splitSS);
#endif

	if ( isScaled ) rescale(*splitSS);

#if GEOS_DEBUG > 1
	sqlPrint("scaledNodedSegStr", *splitSS);
#endif

	return splitSS;

}

/*public*/
void
ScaledNoder::computeNodes(SegmentString::NonConstVect* inputSegStr)
{

#if GEOS_DEBUG > 1
	sqlPrint("inputSegStr", *inputSegStr);
#endif

	if (isScaled) scale(*inputSegStr);

#if GEOS_DEBUG > 1
	sqlPrint("scaledInputSegStr", *inputSegStr);
#endif

	noder.computeNodes(inputSegStr);
}

} // namespace geos.noding
} // namespace geos

/**********************************************************************
 * $Log$
 * Revision 1.14  2006/06/19 23:33:03  strk
 * Don't *require* CoordinateFilters to define both read-only and read-write methods.
 *
 * Revision 1.13  2006/05/04 14:05:31  strk
 * * source/headers/geos/util/math.h: provided an util::round() method being an inline proxy to call appropriate default rounding function for the whole GEOS codebase. Currently pointing at util::java_math_round() being the last being used.
 *
 * Revision 1.12  2006/05/04 08:30:02  strk
 * removed use of SegmentString::setCoordinates() [dropped]
 *
 * Revision 1.11  2006/05/03 20:05:18  strk
 * Added SQL debugging output
 *
 * Revision 1.10  2006/05/03 15:40:14  strk
 * test SegmentString invariant before and after scaling
 *
 * Revision 1.9  2006/05/03 15:12:35  strk
 * Oops, uninitialized value fix
 *
 * Revision 1.8  2006/05/03 15:00:43  strk
 * Fixed scale() function to remove repeated points *after* rounding. Added brief doxygen class description.
 *
 * Revision 1.7  2006/05/03 09:14:22  strk
 * * source/operation/buffer/OffsetCurveSetBuilder.cpp: used auto_ptr to protect leaks of CoordinateSequence
 * * source/noding/ScaledNoder.cpp, source/headers/geos/noding/ScaledNoder.h: ported JTS bugfix in scale method.
 *
 * Revision 1.6  2006/05/02 16:22:18  strk
 * * source/noding/ScaledNoder.cpp: use java_math_round instead of sym_round.
 *
 * Revision 1.5  2006/03/15 09:51:12  strk
 * streamlined headers usage
 *
 * Revision 1.4  2006/03/13 21:19:51  strk
 * Fixed bug in ScaledNoder scaling mechanism (hugly code, due to CoordinateSequence visitor pattern design). Tests are still failing so this possibly needs some other fix. Streamlined includes by implementation file.
 *
 * Revision 1.3  2006/02/23 11:54:20  strk
 * - MCIndexPointSnapper
 * - MCIndexSnapRounder
 * - SnapRounding BufferOp
 * - ScaledNoder
 * - GEOSException hierarchy cleanups
 * - SpatialIndex memory-friendly query interface
 * - GeometryGraph::getBoundaryNodes memory-friendly
 * - NodeMap::getBoundaryNodes memory-friendly
 * - Cleanups in geomgraph::Edge
 * - Added an XML test for snaprounding buffer (shows leaks, working on it)
 *
 * Revision 1.2  2006/02/19 19:46:49  strk
 * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
 *
 * Revision 1.1  2006/02/18 21:08:09  strk
 * - new CoordinateSequence::applyCoordinateFilter method (slow but useful)
 * - SegmentString::getCoordinates() doesn't return a clone anymore.
 * - SegmentString::getCoordinatesRO() obsoleted.
 * - SegmentString constructor does not promises constness of passed
 *   CoordinateSequence anymore.
 * - NEW ScaledNoder class
 * - Stubs for MCIndexPointSnapper and  MCIndexSnapRounder
 * - Simplified internal interaces of OffsetCurveBuilder and OffsetCurveSetBuilder
 *
 **********************************************************************/
<commit_msg>Refined changeset r2766 - fix for nested classes required by GCC.<commit_after>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2006 Refractions Research Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: noding/ScaledNoder.java rev. 1.3 (JTS-1.7.1)
 *
 **********************************************************************/

#include <geos/geom/Coordinate.h>
#include <geos/geom/CoordinateSequence.h> // for apply and delete
#include <geos/geom/CoordinateFilter.h> // for inheritance
#include <geos/noding/ScaledNoder.h>
#include <geos/noding/SegmentString.h>
#include <geos/util/math.h>
#include <geos/util.h>

#include <functional>
#include <vector>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#include <string>
#endif

using namespace geos::geom;

namespace geos {
namespace noding { // geos.noding

namespace {

#if GEOS_DEBUG > 1
void
sqlPrint(const std::string& table, std::vector<SegmentString*>& ssv)
{
	std::cerr << "CREATE TABLE \"" << table
		<< "\" (id integer, geom geometry);" << std::endl;

	std::cerr << "COPY \"" << table
		<< "\" FROM stdin;" << std::endl;

	for (size_t i=0, n=ssv.size(); i<n; i++)
	{
		SegmentString* ss=ssv[i];
		geom::CoordinateSequence* cs = ss->getCoordinates();
		assert(cs);

		std::cerr << i << '\t' << "LINESTRING"
			<< *cs
			<< std::endl;
	}
	std::cerr << "\\." << std::endl;
}
#endif // GEOS_DEBUG > 1

} // anonym namespace

class ScaledNoder::Scaler : public geom::CoordinateFilter {
public:
	const ScaledNoder& sn;
	Scaler(const ScaledNoder&n): sn(n)
	{
#ifdef GEOS_DEBUG
		std::cerr << "Scaler: offsetX,Y: " << sn.offsetX << ","
			<< sn.offsetY << " scaleFactor: " << sn.scaleFactor
			<< std::endl;
#endif
	}

	//void filter_ro(const geom::Coordinate* c) { assert(0); }

	void filter_rw(geom::Coordinate* c) const {
		c->x = util::round( ( c->x - sn.offsetX ) * sn.scaleFactor );
		c->y = util::round( ( c->y - sn.offsetY ) * sn.scaleFactor );
	}

private:
    // Declare type as noncopyable
    Scaler(const Scaler& other);
    Scaler& operator=(const Scaler& rhs);
};

class ScaledNoder::ReScaler: public geom::CoordinateFilter {
public:
	const ScaledNoder& sn;
	ReScaler(const ScaledNoder&n): sn(n)
	{
#ifdef GEOS_DEBUG
		std::cerr << "ReScaler: offsetX,Y: " << sn.offsetX << ","
			<< sn.offsetY << " scaleFactor: " << sn.scaleFactor
			<< std::endl;
#endif
	}

	void filter_ro(const geom::Coordinate* c)
    {
        ::geos::ignore_unused_variable_warning(c);
        assert(0);
    }

	void filter_rw(geom::Coordinate* c) const {
		c->x = c->x / sn.scaleFactor + sn.offsetX;
		c->y = c->y / sn.scaleFactor + sn.offsetY;
	}

private:
    // Declare type as noncopyable
    ReScaler(const ReScaler& other);
    ReScaler& operator=(const ReScaler& rhs);
};

/*private*/
void
ScaledNoder::rescale(SegmentString::NonConstVect& segStrings) const
{
	ReScaler rescaler(*this);
	for (SegmentString::NonConstVect::const_iterator
		i0=segStrings.begin(), i0End=segStrings.end();
			i0!=i0End; ++i0)
	{

		SegmentString* ss=*i0;

		ss->getCoordinates()->apply_rw(&rescaler);

	}
}

/*private*/
void
ScaledNoder::scale(SegmentString::NonConstVect& segStrings) const
{
	Scaler scaler(*this);
	for (SegmentString::NonConstVect::const_iterator
		i0=segStrings.begin(), i0End=segStrings.end();
			i0!=i0End; ++i0)
	{
		SegmentString* ss=*i0;

		CoordinateSequence* cs=ss->getCoordinates();

#ifndef NDEBUG
		size_t npts = cs->size();
#endif
		cs->apply_rw(&scaler);
		assert(cs->size() == npts);

		// Actually, we should be creating *new*
		// SegmentStrings here, but who's going
		// to delete them then ? And is it worth
		// the memory cost ?
		cs->removeRepeatedPoints();

	}
}

ScaledNoder::~ScaledNoder()
{
	for (std::vector<geom::CoordinateSequence*>::const_iterator
		it=newCoordSeq.begin(), end=newCoordSeq.end();
		it != end;
		++it)
	{
		delete *it;
	}
}

/*public*/
SegmentString::NonConstVect*
ScaledNoder::getNodedSubstrings() const
{
	SegmentString::NonConstVect* splitSS = noder.getNodedSubstrings();

#if GEOS_DEBUG > 1
	sqlPrint("nodedSegStr", *splitSS);
#endif

	if ( isScaled ) rescale(*splitSS);

#if GEOS_DEBUG > 1
	sqlPrint("scaledNodedSegStr", *splitSS);
#endif

	return splitSS;

}

/*public*/
void
ScaledNoder::computeNodes(SegmentString::NonConstVect* inputSegStr)
{

#if GEOS_DEBUG > 1
	sqlPrint("inputSegStr", *inputSegStr);
#endif

	if (isScaled) scale(*inputSegStr);

#if GEOS_DEBUG > 1
	sqlPrint("scaledInputSegStr", *inputSegStr);
#endif

	noder.computeNodes(inputSegStr);
}

} // namespace geos.noding
} // namespace geos

/**********************************************************************
 * $Log$
 * Revision 1.14  2006/06/19 23:33:03  strk
 * Don't *require* CoordinateFilters to define both read-only and read-write methods.
 *
 * Revision 1.13  2006/05/04 14:05:31  strk
 * * source/headers/geos/util/math.h: provided an util::round() method being an inline proxy to call appropriate default rounding function for the whole GEOS codebase. Currently pointing at util::java_math_round() being the last being used.
 *
 * Revision 1.12  2006/05/04 08:30:02  strk
 * removed use of SegmentString::setCoordinates() [dropped]
 *
 * Revision 1.11  2006/05/03 20:05:18  strk
 * Added SQL debugging output
 *
 * Revision 1.10  2006/05/03 15:40:14  strk
 * test SegmentString invariant before and after scaling
 *
 * Revision 1.9  2006/05/03 15:12:35  strk
 * Oops, uninitialized value fix
 *
 * Revision 1.8  2006/05/03 15:00:43  strk
 * Fixed scale() function to remove repeated points *after* rounding. Added brief doxygen class description.
 *
 * Revision 1.7  2006/05/03 09:14:22  strk
 * * source/operation/buffer/OffsetCurveSetBuilder.cpp: used auto_ptr to protect leaks of CoordinateSequence
 * * source/noding/ScaledNoder.cpp, source/headers/geos/noding/ScaledNoder.h: ported JTS bugfix in scale method.
 *
 * Revision 1.6  2006/05/02 16:22:18  strk
 * * source/noding/ScaledNoder.cpp: use java_math_round instead of sym_round.
 *
 * Revision 1.5  2006/03/15 09:51:12  strk
 * streamlined headers usage
 *
 * Revision 1.4  2006/03/13 21:19:51  strk
 * Fixed bug in ScaledNoder scaling mechanism (hugly code, due to CoordinateSequence visitor pattern design). Tests are still failing so this possibly needs some other fix. Streamlined includes by implementation file.
 *
 * Revision 1.3  2006/02/23 11:54:20  strk
 * - MCIndexPointSnapper
 * - MCIndexSnapRounder
 * - SnapRounding BufferOp
 * - ScaledNoder
 * - GEOSException hierarchy cleanups
 * - SpatialIndex memory-friendly query interface
 * - GeometryGraph::getBoundaryNodes memory-friendly
 * - NodeMap::getBoundaryNodes memory-friendly
 * - Cleanups in geomgraph::Edge
 * - Added an XML test for snaprounding buffer (shows leaks, working on it)
 *
 * Revision 1.2  2006/02/19 19:46:49  strk
 * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
 *
 * Revision 1.1  2006/02/18 21:08:09  strk
 * - new CoordinateSequence::applyCoordinateFilter method (slow but useful)
 * - SegmentString::getCoordinates() doesn't return a clone anymore.
 * - SegmentString::getCoordinatesRO() obsoleted.
 * - SegmentString constructor does not promises constness of passed
 *   CoordinateSequence anymore.
 * - NEW ScaledNoder class
 * - Stubs for MCIndexPointSnapper and  MCIndexSnapRounder
 * - Simplified internal interaces of OffsetCurveBuilder and OffsetCurveSetBuilder
 *
 **********************************************************************/
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenscrollbardata.h"
#include "../oxygengtkutils.h"

#include <gtk/gtk.h>

namespace Oxygen
{

    //________________________________________________________________________________
    void ScrollBarData::connect( GtkWidget* widget )
    {
        _target = widget;
        _updatesDelayed = true;
        _valueChangedId.connect( G_OBJECT(widget), "value-changed", G_CALLBACK( valueChanged ), this );
    }

    //________________________________________________________________________________
    void ScrollBarData::disconnect( GtkWidget* widget )
    {
        _target = 0L;

        // reset timeout and locked flag
        _timer.stop();
        _locked = false;

        _valueChangedId.disconnect();
    }

    //________________________________________________________________________________
    void ScrollBarData::valueChanged( GtkRange* widget, gpointer pointer )
    {

        ScrollBarData& data( *static_cast<ScrollBarData*>( pointer ) );
        if( data._updatesDelayed )
        {

            // schedule delayed timeOut
            if( !data._timer.isRunning() )
            {

                data._timer.start( data._delay, (GSourceFunc)delayedUpdate, &data );
                data._locked = false;

            } else data._locked = true;

        } else if( GtkWidget* parent = Gtk::gtk_parent_scrolled_window( GTK_WIDGET( widget ) ) ) {

            gtk_widget_queue_draw( parent );

        }

        return;
    }

    //________________________________________________________________________________
    gboolean ScrollBarData::delayedUpdate( gpointer pointer )
    {

        ScrollBarData& data( *static_cast<ScrollBarData*>(pointer) );

        if( !data._target )
        {

            // if target is invalid, reset timeout and return
            data._locked = false;
            return FALSE;

        } else if( data._locked ) {

            // if locked, reset the flag and re-run timer
            data._locked = false;
            return TRUE;

        } else if( GtkWidget* parent = Gtk::gtk_parent_scrolled_window( GTK_WIDGET( data._target ) ) ) {

            // otherwise, trigger update
            gtk_widget_queue_draw( parent );
            return FALSE;

        }

        // if everything fails, unlock and do nothing
        data._locked = false;
        return FALSE;

    }

}
<commit_msg>disable delayed updates by default.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenscrollbardata.h"
#include "../oxygengtkutils.h"

#include <gtk/gtk.h>

namespace Oxygen
{

    //________________________________________________________________________________
    void ScrollBarData::connect( GtkWidget* widget )
    {
        _target = widget;
        _locked = false;
        _valueChangedId.connect( G_OBJECT(widget), "value-changed", G_CALLBACK( valueChanged ), this );
    }

    //________________________________________________________________________________
    void ScrollBarData::disconnect( GtkWidget* widget )
    {
        _target = 0L;

        // reset timeout and locked flag
        _timer.stop();
        _locked = false;

        _valueChangedId.disconnect();
    }

    //________________________________________________________________________________
    void ScrollBarData::valueChanged( GtkRange* widget, gpointer pointer )
    {

        ScrollBarData& data( *static_cast<ScrollBarData*>( pointer ) );
        if( data._updatesDelayed )
        {

            // schedule delayed timeOut
            if( !data._timer.isRunning() )
            {

                data._timer.start( data._delay, (GSourceFunc)delayedUpdate, &data );
                data._locked = false;

            } else data._locked = true;

        } else if( GtkWidget* parent = Gtk::gtk_parent_scrolled_window( GTK_WIDGET( widget ) ) ) {

            gtk_widget_queue_draw( parent );

        }

        return;
    }

    //________________________________________________________________________________
    gboolean ScrollBarData::delayedUpdate( gpointer pointer )
    {

        ScrollBarData& data( *static_cast<ScrollBarData*>(pointer) );

        if( !data._target )
        {

            // if target is invalid, reset timeout and return
            data._locked = false;
            return FALSE;

        } else if( data._locked ) {

            // if locked, reset the flag and re-run timer
            data._locked = false;
            return TRUE;

        } else if( GtkWidget* parent = Gtk::gtk_parent_scrolled_window( GTK_WIDGET( data._target ) ) ) {

            // otherwise, trigger update
            gtk_widget_queue_draw( parent );
            return FALSE;

        }

        // if everything fails, unlock and do nothing
        data._locked = false;
        return FALSE;

    }

}
<|endoftext|>


<commit_before>//
//  MCIMAPQuotaOperation.cc
//  mailcore2
//
//  Created by Petro Korenev on 8/2/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCIMAPQuotaOperation.h"

#include "MCIMAPSession.h"
#include "MCIMAPAsyncConnection.h"

using namespace mailcore;

IMAPQuotaOperation::IMAPQuotaOperation()
{
    mLimit = 0;
    mUsage = 0;
}

IMAPQuotaOperation::~IMAPQuotaOperation()
{
}

uint32_t IMAPQuotaOperation::limit()
{
    return mLimit;
}

uint32_t IMAPQuotaOperation::usage()
{
    return mUsage;
}

void IMAPQuotaOperation::main()
{
    ErrorCode error;
    session()->session()->getQuota(&mUsage, &mLimit, &error);
    setError(error);
}
<commit_msg>Fixed IMAPQuotaOperation<commit_after>//
//  MCIMAPQuotaOperation.cc
//  mailcore2
//
//  Created by Petro Korenev on 8/2/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCIMAPQuotaOperation.h"

#include "MCIMAPSession.h"
#include "MCIMAPAsyncConnection.h"

using namespace mailcore;

IMAPQuotaOperation::IMAPQuotaOperation()
{
    mLimit = 0;
    mUsage = 0;
}

IMAPQuotaOperation::~IMAPQuotaOperation()
{
}

uint32_t IMAPQuotaOperation::limit()
{
    return mLimit;
}

uint32_t IMAPQuotaOperation::usage()
{
    return mUsage;
}

void IMAPQuotaOperation::main()
{
    ErrorCode error;
    session()->session()->loginIfNeeded(&error);
    if (error != ErrorNone) {
        setError(error);
        return;
    }

    session()->session()->getQuota(&mUsage, &mLimit, &error);
    setError(error);
}
<|endoftext|>


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

#ifndef _BGFX_TUPLE_B2I64TUPLE_HXX
#include <basegfx/tuple/b2i64tuple.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

namespace { struct EmptyTuple : public rtl::Static<basegfx::B2I64Tuple, EmptyTuple> {}; }

namespace basegfx
{
    const B2I64Tuple& B2I64Tuple::getEmptyTuple()
    {
        return EmptyTuple::get();
    }

} // end of namespace basegfx

// eof
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.44); FILE MERGED 2005/09/05 17:38:45 rt 1.2.44.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b2i64tuple.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:52:30 $
 *
 *  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 _BGFX_TUPLE_B2I64TUPLE_HXX
#include <basegfx/tuple/b2i64tuple.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

namespace { struct EmptyTuple : public rtl::Static<basegfx::B2I64Tuple, EmptyTuple> {}; }

namespace basegfx
{
    const B2I64Tuple& B2I64Tuple::getEmptyTuple()
    {
        return EmptyTuple::get();
    }

} // end of namespace basegfx

// eof
<|endoftext|>