text:
using ::chromeos::CrosSettings;
using ::chromeos::system::TimezoneSettings;

namespace {

bool GetHttpProxyServer(const ProxyConfigDictionary& proxy_config_dict,
                        std::string* host,
                        int* port) {
  std::string proxy_rules_string;
  if (!proxy_config_dict.GetProxyServer(&proxy_rules_string))
    return false;

  net::ProxyConfig::ProxyRules proxy_rules;
  proxy_rules.ParseFromString(proxy_rules_string);

  const net::ProxyList* proxy_list = nullptr;
  if (proxy_rules.type == net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY) {
    proxy_list = &proxy_rules.single_proxies;
  } else if (proxy_rules.type ==
             net::ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME) {
    proxy_list = proxy_rules.MapUrlSchemeToProxyList(url::kHttpScheme);
  }
  if (!proxy_list || proxy_list->IsEmpty())
    return false;

  const net::ProxyServer& server = proxy_list->Get();
  *host = server.host_port_pair().host();
  *port = server.host_port_pair().port();
  return !host->empty() && *port;
}

}  // namespace

namespace arc {

// Listens to changes for select Chrome settings (prefs) that Android cares
// about and sends the new values to Android to keep the state in sync.
class ArcSettingsServiceImpl
    : public chromeos::system::TimezoneSettings::Observer,
      public device::BluetoothAdapter::Observer,
      public ArcAuthService::Observer {
 public:
  explicit ArcSettingsServiceImpl(ArcBridgeService* arc_bridge_service);
  ~ArcSettingsServiceImpl() override;

  // Called when a Chrome pref we have registered an observer for has changed.
  // Obtains the new pref value and sends it to Android.
  void OnPrefChanged(const std::string& pref_name) const;

  // TimezoneSettings::Observer:
  void TimezoneChanged(const icu::TimeZone& timezone) override;

  // BluetoothAdapter::Observer:
  void AdapterPoweredChanged(device::BluetoothAdapter* adapter,
                             bool powered) override;

  // ArcAuthService::Observer:
  void OnInitialStart() override;

 private:
  // Registers to observe changes for Chrome settings we care about.
  void StartObservingSettingsChanges();

  // Stops listening for Chrome settings changes.
  void StopObservingSettingsChanges();

  // Retrieves Chrome's state for the settings that need to be synced on each
  // Android boot and send it to Android.
  void SyncRuntimeSettings() const;
  // Send settings that need to be synced only on Android first start to
  // Android.
  void SyncInitialSettings() const;
  void SyncFontSize() const;
  void SyncLocale() const;
  void SyncProxySettings() const;
  void SyncReportingConsent() const;
  void SyncSpokenFeedbackEnabled() const;
  void SyncTimeZone() const;
  void SyncUse24HourClock() const;
  void SyncBackupEnabled() const;
  void SyncLocationServiceEnabled() const;

  void OnBluetoothAdapterInitialized(
      scoped_refptr<device::BluetoothAdapter> adapter);

  // Registers to listen to a particular perf.
  void AddPrefToObserve(const std::string& pref_name);

  // Returns the integer value of the pref.  pref_name must exist.
  int GetIntegerPref(const std::string& pref_name) const;

  // Sends boolean pref broadcast to the delegate.
  void SendBoolPrefSettingsBroadcast(const std::string& pref_name,
                                     const std::string& action) const;

  // Sends a broadcast to the delegate.
  void SendSettingsBroadcast(const std::string& action,
                             const base::DictionaryValue& extras) const;

  // Manages pref observation registration.
  PrefChangeRegistrar registrar_;

  std::unique_ptr<chromeos::CrosSettings::ObserverSubscription>
      reporting_consent_subscription_;
  ArcBridgeService* const arc_bridge_service_;

  scoped_refptr<device::BluetoothAdapter> bluetooth_adapter_;

  // WeakPtrFactory to use for callback for getting the bluetooth adapter.
  base::WeakPtrFactory<ArcSettingsServiceImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ArcSettingsServiceImpl);
};

ArcSettingsServiceImpl::ArcSettingsServiceImpl(
    ArcBridgeService* arc_bridge_service)
    : arc_bridge_service_(arc_bridge_service), weak_factory_(this) {
  StartObservingSettingsChanges();
  SyncRuntimeSettings();
  DCHECK(ArcAuthService::Get());
  ArcAuthService::Get()->AddObserver(this);
}

ArcSettingsServiceImpl::~ArcSettingsServiceImpl() {
  StopObservingSettingsChanges();

  ArcAuthService* arc_auth_service = ArcAuthService::Get();
  if (arc_auth_service)
    arc_auth_service->RemoveObserver(this);

  if (bluetooth_adapter_)
    bluetooth_adapter_->RemoveObserver(this);
}

void ArcSettingsServiceImpl::StartObservingSettingsChanges() {
  Profile* profile = ProfileManager::GetActiveUserProfile();
  registrar_.Init(profile->GetPrefs());

  AddPrefToObserve(prefs::kWebKitDefaultFixedFontSize);
  AddPrefToObserve(prefs::kWebKitDefaultFontSize);
  AddPrefToObserve(prefs::kWebKitMinimumFontSize);
  AddPrefToObserve(prefs::kAccessibilitySpokenFeedbackEnabled);
  AddPrefToObserve(prefs::kUse24HourClock);
  AddPrefToObserve(proxy_config::prefs::kProxy);
  AddPrefToObserve(prefs::kArcBackupRestoreEnabled);

  reporting_consent_subscription_ = CrosSettings::Get()->AddSettingsObserver(
      chromeos::kStatsReportingPref,
      base::Bind(&ArcSettingsServiceImpl::SyncReportingConsent,
                 base::Unretained(this)));

  TimezoneSettings::GetInstance()->AddObserver(this);

  if (device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable()) {
    device::BluetoothAdapterFactory::GetAdapter(
        base::Bind(&ArcSettingsServiceImpl::OnBluetoothAdapterInitialized,
                   weak_factory_.GetWeakPtr()));
  }
}

void ArcSettingsServiceImpl::OnBluetoothAdapterInitialized(
    scoped_refptr<device::BluetoothAdapter> adapter) {
  DCHECK(adapter);
  bluetooth_adapter_ = adapter;
  bluetooth_adapter_->AddObserver(this);

  AdapterPoweredChanged(adapter.get(), adapter->IsPowered());
}

void ArcSettingsServiceImpl::OnInitialStart() {
  SyncInitialSettings();
}

void ArcSettingsServiceImpl::SyncRuntimeSettings() const {
  SyncFontSize();
  SyncLocale();
  SyncProxySettings();
  SyncReportingConsent();
  SyncSpokenFeedbackEnabled();
  SyncTimeZone();
  SyncUse24HourClock();
}

void ArcSettingsServiceImpl::SyncInitialSettings() const {
  SyncBackupEnabled();
  SyncLocationServiceEnabled();
}

void ArcSettingsServiceImpl::StopObservingSettingsChanges() {
  registrar_.RemoveAll();
  reporting_consent_subscription_.reset();

  TimezoneSettings::GetInstance()->RemoveObserver(this);
}

void ArcSettingsServiceImpl::AddPrefToObserve(const std::string& pref_name) {
  registrar_.Add(pref_name, base::Bind(&ArcSettingsServiceImpl::OnPrefChanged,
                                       base::Unretained(this)));
}

void ArcSettingsServiceImpl::AdapterPoweredChanged(
    device::BluetoothAdapter* adapter,
    bool powered) {
  base::DictionaryValue extras;
  extras.SetBoolean("enable", powered);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_BLUETOOTH_STATE",
                        extras);
}

void ArcSettingsServiceImpl::OnPrefChanged(const std::string& pref_name) const {
  if (pref_name == prefs::kAccessibilitySpokenFeedbackEnabled) {
    SyncSpokenFeedbackEnabled();
  } else if (pref_name == prefs::kWebKitDefaultFixedFontSize ||
             pref_name == prefs::kWebKitDefaultFontSize ||
             pref_name == prefs::kWebKitMinimumFontSize) {
    SyncFontSize();
  } else if (pref_name == prefs::kUse24HourClock) {
    SyncUse24HourClock();
  } else if (pref_name == proxy_config::prefs::kProxy) {
    SyncProxySettings();
  } else {
    LOG(ERROR) << "Unknown pref changed.";
  }
}

void ArcSettingsServiceImpl::TimezoneChanged(const icu::TimeZone& timezone) {
  SyncTimeZone();
}

int ArcSettingsServiceImpl::GetIntegerPref(const std::string& pref_name) const {
  const PrefService::Preference* pref =
      registrar_.prefs()->FindPreference(pref_name);
  DCHECK(pref);
  int val = -1;
  bool value_exists = pref->GetValue()->GetAsInteger(&val);
  DCHECK(value_exists);
  return val;
}

void ArcSettingsServiceImpl::SyncFontSize() const {
  int default_size = GetIntegerPref(prefs::kWebKitDefaultFontSize);
  int default_fixed_size = GetIntegerPref(prefs::kWebKitDefaultFixedFontSize);
  int minimum_size = GetIntegerPref(prefs::kWebKitMinimumFontSize);

  double android_scale = ConvertFontSizeChromeToAndroid(
      default_size, default_fixed_size, minimum_size);

  base::DictionaryValue extras;
  extras.SetDouble("scale", android_scale);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_FONT_SCALE",
                        extras);
}

void ArcSettingsServiceImpl::SendBoolPrefSettingsBroadcast(
    const std::string& pref_name,
    const std::string& action) const {
  const PrefService::Preference* pref =
      registrar_.prefs()->FindPreference(pref_name);
  DCHECK(pref);
  bool enabled = false;
  bool value_exists = pref->GetValue()->GetAsBoolean(&enabled);
  DCHECK(value_exists);
  base::DictionaryValue extras;
  extras.SetBoolean("enabled", enabled);
  extras.SetBoolean("managed", !pref->IsUserModifiable());
  SendSettingsBroadcast(action, extras);
}

void ArcSettingsServiceImpl::SyncSpokenFeedbackEnabled() const {
  SendBoolPrefSettingsBroadcast(
      prefs::kAccessibilitySpokenFeedbackEnabled,
      "org.chromium.arc.intent_helper.SET_SPOKEN_FEEDBACK_ENABLED");
}

void ArcSettingsServiceImpl::SyncLocale() const {
  const PrefService::Preference* pref =
      registrar_.prefs()->FindPreference(prefs::kApplicationLocale);
  DCHECK(pref);
  std::string locale;
  bool value_exists = pref->GetValue()->GetAsString(&locale);
  DCHECK(value_exists);
  base::DictionaryValue extras;
  extras.SetString("locale", locale);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_LOCALE", extras);
}

void ArcSettingsServiceImpl::SyncReportingConsent() const {
  bool consent = false;
  CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref, &consent);
  base::DictionaryValue extras;
  extras.SetBoolean("reportingConsent", consent);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_REPORTING_CONSENT",
                        extras);
}

void ArcSettingsServiceImpl::SyncTimeZone() const {
  TimezoneSettings* timezone_settings = TimezoneSettings::GetInstance();
  base::string16 timezoneID = timezone_settings->GetCurrentTimezoneID();
  base::DictionaryValue extras;
  extras.SetString("olsonTimeZone", timezoneID);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_TIME_ZONE", extras);
}

void ArcSettingsServiceImpl::SyncUse24HourClock() const {
  const PrefService::Preference* pref =
      registrar_.prefs()->FindPreference(prefs::kUse24HourClock);
  DCHECK(pref);
  bool use24HourClock = false;
  bool value_exists = pref->GetValue()->GetAsBoolean(&use24HourClock);
  DCHECK(value_exists);
  base::DictionaryValue extras;
  extras.SetBoolean("use24HourClock", use24HourClock);
  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_USE_24_HOUR_CLOCK",
                        extras);
}

