<commit_before>/*
 * Copyright 2019 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "modules/skottie/src/effects/Effects.h"

#include "include/effects/SkGradientShader.h"
#include "include/effects/SkShaderMaskFilter.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGRenderEffect.h"
#include "src/utils/SkJSON.h"

#include <cmath>

namespace skottie {
namespace internal {

namespace  {

class VenetianBlindsAdapter final : public MaskShaderEffectBase {
public:
    static sk_sp<VenetianBlindsAdapter> Make(const skjson::ArrayValue& jprops,
                                             sk_sp<sksg::RenderNode> layer,
                                             const SkSize& layer_size,
                                             const AnimationBuilder* abuilder) {
        return sk_sp<VenetianBlindsAdapter>(
                    new VenetianBlindsAdapter(jprops, std::move(layer), layer_size, abuilder));
    }

private:
    VenetianBlindsAdapter(const skjson::ArrayValue& jprops,
                          sk_sp<sksg::RenderNode> layer, const SkSize& ls,
                          const AnimationBuilder* abuilder)
        : INHERITED(std::move(layer), ls) {
        enum : size_t {
            kCompletion_Index = 0,
             kDirection_Index = 1,
                 kWidth_Index = 2,
               kFeather_Index = 3,
        };

        EffectBinder(jprops, *abuilder, this)
                .bind(kCompletion_Index, fCompletion)
                .bind( kDirection_Index, fDirection )
                .bind(     kWidth_Index, fWidth     )
                .bind(   kFeather_Index, fFeather   );
    }

    MaskInfo onMakeMask() const override {
        if (fCompletion >= 100) {
            // The layer is fully disabled.
            return { nullptr, false };
        }

        if (fCompletion <= 0) {
            // The layer is fully visible (no mask).
            return { nullptr, true };
        }

        static constexpr float kFeatherSigmaFactor = 3.0f,
                                       kMinFeather = 0.5f; // for soft gradient edges

        const auto t = fCompletion * 0.01f,
                size = std::max(1.0f, fWidth),
               angle = SkDegreesToRadians(-fDirection),
             feather = std::max(fFeather * kFeatherSigmaFactor, kMinFeather),
                  df = feather / size, // feather distance in normalized stop space
                 df0 = 0.5f * std::min(df,     t),
                 df1 = 0.5f * std::min(df, 1 - t);

        // In its simplest form, the Venetian Blinds effect is a single-step gradient
        // repeating along the direction vector.
        //
        // To avoid an expensive blur pass, we emulate the feather property by softening
        // the gradient edges:
        //
        //  1.0 [                                 |       -------       ]
        //      [                                 |      /       \      ]
        //      [                                 |     /         \     ]
        //      [                                 |    /           \    ]
        //      [                                 |   /             \   ]
        //      [                                 |  /               \  ]
        //      [                                 | /                 \ ]
        //      [                                 |/                   \]
        //  0.5 [                                 |                     ]
        //      [\                               /|                     ]
        //      [ \                             / |                     ]
        //      [  \                           /  |                     ]
        //      [   \                         /   |                     ]
        //      [    \                       /    |                     ]
        //      [     \                     /     |                     ]
        //      [      \                   /      |                     ]
        //  0.0 [       -------------------       |                     ]
        //
        //      ^       ^                 ^       ^       ^     ^       ^
        //      0      fp0               fp1      T      fp2   fp3      1
        //
        //      |       |                 |       |       |     |       |
        //      |< df0 >|                 |< df0 >|< df1 >|     |< df1 >|
        //
        //  ... df     >|                 |<      df     >|     |<      df ...
        //
        // Note 1: fp0-fp1 and/or fp2-fp3 can collapse when df is large enough.
        //
        // Note 2: G(fp0) == G(fp1) and G(fp2) == G(fp3), whether collapsed or not.
        //
        // Note 3: to minimize the number of gradient stops, we can shift the gradient by -df0
        //         (such that fp0 aligns with 0/pts[0]).

        // Gradient value at fp0/fp1, fp2/fp3.
        // Note: g01 > 0 iff fp0-fp1 is collapsed and g23 < 1 iff fp2-fp3 is collapsed
        const auto g01 = std::max(0.0f, 0.5f * (1 + (0 - t) / df)),
                   g23 = std::min(1.0f, 0.5f * (1 + (1 - t) / df));

        const SkColor c01 = SkColorSetA(SK_ColorWHITE, SkScalarRoundToInt(g01 * 0xff)),
                      c23 = SkColorSetA(SK_ColorWHITE, SkScalarRoundToInt(g23 * 0xff)),
                 colors[] = { c01, c23, c23, c01 };

        const SkScalar pos[] = {
         // 0,              // fp0
            t - df0 - df0,  // fp1
            t + df1 - df0,  // fp2
            1 - df1 - df0,  // fp3
            1,
        };
        static_assert(SK_ARRAY_COUNT(colors) == SK_ARRAY_COUNT(pos), "");

        const auto center = SkPoint::Make(0.5f * this->layerSize().width(),
                                          0.5f * this->layerSize().height()),
                 grad_vec = SkVector::Make( size * std::cos(angle),
                                           -size * std::sin(angle));

        const SkPoint pts[] = {
            center + grad_vec * (df0 + 0),
            center + grad_vec * (df0 + 1),
        };

        return {
            SkGradientShader::MakeLinear(pts, colors, pos, SK_ARRAY_COUNT(colors),
                                         SkTileMode::kRepeat),
            true
        };
    }

    ScalarValue fCompletion = 0,
                fDirection  = 0,
                fWidth      = 0,
                fFeather    = 0;

    using INHERITED = MaskShaderEffectBase;
};

} // namespace

sk_sp<sksg::RenderNode> EffectBuilder::attachVenetianBlindsEffect(
        const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const {
    return fBuilder->attachDiscardableAdapter<VenetianBlindsAdapter>(jprops,
                                                                     std::move(layer),
                                                                     fLayerSize,
                                                                     fBuilder);
}

} // namespace internal
} // namespace skottie
<commit_msg>Roll external/skia 607a489345ad..24ea293cd25b (1 commits)<commit_after>/*
 * Copyright 2019 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "modules/skottie/src/effects/Effects.h"

#include "include/effects/SkGradientShader.h"
#include "include/effects/SkShaderMaskFilter.h"
#include "modules/skottie/src/SkottieValue.h"
#include "modules/sksg/include/SkSGRenderEffect.h"
#include "src/utils/SkJSON.h"

#include <cmath>

namespace skottie {
namespace internal {

namespace  {

class VenetianBlindsAdapter final : public MaskShaderEffectBase {
public:
    static sk_sp<VenetianBlindsAdapter> Make(const skjson::ArrayValue& jprops,
                                             sk_sp<sksg::RenderNode> layer,
                                             const SkSize& layer_size,
                                             const AnimationBuilder* abuilder) {
        return sk_sp<VenetianBlindsAdapter>(
                    new VenetianBlindsAdapter(jprops, std::move(layer), layer_size, abuilder));
    }

private:
    VenetianBlindsAdapter(const skjson::ArrayValue& jprops,
                          sk_sp<sksg::RenderNode> layer, const SkSize& ls,
                          const AnimationBuilder* abuilder)
        : INHERITED(std::move(layer), ls) {
        enum : size_t {
            kCompletion_Index = 0,
             kDirection_Index = 1,
                 kWidth_Index = 2,
               kFeather_Index = 3,
        };

        EffectBinder(jprops, *abuilder, this)
                .bind(kCompletion_Index, fCompletion)
                .bind( kDirection_Index, fDirection )
                .bind(     kWidth_Index, fWidth     )
                .bind(   kFeather_Index, fFeather   );
    }

    MaskInfo onMakeMask() const override {
        if (fCompletion >= 100) {
            // The layer is fully disabled.
            return { nullptr, false };
        }

        if (fCompletion <= 0) {
            // The layer is fully visible (no mask).
            return { nullptr, true };
        }

        static constexpr float kFeatherSigmaFactor = 3.0f,
                                       kMinFeather = 0.5f; // for soft gradient edges

        const auto t = fCompletion * 0.01f,
                size = std::max(1.0f, fWidth),
               angle = SkDegreesToRadians(-fDirection),
             feather = std::max(fFeather * kFeatherSigmaFactor, kMinFeather),
                  df = feather / size, // feather distance in normalized stop space
                 df0 = 0.5f * std::min(df,     t),
                 df1 = 0.5f * std::min(df, 1 - t);

        // In its simplest form, the Venetian Blinds effect is a single-step gradient
        // repeating along the direction vector.
        //
        // To avoid an expensive blur pass, we emulate the feather property by softening
        // the gradient edges:
        //
        //  1.0 [                                 |       -------       ]
        //      [                                 |      /       \      ]
        //      [                                 |     /         \     ]
        //      [                                 |    /           \    ]
        //      [                                 |   /             \   ]
        //      [                                 |  /               \  ]
        //      [                                 | /                 \ ]
        //      [                                 |/                   \]
        //  0.5 [                                 |                     ]
        //      [\                               /|                     ]
        //      [ \                             / |                     ]
        //      [  \                           /  |                     ]
        //      [   \                         /   |                     ]
        //      [    \                       /    |                     ]
        //      [     \                     /     |                     ]
        //      [      \                   /      |                     ]
        //  0.0 [       -------------------       |                     ]
        //
        //      ^       ^                 ^       ^       ^     ^       ^
        //      0      fp0               fp1      T      fp2   fp3      1
        //
        //      |       |                 |       |       |     |       |
        //      |< df0 >|                 |< df0 >|< df1 >|     |< df1 >|
        //
        //  ... df     >|                 |<      df     >|     |<      df ...
        //
        // Note 1: fp0-fp1 and/or fp2-fp3 can collapse when df is large enough.
        //
        // Note 2: G(fp0) == G(fp1) and G(fp2) == G(fp3), whether collapsed or not.
        //
        // Note 3: to minimize the number of gradient stops, we can shift the gradient by -df0
        //         (such that fp0 aligns with 0/pts[0]).

        // Gradient value at fp0/fp1, fp2/fp3.
        // Note: g01 > 0 iff fp0-fp1 is collapsed and g23 < 1 iff fp2-fp3 is collapsed
        const auto g01 = std::max(0.0f, 0.5f * (1 + sk_ieee_float_divide(0 - t, df))),
                   g23 = std::min(1.0f, 0.5f * (1 + sk_ieee_float_divide(1 - t, df)));
        SkASSERT(0 <= g01 && g01 <= g23 && g23 <= 1);

        const SkColor c01 = SkColorSetA(SK_ColorWHITE, SkScalarRoundToInt(g01 * 0xff)),
                      c23 = SkColorSetA(SK_ColorWHITE, SkScalarRoundToInt(g23 * 0xff)),
                 colors[] = { c01, c23, c23, c01 };

        const SkScalar pos[] = {
         // 0,              // fp0
            t - df0 - df0,  // fp1
            t + df1 - df0,  // fp2
            1 - df1 - df0,  // fp3
            1,
        };
        static_assert(SK_ARRAY_COUNT(colors) == SK_ARRAY_COUNT(pos), "");

        const auto center = SkPoint::Make(0.5f * this->layerSize().width(),
                                          0.5f * this->layerSize().height()),
                 grad_vec = SkVector::Make( size * std::cos(angle),
                                           -size * std::sin(angle));

        const SkPoint pts[] = {
            center + grad_vec * (df0 + 0),
            center + grad_vec * (df0 + 1),
        };

        return {
            SkGradientShader::MakeLinear(pts, colors, pos, SK_ARRAY_COUNT(colors),
                                         SkTileMode::kRepeat),
            true
        };
    }

    ScalarValue fCompletion = 0,
                fDirection  = 0,
                fWidth      = 0,
                fFeather    = 0;

    using INHERITED = MaskShaderEffectBase;
};

} // namespace

sk_sp<sksg::RenderNode> EffectBuilder::attachVenetianBlindsEffect(
        const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const {
    return fBuilder->attachDiscardableAdapter<VenetianBlindsAdapter>(jprops,
                                                                     std::move(layer),
                                                                     fLayerSize,
                                                                     fBuilder);
}

} // namespace internal
} // namespace skottie
<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "coding/bit_streams.hpp"
#include "coding/reader.hpp"
#include "coding/writer.hpp"

#include "std/random.hpp"
#include "std/utility.hpp"
#include "std/vector.hpp"

UNIT_TEST(BitStreams_Smoke)
{
  uniform_int_distribution<uint8_t> randomBytesDistribution(0, 255);
  mt19937 rng(0);
  vector<pair<uint8_t, uint32_t>> nums;
  for (size_t i = 0; i < 100; ++i)
  {
    uint32_t numBits = randomBytesDistribution(rng) % 8;
    uint8_t num = randomBytesDistribution(rng) >> (CHAR_BIT - numBits);
    nums.push_back(make_pair(num, numBits));
  }
  for (size_t i = 0; i < 100; ++i)
  {
    uint32_t numBits = 8;
    uint8_t num = randomBytesDistribution(rng);
    nums.push_back(make_pair(num, numBits));
  }

  vector<uint8_t> encodedBits;
  MemWriter<vector<uint8_t>> encodedBitsWriter(encodedBits);
  BitWriter<MemWriter<vector<uint8_t>>> bitSink(encodedBitsWriter);
  for (size_t i = 0; i < nums.size(); ++i)
    bitSink.Write(nums[i].first, nums[i].second);

  MemReader encodedBitsReader(encodedBits.data(), encodedBits.size());
  ReaderSource<MemReader> reader(encodedBitsReader);
  BitReader<ReaderSource<MemReader>> bitsSource(reader);
  for (size_t i = 0; i < nums.size(); ++i)
  {
    uint8_t num = bitsSource.Read(nums[i].second);
    TEST_EQUAL(num, nums[i].first, (i));
  }
}
<commit_msg>Fix build.<commit_after>#include "testing/testing.hpp"

#include "coding/bit_streams.hpp"
#include "coding/reader.hpp"
#include "coding/writer.hpp"

#include "std/random.hpp"
#include "std/utility.hpp"
#include "std/vector.hpp"

UNIT_TEST(BitStreams_Smoke)
{
  uniform_int_distribution<uint8_t> randomBytesDistribution(0, 255);
  mt19937 rng(0);
  vector<pair<uint8_t, uint32_t>> nums;
  for (size_t i = 0; i < 100; ++i)
  {
    uint32_t numBits = randomBytesDistribution(rng) % 8;
    uint8_t num = randomBytesDistribution(rng) >> (CHAR_BIT - numBits);
    nums.push_back(make_pair(num, numBits));
  }
  for (size_t i = 0; i < 100; ++i)
  {
    uint32_t numBits = 8;
    uint8_t num = randomBytesDistribution(rng);
    nums.push_back(make_pair(num, numBits));
  }

  vector<uint8_t> encodedBits;
  {
    MemWriter<vector<uint8_t>> encodedBitsWriter(encodedBits);
    BitWriter<MemWriter<vector<uint8_t>>> bitSink(encodedBitsWriter);
    for (size_t i = 0; i < nums.size(); ++i)
      bitSink.Write(nums[i].first, nums[i].second);
  }

  MemReader encodedBitsReader(encodedBits.data(), encodedBits.size());
  ReaderSource<MemReader> reader(encodedBitsReader);
  BitReader<ReaderSource<MemReader>> bitsSource(reader);
  for (size_t i = 0; i < nums.size(); ++i)
  {
    uint8_t num = bitsSource.Read(nums[i].second);
    TEST_EQUAL(num, nums[i].first, (i));
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#pragma once

#include <unordered_set>
#include <memory>
#include <seastar/core/shared_ptr.hh>
#include "sstables/shared_sstable.hh"
#include "sstables/progress_monitor.hh"
#include "timestamp.hh"

class compaction_backlog_manager;
class compaction_controller;

// Read and write progress are provided by structures present in progress_manager.hh
// However, we don't want to be tied to their lifetimes and for that reason we will not
// manipulate them directly in the backlog manager.
//
// The structure that register those progress structures - the monitors - will let us know when does
// the sstable-side tracking structures go out of scope. And in that case we can do something about
// it.
//
// These objects lifetime are tied to the SSTable shared object lifetime and are expected to be kept
// alive until the SSTable is no longer being written/compacted. In other words, they are expected
// to be kept alive until one of compaction_backlog_tracker's add_sstable, remove_sstable or
// revert_charges are called.
//
// The reason for us to bundle this into the add_sstable/remove_sstable lifetime, instead of dealing
// with them separately and removing when the data transfer is done is that if we unregister a
// progrees manager and only later on add/remove the corresponding SSTable we can see large valley
// or peaks in the backlog.
//
// Those valleys/peaks originate from the fact that we may be removing/adding a fair chunk of
// backlog that will only be corrected much later, when we call add_sstable / remove_sstable.
// Because of that, we want to keep the backlog originating from the progress manager around for as
// long as possible, up to the moment the sstable list is fixed. The compaction object hosting this
// will certainly be gone by then.
struct backlog_write_progress_manager {
    virtual uint64_t written() const = 0;
    virtual api::timestamp_type maximum_timestamp() const = 0;
    virtual unsigned level() const = 0;
    virtual ~backlog_write_progress_manager() {}
};

struct backlog_read_progress_manager {
    virtual uint64_t compacted() const = 0;
    virtual ~backlog_read_progress_manager() {}
};

// Manages one individual source of compaction backlog, usually a column family.
class compaction_backlog_tracker {
public:
    using ongoing_writes = std::unordered_map<sstables::shared_sstable, backlog_write_progress_manager*>;
    using ongoing_compactions = std::unordered_map<sstables::shared_sstable, backlog_read_progress_manager*>;

    struct impl {
        virtual void add_sstable(sstables::shared_sstable sst) = 0;
        virtual void remove_sstable(sstables::shared_sstable sst) = 0;
        virtual double backlog(const ongoing_writes& ow, const ongoing_compactions& oc) const = 0;
        virtual ~impl() { }
    };

    compaction_backlog_tracker(std::unique_ptr<impl> impl) : _impl(std::move(impl)) {}
    compaction_backlog_tracker(compaction_backlog_tracker&&) = default;
    compaction_backlog_tracker(const compaction_backlog_tracker&) = delete;
    ~compaction_backlog_tracker();

    double backlog() const;
    void add_sstable(sstables::shared_sstable sst);
    void remove_sstable(sstables::shared_sstable sst);
    void register_partially_written_sstable(sstables::shared_sstable sst, backlog_write_progress_manager& wp);
    void register_compacting_sstable(sstables::shared_sstable sst, backlog_read_progress_manager& rp);
    void transfer_ongoing_charges(compaction_backlog_tracker& new_bt, bool move_read_charges = true);
    void revert_charges(sstables::shared_sstable sst);
private:
    // Returns true if this SSTable can be added or removed from the tracker.
    bool sstable_belongs_to_tracker(const sstables::shared_sstable& sst);

    void disable() {
        _impl = {};
        _ongoing_writes = {};
        _ongoing_compactions = {};
    }
    bool disabled() const noexcept { return !_impl; }
    std::unique_ptr<impl> _impl;
    // We keep track of this so that we can transfer to a new tracker if the compaction strategy is
    // changed in the middle of a compaction.
    ongoing_writes _ongoing_writes;
    ongoing_compactions _ongoing_compactions;
    compaction_backlog_manager* _manager = nullptr;
    friend class compaction_backlog_manager;
};

// System-wide manager for compaction backlog.
//
// The number of backlogs is the same as the number of column families, which can be very high.
// As an optimization we could keep column families that are not undergoing any change in a special
// list and only iterate over the ones that are changing.
//
// However, the calculation of the backlog is not that expensive: I have benchmarked the cost of
// computing the backlog of 3500 column families to less than 200 microseconds, and that is only
// requested periodically, for relatively large periods of hundreds of milliseconds.
//
// Keeping a static part for the backlog complicates the code significantly, though, so this will
// be left for a future optimization.
class compaction_backlog_manager {
    std::unordered_set<compaction_backlog_tracker*> _backlog_trackers;
    void remove_backlog_tracker(compaction_backlog_tracker* tracker);
    compaction_controller* _compaction_controller;
    friend class compaction_backlog_tracker;
public:
    ~compaction_backlog_manager();
    compaction_backlog_manager(compaction_controller& controller) : _compaction_controller(&controller) {}
    double backlog() const;
    void register_backlog_tracker(compaction_backlog_tracker& tracker);
};
<commit_msg>compaction_backlog_tracker: make disable() public<commit_after>/*
 * Copyright (C) 2017-present ScyllaDB
 */

