text:
namespace chromeos {

namespace {

const char kNetworkStateOffline[] = "offline";
const char kNetworkStateOnline[] = "online";
const char kNetworkStateCaptivePortal[] = "behind captive portal";
const char kNetworkStateConnecting[] = "connecting";
const char kNetworkStateProxyAuthRequired[] = "proxy auth required";

bool HasDefaultNetworkProxyConfigured() {
  const NetworkState* network =
      NetworkHandler::Get()->network_state_handler()->DefaultNetwork();
  if (!network)
    return false;
  onc::ONCSource onc_source = onc::ONC_SOURCE_NONE;
  scoped_ptr<ProxyConfigDictionary> proxy_dict =
      proxy_config::GetProxyConfigForNetwork(
          NULL, g_browser_process->local_state(), *network, &onc_source);
  ProxyPrefs::ProxyMode mode;
  return (proxy_dict && proxy_dict->GetMode(&mode) &&
          mode == ProxyPrefs::MODE_FIXED_SERVERS);
}

NetworkStateInformer::State GetStateForDefaultNetwork() {
  const NetworkState* network =
      NetworkHandler::Get()->network_state_handler()->DefaultNetwork();
  if (!network)
    return NetworkStateInformer::OFFLINE;

  if (NetworkPortalDetector::Get()->IsEnabled()) {
    NetworkPortalDetector::CaptivePortalState state =
        NetworkPortalDetector::Get()->GetCaptivePortalState(network->guid());
    NetworkPortalDetector::CaptivePortalStatus status = state.status;
    if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN &&
        NetworkState::StateIsConnecting(network->connection_state())) {
      return NetworkStateInformer::CONNECTING;
    }
    // For proxy-less networks rely on shill's online state if
    // NetworkPortalDetector's state of current network is unknown.
    if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE ||
        (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN &&
         !HasDefaultNetworkProxyConfigured() &&
         network->connection_state() == shill::kStateOnline)) {
      return NetworkStateInformer::ONLINE;
    }
    if (status ==
            NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PROXY_AUTH_REQUIRED &&
        HasDefaultNetworkProxyConfigured()) {
      return NetworkStateInformer::PROXY_AUTH_REQUIRED;
    }
    if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL ||
        (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN &&
         network->is_captive_portal()))
      return NetworkStateInformer::CAPTIVE_PORTAL;
  } else {
    if (NetworkState::StateIsConnecting(network->connection_state()))
      return NetworkStateInformer::CONNECTING;
    if (network->connection_state() == shill::kStateOnline)
      return NetworkStateInformer::ONLINE;
    if (network->is_captive_portal())
      return NetworkStateInformer::CAPTIVE_PORTAL;
  }
  return NetworkStateInformer::OFFLINE;
}

}  // namespace

NetworkStateInformer::NetworkStateInformer()
    : state_(OFFLINE),
      weak_ptr_factory_(this) {
}

NetworkStateInformer::~NetworkStateInformer() {
  if (NetworkHandler::IsInitialized()) {
    NetworkHandler::Get()->network_state_handler()->RemoveObserver(
        this, FROM_HERE);
  }
  NetworkPortalDetector::Get()->RemoveObserver(this);
}

void NetworkStateInformer::Init() {
  UpdateState();
  NetworkHandler::Get()->network_state_handler()->AddObserver(
      this, FROM_HERE);

  NetworkPortalDetector::Get()->AddAndFireObserver(this);

  registrar_.Add(this,
                 chrome::NOTIFICATION_LOGIN_PROXY_CHANGED,
                 content::NotificationService::AllSources());
  registrar_.Add(this,
                 chrome::NOTIFICATION_SESSION_STARTED,
                 content::NotificationService::AllSources());
}

void NetworkStateInformer::AddObserver(NetworkStateInformerObserver* observer) {
  if (!observers_.HasObserver(observer))
    observers_.AddObserver(observer);
}

void NetworkStateInformer::RemoveObserver(
    NetworkStateInformerObserver* observer) {
  observers_.RemoveObserver(observer);
}

void NetworkStateInformer::DefaultNetworkChanged(const NetworkState* network) {
  UpdateStateAndNotify();
}

void NetworkStateInformer::OnPortalDetectionCompleted(
    const NetworkState* network,
    const NetworkPortalDetector::CaptivePortalState& state) {
  UpdateStateAndNotify();
}

void NetworkStateInformer::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  if (type == chrome::NOTIFICATION_SESSION_STARTED)
    registrar_.RemoveAll();
  else if (type == chrome::NOTIFICATION_LOGIN_PROXY_CHANGED)
    SendStateToObservers(NetworkError::ERROR_REASON_PROXY_CONFIG_CHANGED);
  else
    NOTREACHED() << "Unknown notification: " << type;
}

void NetworkStateInformer::OnPortalDetected() {
  UpdateStateAndNotify();
}

// static
const char* NetworkStateInformer::StatusString(State state) {
  switch (state) {
    case OFFLINE:
      return kNetworkStateOffline;
    case ONLINE:
      return kNetworkStateOnline;
    case CAPTIVE_PORTAL:
      return kNetworkStateCaptivePortal;
    case CONNECTING:
      return kNetworkStateConnecting;
    case PROXY_AUTH_REQUIRED:
      return kNetworkStateProxyAuthRequired;
    default:
      NOTREACHED();
      return NULL;
  }
}

bool NetworkStateInformer::UpdateState() {
  const NetworkState* default_network =
      NetworkHandler::Get()->network_state_handler()->DefaultNetwork();
  State new_state = GetStateForDefaultNetwork();
  std::string new_network_path;
  std::string new_network_type;
  if (default_network) {
    new_network_path = default_network->path();
    new_network_type = default_network->type();
  }

  bool updated = (new_state != state_) ||
      (new_network_path != network_path_) ||
      (new_network_type != network_type_);
  state_ = new_state;
  network_path_ = new_network_path;
  network_type_ = new_network_type;

  if (updated && state_ == ONLINE) {
    FOR_EACH_OBSERVER(NetworkStateInformerObserver, observers_,
                      OnNetworkReady());
  }

  return updated;
}

void NetworkStateInformer::UpdateStateAndNotify() {
  if (UpdateState())
    SendStateToObservers(NetworkError::ERROR_REASON_NETWORK_STATE_CHANGED);
  else
    SendStateToObservers(NetworkError::ERROR_REASON_UPDATE);
}

void NetworkStateInformer::SendStateToObservers(
    NetworkError::ErrorReason reason) {
  FOR_EACH_OBSERVER(NetworkStateInformerObserver, observers_,
      UpdateState(reason));
}

}  // namespace chromeos


text:
/**
  * © 2019 Refinitiv. All Rights Reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
package cmwell.tools.data.utils.akka

import akka.stream.ThrottleMode.{Enforcing, Shaping}
import akka.stream.stage.GraphStage
import akka.stream.stage._
import akka.stream.{Attributes, RateExceededException, ThrottleMode, _}
import akka.util.NanoTimeTokenBucket

import scala.concurrent.duration.{FiniteDuration, _}

/**
  * INTERNAL API
  */
class TitForTatThrottle[T] extends GraphStage[FlowShape[T, T]] {

  val in = Inlet[T]("TitForTatThrottle.in")
  val out = Outlet[T]("TitForTatThrottle.out")
  override val shape = FlowShape(in, out)