void ArcSettingsServiceImpl::SyncProxySettings() const {
  const PrefService::Preference* const pref =
      registrar_.prefs()->FindPreference(proxy_config::prefs::kProxy);
  const base::DictionaryValue* proxy_config_value;
  bool value_exists = pref->GetValue()->GetAsDictionary(&proxy_config_value);
  DCHECK(value_exists);

  ProxyConfigDictionary proxy_config_dict(proxy_config_value);

  ProxyPrefs::ProxyMode mode;
  if (!proxy_config_dict.GetMode(&mode))
    mode = ProxyPrefs::MODE_DIRECT;

  base::DictionaryValue extras;
  extras.SetString("mode", ProxyPrefs::ProxyModeToString(mode));

  switch (mode) {
    case ProxyPrefs::MODE_DIRECT:
      break;
    case ProxyPrefs::MODE_SYSTEM:
      VLOG(1) << "The system mode is not translated.";
      return;
    case ProxyPrefs::MODE_AUTO_DETECT:
      extras.SetString("pacUrl", "http://wpad/wpad.dat");
      break;
    case ProxyPrefs::MODE_PAC_SCRIPT: {
      std::string pac_url;
      if (!proxy_config_dict.GetPacUrl(&pac_url)) {
        LOG(ERROR) << "No pac URL for pac_script proxy mode.";
        return;
      }
      extras.SetString("pacUrl", pac_url);
      break;
    }
    case ProxyPrefs::MODE_FIXED_SERVERS: {
      std::string host;
      int port = 0;
      if (!GetHttpProxyServer(proxy_config_dict, &host, &port)) {
        LOG(ERROR) << "No Http proxy server is sent.";
        return;
      }
      extras.SetString("host", host);
      extras.SetInteger("port", port);

      std::string bypass_list;
      if (proxy_config_dict.GetBypassList(&bypass_list) &&
          !bypass_list.empty()) {
        extras.SetString("bypassList", bypass_list);
      }
      break;
    }
    default:
      LOG(ERROR) << "Incorrect proxy mode.";
      return;
  }

  SendSettingsBroadcast("org.chromium.arc.intent_helper.SET_PROXY", extras);
}

void ArcSettingsServiceImpl::SyncBackupEnabled() const {
  SendBoolPrefSettingsBroadcast(
      prefs::kArcBackupRestoreEnabled,
      "org.chromium.arc.intent_helper.SET_BACKUP_ENABLED");
}

void ArcSettingsServiceImpl::SyncLocationServiceEnabled() const {
  SendBoolPrefSettingsBroadcast(
      prefs::kArcLocationServiceEnabled,
      "org.chromium.arc.intent_helper.SET_LOCATION_SERVICE_ENABLED");
}

void ArcSettingsServiceImpl::SendSettingsBroadcast(
    const std::string& action,
    const base::DictionaryValue& extras) const {
  if (!arc_bridge_service_->intent_helper()->instance()) {
    LOG(ERROR) << "IntentHelper instance is not ready.";
    return;
  }

  std::string extras_json;
  bool write_success = base::JSONWriter::Write(extras, &extras_json);
  DCHECK(write_success);

  if (arc_bridge_service_->intent_helper()->version() >= 1) {
    arc_bridge_service_->intent_helper()->instance()->SendBroadcast(
        action, "org.chromium.arc.intent_helper",
        "org.chromium.arc.intent_helper.SettingsReceiver", extras_json);
  }
}

ArcSettingsService::ArcSettingsService(ArcBridgeService* bridge_service)
    : ArcService(bridge_service) {
  arc_bridge_service()->intent_helper()->AddObserver(this);
}

ArcSettingsService::~ArcSettingsService() {
  arc_bridge_service()->intent_helper()->RemoveObserver(this);
}

void ArcSettingsService::OnInstanceReady() {
  impl_.reset(new ArcSettingsServiceImpl(arc_bridge_service()));
}

void ArcSettingsService::OnInstanceClosed() {
  impl_.reset();
}

}  // namespace arc


text:
package org.wso2.carbon.event.input.adapter.core.internal.ds;

import com.hazelcast.core.HazelcastInstance;
import org.wso2.carbon.event.input.adapter.core.internal.config.AdapterConfigs;
import org.wso2.carbon.event.input.adapter.core.internal.CarbonInputEventAdapterService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.ConfigurationContextService;

public class InputEventAdapterServiceValueHolder {

    private static CarbonInputEventAdapterService carbonInputEventAdapterService;
    private static RegistryService registryService;
    private static AdapterConfigs globalAdapterConfigs;
    private static ConfigurationContextService configurationContextService;
    private static HazelcastInstance hazelcastInstance;

    private InputEventAdapterServiceValueHolder() {

    }

    public static CarbonInputEventAdapterService getCarbonInputEventAdapterService() {
        return carbonInputEventAdapterService;
    }

    public static void setCarbonInputEventAdapterService(CarbonInputEventAdapterService carbonInputEventAdapterService) {
        InputEventAdapterServiceValueHolder.carbonInputEventAdapterService = carbonInputEventAdapterService;
    }

    public static RegistryService getRegistryService() {
        return registryService;
    }

    public static void setRegistryService(RegistryService registryService) {
        InputEventAdapterServiceValueHolder.registryService = registryService;
    }

    public static void setGlobalAdapterConfigs(AdapterConfigs globalAdapterConfigs) {
        InputEventAdapterServiceValueHolder.globalAdapterConfigs = globalAdapterConfigs;
    }

    public static AdapterConfigs getGlobalAdapterConfigs() {
        return globalAdapterConfigs;
    }

    public static ConfigurationContextService getConfigurationContextService() {
        return configurationContextService;
    }

    public static void setConfigurationContextService(ConfigurationContextService configurationContextService) {
        InputEventAdapterServiceValueHolder.configurationContextService = configurationContextService;
    }

    public static void registerHazelcastInstance(HazelcastInstance hazelcastInstance) {
        InputEventAdapterServiceValueHolder.hazelcastInstance = hazelcastInstance;
    }

    public static HazelcastInstance getHazelcastInstance() {
        return hazelcastInstance;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.nd4j.linalg.slicing;

import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;

import static org.junit.Assert.assertEquals;

/**
 * @author Adam Gibson
 */
@RunWith(Parameterized.class)
public class SlicingTests extends BaseNd4jTest {

    public SlicingTests(Nd4jBackend backend) {
        super(backend);
    }

    @Test
    public void testSlices() {
        INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24, DataType.DOUBLE).data(), new int[] {4, 3, 2});
        for (int i = 0; i < arr.slices(); i++) {
            INDArray slice = arr.slice(i).slice(1);
            val slices = slice.slices();
            assertEquals(2, slices);
        }

    }

    @Test
    public void testSlice() {
        INDArray arr = Nd4j.linspace(1, 24, 24, DataType.DOUBLE).reshape(4, 3, 2);
        INDArray assertion = Nd4j.create(new double[][] {{1, 13}, {5, 17}, {9, 21}});

        INDArray firstSlice = arr.slice(0);
        INDArray slice1Assertion = Nd4j.create(new double[][] {{2, 14}, {6, 18}, {10, 22},

        });

        INDArray secondSlice = arr.slice(1);
        assertEquals(assertion, firstSlice);
        assertEquals(slice1Assertion, secondSlice);

    }

    @Override
    public char ordering() {
        return 'f';
    }
}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Wuwei Lin
 */

#include <shogun/lib/exception/InvalidStateException.h>
#include <shogun/machine/Pipeline.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace shogun
{
	CPipelineBuilder::~CPipelineBuilder()
	{
		for (auto&& stage : m_stages)
		{
			visit([](auto&& object) { SG_UNREF(object) }, stage.second);
		}
	}

	CPipelineBuilder* CPipelineBuilder::over(CTransformer* transformer)
	{
		return over(transformer->get_name(), transformer);
	}

	CPipelineBuilder*
	CPipelineBuilder::over(const std::string& name, CTransformer* transformer)
	{
		REQUIRE_E(
		    m_stages.empty() ||
		        holds_alternative<CTransformer*>(m_stages.back().second),
		    std::invalid_argument,
		    "Transformers can not be placed after machines. Last element is "
		    "%s\n",
		    m_stages.back().first.c_str());

		SG_REF(transformer);
		m_stages.emplace_back(name, transformer);

		return this;
	}

	CPipeline* CPipelineBuilder::then(CMachine* machine)
	{
		return then(machine->get_name(), machine);
	}

	CPipeline*
	CPipelineBuilder::then(const std::string& name, CMachine* machine)
	{
		REQUIRE_E(
		    m_stages.empty() ||
		        holds_alternative<CTransformer*>(m_stages.back().second),
		    std::invalid_argument,
		    "Multiple machines are added to pipeline. Last element is %s\n",
		    m_stages.back().first.c_str());

		SG_REF(machine);
		m_stages.emplace_back(name, machine);

		return build();
	}

	CPipelineBuilder*
	CPipelineBuilder::add_stages(std::vector<CSGObject*> stages)
	{
		for (auto stage : stages)
		{
			auto transformer = dynamic_cast<CTransformer*>(stage);
			if (transformer)
			{
				over(transformer);
			}
			else
			{
				auto machine = dynamic_cast<CMachine*>(stage);
				REQUIRE_E(
				    machine, std::invalid_argument, "Stage must be either a "
				                                    "transformer or a machine. "
				                                    "Provided %s\n",
				    stage->get_name());
				SG_REF(machine);
				m_stages.emplace_back(machine->get_name(), machine);
			}
		}
		return this;
	}

	CPipeline* CPipelineBuilder::build()
	{
		check_pipeline();

		auto pipeline = new CPipeline();
		pipeline->m_stages = std::move(m_stages);
		m_stages.clear();

		return pipeline;
	}

	void CPipelineBuilder::check_pipeline() const
	{
		REQUIRE_E(
		    !m_stages.empty(), InvalidStateException, "Pipeline is empty");
		REQUIRE_E(
		    holds_alternative<CMachine*>(m_stages.back().second),
		    InvalidStateException, "Pipline cannot be trained without an "
		                           "added machine. Last element "
		                           "is %s.\n",
		    m_stages.back().first.c_str());
	}

	CPipeline::CPipeline() : CMachine()
	{
	}

	CPipeline::~CPipeline()
	{
		for (auto&& stage : m_stages)
		{
			visit([](auto&& object) { SG_UNREF(object) }, stage.second);
		}
	}

	bool CPipeline::train_machine(CFeatures* data)
	{
		if (train_require_labels())
		{
			REQUIRE(m_labels, "No labels given.\n");
		}

		for (auto&& stage : m_stages)
		{
			if (holds_alternative<CTransformer*>(stage.second))
			{
				auto transformer = shogun::get<CTransformer*>(stage.second);
				transformer->train_require_labels()
				    ? transformer->fit(data, m_labels)
				    : transformer->fit(data);

				data = transformer->transform(data);
			}
			else
			{
				auto machine = shogun::get<CMachine*>(stage.second);
				if (machine->train_require_labels())
					machine->set_labels(m_labels);
				machine->train(data);
			}
		}
		return true;
	}

	CLabels* CPipeline::apply(CFeatures* data)
	{
		for (auto&& stage : m_stages)
		{
			if (holds_alternative<CTransformer*>(stage.second))
			{
				auto transformer = shogun::get<CTransformer*>(stage.second);
				data = transformer->transform(data);
			}
			else
			{
				auto machine = shogun::get<CMachine*>(stage.second);
				return machine->apply(data);
			}
		}

		return nullptr; // unreachable
	}

	bool CPipeline::train_require_labels() const
	{
		bool require_labels = false;

		for (auto&& stage : m_stages)
		{
			visit(
			    [&require_labels](auto&& fittable) {
				    require_labels = fittable->train_require_labels();
				},
			    stage.second);

			if (require_labels)
				return require_labels;
		}

		return require_labels;
	}

	std::string CPipeline::to_string() const
	{
		std::stringstream ss;

		for (auto i : range(m_stages.size()))
		{
			ss << '[' << i << "]: " << m_stages[i].first << std::endl;
		}

		return ss.str();
	}

	CTransformer* CPipeline::get_transformer(const std::string& name) const
	{
		for (auto&& stage : m_stages)
		{
			if (stage.first == name &&
			    holds_alternative<CTransformer*>(stage.second))
				return shogun::get<CTransformer*>(stage.second);
		}

		SG_THROW(
		    std::invalid_argument, "Transformer with name %s not found.\n",
		    name.c_str());

		return nullptr;
	}

	CMachine* CPipeline::get_machine() const
	{
		return shogun::get<CMachine*>(m_stages.back().second);
	}

	void CPipeline::set_store_model_features(bool store_model)
	{
		get_machine()->set_store_model_features(store_model);
	}

	void CPipeline::store_model_features()
	{
		get_machine()->store_model_features();
	}

	CSGObject* CPipeline::clone()
	{
		auto result = CMachine::clone()->as<CPipeline>();
		for (auto&& stage : m_stages)
		{
			visit(
			    [&](auto object) {
				    result->m_stages.emplace_back(
				        stage.first,
				        object->clone()
				            ->template as<typename std::remove_pointer<decltype(
				                object)>::type>());
				},
			    stage.second);
		}
		return result;
	}

	EProblemType CPipeline::get_machine_problem_type() const
	{
		return get_machine()->get_machine_problem_type();
	}
}