/*
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#pragma once

#include <unordered_set>
#include <memory>
#include <seastar/core/shared_ptr.hh>
#include "sstables/shared_sstable.hh"
#include "sstables/progress_monitor.hh"
#include "timestamp.hh"

class compaction_backlog_manager;
class compaction_controller;

// Read and write progress are provided by structures present in progress_manager.hh
// However, we don't want to be tied to their lifetimes and for that reason we will not
// manipulate them directly in the backlog manager.
//
// The structure that register those progress structures - the monitors - will let us know when does
// the sstable-side tracking structures go out of scope. And in that case we can do something about
// it.
//
// These objects lifetime are tied to the SSTable shared object lifetime and are expected to be kept
// alive until the SSTable is no longer being written/compacted. In other words, they are expected
// to be kept alive until one of compaction_backlog_tracker's add_sstable, remove_sstable or
// revert_charges are called.
//
// The reason for us to bundle this into the add_sstable/remove_sstable lifetime, instead of dealing
// with them separately and removing when the data transfer is done is that if we unregister a
// progrees manager and only later on add/remove the corresponding SSTable we can see large valley
// or peaks in the backlog.
//
// Those valleys/peaks originate from the fact that we may be removing/adding a fair chunk of
// backlog that will only be corrected much later, when we call add_sstable / remove_sstable.
// Because of that, we want to keep the backlog originating from the progress manager around for as
// long as possible, up to the moment the sstable list is fixed. The compaction object hosting this
// will certainly be gone by then.
struct backlog_write_progress_manager {
    virtual uint64_t written() const = 0;
    virtual api::timestamp_type maximum_timestamp() const = 0;
    virtual unsigned level() const = 0;
    virtual ~backlog_write_progress_manager() {}
};

struct backlog_read_progress_manager {
    virtual uint64_t compacted() const = 0;
    virtual ~backlog_read_progress_manager() {}
};

// Manages one individual source of compaction backlog, usually a column family.
class compaction_backlog_tracker {
public:
    using ongoing_writes = std::unordered_map<sstables::shared_sstable, backlog_write_progress_manager*>;
    using ongoing_compactions = std::unordered_map<sstables::shared_sstable, backlog_read_progress_manager*>;

    struct impl {
        virtual void add_sstable(sstables::shared_sstable sst) = 0;
        virtual void remove_sstable(sstables::shared_sstable sst) = 0;
        virtual double backlog(const ongoing_writes& ow, const ongoing_compactions& oc) const = 0;
        virtual ~impl() { }
    };

    compaction_backlog_tracker(std::unique_ptr<impl> impl) : _impl(std::move(impl)) {}
    compaction_backlog_tracker(compaction_backlog_tracker&&) = default;
    compaction_backlog_tracker(const compaction_backlog_tracker&) = delete;
    ~compaction_backlog_tracker();

    double backlog() const;
    void add_sstable(sstables::shared_sstable sst);
    void remove_sstable(sstables::shared_sstable sst);
    void register_partially_written_sstable(sstables::shared_sstable sst, backlog_write_progress_manager& wp);
    void register_compacting_sstable(sstables::shared_sstable sst, backlog_read_progress_manager& rp);
    void transfer_ongoing_charges(compaction_backlog_tracker& new_bt, bool move_read_charges = true);
    void revert_charges(sstables::shared_sstable sst);

    void disable() {
        _impl = {};
        _ongoing_writes = {};
        _ongoing_compactions = {};
    }
private:
    // Returns true if this SSTable can be added or removed from the tracker.
    bool sstable_belongs_to_tracker(const sstables::shared_sstable& sst);
    bool disabled() const noexcept { return !_impl; }
    std::unique_ptr<impl> _impl;
    // We keep track of this so that we can transfer to a new tracker if the compaction strategy is
    // changed in the middle of a compaction.
    ongoing_writes _ongoing_writes;
    ongoing_compactions _ongoing_compactions;
    compaction_backlog_manager* _manager = nullptr;
    friend class compaction_backlog_manager;
};

// System-wide manager for compaction backlog.
//
// The number of backlogs is the same as the number of column families, which can be very high.
// As an optimization we could keep column families that are not undergoing any change in a special
// list and only iterate over the ones that are changing.
//
// However, the calculation of the backlog is not that expensive: I have benchmarked the cost of
// computing the backlog of 3500 column families to less than 200 microseconds, and that is only
// requested periodically, for relatively large periods of hundreds of milliseconds.
//
// Keeping a static part for the backlog complicates the code significantly, though, so this will
// be left for a future optimization.
class compaction_backlog_manager {
    std::unordered_set<compaction_backlog_tracker*> _backlog_trackers;
    void remove_backlog_tracker(compaction_backlog_tracker* tracker);
    compaction_controller* _compaction_controller;
    friend class compaction_backlog_tracker;
public:
    ~compaction_backlog_manager();
    compaction_backlog_manager(compaction_controller& controller) : _compaction_controller(&controller) {}
    double backlog() const;
    void register_backlog_tracker(compaction_backlog_tracker& tracker);
};
<|endoftext|>


<commit_before>#include "webcam.hpp"

using namespace cv;
using namespace std;

Mat ellipticKernel(int width, int height = -1) {
 if (height==-1) {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
 } else {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
 }
}

void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
 int width, height;
 width = inout.size().width;
 height = inout.size().height;
 Mat downsample;
 resize(inout, downsample, Size(smallsize,smallsize));
 Mat kernel = ellipticKernel(factor);
 if (diler) {
  erode(downsample, downsample, kernel);
 } else {
  dilate(downsample, downsample, kernel);
 }
 if (eq) {
  equalizeHist(downsample, downsample);
 }
 resize(downsample, inout, Size(width, height));
}

int main (int argc, char** argv) {

 int tracker1, tracker2, tracker3;
 namedWindow("s",1);
 createTrackbar("1","s",&tracker1,100);
 createTrackbar("2","s",&tracker2,100);
 createTrackbar("3","s",&tracker3,100);

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
//  imshow("webcam", image);

// let's make multiple masks where 0=not mouth, 1=uncertain

// then multiply them together and multiply that with image
// and run haar classifier on image

  Mat gray, blurred_img;
  cvtColor(image, gray, CV_RGB2GRAY);
  blur(image, blurred_img, Size(50,50));

// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 200, 1, THRESH_BINARY);
  blur(canny*255, canny, Size(width/10, height/10));
  threshold(canny, canny, 220, 1, THRESH_BINARY);
  imshow("canny mask", gray.mul(canny));
*/

// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
  Mat flow;
  absdiff(blurred_img, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  morphFast(flow);
  threshold(flow, flow, 60, 1, THRESH_BINARY);
//  imshow("flow mask", gray.mul(flow));

// this mask gets anything kind of dark (DK2) and dilates
  Mat kindofdark;
  equalizeHist(gray, kindofdark);
  threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
  morphFast(kindofdark, 100, 17, 0);
//  imshow("dark mask", gray.mul(kindofdark));

// this mask gets rid of anything far away from red stuff
// lips have a lot of red
  Mat notlips, channels;
  split(image, channels);
  notlips = channels[2] - (channels[0]+channels[1])/2;//BGR?
  imshow("0", channels[0]);
  imshow("1", channels[1]);
  imshow("2", channels[2]);
  imshow("0+1", (channels[0]+channels[1])/2);
  imshow("2-0", channels[2] - channels[0]);
  imshow("2-1", channels[2] - channels[1]);
  //equalistHist is horrible for a red background
  //equalizeHist(notlips, notlips);
  threshold(notlips, notlips, tracker1*3, 1, THRESH_BINARY);
  imshow("lip mask", notlips*255);
  waitKey(1);

  Mat mask = flow.mul(kindofdark);
// open the mask
  Mat smallMask0, smallMask1;
  resize(mask, smallMask0, Size(width/5,height/5));
  Mat erodeKernel = ellipticKernel(69,79);
  erode(smallMask0, smallMask1, erodeKernel);
  Mat dilateKernel = ellipticKernel(69,79);
  dilate(smallMask1, smallMask1, dilateKernel);
  bitwise_and(smallMask0, smallMask1, smallMask1);
  resize(smallMask1, mask, Size(width, height));
//  imshow("morph mask", gray.mul(mask));

// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg

//  Mat erodeKernel = ellipticKernel(21);
  Mat erodedMask;
  erode(mask, erodedMask, erodeKernel);
  Mat mask_;
  subtract(1,erodedMask,mask_);
  Mat mask3, mask3_;
  channel[0] = erodedMask;
  channel[1] = erodedMask;
  channel[2] = erodedMask;
  merge(channel, 3, mask3);
  channel[0] = mask_;
  channel[1] = mask_;
  channel[2] = mask_;
  merge(channel, 3, mask3_);

  background = background.mul(mask3) +
   (background.mul(mask3_) + blurred_img.mul(mask3_))/2;

  imshow("background", background);

/*
  Moments lol = moments(gray, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
*/
/*
  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  int scale = tracker1+1;
  Mat classifyThis = image.clone();
  equalizeHist(gray, gray);//ew; watch out not to use this later
  resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
//  bilateralFilter(gray, classifyThis, 15, 10, 1);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, tracker2, CV_HAAR_SCALE_IMAGE);
  for (size_t i=0; i<mouths.size(); i++) {
   Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
   rectangle(image, scaled, Scalar(255,0,0));
  }
  imshow("MOUTH", image);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"

using namespace cv;
using namespace std;

Mat ellipticKernel(int width, int height = -1) {
 if (height==-1) {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
 } else {
  return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
 }
}

void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
 int width, height;
 width = inout.size().width;
 height = inout.size().height;
 Mat downsample;
 resize(inout, downsample, Size(smallsize,smallsize));
 Mat kernel = ellipticKernel(factor);
 if (diler) {
  erode(downsample, downsample, kernel);
 } else {
  dilate(downsample, downsample, kernel);
 }
 if (eq) {
  equalizeHist(downsample, downsample);
 }
 resize(downsample, inout, Size(width, height));
}

int main (int argc, char** argv) {

 int tracker1, tracker2, tracker3;
 namedWindow("s",1);
 createTrackbar("1","s",&tracker1,100);
 createTrackbar("2","s",&tracker2,100);
 createTrackbar("3","s",&tracker3,100);

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 for (int i = 0; i < 30; i++) {
  // capture some frames so exposure correction takes place
  cvQueryFrame(capture);
 }

 Mat background = cvQueryFrame(capture);
 background = background.clone();
 blur(background, background, Size(50,50));

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
//  imshow("webcam", image);

// let's make multiple masks where 0=not mouth, 1=uncertain

// then multiply them together and multiply that with image
// and run haar classifier on image

  Mat gray, blurred_img;
  cvtColor(image, gray, CV_RGB2GRAY);
  blur(image, blurred_img, Size(50,50));

// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
  Mat canny;
  Canny(gray, canny, 50, 50, 3);
  blur(canny, canny, Size(width/20,height/20));
  bitwise_not(canny, canny);
  threshold(canny, canny, 200, 1, THRESH_BINARY);
  blur(canny*255, canny, Size(width/10, height/10));
  threshold(canny, canny, 220, 1, THRESH_BINARY);
  imshow("canny mask", gray.mul(canny));
*/

// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
  Mat flow;
  absdiff(blurred_img, background, flow);
  cvtColor(flow, flow, CV_RGB2GRAY);
  morphFast(flow);
  threshold(flow, flow, 60, 1, THRESH_BINARY);
//  imshow("flow mask", gray.mul(flow));

// this mask gets anything kind of dark (DK2) and dilates
  Mat kindofdark;
  equalizeHist(gray, kindofdark);
  threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
  morphFast(kindofdark, 100, 17, 0);
//  imshow("dark mask", gray.mul(kindofdark));

// this mask gets rid of anything far away from red stuff
// lips have a lot of red
  Mat notlips;
  Mat channels[3];
  split(image, channels);
  notlips = channels[2] - (channels[0]+channels[1])/2;//BGR?
  imshow("0", channels[0]);
  imshow("1", channels[1]);
  imshow("2", channels[2]);
  imshow("0+1", (channels[0]+channels[1])/2);
  imshow("2-0", channels[2] - channels[0]);
  imshow("2-1", channels[2] - channels[1]);
  //equalistHist is horrible for a red background
  //equalizeHist(notlips, notlips);
  threshold(notlips, notlips, tracker1*3, 1, THRESH_BINARY);
  imshow("lip mask", notlips*255);
  waitKey(1);

  Mat mask = flow.mul(kindofdark);
// open the mask
  Mat smallMask0, smallMask1;
  resize(mask, smallMask0, Size(width/5,height/5));
  Mat erodeKernel = ellipticKernel(69,79);
  erode(smallMask0, smallMask1, erodeKernel);
  Mat dilateKernel = ellipticKernel(69,79);
  dilate(smallMask1, smallMask1, dilateKernel);
  bitwise_and(smallMask0, smallMask1, smallMask1);
  resize(smallMask1, mask, Size(width, height));
//  imshow("morph mask", gray.mul(mask));

// update background with new morph mask
// average what we know is background with prior background
// erode it first since we really want to be sure it's bg

//  Mat erodeKernel = ellipticKernel(21);
  Mat erodedMask;
  erode(mask, erodedMask, erodeKernel);
  Mat mask_;
  subtract(1,erodedMask,mask_);
  Mat mask3, mask3_;
  channel[0] = erodedMask;
  channel[1] = erodedMask;
  channel[2] = erodedMask;
  merge(channel, 3, mask3);
  channel[0] = mask_;
  channel[1] = mask_;
  channel[2] = mask_;
  merge(channel, 3, mask3_);

  background = background.mul(mask3) +
   (background.mul(mask3_) + blurred_img.mul(mask3_))/2;

  imshow("background", background);

/*
  Moments lol = moments(gray, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
*/
/*
  CascadeClassifier mouth_cascade;
  mouth_cascade.load("Mouth.xml");
  vector<Rect> mouths;
  int scale = tracker1+1;
  Mat classifyThis = image.clone();
  equalizeHist(gray, gray);//ew; watch out not to use this later
  resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
//  bilateralFilter(gray, classifyThis, 15, 10, 1);
  mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, tracker2, CV_HAAR_SCALE_IMAGE);
  for (size_t i=0; i<mouths.size(); i++) {
   Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
   rectangle(image, scaled, Scalar(255,0,0));
  }
  imshow("MOUTH", image);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>#include "webcam.hpp"

using namespace cv;
using namespace std;

int main (int argc, char** argv) {

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  imshow("webcam", image);

// thresholds on dark regions

  Mat black, blurred;
  split(image, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
//  equalizeHist(black, black);
//  blur(black, blurred, Size(width/9,height/18));
//  threshold(blurred, blurred, 220, 255, THRESH_BINARY);
//  imshow("lol", blurred);
//  waitKey(1);
  merge(channel, 3, black);
  blur(black, blurred, Size(width/4.5,height/9));
  split(blurred, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
  equalizeHist(black, black);
  bitwise_not(black,black);

  threshold(black, black, 220, 255, THRESH_BINARY);
  imshow("black", black);

/*
  split(image, channel);
  channel[0] = channel[0].mul(black);
  channel[1] = channel[1].mul(black);
  channel[2] = channel[2].mul(black);
  merge(channel, 3, image);
*/
//  imshow("yox", image);

//do some weird morphological closing thing
//  Mat channel[3];

/*
  Mat canny;
  Canny(image, canny, 0, 50);
  imshow("canny", canny);
*/

/*
  Mat fill = image.clone();
  Point seed(rand()%width, rand()%height);
  floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
  imshow("fill", fill);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"

using namespace cv;
using namespace std;

int main (int argc, char** argv) {

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  imshow("webcam", image);

// thresholds on dark regions

  Mat black, blurred;
  split(image, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
  equalizeHist(black, black);
  blur(black, blurred, Size(width/9,height/18));
  threshold(blurred, blurred, 220, 255, THRESH_BINARY);
  imshow("lol", blurred);
  waitKey(1);
  merge(channel, 3, black);
  blur(black, blurred, Size(width/4.5,height/9));
  split(blurred, channel);
  black = (channel[0] + channel[1] + channel[2])/3.0;
  equalizeHist(black, black);
  bitwise_not(black,black);

  threshold(black, black, 220, 255, THRESH_BINARY);
  imshow("black", black);

/*
  split(image, channel);
  channel[0] = channel[0].mul(black);
  channel[1] = channel[1].mul(black);
  channel[2] = channel[2].mul(black);
  merge(channel, 3, image);
*/
//  imshow("yox", image);

//do some weird morphological closing thing
//  Mat channel[3];

/*
  Mat canny;
  Canny(image, canny, 0, 50);
  imshow("canny", canny);
*/

/*
  Mat fill = image.clone();
  Point seed(rand()%width, rand()%height);
  floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25));
  imshow("fill", fill);
*/

  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>/** \file   VuFind.cc
 *  \brief  VuFind-related constants and utility functions.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015,2017 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "VuFind.h"
#include <stdexcept>
#include "DbConnection.h"
#include "File.h"
#include "FileUtil.h"
#include "MiscUtil.h"
#include "StringUtil.h"

namespace VuFind {

static const std::string DATABASE_CONF("local/config/vufind/local_overrides/database.conf");
static const std::string DATABASE_CONF_ALTERNATIVE("local/tuefind/local_overrides/database.conf");

std::shared_ptr<DbConnection> GetDbConnection() {
    return std::make_shared<DbConnection>(GetMysqlURL());
}

std::string GetDefaultDatabaseConf() {
    const std::string VUFIND_HOME(MiscUtil::GetEnv("VUFIND_HOME"));
    const std::string database_conf(VUFIND_HOME + "/" + VuFind::DATABASE_CONF);
    return FileUtil::Exists(database_conf)  ? database_conf : VUFIND_HOME + "/" + VuFind::DATABASE_CONF_ALTERNATIVE;
}

std::string GetMysqlURL(const std::string &vufind_config_file_path) {
    const std::string database_conf_filename(vufind_config_file_path.empty()
                                             ? GetDefaultDatabaseConf() : vufind_config_file_path);
    File database_conf(database_conf_filename, "r", File::THROW_ON_ERROR);
    const std::string line(database_conf.getline());
    const size_t schema_pos(line.find("mysql://"));
    if (schema_pos == std::string::npos)
        throw std::runtime_error("MySQL schema not found in \"" + database_conf_filename + "\"!");
    std::string mysql_url(StringUtil::RightTrim(line.substr(schema_pos)));
    mysql_url.resize(mysql_url.size() - 1); // Remove trailing double quote.
    return mysql_url;
}

const std::string GetTueFindFlavour() {
    return MiscUtil::SafeGetEnv("TUEFIND_FLAVOUR");
}

} // namespace VuFind
<commit_msg>VuFind.cc: copyright<commit_after>/** \file   VuFind.cc
 *  \brief  VuFind-related constants and utility functions.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2015,2017,2019 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "VuFind.h"
#include <stdexcept>
#include "DbConnection.h"
#include "File.h"
#include "FileUtil.h"
#include "MiscUtil.h"
#include "StringUtil.h"

namespace VuFind {

static const std::string DATABASE_CONF("local/config/vufind/local_overrides/database.conf");
static const std::string DATABASE_CONF_ALTERNATIVE("local/tuefind/local_overrides/database.conf");

std::shared_ptr<DbConnection> GetDbConnection() {
    return std::make_shared<DbConnection>(GetMysqlURL());
}

std::string GetDefaultDatabaseConf() {
    const std::string VUFIND_HOME(MiscUtil::GetEnv("VUFIND_HOME"));
    const std::string database_conf(VUFIND_HOME + "/" + VuFind::DATABASE_CONF);
    return FileUtil::Exists(database_conf)  ? database_conf : VUFIND_HOME + "/" + VuFind::DATABASE_CONF_ALTERNATIVE;
}

std::string GetMysqlURL(const std::string &vufind_config_file_path) {
    const std::string database_conf_filename(vufind_config_file_path.empty()
                                             ? GetDefaultDatabaseConf() : vufind_config_file_path);
    File database_conf(database_conf_filename, "r", File::THROW_ON_ERROR);
    const std::string line(database_conf.getline());
    const size_t schema_pos(line.find("mysql://"));
    if (schema_pos == std::string::npos)
        throw std::runtime_error("MySQL schema not found in \"" + database_conf_filename + "\"!");
    std::string mysql_url(StringUtil::RightTrim(line.substr(schema_pos)));
    mysql_url.resize(mysql_url.size() - 1); // Remove trailing double quote.
    return mysql_url;
}

const std::string GetTueFindFlavour() {
    return MiscUtil::SafeGetEnv("TUEFIND_FLAVOUR");
}

} // namespace VuFind
<|endoftext|>


<commit_before>
/** @author  Jackson Wright, Michael E. Cotterell
 *  @see     LICENSE (MIT style license file)
 */

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

using namespace std;

#define MY_SOCK_PATH "socket.sock"
#define LISTEN_BACKLOG 50

void nope_out(string fname) {
  perror(fname.c_str());
  exit(EXIT_FAILURE);
} // nope_out

// @TODO implement; unwaited children are zombies
void check_children() {

} // check_children

int main() {

  int sfd, cfd;
  char buffer [256];
  struct sockaddr_un my_addr, peer_addr;
  socklen_t peer_addr_size;

  // create socket
  if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    nope_out("socket");
  } // if

  // clear and set structure
  memset(&my_addr, 0, sizeof(struct sockaddr_un));
  my_addr.sun_family = AF_UNIX; //address family
  strcpy(my_addr.sun_path, MY_SOCK_PATH);

  // bind the socket to an address
  if (bind(sfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1) {
    nope_out("bind");
  } // if

  // listen for connections on the socket
  if (listen(sfd, LISTEN_BACKLOG) == -1) {
    nope_out("listen");
  } // if

  /* Now we can accept incoming connections one
     at a time using accept(2) */

  peer_addr_size = sizeof(struct sockaddr_un);

  bool done = false;

  /* This is the main server loop, will forever accept connections
     and fork, and no more */
  while (!done) {

    // accept a connection on the socket
    if ((cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_size)) == -1) {
      nope_out("accept");
    } // if

    int pid = fork();

    /* From hereonout, the CHILD process will branch out to send a receive
       inputs with the client until the client exits, whereupon it will terminate.
       The parent process will instead continue handling connections. */
    if (pid == 0) {

      /* This is a inner server loop, will forever receive and send inputs,
         and no more */
      while (!done) {
        string input;
        int inputAmount = 0;

        inputAmount = recv(cfd, buffer, 256, 0);

        if (inputAmount < 256) buffer[inputAmount] = '\0';
        input = buffer;

        // If their first four chars are "ping"
        if ((input.substr(0,4).compare("ping") == 0) &&
            ('0'<= input.back() && input.back() <= '9')) { //Is a digit

          // Send back "pong" and a number
          if(('0'<= input.back() && input.back() <= '9') && // Is even
             ((input.back() - '0') % 2 == 0)) {

            string response = "pong 0";
            send(cfd, response.c_str(), strlen(response.c_str()), 0);

          }

          else { // Is odd

            string response = "pong 1";
            send(cfd, response.c_str(), strlen(response.c_str()), 0);

          }

        }

        // If their first four chars are "quit"
        else if (input.substr(0,4).compare("quit") == 0) {
          // Break out of the loop
          done = true;

          // End the connection
          if (shutdown(cfd, SHUT_RDWR) == -1) nope_out("shutdown(cfd)");
          if (close(cfd) == -1) nope_out("close(cfd)");

          exit(EXIT_SUCCESS);
        }

        // If their command is unkown
        else {
          string response = "unknown";
          send(cfd, response.c_str(), strlen(response.c_str()), 0);
        }

      } // while

    } // if

  } // while

  /* Technically the following doesn't happen because the server doesnt shut
     down when the client wants to exit */
  if (shutdown(sfd, SHUT_RDWR) == -1) nope_out("shutdown(sfd)");
  if (close(sfd) == -1) nope_out("close(sfd)");
  if (unlink(MY_SOCK_PATH) == -1) nope_out("unlink");

  return EXIT_SUCCESS;

} // main
<commit_msg>updated socket example<commit_after>
/** @author  Jackson Wright, Michael E. Cotterell
 *  @see     LICENSE (MIT style license file)
 */

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>

