text:
package deb

import (
	"errors"

	"github.com/aptly-dev/aptly/database"

	. "gopkg.in/check.v1"
)

type LocalRepoSuite struct {
	db      database.Storage
	list    *PackageList
	reflist *PackageRefList
	repo    *LocalRepo
}

var _ = Suite(&LocalRepoSuite{})

func (s *LocalRepoSuite) SetUpTest(c *C) {
	s.db, _ = database.NewOpenDB(c.MkDir())
	s.list = NewPackageList()
	s.list.Add(&Package{Name: "lib", Version: "1.7", Architecture: "i386"})
	s.list.Add(&Package{Name: "app", Version: "1.9", Architecture: "amd64"})

	s.reflist = NewPackageRefListFromPackageList(s.list)

	s.repo = NewLocalRepo("lrepo", "Super repo")
	s.repo.packageRefs = s.reflist
}

func (s *LocalRepoSuite) TearDownTest(c *C) {
	s.db.Close()
}

func (s *LocalRepoSuite) TestString(c *C) {
	c.Check(NewLocalRepo("lrepo", "My first repo").String(), Equals, "[lrepo]: My first repo")
	c.Check(NewLocalRepo("lrepo2", "").String(), Equals, "[lrepo2]")
}

func (s *LocalRepoSuite) TestNumPackages(c *C) {
	c.Check(NewLocalRepo("lrepo", "My first repo").NumPackages(), Equals, 0)
	c.Check(s.repo.NumPackages(), Equals, 2)
}

func (s *LocalRepoSuite) TestRefList(c *C) {
	c.Check(NewLocalRepo("lrepo", "My first repo").RefList(), IsNil)
	c.Check(s.repo.RefList(), Equals, s.reflist)
}

func (s *LocalRepoSuite) TestUpdateRefList(c *C) {
	s.repo.UpdateRefList(nil)
	c.Check(s.repo.RefList(), IsNil)
}

func (s *LocalRepoSuite) TestEncodeDecode(c *C) {
	repo := &LocalRepo{}
	err := repo.Decode(s.repo.Encode())
	c.Assert(err, IsNil)

	c.Check(repo.Name, Equals, s.repo.Name)
	c.Check(repo.Comment, Equals, s.repo.Comment)
}

func (s *LocalRepoSuite) TestKey(c *C) {
	c.Assert(len(s.repo.Key()), Equals, 37)
	c.Assert(s.repo.Key()[0], Equals, byte('L'))
}

func (s *LocalRepoSuite) TestRefKey(c *C) {
	c.Assert(len(s.repo.RefKey()), Equals, 37)
	c.Assert(s.repo.RefKey()[0], Equals, byte('E'))
	c.Assert(s.repo.RefKey()[1:], DeepEquals, s.repo.Key()[1:])
}

type LocalRepoCollectionSuite struct {
	db         database.Storage
	collection *LocalRepoCollection
	list       *PackageList
	reflist    *PackageRefList
}

var _ = Suite(&LocalRepoCollectionSuite{})

func (s *LocalRepoCollectionSuite) SetUpTest(c *C) {
	s.db, _ = database.NewOpenDB(c.MkDir())
	s.collection = NewLocalRepoCollection(s.db)

	s.list = NewPackageList()
	s.list.Add(&Package{Name: "lib", Version: "1.7", Architecture: "i386"})
	s.list.Add(&Package{Name: "app", Version: "1.9", Architecture: "amd64"})

	s.reflist = NewPackageRefListFromPackageList(s.list)
}

func (s *LocalRepoCollectionSuite) TearDownTest(c *C) {
	s.db.Close()
}

func (s *LocalRepoCollectionSuite) TestAddByName(c *C) {
	_, err := s.collection.ByName("local1")
	c.Assert(err, ErrorMatches, "*.not found")

	repo := NewLocalRepo("local1", "Comment 1")
	c.Assert(s.collection.Add(repo), IsNil)
	c.Assert(s.collection.Add(repo), ErrorMatches, ".*already exists")

	r, err := s.collection.ByName("local1")
	c.Assert(err, IsNil)
	c.Assert(r.String(), Equals, repo.String())

	collection := NewLocalRepoCollection(s.db)
	r, err = collection.ByName("local1")
	c.Assert(err, IsNil)
	c.Assert(r.String(), Equals, repo.String())
}

func (s *LocalRepoCollectionSuite) TestByUUID(c *C) {
	_, err := s.collection.ByUUID("some-uuid")
	c.Assert(err, ErrorMatches, "*.not found")

	repo := NewLocalRepo("local1", "Comment 1")
	c.Assert(s.collection.Add(repo), IsNil)

	r, err := s.collection.ByUUID(repo.UUID)
	c.Assert(err, IsNil)
	c.Assert(r, Equals, repo)

	collection := NewLocalRepoCollection(s.db)
	r, err = collection.ByUUID(repo.UUID)
	c.Assert(err, IsNil)
	c.Assert(r.String(), Equals, repo.String())
}

func (s *LocalRepoCollectionSuite) TestUpdateLoadComplete(c *C) {
	repo := NewLocalRepo("local1", "Comment 1")
	c.Assert(s.collection.Update(repo), IsNil)

	collection := NewLocalRepoCollection(s.db)
	r, err := collection.ByName("local1")
	c.Assert(err, IsNil)
	c.Assert(r.packageRefs, IsNil)

	repo.packageRefs = s.reflist
	c.Assert(s.collection.Update(repo), IsNil)

	collection = NewLocalRepoCollection(s.db)
	r, err = collection.ByName("local1")
	c.Assert(err, IsNil)
	c.Assert(r.packageRefs, IsNil)
	c.Assert(r.NumPackages(), Equals, 0)
	c.Assert(s.collection.LoadComplete(r), IsNil)
	c.Assert(r.NumPackages(), Equals, 2)
}

func (s *LocalRepoCollectionSuite) TestForEachAndLen(c *C) {
	repo := NewLocalRepo("local1", "Comment 1")
	s.collection.Add(repo)

	count := 0
	err := s.collection.ForEach(func(*LocalRepo) error {
		count++
		return nil
	})
	c.Assert(count, Equals, 1)
	c.Assert(err, IsNil)

	c.Check(s.collection.Len(), Equals, 1)

	e := errors.New("c")

	err = s.collection.ForEach(func(*LocalRepo) error {
		return e
	})
	c.Assert(err, Equals, e)
}

func (s *LocalRepoCollectionSuite) TestDrop(c *C) {
	repo1 := NewLocalRepo("local1", "Comment 1")
	s.collection.Add(repo1)

	repo2 := NewLocalRepo("local2", "Comment 2")
	s.collection.Add(repo2)

	r1, _ := s.collection.ByUUID(repo1.UUID)
	c.Check(r1, Equals, repo1)

	err := s.collection.Drop(repo1)
	c.Check(err, IsNil)

	_, err = s.collection.ByUUID(repo1.UUID)
	c.Check(err, ErrorMatches, "local repo .* not found")

	collection := NewLocalRepoCollection(s.db)
	_, err = collection.ByName("local1")
	c.Check(err, ErrorMatches, "local repo .* not found")

	r2, _ := collection.ByName("local2")
	c.Check(r2.String(), Equals, repo2.String())

	c.Check(func() { s.collection.Drop(repo1) }, Panics, "local repo not found!")
}


text:
package unix

import (
	"gvisor.dev/gvisor/pkg/context"
	"gvisor.dev/gvisor/pkg/safemem"
	"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport"
	"gvisor.dev/gvisor/pkg/tcpip"
)

// EndpointWriter implements safemem.Writer that writes to a transport.Endpoint.
//
// EndpointWriter is not thread-safe.
type EndpointWriter struct {
	Ctx context.Context

	// Endpoint is the transport.Endpoint to write to.
	Endpoint transport.Endpoint

	// Control is the control messages to send.
	Control transport.ControlMessages

	// To is the endpoint to send to. May be nil.
	To transport.BoundEndpoint

	// Notify is the receiver.SendNotify notification callback that is set
	// by WriteFromBlocks and should be called without mm.activeMu held
	// (i.e. after CopyOut completes).
	Notify func()
}

// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.
func (w *EndpointWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {
	return safemem.FromVecWriterFunc{func(bufs [][]byte) (int64, error) {
		n, notify, err := w.Endpoint.SendMsg(w.Ctx, bufs, w.Control, w.To)
		w.Notify = notify
		if err != nil {
			return int64(n), err.ToError()
		}
		return int64(n), nil
	}}.WriteFromBlocks(srcs)
}

// EndpointReader implements safemem.Reader that reads from a
// transport.Endpoint.
//
// EndpointReader is not thread-safe.
type EndpointReader struct {
	Ctx context.Context

	// Endpoint is the transport.Endpoint to read from.
	Endpoint transport.Endpoint

	// Creds indicates if credential control messages are requested.
	Creds bool

	// NumRights is the number of SCM_RIGHTS FDs requested.
	NumRights int

	// Peek indicates that the data should not be consumed from the
	// endpoint.
	Peek bool

	// MsgSize is the size of the message that was read from. For stream
	// sockets, it is the amount read.
	MsgSize int64

	// From, if not nil, will be set with the address read from.
	From *tcpip.FullAddress

	// Control contains the received control messages.
	Control transport.ControlMessages

	// ControlTrunc indicates that SCM_RIGHTS FDs were discarded based on
	// the value of NumRights.
	ControlTrunc bool

	// Notify is the ConnectedEndpoint.RecvNotify callback that is set by
	// ReadToBlocks and should be called without mm.activeMu held (i.e.
	// after CopyIn completes).
	Notify func()
}

// Truncate calls RecvMsg on the endpoint without writing to a destination.
func (r *EndpointReader) Truncate() error {
	// Ignore bytes read since it will always be zero.
	_, ms, c, ct, notify, err := r.Endpoint.RecvMsg(r.Ctx, [][]byte{}, r.Creds, r.NumRights, r.Peek, r.From)
	r.Control = c
	r.ControlTrunc = ct
	r.MsgSize = ms
	if notify != nil {
		notify()
	}
	if err != nil {
		return err.ToError()
	}
	return nil
}

// ReadToBlocks implements safemem.Reader.ReadToBlocks.
func (r *EndpointReader) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {
	return safemem.FromVecReaderFunc{func(bufs [][]byte) (int64, error) {
		n, ms, c, ct, notify, err := r.Endpoint.RecvMsg(r.Ctx, bufs, r.Creds, r.NumRights, r.Peek, r.From)
		r.Control = c
		r.ControlTrunc = ct
		r.MsgSize = ms
		r.Notify = notify
		if err != nil {
			return int64(n), err.ToError()
		}
		return int64(n), nil
	}}.ReadToBlocks(dsts)
}

redpajama_set_name: RedPajamaGithub


text:
#include <fstream>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include "Config.h"
#include "FS.h"
#include "Log.h"
#include "Identity.h"
#include "util.h"
#include "ClientContext.h"
#include "SOCKS.h"
#include "MatchedDestination.h"

namespace i2p
{
namespace client
{
	ClientContext context;

	ClientContext::ClientContext (): m_SharedLocalDestination (nullptr),
		m_HttpProxy (nullptr), m_SocksProxy (nullptr), m_SamBridge (nullptr),
		m_BOBCommandChannel (nullptr), m_I2CPServer (nullptr)
	{
	}

	ClientContext::~ClientContext ()
	{
		delete m_HttpProxy;
		delete m_SocksProxy;
		delete m_SamBridge;
		delete m_BOBCommandChannel;
		delete m_I2CPServer;
	}

	void ClientContext::Start ()
	{
		// shared local destination
		if (!m_SharedLocalDestination)
			CreateNewSharedLocalDestination ();

		// addressbook
		m_AddressBook.Start ();

		// HTTP proxy
		ReadHttpProxy ();

		// SOCKS proxy
		ReadSocksProxy ();

		// I2P tunnels
		ReadTunnels ();

		// SAM
		bool sam; i2p::config::GetOption("sam.enabled", sam);
		if (sam)
		{
			std::string samAddr; i2p::config::GetOption("sam.address", samAddr);
			uint16_t    samPort; i2p::config::GetOption("sam.port",    samPort);
			bool singleThread; i2p::config::GetOption("sam.singlethread", singleThread);
			LogPrint(eLogInfo, "Clients: Starting SAM bridge at ", samAddr, ":", samPort);
			try
			{
				m_SamBridge = new SAMBridge (samAddr, samPort, singleThread);
				m_SamBridge->Start ();
			}
			catch (std::exception& e)
			{
				LogPrint(eLogError, "Clients: Exception in SAM bridge: ", e.what());
				ThrowFatal ("Unable to start SAM bridge at ", samAddr, ":", samPort, ": ", e.what ());
			}
		}

		// BOB
		bool bob; i2p::config::GetOption("bob.enabled", bob);
		if (bob) {
			std::string bobAddr; i2p::config::GetOption("bob.address", bobAddr);
			uint16_t    bobPort; i2p::config::GetOption("bob.port",    bobPort);
			LogPrint(eLogInfo, "Clients: Starting BOB command channel at ", bobAddr, ":", bobPort);
			try
			{
				m_BOBCommandChannel = new BOBCommandChannel (bobAddr, bobPort);
				m_BOBCommandChannel->Start ();
			}
			catch (std::exception& e)
			{
				LogPrint(eLogError, "Clients: Exception in BOB bridge: ", e.what());
				ThrowFatal ("Unable to start BOB bridge at ", bobAddr, ":", bobPort, ": ", e.what ());
			}
		}

		// I2CP
		bool i2cp; i2p::config::GetOption("i2cp.enabled", i2cp);
		if (i2cp)
		{
			std::string i2cpAddr; i2p::config::GetOption("i2cp.address", i2cpAddr);
			uint16_t i2cpPort; i2p::config::GetOption("i2cp.port", i2cpPort);
			bool singleThread; i2p::config::GetOption("i2cp.singlethread", singleThread);
			LogPrint(eLogInfo, "Clients: Starting I2CP at ", i2cpAddr, ":", i2cpPort);
			try
			{
				m_I2CPServer = new I2CPServer (i2cpAddr, i2cpPort, singleThread);
				m_I2CPServer->Start ();
			}
			catch (std::exception& e)
			{
				LogPrint(eLogError, "Clients: Exception in I2CP: ", e.what());
				ThrowFatal ("Unable to start I2CP at ", i2cpAddr, ":", i2cpPort, ": ", e.what ());
			}
		}

		m_AddressBook.StartResolvers ();

		// start UDP cleanup
		if (!m_ServerForwards.empty ())
		{
			m_CleanupUDPTimer.reset (new boost::asio::deadline_timer(m_SharedLocalDestination->GetService ()));
			ScheduleCleanupUDP();
		}
	}

	void ClientContext::Stop ()
	{
		if (m_HttpProxy)
		{
			LogPrint(eLogInfo, "Clients: Stopping HTTP Proxy");
			m_HttpProxy->Stop();
			delete m_HttpProxy;
			m_HttpProxy = nullptr;
		}

		if (m_SocksProxy)
		{
			LogPrint(eLogInfo, "Clients: Stopping SOCKS Proxy");
			m_SocksProxy->Stop();
			delete m_SocksProxy;
			m_SocksProxy = nullptr;
		}

		for (auto& it: m_ClientTunnels)
		{
			LogPrint(eLogInfo, "Clients: Stopping I2P client tunnel on port ", it.first);
			it.second->Stop ();
		}
		m_ClientTunnels.clear ();

		for (auto& it: m_ServerTunnels)
		{
			LogPrint(eLogInfo, "Clients: Stopping I2P server tunnel");
			it.second->Stop ();
		}
		m_ServerTunnels.clear ();

		if (m_SamBridge)
		{
			LogPrint(eLogInfo, "Clients: Stopping SAM bridge");
			m_SamBridge->Stop ();
			delete m_SamBridge;
			m_SamBridge = nullptr;
		}

		if (m_BOBCommandChannel)
		{
			LogPrint(eLogInfo, "Clients: Stopping BOB command channel");
			m_BOBCommandChannel->Stop ();
			delete m_BOBCommandChannel;
			m_BOBCommandChannel = nullptr;
		}

		if (m_I2CPServer)
		{
			LogPrint(eLogInfo, "Clients: Stopping I2CP");
			m_I2CPServer->Stop ();
			delete m_I2CPServer;
			m_I2CPServer = nullptr;
		}

		LogPrint(eLogInfo, "Clients: Stopping AddressBook");
		m_AddressBook.Stop ();

		{
			std::lock_guard<std::mutex> lock(m_ForwardsMutex);
			m_ServerForwards.clear();
			m_ClientForwards.clear();
		}

		if (m_CleanupUDPTimer)
		{
			m_CleanupUDPTimer->cancel ();
			m_CleanupUDPTimer = nullptr;
		}

		for (auto& it: m_Destinations)
			it.second->Stop ();
		m_Destinations.clear ();

		m_SharedLocalDestination->Release ();
		m_SharedLocalDestination = nullptr;
	}

	void ClientContext::ReloadConfig ()
	{
		// TODO: handle config changes
		/*std::string config; i2p::config::GetOption("conf", config);
		i2p::config::ParseConfig(config);*/

		// change shared local destination
		m_SharedLocalDestination->Release ();
		CreateNewSharedLocalDestination ();

		// recreate HTTP proxy
		if (m_HttpProxy)
		{
			m_HttpProxy->Stop ();
			delete m_HttpProxy;
			m_HttpProxy = nullptr;
		}
		ReadHttpProxy ();

		// recreate SOCKS proxy
		if (m_SocksProxy)
		{
			m_SocksProxy->Stop ();
			delete m_SocksProxy;
			m_SocksProxy = nullptr;
		}
		ReadSocksProxy ();

		// handle tunnels
		// reset isUpdated for each tunnel
		VisitTunnels (false);
		// reload tunnels
		ReadTunnels();
		// delete not updated tunnels (not in config anymore)
		VisitTunnels (true);

		// delete unused destinations
		std::unique_lock<std::mutex> l(m_DestinationsMutex);
		for (auto it = m_Destinations.begin (); it != m_Destinations.end ();)
		{
			auto dest = it->second;
			if (dest->GetRefCounter () > 0) ++it; // skip
			else
			{
				dest->Stop ();
				it = m_Destinations.erase (it);
			}
		}
	}

	bool ClientContext::LoadPrivateKeys (i2p::data::PrivateKeys& keys, const std::string& filename,
		i2p::data::SigningKeyType sigType, i2p::data::CryptoKeyType cryptoType)
	{
		static const std::string transient("transient");
		if (!filename.compare (0, transient.length (), transient)) // starts with transient
		{
			keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType, true);
			LogPrint (eLogInfo, "Clients: New transient keys address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
			return true;
		}

		bool success = true;
		std::string fullPath = i2p::fs::DataDirPath (filename);
		std::ifstream s(fullPath, std::ifstream::binary);
		if (s.is_open ())
		{
			s.seekg (0, std::ios::end);
			size_t len = s.tellg();
			s.seekg (0, std::ios::beg);
			uint8_t * buf = new uint8_t[len];
			s.read ((char *)buf, len);
			if(!keys.FromBuffer (buf, len))
			{
				LogPrint (eLogError, "Clients: Failed to load keyfile ", filename);
				success = false;
			}
			else
				LogPrint (eLogInfo, "Clients: Local address ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " loaded");
			delete[] buf;
		}
		else
		{
			LogPrint (eLogError, "Clients: Can't open file ", fullPath, " Creating new one with signature type ", sigType, " crypto type ", cryptoType);
			keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType, true);
			std::ofstream f (fullPath, std::ofstream::binary | std::ofstream::out);
			size_t len = keys.GetFullLen ();
			uint8_t * buf = new uint8_t[len];
			len = keys.ToBuffer (buf, len);
			f.write ((char *)buf, len);
			delete[] buf;

			LogPrint (eLogInfo, "Clients: New private keys file ", fullPath, " for ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " created");
		}
		return success;
	}

	std::vector<std::shared_ptr<DatagramSessionInfo> > ClientContext::GetForwardInfosFor(const i2p::data::IdentHash & destination)
	{
		std::vector<std::shared_ptr<DatagramSessionInfo> > infos;
		std::lock_guard<std::mutex> lock(m_ForwardsMutex);
		for(const auto & c : m_ClientForwards)
		{
			if (c.second->IsLocalDestination(destination))
			{
				for (auto & i : c.second->GetSessions()) infos.push_back(i);
				break;
			}
		}
		for(const auto & s : m_ServerForwards)
		{
			if(std::get<0>(s.first) == destination)
			{
				for( auto & i : s.second->GetSessions()) infos.push_back(i);
				break;
			}
		}
		return infos;
	}

	std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (bool isPublic,
		i2p::data::SigningKeyType sigType, i2p::data::CryptoKeyType cryptoType,
		const std::map<std::string, std::string> * params)
	{
		i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType, true);
		auto localDestination = std::make_shared<RunnableClientDestination> (keys, isPublic, params);
		AddLocalDestination (localDestination);
		return localDestination;
	}

	std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (
		boost::asio::io_service& service, bool isPublic,
		i2p::data::SigningKeyType sigType, i2p::data::CryptoKeyType cryptoType,
		const std::map<std::string, std::string> * params)
	{
		i2p::data::PrivateKeys keys = i2p::data::PrivateKeys::CreateRandomKeys (sigType, cryptoType, true);
		auto localDestination = std::make_shared<ClientDestination> (service, keys, isPublic, params);
		AddLocalDestination (localDestination);
		return localDestination;
	}

	std::shared_ptr<ClientDestination> ClientContext::CreateNewMatchedTunnelDestination(const i2p::data::PrivateKeys &keys, const std::string & name, const std::map<std::string, std::string> * params)
	{
		auto localDestination = std::make_shared<MatchedTunnelDestination>(keys, name, params);
		AddLocalDestination (localDestination);
		return localDestination;
	}

	void ClientContext::AddLocalDestination (std::shared_ptr<ClientDestination> localDestination)
	{
		std::unique_lock<std::mutex> l(m_DestinationsMutex);
		m_Destinations[localDestination->GetIdentHash ()] = localDestination;
		localDestination->Start ();
	}

	void ClientContext::DeleteLocalDestination (std::shared_ptr<ClientDestination> destination)
	{
		if (!destination) return;
		auto it = m_Destinations.find (destination->GetIdentHash ());
		if (it != m_Destinations.end ())
		{
			auto d = it->second;
			{
				std::unique_lock<std::mutex> l(m_DestinationsMutex);
				m_Destinations.erase (it);
			}
			d->Stop ();
		}
	}

	std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (const i2p::data::PrivateKeys& keys, bool isPublic,
		const std::map<std::string, std::string> * params)
	{
		auto it = m_Destinations.find (keys.GetPublic ()->GetIdentHash ());
		if (it != m_Destinations.end ())
		{
			LogPrint (eLogWarning, "Clients: Local destination ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " exists");
			it->second->Start (); // make sure to start
			return it->second;
		}
		auto localDestination = std::make_shared<RunnableClientDestination> (keys, isPublic, params);
		AddLocalDestination (localDestination);
		return localDestination;
	}

	std::shared_ptr<ClientDestination> ClientContext::CreateNewLocalDestination (boost::asio::io_service& service,
		const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params)
	{
		auto it = m_Destinations.find (keys.GetPublic ()->GetIdentHash ());
		if (it != m_Destinations.end ())
		{
			LogPrint (eLogWarning, "Clients: Local destination ", m_AddressBook.ToAddress(keys.GetPublic ()->GetIdentHash ()), " exists");
			it->second->Start (); // make sure to start
			return it->second;
		}
		auto localDestination = std::make_shared<ClientDestination> (service, keys, isPublic, params);
		AddLocalDestination (localDestination);
		return localDestination;
	}

	void ClientContext::CreateNewSharedLocalDestination ()
	{
		std::map<std::string, std::string> params
		{
			{ I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, "3" },
			{ I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, "3" },
			{ I2CP_PARAM_LEASESET_TYPE, "3" },
			{ I2CP_PARAM_LEASESET_ENCRYPTION_TYPE, "0,4" }
		};
		m_SharedLocalDestination = CreateNewLocalDestination (false, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519,
			i2p::data::CRYPTO_KEY_TYPE_ELGAMAL, &params); // non-public, EDDSA
		m_SharedLocalDestination->Acquire ();
	}

	std::shared_ptr<ClientDestination> ClientContext::FindLocalDestination (const i2p::data::IdentHash& destination) const
	{
		auto it = m_Destinations.find (destination);
		if (it != m_Destinations.end ())
			return it->second;
		return nullptr;
	}

	template<typename Section, typename Type>
	std::string ClientContext::GetI2CPOption (const Section& section, const std::string& name, const Type& value) const
	{
		return section.second.get (boost::property_tree::ptree::path_type (name, '/'), std::to_string (value));
	}

	template<typename Section>
	std::string ClientContext::GetI2CPStringOption (const Section& section, const std::string& name, const std::string& value) const
	{
		return section.second.get (boost::property_tree::ptree::path_type (name, '/'), value);
	}

	template<typename Section>
	void ClientContext::ReadI2CPOptionsGroup (const Section& section, const std::string& group, std::map<std::string, std::string>& options) const
	{
		for (auto it: section.second)
		{
			if (it.first.length () >= group.length () && !it.first.compare (0, group.length (), group))
				options[it.first] = it.second.get_value ("");
		}
	}

	template<typename Section>
	void ClientContext::ReadI2CPOptions (const Section& section, bool isServer, std::map<std::string, std::string>& options) const
	{
		options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNEL_LENGTH, DEFAULT_INBOUND_TUNNEL_LENGTH);
		options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, DEFAULT_OUTBOUND_TUNNEL_LENGTH);
		options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, DEFAULT_INBOUND_TUNNELS_QUANTITY);
		options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, DEFAULT_OUTBOUND_TUNNELS_QUANTITY);
		options[I2CP_PARAM_INBOUND_TUNNELS_LENGTH_VARIANCE] = GetI2CPOption (section, I2CP_PARAM_INBOUND_TUNNELS_LENGTH_VARIANCE, DEFAULT_INBOUND_TUNNELS_LENGTH_VARIANCE);
		options[I2CP_PARAM_OUTBOUND_TUNNELS_LENGTH_VARIANCE] = GetI2CPOption (section, I2CP_PARAM_OUTBOUND_TUNNELS_LENGTH_VARIANCE, DEFAULT_OUTBOUND_TUNNELS_LENGTH_VARIANCE);
		options[I2CP_PARAM_TAGS_TO_SEND] = GetI2CPOption (section, I2CP_PARAM_TAGS_TO_SEND, DEFAULT_TAGS_TO_SEND);
		options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MIN_TUNNEL_LATENCY, DEFAULT_MIN_TUNNEL_LATENCY);
		options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = GetI2CPOption(section, I2CP_PARAM_MAX_TUNNEL_LATENCY, DEFAULT_MAX_TUNNEL_LATENCY);
		options[I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY] = GetI2CPOption(section, I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY, DEFAULT_INITIAL_ACK_DELAY);
		options[I2CP_PARAM_STREAMING_ANSWER_PINGS] = GetI2CPOption(section, I2CP_PARAM_STREAMING_ANSWER_PINGS, isServer ? DEFAULT_ANSWER_PINGS : false);
		options[I2CP_PARAM_LEASESET_TYPE] = GetI2CPOption(section, I2CP_PARAM_LEASESET_TYPE, DEFAULT_LEASESET_TYPE);
		std::string encType = GetI2CPStringOption(section, I2CP_PARAM_LEASESET_ENCRYPTION_TYPE, "0,4");
		if (encType.length () > 0) options[I2CP_PARAM_LEASESET_ENCRYPTION_TYPE] = encType;
		std::string privKey = GetI2CPStringOption(section, I2CP_PARAM_LEASESET_PRIV_KEY, "");
		if (privKey.length () > 0) options[I2CP_PARAM_LEASESET_PRIV_KEY] = privKey;
		auto authType = GetI2CPOption(section, I2CP_PARAM_LEASESET_AUTH_TYPE, 0);
		if (authType != "0") // auth is set
		{
			options[I2CP_PARAM_LEASESET_AUTH_TYPE] = authType;
			if (authType == "1") // DH
				ReadI2CPOptionsGroup (section, I2CP_PARAM_LEASESET_CLIENT_DH, options);
			else if (authType == "2") // PSK
				ReadI2CPOptionsGroup (section, I2CP_PARAM_LEASESET_CLIENT_PSK, options);
		}
		std::string explicitPeers = GetI2CPStringOption(section, I2CP_PARAM_EXPLICIT_PEERS, "");
		if (explicitPeers.length () > 0) options[I2CP_PARAM_EXPLICIT_PEERS] = explicitPeers;
		std::string ratchetInboundTags = GetI2CPStringOption(section, I2CP_PARAM_RATCHET_INBOUND_TAGS, "");
		if (ratchetInboundTags.length () > 0) options[I2CP_PARAM_RATCHET_INBOUND_TAGS] = ratchetInboundTags;
	}

	void ClientContext::ReadI2CPOptionsFromConfig (const std::string& prefix, std::map<std::string, std::string>& options) const
	{
		std::string value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNEL_LENGTH, value))
			options[I2CP_PARAM_INBOUND_TUNNEL_LENGTH] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, value))
			options[I2CP_PARAM_INBOUND_TUNNELS_QUANTITY] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_INBOUND_TUNNELS_LENGTH_VARIANCE, value))
			options[I2CP_PARAM_INBOUND_TUNNELS_LENGTH_VARIANCE] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, value))
			options[I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, value))
			options[I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_OUTBOUND_TUNNELS_LENGTH_VARIANCE, value))
			options[I2CP_PARAM_OUTBOUND_TUNNELS_LENGTH_VARIANCE] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_MIN_TUNNEL_LATENCY, value))
			options[I2CP_PARAM_MIN_TUNNEL_LATENCY] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_MAX_TUNNEL_LATENCY, value))
			options[I2CP_PARAM_MAX_TUNNEL_LATENCY] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_LEASESET_TYPE, value))
			options[I2CP_PARAM_LEASESET_TYPE] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_LEASESET_ENCRYPTION_TYPE, value))
			options[I2CP_PARAM_LEASESET_ENCRYPTION_TYPE] = value;
		if (i2p::config::GetOption(prefix + I2CP_PARAM_LEASESET_PRIV_KEY, value) && !value.empty ())
			options[I2CP_PARAM_LEASESET_PRIV_KEY] = value;
	}

	void ClientContext::ReadTunnels ()
	{
		int numClientTunnels = 0, numServerTunnels = 0;
		std::string tunConf; i2p::config::GetOption("tunconf", tunConf);
		if (tunConf.empty ())
			tunConf = i2p::fs::DataDirPath ("tunnels.conf");

		LogPrint(eLogDebug, "Clients: Tunnels config file: ", tunConf);
		ReadTunnels (tunConf, numClientTunnels, numServerTunnels);

		std::string tunDir; i2p::config::GetOption("tunnelsdir", tunDir);
		if (tunDir.empty ())
			tunDir = i2p::fs::DataDirPath ("tunnels.d");

		if (i2p::fs::Exists (tunDir))
		{
			std::vector<std::string> files;
			if (i2p::fs::ReadDir (tunDir, files))
			{
				for (auto& it: files)
				{
					if (it.substr(it.size() - 5) != ".conf") continue; // skip files which not ends with ".conf"
					LogPrint(eLogDebug, "Clients: Tunnels extra config file: ", it);
					ReadTunnels (it, numClientTunnels, numServerTunnels);
				}
			}
		}

		LogPrint (eLogInfo, "Clients: ", numClientTunnels, " I2P client tunnels created");
		LogPrint (eLogInfo, "Clients: ", numServerTunnels, " I2P server tunnels created");
	}

	void ClientContext::ReadTunnels (const std::string& tunConf, int& numClientTunnels, int& numServerTunnels)
	{
		boost::property_tree::ptree pt;
		try {
			boost::property_tree::read_ini (tunConf, pt);
		} catch (std::exception& ex) {
			LogPrint (eLogWarning, "Clients: Can't read ", tunConf, ": ", ex.what ());
			return;
		}

		std::map<std::string, std::shared_ptr<ClientDestination> > destinations; // keys -> destination
		for (auto& section: pt)
		{
			std::string name = section.first;
			try
			{
				std::string type = section.second.get<std::string> (I2P_TUNNELS_SECTION_TYPE);
				if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT
					|| type == I2P_TUNNELS_SECTION_TYPE_SOCKS
					|| type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS
					|| type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY
					|| type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
				{
					// mandatory params
					std::string dest;
					if (type == I2P_TUNNELS_SECTION_TYPE_CLIENT || type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT)
						dest = section.second.get<std::string> (I2P_CLIENT_TUNNEL_DESTINATION);
					int port = section.second.get<int> (I2P_CLIENT_TUNNEL_PORT);
					// optional params
					bool matchTunnels = section.second.get(I2P_CLIENT_TUNNEL_MATCH_TUNNELS, false);
					std::string keys = section.second.get (I2P_CLIENT_TUNNEL_KEYS, "transient");
					std::string address = section.second.get (I2P_CLIENT_TUNNEL_ADDRESS, "127.0.0.1");
					int destinationPort = section.second.get (I2P_CLIENT_TUNNEL_DESTINATION_PORT, 0);
					i2p::data::SigningKeyType sigType = section.second.get (I2P_CLIENT_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519);
					i2p::data::CryptoKeyType cryptoType = section.second.get (I2P_CLIENT_TUNNEL_CRYPTO_TYPE, i2p::data::CRYPTO_KEY_TYPE_ELGAMAL);
					// I2CP
					std::map<std::string, std::string> options;
					ReadI2CPOptions (section, false, options);

					std::shared_ptr<ClientDestination> localDestination = nullptr;
					if (keys.length () > 0)
					{
						auto it = destinations.find (keys);
						if (it != destinations.end ())
							localDestination = it->second;
						else
						{
							i2p::data::PrivateKeys k;
							if(LoadPrivateKeys (k, keys, sigType, cryptoType))
							{
								localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
								if (!localDestination)
								{
									if(matchTunnels)
										localDestination = CreateNewMatchedTunnelDestination(k, dest, &options);
									else
										localDestination = CreateNewLocalDestination (k, type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT, &options);
									if (keys != "transient")
										destinations[keys] = localDestination;
								}
							}
						}
					}

					if (type == I2P_TUNNELS_SECTION_TYPE_UDPCLIENT) {
						// udp client
						// TODO: hostnames
						boost::asio::ip::udp::endpoint end (boost::asio::ip::address::from_string(address), port);
						if (!localDestination)
							localDestination = m_SharedLocalDestination;

						bool gzip = section.second.get (I2P_CLIENT_TUNNEL_GZIP, true);
						auto clientTunnel = std::make_shared<I2PUDPClientTunnel> (name, dest, end, localDestination, destinationPort, gzip);

						auto ins = m_ClientForwards.insert (std::make_pair (end, clientTunnel));
						if (ins.second)
						{
							clientTunnel->Start ();
							numClientTunnels++;
						}
						else
						{
							// TODO: update
							if (ins.first->second->GetLocalDestination () != clientTunnel->GetLocalDestination ())
							{
								LogPrint (eLogInfo, "Clients: I2P UDP client tunnel destination updated");
								ins.first->second->Stop ();
								ins.first->second->SetLocalDestination (clientTunnel->GetLocalDestination ());
								ins.first->second->Start ();
							}
							ins.first->second->isUpdated = true;
							LogPrint(eLogError, "Clients: I2P Client forward for endpoint ", end, " already exists");
						}

					} else {
						boost::asio::ip::tcp::endpoint clientEndpoint;
						std::shared_ptr<I2PService> clientTunnel;
						if (type == I2P_TUNNELS_SECTION_TYPE_SOCKS)
						{
							// socks proxy
							std::string outproxy = section.second.get("outproxy", "");
							auto tun = std::make_shared<i2p::proxy::SOCKSProxy>(name, address, port, !outproxy.empty(), outproxy, destinationPort, localDestination);
							clientTunnel = tun;
							clientEndpoint = tun->GetLocalEndpoint ();
						}
						else if (type == I2P_TUNNELS_SECTION_TYPE_HTTPPROXY)
						{
							// http proxy
							std::string outproxy = section.second.get("outproxy", "");
							bool addresshelper = section.second.get("addresshelper", true);
							auto tun = std::make_shared<i2p::proxy::HTTPProxy>(name, address, port, outproxy, addresshelper, localDestination);
							clientTunnel = tun;
							clientEndpoint = tun->GetLocalEndpoint ();
						}
						else if (type == I2P_TUNNELS_SECTION_TYPE_WEBSOCKS)
						{
							LogPrint(eLogWarning, "Clients: I2P Client tunnel websocks is deprecated, not starting ", name, " tunnel");
							continue;
						}
						else
						{
							// tcp client
							auto tun = std::make_shared<I2PClientTunnel> (name, dest, address, port, localDestination, destinationPort);
							clientTunnel = tun;
							clientEndpoint = tun->GetLocalEndpoint ();

							uint32_t keepAlive = section.second.get<uint32_t>(I2P_CLIENT_TUNNEL_KEEP_ALIVE_INTERVAL, 0);
							if (keepAlive)
							{
								tun->SetKeepAliveInterval (keepAlive);
								LogPrint(eLogInfo, "Clients: I2P Client tunnel keep alive interval set to ", keepAlive);
							}
						}

						uint32_t timeout = section.second.get<uint32_t>(I2P_CLIENT_TUNNEL_CONNECT_TIMEOUT, 0);
						if(timeout)
						{
							clientTunnel->SetConnectTimeout(timeout);
							LogPrint(eLogInfo, "Clients: I2P Client tunnel connect timeout set to ", timeout);
						}

						auto ins = m_ClientTunnels.insert (std::make_pair (clientEndpoint, clientTunnel));
						if (ins.second)
						{
							clientTunnel->Start ();
							numClientTunnels++;
						}
						else
						{
							// TODO: update
							if (ins.first->second->GetLocalDestination () != clientTunnel->GetLocalDestination ())
							{
								LogPrint (eLogInfo, "Clients: I2P client tunnel destination updated");
								ins.first->second->Stop ();
								ins.first->second->SetLocalDestination (clientTunnel->GetLocalDestination ());
								ins.first->second->Start ();
							}
							ins.first->second->isUpdated = true;
							LogPrint (eLogInfo, "Clients: I2P client tunnel for endpoint ", clientEndpoint, " already exists");
						}
					}
				}

				else if (type == I2P_TUNNELS_SECTION_TYPE_SERVER
					|| type == I2P_TUNNELS_SECTION_TYPE_HTTP
					|| type == I2P_TUNNELS_SECTION_TYPE_IRC
					|| type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
				{
					// mandatory params
					std::string host = section.second.get<std::string> (I2P_SERVER_TUNNEL_HOST);
					int port = section.second.get<int> (I2P_SERVER_TUNNEL_PORT);
					std::string keys = section.second.get<std::string> (I2P_SERVER_TUNNEL_KEYS);
					// optional params
					int inPort = section.second.get (I2P_SERVER_TUNNEL_INPORT, 0);
					std::string accessList = section.second.get (I2P_SERVER_TUNNEL_ACCESS_LIST, "");
					if(accessList == "")
						accessList=section.second.get (I2P_SERVER_TUNNEL_WHITE_LIST, "");
					std::string hostOverride = section.second.get (I2P_SERVER_TUNNEL_HOST_OVERRIDE, "");
					std::string webircpass = section.second.get<std::string> (I2P_SERVER_TUNNEL_WEBIRC_PASSWORD, "");
					bool gzip = section.second.get (I2P_SERVER_TUNNEL_GZIP, false);
					i2p::data::SigningKeyType sigType = section.second.get (I2P_SERVER_TUNNEL_SIGNATURE_TYPE, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519);
					i2p::data::CryptoKeyType cryptoType = section.second.get (I2P_CLIENT_TUNNEL_CRYPTO_TYPE, i2p::data::CRYPTO_KEY_TYPE_ELGAMAL);

					std::string address = section.second.get<std::string> (I2P_SERVER_TUNNEL_ADDRESS, "");
					bool isUniqueLocal = section.second.get(I2P_SERVER_TUNNEL_ENABLE_UNIQUE_LOCAL, true);
					bool ssl = section.second.get(I2P_SERVER_TUNNEL_SSL, false);

					// I2CP
					std::map<std::string, std::string> options;
					ReadI2CPOptions (section, true, options);

					std::shared_ptr<ClientDestination> localDestination = nullptr;
					auto it = destinations.find (keys);
					if (it != destinations.end ())
					{
						localDestination = it->second;
						localDestination->SetPublic (true);
					}
					else
					{
						i2p::data::PrivateKeys k;
						if(!LoadPrivateKeys (k, keys, sigType, cryptoType))
							continue;
						localDestination = FindLocalDestination (k.GetPublic ()->GetIdentHash ());
						if (!localDestination)
						{
							localDestination = CreateNewLocalDestination (k, true, &options);
							destinations[keys] = localDestination;
						}
						else
							localDestination->SetPublic (true);
					}
					if (type == I2P_TUNNELS_SECTION_TYPE_UDPSERVER)
					{
						// udp server tunnel
						// TODO: hostnames
						boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
						if (address.empty ())
						{
							if (!endpoint.address ().is_unspecified () && endpoint.address ().is_v6 ())
								address = "::1";
							else
								address = "127.0.0.1";
						}
						auto localAddress = boost::asio::ip::address::from_string(address);
						auto serverTunnel = std::make_shared<I2PUDPServerTunnel>(name, localDestination, localAddress, endpoint, port, gzip);
						if(!isUniqueLocal)
						{
							LogPrint(eLogInfo, "Clients: Disabling loopback address mapping");
							serverTunnel->SetUniqueLocal(isUniqueLocal);
						}
						std::lock_guard<std::mutex> lock(m_ForwardsMutex);
						auto ins = m_ServerForwards.insert(std::make_pair(
							std::make_pair(localDestination->GetIdentHash(), port),
							serverTunnel));
						if (ins.second)
						{
							serverTunnel->Start();
							LogPrint(eLogInfo, "Clients: I2P Server Forward created for UDP Endpoint ", host, ":", port, " bound on ", address, " for ",localDestination->GetIdentHash().ToBase32());
						}
						else
						{
							ins.first->second->isUpdated = true;
							LogPrint(eLogError, "Clients: I2P Server Forward for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash()), "/", port, " already exists");
						}

						continue;
					}

					std::shared_ptr<I2PServerTunnel> serverTunnel;
					if (type == I2P_TUNNELS_SECTION_TYPE_HTTP)
						serverTunnel = std::make_shared<I2PServerTunnelHTTP> (name, host, port, localDestination, hostOverride, inPort, gzip);
					else if (type == I2P_TUNNELS_SECTION_TYPE_IRC)
						serverTunnel = std::make_shared<I2PServerTunnelIRC> (name, host, port, localDestination, webircpass, inPort, gzip);
					else // regular server tunnel by default
						serverTunnel = std::make_shared<I2PServerTunnel> (name, host, port, localDestination, inPort, gzip);

					if (!address.empty ())
						serverTunnel->SetLocalAddress (address);
					if (!isUniqueLocal)
					{
						LogPrint(eLogInfo, "Clients: Disabling loopback address mapping");
						serverTunnel->SetUniqueLocal(isUniqueLocal);
					}
					if (ssl)
						serverTunnel->SetSSL (true);
					if (accessList.length () > 0)
					{
						std::set<i2p::data::IdentHash> idents;
						size_t pos = 0, comma;
						do
						{
							comma = accessList.find (',', pos);
							i2p::data::IdentHash ident;
							ident.FromBase32 (accessList.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos));
							idents.insert (ident);
							pos = comma + 1;
						}
						while (comma != std::string::npos);
						serverTunnel->SetAccessList (idents);
					}
					auto ins = m_ServerTunnels.insert (std::make_pair (
							std::make_pair (localDestination->GetIdentHash (), inPort),
							serverTunnel));
					if (ins.second)
					{
						serverTunnel->Start ();
						numServerTunnels++;
					}
					else
					{
						// TODO: update
						if (ins.first->second->GetLocalDestination () != serverTunnel->GetLocalDestination ())
						{
							LogPrint (eLogInfo, "Clients: I2P server tunnel destination updated");
							ins.first->second->Stop ();
							ins.first->second->SetLocalDestination (serverTunnel->GetLocalDestination ());
							ins.first->second->Start ();
						}
						ins.first->second->isUpdated = true;
						LogPrint (eLogInfo, "Clients: I2P server tunnel for destination/port ", m_AddressBook.ToAddress(localDestination->GetIdentHash ()), "/", inPort, " already exists");
					}

				}
				else
					LogPrint (eLogWarning, "Clients: Unknown section type = ", type, " of ", name, " in ", tunConf);
			}
			catch (std::exception& ex)
			{
				LogPrint (eLogError, "Clients: Can't read tunnel ", name, " params: ", ex.what ());
				ThrowFatal ("Unable to start tunnel ", name, ": ", ex.what ());
			}
		}
	}

	void ClientContext::ReadHttpProxy ()
	{
		std::shared_ptr<ClientDestination> localDestination;
		bool httproxy; i2p::config::GetOption("httpproxy.enabled", httproxy);
		if (httproxy)
		{
			std::string httpProxyKeys;         i2p::config::GetOption("httpproxy.keys",          httpProxyKeys);
			std::string httpProxyAddr;         i2p::config::GetOption("httpproxy.address",       httpProxyAddr);
			uint16_t    httpProxyPort;         i2p::config::GetOption("httpproxy.port",          httpProxyPort);
			std::string httpOutProxyURL;       i2p::config::GetOption("httpproxy.outproxy",      httpOutProxyURL);
			bool        httpAddresshelper;     i2p::config::GetOption("httpproxy.addresshelper", httpAddresshelper);
			if (httpAddresshelper)
				i2p::config::GetOption("addressbook.enabled", httpAddresshelper); // addresshelper is not supported without address book
			i2p::data::SigningKeyType sigType; i2p::config::GetOption("httpproxy.signaturetype", sigType);
			LogPrint(eLogInfo, "Clients: Starting HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort);
			if (httpProxyKeys.length () > 0)
			{
				i2p::data::PrivateKeys keys;
				if(LoadPrivateKeys (keys, httpProxyKeys, sigType))
				{
					std::map<std::string, std::string> params;
					ReadI2CPOptionsFromConfig ("httpproxy.", params);
					localDestination = CreateNewLocalDestination (keys, false, &params);
					if (localDestination) localDestination->Acquire ();
				}
				else
					LogPrint(eLogError, "Clients: Failed to load HTTP Proxy key");
			}
			try
			{
				m_HttpProxy = new i2p::proxy::HTTPProxy("HTTP Proxy", httpProxyAddr, httpProxyPort, httpOutProxyURL, httpAddresshelper, localDestination);
				m_HttpProxy->Start();
			}
			catch (std::exception& e)
			{
				LogPrint(eLogError, "Clients: Exception in HTTP Proxy: ", e.what());
				ThrowFatal ("Unable to start HTTP Proxy at ", httpProxyAddr, ":", httpProxyPort, ": ", e.what ());
			}
		}
	}

	void ClientContext::ReadSocksProxy ()
	{
		std::shared_ptr<ClientDestination> localDestination;
		bool socksproxy; i2p::config::GetOption("socksproxy.enabled", socksproxy);
		if (socksproxy)
		{
			std::string httpProxyKeys;         i2p::config::GetOption("httpproxy.keys",              httpProxyKeys);
			// we still need httpProxyKeys to compare with sockProxyKeys
			std::string socksProxyKeys;        i2p::config::GetOption("socksproxy.keys",             socksProxyKeys);
			std::string socksProxyAddr;        i2p::config::GetOption("socksproxy.address",          socksProxyAddr);
			uint16_t    socksProxyPort;        i2p::config::GetOption("socksproxy.port",             socksProxyPort);
			bool        socksOutProxy;         i2p::config::GetOption("socksproxy.outproxy.enabled", socksOutProxy);
			std::string socksOutProxyAddr;     i2p::config::GetOption("socksproxy.outproxy",         socksOutProxyAddr);
			uint16_t    socksOutProxyPort;     i2p::config::GetOption("socksproxy.outproxyport",     socksOutProxyPort);
			i2p::data::SigningKeyType sigType; i2p::config::GetOption("socksproxy.signaturetype",    sigType);
			LogPrint(eLogInfo, "Clients: Starting SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort);
			if (httpProxyKeys == socksProxyKeys && m_HttpProxy)
			{
				localDestination = m_HttpProxy->GetLocalDestination ();
				localDestination->Acquire ();
			}
			else if (socksProxyKeys.length () > 0)
			{
				i2p::data::PrivateKeys keys;
				if (LoadPrivateKeys (keys, socksProxyKeys, sigType))
				{
					std::map<std::string, std::string> params;
					ReadI2CPOptionsFromConfig ("socksproxy.", params);
					localDestination = CreateNewLocalDestination (keys, false, &params);
					if (localDestination) localDestination->Acquire ();
				}
				else
					LogPrint(eLogError, "Clients: Failed to load SOCKS Proxy key");
			}
			try
			{
				m_SocksProxy = new i2p::proxy::SOCKSProxy("SOCKS", socksProxyAddr, socksProxyPort,
					socksOutProxy, socksOutProxyAddr, socksOutProxyPort, localDestination);
				m_SocksProxy->Start();
			}
			catch (std::exception& e)
			{
				LogPrint(eLogError, "Clients: Exception in SOCKS Proxy: ", e.what());
				ThrowFatal ("Unable to start SOCKS Proxy at ", socksProxyAddr, ":", socksProxyPort, ": ", e.what ());
			}
		}
	}

	void ClientContext::ScheduleCleanupUDP()
	{
		if (m_CleanupUDPTimer)
		{
			// schedule cleanup in 17 seconds
			m_CleanupUDPTimer->expires_from_now (boost::posix_time::seconds (17));
			m_CleanupUDPTimer->async_wait(std::bind(&ClientContext::CleanupUDP, this, std::placeholders::_1));
		}
	}

	void ClientContext::CleanupUDP(const boost::system::error_code & ecode)
	{
		if(!ecode)
		{
			std::lock_guard<std::mutex> lock(m_ForwardsMutex);
			for (auto & s : m_ServerForwards ) s.second->ExpireStale();
			ScheduleCleanupUDP();
		}
	}

	void ClientContext::VisitTunnels (bool clean)
	{
		for (auto it = m_ClientTunnels.begin (); it != m_ClientTunnels.end ();)
		{
			if(clean && !it->second->isUpdated) {
				it->second->Stop ();
				it = m_ClientTunnels.erase(it);
			} else {
				it->second->isUpdated = false;
				it++;
			}
		}

		for (auto it = m_ServerTunnels.begin (); it != m_ServerTunnels.end ();)
		{
			if(clean && !it->second->isUpdated) {
				it->second->Stop ();
				it = m_ServerTunnels.erase(it);
			} else {
				it->second->isUpdated = false;
				it++;
			}
		}

		// TODO: Write correct UDP tunnels stop
		for (auto it = m_ClientForwards.begin (); it != m_ClientForwards.end ();)
		{
			if(clean && !it->second->isUpdated) {
				it->second->Stop ();
				it = m_ClientForwards.erase(it);
			} else {
				it->second->isUpdated = false;
				it++;
			}
		}

		for (auto it = m_ServerForwards.begin (); it != m_ServerForwards.end ();)
		{
			if(clean && !it->second->isUpdated) {
				it->second->Stop ();
				it = m_ServerForwards.erase(it);
			} else {
				it->second->isUpdated = false;
				it++;
			}
		}
	}
}
}


text:
/**
 * Created by pvishn200 on 2/4/17.
Objective editable input.
 **/
(function ($) {
    "use strict";

    var Evaluation_criteria = function (options) {
        this.init('evaluation_criteria', options, Evaluation_criteria.defaults);
    };

    //inherit from Abstract input
    $.fn.editableutils.inherit(Evaluation_criteria, $.fn.editabletypes.abstractinput);

    $.extend(Evaluation_criteria.prototype, {
        /**
        Renders input from tpl

        @method render()
        **/
        render: function() {
           this.$input = this.$tpl.find('input');
        },

        /**
        Default method to show value in element. Can be overwritten by display option.

        @method value2html(value, element)
        **/
        value2html: function(value, element) {
            if(!value) {
                $(element).empty();
                return;
            }
            var html = $('
').text(value.evaluation_criterionId).html() + ', ' +
                $('
').text(value.evaluation_criterion).html() ;

            // $(element).html('');
            // $(element).html(html);
        },

        /**
        Gets value from element's html

        @method html2value(html)
        **/
        html2value: function(html) {
          /*
            you may write parsing method to get value by element's html
            e.g. "Moscow, st. Lenina, bld. 15" => {evaluation_criterionId: "Moscow", evaluation_criterion: "Lenina", criterion_percentage: "15"}
            but for complex structures it's not recommended.
            Better set value directly via javascript, e.g.
            editable({
                value: {
                    evaluation_criterionId: "Moscow",
                    evaluation_criterion: "Lenina",
                    criterion_percentage: "15"
                }
            });
          */
          return null;
        },

       /**
        Converts value to string.
        It is used in internal comparing (not for sending to server).

        @method value2str(value)
       **/
       value2str: function(value) {
           var str = '';
           if(value) {
               for(var k in value) {
                   str = str + k + ':' + value[k] + ';';
               }
           }
           return str;
       },

       /*
        Converts string to value. Used for reading value from 'data-value' attribute.

        @method str2value(str)
       */
       str2value: function(str) {
           /*
           this is mainly for parsing value defined in data-value attribute.
           If you will always set value by javascript, no need to overwrite it
           */
           return str;
       },

       /**
        Sets value of input.

        @method value2input(value)
        @param {mixed} value
       **/
       value2input: function(value) {
           if(!value) {
             return;
           }
           this.$input.filter('[name="evaluation_criterionId"]').val(value.evaluation_criterionId);
           this.$input.filter('[name="evaluation_criterion"]').val(value.evaluation_criterion);
       },

       /**
        Returns value of input.

        @method input2value()
       **/
       input2value: function() {
           return {
              evaluation_criterionId: this.$input.filter('[name="evaluation_criterionId"]').val(),
              evaluation_criterion: this.$input.filter('[name="evaluation_criterion"]').val()
           };
       },

        /**
        Activates input: sets focus on the first field.

        @method activate()
       **/
       activate: function() {
            this.$input.filter('[name="evaluation_criterionId"]').focus();
       },

       /**
        Attaches handler to submit form in case of 'showbuttons=false' mode

        @method autosubmit()
       **/
       autosubmit: function() {
           this.$input.keydown(function (e) {
                if (e.which === 13) {
                    $(this).closest('form').submit();
                }
           });
       }
    });

    Evaluation_criteria.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
        tpl: '
Eval Criterion Id: <input type="text" name="evaluation_criterionId" class="input-small" >
'+
             '
Criterion: <input type="text" name="evaluation_criterion" class="input-small">
',

        inputclass: ''
    });

    $.fn.editabletypes.evaluation_criteria = Evaluation_criteria;

}(window.jQuery));


text:
package de.pentasys.SilverPen.model.booking;

import java.text.SimpleDateFormat;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import de.pentasys.SilverPen.model.User;

/**
 * Einzelne Stundenbuchung
 */
@NamedQueries({
    @NamedQuery(name = "BookingItem.findAll", query = "SELECT b FROM BookingItem b"),
    @NamedQuery(name = "BookingItem.findByUser", query = "SELECT b FROM BookingItem b Where b.user = :user"),
    @NamedQuery(name = "BookingItem.findSpanByUser", query = "SELECT b FROM BookingItem b Where b.user = :user AND ((b.start < :spanStart  AND b.stop > :spanStop) OR ((b.start BETWEEN :spanStart AND :spanStop) OR (b.stop BETWEEN :spanStart AND :spanStop))) ORDER BY b.start"),
    @NamedQuery(name = "BookingItem.findSpanByUserOrderStop", query = "SELECT b FROM BookingItem b Where b.user = :user AND ((b.start < :spanStart  AND b.stop > :spanStop) OR ((b.start BETWEEN :spanStart AND :spanStop) OR (b.stop BETWEEN :spanStart AND :spanStop))) ORDER BY b.stop")

})
@Entity
@Table(name="BOOKINGITEM")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="BOOKING_TYPE", discriminatorType=DiscriminatorType.STRING)
public abstract class BookingItem {