text:
#include "RandomWalkerMotion.hpp"
#include "PoseRandomWalker.hpp"

namespace loc{

    template<class Ts, class Tin>
    Ts RandomWalkerMotion<Ts, Tin>::predict(Ts state, Tin input){
        auto& mRandGen = RandomWalker<Ts, Tin>::mRandGen;
        const auto& mPedometer = mRWMotionProperty->pedometer();
        const auto& mOrientationMeter = mRWMotionProperty->orientationMeter();

        long t_pre = input.previousTimestamp();
        long t_cur = input.timestamp();
        double dt = (t_cur-t_pre)*input.timeUnit();

        if(dt < 0){
            std::cerr << "Inconsistent timestamp found in RandomWalkerMotion. Location was not updated." << std::endl;
            return state;
        }

        if(mPedometer && mOrientationMeter){
            double movLevel = movingLevel();
            double x = state.x();
            double y = state.y();
            double z = state.z();
            double floor = state.floor();

            if(dt<input.timeUnit()){
                throw std::runtime_error("Time increment is too small in RandomWalkerMotion.");
            }

            // Compute velocity rate to reduce velocity when turning
            if(mRWMotionProperty->usesAngularVelocityLimit()){
                double yaw =  Pose::normalizeOrientaion(mOrientationMeter->getYaw());
                if(!wasYawUpdated){
                    currentTimestamp = t_cur;
                    currentYaw = yaw;
                    wasYawUpdated = true;
                }
                if(currentTimestamp!=t_cur){
                    currentTimestamp = t_cur;
                    double previousYaw = Pose::normalizeOrientaion(currentYaw);
                    currentYaw = Pose::normalizeOrientaion(yaw);
                    double oriDiff = Pose::computeOrientationDifference(previousYaw, currentYaw);
                    double angularVelocity = oriDiff/dt;
                    double angularVelocityLimit = mRWMotionProperty->angularVelocityLimit();
                    turningVelocityRate = std::sqrt(1.0 - std::min(1.0, std::pow(angularVelocity/angularVelocityLimit,2)));
                }
            }else{
                turningVelocityRate = 1.0;
            }

            double sigma;
            if(movLevel > 0){
                sigma = mRWMotionProperty->sigmaMove;
            }else{
                sigma = mRWMotionProperty->sigmaStop;
            }

            // Scale sigma by time increment
            sigma = sigma * std::sqrt(1.0/dt);

            // Multiply sigma by velocity rate
            sigma = sigma * velocityRate();

            // Multyply sigma by turning velocity rate
            sigma = sigma * turningVelocityRate;

            double nx = mRandGen->nextGaussian();
            double ny = mRandGen->nextGaussian();
            double theta = std::atan2(ny, nx);

            double vx = sigma * nx;
            double vy = sigma * ny;
            double v = std::sqrt(vx*vx + vy*vy);

            x += vx*dt;
            y += vy*dt;

            Ts stateNew(state);
            stateNew.x(x).y(y).z(z).floor(floor);
            stateNew.velocity(v).normalVelocity(v).orientation(theta);

            return stateNew;
        }else{
            if(!mPedometer){
                BOOST_THROW_EXCEPTION(LocException("Pedometer is not set to WeakPoseRandomWalker."));
            }
            else{
                BOOST_THROW_EXCEPTION(LocException("OrientationMeter is not set to WeakPoseRandomWalker."));
            }
        }
    }

    template<class Ts, class Tin>
    RandomWalkerMotion<Ts, Tin>& RandomWalkerMotion<Ts, Tin>::setProperty(RandomWalkerMotionProperty::Ptr property){
        mRWMotionProperty = property;
        return *this;
    }

    template<class Ts, class Tin>
    double RandomWalkerMotion<Ts, Tin>::movingLevel(){
        if(isUnderControll){
            return mMovement;
        }else{
            return mRWMotionProperty->pedometer()->getNSteps();
        }
    }

    // Explicit instantiation
    template class RandomWalkerMotion<State, RandomWalkerInput>;
}


text:
// Declarations for a class that can track operations applied to its objects.
// This header is an optional part of the test harness.

#ifndef tbb_test_harness_state_trackable_H
#define tbb_test_harness_state_trackable_H

#include <cstddef>
#include <map>
#include <tbb/atomic.h>

#include "harness_assert.h"

namespace Harness{
    struct StateTrackableBase {
        enum StateValue {
            ZeroInitialized     = 0,
            DefaultInitialized  = 0xDEFAUL,
            DirectInitialized   = 0xD1111,
            CopyInitialized     = 0xC0314,
            MoveInitialized     = 0xAAAAA,
            Assigned            = 0x11AED,
            MoveAssigned        = 0x22AED,
            MovedFrom           = 0xFFFFF,
            Destroyed           = 0xDEADF00,
            Unspecified         = 0xEEEEE
        };

        class State {
        public:
            State() __TBB_NOEXCEPT(true) : state(Unspecified) {
                assignNewState(Unspecified);
            }
            State(const State& s) : state(Unspecified) {
                assignNewState(s.state);
            }
            State(StateValue s) __TBB_NOEXCEPT(true) : state(Unspecified) {
                assignNewState(s);
            };
            State& operator=(StateValue s) __TBB_NOEXCEPT(true) {
                assignNewState(s);
                return *this;
            }
            operator StateValue() const __TBB_NOEXCEPT(true) { return state; }
        private:
            void assignNewState(StateValue s) __TBB_NOEXCEPT(true);
            StateValue state;
        };
    };

    struct StateTrackableCounters {
        static void reset() {
            counters[StateTrackableBase::ZeroInitialized] = counters[StateTrackableBase::DefaultInitialized] =
                counters[StateTrackableBase::DirectInitialized] = counters[StateTrackableBase::CopyInitialized] =
                counters[StateTrackableBase::MoveInitialized] = counters[StateTrackableBase::Assigned] =
                counters[StateTrackableBase::MoveAssigned] = counters[StateTrackableBase::MovedFrom] =
                counters[StateTrackableBase::Destroyed] = counters[StateTrackableBase::Unspecified] = 0;
        }

        static bool initialize() {
            reset();
            return true;
        }

        typedef std::map<StateTrackableBase::StateValue, tbb::atomic<std::size_t> > counters_t;
        static counters_t counters;
    };

    StateTrackableCounters::counters_t StateTrackableCounters::counters;
    static const bool stateTrackableBaseStateInitialized = StateTrackableCounters::initialize();

    void StateTrackableBase::State::assignNewState(StateValue s) __TBB_NOEXCEPT(true) {
        ASSERT(stateTrackableBaseStateInitialized, "State trackable counters are not initialized");
        ASSERT(s == StateTrackableBase::Unspecified ||
            StateTrackableCounters::counters.find(s) != StateTrackableCounters::counters.end(), "The current state value is unknown");
        ASSERT(state == StateTrackableBase::Unspecified ||
            StateTrackableCounters::counters.find(state) != StateTrackableCounters::counters.end(), "The new state value is unknown");
        state = s;
        ++StateTrackableCounters::counters[state];
    }

    template<bool allow_zero_initialized_state = false>
    struct StateTrackable: StateTrackableBase {
        static const bool is_zero_initialized_state_allowed = allow_zero_initialized_state;
        State state;

        bool is_valid() const {
            return state == DefaultInitialized || state == DirectInitialized || state == CopyInitialized
                || state == MoveInitialized || state == Assigned || state == MoveAssigned || state == MovedFrom
                || (allow_zero_initialized_state && state == ZeroInitialized)
                ;
        }

        StateTrackable (intptr_t)       __TBB_NOEXCEPT(true) : state (DirectInitialized){}
        StateTrackable ()               __TBB_NOEXCEPT(true) : state (DefaultInitialized){}
        StateTrackable (const StateTrackable & src) __TBB_NOEXCEPT(true) {
            ASSERT( src.is_valid(), "bad source for copy" );
            state = CopyInitialized;
        }
    #if __TBB_CPP11_RVALUE_REF_PRESENT
        StateTrackable (StateTrackable && src) __TBB_NOEXCEPT(true) {
            ASSERT( src.is_valid(), "bad source for move?" );
            state = MoveInitialized;
            src.state = MovedFrom;
        }
        StateTrackable & operator=(StateTrackable && src) __TBB_NOEXCEPT(true) {
            ASSERT( src.is_valid(), "bad source for assignment" );
            ASSERT( is_valid(), "assigning to invalid instance?" );

            src.state = MovedFrom;
            state = MoveAssigned;
            return *this;
        }
    #endif
        StateTrackable & operator=(const StateTrackable & src) __TBB_NOEXCEPT(true) {
            ASSERT( src.is_valid(), "bad source for assignment?" );
            ASSERT( is_valid(), "assigning to invalid instance?" );

            state = Assigned;
            return *this;
        }
        ~StateTrackable () __TBB_NOEXCEPT(true) {
            ASSERT( is_valid(), "Calling destructor on invalid instance? (twice destructor call?)" );
            state = Destroyed;
        }
    };
} // Harness
#endif // tbb_test_harness_state_trackable_H


text:
ActiveRecord::Schema.define(:version => 2) do

  create_table "reflex_connections", :force => true do |t|
    t.string   "provider",          :null => false
    t.string   "authorizable_type", :null => false
    t.integer  "authorizable_id",   :null => false
    t.string   "uuid",              :null => false
    t.datetime "created_at",        :null => false
    t.datetime "updated_at",        :null => false
  end

  add_index "reflex_connections", ["authorizable_type", "authorizable_id"], :name => "index_reflex_connections_on_authorizable_type_and_authorizable_id", :unique => true

  create_table "users", :force => true do |t|
    t.string   "name",              :null => false
    t.string   "login",             :null => true
    t.string   "crypted_password",  :null => true
    t.string   "password_salt",     :null => true
    t.string   "persistence_token", :null => false
    t.datetime "created_at",        :null => false
    t.datetime "updated_at",        :null => false
  end

end


text:
package log

import (
	"context"
	"io"
	"strings"
	"sync"
)

// Flags define which text to prefix to each log entry in a Writer.
type Flags uint