using namespace std;

#define MY_SOCK_PATH "socket.sock"
#define LISTEN_BACKLOG 50

void nope_out(string fname) {
  perror(fname.c_str());
  exit(EXIT_FAILURE);
} // nope_out

int main() {

  int sfd, cfd;
  char buffer [256];
  struct sockaddr_un my_addr, peer_addr;
  socklen_t peer_addr_size;

  // explicitly prevent children turning into zombies
  if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
    nope_out("signal");
  } // if

  // create socket
  if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    nope_out("socket");
  } // if

  // clear and set structure
  memset(&my_addr, 0, sizeof(struct sockaddr_un));
  my_addr.sun_family = AF_UNIX; //address family
  strcpy(my_addr.sun_path, MY_SOCK_PATH);

  // bind the socket to an address
  if (bind(sfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1) {
    nope_out("bind");
  } // if

  // listen for connections on the socket
  if (listen(sfd, LISTEN_BACKLOG) == -1) {
    nope_out("listen");
  } // if

  /* Now we can accept incoming connections one
     at a time using accept(2) */

  peer_addr_size = sizeof(struct sockaddr_un);

  bool done = false;

  /* This is the main server loop, will forever accept connections
     and fork, and no more */
  while (!done) {

    // accept a connection on the socket
    if ((cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_size)) == -1) {
      nope_out("accept");
    } // if

    int pid = fork();

    /* From hereonout, the CHILD process will branch out to send a receive
       inputs with the client until the client exits, whereupon it will terminate.
       The parent process will instead continue handling connections. */
    if (pid == 0) {

      /* This is a inner server loop, will forever receive and send inputs,
         and no more */
      while (!done) {
        string input;
        int inputAmount = 0;

        inputAmount = recv(cfd, buffer, 256, 0);

        if (inputAmount < 256) buffer[inputAmount] = '\0';
        input = buffer;

        // If their first four chars are "ping"
        if ((input.substr(0,4).compare("ping") == 0) &&
            ('0'<= input.back() && input.back() <= '9')) { //Is a digit

          // Send back "pong" and a number
          if(('0'<= input.back() && input.back() <= '9') && // Is even
             ((input.back() - '0') % 2 == 0)) {

            string response = "pong 0";
            send(cfd, response.c_str(), strlen(response.c_str()), 0);

          }

          else { // Is odd

            string response = "pong 1";
            send(cfd, response.c_str(), strlen(response.c_str()), 0);

          }

        }

        // If their first four chars are "quit"
        else if (input.substr(0,4).compare("quit") == 0) {
          // Break out of the loop
          done = true;

          // End the connection
          if (shutdown(cfd, SHUT_RDWR) == -1) nope_out("shutdown(cfd)");
          if (close(cfd) == -1) nope_out("close(cfd)");

          exit(EXIT_SUCCESS);
        }

        // If their command is unkown
        else {
          string response = "unknown";
          send(cfd, response.c_str(), strlen(response.c_str()), 0);
        }

      } // while

    } // if

  } // while

  /* Technically the following doesn't happen because the server doesnt shut
     down when the client wants to exit */
  if (shutdown(sfd, SHUT_RDWR) == -1) nope_out("shutdown(sfd)");
  if (close(sfd) == -1) nope_out("close(sfd)");
  if (unlink(MY_SOCK_PATH) == -1) nope_out("unlink");

  return EXIT_SUCCESS;

} // main
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    currScene(new QGraphicsScene),
    currImg(new QImage)
{
    this->ui->setupUi(this);
    this->ui->graphicsView->setScene(currScene);
}