	public static final String findAll = "BookingItem.findAll";
    public static final String findByUser = "BookingItem.findByUser";
    public static final String findSpanByUser = "BookingItem.findSpanByUser";
    public static final String findSpanByUserOrderStop = "BookingItem.findSpanByUserOrderStop";

    private double sumHours;

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable=false)
    private java.util.Date start;

    @Column(nullable=false)
    private java.util.Date stop;

    @Column
    private String description;

    @Column
    private String status;

    @ManyToOne
    private User user;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public java.util.Date getStart() {
        return start;
    }

    public void setStart(java.util.Date start) {
        this.start = start;
    }

    public java.util.Date getStop() {
        return stop;
    }

    public void setStop(java.util.Date stop) {
        this.stop = stop;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public double getSumHours() {
        return sumHours;
    }

    public void setSumHours(double sumHours) {
        this.sumHours = sumHours;
    }

    public double calculateTime() {
        double milliseconds = this.stop.getTime()-this.start.getTime();
        int minutes = (int) (milliseconds / (60 * 1000) % 60);
        int hours = (int) milliseconds / (60 * 60 * 1000) % 24;
        return hours + (double) minutes/60.0;
    }

    public String getWeekDay() {
        String sim = new SimpleDateFormat("EEEEE").format(this.getStart());
        return sim;
    }
}