  // There is some loss of precision here because of rounding, but this only happens if nanosBetweenTokens is very
  // small which is usually at rates where that precision is highly unlikely anyway as the overhead of this stage
  // is likely higher than the required accuracy interval.
//  private val nanosBetweenTokens = per.toNanos / cost
  private val timerName: String = "ThrottleTimer"

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new TimerGraphStageLogic(shape) {
//    private val tokenBucket = new NanoTimeTokenBucket(maximumBurst, nanosBetweenTokens)

    var willStop = false
    var currentElement: T = _

    // This scope is here just to not retain an extra reference to the handler below.
    // We can't put this code into preRestart() because setHandler() must be called before that.
    {
      val handler = new InHandler with OutHandler {
        var timeOfPreviousElmement = System.currentTimeMillis()

        override def onUpstreamFinish(): Unit =
          if (isAvailable(out) && isTimerActive(timerName)) willStop = true
          else completeStage()

        override def onPush(): Unit = {
          val elem = grab(in)
          val now = System.currentTimeMillis()
          val delayMillis = now - timeOfPreviousElmement
          timeOfPreviousElmement = now

          if (delayMillis == 0L) push(out, elem)
          else {
            currentElement = elem
            System.err.println(s"scheduled push in ${delayMillis.milliseconds}")
            scheduleOnce(timerName, delayMillis.milliseconds)
          }
        }

        override def onPull(): Unit = pull(in)
      }

      setHandler(in, handler)
      setHandler(out, handler)
      // After this point, we no longer need the `handler` so it can just fall out of scope.
    }

    override protected def onTimer(key: Any): Unit = {
      push(out, currentElement)
      currentElement = null.asInstanceOf[T]
      if (willStop) completeStage()
    }

  }

  override def toString = "Throttle"
}

redpajama_set_name: RedPajamaGithub


text:
from setuptools import find_packages, setup

setup(name="umaineapi",
      version = "0.1",
      description = "A collection of API's for various UMaine services",
      author = "Noah Howard",
      platforms = ["any"],
      license = "BSD",
      packages = find_packages(),
      install_requires = ["Flask", "requests", "flask-mysqldb", "jsonify" ],
      )


text:
<?php

namespace Google\Service\CloudSearch;

class PrefDeleted extends \Google\Model
{
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PrefDeleted::class, 'Google_Service_CloudSearch_PrefDeleted');


text:
using System;
using System.Globalization;

///<summary>
///System.Globalization.CharUnicodeInfo.GetNumericValue(Char)
///</summary>

public class CharUnicodeInfoGetNumericValue
{

    public static int Main()
    {
        CharUnicodeInfoGetNumericValue testObj = new CharUnicodeInfoGetNumericValue();
        TestLibrary.TestFramework.BeginTestCase("for method of System.Globalization.CharUnicodeInfo.GetNumericValue");
        if (testObj.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }

    }

    public bool RunTests()
    {
        bool retVal = true;
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;
        retVal = PosTest4() && retVal;
        retVal = PosTest5() && retVal;
        retVal = PosTest6() && retVal;
        return retVal;
    }

    #region Test Logic
    public bool PosTest1()
    {
        bool retVal = true;

        Char ch = '\0';

        Double expectedValue = -1;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario(@"PosTest1:Test the method with '\0'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;

        Char ch = '0';

        Double expectedValue = 0;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '0'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    public bool PosTest3()
    {
        bool retVal = true;

        Char ch = '9';

        Double expectedValue = 9;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '9'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    public bool PosTest4()
    {
        bool retVal = true;

        Char ch = '\u3289';

        Double expectedValue = 10;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char '\\u3289'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("007", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    public bool PosTest5()
    {
        bool retVal = true;

        Char ch = 'a';

        Double expectedValue = -1;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char 'a'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("009", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    public bool PosTest6()
    {
        bool retVal = true;

        Char ch = 'Z';

        Double expectedValue = -1;

        Double actualValue;

        TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with char 'Z'");
        try
        {
            actualValue = CharUnicodeInfo.GetNumericValue(ch);
            if (expectedValue != actualValue)
            {
                TestLibrary.TestFramework.LogError("011", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e);
            retVal = false;
        }
        return retVal;
    }

    #endregion
}


text:
namespace tests
{

struct Foo final
{
    struct Schema
    {
        static const ::bond::Metadata metadata;

        private: static const ::bond::Metadata s_foo11_metadata;
        private: static const ::bond::Metadata s_foo12_metadata;
        private: static const ::bond::Metadata s_foo12_impl_metadata;
        private: static const ::bond::Metadata s_foo13_metadata;
        private: static const ::bond::Metadata s_foo14_metadata;
        private: static const ::bond::Metadata s_foo15_metadata;
        private: static const ::bond::Metadata s_foo21_metadata;
        private: static const ::bond::Metadata s_foo22_metadata;
        private: static const ::bond::Metadata s_foo23_metadata;
        private: static const ::bond::Metadata s_foo24_metadata;
        private: static const ::bond::Metadata s_foo31_metadata;
        private: static const ::bond::Metadata s_foo32_metadata;
        private: static const ::bond::Metadata s_foo33_metadata;
        private: static const ::bond::Metadata s__rd_foo33_metadata;
        private: static const ::bond::Metadata s_foo34_metadata;
        private: static const ::bond::Metadata s_foo41_metadata;
        private: static const ::bond::Metadata s_foo42_metadata;
        private: static const ::bond::Metadata s_foo43_metadata;
        private: static const ::bond::Metadata s_foo44_metadata;
        private: static const ::bond::Metadata s_cq_metadata;

        public: struct service
        {
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::bond::reflection::nothing, &s_foo11_metadata> {} foo11;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::bond::reflection::nothing, &s_foo12_metadata> {} foo12;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::bond::reflection::nothing, &s_foo12_impl_metadata> {} foo12_impl;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::BasicTypes, ::bond::reflection::nothing, &s_foo13_metadata> {} foo13;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::dummy, ::bond::reflection::nothing, &s_foo14_metadata> {} foo14;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests2::OtherBasicTypes, ::bond::reflection::nothing, &s_foo15_metadata> {} foo15;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, void, &s_foo21_metadata> {} foo21;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, void, &s_foo22_metadata> {} foo22;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::BasicTypes, void, &s_foo23_metadata> {} foo23;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::dummy, void, &s_foo24_metadata> {} foo24;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::tests::BasicTypes, &s_foo31_metadata> {} foo31;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::tests::BasicTypes, &s_foo32_metadata> {} foo32;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::BasicTypes, ::tests::BasicTypes, &s_foo33_metadata> {} foo33;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::BasicTypes, ::tests::BasicTypes, &s__rd_foo33_metadata> {} _rd_foo33;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::dummy, ::tests::BasicTypes, &s_foo34_metadata> {} foo34;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::tests::dummy, &s_foo41_metadata> {} foo41;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::tests::dummy, &s_foo42_metadata> {} foo42;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::BasicTypes, ::tests::dummy, &s_foo43_metadata> {} foo43;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, ::tests::dummy, ::tests::dummy, &s_foo44_metadata> {} foo44;
            typedef struct : ::bond::ext::grpc::reflection::MethodTemplate<Foo, void, ::tests::BasicTypes, &s_cq_metadata> {} cq;
        };

        private: typedef boost::mpl::list<> methods0;
        private: typedef boost::mpl::push_front<methods0, service::cq>::type methods1;
        private: typedef boost::mpl::push_front<methods1, service::foo44>::type methods2;
        private: typedef boost::mpl::push_front<methods2, service::foo43>::type methods3;
        private: typedef boost::mpl::push_front<methods3, service::foo42>::type methods4;
        private: typedef boost::mpl::push_front<methods4, service::foo41>::type methods5;
        private: typedef boost::mpl::push_front<methods5, service::foo34>::type methods6;
        private: typedef boost::mpl::push_front<methods6, service::_rd_foo33>::type methods7;
        private: typedef boost::mpl::push_front<methods7, service::foo33>::type methods8;
        private: typedef boost::mpl::push_front<methods8, service::foo32>::type methods9;
        private: typedef boost::mpl::push_front<methods9, service::foo31>::type methods10;
        private: typedef boost::mpl::push_front<methods10, service::foo24>::type methods11;
        private: typedef boost::mpl::push_front<methods11, service::foo23>::type methods12;
        private: typedef boost::mpl::push_front<methods12, service::foo22>::type methods13;
        private: typedef boost::mpl::push_front<methods13, service::foo21>::type methods14;
        private: typedef boost::mpl::push_front<methods14, service::foo15>::type methods15;
        private: typedef boost::mpl::push_front<methods15, service::foo14>::type methods16;
        private: typedef boost::mpl::push_front<methods16, service::foo13>::type methods17;
        private: typedef boost::mpl::push_front<methods17, service::foo12_impl>::type methods18;
        private: typedef boost::mpl::push_front<methods18, service::foo12>::type methods19;
        private: typedef boost::mpl::push_front<methods19, service::foo11>::type methods20;

        public: typedef methods20::type methods;

    };

    class Client : public ::bond::ext::grpc::detail::client
    {
    public:
        using ::bond::ext::grpc::detail::client::client;

        void Asyncfoo11(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo11, std::move(context), {});
        }

        void Asyncfoo12(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo12, std::move(context), {});
        }

        void Asyncfoo12_impl(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo12_impl, std::move(context), {});
        }

        void Asyncfoo13(const ::bond::bonded< ::tests::BasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo13, std::move(context), {}, request);
        }
        void Asyncfoo13(const ::tests::BasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo13, std::move(context), {}, request);
        }

        void Asyncfoo14(const ::bond::bonded< ::tests::dummy>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo14, std::move(context), {}, request);
        }
        void Asyncfoo14(const ::tests::dummy& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo14, std::move(context), {}, request);
        }

        void Asyncfoo15(const ::bond::bonded< ::tests2::OtherBasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo15, std::move(context), {}, request);
        }
        void Asyncfoo15(const ::tests2::OtherBasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo15, std::move(context), {}, request);
        }

        void Asyncfoo21(const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo21, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo21(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo21, std::move(context));
        }

        void Asyncfoo22(const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo22, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo22(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo22, std::move(context));
        }

        void Asyncfoo23(const ::bond::bonded< ::tests::BasicTypes>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo23, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo23(const ::bond::bonded< ::tests::BasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo23, std::move(context), request);
        }
        void Asyncfoo23(const ::tests::BasicTypes& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo23, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo23(const ::tests::BasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo23, std::move(context), request);
        }

        void Asyncfoo24(const ::bond::bonded< ::tests::dummy>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo24, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo24(const ::bond::bonded< ::tests::dummy>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo24, std::move(context), request);
        }
        void Asyncfoo24(const ::tests::dummy& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<void>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo24, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<void>> Asyncfoo24(const ::tests::dummy& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<void>(_mfoo24, std::move(context), request);
        }

        void Asyncfoo31(const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo31, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo31(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo31, std::move(context));
        }

        void Asyncfoo32(const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo32, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo32(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo32, std::move(context));
        }

        void Asyncfoo33(const ::bond::bonded< ::tests::BasicTypes>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo33, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo33(const ::bond::bonded< ::tests::BasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo33, std::move(context), request);
        }
        void Asyncfoo33(const ::tests::BasicTypes& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo33, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo33(const ::tests::BasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo33, std::move(context), request);
        }

        void Async_rd_foo33(const ::bond::bonded< ::tests::BasicTypes>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_m_rd_foo33, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Async_rd_foo33(const ::bond::bonded< ::tests::BasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_m_rd_foo33, std::move(context), request);
        }
        void Async_rd_foo33(const ::tests::BasicTypes& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_m_rd_foo33, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Async_rd_foo33(const ::tests::BasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_m_rd_foo33, std::move(context), request);
        }

        void Asyncfoo34(const ::bond::bonded< ::tests::dummy>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo34, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo34(const ::bond::bonded< ::tests::dummy>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo34, std::move(context), request);
        }
        void Asyncfoo34(const ::tests::dummy& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo34, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asyncfoo34(const ::tests::dummy& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mfoo34, std::move(context), request);
        }

        void Asyncfoo41(const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo41, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo41(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo41, std::move(context));
        }

        void Asyncfoo42(const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo42, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo42(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo42, std::move(context));
        }

        void Asyncfoo43(const ::bond::bonded< ::tests::BasicTypes>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo43, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo43(const ::bond::bonded< ::tests::BasicTypes>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo43, std::move(context), request);
        }
        void Asyncfoo43(const ::tests::BasicTypes& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo43, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo43(const ::tests::BasicTypes& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo43, std::move(context), request);
        }

        void Asyncfoo44(const ::bond::bonded< ::tests::dummy>& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo44, std::move(context), cb, request);
        }
        std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo44(const ::bond::bonded< ::tests::dummy>& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo44, std::move(context), request);
        }
        void Asyncfoo44(const ::tests::dummy& request, const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::dummy>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mfoo44, std::move(context), cb, request);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::dummy>> Asyncfoo44(const ::tests::dummy& request, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::dummy>(_mfoo44, std::move(context), request);
        }