MainWindow::~MainWindow()
{
    delete currImg;
    delete currScene;
    delete ui;
}

void MainWindow::display()
{
    this->currScene->clear();
    this->currScene->addPixmap(QPixmap::fromImage(*currImg));
    this->ui->graphicsView->show();
}
void MainWindow::on_actionOpen_triggered()
{
    this->fileName = QFileDialog::getOpenFileName(this,
                                                 tr("Open Image"),
                                                 QDir::currentPath(),
                                                 tr("Image Files (*.jpeg *.jpg *.bmp *.tif *.png)")
                                                 );
    this->currImg->load(fileName);
    this->display();
}

void MainWindow::on_actionSave_triggered()
{
    this->currImg->save(this->fileName,0,100);
}

void MainWindow::on_actionSave_As_triggered()
{
    QString saveName = QFileDialog::getSaveFileName(this,
                                                    tr("Save Image"),
                                                    QDir::currentPath(),
                                                    tr("Jpeg (*.jpeg);;Bmp (*.bmp);; Tif (*.tif);;Png (*.png)")
                                                    );
    this->currImg->save(saveName,0,100);
}

void MainWindow::on_actionBlur_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}

void MainWindow::on_actionSharpen_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}

void MainWindow::on_actionTo_Greyscale_triggered()
{
    /*Apply filter to this->currImg */
    this->display();
}