text:
function Convert-EventLogObjectId4647
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        $Record,

        [Parameter(Mandatory = $true)]
        [System.Collections.Hashtable]
        $Map
    )

    $activity = Convert-EventLogObject -Record $Record -Map $Map

    # Grab record properties
    $recordUser     = $Record.Properties[2].Value + '\' + $Record.Properties[1].Value

    # Set default values
    $activity.Username     = $recordUser

    Write-Output $activity
}


text:
module Admin
  # Allow a user to view, create and edit case studies from within the admin
  # interface.
  #
  # @author Matthew Rayner
  # @since 0.1
  class CaseStudiesController < Admin::BaseController
    def index
      @case_studies = CaseStudy.all
    end

    def new
      @case_study = CaseStudy.new
    end

    def edit
      @case_study = CaseStudy.find_by id: params[:id]

      not_found if @case_study.nil?
    end

    def show
      @case_study = CaseStudy.find_by id: params[:id]

      not_found if @case_study.nil?
    end

    def create
      @case_study = CaseStudy.create(case_study_params)

      create_gallery_images if @case_study && valid_case_study?

      if valid_case_study?
        redirect_to admin_case_study_path(@case_study)
      else
        render 'admin/case_studies/new'
      end
    end

    def update
      @case_study = CaseStudy.find_by id: params[:id]
      not_found if @case_study.nil?

      @case_study.update(case_study_params)

      if valid_case_study?
        update_gallery_images

        create_gallery_images

        redirect_to admin_case_study_path(@case_study), notice: t('.success')
      else
        render 'admin/case_studies/edit'
      end
    end

    def destroy
      @case_study = CaseStudy.find_by id: params[:id]
      not_found if @case_study.nil?

      @case_study.destroy

      if @case_study.frozen?
        redirect_to admin_case_studies_path, notice: t('.success')
      else
        redirect_to admin_case_studies_path, alert: t('.error')
      end
    end

    private

    def case_study_params
      params.require(:case_study).permit(:title, :intro, :body, :header_image,
                                         :remove_header_image,
                                         skill_ids: [],
                                         gallery_images_attributes:
                                           [:id,
                                            :case_study_id, :image,
                                            :remove_image])
    end

    def create_gallery_images
      fetch_gallery_images.each do |image|
        @case_study.gallery_images.create!(image: image,
                                           case_study_id: @case_study.id)
      end
    end

    def update_gallery_images
      fetch_gallery_image_attributes.each do |image|
        image = image[1]

        if image[:remove_image] == '1'
          @gallery_image = CaseStudyGalleryImage.find_by(id: image[:id])
          @gallery_image.destroy unless @gallery_image.nil?
        end
      end
    end

    def valid_case_study?
      @case_study.valid?
    end

    def fetch_gallery_images
      params.fetch(:case_study_gallery_images, {}).fetch(:images, [])
    end

    def fetch_gallery_image_attributes
      params.fetch(:case_study, {}).fetch(:gallery_images_attributes, [])
    end
  end