// Bits or'ed together to control what's printed.
// There is no control over the order they appear (the order listed
// here) or the format they present (as described in the comments).
// The prefix is followed by a colon only when ShowFile, ShortFile, or ShowLevel
// is specified.
//
// For example, flags ShowDate | ShowTime produce,
//
//	2009/01/23 01:23:23 message
//
// while flags ShowDate | ShowTime | Microseconds | ShowFile produce,
//
//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
const (
	ShowDate     Flags = 1 << iota // the date in the local time zone: 2009/01/23
	ShowTime                       // the time in the local time zone: 01:23:23
	Microseconds                   // microsecond resolution: 01:23:23.123123.  assumes ShowTime.
	ShowFile                       // full file name and line number: /a/b/c/d.go:23
	ShortFile                      // final file name element and line number: d.go:23. overrides ShowFile
	UTC                            // if ShowDate or ShowTime is set, use UTC rather than the local time zone
	ShowLevel                      // level name, all caps. INFO

	StdFlags Flags = ShowDate | ShowTime | ShowLevel // initial values for the standard logger
)

const allFlags = ShowDate | ShowTime | Microseconds | ShowFile | ShortFile | UTC | ShowLevel

// String formats the flags as |-separated constant names,
// like "ShowDate|ShowFile|ShowLevel".
func (f Flags) String() string {
	if f == 0 {
		return "0"
	}
	buf := new(strings.Builder)
	if f&ShowDate != 0 {
		appendOredFlag(buf, "ShowDate")
	}
	if f&ShowTime != 0 {
		appendOredFlag(buf, "ShowTime")
	}
	if f&Microseconds != 0 {
		appendOredFlag(buf, "Microseconds")
	}
	if f&ShowFile != 0 {
		appendOredFlag(buf, "ShowFile")
	}
	if f&ShortFile != 0 {
		appendOredFlag(buf, "ShortFile")
	}
	if f&UTC != 0 {
		appendOredFlag(buf, "UTC")
	}
	if f&ShowLevel != 0 {
		appendOredFlag(buf, "ShowLevel")
	}
	if others := f &^ allFlags; others != 0 {
		if buf.Len() > 0 {
			buf.WriteByte('|')
		}
		buf.Write(itoa(nil, int(others), -1))
	}
	return buf.String()
}

func appendOredFlag(sb *strings.Builder, name string) {
	if sb.Len() > 0 {
		sb.WriteByte('|')
	}
	sb.WriteString(name)
}

// A Writer implements Logger by writing lines of output to an io.Writer.
// Each logging operation makes a single call to the Writer's Write method.
// A Logger can be used simultaneously from multiple goroutines; it
// guarantees to serialize access to the Writer.
type Writer struct {
	errFunc func(context.Context, error) // called if out returns error
	prefix  string                       // prefix to write at beginning of each line
	flag    Flags                        // properties

	mu  sync.Mutex // ensures atomic writes; protects the following fields
	out io.Writer  // destination for output
	buf []byte     // for accumulating text to write
}

// New creates a new Writer. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
// If not nil, the errFunc argument is called when w.Write returns an error.
// errFunc must be safe to call from multiple goroutines and should be fast, as it blocks Log returning.
func New(w io.Writer, prefix string, flag Flags, errFunc func(context.Context, error)) *Writer {
	return &Writer{out: w, prefix: prefix, flag: flag, errFunc: errFunc}
}

// Log writes the output for a logging entry. A newline is appended if
// the last character of s is not already a newline.
func (w *Writer) Log(ctx context.Context, ent Entry) {
	defer w.mu.Unlock()
	w.mu.Lock()
	w.buf = append(w.buf[:0], w.prefix...)
	w.buf = ent.Append(w.buf, w.flag)
	w.buf = append(w.buf, '\n')
	_, err := w.out.Write(w.buf)
	if err != nil && w.errFunc != nil {
		w.errFunc(ctx, err)
	}
}

// LogEnabled always returns true.
func (w *Writer) LogEnabled(Entry) bool { return true }


text:
package mongodb