void MainWindow::on_actionShow_Greylevel_Histogram_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}

void MainWindow::on_actionOtsu_s_method_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}
<commit_msg>Adding actions on the buttons<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "imagefilter.h"
#include "blur.h"
#include "grayscale.h"
#include<iostream>
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    currScene(new QGraphicsScene),
    currImg(new QImage)
{
    this->ui->setupUi(this);
    this->ui->graphicsView->setScene(currScene);
}

MainWindow::~MainWindow()
{
    delete currImg;
    delete currScene;
    delete ui;
}

void MainWindow::display()
{
    this->currScene->clear();
    this->currScene->addPixmap(QPixmap::fromImage(*currImg));
    this->ui->graphicsView->show();
}
void MainWindow::on_actionOpen_triggered()
{
    this->fileName = QFileDialog::getOpenFileName(this,
                                                 tr("Open Image"),
                                                 QDir::currentPath(),
                                                 tr("Image Files (*.jpeg *.jpg *.bmp *.tif *.png)")
                                                 );
    this->currImg->load(fileName);
    this->display();
}

void MainWindow::on_actionSave_triggered()
{
    this->currImg->save(this->fileName,0,100);
}

void MainWindow::on_actionSave_As_triggered()
{
    QString saveName = QFileDialog::getSaveFileName(this,
                                                    tr("Save Image"),
                                                    QDir::currentPath(),
                                                    tr("Jpeg (*.jpeg);;Bmp (*.bmp);; Tif (*.tif);;Png (*.png)")
                                                    );
    this->currImg->save(saveName,0,100);
}

void MainWindow::on_actionBlur_triggered()
{
    /*Apply filter to this->currImg */
    ImageFilter* filter = new Blur();
    QImage image = filter->apply(*(this->currImg));
    this->currImg = ℑ
    this->display();

}

void MainWindow::on_actionSharpen_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}

void MainWindow::on_actionTo_Greyscale_triggered()
{
    /*Apply filter to this->currImg */
    ImageFilter* filter = new GrayScale();
    QImage image = filter->apply(*(this->currImg));
    this->currImg = ℑ
    this->display();
}

void MainWindow::on_actionShow_Greylevel_Histogram_triggered()
{
    /*Apply filter to this->currImg */
    this->display();
}