end


text:
class GURL;
class Profile;

namespace content {
class SiteInstance;
class WebContents;
}

namespace tab_util {

// Helper to find the WebContents that originated the given request. Can be
// NULL if the tab has been closed or some other error occurs.
// Should only be called from the UI thread, since it accesses WebContents.
content::WebContents* GetWebContentsByID(int render_process_id,
                                         int render_view_id);

// Returns a new SiteInstance for WebUI and app URLs. Returns the SiteInstance
// for |source_contents| if it represents the same website as |url|. Returns
// NULL otherwise.
content::SiteInstance* GetSiteInstanceForNewTab(
    content::WebContents* source_contents,
    Profile* profile,
    const GURL& url);

}  // namespace tab_util

#endif  // CHROME_BROWSER_TAB_CONTENTS_TAB_UTIL_H_


text:
import React, { Component } from 'react';
import Section from 'shared/components/section/section';
import OutboundLink from 'shared/components/outboundLink/outboundLink';
import FeaturedJob from './featuredJob/featuredJob';
import FeaturedJobsData from './featuredJobs.json';
import styles from './jobs.css';

const zipRecruiterScript = document.createElement('script');

zipRecruiterScript.src = 'https://www.ziprecruiter.com/jobs-widget/pro/v2/63bjfya4arc58ywaxtvi8jkchvzymeep';