        void Asynccq(const ::std::function<void(::bond::ext::grpc::unary_call_result<::tests::BasicTypes>)>& cb, ::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            ::bond::ext::grpc::detail::client::dispatch(_mcq, std::move(context), cb);
        }
        ::std::future<::bond::ext::grpc::unary_call_result<::tests::BasicTypes>> Asynccq(::std::shared_ptr<::grpc::ClientContext> context = {})
        {
            return ::bond::ext::grpc::detail::client::dispatch<::tests::BasicTypes>(_mcq, std::move(context));
        }

    private:
        const ::bond::ext::grpc::detail::client::Method _mfoo11{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo11") };
        const ::bond::ext::grpc::detail::client::Method _mfoo12{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo12") };
        const ::bond::ext::grpc::detail::client::Method _mfoo12_impl{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo12_impl") };
        const ::bond::ext::grpc::detail::client::Method _mfoo13{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo13") };
        const ::bond::ext::grpc::detail::client::Method _mfoo14{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo14") };
        const ::bond::ext::grpc::detail::client::Method _mfoo15{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo15") };
        const ::bond::ext::grpc::detail::client::Method _mfoo21{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo21") };
        const ::bond::ext::grpc::detail::client::Method _mfoo22{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo22") };
        const ::bond::ext::grpc::detail::client::Method _mfoo23{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo23") };
        const ::bond::ext::grpc::detail::client::Method _mfoo24{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo24") };
        const ::bond::ext::grpc::detail::client::Method _mfoo31{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo31") };
        const ::bond::ext::grpc::detail::client::Method _mfoo32{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo32") };
        const ::bond::ext::grpc::detail::client::Method _mfoo33{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo33") };
        const ::bond::ext::grpc::detail::client::Method _m_rd_foo33{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/_rd_foo33") };
        const ::bond::ext::grpc::detail::client::Method _mfoo34{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo34") };
        const ::bond::ext::grpc::detail::client::Method _mfoo41{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo41") };
        const ::bond::ext::grpc::detail::client::Method _mfoo42{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo42") };
        const ::bond::ext::grpc::detail::client::Method _mfoo43{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo43") };
        const ::bond::ext::grpc::detail::client::Method _mfoo44{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/foo44") };
        const ::bond::ext::grpc::detail::client::Method _mcq{ ::bond::ext::grpc::detail::client::make_method("/tests.Foo/cq") };
    };

    class Service : public ::bond::ext::grpc::detail::service
    {
    public:
        explicit Service(const ::bond::ext::grpc::Scheduler& scheduler)
            : ::bond::ext::grpc::detail::service(
                scheduler,
                {
                    "/tests.Foo/foo11",
                    "/tests.Foo/foo12",
                    "/tests.Foo/foo12_impl",
                    "/tests.Foo/foo13",
                    "/tests.Foo/foo14",
                    "/tests.Foo/foo15",
                    "/tests.Foo/foo21",
                    "/tests.Foo/foo22",
                    "/tests.Foo/foo23",
                    "/tests.Foo/foo24",
                    "/tests.Foo/foo31",
                    "/tests.Foo/foo32",
                    "/tests.Foo/foo33",
                    "/tests.Foo/_rd_foo33",
                    "/tests.Foo/foo34",
                    "/tests.Foo/foo41",
                    "/tests.Foo/foo42",
                    "/tests.Foo/foo43",
                    "/tests.Foo/foo44",
                    "/tests.Foo/cq"
                })
        {}

        virtual void foo11(::bond::ext::grpc::unary_call<void, ::bond::reflection::nothing>) = 0;
        virtual void foo12(::bond::ext::grpc::unary_call<void, ::bond::reflection::nothing>) = 0;
        virtual void foo12_impl(::bond::ext::grpc::unary_call<void, ::bond::reflection::nothing>) = 0;
        virtual void foo13(::bond::ext::grpc::unary_call<::tests::BasicTypes, ::bond::reflection::nothing>) = 0;
        virtual void foo14(::bond::ext::grpc::unary_call<::tests::dummy, ::bond::reflection::nothing>) = 0;
        virtual void foo15(::bond::ext::grpc::unary_call<::tests2::OtherBasicTypes, ::bond::reflection::nothing>) = 0;
        virtual void foo21(::bond::ext::grpc::unary_call<void, void>) = 0;
        virtual void foo22(::bond::ext::grpc::unary_call<void, void>) = 0;
        virtual void foo23(::bond::ext::grpc::unary_call<::tests::BasicTypes, void>) = 0;
        virtual void foo24(::bond::ext::grpc::unary_call<::tests::dummy, void>) = 0;
        virtual void foo31(::bond::ext::grpc::unary_call<void, ::tests::BasicTypes>) = 0;
        virtual void foo32(::bond::ext::grpc::unary_call<void, ::tests::BasicTypes>) = 0;
        virtual void foo33(::bond::ext::grpc::unary_call<::tests::BasicTypes, ::tests::BasicTypes>) = 0;
        virtual void _rd_foo33(::bond::ext::grpc::unary_call<::tests::BasicTypes, ::tests::BasicTypes>) = 0;
        virtual void foo34(::bond::ext::grpc::unary_call<::tests::dummy, ::tests::BasicTypes>) = 0;
        virtual void foo41(::bond::ext::grpc::unary_call<void, ::tests::dummy>) = 0;
        virtual void foo42(::bond::ext::grpc::unary_call<void, ::tests::dummy>) = 0;
        virtual void foo43(::bond::ext::grpc::unary_call<::tests::BasicTypes, ::tests::dummy>) = 0;
        virtual void foo44(::bond::ext::grpc::unary_call<::tests::dummy, ::tests::dummy>) = 0;
        virtual void cq(::bond::ext::grpc::unary_call<void, ::tests::BasicTypes>) = 0;

    private:
        void start() override
        {
            _data.emplace(*this);
        }

        struct data
        {
            explicit data(Service& s)
                : _s(s)
            {}

            Service& _s;
            ::bond::ext::grpc::detail::service::Method _m0{ _s, 0, ::bond::ext::grpc::detail::service::make_callback(&Service::foo11, _s) };
            ::bond::ext::grpc::detail::service::Method _m1{ _s, 1, ::bond::ext::grpc::detail::service::make_callback(&Service::foo12, _s) };
            ::bond::ext::grpc::detail::service::Method _m2{ _s, 2, ::bond::ext::grpc::detail::service::make_callback(&Service::foo12_impl, _s) };
            ::bond::ext::grpc::detail::service::Method _m3{ _s, 3, ::bond::ext::grpc::detail::service::make_callback(&Service::foo13, _s) };
            ::bond::ext::grpc::detail::service::Method _m4{ _s, 4, ::bond::ext::grpc::detail::service::make_callback(&Service::foo14, _s) };
            ::bond::ext::grpc::detail::service::Method _m5{ _s, 5, ::bond::ext::grpc::detail::service::make_callback(&Service::foo15, _s) };
            ::bond::ext::grpc::detail::service::Method _m6{ _s, 6, ::bond::ext::grpc::detail::service::make_callback(&Service::foo21, _s) };
            ::bond::ext::grpc::detail::service::Method _m7{ _s, 7, ::bond::ext::grpc::detail::service::make_callback(&Service::foo22, _s) };
            ::bond::ext::grpc::detail::service::Method _m8{ _s, 8, ::bond::ext::grpc::detail::service::make_callback(&Service::foo23, _s) };
            ::bond::ext::grpc::detail::service::Method _m9{ _s, 9, ::bond::ext::grpc::detail::service::make_callback(&Service::foo24, _s) };
            ::bond::ext::grpc::detail::service::Method _m10{ _s, 10, ::bond::ext::grpc::detail::service::make_callback(&Service::foo31, _s) };
            ::bond::ext::grpc::detail::service::Method _m11{ _s, 11, ::bond::ext::grpc::detail::service::make_callback(&Service::foo32, _s) };
            ::bond::ext::grpc::detail::service::Method _m12{ _s, 12, ::bond::ext::grpc::detail::service::make_callback(&Service::foo33, _s) };
            ::bond::ext::grpc::detail::service::Method _m13{ _s, 13, ::bond::ext::grpc::detail::service::make_callback(&Service::_rd_foo33, _s) };
            ::bond::ext::grpc::detail::service::Method _m14{ _s, 14, ::bond::ext::grpc::detail::service::make_callback(&Service::foo34, _s) };
            ::bond::ext::grpc::detail::service::Method _m15{ _s, 15, ::bond::ext::grpc::detail::service::make_callback(&Service::foo41, _s) };
            ::bond::ext::grpc::detail::service::Method _m16{ _s, 16, ::bond::ext::grpc::detail::service::make_callback(&Service::foo42, _s) };
            ::bond::ext::grpc::detail::service::Method _m17{ _s, 17, ::bond::ext::grpc::detail::service::make_callback(&Service::foo43, _s) };
            ::bond::ext::grpc::detail::service::Method _m18{ _s, 18, ::bond::ext::grpc::detail::service::make_callback(&Service::foo44, _s) };
            ::bond::ext::grpc::detail::service::Method _m19{ _s, 19, ::bond::ext::grpc::detail::service::make_callback(&Service::cq, _s) };
        };

        ::boost::optional<data> _data;
    };
};

} // namespace tests


text:
package org.hisp.dhis.webapi.controller;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hisp.dhis.datastore.MetadataDatastoreService.METADATA_STORE_NS;
import static org.hisp.dhis.utils.Assertions.assertContainsOnly;
import static org.hisp.dhis.web.WebClientUtils.assertSeries;
import static org.hisp.dhis.web.WebClientUtils.assertStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.LocalDate;
import java.util.List;

import org.hisp.dhis.datastore.DatastoreEntry;
import org.hisp.dhis.datastore.DatastoreNamespaceProtection;
import org.hisp.dhis.datastore.DatastoreNamespaceProtection.ProtectionType;
import org.hisp.dhis.datastore.DatastoreService;
import org.hisp.dhis.web.HttpStatus;
import org.hisp.dhis.web.HttpStatus.Series;
import org.hisp.dhis.webapi.DhisControllerConvenienceTest;
import org.hisp.dhis.webapi.json.domain.JsonDatastoreValue;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Tests the {@link DatastoreController} using (mocked) REST requests.
 *
 * @author Jan Bernitt
 */
class DatastoreControllerTest extends DhisControllerConvenienceTest
{

    /**
     * Only used directly to setup namespace protection as this is by intention
     * not possible using the REST API.
     */
    @Autowired
    private DatastoreService service;

    @Test
    void testGetNamespaces()
    {
        // out of the box (as superuser)
        assertSeries( Series.SUCCESSFUL, POST( "/dataStore/METADATASTORE/key", "{}" ) );
        assertEquals( singletonList( METADATA_STORE_NS ), GET( "/dataStore" ).content().stringValues() );
        // after we created an entry in foo namespace
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/colors/blue", "{'answer': 42}" ) );
        assertEquals( asList( METADATA_STORE_NS, "colors" ), GET( "/dataStore" ).content().stringValues() );
    }

    @Test
    void testGetNamespaces_HiddenNamespaceNotVisible()
    {
        // does not have special authorities
        switchToNewUser( "anonymous" );
        assertEquals( emptyList(), GET( "/dataStore" ).content().stringValues() );
    }

    @Test
    void testGetNamespaces_RestrictedNamespaceIsVisible()
    {
        setUpNamespaceProtection( "fruits", ProtectionType.RESTRICTED, "fruits_ns_authority" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/fruits/apple", "{'answer': 42}" ) );
        // does not have special authorities
        switchToNewUser( "anonymous" );
        assertEquals( singletonList( "fruits" ), GET( "/dataStore" ).content().stringValues() );
    }

    @Test
    void testGetKeysInNamespace()
    {
        assertSeries( Series.SUCCESSFUL, POST( "/dataStore/METADATASTORE/key", "{}" ) );
        assertEquals( singletonList( "key" ),
            GET( "/dataStore/{namespace}", METADATA_STORE_NS ).content().stringValues() );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{'answer': 42}" ) );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/dog", "{'answer': true}" ) );
        assertContainsOnly( List.of( "cat", "dog" ), GET( "/dataStore/pets" ).content().stringValues() );
    }

    @Test
    void testGetKeysInNamespace_MustExist()
    {
        assertEquals( "Namespace not found: 'missing'",
            GET( "/dataStore/missing" ).error( HttpStatus.NOT_FOUND ).getMessage() );
    }

    @Test
    void testGetKeysInNamespace_LastUpdatedFilter()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{'answer': 42}" ) );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/dog", "{'answer': true}" ) );
        assertTrue( GET( "/dataStore/pets?lastUpdated=" + (LocalDate.now().getYear() + 1) ).content().stringValues()
            .isEmpty() );
    }

    @Test
    void testGetKeysInNamespace_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{'answer': 42}" ) );
        // as superuser:
        assertEquals( singletonList( "cat" ), GET( "/dataStore/pets" ).content().stringValues() );
        // as a user that is a pets admin
        switchToNewUser( "some-user", "pets-admin" );
        assertEquals( singletonList( "cat" ), GET( "/dataStore/pets" ).content().stringValues() );
        // as a user that lacks authority
        switchToNewUser( "anonymous" );
        assertEquals( "Namespace 'pets' is protected, access denied",
            GET( "/dataStore/pets" ).error( HttpStatus.FORBIDDEN ).getMessage() );
    }

    @Test
    void testGetKeysInNamespace_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{'answer': 42}" ) );
        // as superuser:
        assertEquals( singletonList( "cat" ), GET( "/dataStore/pets" ).content().stringValues() );
        // as a user that is a pets admin
        switchToNewUser( "some-user", "pets-admin" );
        assertEquals( singletonList( "cat" ), GET( "/dataStore/pets" ).content().stringValues() );
        // as a user that lacks authority
        switchToNewUser( "anonymous" );
        assertEquals( "Namespace not found: 'pets'",
            GET( "/dataStore/pets" ).error( HttpStatus.NOT_FOUND ).getMessage() );
    }

    @Test
    void testDeleteNamespace()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets" ) );
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets" ) );
    }

    @Test
    void testDeleteNamespace_MustExist()
    {
        assertStatus( HttpStatus.NOT_FOUND, DELETE( "/dataStore/missing" ) );
    }

    @Test
    void testDeleteNamespace_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        // user that lacks authority
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.FORBIDDEN, DELETE( "/dataStore/pets" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets" ) );
    }

    @Test
    void testDeleteNamespace_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        // user that lacks authority
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.NOT_FOUND, DELETE( "/dataStore/pets" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets" ) );
    }

    @Test
    void testDeleteNamespace_ProtectedNamespaceWithSharing()
    {
        setUpNamespaceProtectionWithSharing( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        String uid = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class ).getId();
        assertStatus( HttpStatus.OK,
            POST( "/sharing?type=dataStore&id=" + uid, "{'object':{'publicAccess':'--------'}}" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertEquals( "Access denied for key 'cat' in namespace 'pets'",
            DELETE( "/dataStore/pets" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        switchToSuperuser();
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets" ) );
    }

    @Test
    void testGetKeyJsonValue()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "'dog'" ) );
        assertEquals( "dog", GET( "/dataStore/pets/cat" ).content().string() );
    }

    @Test
    void testGetKeyJsonValue_ComplexValue()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{'x':[1,2,3]}" ) );
        assertEquals( asList( 1, 2, 3 ), GET( "/dataStore/pets/cat" ).content().getArray( "x" ).numberValues() );
    }

    @Test
    void testGetKeyJsonValue_MustExist()
    {
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets/cat" ) );
    }

    @Test
    void testGetKeyJsonValue_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets/cat" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertTrue( GET( "/dataStore/pets/cat" ).content().isObject() );
    }

    @Test
    void testGetKeyJsonValue_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.FORBIDDEN, GET( "/dataStore/pets/cat" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertTrue( GET( "/dataStore/pets/cat" ).content().isObject() );
    }

    @Test
    void testGetKeyJsonValue_ProtectedNamespaceWithSharing()
    {
        setUpNamespaceProtectionWithSharing( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        String uid = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class ).getId();
        assertStatus( HttpStatus.OK,
            POST( "/sharing?type=dataStore&id=" + uid, "{'object':{'publicAccess':'--------'}}" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertEquals( "Access denied for key 'cat' in namespace 'pets'",
            GET( "/dataStore/pets/cat" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        switchToSuperuser();
        assertStatus( HttpStatus.OK, GET( "/dataStore/pets/cat" ) );
    }

    @Test
    void testGetKeyJsonValueMetaData()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        JsonDatastoreValue metaData = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class );
        assertEquals( "pets", metaData.getNamespace() );
        assertEquals( "cat", metaData.getKey() );
        assertTrue( metaData.getValue().isUndefined(), "metadata should not contain the value" );
    }

    @Test
    void testGetKeyJsonValueMetaData_MustExist()
    {
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets/missing/metaData" ) );
    }

    @Test
    void testGetKeyJsonValueMetaData_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.FORBIDDEN, GET( "/dataStore/pets/cat/metaData" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, GET( "/dataStore/pets/cat/metaData" ) );
    }

    @Test
    void testGetKeyJsonValueMetaData_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets/cat/metaData" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, GET( "/dataStore/pets/cat/metaData" ) );
    }

    @Test
    void testGetKeyJsonValueMetaData_ProtectedNamespaceWithSharing()
    {
        setUpNamespaceProtectionWithSharing( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        String uid = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class ).getId();
        assertStatus( HttpStatus.OK,
            POST( "/sharing?type=dataStore&id=" + uid, "{'object':{'publicAccess':'--------'}}" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertEquals( "Access denied for key 'cat' in namespace 'pets'",
            GET( "/dataStore/pets/cat/metaData" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        switchToSuperuser();
        assertStatus( HttpStatus.OK, GET( "/dataStore/pets/cat/metaData" ) );
    }

    @Test
    void testAddKeyJsonValue()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
    }

    @Test
    void testAddKeyJsonValue_Encrypt()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat?encrypt=true", "{}" ) );
        // there is no way to see in the exposed metadata that a value is
        // encrypted, user service
        DatastoreEntry entry = service.getEntry( "pets", "cat" );
        assertTrue( entry.getEncrypted() );
        assertNull( entry.getJbPlainValue() );
        assertNotNull( entry.getEncryptedValue() );
    }

    @Test
    void testAddKeyJsonValue_AlreadyExists()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        assertEquals( "Key 'cat' already exists in namespace 'pets'",
            POST( "/dataStore/pets/cat", "{}" ).error( HttpStatus.CONFLICT ).getMessage() );
    }

    @Test
    void testAddKeyJsonValue_MustBeJson()
    {
        assertEquals( "Invalid JSON value for key 'cat'",
            POST( "/dataStore/pets/cat", "/not JSON/" ).error( HttpStatus.BAD_REQUEST ).getMessage() );
    }

    @Test
    void testAddKeyJsonValue_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.FORBIDDEN, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
    }

    @Test
    void testAddKeyJsonValue_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        // but:
        assertStatus( HttpStatus.NOT_FOUND, GET( "/dataStore/pets/cat" ) );
    }

    @Test
    void testUpdateKeyJsonValue()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        assertStatus( HttpStatus.OK, PUT( "/dataStore/pets/cat", "[1,2,3]" ) );
        assertEquals( asList( 1, 2, 3 ), GET( "/dataStore/pets/cat" ).content().numberValues() );
    }

    @Test
    void testUpdateKeyJsonValue_MustExist()
    {
        assertEquals( "Key 'cat' not found in namespace 'pets'",
            PUT( "/dataStore/pets/cat", "[]" ).error( HttpStatus.NOT_FOUND ).getMessage() );
    }

    @Test
    void testUpdateKeyJsonValue_MustBeJson()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        assertEquals( "Invalid JSON value for key 'cat'",
            PUT( "/dataStore/pets/cat", "+not JSON+" ).error( HttpStatus.BAD_REQUEST ).getMessage() );
    }

    @Test
    void testUpdateKeyJsonValue_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.FORBIDDEN, PUT( "/dataStore/pets/cat", "[]" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, PUT( "/dataStore/pets/cat", "[]" ) );
    }

    @Test
    void testUpdateKeyJsonValue_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertStatus( HttpStatus.NOT_FOUND, PUT( "/dataStore/pets/cat", "[]" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, PUT( "/dataStore/pets/cat", "[]" ) );
    }

    @Test
    void testUpdateKeyJsonValue_ProtectedNamespaceWithSharing()
    {
        setUpNamespaceProtectionWithSharing( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        String uid = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class ).getId();
        assertStatus( HttpStatus.OK,
            POST( "/sharing?type=dataStore&id=" + uid, "{'object':{'publicAccess':'r-------'}}" ) );
        switchToNewUser( "someone", "pets-admin" );
        assertEquals( "Access denied for key 'cat' in namespace 'pets'",
            PUT( "/dataStore/pets/cat", "[]" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        switchToSuperuser();
        assertStatus( HttpStatus.OK, PUT( "/dataStore/pets/cat", "[]" ) );
    }

    @Test
    void testDeleteKeyJsonValue()
    {
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets/cat" ) );
    }

    @Test
    void testDeleteKeyJsonValue_MustExist()
    {
        assertEquals( "Key 'cat' not found in namespace 'pets'",
            DELETE( "/dataStore/pets/cat" ).error( HttpStatus.NOT_FOUND ).getMessage() );
    }

    @Test
    void testDeleteKeyJsonValue_ProtectedNamespaceWhenRestricted()
    {
        setUpNamespaceProtection( "pets", ProtectionType.RESTRICTED, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertEquals( "Namespace 'pets' is protected, access denied",
            DELETE( "/dataStore/pets/cat" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets/cat" ) );
    }

    @Test
    void testDeleteKeyJsonValue_ProtectedNamespaceWhenHidden()
    {
        setUpNamespaceProtection( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        switchToNewUser( "anonymous" );
        assertEquals( "Key 'cat' not found in namespace 'pets'",
            DELETE( "/dataStore/pets/cat" ).error( HttpStatus.NOT_FOUND ).getMessage() );
        switchToNewUser( "someone", "pets-admin" );
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets/cat" ) );
    }

    @Test
    void testDeleteKeyJsonValue_ProtectedNamespaceWithSharing()
    {
        setUpNamespaceProtectionWithSharing( "pets", ProtectionType.HIDDEN, "pets-admin" );
        assertStatus( HttpStatus.CREATED, POST( "/dataStore/pets/cat", "{}" ) );
        String uid = GET( "/dataStore/pets/cat/metaData" ).content().as( JsonDatastoreValue.class ).getId();
        assertStatus( HttpStatus.OK,
            POST( "/sharing?type=dataStore&id=" + uid, "{'object':{'publicAccess':'r-------'}}" ) );
        // a user with required authority cannot delete (ACL fails)
        switchToNewUser( "someone", "pets-admin" );
        assertEquals( "Access denied for key 'cat' in namespace 'pets'",
            DELETE( "/dataStore/pets/cat" ).error( HttpStatus.FORBIDDEN ).getMessage() );
        // but the owner still can
        switchToSuperuser();
        assertStatus( HttpStatus.OK, DELETE( "/dataStore/pets/cat" ) );
    }

    private void setUpNamespaceProtection( String namespace, ProtectionType readWrite, String... authorities )
    {
        service.addProtection( new DatastoreNamespaceProtection( namespace, readWrite, false, authorities ) );
    }

    private void setUpNamespaceProtectionWithSharing( String namespace, ProtectionType readWrite,
        String... authorities )
    {
        service.addProtection( new DatastoreNamespaceProtection( namespace, readWrite, true, authorities ) );
    }
}


text:
{
    'name': 'Barcodes',
    'version': '2.0',
    'category': 'Extra Tools',
    'summary': 'Barcodes Scanning and Parsing',
    'description': """
This module adds support for barcode scanning and parsing.

Scanning
--------
Use a USB scanner (that mimics keyboard inputs) in order to work with barcodes in Odoo.
The scanner must be configured to use no prefix and a carriage return or tab as suffix.
The delay between each character input must be less than or equal to 50 milliseconds.
Most barcode scanners will work out of the box.
However, make sure the scanner uses the same keyboard layout as the device it's plugged in.
Either by setting the device's keyboard layout to US QWERTY (default value for most readers)
or by changing the scanner's keyboard layout (check the manual).

Parsing
-------
The barcodes are interpreted using the rules defined by a nomenclature.
It provides the following features:
- Patterns to identify barcodes containing a numerical value (e.g. weight, price)
- Definition of barcode aliases that allow to identify the same product with different barcodes
- Support for encodings EAN-13, EAN-8 and UPC-A
""",
    'depends': ['web'],
    'data': [
        'data/barcodes_data.xml',
        'barcodes_view.xml',
        'security/ir.model.access.csv',
        'views/templates.xml',
    ],
    'installable': True,
    'auto_install': False,
}


text: export { default } from 'ember-sortable/modifiers/sortable-item';


text:
<!--
  ~ Copyright (c) 2015 by David Hardy. Licensed under the Apache License, Version 2.0.
  -->

<resources>
    <string name="app_name">BabyNames</string>
    <string name="action_settings">Settings</string>
</resources>


text:
title: 'Visualize git log with 'gource''
layout: post
comments: true
---
Visualization never gets boring, especially when it comes to demonstrate your working processing in a time span.

In my case, I had been working on the project **ihotfood** for a couple of months, spanning from October  2014 till mid December 2014. At the end of the project, I demonstrated the team members' contributions to the project in the most intuitive way. That's where the de facto open source **gource **comes to shine.

Git log can be used as the input to **gource**. Then, I customized by changing the avatars, adding subtitle and background music.

<iframe width="750" height="422" src="https://www.youtube.com/embed/DBt8ToWJgaw" frameborder="0" allowfullscreen="allowfullscreen"></iframe>


text:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Util;

namespace QuantConnect.Data.UniverseSelection
{
    /// <summary>
    /// Provides a base class for all universes to derive from.
    /// </summary>
    public abstract class Universe : IDisposable
    {
        /// <summary>
        /// Used to round the members time in universe <see cref="CanRemoveMember"/>, this is
        /// done because we can not guarantee exact selection time in live mode, see GH issue 3287
        /// </summary>
        private TimeSpan? _minimumTimeInUniverseRoundingInterval;

        /// <summary>
        /// Gets a value indicating that no change to the universe should be made
        /// </summary>
        public static readonly UnchangedUniverse Unchanged = UnchangedUniverse.Instance;

        private HashSet<Symbol> _previousSelections;

        /// <summary>
        /// Gets the internal security collection used to define membership in this universe
        /// </summary>
        public virtual ConcurrentDictionary<Symbol, Member> Securities
        {
            get;
            private set;
        }

        /// <summary>
        /// Event fired when the universe selection has changed
        /// </summary>
        public event EventHandler SelectionChanged;

        /// <summary>
        /// Gets the security type of this universe
        /// </summary>
        public SecurityType SecurityType
        {
            get { return Configuration.SecurityType; }
        }

        /// <summary>
        /// Gets the market of this universe
        /// </summary>
        public string Market
        {
            get { return Configuration.Market; }
        }

        /// <summary>
        /// Flag indicating if disposal of this universe has been requested
        /// </summary>
        public virtual bool DisposeRequested
        {
            get;
            protected set;
        }

        /// <summary>
        /// Gets the settings used for subscriptions added for this universe
        /// </summary>
        public abstract UniverseSettings UniverseSettings
        {
            get;
        }

        /// <summary>
        /// Gets the configuration used to get universe data
        /// </summary>
        public virtual SubscriptionDataConfig Configuration
        {
            get; private set;
        }

        /// <summary>
        /// Gets the current listing of members in this universe. Modifications
        /// to this dictionary do not change universe membership.
        /// </summary>
        public Dictionary<Symbol, Security> Members
        {
            get { return Securities.Select(x => x.Value.Security).ToDictionary(x => x.Symbol); }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Universe"/> class
        /// </summary>
        /// <param name="config">The configuration used to source data for this universe</param>
        protected Universe(SubscriptionDataConfig config)
        {
            _previousSelections = new HashSet<Symbol>();
            Securities = new ConcurrentDictionary<Symbol, Member>();

            Configuration = config;
        }

        /// <summary>
        /// Determines whether or not the specified security can be removed from
        /// this universe. This is useful to prevent securities from being taken
        /// out of a universe before the algorithm has had enough time to make
        /// decisions on the security
        /// </summary>
        /// <param name="utcTime">The current utc time</param>
        /// <param name="security">The security to check if its ok to remove</param>
        /// <returns>True if we can remove the security, false otherwise</returns>
        public virtual bool CanRemoveMember(DateTime utcTime, Security security)
        {
            // can always remove securities after dispose requested
            if (DisposeRequested)
            {
                return true;
            }

            // can always remove delisted securities from the universe
            if (security.IsDelisted)
            {
                return true;
            }

            // if we haven't begun receiving data for this security then it's safe to remove
            var lastData = security.Cache.GetData();
            if (lastData == null)
            {
                return true;
            }

            Member member;
            if (Securities.TryGetValue(security.Symbol, out member))
            {
                if (_minimumTimeInUniverseRoundingInterval == null)
                {
                    // lets set _minimumTimeInUniverseRoundingInterval once
                    _minimumTimeInUniverseRoundingInterval = UniverseSettings.MinimumTimeInUniverse;
                    AdjustMinimumTimeInUniverseRoundingInterval();
                }

                var timeInUniverse = utcTime - member.Added;
                if (timeInUniverse.Round(_minimumTimeInUniverseRoundingInterval.Value)
                    >= UniverseSettings.MinimumTimeInUniverse)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Performs universe selection using the data specified
        /// </summary>
        /// <param name="utcTime">The current utc time</param>
        /// <param name="data">The symbols to remain in the universe</param>
        /// <returns>The data that passes the filter</returns>
        public IEnumerable<Symbol> PerformSelection(DateTime utcTime, BaseDataCollection data)
        {
            // select empty set of symbols after dispose requested
            if (DisposeRequested)
            {
                OnSelectionChanged();
                return Enumerable.Empty<Symbol>();
            }

            var result = SelectSymbols(utcTime, data);
            if (ReferenceEquals(result, Unchanged))
            {
                data.FilteredContracts = _previousSelections;
                return Unchanged;
            }

            var selections = result.ToHashSet();
            data.FilteredContracts = selections;
            var hasDiffs = _previousSelections.AreDifferent(selections);
            _previousSelections = selections;
            if (!hasDiffs)
            {
                return Unchanged;
            }

            OnSelectionChanged(selections);
            return selections;
        }

        /// <summary>
        /// Performs universe selection using the data specified
        /// </summary>
        /// <param name="utcTime">The current utc time</param>
        /// <param name="data">The symbols to remain in the universe</param>
        /// <returns>The data that passes the filter</returns>
        public abstract IEnumerable<Symbol> SelectSymbols(DateTime utcTime, BaseDataCollection data);

        /// <summary>
        /// Creates and configures a security for the specified symbol
        /// </summary>
        /// <param name="symbol">The symbol of the security to be created</param>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="marketHoursDatabase">The market hours database</param>
        /// <param name="symbolPropertiesDatabase">The symbol properties database</param>
        /// <returns>The newly initialized security object</returns>
        /// <obsolete>The CreateSecurity won't be called</obsolete>
        [Obsolete("CreateSecurity is obsolete and will not be called. The system will create the required Securities based on selected symbols")]
        public virtual Security CreateSecurity(Symbol symbol, IAlgorithm algorithm, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase)
        {
            throw new InvalidOperationException("CreateSecurity is obsolete and should not be called." +
                "The system will create the required Securities based on selected symbols");
        }

        /// <summary>
        /// Gets the subscription requests to be added for the specified security
        /// </summary>
        /// <param name="security">The security to get subscriptions for</param>
        /// <param name="currentTimeUtc">The current time in utc. This is the frontier time of the algorithm</param>
        /// <param name="maximumEndTimeUtc">The max end time</param>
        /// <returns>All subscriptions required by this security</returns>
        [Obsolete("This overload is obsolete and will not be called. It was not capable of creating new SubscriptionDataConfig due to lack of information")]
        public virtual IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc)
        {
            throw new InvalidOperationException("This overload is obsolete and should not be called." +
                "It was not capable of creating new SubscriptionDataConfig due to lack of information");
        }

        /// <summary>
        /// Gets the subscription requests to be added for the specified security
        /// </summary>
        /// <param name="security">The security to get subscriptions for</param>
        /// <param name="currentTimeUtc">The current time in utc. This is the frontier time of the algorithm</param>
        /// <param name="maximumEndTimeUtc">The max end time</param>
        /// <param name="subscriptionService">Instance which implements <see cref="ISubscriptionDataConfigService"/> interface</param>
        /// <returns>All subscriptions required by this security</returns>
        public virtual IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security,
            DateTime currentTimeUtc,
            DateTime maximumEndTimeUtc,
            ISubscriptionDataConfigService subscriptionService)
        {
            var result = subscriptionService.Add(security.Symbol,
                UniverseSettings.Resolution,
                UniverseSettings.FillForward,
                UniverseSettings.ExtendedMarketHours,
                dataNormalizationMode: UniverseSettings.DataNormalizationMode,
                subscriptionDataTypes: UniverseSettings.SubscriptionDataTypes,
                dataMappingMode: UniverseSettings.DataMappingMode,
                contractDepthOffset: (uint)Math.Abs(UniverseSettings.ContractDepthOffset));
            return result.Select(config => new SubscriptionRequest(isUniverseSubscription: false,
                universe: this,
                security: security,
                configuration: config,
                startTimeUtc: currentTimeUtc,
                endTimeUtc: maximumEndTimeUtc));
        }

        /// <summary>
        /// Determines whether or not the specified symbol is currently a member of this universe
        /// </summary>
        /// <param name="symbol">The symbol whose membership is to be checked</param>
        /// <returns>True if the specified symbol is part of this universe, false otherwise</returns>
        public bool ContainsMember(Symbol symbol)
        {
            return Securities.ContainsKey(symbol);
        }

        /// <summary>
        /// Adds the specified security to this universe
        /// </summary>
        /// <param name="utcTime">The current utc date time</param>
        /// <param name="security">The security to be added</param>
        /// <param name="isInternal">True if internal member</param>
        /// <returns>True if the security was successfully added,
        /// false if the security was already in the universe</returns>
        internal virtual bool AddMember(DateTime utcTime, Security security, bool isInternal)
        {
            // never add members to disposed universes
            if (DisposeRequested)
            {
                return false;
            }

            if (security.IsDelisted)
            {
                return false;
            }

            return Securities.TryAdd(security.Symbol, new Member(utcTime, security, isInternal));
        }

        /// <summary>
        /// Tries to remove the specified security from the universe. This
        /// will first check to verify that we can remove the security by
        /// calling the <see cref="CanRemoveMember"/> function.
        /// </summary>
        /// <param name="utcTime">The current utc time</param>
        /// <param name="security">The security to be removed</param>
        /// <returns>True if the security was successfully removed, false if
        /// we're not allowed to remove or if the security didn't exist</returns>
        internal virtual bool RemoveMember(DateTime utcTime, Security security)
        {
            if (CanRemoveMember(utcTime, security))
            {
                Member member;
                return Securities.TryRemove(security.Symbol, out member);
            }
            return false;
        }

        /// <summary>
        /// Marks this universe as disposed and ready to remove all child subscriptions
        /// </summary>
        public virtual void Dispose()
        {
            DisposeRequested = true;
        }

        /// <summary>
        /// Event invocator for the <see cref="SelectionChanged"/> event
        /// </summary>
        /// <param name="selection">The current universe selection</param>
        protected void OnSelectionChanged(HashSet<Symbol> selection = null)
        {
            SelectionChanged?.Invoke(this, new SelectionEventArgs(selection ?? new HashSet<Symbol>()));
        }

        /// <summary>
        /// Provides a value to indicate that no changes should be made to the universe.
        /// This value is intended to be returned by reference via <see cref="Universe.SelectSymbols"/>
        /// </summary>
        public sealed class UnchangedUniverse : IEnumerable<string>, IEnumerable<Symbol>
        {
            /// <summary>
            /// Read-only instance of the <see cref="UnchangedUniverse"/> value
            /// </summary>
            public static readonly UnchangedUniverse Instance = new UnchangedUniverse();
            private UnchangedUniverse() { }
            IEnumerator<Symbol> IEnumerable<Symbol>.GetEnumerator() { yield break; }
            IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield break; }
            IEnumerator IEnumerable.GetEnumerator() { yield break; }
        }

        /// <summary>
        /// Will adjust the <see cref="_minimumTimeInUniverseRoundingInterval"/>
        /// so rounding is performed as expected
        /// </summary>
        private void AdjustMinimumTimeInUniverseRoundingInterval()
        {
            if (_minimumTimeInUniverseRoundingInterval >= Time.OneDay)
            {
                _minimumTimeInUniverseRoundingInterval = Time.OneDay;
            }
            else if (_minimumTimeInUniverseRoundingInterval >= Time.OneHour)
            {
                _minimumTimeInUniverseRoundingInterval = Time.OneHour;
            }
            else if (_minimumTimeInUniverseRoundingInterval >= Time.OneMinute)
            {
                _minimumTimeInUniverseRoundingInterval = Time.OneMinute;
            }
            else if (_minimumTimeInUniverseRoundingInterval >= Time.OneSecond)
            {
                _minimumTimeInUniverseRoundingInterval = Time.OneSecond;
            }
        }

        /// <summary>
        /// Member of the Universe
        /// </summary>
        public sealed class Member
        {
            /// <summary>
            /// DateTime when added
            /// </summary>
            public readonly DateTime Added;

            /// <summary>
            /// The security that was added
            /// </summary>
            public readonly Security Security;

            /// <summary>
            /// True if the security was added as internal by this universe
            /// </summary>
            public readonly bool IsInternal;

            /// <summary>
            /// Initialize a new member for the universe
            /// </summary>
            /// <param name="added">DateTime added</param>
            /// <param name="security">Security to add</param>
            /// <param name="isInternal">True if internal member</param>
            public Member(DateTime added, Security security, bool isInternal)
            {
                Added = added;
                Security = security;
                IsInternal = isInternal;
            }
        }

        /// <summary>
        /// Event fired when the universe selection changes
        /// </summary>
        public class SelectionEventArgs : EventArgs
        {
            /// <summary>
            /// The current universe selection
            /// </summary>
            public HashSet<Symbol> CurrentSelection { get; }

            /// <summary>
            /// Creates a new instance
            /// </summary>
            public SelectionEventArgs(HashSet<Symbol> currentSelection)
            {
                CurrentSelection = currentSelection;
            }
        }
    }
}


text:
package it.besil.jweb.app.resources;

/**
 * Created by besil on 03/08/2016.
 */
public enum HttpMethod {
    get, post, put, delete, head, trace, connect
}


text:
package com.google.android.gms.samples.vision.ocrreader.ui.camera;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

import com.google.android.gms.vision.CameraSource;

import java.util.HashSet;
import java.util.Set;

/**
 * A view which renders a series of custom graphics to be overlaid on top of an associated preview
 * (i.e., the camera preview).  The creator can add graphics objects, update the objects, and remove
 * them, triggering the appropriate drawing and invalidation within the view.

 *
 * Supports scaling and mirroring of the graphics relative the camera's preview properties.  The
 * idea is that detection items are expressed in terms of a preview size, but need to be scaled up
 * to the full view size, and also mirrored in the case of the front-facing camera.

 *
 * Associated {@link Graphic} items should use the following methods to convert to view coordinates
 * for the graphics that are drawn:
 *

 *
{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the
 * supplied value from the preview scale to the view scale.

 *
{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate
 * from the preview's coordinate system to the view coordinate system.

 *

 */
public class GraphicOverlay<T extends GraphicOverlay.Graphic> extends View {
    private final Object mLock = new Object();
    private int mPreviewWidth;
    private float mWidthScaleFactor = 1.0f;
    private int mPreviewHeight;
    private float mHeightScaleFactor = 1.0f;
    private int mFacing = CameraSource.CAMERA_FACING_BACK;
    private Set<T> mGraphics = new HashSet<>();

    /**
     * Base class for a custom graphics object to be rendered within the graphic overlay.  Subclass
     * this and implement the {@link Graphic#draw(Canvas)} method to define the
     * graphics element.  Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}.
     */
    public static abstract class Graphic {
        private GraphicOverlay mOverlay;

        public Graphic(GraphicOverlay overlay) {
            mOverlay = overlay;
        }

        /**
         * Draw the graphic on the supplied canvas.  Drawing should use the following methods to
         * convert to view coordinates for the graphics that are drawn:
         *

         *
{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of
         * the supplied value from the preview scale to the view scale.

         *
{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the
         * coordinate from the preview's coordinate system to the view coordinate system.

         *

         *
         * @param canvas drawing canvas
         */
        public abstract void draw(Canvas canvas);

        /**
         * Returns true if the supplied coordinates are within this graphic.
         */
        public abstract boolean contains(float x, float y);

        /**
         * Adjusts a horizontal value of the supplied value from the preview scale to the view
         * scale.
         */
        public float scaleX(float horizontal) {
            return horizontal * mOverlay.mWidthScaleFactor;
        }

        /**
         * Adjusts a vertical value of the supplied value from the preview scale to the view scale.
         */
        public float scaleY(float vertical) {
            return vertical * mOverlay.mHeightScaleFactor;
        }

        /**
         * Adjusts the x coordinate from the preview's coordinate system to the view coordinate
         * system.
         */
        public float translateX(float x) {
            if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) {
                return mOverlay.getWidth() - scaleX(x);
            } else {
                return scaleX(x);
            }
        }

        /**
         * Adjusts the y coordinate from the preview's coordinate system to the view coordinate
         * system.
         */
        public float translateY(float y) {
            return scaleY(y);
        }

        public void postInvalidate() {
            mOverlay.postInvalidate();
        }
    }

    public GraphicOverlay(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Removes all graphics from the overlay.
     */
    public void clear() {
        synchronized (mLock) {
            mGraphics.clear();
        }
        postInvalidate();
    }

    /**
     * Adds a graphic to the overlay.
     */
    public void add(T graphic) {
        synchronized (mLock) {
            mGraphics.add(graphic);
        }
        postInvalidate();
    }

    /**
     * Removes a graphic from the overlay.
     */
    public void remove(T graphic) {
        synchronized (mLock) {
            mGraphics.remove(graphic);
        }
        postInvalidate();
    }

    /**
     * Returns the first graphic, if any, that exists at the provided absolute screen coordinates.
     * These coordinates will be offset by the relative screen position of this view.
     * @return First graphic containing the point, or null if no text is detected.
     */
    public T getGraphicAtLocation(float rawX, float rawY) {
        synchronized (mLock) {
            // Get the position of this View so the raw location can be offset relative to the view.
            int[] location = new int[2];
            this.getLocationOnScreen(location);
            for (T graphic : mGraphics) {
                if (graphic.contains(rawX - location[0], rawY - location[1])) {
                    return graphic;
                }
            }
            return null;
        }
    }

    /**
     * Sets the camera attributes for size and facing direction, which informs how to transform
     * image coordinates later.
     */
    public void setCameraInfo(int previewWidth, int previewHeight, int facing) {
        synchronized (mLock) {
            mPreviewWidth = previewWidth;
            mPreviewHeight = previewHeight;
            mFacing = facing;
        }
        postInvalidate();
    }

    /**
     * Draws the overlay with its associated graphic objects.
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        synchronized (mLock) {
            if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) {
                mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
                mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
            }

            for (Graphic graphic : mGraphics) {
                graphic.draw(canvas);
            }
        }
    }
}