void MainWindow::on_actionOtsu_s_method_triggered()
{
    /*Apply filter to this->currImg */
    this->display();

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_eff_config_aggregate.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_fbc_eff_config_aggregate.H
/// @brief Set fabric effective config attributes (aggregate) (FAPI2)
///
/// Set attributes to drive fabric SMP link enablement/SMP build operations
///
/// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
/// *HWP Team: Nest
/// *HWP Level: 2
/// *HWP Consumed by: HB,FSP
///

#ifndef _P9_FBC_EFF_CONFIG_AGGREGATE_H_
#define _P9_FBC_EFF_CONFIG_AGGREGATE_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_fbc_eff_config_aggregate_FP_t)
(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

extern "C"
{

///
/// @brief Set fabric effective configuration attributes
///
/// @param[in] i_target              Chip level target
///
/// @return fapi2:ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_fbc_eff_config_aggregate(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern "C"

#endif // _P9_FBC_EFF_CONFIG_AGGREGATE_H_
<commit_msg>L3 update -- p9_fbc_eff_config_aggregate<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_eff_config_aggregate.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_fbc_eff_config_aggregate.H
/// @brief Set fabric effective config attributes (aggregate) (FAPI2)
///
/// Set attributes to drive fabric SMP link enablement/SMP build operations
///
/// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
/// *HWP Team: Nest
/// *HWP Level: 3
/// *HWP Consumed by: HB,FSP
///

#ifndef _P9_FBC_EFF_CONFIG_AGGREGATE_H_
#define _P9_FBC_EFF_CONFIG_AGGREGATE_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_fbc_eff_config_aggregate_FP_t)
(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

extern "C"
{

///
/// @brief Set fabric effective configuration attributes
///
/// @param[in] i_target Chip level target
///
/// @return fapi2:ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_fbc_eff_config_aggregate(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern "C"

#endif // _P9_FBC_EFF_CONFIG_AGGREGATE_H_
<|endoftext|>


<commit_before>
fun nestlist : (nl_x : integer) -> ([[integer]])
  for nl_i1 in 0 .. nl_x
  initially nl1_acc = [] typed [[integer]]:
    let nl_i1_list =
      for nl_i2 in 0 .. nl_i1
      initially nl2_acc = [] typed [integer]:
        nl_i2 :: nl2_acc
    nl_i1_list :: nl1_acc
<commit_msg>added comments;<commit_after># To use this, create a runtime and include the following:
#  Load "tests/nested_loop.cp";
#  Eval "nestlist(5)";

fun nestlist : (nl_x : integer) -> ([[integer]])
  for nl_i1 in 0 .. nl_x
  initially nl1_acc = [] typed [[integer]]:
    let nl_i1_list =
      for nl_i2 in 0 .. nl_i1
      initially nl2_acc = [] typed [integer]:
        nl_i2 :: nl2_acc
    # Enable this line to see instrumentation info.
    # @: print(runtime_context) :@ typed <>
    nl_i1_list :: nl1_acc
<|endoftext|>


<commit_before>#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#include "typedecl/typedecl.hpp"

using namespace std;

string red(const string& s)     { return "\e[31m" + s + "\e[0m"; }
string green(const string& s)   { return "\e[32m" + s + "\e[0m"; }
string yellow(const string& s)  { return "\e[33m" + s + "\e[0m"; }
string blue(const string& s)    { return "\e[34m" + s + "\e[0m"; }
string magenta(const string& s) { return "\e[35m" + s + "\e[0m"; }
string cyan(const string& s)    { return "\e[36m" + s + "\e[0m"; }

struct Result {
	const string deducedTemplateArg;
	const string rvalueRefSolvedAs;
	const string overloadCalled;

	Result(const string& ded, const string& as, const string& oc)
		: deducedTemplateArg(ded), rvalueRefSolvedAs(as), overloadCalled(oc)
	{}
};
bool operator==(const Result& lhs, const Result& rhs) {
	return lhs.overloadCalled == rhs.overloadCalled
	    && lhs.deducedTemplateArg == rhs.deducedTemplateArg
	    && lhs.rvalueRefSolvedAs == rhs.rvalueRefSolvedAs;
}

class C {
public:
	const string name;
	C(const string& name) : name(name) {}
};
DEFINE_TYPEDECL(C);

string overloadedFunction(const C&) { return "const C&"; }
string overloadedFunction(C&)       { return "C&"; }

template <typename T>
Result forwardingFunction(T&& arg) {
	string deducedTemplateArg = typedecl<T>();
	string rvalueRefSolvedAs = typedecl<T&&>();

	string overloadCalled = overloadedFunction(forward<T>(arg));

	cout << "Calling forwardingFunction(" << cyan("T") << yellow("&&") << " arg) with " << blue(arg.name) << endl;
	cout << "\tDeduced " << cyan("T") << " = " << cyan(deducedTemplateArg) << endl;
	cout << "\tType of arg is " << cyan("T") << yellow("&&") << " = " << cyan(deducedTemplateArg) << " " << yellow("&&") << " = " << green(rvalueRefSolvedAs) << endl;
	cout << "\tForwarded to: overloadedFunction(" << red(overloadCalled) << ")" << endl;
	cout << endl;
	return {deducedTemplateArg, rvalueRefSolvedAs, overloadCalled};
}

enum Category { LVALUE, RVALUE };

template <typename T, Category CAT>
T returns() {
	static C c = namedecl<T>(CAT == LVALUE ? "lvalue" : "rvalue");
	return static_cast<T>(c);
}

int main() {
	C                    lvalue = returns<C, LVALUE>();
	C&              lref_lvalue = returns<C&, LVALUE>();
	C&&             rref_lvalue = returns<C&&, LVALUE>();
	const C        const_lvalue = returns<const C, LVALUE>();
	const C&  const_lref_lvalue = returns<const C&, LVALUE>();
	const C&& const_rref_lvalue = returns<const C&&, LVALUE>();

	assert(forwardingFunction(lvalue)            == Result(      "C&",       "C&",       "C&"));
	assert(forwardingFunction(lref_lvalue)       == Result(      "C&",       "C&",       "C&"));
	assert(forwardingFunction(rref_lvalue)       == Result(      "C&",       "C&",       "C&"));
	assert(forwardingFunction(const_lvalue)      == Result("const C&", "const C&", "const C&"));
	assert(forwardingFunction(const_lref_lvalue) == Result("const C&", "const C&", "const C&"));
	assert(forwardingFunction(const_rref_lvalue) == Result("const C&", "const C&", "const C&"));

	#define            rvalue returns<C, RVALUE>()
	#define       lref_rvalue returns<C&, RVALUE>()
	#define       rref_rvalue returns<C&&, RVALUE>()
	#define      const_rvalue returns<const C, RVALUE>()
	#define const_lref_rvalue returns<const C&, RVALUE>()
	#define const_rref_rvalue returns<const C&&, RVALUE>()

	assert(forwardingFunction(           rvalue) == Result(      "C" ,       "C&&", "const C&"));
	assert(forwardingFunction(      lref_rvalue) == Result(      "C&",       "C&" ,       "C&"));
	assert(forwardingFunction(      rref_rvalue) == Result(      "C" ,       "C&&", "const C&"));
	assert(forwardingFunction(     const_rvalue) == Result("const C" , "const C&&", "const C&"));
	assert(forwardingFunction(const_lref_rvalue) == Result("const C&", "const C&" , "const C&"));
	assert(forwardingFunction(const_rref_rvalue) == Result("const C" , "const C&&", "const C&"));

	cout << "OK" << endl;
}
<commit_msg>perfect-forwarding: Include cases for common constructor overloads<commit_after>#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#include "typedecl/typedecl.hpp"

using namespace std;

string red(const string& s)     { return "\e[31m" + s + "\e[0m"; }
string green(const string& s)   { return "\e[32m" + s + "\e[0m"; }
string yellow(const string& s)  { return "\e[33m" + s + "\e[0m"; }
string blue(const string& s)    { return "\e[34m" + s + "\e[0m"; }
string magenta(const string& s) { return "\e[35m" + s + "\e[0m"; }
string cyan(const string& s)    { return "\e[36m" + s + "\e[0m"; }

struct Result {
	const string deducedTemplateArg;
	const string rvalueRefSolvedAs;
	const string functionOverloadCalled;
	const string constructorOverloadCalled;

	Result(const string& ded, const string& as, const string& foc, const string& coc)
		: deducedTemplateArg(ded),
		  rvalueRefSolvedAs(as),
		  functionOverloadCalled(foc),
		  constructorOverloadCalled(coc)
	{}
};
bool operator==(const Result& lhs, const Result& rhs) {
	return lhs.functionOverloadCalled == rhs.functionOverloadCalled
	    && lhs.constructorOverloadCalled == rhs.constructorOverloadCalled
	    && lhs.deducedTemplateArg == rhs.deducedTemplateArg
	    && lhs.rvalueRefSolvedAs == rhs.rvalueRefSolvedAs;
}

class C {
public:
	const string name;
	C(const string& name) : name(name) {}
};
DEFINE_TYPEDECL(C);

string overloadedFunction(const C&) { return "const C&"; }
string overloadedFunction(C&)       { return "C&"; }

string overloadedConstructor(const C&)  { return "const C&"; }
string overloadedConstructor(C&&)       { return "C&&"; }

template <typename T>
Result forwardingFunction(T&& arg) {
	string deducedTemplateArg = typedecl<T>();
	string rvalueRefSolvedAs = typedecl<T&&>();

	string functionOverloadCalled = overloadedFunction(forward<T>(arg));
	string constructorOverloadCalled = overloadedConstructor(forward<T>(arg));

	cout << "Calling forwardingFunction(" << cyan("T") << yellow("&&") << " arg) with " << blue(arg.name) << endl;
	cout << "\tDeduced " << cyan("T") << " = " << cyan(deducedTemplateArg) << endl;
	cout << "\tType of arg is " << cyan("T") << yellow("&&") << " = " << cyan(deducedTemplateArg) << " " << yellow("&&") << " = " << green(rvalueRefSolvedAs) << endl;
	cout << "\tForwarded to: overloadedFunction(" << red(functionOverloadCalled) << ")" << endl;
	cout << "\tForwarded to: overloadedConstructor(" << red(constructorOverloadCalled) << ")" << endl;
	cout << endl;
	return {deducedTemplateArg, rvalueRefSolvedAs, functionOverloadCalled, constructorOverloadCalled};
}

enum Category { LVALUE, RVALUE };

template <typename T, Category CAT>
T returns() {
	static C c = namedecl<T>(CAT == LVALUE ? "lvalue" : "rvalue");
	return static_cast<T>(c);
}

int main() {
	C                    lvalue = returns<C, LVALUE>();
	C&              lref_lvalue = returns<C&, LVALUE>();
	C&&             rref_lvalue = returns<C&&, LVALUE>();
	const C        const_lvalue = returns<const C, LVALUE>();
	const C&  const_lref_lvalue = returns<const C&, LVALUE>();
	const C&& const_rref_lvalue = returns<const C&&, LVALUE>();

	assert(forwardingFunction(lvalue)            == Result(      "C&",       "C&",       "C&", "const C&"));
	assert(forwardingFunction(lref_lvalue)       == Result(      "C&",       "C&",       "C&", "const C&"));
	assert(forwardingFunction(rref_lvalue)       == Result(      "C&",       "C&",       "C&", "const C&"));
	assert(forwardingFunction(const_lvalue)      == Result("const C&", "const C&", "const C&", "const C&"));
	assert(forwardingFunction(const_lref_lvalue) == Result("const C&", "const C&", "const C&", "const C&"));
	assert(forwardingFunction(const_rref_lvalue) == Result("const C&", "const C&", "const C&", "const C&"));

	#define            rvalue returns<C, RVALUE>()
	#define       lref_rvalue returns<C&, RVALUE>()
	#define       rref_rvalue returns<C&&, RVALUE>()
	#define      const_rvalue returns<const C, RVALUE>()
	#define const_lref_rvalue returns<const C&, RVALUE>()
	#define const_rref_rvalue returns<const C&&, RVALUE>()

	assert(forwardingFunction(           rvalue) == Result(      "C" ,       "C&&", "const C&",       "C&&"));
	assert(forwardingFunction(      lref_rvalue) == Result(      "C&",       "C&" ,       "C&", "const C&"));
	assert(forwardingFunction(      rref_rvalue) == Result(      "C" ,       "C&&", "const C&",       "C&&"));
	assert(forwardingFunction(     const_rvalue) == Result("const C" , "const C&&", "const C&", "const C&"));
	assert(forwardingFunction(const_lref_rvalue) == Result("const C&", "const C&" , "const C&", "const C&"));
	assert(forwardingFunction(const_rref_rvalue) == Result("const C" , "const C&&", "const C&", "const C&"));
}
<|endoftext|>


<commit_before>#include <jni.h>

#include <assert.h>
#include <jni.h>
#include <string.h>

// for __android_log_print(ANDROID_LOG_INFO, "YourApp", "formatted message");
// #include <android/log.h>

// for native audio
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>

// for native asset manager
#include <sys/types.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>

#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "JNI_DEBUGGING", __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,   "JNI_DEBUGGING", __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,   "JNI_DEBUGGING", __VA_ARGS__)

// engine interfaces
static SLObjectItf engineObject = NULL;
static SLEngineItf engineEngine;

// recorder interfaces
static SLObjectItf recorderObject = NULL;
static SLRecordItf recorderRecord;
static SLAndroidSimpleBufferQueueItf recorderBufferQueue;

static short* recorderBuffer[2];
static int currentBuffer;
static int currentBufferIndex;
static unsigned recorderSize = 0;
static SLmilliHertz recorderSR;

static JNIEnv* environment;
static jobject theObject;
static jclass parentClass;
static jmethodID parentCallback;

static int RECORDER_FRAMES = 4410;

void callParentCallback(char* ch){
	//a sample function to call JAVA method
	//parentClass = (*environment)->FindClass(environment, "com/example/tapir/MainActivity");
	//parentCallback = (*environment)->GetStaticMethodID(environment,parentClass,"tc", "(Ljava/lang/String;)Ljava/lang/String;");
	//(*environment)->CallStaticVoidMethod(environment, parentClass, parentCallback, (*environment)->NewStringUTF(environment, "decoded string"));

	jstring jstr = (*environment)->NewStringUTF(environment, ch);
	    jclass clazz = (*environment)->FindClass(environment, "com/example/tapirreceiver/MainActivity");
	    jmethodID messageMe = (*environment)->GetMethodID(environment, clazz, "tc", "(Ljava/lang/String;)Ljava/lang/String;");
	    jobject rrr	 = (*environment)->CallObjectMethod(environment, theObject, messageMe, jstr);
}

// this callback handler is called every time a buffer finishes recording
void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
	//recorderBuffer[currentbuffer] contains (the lastly filled) buffer data
	//do correlation check, decoding, or whatsoever with this array BEFORE enqueueing

    SLresult result;
	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[currentBuffer],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	currentBuffer= (currentBuffer==0?1:0);

	//LOGE("recording...");

    //callParentCallback("recording ");
}

void Java_com_example_tapirreceiver_MainActivity_startTapir( JNIEnv* env,
                                                  jobject thiz )
{
	environment = env;
	theObject = thiz;

	TapirDSP::init();

	callParentCallback("recording initiated");

	currentBuffer = 0;
	currentBufferIndex =0;
	recorderBuffer[0] = (short*)calloc(RECORDER_FRAMES, sizeof(short));
	recorderBuffer[1] = (short*)calloc(RECORDER_FRAMES, sizeof(short));

	SLresult result;

	// create engine
	result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// realize the engine
	result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// get the engine interface, which is needed in order to create other objects
	result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// configure audio source
	SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT,
			SL_DEFAULTDEVICEID_AUDIOINPUT, NULL};
	SLDataSource audioSrc = {&loc_dev, NULL};

	// configure audio sink
	SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
	SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
		SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
		SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN};
	SLDataSink audioSnk = {&loc_bq, &format_pcm};

	// create audio recorder
	// (requires the RECORD_AUDIO permission)
	const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE};
	const SLboolean req[1] = {SL_BOOLEAN_TRUE};
	result = (*engineEngine)->CreateAudioRecorder(engineEngine, &recorderObject, &audioSrc,
			&audioSnk, 1, id, req);
	if (SL_RESULT_SUCCESS != result) {
		//return JNI_FALSE;
	}

	// realize the audio recorder
	result = (*recorderObject)->Realize(recorderObject, SL_BOOLEAN_FALSE);
	if (SL_RESULT_SUCCESS != result) {
		//return JNI_FALSE;
	}

	// get the record interface
	result = (*recorderObject)->GetInterface(recorderObject, SL_IID_RECORD, &recorderRecord);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// get the buffer queue interface
	result = (*recorderObject)->GetInterface(recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
			&recorderBufferQueue);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// register callback on the buffer queue
	result = (*recorderBufferQueue)->RegisterCallback(recorderBufferQueue, bqRecorderCallback,
			NULL);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// the buffer is not valid for playback yet
	recorderSize = 0;

	// enqueue two empty buffers to be filled by the recorder

	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[0],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;
	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[1],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// start recording
	result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_RECORDING);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;
}