document.body.appendChild(zipRecruiterScript);

const initializeZipRecruiter = (zipsearch) => {
  const options = {
    container: 'zipsearch_container',
    alerts_api_key: 'mnsiawwpjgk5i4u42awbp5kdhs8gpy26',
    search: 'software engineer',
    jobs_per_page: '20',
    days_ago: '30',
    font_family: 'Tahoma'
  };
  zipsearch.init(options);
};

class Jobs extends Component {
  componentDidMount() {
    const tryRunInit = () => {
      if (window.zipsearch) {
        return initializeZipRecruiter(window.zipsearch);
      }
      return setTimeout(tryRunInit, 500);
    };
    tryRunInit();
  }

  render() {
    const featuredJobs = FeaturedJobsData
      .filter(job => job.status === 'active')
      .map(job => (
        <FeaturedJob
          key={`${Math.random()} + ${job.name} + ${job.sourceUrl}`}
          {...job}
        />
      ));

    return (

              {featuredJobs}

            Are you hiring? <OutboundLink href="mailto:kelly@operationcode.org" analyticsEventLabel="User clicked on Job Posting contact">Contact</OutboundLink> us to post your job opening with Operation Code!

    );
  }
}

export default Jobs;


text:
<?php

namespace Rhubarb\Leaf\Table\Leaves\Columns;

require_once __DIR__ . "/ModelColumn.php";

use Rhubarb\Crown\DateTime\RhubarbDateTime;

class DateColumn extends ModelColumn
{
    private $dateFormat;

    public function __construct($columnName, $label = "", $dateFormat = "jS F Y")
    {
        parent::__construct($columnName, $label);

        $this->dateFormat = $dateFormat;
    }

    protected function getFormattedValue($value)
    {
        if ($value instanceof RhubarbDateTime) {
            return $value->format($this->dateFormat);
        }

        return parent::getFormattedValue($value);
    }
}


text:
@interface CellEntity : NSManagedObject

@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * subTitle;
@property (nonatomic, retain) NSNumber * section;

@end


text:
<?php

if (!defined('W3TC')) {
    die();
}

/**
 * @see Microsoft_Http_Exception
 */
require_once 'Microsoft/Http/Exception.php';

/**
 * @category   Microsoft
 * @package    Microsoft_Http
 * @subpackage Client
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Microsoft_Http_Client_Exception extends Microsoft_Http_Exception
{}


text:
class GFSDK_SSAO_Context_D3D11;

namespace SceneEngine
{
    /// \defgroup AO Ambient Occlusion
    /// @{
    class AmbientOcclusionResources
    {
    public:
        class Desc
        {
        public:
            unsigned _width, _height;
            RenderCore::Metal::NativeFormat::Enum _destinationFormat;
            bool _useNormals;
            RenderCore::Metal::NativeFormat::Enum _normalsResolveFormat;
            Desc(   unsigned width, unsigned height,
                    RenderCore::Metal::NativeFormat::Enum destinationFormat,
                    bool useNormals,
                    RenderCore::Metal::NativeFormat::Enum normalsResolveFormat)
            {
                std::fill((char*)this, PtrAdd((char*)this, sizeof(*this)), 0);
                _width = width;
                _height = height;
                _destinationFormat = destinationFormat;
                _useNormals = useNormals;
                _normalsResolveFormat = normalsResolveFormat;
            }
        };

        intrusive_ptr<ID3D::Resource>           _aoTexture;
        RenderCore::Metal::RenderTargetView     _aoTarget;
        RenderCore::Metal::ShaderResourceView   _aoSRV;

        bool                                    _useNormals;
        RenderCore::Metal::NativeFormat::Enum   _normalsResolveFormat;
        intrusive_ptr<ID3D::Resource>           _resolvedNormals;
        RenderCore::Metal::ShaderResourceView   _resolvedNormalsSRV;

        struct ContextDeletor { void operator()(void* ptr); };
        std::unique_ptr<GFSDK_SSAO_Context_D3D11, ContextDeletor> _aoContext;

        AmbientOcclusionResources(const Desc& desc);
        ~AmbientOcclusionResources();
    };

    class LightingParserContext;
    void AmbientOcclusion_Render(   RenderCore::Metal::DeviceContext* context,
                                    LightingParserContext& parserContext,
                                    AmbientOcclusionResources& resources,
                                    RenderCore::Metal::ShaderResourceView& depthBuffer,
                                    RenderCore::Metal::ShaderResourceView* normalsBuffer,
                                    const RenderCore::Metal::ViewportDesc& mainViewport);
    /// @}
}


text:
#ifndef __OS_H__
#define __OS_H__

#include <stdarg.h>
#include "irq_user.h"
#include "longjmp.h"
#include "mm_id.h"

#define CATCH_EINTR(expr) while ((errno = 0, ((expr) < 0)) && (errno == EINTR))

#define OS_TYPE_FILE 1
#define OS_TYPE_DIR 2
#define OS_TYPE_SYMLINK 3
#define OS_TYPE_CHARDEV 4
#define OS_TYPE_BLOCKDEV 5
#define OS_TYPE_FIFO 6
#define OS_TYPE_SOCK 7

/* os_access() flags */
#define OS_ACC_F_OK    0       /* Test for existence.  */
#define OS_ACC_X_OK    1       /* Test for execute permission.  */
#define OS_ACC_W_OK    2       /* Test for write permission.  */
#define OS_ACC_R_OK    4       /* Test for read permission.  */
#define OS_ACC_RW_OK   (OS_ACC_W_OK | OS_ACC_R_OK) /* Test for RW permission */

#ifdef CONFIG_64BIT
#define OS_LIB_PATH	"/usr/lib64/"
#else
#define OS_LIB_PATH	"/usr/lib/"
#endif

/*
 * types taken from stat_file() in hostfs_user.c
 * (if they are wrong here, they are wrong there...).
 */
struct uml_stat {
	int                ust_dev;        /* device */
	unsigned long long ust_ino;        /* inode */
	int                ust_mode;       /* protection */
	int                ust_nlink;      /* number of hard links */
	int                ust_uid;        /* user ID of owner */
	int                ust_gid;        /* group ID of owner */
	unsigned long long ust_size;       /* total size, in bytes */
	int                ust_blksize;    /* blocksize for filesystem I/O */
	unsigned long long ust_blocks;     /* number of blocks allocated */
	unsigned long      ust_atime;      /* time of last access */
	unsigned long      ust_mtime;      /* time of last modification */
	unsigned long      ust_ctime;      /* time of last change */
};

struct openflags {
	unsigned int r : 1;
	unsigned int w : 1;
	unsigned int s : 1;	/* O_SYNC */
	unsigned int c : 1;	/* O_CREAT */
	unsigned int t : 1;	/* O_TRUNC */
	unsigned int a : 1;	/* O_APPEND */
	unsigned int e : 1;	/* O_EXCL */
	unsigned int cl : 1;    /* FD_CLOEXEC */
};

#define OPENFLAGS() ((struct openflags) { .r = 0, .w = 0, .s = 0, .c = 0, \
					  .t = 0, .a = 0, .e = 0, .cl = 0 })

static inline struct openflags of_read(struct openflags flags)
{
	flags.r = 1;
	return flags;
}

static inline struct openflags of_write(struct openflags flags)
{
	flags.w = 1;
	return flags;
}

static inline struct openflags of_rdwr(struct openflags flags)
{
	return of_read(of_write(flags));
}

static inline struct openflags of_set_rw(struct openflags flags, int r, int w)
{
	flags.r = r;
	flags.w = w;
	return flags;
}

static inline struct openflags of_sync(struct openflags flags)
{
	flags.s = 1;
	return flags;
}

static inline struct openflags of_create(struct openflags flags)
{
	flags.c = 1;
	return flags;
}

static inline struct openflags of_trunc(struct openflags flags)
{
	flags.t = 1;
	return flags;
}

static inline struct openflags of_append(struct openflags flags)
{
	flags.a = 1;
	return flags;
}

static inline struct openflags of_excl(struct openflags flags)
{
	flags.e = 1;
	return flags;
}

static inline struct openflags of_cloexec(struct openflags flags)
{
	flags.cl = 1;
	return flags;
}

/* file.c */
extern int os_stat_file(const char *file_name, struct uml_stat *buf);
extern int os_stat_fd(const int fd, struct uml_stat *buf);
extern int os_access(const char *file, int mode);
extern int os_set_exec_close(int fd);
extern int os_ioctl_generic(int fd, unsigned int cmd, unsigned long arg);
extern int os_get_ifname(int fd, char *namebuf);
extern int os_set_slip(int fd);
extern int os_mode_fd(int fd, int mode);

extern int os_seek_file(int fd, unsigned long long offset);
extern int os_open_file(const char *file, struct openflags flags, int mode);
extern int os_read_file(int fd, void *buf, int len);
extern int os_write_file(int fd, const void *buf, int count);
extern int os_file_size(const char *file, unsigned long long *size_out);
extern int os_file_modtime(const char *file, unsigned long *modtime);
extern int os_pipe(int *fd, int stream, int close_on_exec);
extern int os_set_fd_async(int fd);
extern int os_clear_fd_async(int fd);
extern int os_set_fd_block(int fd, int blocking);
extern int os_accept_connection(int fd);
extern int os_create_unix_socket(const char *file, int len, int close_on_exec);
extern int os_shutdown_socket(int fd, int r, int w);
extern void os_close_file(int fd);
extern int os_rcv_fd(int fd, int *helper_pid_out);
extern int create_unix_socket(char *file, int len, int close_on_exec);
extern int os_connect_socket(const char *name);
extern int os_file_type(char *file);
extern int os_file_mode(const char *file, struct openflags *mode_out);
extern int os_lock_file(int fd, int excl);
extern void os_flush_stdout(void);
extern int os_stat_filesystem(char *path, long *bsize_out,
			      long long *blocks_out, long long *bfree_out,
			      long long *bavail_out, long long *files_out,
			      long long *ffree_out, void *fsid_out,
			      int fsid_size, long *namelen_out,
			      long *spare_out);
extern int os_change_dir(char *dir);
extern int os_fchange_dir(int fd);
extern unsigned os_major(unsigned long long dev);
extern unsigned os_minor(unsigned long long dev);
extern unsigned long long os_makedev(unsigned major, unsigned minor);

/* start_up.c */
extern void os_early_checks(void);
extern void can_do_skas(void);
extern void os_check_bugs(void);
extern void check_host_supports_tls(int *supports_tls, int *tls_min);

/* mem.c */
extern int create_mem_file(unsigned long long len);

/* process.c */
extern unsigned long os_process_pc(int pid);
extern int os_process_parent(int pid);
extern void os_stop_process(int pid);
extern void os_kill_process(int pid, int reap_child);
extern void os_kill_ptraced_process(int pid, int reap_child);
extern long os_ptrace_ldt(long pid, long addr, long data);

extern int os_getpid(void);
extern int os_getpgrp(void);