import (
	"context"

	"github.com/mainflux/mainflux/errors"
	"github.com/mainflux/mainflux/readers"
	"github.com/mainflux/mainflux/transformers/senml"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const collection = "mainflux"

var errReadMessages = errors.New("faled to read messages from mongodb database")

var _ readers.MessageRepository = (*mongoRepository)(nil)

type mongoRepository struct {
	db *mongo.Database
}

// Message struct is used as a MongoDB representation of Mainflux message.
type message struct {
	Channel     string   `bson:"channel,omitempty"`
	Subtopic    string   `bson:"subtopic,omitempty"`
	Publisher   string   `bson:"publisher,omitempty"`
	Protocol    string   `bson:"protocol,omitempty"`
	Name        string   `bson:"name,omitempty"`
	Unit        string   `bson:"unit,omitempty"`
	Value       *float64 `bson:"value,omitempty"`
	StringValue *string  `bson:"stringValue,omitempty"`
	BoolValue   *bool    `bson:"boolValue,omitempty"`
	DataValue   *string  `bson:"dataValue,omitempty"`
	Sum         *float64 `bson:"sum,omitempty"`
	Time        float64  `bson:"time,omitempty"`
	UpdateTime  float64  `bson:"updateTime,omitempty"`
}

// New returns new MongoDB reader.
func New(db *mongo.Database) readers.MessageRepository {
	return mongoRepository{
		db: db,
	}
}

func (repo mongoRepository) ReadAll(chanID string, offset, limit uint64, query map[string]string) (readers.MessagesPage, error) {
	col := repo.db.Collection(collection)
	sortMap := map[string]interface{}{
		"time": -1,
	}

	filter := fmtCondition(chanID, query)
	cursor, err := col.Find(context.Background(), filter, options.Find().SetSort(sortMap).SetLimit(int64(limit)).SetSkip(int64(offset)))
	if err != nil {
		return readers.MessagesPage{}, errors.Wrap(errReadMessages, err)
	}
	defer cursor.Close(context.Background())

	messages := []senml.Message{}
	for cursor.Next(context.Background()) {
		var m message
		if err := cursor.Decode(&m); err != nil {
			return readers.MessagesPage{}, errors.Wrap(errReadMessages, err)
		}

		msg := senml.Message{
			Channel:    m.Channel,
			Subtopic:   m.Subtopic,
			Publisher:  m.Publisher,
			Protocol:   m.Protocol,
			Name:       m.Name,
			Unit:       m.Unit,
			Time:       m.Time,
			UpdateTime: m.UpdateTime,
			Sum:        m.Sum,
		}

		switch {
		case m.Value != nil:
			msg.Value = m.Value
		case m.StringValue != nil:
			msg.StringValue = m.StringValue
		case m.DataValue != nil:
			msg.DataValue = m.DataValue
		case m.BoolValue != nil:
			msg.BoolValue = m.BoolValue
		}

		messages = append(messages, msg)
	}

	total, err := col.CountDocuments(context.Background(), filter)
	if err != nil {
		return readers.MessagesPage{}, errors.Wrap(errReadMessages, err)
	}
	if total < 0 {
		return readers.MessagesPage{}, nil
	}

	return readers.MessagesPage{
		Total:    uint64(total),
		Offset:   offset,
		Limit:    limit,
		Messages: messages,
	}, nil
}

func fmtCondition(chanID string, query map[string]string) *bson.D {
	filter := bson.D{
		bson.E{
			Key:   "channel",
			Value: chanID,
		},
	}
	for name, value := range query {
		switch name {
		case
			"channel",
			"subtopic",
			"publisher",
			"name",
			"protocol":
			filter = append(filter, bson.E{Key: name, Value: value})
		}
	}

	return &filter
}


text:
package com.ea.orbit.actors.streams;

import com.ea.orbit.actors.runtime.ActorRuntime;
import com.ea.orbit.actors.runtime.Invocation;
import com.ea.orbit.actors.server.ServerPeer;
import com.ea.orbit.actors.transactions.IdUtils;
import com.ea.orbit.concurrent.Task;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.ea.orbit.async.Await.await;

public class ClientStreamProxy
{
    private Map<String, StreamSubscription> observerMap = new LinkedHashMap<>();
    ActorRuntime runtime;
    ServerPeer peer;

    static class StreamSubscription
    {
        String provider;
        Class dataClass;
        String streamId;
        boolean valid;
        Task<StreamSubscriptionHandle> handle;
    }

    @SuppressWarnings("unchecked")
    public Task<String> subscribe(String provider, Class dataClass, String streamId)
    {
        String handle = IdUtils.urlSafeString(128);
        StreamSubscription subscription = new StreamSubscription();
        subscription.provider = provider;
        subscription.dataClass = dataClass;
        subscription.streamId = streamId;
        subscription.handle = runtime.getStream(provider, dataClass, streamId).subscribe(new AsyncObserver()
        {
            @Override
            public Task<Void> onNext(final Object data, final StreamSequenceToken sequenceToken)
            {
                if (subscription.valid && peer.getPipeline().isActive())
                {
                    return peer.getPipeline().write(new Invocation());
                }
                return Task.done();
            }
        }, null);
        observerMap.put(handle, subscription);
        await(subscription.handle);
        return Task.fromValue(handle);
    }

    @SuppressWarnings("unchecked")
    public Task<Void> unsubscribe(String handle)
    {
        StreamSubscription subscription = observerMap.remove(handle);
        // no more messages
        if (subscription != null && subscription.valid)
        {
            subscription.valid = false;
            await(subscription.handle);
            await(runtime.getStream(subscription.provider, subscription.dataClass, subscription.streamId)
                    .unsubscribe(subscription.handle.join()));
            observerMap.remove(handle);
        }
        return Task.done();
    }

}


text:
from __future__ import absolute_import
from __future__ import unicode_literals

import io
import os.path
import re
import sys

import mock
import pytest

from pre_commit import error_handler
from pre_commit import five
from pre_commit.errors import FatalError
from pre_commit.util import cmd_output

@pytest.yield_fixture
def mocked_log_and_exit():
    with mock.patch.object(error_handler, '_log_and_exit') as log_and_exit:
        yield log_and_exit

def test_error_handler_no_exception(mocked_log_and_exit):
    with error_handler.error_handler():
        pass
    assert mocked_log_and_exit.call_count == 0

def test_error_handler_fatal_error(mocked_log_and_exit):
    exc = FatalError('just a test')
    with error_handler.error_handler():
        raise exc

    mocked_log_and_exit.assert_called_once_with(
        'An error has occurred',
        exc,
        # Tested below
        mock.ANY,
    )

    assert re.match(
        r'Traceback \(most recent call last\):\n'
        r'  File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
        r'    yield\n'
        r'  File ".+tests.error_handler_test.py", line \d+, '
        r'in test_error_handler_fatal_error\n'
        r'    raise exc\n'
        r'(pre_commit\.errors\.)?FatalError: just a test\n',
        mocked_log_and_exit.call_args[0][2],
    )

def test_error_handler_uncaught_error(mocked_log_and_exit):
    exc = ValueError('another test')
    with error_handler.error_handler():
        raise exc

    mocked_log_and_exit.assert_called_once_with(
        'An unexpected error has occurred',
        exc,
        # Tested below
        mock.ANY,
    )
    assert re.match(
        r'Traceback \(most recent call last\):\n'
        r'  File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
        r'    yield\n'
        r'  File ".+tests.error_handler_test.py", line \d+, '
        r'in test_error_handler_uncaught_error\n'
        r'    raise exc\n'
        r'ValueError: another test\n',
        mocked_log_and_exit.call_args[0][2],
    )

def test_log_and_exit(mock_out_store_directory):
    mocked_write = mock.Mock()
    with pytest.raises(error_handler.PreCommitSystemExit):
        error_handler._log_and_exit(
            'msg', FatalError('hai'), "I'm a stacktrace",
            write_fn=mocked_write,
        )

    printed = ''.join(
        five.to_text(call[0][0]) for call in mocked_write.call_args_list
    )
    assert printed == (
        'msg: FatalError: hai\n'
        'Check the log at ~/.pre-commit/pre-commit.log\n'
    )

    log_file = os.path.join(mock_out_store_directory, 'pre-commit.log')
    assert os.path.exists(log_file)
    contents = io.open(log_file).read()
    assert contents == (
        'msg: FatalError: hai\n'
        "I'm a stacktrace\n"
    )

def test_error_handler_non_ascii_exception(mock_out_store_directory):
    with pytest.raises(error_handler.PreCommitSystemExit):
        with error_handler.error_handler():
            raise ValueError('☃')

def test_error_handler_no_tty(tempdir_factory):
    output = cmd_output(
        sys.executable, '-c',
        'from __future__ import unicode_literals\n'
        'from pre_commit.error_handler import error_handler\n'
        'with error_handler():\n'
        '    raise ValueError("\\u2603")\n',
        env=dict(os.environ, PRE_COMMIT_HOME=tempdir_factory.get()),
        retcode=1,
    )
    assert output[1].replace('\r', '') == (
        'An unexpected error has occurred: ValueError: ☃\n'
        'Check the log at ~/.pre-commit/pre-commit.log\n'
    )


text:
// Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/OmniKassa).
// Licensed under the MIT License.

#if NETSTANDARD1_3

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace OmniKassa
{
    internal static class HttpClientExtensions
    {
        public static async Task<byte[]> PostData(this HttpClient self, Uri uri, IPaymentPostData postData)
        {
            FormUrlEncodedContent content = ConvertPostData(postData);

            using (HttpResponseMessage response = await self.PostAsync(uri, content))
            {
                if (response.Content == null)
                    return await Task.FromResult<byte[]>(null);

                return await response.Content.ReadAsByteArrayAsync();
            }
        }

        internal static FormUrlEncodedContent ConvertPostData(IPaymentPostData postData)
        {
            KeyValuePair<string, string>[] nameValueCollection = new KeyValuePair<string, string>[3]
            {
                 new KeyValuePair<string, string>("Data", postData.Data),
                 new KeyValuePair<string, string>("InterfaceVersion", postData.InterfaceVersion),
                 new KeyValuePair<string, string>("Seal", postData.Seal),
            };

            return new FormUrlEncodedContent(nameValueCollection);
        }
    }
}

#endif


text:
#include "remill/BC/ABI.h"

namespace remill {

const std::string_view kMemoryVariableName = "MEMORY";
const std::string_view kStateVariableName = "STATE";
const std::string_view kPCVariableName = "PC";
const std::string_view kNextPCVariableName = "NEXT_PC";
const std::string_view kReturnPCVariableName = "RETURN_PC";
const std::string_view kBranchTakenVariableName = "BRANCH_TAKEN";

const std::string_view kInvalidInstructionISelName = "INVALID_INSTRUCTION";
const std::string_view kUnsupportedInstructionISelName =
    "UNSUPPORTED_INSTRUCTION";

const std::string_view kIgnoreNextPCVariableName = "IGNORE_NEXT_PC";

}  // namespace remill


text:
package unnamed.utils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;

public abstract class FieldsSelector {

    public static class FieldEntry implements Comparable<FieldEntry> {
        public final Field field;
        public final int rank;

        public FieldEntry(Field field, int rank) {
            this.field = field;
            this.rank = rank;
        }

        @Override
        public int compareTo(FieldEntry o) {
            int result = Ints.compare(this.rank, o.rank);
            if (result != 0) return result;

            return this.field.getName().compareTo(o.field.getName());
        }
    }

    private final CachedFactory<Class<?>, Collection<Field>> cache = new CachedFactory<Class<?>, Collection<Field>>() {
        @Override
        protected Collection<Field> create(Class<?> key) {
            return scanForFields(key);
        }
    };

    protected abstract List<FieldEntry> listFields(Class<?> cls);

    private Collection<Field> scanForFields(Class<?> cls) {
        final List<FieldEntry> entries = listFields(cls);
        Collections.sort(entries);

        ImmutableList.Builder<Field> result = ImmutableList.builder();
        for (FieldEntry entry : entries) {
            final Field field = entry.field;
            result.add(field);
            field.setAccessible(true);
        }
        return result.build();
    }

    public Collection<Field> getFields(Class<?> cls) {
        synchronized (cache) {
            return cache.getOrCreate(cls);
        }
    }
}


text:
package com.amazonaws.services.rds.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * The status of the DB parameter group.
 *

 *

 * This data type is used as a response element in the following actions:
 *

 *

 *

 *

 * CreateDBInstance
 *

 *

 *

 *

 * CreateDBInstanceReadReplica
 *

 *

 *

 *

 * DeleteDBInstance
 *

 *

 *

 *

 * ModifyDBInstance
 *

 *

 *

 *

 * RebootDBInstance
 *

 *

 *

 *

 * RestoreDBInstanceFromDBSnapshot
 *

 *

 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DBParameterGroupStatus implements Serializable, Cloneable {

    /**
     *

     * The name of the DP parameter group.
     *

     */
    private String dBParameterGroupName;
    /**
     *

     * The status of parameter updates.
     *

     */
    private String parameterApplyStatus;

    /**
     *

     * The name of the DP parameter group.
     *

     *
     * @param dBParameterGroupName
     *        The name of the DP parameter group.
     */

    public void setDBParameterGroupName(String dBParameterGroupName) {
        this.dBParameterGroupName = dBParameterGroupName;
    }

    /**
     *

     * The name of the DP parameter group.
     *

     *
     * @return The name of the DP parameter group.
     */

    public String getDBParameterGroupName() {
        return this.dBParameterGroupName;
    }

    /**
     *

     * The name of the DP parameter group.
     *

     *
     * @param dBParameterGroupName
     *        The name of the DP parameter group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DBParameterGroupStatus withDBParameterGroupName(String dBParameterGroupName) {
        setDBParameterGroupName(dBParameterGroupName);
        return this;
    }

    /**
     *

     * The status of parameter updates.
     *

     *
     * @param parameterApplyStatus
     *        The status of parameter updates.
     */

    public void setParameterApplyStatus(String parameterApplyStatus) {
        this.parameterApplyStatus = parameterApplyStatus;
    }

    /**
     *

     * The status of parameter updates.
     *

     *
     * @return The status of parameter updates.
     */

    public String getParameterApplyStatus() {
        return this.parameterApplyStatus;
    }

    /**
     *

     * The status of parameter updates.
     *

     *
     * @param parameterApplyStatus
     *        The status of parameter updates.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DBParameterGroupStatus withParameterApplyStatus(String parameterApplyStatus) {
        setParameterApplyStatus(parameterApplyStatus);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDBParameterGroupName() != null)
            sb.append("DBParameterGroupName: ").append(getDBParameterGroupName()).append(",");
        if (getParameterApplyStatus() != null)
            sb.append("ParameterApplyStatus: ").append(getParameterApplyStatus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DBParameterGroupStatus == false)
            return false;
        DBParameterGroupStatus other = (DBParameterGroupStatus) obj;
        if (other.getDBParameterGroupName() == null ^ this.getDBParameterGroupName() == null)
            return false;
        if (other.getDBParameterGroupName() != null && other.getDBParameterGroupName().equals(this.getDBParameterGroupName()) == false)
            return false;
        if (other.getParameterApplyStatus() == null ^ this.getParameterApplyStatus() == null)
            return false;
        if (other.getParameterApplyStatus() != null && other.getParameterApplyStatus().equals(this.getParameterApplyStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDBParameterGroupName() == null) ? 0 : getDBParameterGroupName().hashCode());
        hashCode = prime * hashCode + ((getParameterApplyStatus() == null) ? 0 : getParameterApplyStatus().hashCode());
        return hashCode;
    }

    @Override
    public DBParameterGroupStatus clone() {
        try {
            return (DBParameterGroupStatus) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
export default (state={list:[]}, action) => {
  const newState = {list:[]};

  switch (action.type) {
    case 'LOAD_LIST' : {
      newState.list = action.payload;
      break;
    }
    case 'ADD_TODO': {
      newState.list = state.list.concat(action.payload);
      break;
    }
    case 'MARK_DONE' : {
      const o = getItem(state.list, action.payload);
      o.item.done = !o.item.done;
      newState.list = o.list.slice();
      break;
    }
    case 'ARCHIVE' : {
      const o = getItem(state.list, action.payload);
      o.item.archived = true;
      newState.list = o.list;
      break;
    }
    case 'SET_DUE' : {
      console.log('due date is set');
      break;
    }
    default : {
      return state;
    }
  }
  return newState;
};

const getItem  = (list, item) => {
  const newList = list.slice();
  const index = newList.indexOf(item);
  return { list: newList, item: newList[index] };
}


text: export { default } from 'ember-fhir/serializers/search-parameter';


text:
'use strict';

module.exports = function (grunt) {

	// Please see the Grunt documentation for more information regarding task
	// creation: http://gruntjs.com/creating-tasks

	function getHeaders(data) {
		var output = '=== ' + data.displayName + ' ===\n';
		if ('string' === typeof data.contributors) {
			data.contributors = [data.contributors];
		}
		output += 'Contributors: ' + data.contributors.join(', ') + '\n' +
				(data.donateLink ? 'Donate link: ' + data.donateLink + '\n' : '') +
				'Tags: ' + data.tags.join(', ') + '\n' +
				'Requires at least: ' + data.minimumVersion + '\n' +
				'Tested up to: ' + data.testedUpTo + '\n' +
				'Stable tag: ' + data.stableTag + '\n' +
				'License: ' + data.license + '\n' +
				'License URI: ' + data.licenseURI + '\n' +
				(data.textDomain ? 'Text Domain: ' + data.textDomain + '\n' : '') +
				(data.domainPath ? 'Domain Path: ' + data.domainPath + '\n' : '') +
				'\n' +
				data.blurb + '\n' +
				'\n';

		return output;
	}

	function getDescriptionSection(section) {
		return '== Description ==\n' +
				'\n' +
				section + '\n' +
				'\n';
	}

	function getInstallationSection(section, options) {
		var index,
				item,
				output = '== Installation ==\n' +
						'\n';
		if (!section.length) {
			return output + options.defaultInstallation;
		}
		if (section instanceof Array) {
			for (index = 0; index < section.length; index += 1) {
				item = section[index];
				output += (index + 1) + '. ' + item + '\n';
			}
		} else {
			output += section + '\n';
		}

		return output + '\n';
	}

	function getFaqSection(section, options) {
		var index,
				item,
				output = '== Frequently Asked Questions ==\n' +
						'\n';
		if (!section.length) {
			return output + options.defaultFaq;
		}

		for (index = 0; index < section.length; index += 1) {
			item = section[index];
			output += '= ' + item.question + ' =\n' +
					'\n' +
					item.answer + '\n' +
					'\n';
		}

		return output;
	}

	function getScreenshotsSection(section, options) {
		var index,
				item,
				output = '== Screenshots ==\n' +
						'\n';
		if (!section.length) {
			return output + options.defaultScreenshots;
		}

		for (index = 0; index < section.length; index += 1) {
			item = section[index];
			output += (index + 1) + '. ' + item + '\n';
		}

		return output + '\n';
	}

	function getChangelogSection(section, options) {
		var index,
				item,
				formatChange = function (change) {
					return '* ' + change;
				},
				output = '== Changelog ==\n' +
						'\n';
		if (!section.length) {
			return output + options.defaultChangelog;
		}

		for (index = 0; index < section.length; index += 1) {
			item = section[index];
			output += '= ' + item.version + ' =\n';
			if (undefined !== item.releaseDate) {
				output += '* Released: ' + item.releaseDate + '\n';
			}
			if (item.changes instanceof Array) {
				output += item.changes.map(formatChange).join('\n') + '\n';
			} else {
				output += item.changes + '\n';
			}
			output += '\n';
		}

		return output;
	}

	function getUpgradeSection(section, options) {
		var banner = '== Upgrade Notice ==\n' +
				'\n';
		if ('' === section) {
			return banner + options.defaultUpgrade;
		}
		return banner +
				section + '\n' +
				'\n';
	}

	function getExtraSection(section) {
		if (!section.header || !section.body) {
			return '';
		}
		return '== ' + section.header + ' ==\n' +
				'\n' +
				section.body + '\n' +
				'\n';
	}

	grunt.registerMultiTask('wp_readme', 'Generate a readme.txt for your WordPress plugins.', function () {
		// Merge task-specific and/or target-specific options with these defaults.
		var wpData,
				sections,
				output,
				options = this.options({
					readme             : 'readme.txt',
					defaultInstallation: '',
					defaultFaq         : '',
					defaultChangelog   : '',
					defaultUpgrade     : '',
					defaultScreenshots : ''
				});

		if ('readme.txt' !== options.readme.substr(-10)) {
			options.readme += '/readme.txt';
		}

		wpData = {
			displayName   : this.data.displayName || false,
			contributors  : this.data.contributors || [],
			donateLink    : this.data.donateLink || false,
			tags          : this.data.tags || [],
			minimumVersion: this.data.minimumVersion || false,
			testedUpTo    : this.data.testedUpTo || false,
			stableTag     : this.data.stableTag || false,
			license       : this.data.license || 'GPL-2.0+',
			licenseURI    : this.data.licenseURI || 'http://www.gnu.org/licenses/gpl-2.0.html',
			textDomain    : this.data.textDomain || false,
			domainPath    : this.data.domainPath || false,
			blurb         : this.data.blurb || '',
			sections      : this.data.sections || {}
		};

		['displayName', 'minimumVersion', 'testedUpTo', 'stableTag'].forEach(function (item) {
			if (!wpData[item]) {
				grunt.fail.warn(item + ' is a required field!');
			}
		});
		if (!wpData.contributors.length) {
			grunt.fail.warn('You must specify at least one contributor!');
		}

		sections = {
			description : wpData.sections.description || wpData.blurb,
			installation: wpData.sections.installation || '',
			faq         : wpData.sections.faq || [],
			screenshots : wpData.sections.screenshots || [],
			changelog   : wpData.sections.changelog || [],
			upgrade     : wpData.sections.upgrade || '',
			extra       : wpData.sections.extra || {header: false, body: false}
		};

		output = getHeaders(wpData) +
				getDescriptionSection(sections.description) +
				getInstallationSection(sections.installation, options) +
				getFaqSection(sections.faq, options) +
				getScreenshotsSection(sections.screenshots, options) +
				getChangelogSection(sections.changelog, options) +
				getUpgradeSection(sections.upgrade, options) +
				getExtraSection(sections.extra);

		grunt.file.write(options.readme, grunt.util.normalizelf(output));

		grunt.log.writeln('File ' + options.readme + ' created.');
	});

};


text:
module Traceable
  class BasicHandler
    require File.dirname(__FILE__) + '/line_types'

    attr_accessor :status, :results, :current, :stats, :teased, :unknown, :session

#    Result = Struct.new(:start, :between, :end)
    Seat = Struct.new(:session_id, :requests, :start,:last,:user )
    Request = Struct.new(:controller, :action, :ip, :method, :when, :duration, :parameters, :unknown)
    Stats = Struct.new(:started, :failed, :completed, :teased, :unknown)
    def initialize
      @status = :ready
      @results = []
      @stats = Stats.new(0,0,0,0,0)
      @teased = []
      @unknown = []
    end

    def log_lines
      Traceable::LineTypes::LOG_LINES
    end

#   { :controller => 1, :action => 2, :ip => 3, :method => 5, :timestamp => 4 }
    def started(line, options, match_data)
      @status = :inside
      @current = Request.new(match_data[1], match_data[2], match_data[3], match_data[5], match_data[4])
      @stats[:started] += 1
    end

    def failed(line, options, match_data)
      if @status == :inside
        @status = :ready
# TODO ..
        @stats[:failed] += 1
      end
    end

#   { :url => 7, :status => [6, :to_i], :duration => [1, :to_f], :rendering => [3, :to_f], :db => [5, :to_f] }
    def completed(line, options, match_data)
      if @status == :inside
        @status = :ready
        @current[:duration] = match_data[1]
# TODO ...
        @stats[:completed] += 1
      end
    end

#   {:session_id => 1}
    def session(line, options, match_data)
      if @status == :inside
        session_id = match_data[1]
        if (@session && (@session.session_id == session_id)) || (@session = results.find{|session| session.session_id == session_id})
          @session[:last] = @current.when
        else
          @session = Seat.new(session_id, [], @current.when, @current.when)
          @results << @session
        end
        @session[:requests] = (@session[:requests] || [])  << @current
      # else session line outside of a request log block "found"
      end
    end

    def parameters(line, options, match_data)
      if @status == :inside
        @current[:parameters] = match_data[1]
      end
    end

    def teased_line(type, line, options)
      puts type
      @stats[:teased] += 1
      @teased << line
    end

    def unknown_line(line)
      return if line == "\n"
      if @status == :inside
        @current[:unknown] = (@current[:unknown] || []) << line
      end
      @unknown << line
#      @current[:between] << line if @status == :inside
      @stats[:unknown] += 1
    end

 end
end


text:
package workerpool_test

import (
	. "github.com/cloudfoundry/storeadapter/workerpool"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"runtime"
	"time"
)

var _ = Describe("WorkerPool", func() {
	var pool *WorkerPool

	BeforeEach(func() {
		poolSize := 2
		pool = NewWorkerPool(poolSize)
	})

	AfterEach(func() {
		pool.StopWorkers()
	})

	Describe("scheduling work", func() {
		Context("when passed one function", func() {
			It("should run the passed in function", func() {
				called := make(chan bool, 1)

				pool.ScheduleWork(func() {
					called <- true
				})

				Eventually(called, 0.1, 0.01).Should(HaveLen(1))
			})
		})

		Context("when passed many function", func() {
			var (
				startTime time.Time
				runTimes  chan time.Duration
				sleepTime time.Duration
				work      func()
			)

			BeforeEach(func() {
				startTime = time.Now()
				runTimes = make(chan time.Duration, 10)
				sleepTime = time.Duration(0.01 * float64(time.Second))

				work = func() {
					time.Sleep(sleepTime)
					runTimes <- time.Since(startTime)
				}
			})

			Context("when passed poolSize functions", func() {
				BeforeEach(func() {
					pool.ScheduleWork(work)
					pool.ScheduleWork(work)
				})

				It("should run the functions concurrently", func() {
					Eventually(runTimes, 0.1, 0.01).Should(HaveLen(2))
					Ω(<-runTimes).Should(BeNumerically("<=", sleepTime+sleepTime/2))
					Ω(<-runTimes).Should(BeNumerically("<=", sleepTime+sleepTime/2))
				})
			})

			Context("when passed more than poolSize functions", func() {
				BeforeEach(func() {
					pool.ScheduleWork(work)
					pool.ScheduleWork(work)
					pool.ScheduleWork(work)
				})

				It("should run all the functions, but at most poolSize at a time", func() {
					Eventually(runTimes, 0.1, 0.01).Should(HaveLen(3))

					//first batch
					Ω(<-runTimes).Should(BeNumerically("<=", sleepTime+sleepTime/2))
					Ω(<-runTimes).Should(BeNumerically("<=", sleepTime+sleepTime/2))

					//second batch
					Ω(<-runTimes).Should(BeNumerically(">=", sleepTime*2))
				})
			})
		})

		Context("when stopped", func() {
			var numGoroutines int

			BeforeEach(func() {
				numGoroutines = runtime.NumGoroutine()
				pool.StopWorkers()
			})

			It("should never perform the work", func() {
				called := make(chan bool, 1)

				pool.ScheduleWork(func() {
					called <- true
				})

				time.Sleep(time.Duration(0.1 * float64(time.Second)))

				Ω(called).Should(HaveLen(0))
			})

			It("should stop the workers", func() {
				Eventually(runtime.NumGoroutine, 0.1, 0.01).Should(Equal(numGoroutines-2), "Should have reduced number of go routines by pool size")
			})
		})
	})

	Describe("Measuring capacity", func() {
		It("should track the ...", func() {
			dt := time.Duration(0.1 * float64(time.Second))

			pool.StartTrackingUsage()
			called := make(chan bool, 1)
			pool.ScheduleWork(func() {
				time.Sleep(dt)
				called <- true
			})

			<-called
			time.Sleep(dt)

			usage, duration := pool.MeasureUsage()

			Ω(duration.Seconds()).Should(BeNumerically("~", 0.2, 0.05))
			Ω(usage).Should(BeNumerically("~", 0.25, 0.05)) //one of two workers was occupied for half the time:

			//now do it again, but occupy two workers

			called = make(chan bool, 1)
			pool.ScheduleWork(func() {
				time.Sleep(dt)
				called <- true
			})

			pool.ScheduleWork(func() {
				time.Sleep(dt)
				called <- true
			})

			<-called
			time.Sleep(dt)

			usage, duration = pool.MeasureUsage()
			Ω(duration.Seconds()).Should(BeNumerically("~", 0.2, 0.05))
			Ω(usage).Should(BeNumerically("~", 0.5, 0.05)) //both workers were occupied for half the time:
		})
	})
})


text:
using System;
using Internal.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Internal.Runtime.Augments
{
    [CLSCompliant(false)]
    public abstract class InteropCallbacks
    {
        public abstract bool TryGetMarshallerDataForDelegate(RuntimeTypeHandle delegateTypeHandle, out McgPInvokeDelegateData  delegateData);

        public abstract bool TryGetStructUnmarshalStub(RuntimeTypeHandle structureTypeHandle, out IntPtr unmarshalStub);

        public abstract bool TryGetStructMarshalStub(RuntimeTypeHandle structureTypeHandle, out IntPtr marshalStub);

        public abstract bool TryGetDestroyStructureStub(RuntimeTypeHandle structureTypeHandle, out IntPtr destroyStructureStub, out bool hasInvalidLayout);

        public abstract bool TryGetStructFieldOffset(RuntimeTypeHandle structureTypeHandle, string fieldName, out bool structExists, out uint offset);

        public abstract bool TryGetStructUnsafeStructSize(RuntimeTypeHandle structureTypeHandle, out int size);
    }
}


text:
namespace Alkadia.Roslyn.CodeRefactoring.Tests.Providers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using CodeRefactoring.CodeActions;
    using CodeRefactoring.Providers;
    using FakeItEasy;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CodeActions;
    using Microsoft.CodeAnalysis.CodeRefactorings;
    using Microsoft.CodeAnalysis.Text;
    using Xunit;

    public class InitializeFieldsFromConstructorCodeRefactoringProviderTests
    {
        //private readonly static Action<CodeAction> _empty = _ => { };
        public CodeRefactoringContext GetContext(
            string code,
            TextSpan span,
            string documentName = "Test",
            string projectName = "Test",
            IEnumerable<string> folders = null,
            Action<CodeAction> interceptRegister = null)
        {
            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject(ProjectInfo.Create(
                ProjectId.CreateNewId(),
                VersionStamp.Default,
                projectName,
                projectName,
                LanguageNames.CSharp
            ));
            var document = project.AddDocument($"{documentName}.cs", code, folders);

            var context = new CodeRefactoringContext(
                document,
                span,
                interceptRegister,
                CancellationToken.None
            );

            return context;
        }

        [Theory]
        [AutoFakeItEasyData]
        public async Task Should_not_register_when_context_is_not_a_constructor_parameter_or_parameter_name_is_missing(
            ICodeRefactoringContextSubscriber interceptor,
            InitializeFieldsFromConstructorCodeRefactoringProvider sut
        )
        {
            const string TestCase = @"
namespace Test {
    public class Foo {
        private class Inner { }
        public Foo() {}
        public Foo(int intParam, MissingParameterName) {
            var innerDecl = new DateTime(2016, 3, 21, 0, 0, 0);
        }
        public void MyMethod(MyType boolParam) { }
    }
}
";
            var cases = new[]
            {
                "MissingParameterName",
                "namespace",
                "Test",
                "public",
                "Foo",
                "class I",
                "Inner",
                "Foo(",
                "innerDecl",
                "DateTime",
                "MyMethod",
                "MyType",
                "boolParam",
                "()"
            }.Select(c => GetContext(
                TestCase,
                new TextSpan(TestCase.IndexOf(c, StringComparison.Ordinal) + 1, 0),
                projectName: "TestSuite",
                interceptRegister: interceptor.Register
            ));

            foreach (var context in cases)
                await sut.ComputeRefactoringsAsync(context);

            A
                .CallTo(() => interceptor.Register(A<CodeAction>.Ignored))
                .MustNotHaveHappened();
        }

        [Theory]
        [AutoFakeItEasyData]
        public async Task Should_not_register_if_parameter_is_already_assigned(
            ICodeRefactoringContextSubscriber interceptor,
            InitializeFieldsFromConstructorCodeRefactoringProvider sut
        )
        {
            const string TestCase = @"
namespace Test {
    public class Foo {
        public Foo(int intParam) {
            _tmp = intParam;
        }
    }
    public class Foo2 {
        public Foo(bool boolParam) {
            this.tmp = boolParam;
        }
    }
}
";
            var cases = new[]
            {
                "intParam",
                "boolParam"
            }.Select(c => GetContext(
                TestCase,
                new TextSpan(TestCase.IndexOf(c, StringComparison.Ordinal) + 1, 0),
                projectName: "TestSuite",
                interceptRegister: interceptor.Register
            ));

            foreach (var context in cases)
                await sut.ComputeRefactoringsAsync(context);

            A
                .CallTo(() => interceptor.Register(A<CodeAction>.Ignored))
                .MustNotHaveHappened();
        }

        [Theory]
        [AutoFakeItEasyData]
        public async Task Should_register_with_correct_parameters(
            ICodeRefactoringContextSubscriber interceptor,
            InitializeFieldsFromConstructorCodeRefactoringProvider sut
        )
        {
            const string TestCase = @"
namespace Test {
    public class Foo {
        public Foo(int intParam) {
            field = otherField;
            intParam = 12;
        }
    }
}
";
            var cases = new[]
            {
                "intParam"
            }.Select(c => GetContext(
                TestCase,
                new TextSpan(TestCase.IndexOf(c, StringComparison.Ordinal) + 1, 0),
                projectName: "TestSuite",
                interceptRegister: interceptor.Register
            )).ToArray();

            var actions = new List<InitializeFieldsFromConstructorCodeAction>();
            A
                .CallTo(() => interceptor.Register(A<CodeAction>.Ignored))
                .Invokes((CodeAction act) => { actions.Add(act as InitializeFieldsFromConstructorCodeAction); });

            foreach (var context in cases)
                await sut.ComputeRefactoringsAsync(context);

            A
                .CallTo(() => interceptor.Register(A<CodeAction>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Once);

            Assert.Equal("Initialize field '_intParam'", actions[0].Title);

            Assert.Equal(cases[0].Document.Id, actions[0].FixParameters.DocumentId);
            Assert.Equal(cases[0].Document.Project.Solution.Id, actions[0].FixParameters.Solution.Id);
            Assert.Equal("intParam", actions[0].FixParameters.ParameterName);
            Assert.Equal(cases[0].Span, actions[0].FixParameters.Span);
        }

    }
}


text:
/*
 * Created on Sep 28, 2004
 *
 */
package br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.impl;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;

import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.dt.Constants;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.spec.req.IAlbumCtr;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.spec.req.IExceptionsHandlerCtr;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.spec.req.IFilesystemCtr;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.mobilephonecontroller.spec.req.IPhotoCtr;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.excep.ImageNotFoundException;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.excep.InvalidImageDataException;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.excep.InvalidPhotoAlbumNameException;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.excep.PersistenceMechanismException;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.excep.UnavailablePhotoAlbumException;
import br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.prov.IManager;

/**
 * @author tyoung
 *
 * This is the base controller class used in the MVC architecture.
 * It controls the flow of screens for the MobileMedia application.
 * Commands handled by this class should only be for the core application
 * that runs on any MIDP platform. Each device or class of devices that supports
 * optional features will extend this class to handle feature specific commands.
 *
 */
class BaseController implements CommandListener, ControllerInterface {

	//Define a successor to implement the Chain of Responsibility design pattern
	private BaseController nextController;

	;

	//Keep track of the navigation so we can go 'back' easily
	private String currentScreenName;

	//Keep track of the current photo album being viewed
	//Ie. name of the currently active J2ME record store
	private String currentStoreName = "My Photo Album";

/*	protected IManager getManager() {
		if(manager == null)
			System.out.println("manager is null");
		return manager;this.getManager();
	}

	protected void setManager(IManager manager2) {
		if(manager2 == null)
			System.out.println("manager2 is null");
		this.manager = (Manager) manager2;
	}*/

	/**
	 * Initialize the controller
	 */
	public void init() { //System.out.println("BaseController.init()");

		IManager manager = ComponentFactory.createInstance();

		//Get all MobileMedia defined albums from the record store
	    IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
	    if(fileSystem == null)
	    	System.err.println("filesystem is null inside basecontroller");

	    String[] albumNames = fileSystem.getAlbumNames();

	    //System.out.println("realizou operacoes com filesystem");

		//initialize all the screens
		IAlbumCtr album = (IAlbumCtr)manager.getRequiredInterface("IAlbumCtr");
		album.initAlbumListScreen(albumNames);

		//Set the current screen to the photo album listing
		currentScreenName = Constants.ALBUMLIST_SCREEN;

	}

    public boolean handleCommand(Command c) { System.out.println("BaseController.handleCommand()");

    	IManager manager = ComponentFactory.createInstance();

		IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
		IAlbumCtr album = (IAlbumCtr)manager.getRequiredInterface("IAlbumCtr");
		if(album == null)
			System.err.println("album is null before the if/else");
		IPhotoCtr photo = (IPhotoCtr)manager.getRequiredInterface("IPhotoCtr");
		IExceptionsHandlerCtr excepHandler = (IExceptionsHandlerCtr)manager.getRequiredInterface("IExceptionsHandlerCtr");

    	//Can this controller handle the desired action?
		//If yes, handleCommand will return true, and we're done
		//If no, handleCommand will return false, and postCommand
		//will pass the request to the next controller in the chain if one exists.

		String label = c.getLabel();
      	//System.out.println( this.getClass().getName() + "::handleCommand: " + label);

		/** Case: Exit Application **/
		if (label.equals("Exit")) {
			//TODO: Funcionalidade de destruir aplicação
			//midlet.destroyApp(true);
			return true;
		/** Case: Reset PhotoAlbum data **/
		} else if (label.equals("Reset")) {
		    resetImageData();
			currentScreenName = Constants.ALBUMLIST_SCREEN;
			return true;
		}else if (label.equals("New Photo Album")) {
			//System.out.println("Create new Photo Album here");
			currentScreenName = Constants.NEWALBUM_SCREEN;
			album.initNewAlbumScreen();
			return true;
			/** Case: Delete Album Photo**/
		}else if (label.equals("Delete Album")) {
			//System.out.println("Delete Photo Album here");
			currentScreenName = Constants.CONFIRMDELETEALBUM_SCREEN;
			currentStoreName = album.getSelectedAlbum( );
			album.initDeleteAlbumScreen( currentStoreName );
			return true;
		/** Case: Yes delete Photo Album  **/
		}else if (label.equals("Yes - Delete")) {
			try {
				fileSystem.deletePhotoAlbum(currentStoreName);
			} catch (PersistenceMechanismException e) {
				excepHandler.handle( e );
				//Alert alert = new Alert( "Error", "The mobile database can not delete this photo album", null, AlertType.ERROR);
				//TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
			}
			goToPreviousScreen();
			return true;
		/** Case: Save new Photo Album  **/
			/** Case: No delete Photo Album  **/
		}else if (label.equals("No - Delete")) {
			goToPreviousScreen();
			return true;
		/** Case: Save new Photo Album  **/
		} else if (label.equals("Save")) {
			try {
				//TODO: Apagar codigo comentado
				//model.createNewPhotoAlbum(((NewAlbumScreen)getCurrentScreenName()).getAlbumName());
				fileSystem.createNewPhotoAlbum( album.getNewAlbumName() );
			} catch (PersistenceMechanismException e) {
				excepHandler.handle( e );
				/*Alert alert = null;
				if (e.getCause() instanceof  RecordStoreFullException)
					alert = new Alert( "Error", "The mobile database is full", null, AlertType.ERROR);
				else
					alert = new Alert( "Error", "The mobile database can not add a new photo album", null, AlertType.ERROR);
				*///TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
				return true;
		    } catch (InvalidPhotoAlbumNameException e) {
		    	excepHandler.handle( e );
		    	//Alert alert = new Alert( "Error", "You have provided an invalid Photo Album name", null, AlertType.ERROR);
		    	//TODO: Apagar codigo comentado
		    	//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
				return true;
			}
			goToPreviousScreen();
			return true;
			/** Case: Select PhotoAlbum to view **/
		} else if (label.equals("Select")) {

			//System.out.println("\n\n========" + this );

			if(currentStoreName == null)
				System.err.println("currentStoreName is null");
			if(album == null)
				System.err.println("album is null");

			//Get the name of the PhotoAlbum selected, and load image list from RecordStore
			currentStoreName = album.getSelectedAlbum();
			showImageList(currentStoreName);
			currentScreenName = Constants.IMAGELIST_SCREEN;
			return true;
			/** Case: View Image **/
		} else if (label.equals("View")) {
			showImage();
			currentScreenName = Constants.IMAGE_SCREEN;
			return true;

		/** Case: Add photo  **/
		} else if (label.equals("Add")) {
			currentScreenName = Constants.ADDPHOTOTOALBUM_SCREEN;
			photo.initAddPhotoToAlbum( currentStoreName );
			return true;
			/** Case: Save Add photo  **/
		} else if (label.equals("Save Add Photo")) {
			try {
				fileSystem.addNewPhotoToAlbum(photo.getAddedPhotoName(), photo.getAddedPhotoPath() , currentStoreName );

				//TODO: Apagar codigo comentado
				//model.addNewPhotoToAlbum(((AddPhotoToAlbum)getCurrentScreenName()).getPhotoName(), ((AddPhotoToAlbum)getCurrentScreenName()).getPath(), currentStoreName);
			} catch (InvalidImageDataException e) {
				excepHandler.handle( e );
				/*Alert alert = null;
				if (e instanceof ImagePathNotValidException)
					alert = new Alert( "Error", "The path is not valid", null, AlertType.ERROR);
				else
					alert = new Alert( "Error", "The image file format is not valid", null, AlertType.ERROR);
				*///TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
				return true;
				//alert.setTimeout(5000);
			} catch (PersistenceMechanismException e) {
				excepHandler.handle( e );
				/*Alert alert = null;
				if (e.getCause() instanceof  RecordStoreFullException)
					alert = new Alert( "Error", "The mobile database is full", null, AlertType.ERROR);
				else
					alert = new Alert( "Error", "The mobile database can not add a new photo", null, AlertType.ERROR);
				*///TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
			}
			goToPreviousScreen();
			return true;

		/** Case: Delete selected Photo from recordstore **/
		} else if (label.equals("Delete")) {
	      	String selectedImageName = getSelectedImageName();
	      	try {
	      		//TODO: Apagar codigo comentado
				//model.deleteImage(currentStoreName, selectedImageName);
	      		fileSystem.deleteImage(currentStoreName, selectedImageName );
	      	} catch (PersistenceMechanismException e) {
	      		excepHandler.handle( e );
	      		//Alert alert = new Alert( "Error", "The mobile database can not delete this photo", null, AlertType.ERROR);
				//TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
		        return true;
			} catch (ImageNotFoundException e) {
				excepHandler.handle( e );
				//Alert alert = new Alert( "Error", "The selected photo was not found in the mobile device", null, AlertType.ERROR);
				//TODO: Apagar codigo comentado
				//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());		        return true;
			}
	      	showImageList(currentStoreName);
		    currentScreenName = Constants.IMAGELIST_SCREEN;
			return true;

		/** Case: Go to the Previous or Fallback screen **/
		} else if (label.equals("Back")) {

		    goToPreviousScreen();
			return true;

		/** Case: Cancel the current screen and go back one**/
		} else if (label.equals("Cancel")) {

			goToPreviousScreen();
			return true;

		}

		//If we couldn't handle the current command, return false
        return false;
    }

    public void postCommand(Command c) { //System.out.println("BaseController.postCommand()");

        //System.out.println("BaseController::postCommand - Current controller is: " + this.getClass().getName());

        //If the current controller cannot handle the command, pass it to the next
        //controller in the chain.
        if (handleCommand(c) == false) {
            BaseController next = getNextController();
            if (next != null) {
                System.err.println("Passing to next controller in chain: " + next.getClass().getName());
                next.postCommand(c);
            } else {
                System.err.println("BaseController::postCommand - Reached top of chain. No more handlers for command: " + c.getLabel());
            }
        }

    }

	/**
	 * Handle events. For now, this just passes control off to a 'wrapper'
	 * so we can ensure , in order to use it in the aspect advice
	 */
	public void commandAction(Command c, Displayable d) { //System.out.println("BaseController.commandAction()");
	    postCommand(c);
	}

    /**
	 * This option is mainly for testing purposes. If the record store
	 * on the device or emulator gets into an unstable state, or has too
	 * many images, you can reset it, which clears the record stores and
	 * re-creates them with the default images bundled with the application
	 */
	private void resetImageData() { System.out.println("BaseController.resetImageData()");

		//Get all required interfaces for this method
		IManager manager = ComponentFactory.createInstance();
		IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
		IAlbumCtr album = (IAlbumCtr)manager.getRequiredInterface("IAlbumCtr");
		IExceptionsHandlerCtr excepHandler = (IExceptionsHandlerCtr)manager.getRequiredInterface("IExceptionsHandlerCtr");

		try {
			fileSystem.resetImageData();
		} catch (PersistenceMechanismException e) {
			excepHandler.handle( e );
			/*Alert alert = null;
			if (e.getCause() instanceof  RecordStoreFullException)
				alert = new Alert( "Error", "The mobile database is full", null, AlertType.ERROR);
			else
				alert = new Alert( "Error", "It is not possible to reset the database", null, AlertType.ERROR);
			*///TODO: Apagar codigo comentado
			//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
			return;
		}

        //Clear the names from the album list
		//TODO: Apagar codigo comentado
		/*
		for (int i = 0; i < albumListScreen.size(); i++) {
        	albumListScreen.delete(i);
        }

        //Get the default ones from the album
        String[] albumNames = model.getAlbumNames();
        for (int i = 0; i < albumNames.length; i++) {
        	if (albumNames[i] != null) {
        		//Add album name to menu list
        		albumListScreen.append(albumNames[i], null);

        	}
        }

        setCurrentScreen(albumListScreen);*/
        String[] albumNames = fileSystem.getAlbumNames();
        album.initAlbumListScreen(albumNames);
    }

	//TODO: Apagar codigo comentado
    /**
	 * Set the current screen for display
	 *
    public void setCurrentScreen(Displayable d) {
        Display.getDisplay(midlet).setCurrent(d);
    }

    /**
	 * Set the current screen for display, after alert
	 *
    public void setCurrentScreen(Alert a, Displayable d) {
//        display.setCurrent(a, d);
        Display.getDisplay(midlet).setCurrent(a, d);
    }

    /**
	 * Get the current screen name that is displayed
	 *
    public Displayable getCurrentScreenName() {
//        return display.getCurrent();
        return Display.getDisplay(midlet).getCurrent();
    }

    /**
     * Go to the previous screen
     * TODO: Re-implement. Not working properly yet.
	 */
    private void goToPreviousScreen() { //System.out.println("BaseController.goToPreviousScreen()");

    	//System.out.println("\n\n========" + this );

    	//Get all required interfaces for this method
    	IManager manager = ComponentFactory.createInstance();
		IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
		IAlbumCtr album = (IAlbumCtr)manager.getRequiredInterface("IAlbumCtr");
		//System.out.println("ALBUM**************"+album);
		//System.out.println("FILESYSTEM****************"+fileSystem);
    	//System.out.println("currentScreenName***********"+currentScreenName);

    	if (currentScreenName.equals(Constants.ALBUMLIST_SCREEN)) {
		    System.err.println("Can't go back here...Should never reach this spot");
		} else if (currentScreenName.equals(Constants.IMAGE_SCREEN)) {
		    //Go to the image list here, not the main screen...
		    showImageList(currentStoreName);
		    currentScreenName = Constants.IMAGELIST_SCREEN;
		} else if (currentScreenName.equals(Constants.IMAGELIST_SCREEN)) {
			album.initAlbumListScreen( fileSystem.getAlbumNames() );
		    currentScreenName = Constants.ALBUMLIST_SCREEN;
		}else if (currentScreenName.equals(Constants.NEWALBUM_SCREEN)) {
			album.initAlbumListScreen( fileSystem.getAlbumNames() );
		    currentScreenName = Constants.ALBUMLIST_SCREEN;
		}else if (currentScreenName.equals(Constants.CONFIRMDELETEALBUM_SCREEN)) {
			album.initAlbumListScreen( fileSystem.getAlbumNames() );
			currentScreenName = Constants.ALBUMLIST_SCREEN;
		}else if (currentScreenName.equals(Constants.ADDPHOTOTOALBUM_SCREEN)) {
			showImageList(currentStoreName);
		    currentScreenName = Constants.IMAGELIST_SCREEN;
		}

    }

    /**
     * Show the current image that is selected
	 */
	public void showImage() { System.out.println("BaseController.showImage()");
		//Get all required interfaces for this method
		IManager manager = ComponentFactory.createInstance();
		IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
		IPhotoCtr photo = (IPhotoCtr)manager.getRequiredInterface("IPhotoCtr");
		IExceptionsHandlerCtr excepHandler = (IExceptionsHandlerCtr)manager.getRequiredInterface("IExceptionsHandlerCtr");

		String name = photo.getSelectedPhoto();
		Image storedImage = null;
		try {
			storedImage = fileSystem.getImageFromRecordStore(currentStoreName, name);
		} catch (ImageNotFoundException e) {
			excepHandler.handle( e );
			//Alert alert = new Alert( "Error", "The selected photo was not found in the mobile device", null, AlertType.ERROR);
			//TODO: Apagar codigo comentado
			//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
	        return;
		} catch (PersistenceMechanismException e) {
			excepHandler.handle( e );
			//Alert alert = new Alert( "Error", "The mobile database can open this photo", null, AlertType.ERROR);
			//TODO: Apagar codigo comentado
			//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
	        return;
		}

		//We can pass in the image directly here, or just the name/model pair and have it loaded
		photo.initPhotoViewScreen( storedImage );
	}

    /**
     * Show the list of images in the record store
	 * TODO: Refactor - Move this to ImageList class
	 */
	public void showImageList(String recordName) { System.out.println("BaseController.showImageList()");

		//Get all required interfaces for this method
		IManager manager = ComponentFactory.createInstance();
		IFilesystemCtr fileSystem = (IFilesystemCtr)manager.getRequiredInterface("IFilesystemCtr");
		IPhotoCtr photo = (IPhotoCtr)manager.getRequiredInterface("IPhotoCtr");
		IExceptionsHandlerCtr excepHandler = (IExceptionsHandlerCtr)manager.getRequiredInterface("IExceptionsHandlerCtr");

		if (recordName == null)
			recordName = currentStoreName;

		String[] labels = null;
		try {
			labels = fileSystem.getImageNames(recordName);
		} catch (UnavailablePhotoAlbumException e) {
			excepHandler.handle( e );
			//Alert alert = new Alert( "Error", "The list of photos can not be recovered", null, AlertType.ERROR);
			//TODO: Apagar codigo comentado
			//Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
	        return;
	    }

		//TODO: Apagar codigo comentado
		//loop through array and add labels to list
		//for (int i = 0; i < labels.length; i++) {
			//if (labels[i] != null) {
				//Add album name to menu list
				//imageList.append(labels[i], null);

			//}
		//}
		//setCurrentScreen(imageList);
		//currentMenu = "list";

		photo.initPhotoListScreen( labels );
	}

    /**
     * Get the last selected image from the Photo List screen.
	 * TODO: This really only gets the selected List item.
	 * So it is only an image name if you are on the PhotoList screen...
	 * Need to fix this
	 */
	public String getSelectedImageName() { //System.out.println("BaseController.getSelectedImageName()");
		//Get all required interfaces for this method
		IManager manager = ComponentFactory.createInstance();
		IPhotoCtr photo = (IPhotoCtr)manager.getRequiredInterface("IPhotoCtr");

	    return photo.getSelectedPhoto();

	}

	/**
	 * @return Returns the currentStoreName.
	 */
	public String getCurrentStoreName() { //System.out.println("BaseController.getCurrentStoreName()");
		return currentStoreName;
	}

	/**
	 * @param currentScreenName The currentScreenName to set.
	 */
	//public void setCurrentScreenName(String currentScreenName) {
	//	this.currentScreenName = currentScreenName;
	//}

    /**
     * @return
     */
    public BaseController getNextController() { //System.out.println("BaseController.getNextController()");
        return nextController;
    }

    /**
     * @param nextController
     */
    public void setNextController(BaseController nextController) { //System.out.println("BaseController.setNextController()");
        this.nextController = nextController;
    }
}


text:
"""A Mesos-customized entry point to the thermos command line tool."""

from twitter.common import app
from twitter.common.log.options import LogOptions

from apache.aurora.executor.common.path_detector import MesosPathDetector
from apache.thermos.cli.common import register_path_detector
from apache.thermos.cli.main import register_commands, register_options
from apache.thermos.common.excepthook import ExceptionTerminationHandler

register_commands(app)
register_options(app)

def register_mesos_root(_, __, value, ___):
  register_path_detector(MesosPathDetector(root=value))

app.add_option(
    '--mesos-root',
    dest='mesos_root',
    type='string',
    action='callback',
    default=MesosPathDetector.DEFAULT_MESOS_ROOT,
    callback=register_mesos_root,
    help='The mesos root directory to search for Thermos executor sandboxes [default: %default]')

# register a default mesos root, since the callback will not be called if no --mesos-root specified.
register_path_detector(MesosPathDetector())

LogOptions.disable_disk_logging()
LogOptions.set_stderr_log_level('google:INFO')

app.register_module(ExceptionTerminationHandler())
app.main()


text:
package com.sohu.jafka.mx;

/**
 * @author adyliu (imxylz@gmail.com)
 * @since 1.0
 */
public interface BrokerTopicStatMBean {

    long getMessagesIn();

    long getBytesIn();

    long getBytesOut();

    long getFailedProduceRequest();

    long getFailedFetchRequest();
}