void Java_com_example_tapir_MainActivity_stopTapir( JNIEnv* env,
                                                  jobject thiz )
{
	SLresult result;
	result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED);
	if (SL_RESULT_SUCCESS == result) {
		recorderSize = RECORDER_FRAMES * sizeof(short);
		recorderSR = SL_SAMPLINGRATE_16;
	}

	// destroy audio recorder object, and invalidate all associated interfaces
	if (recorderObject != NULL) {
		(*recorderObject)->Destroy(recorderObject);
		recorderObject = NULL;
		recorderRecord = NULL;
		recorderBufferQueue = NULL;
	}

	// destroy engine object, and invalidate all associated interfaces
	if (engineObject != NULL) {
		(*engineObject)->Destroy(engineObject);
		engineObject = NULL;
		engineEngine = NULL;
	}

	free(recorderBuffer[0]);
	free(recorderBuffer[1]);
}
<commit_msg>native thread problem solved need to be checked in c++ environment<commit_after>#include <jni.h>

#include <assert.h>
#include <jni.h>
#include <string.h>

// for __android_log_print(ANDROID_LOG_INFO, "YourApp", "formatted message");
// #include <android/log.h>

// for native audio
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>

// for native asset manager
#include <sys/types.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>

#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "JNI_DEBUGGING", __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,   "JNI_DEBUGGING", __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,   "JNI_DEBUGGING", __VA_ARGS__)

// engine interfaces
static SLObjectItf engineObject = NULL;
static SLEngineItf engineEngine;

// recorder interfaces
static SLObjectItf recorderObject = NULL;
static SLRecordItf recorderRecord;
static SLAndroidSimpleBufferQueueItf recorderBufferQueue;

static short* recorderBuffer[2];
static int currentBuffer;
static int currentBufferIndex;
static unsigned recorderSize = 0;
static SLmilliHertz recorderSR;

static JavaVm *qJavaVM;
static JNIEnv* environment;
static jobject theObject;
static jclass parentClass;
static jmethodID parentCallback;

static int RECORDER_FRAMES = 4410;

void callParentCallback(char* ch){

    int status;
    bool isAttached = false;
    status = qJavaVM->GetEnv((void **) &environment, JNI_VERSION_1_4);
    //not sure for the jni version parameter, try 1_6 when this fails
    if(status<0){
        LOGE("JNI callback is called from a native method");
        status = qJavaVM->AttachCurrentThread(&environment, NULL);
        if(status<0){
            LOGE("failed to attach current thread");
        }
        isAttached = true;
    }
	jstring jstr = environment->NewStringUTF(ch);
    jclass clazz = environment->FindClass( "com/example/tapirreceiver/MainActivity");
    jmethodID messageMe = environment->GetMethodID( clazz, "tc", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject rrr	 = environment->CallObjectMethod( theObject, messageMe, jstr);
    if(isAttached){
        qJavaVM->DetachCurrentThread();
    }
}

// this callback handler is called every time a buffer finishes recording
void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
	//recorderBuffer[currentbuffer] contains (the lastly filled) buffer data
	//do correlation check, decoding, or whatsoever with this array BEFORE enqueueing

    SLresult result;
	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[currentBuffer],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	currentBuffer= (currentBuffer==0?1:0);

	//LOGE("recording...");

    //callParentCallback("recording ");
}

void Java_com_example_tapirreceiver_MainActivity_startTapir( JNIEnv* env,
                                                  jobject thiz )
{
	qJavaVM = android::AndroidRuntime::getJavaVM();
    environment = env;
	theObject = thiz;

	TapirDSP::init();

	callParentCallback("recording initiated");

	currentBuffer = 0;
	currentBufferIndex =0;
	recorderBuffer[0] = (short*)calloc(RECORDER_FRAMES, sizeof(short));
	recorderBuffer[1] = (short*)calloc(RECORDER_FRAMES, sizeof(short));

	SLresult result;

	// create engine
	result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// realize the engine
	result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// get the engine interface, which is needed in order to create other objects
	result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// configure audio source
	SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT,
			SL_DEFAULTDEVICEID_AUDIOINPUT, NULL};
	SLDataSource audioSrc = {&loc_dev, NULL};

	// configure audio sink
	SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
	SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
		SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
		SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN};
	SLDataSink audioSnk = {&loc_bq, &format_pcm};

	// create audio recorder
	// (requires the RECORD_AUDIO permission)
	const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE};
	const SLboolean req[1] = {SL_BOOLEAN_TRUE};
	result = (*engineEngine)->CreateAudioRecorder(engineEngine, &recorderObject, &audioSrc,
			&audioSnk, 1, id, req);
	if (SL_RESULT_SUCCESS != result) {
		//return JNI_FALSE;
	}

	// realize the audio recorder
	result = (*recorderObject)->Realize(recorderObject, SL_BOOLEAN_FALSE);
	if (SL_RESULT_SUCCESS != result) {
		//return JNI_FALSE;
	}

	// get the record interface
	result = (*recorderObject)->GetInterface(recorderObject, SL_IID_RECORD, &recorderRecord);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// get the buffer queue interface
	result = (*recorderObject)->GetInterface(recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
			&recorderBufferQueue);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// register callback on the buffer queue
	result = (*recorderBufferQueue)->RegisterCallback(recorderBufferQueue, bqRecorderCallback,
			NULL);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// the buffer is not valid for playback yet
	recorderSize = 0;

	// enqueue two empty buffers to be filled by the recorder

	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[0],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;
	result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, recorderBuffer[1],
			RECORDER_FRAMES * sizeof(short));
	assert(SL_RESULT_SUCCESS == result);
	(void)result;

	// start recording
	result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_RECORDING);
	assert(SL_RESULT_SUCCESS == result);
	(void)result;
}

void Java_com_example_tapir_MainActivity_stopTapir( JNIEnv* env,
                                                  jobject thiz )
{
	SLresult result;
	result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED);
	if (SL_RESULT_SUCCESS == result) {
		recorderSize = RECORDER_FRAMES * sizeof(short);
		recorderSR = SL_SAMPLINGRATE_16;
	}

	// destroy audio recorder object, and invalidate all associated interfaces
	if (recorderObject != NULL) {
		(*recorderObject)->Destroy(recorderObject);
		recorderObject = NULL;
		recorderRecord = NULL;
		recorderBufferQueue = NULL;
	}

	// destroy engine object, and invalidate all associated interfaces
	if (engineObject != NULL) {
		(*engineObject)->Destroy(engineObject);
		engineObject = NULL;
		engineEngine = NULL;
	}

	free(recorderBuffer[0]);
	free(recorderBuffer[1]);
}
<|endoftext|>