extern void init_new_thread_signals(void);
extern int run_kernel_thread(int (*fn)(void *), void *arg, jmp_buf **jmp_ptr);

extern int os_map_memory(void *virt, int fd, unsigned long long off,
			 unsigned long len, int r, int w, int x);
extern int os_protect_memory(void *addr, unsigned long len,
			     int r, int w, int x);
extern int os_unmap_memory(void *addr, int len);
extern int os_drop_memory(void *addr, int length);
extern int can_drop_memory(void);
extern void os_flush_stdout(void);

/* execvp.c */
extern int execvp_noalloc(char *buf, const char *file, char *const argv[]);
/* helper.c */
extern int run_helper(void (*pre_exec)(void *), void *pre_data, char **argv);
extern int run_helper_thread(int (*proc)(void *), void *arg,
			     unsigned int flags, unsigned long *stack_out);
extern int helper_wait(int pid);

/* umid.c */
extern int umid_file_name(char *name, char *buf, int len);
extern int set_umid(char *name);
extern char *get_umid(void);

/* signal.c */
extern void timer_init(void);
extern void set_sigstack(void *sig_stack, int size);
extern void remove_sigstack(void);
extern void set_handler(int sig);
extern int change_sig(int signal, int on);
extern void block_signals(void);
extern void unblock_signals(void);
extern int get_signals(void);
extern int set_signals(int enable);

/* util.c */
extern void stack_protections(unsigned long address);
extern int raw(int fd);
extern void setup_machinename(char *machine_out);
extern void setup_hostinfo(char *buf, int len);
extern void os_dump_core(void) __attribute__ ((noreturn));
extern void um_early_printk(const char *s, unsigned int n);

/* time.c */
extern void idle_sleep(unsigned long long nsecs);
extern int set_interval(void);
extern int timer_one_shot(int ticks);
extern long long disable_timer(void);
extern void uml_idle_timer(void);
extern long long os_nsecs(void);

/* skas/mem.c */
extern long run_syscall_stub(struct mm_id * mm_idp,
			     int syscall, unsigned long *args, long expected,
			     void **addr, int done);
extern long syscall_stub_data(struct mm_id * mm_idp,
			      unsigned long *data, int data_count,
			      void **addr, void **stub_addr);
extern int map(struct mm_id * mm_idp, unsigned long virt,
	       unsigned long len, int prot, int phys_fd,
	       unsigned long long offset, int done, void **data);
extern int unmap(struct mm_id * mm_idp, unsigned long addr, unsigned long len,
		 int done, void **data);
extern int protect(struct mm_id * mm_idp, unsigned long addr,
		   unsigned long len, unsigned int prot, int done, void **data);

/* skas/process.c */
extern int is_skas_winch(int pid, int fd, void *data);
extern int start_userspace(unsigned long stub_stack);
extern int copy_context_skas0(unsigned long stack, int pid);
extern void userspace(struct uml_pt_regs *regs);
extern int map_stub_pages(int fd, unsigned long code, unsigned long data,
			  unsigned long stack);
extern void new_thread(void *stack, jmp_buf *buf, void (*handler)(void));
extern void switch_threads(jmp_buf *me, jmp_buf *you);
extern int start_idle_thread(void *stack, jmp_buf *switch_buf);
extern void initial_thread_cb_skas(void (*proc)(void *),
				 void *arg);
extern void halt_skas(void);
extern void reboot_skas(void);

/* irq.c */
extern int os_waiting_for_events(struct irq_fd *active_fds);
extern int os_create_pollfd(int fd, int events, void *tmp_pfd, int size_tmpfds);
extern void os_free_irq_by_cb(int (*test)(struct irq_fd *, void *), void *arg,
		struct irq_fd *active_fds, struct irq_fd ***last_irq_ptr2);
extern void os_free_irq_later(struct irq_fd *active_fds,
		int irq, void *dev_id);
extern int os_get_pollfd(int i);
extern void os_set_pollfd(int i, int fd);
extern void os_set_ioignore(void);

/* sigio.c */
extern int add_sigio_fd(int fd);
extern int ignore_sigio_fd(int fd);
extern void maybe_sigio_broken(int fd, int read);
extern void sigio_broken(int fd, int read);

/* sys-x86_64/prctl.c */
extern int os_arch_prctl(int pid, int code, unsigned long *addr);

/* tty.c */
extern int get_pty(void);

/* sys-$ARCH/task_size.c */
extern unsigned long os_get_top_address(void);

#endif


text:
@import "./../variables/dimens.css";
@import "./../variables/colors.css";

.issue-info {
  display: flex;
  flex-grow: 1;
  justify-content: flex-end;
  font-size: var(--small-text);
  color: var(--secondary-text-color);
}

.issue-info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.issue-popularity {
  align-self: center;
  flex-shrink: 0;
}

.material-icons-extended.issue-popularity__fire {
  font-size: 14px;
  color: hsl(0, 0%, 83%);
  margin: 0px -1px;
}

.issue-popularity[score='1'] .issue-popularity__fire:nth-child(-n+1) {
  color: var(--actionable-color, red);
}

.issue-popularity[score='2'] .issue-popularity__fire:nth-child(-n+2) {
  color: var(--actionable-color, red);
}

.issue-popularity[score='3'] .issue-popularity__fire:nth-child(-n+3) {
  color: var(--actionable-color, red);
}

.issue-popularity[score='4'] .issue-popularity__fire:nth-child(-n+4) {
  color: var(--actionable-color, red);
}


text:
package com.consol.citrus.dsl.builder;

import com.consol.citrus.TestAction;
import com.consol.citrus.actions.ReceiveMessageAction;
import com.consol.citrus.dsl.actions.DelegatingTestAction;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.http.message.HttpMessage;
import com.consol.citrus.message.MessageType;
import org.springframework.http.HttpMethod;

/**
 * @author Christoph Deppisch
 * @since 2.4
 */
public class HttpServerRequestActionBuilder extends ReceiveMessageBuilder<ReceiveMessageAction, HttpServerRequestActionBuilder> {

    /** Http message to send or receive */
    private HttpMessage httpMessage = new HttpMessage();

    /**
     * Default constructor using http client endpoint.
     * @param delegate
     * @param httpServer
     */
    public HttpServerRequestActionBuilder(DelegatingTestAction<TestAction> delegate, Endpoint httpServer) {
        super(delegate);
        delegate.setDelegate(new ReceiveMessageAction());
        getAction().setEndpoint(httpServer);
        message(httpMessage);
        messageType(MessageType.XML);
    }

    @Override
    protected void setPayload(String payload) {
        httpMessage.setPayload(payload);
    }

    /**
     * Sets the request path.
     * @param path
     * @return
     */
    public HttpServerRequestActionBuilder path(String path) {
        httpMessage.path(path);
        return this;
    }

    /**
     * Sets the request method.
     * @param method
     * @return
     */
    public HttpServerRequestActionBuilder method(HttpMethod method) {
        httpMessage.method(method);
        return this;
    }

    /**
     * Adds a query param to the request uri.
     * @param name
     * @param value
     * @return
     */
    public HttpServerRequestActionBuilder queryParam(String name, String value) {
        httpMessage.queryParam(name, value);
        return this;
    }

    /**
     * Sets the http version.
     * @param version
     * @return
     */
    public HttpServerRequestActionBuilder version(String version) {
        httpMessage.version(version);
        return this;
    }

    /**
     * Sets the request content type header.
     * @param contentType
     * @return
     */
    public HttpServerRequestActionBuilder contentType(String contentType) {
        httpMessage.contentType(contentType);
        return this;
    }

    /**
     * Sets the request accept header.
     * @param accept
     * @return
     */
    public HttpServerRequestActionBuilder accept(String accept) {
        httpMessage.accept(accept);
        return this;
    }
}


text:
package applog

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"sync"
	"sync/atomic"

	"github.com/pkg/errors"
	"github.com/tsuru/tsuru/log"
	tsuruNet "github.com/tsuru/tsuru/net"
	"github.com/tsuru/tsuru/servicemanager"
	appTypes "github.com/tsuru/tsuru/types/app"
)

type aggregatorLogService struct {
	base appTypes.AppLogService
}

func aggregatorAppLogService() (appTypes.AppLogService, error) {
	memory, err := memoryAppLogService()
	if err != nil {
		return nil, err
	}
	return &aggregatorLogService{
		base: memory,
	}, nil
}

func (s *aggregatorLogService) Instance() appTypes.AppLogService {
	return s.base
}

func (s *aggregatorLogService) Enqueue(entry *appTypes.Applog) error {
	return s.base.Enqueue(entry)
}

func (s *aggregatorLogService) Add(appName, message, source, unit string) error {
	return s.base.Add(appName, message, source, unit)
}

func (s *aggregatorLogService) List(args appTypes.ListLogArgs) ([]appTypes.Applog, error) {
	requests, err := buildInstanceRequests(args, false)
	if err != nil {
		return nil, errors.Wrapf(err, "[aggregator service]")
	}
	logsCh := make(chan []appTypes.Applog, len(requests))
	errCh := make(chan error, len(requests))
	wg := sync.WaitGroup{}
	for i := range requests {
		wg.Add(1)
		req := requests[i]
		go func() {
			defer wg.Done()
			logs, instanceErr := listRequest(req)
			if instanceErr != nil {
				errCh <- errors.Wrapf(instanceErr, "[log instance %v]", req.URL.Host)
				return
			}
			logsCh <- logs
		}()
	}
	wg.Wait()
	close(logsCh)
	close(errCh)
	err = <-errCh
	if err != nil {
		return nil, err
	}
	var allLogs []appTypes.Applog
	for logs := range logsCh {
		allLogs = append(allLogs, logs...)
	}
	sort.SliceStable(allLogs, func(i, j int) bool {
		return allLogs[i].Date.Before(allLogs[j].Date)
	})
	if args.Limit > 0 && len(allLogs) > args.Limit {
		allLogs = allLogs[len(allLogs)-args.Limit:]
	}
	return allLogs, nil
}

func (s *aggregatorLogService) Watch(args appTypes.ListLogArgs) (appTypes.LogWatcher, error) {
	args.Limit = -1
	requests, err := buildInstanceRequests(args, true)
	if err != nil {
		return nil, errors.Wrapf(err, "[aggregator service]")
	}
	logsCh := make(chan appTypes.Applog, 1000)
	var cancels []context.CancelFunc
	for i := range requests {
		ctx, cancel := context.WithCancel(context.Background())
		cancels = append(cancels, cancel)
		requests[i] = requests[i].WithContext(ctx)
	}
	watcher := &aggregateWatcher{channel: logsCh, cancels: cancels, quit: make(chan struct{})}
	for i := range requests {
		watcher.watchRequest(requests[i])
	}
	return watcher, nil
}

type aggregateWatcher struct {
	channel     chan appTypes.Applog
	quit        chan struct{}
	cancels     []context.CancelFunc
	wg          sync.WaitGroup
	closeCalled int32
}

func (w *aggregateWatcher) Chan() <-chan appTypes.Applog {
	return w.channel
}

func (w *aggregateWatcher) Close() {
	if atomic.AddInt32(&w.closeCalled, 1) != 1 {
		return
	}
	for _, cancel := range w.cancels {
		cancel()
	}
	close(w.quit)
	w.wg.Wait()
	close(w.channel)
}

func (w *aggregateWatcher) watchRequest(req *http.Request) {
	w.wg.Add(1)
	go func() {
		defer w.Close()
		defer w.wg.Done()
		err := w.goWatchRequest(req)
		if err != nil {
			log.Errorf("[watch log instance %v]: %v", req.URL.Host, err)
		}
	}()
}

func (w *aggregateWatcher) goWatchRequest(req *http.Request) error {
	rsp, err := tsuruNet.Dial15FullUnlimitedClient.Do(req)
	if err != nil {
		return errors.WithStack(err)
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != http.StatusOK {
		return errors.Errorf("invalid status code %v", rsp.StatusCode)
	}
	decoder := json.NewDecoder(rsp.Body)
	for {
		var logs []appTypes.Applog
		err = decoder.Decode(&logs)
		if err != nil {
			if err != io.EOF && err != context.Canceled {
				buffered, _ := ioutil.ReadAll(decoder.Buffered())
				return errors.Wrapf(err, "unable to parse as json: %q", string(buffered))
			}
			return nil
		}
		for _, log := range logs {
			select {
			case w.channel <- log:
			case <-w.quit:
				return nil
			}
		}
	}
}

func listRequest(req *http.Request) ([]appTypes.Applog, error) {
	rsp, err := tsuruNet.Dial15Full60ClientWithPool.Do(req)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	defer rsp.Body.Close()
	data, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	if rsp.StatusCode != http.StatusOK {
		return nil, errors.Errorf("invalid status code %v: %q", rsp.StatusCode, string(data))
	}
	var logs []appTypes.Applog
	err = json.Unmarshal(data, &logs)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to parse log %q", string(data))
	}
	return logs, nil
}

func buildInstanceRequests(args appTypes.ListLogArgs, follow bool) ([]*http.Request, error) {
	instances, err := servicemanager.InstanceTracker.LiveInstances()
	if err != nil {
		return nil, err
	}
	var requests []*http.Request
	for _, instance := range instances {
		if len(instance.Addresses) == 0 {
			continue
		}
		ipAddr := instance.Addresses[0]
		urlValues := url.Values{}
		urlValues.Add("lines", strconv.Itoa(args.Limit))
		urlValues.Add("source", args.Source)
		for _, u := range args.Units {
			urlValues.Add("unit", u)
		}
		urlValues.Add("invert-source", strconv.FormatBool(args.InvertSource))
		if follow {
			urlValues.Add("follow", "1")
		}
		u := fmt.Sprintf("http://%s:%s/apps/%s/log-instance?%s", ipAddr, instance.Port, args.AppName, urlValues.Encode())
		req, err := http.NewRequest(http.MethodGet, u, nil)
		if err != nil {
			return nil, err
		}
		if args.Token != nil {
			req.Header.Set("Authorization", "Bearer "+args.Token.GetValue())
		}
		requests = append(requests, req)
	}
	return requests, nil
}


text:
package com.rtg.reader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import com.rtg.util.diagnostic.Diagnostic;

/**
 * Process elements in an iterator in chunks.
 */
class BatchProcessor<T> {
  private final Function<Batch<T>, FutureTask<?>> mRunnableSupplier;
  private final int mBatchSize;
  private final int mThreads;

  BatchProcessor(Function<Batch<T>, FutureTask<?>> runnableSupplier, int threads, int batchSize) {
    mRunnableSupplier = runnableSupplier;
    mThreads = threads;
    mBatchSize = batchSize;
  }

  void process(Iterator<T> iterator) {
    final ExecutorService stp = new BlockingExecutor(mThreads, 3);
    ArrayList<T> batch = new ArrayList<>(mBatchSize);
    int batchNumber = 0;
    while (true) {
      if (!iterator.hasNext()) {
        break;
      }
      batch.add(iterator.next());

      if (batch.size() >= mBatchSize) {
        Diagnostic.developerLog("Enqueuing batch of " + batch.size());
        stp.execute(mRunnableSupplier.apply(new Batch<>(batchNumber++, batch)));
        batch = new ArrayList<>(mBatchSize);
      }
    }
    if (batch.size() > 0) {
      Diagnostic.developerLog("Enqueuing batch of " + batch.size());
      stp.execute(mRunnableSupplier.apply(new Batch<>(batchNumber, batch)));
    }
    stp.shutdown();
    try {
      stp.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
      Diagnostic.userLog("InterruptedException whilst waiting for jobs to finish. " + e.getMessage());
    }
  }
}


text:
namespace NativeCode.WordPressJson.Models
{
    using Newtonsoft.Json;

    public class Icon
    {
        [JsonProperty("img")]
        public string ImageFileName { get; set; }

        [JsonProperty("ico")]
        public string IconFileName { get; set; }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

Home | About


text:
package net.jxta.impl.endpoint.endpointMeter;

import net.jxta.document.Element;
import net.jxta.document.TextElement;
import net.jxta.id.IDFactory;
import net.jxta.meter.MonitorResources;
import net.jxta.meter.ServiceMonitorFilter;
import net.jxta.platform.ModuleClassID;
import net.jxta.util.documentSerializable.DocumentSerializableUtilities;
import net.jxta.util.documentSerializable.DocumentSerializationException;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;

public class EndpointServiceMonitorFilter implements ServiceMonitorFilter {
    // private boolean reportAllEndpoints = true;
    private ModuleClassID moduleClassID = MonitorResources.endpointServiceMonitorClassID;

    private boolean includeOutboundMetrics = true;
    private boolean includeInboundMetrics = true;
    private boolean includePropagateMetrics = true;

    public EndpointServiceMonitorFilter() {}

    public EndpointServiceMonitorFilter(boolean includeInboundMetrics, boolean includeOutboundMetrics, boolean includePropagateMetrics) {
        this.includeInboundMetrics = includeInboundMetrics;
        this.includeOutboundMetrics = includeOutboundMetrics;
        this.includePropagateMetrics = includePropagateMetrics;
    }

    public void init(ModuleClassID moduleClassID) {
        this.moduleClassID = moduleClassID;
    }

    public void setIncludeInboundMetrics(boolean metrics) {
        includeInboundMetrics = metrics;
    }

    public void setIncludeOutboundMetrics(boolean metrics) {
        includeOutboundMetrics = metrics;
    }

    public void setIncludePropagateMetrics(boolean metrics) {
        includePropagateMetrics = metrics;
    }

    public boolean isIncludeOutboundMetrics() {
        return includeOutboundMetrics;
    }

    public boolean isIncludeInboundMetrics() {
        return includeInboundMetrics;
    }

    public boolean isIncludePropagateMetrics() {
        return includePropagateMetrics;
    }

    public ModuleClassID getModuleClassID() {
        return moduleClassID;
    }

    public void serializeTo(Element element) throws DocumentSerializationException {
        DocumentSerializableUtilities.addBoolean(element, "includeOutboundMetrics", includeOutboundMetrics);
        DocumentSerializableUtilities.addBoolean(element, "includeInboundMetrics", includeInboundMetrics);
        DocumentSerializableUtilities.addBoolean(element, "includePropagateMetrics", includePropagateMetrics);
        if (moduleClassID != null) {
            DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString());
        }
    }

    public void initializeFrom(Element element) throws DocumentSerializationException {
        for (Enumeration e = element.getChildren(); e.hasMoreElements();) {
            Element childElement = (TextElement) e.nextElement();
            String tagName = (String) childElement.getKey();

            if (tagName.equals("includeOutboundMetrics")) {
                includeOutboundMetrics = DocumentSerializableUtilities.getBoolean(childElement);
            }
            if (tagName.equals("includeInboundMetrics")) {
                includeInboundMetrics = DocumentSerializableUtilities.getBoolean(childElement);
            }
            if (tagName.equals("includePropagateMetrics")) {
                includePropagateMetrics = DocumentSerializableUtilities.getBoolean(childElement);
            }

            if (tagName.equals("moduleClassID")) {
                try {
                    moduleClassID = (ModuleClassID) IDFactory.fromURI(
                            new URI(DocumentSerializableUtilities.getString(childElement)));
                } catch (URISyntaxException jex) {
                    throw new DocumentSerializationException("Couldn't uderstand ModuleClassID", jex);
                }
            }
        }
    }

}


text:
package org.ethereum.net.rlpx.discover;

import org.apache.commons.codec.binary.Hex;
import org.ethereum.config.SystemProperties;
import org.ethereum.manager.WorldManager;
import org.ethereum.net.rlpx.Node;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;

/**
 * Makes test RLPx connection to the peers to acquire statistics
 *
 * Created by Anton Nashatyrev on 17.07.2015.
 */
@Component
public class PeerConnectionTester {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover");

    private int ConnectThreads;
    private long ReconnectPeriod;
    private long ReconnectMaxPeers;

    @Autowired
    private WorldManager worldManager;

    @Autowired
    SystemProperties config = SystemProperties.CONFIG;

    // NodeHandler instance should be unique per Node instance
    private Map<NodeHandler, ?> connectedCandidates = Collections.synchronizedMap(new IdentityHashMap());

    // executor with Queue which picks up the Node with the best reputation
    private ExecutorService peerConnectionPool;

    private Timer reconnectTimer = new Timer("DiscoveryReconnectTimer");
    private int reconnectPeersCount = 0;

    private class ConnectTask implements Runnable {
        NodeHandler nodeHandler;

        public ConnectTask(NodeHandler nodeHandler) {
            this.nodeHandler = nodeHandler;
        }

        @Override
        public void run() {
            try {
                if (nodeHandler != null) {
                    nodeHandler.getNodeStatistics().rlpxConnectionAttempts.add();
                    logger.debug("Trying node connection: " + nodeHandler);
                    Node node = nodeHandler.getNode();
                    worldManager.getActivePeer().connect(node.getHost(), node.getPort(),
                            Hex.encodeHexString(node.getId()), true);
                    logger.debug("Terminated node connection: " + nodeHandler);
                    nodeHandler.getNodeStatistics().disconnected();
                    if (!nodeHandler.getNodeStatistics().getEthTotalDifficulty().equals(BigInteger.ZERO) &&
                            ReconnectPeriod > 0 && (reconnectPeersCount < ReconnectMaxPeers || ReconnectMaxPeers == -1)) {
                        // trying to keep good peers information up-to-date
                        reconnectPeersCount++;
                        reconnectTimer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                logger.debug("Trying the node again: " + nodeHandler);
                                peerConnectionPool.execute(new ConnectTask(nodeHandler));
                                reconnectPeersCount--;
                            }
                        }, ReconnectPeriod);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connectedCandidates.remove(nodeHandler);
            }
        }
    }

    public PeerConnectionTester() {
    }

    @PostConstruct
    void init() {
        ConnectThreads = config.peerDiscoveryWorkers();
        ReconnectPeriod = config.peerDiscoveryTouchPeriod() * 1000;
        ReconnectMaxPeers = config.peerDiscoveryTouchMaxNodes();
        peerConnectionPool = new ThreadPoolExecutor(ConnectThreads,
                ConnectThreads, 0L, TimeUnit.SECONDS,
                new MutablePriorityQueue<Runnable, ConnectTask>(new Comparator<ConnectTask>() {
                    @Override
                    public int compare(ConnectTask h1, ConnectTask h2) {
                        return h2.nodeHandler.getNodeStatistics().getReputation() -
                                h1.nodeHandler.getNodeStatistics().getReputation();
                    }
                }));
    }

    public void nodeStatusChanged(final NodeHandler nodeHandler) {
        if (connectedCandidates.size() < NodeManager.MAX_NODES && !connectedCandidates.containsKey(nodeHandler)) {
            logger.debug("Submitting node for RLPx connection : " + nodeHandler);
            connectedCandidates.put(nodeHandler, null);
            peerConnectionPool.execute(new ConnectTask(nodeHandler));
        }
    }

    /**
     * The same as PriorityBlockQueue but with assumption that elements are mutable
     * and priority changes after enqueueing, thus the list is sorted by priority
     * each time the head queue element is requested.
     * The class has poor synchronization since the prioritization might be approximate
     * though the implementation should be inheritedly thread-safe
     */
    public static class MutablePriorityQueue<T, C extends T> extends LinkedBlockingQueue<T> {
        Comparator<C> comparator;

        public MutablePriorityQueue(Comparator<C> comparator) {
            this.comparator = comparator;
        }

        @Override
        public T take() throws InterruptedException {
            if (isEmpty()) {
                return super.take();
            } else {
                T ret = Collections.min(this, (Comparator<? super T>) comparator);
                remove(ret);
                return ret;
            }
        }

        @Override
        public T poll(long timeout, TimeUnit unit) throws InterruptedException {
            if (isEmpty()) {
                return super.poll(timeout, unit);
            } else {
                T ret = Collections.min(this, (Comparator<? super T>) comparator);
                remove(ret);
                return ret;
            }
        }

        @Override
        public T poll() {
            if (isEmpty()) {
                return super.poll();
            } else {
                T ret = Collections.min(this, (Comparator<? super T>) comparator);
                remove(ret);
                return ret;
            }
        }

        @Override
        public T peek() {
            if (isEmpty()) {
                return super.peek();
            } else {
                T ret = Collections.min(this, (Comparator<? super T>) comparator);
                return ret;
            }
        }
    }

}


text: An online app to create and solve crossword puzzles