text:
@echo off

REM Set this to point to the Windows SDK version where fxc is located
REM Recommend Windows SDK 8.1 or higher.
set windows_sdk=8.1

REM Batch file for compiling the TressFX library shaders
echo --- Compiling shaders for TressFX ---

set startdir=%cd%
cd "%~dp0"

set fxc_exe=%ProgramFiles(x86)%\Windows Kits\%windows_sdk%\bin\x86\fxc.exe

REM If fxc.exe exists in the same directory as the batch file, it will be used instead
if exist .\fxc.exe set fxc_exe=.\fxc.exe

echo --- Using "%fxc_exe%" ---

REM TressFXRender Vertex Shaders
"%fxc_exe%" /nologo /T vs_5_0 /E VS_RenderHair /O1 /Fh ..\inc\VS_RenderHair.inc /Vn VS_RenderHair_Data ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T vs_5_0 /E VS_RenderHair_AA /O1 /Fh ..\inc\VS_RenderHair_AA.inc /Vn VS_RenderHair_AA_Data ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T vs_5_0 /E VS_GenerateHairSM /O1 /Fh ..\inc\VS_GenerateHairSM.inc /Vn VS_GenerateHairSM_Data ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T vs_5_0 /E VS_RenderHair_StrandCopies /O1 /Fh ..\inc\VS_RenderHair_StrandCopies.inc /Vn VS_RenderHair_StrandCopies_Data ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T vs_5_0 /E VS_RenderHair_AA_StrandCopies /O1 /Fh ..\inc\VS_RenderHair_AA_StrandCopies.inc /Vn VS_RenderHair_AA_StrandCopies_Data ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T vs_5_0 /E VS_ScreenQuad /O1 /Fh ..\inc\VS_ScreenQuad.inc /Vn VS_ScreenQuad_Data ..\TressFXRender.hlsl

REM TressFXRender Pixel Shaders
"%fxc_exe%" /nologo /T ps_5_0 /E PS_ABuffer_Hair /O1 /Fh ..\inc\PS_ABuffer_Hair.inc /Vn PS_ABuffer_Hair_Data  ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T ps_5_0 /E PS_KBuffer_Hair /O1 /Fh ..\inc\PS_KBuffer_Hair.inc /Vn PS_KBuffer_Hair_Data  ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T ps_5_0 /E PS_Depth_Hair /O1 /Fh ..\inc\PS_Depth_Hair.inc /Vn PS_Depth_Hair_Data  ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T ps_5_0 /E PS_FillColors_Hair /O1 /Fh ..\inc\PS_FillColors_Hair.inc /Vn PS_FillColors_Hair_Data  ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T ps_5_0 /E PS_ResolveDepth_Hair /O1 /Fh ..\inc\PS_ResolveDepth_Hair.inc /Vn PS_ResolveDepth_Hair_Data  ..\TressFXRender.hlsl
"%fxc_exe%" /nologo /T ps_5_0 /E PS_ResolveColor_Hair /O1 /Fh ..\inc\PS_ResolveColor_Hair.inc /Vn PS_ResolveColor_Hair_Data  ..\TressFXRender.hlsl

REM TressFXSimulation Compute Shaders
"%fxc_exe%" /nologo /T cs_5_0 /E IntegrationAndGlobalShapeConstraints /O1 /Fh ..\inc\IntegrationAndGlobalShapeConstraints.inc /Vn IntegrationAndGlobalShapeConstraints_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E ApplyHairTransformGlobally /O1 /Fh ..\inc\ApplyHairTransformGlobally.inc /Vn ApplyHairTransformGlobally_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E ComputeTangents /O1 /Fh ..\inc\ComputeTangents.inc /Vn ComputeTangents_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E LocalShapeConstraints /O1 /Fh ..\inc\LocalShapeConstraints.inc /Vn LocalShapeConstraints_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E LocalShapeConstraintsWithIteration /O1 /Fh ..\inc\LocalShapeConstraintsWithIteration.inc /Vn LocalShapeConstraintsWithIteration_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E LengthConstraintsWindAndCollision /O1 /Fh ..\inc\LengthConstraintsWindAndCollision.inc /Vn LengthConstraintsWindAndCollision_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E UpdateFollowHairVertices /O1 /Fh ..\inc\UpdateFollowHairVertices.inc /Vn UpdateFollowHairVertices_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E PrepareFollowHairBeforeTurningIntoGuide /O1 /Fh ..\inc\PrepareFollowHairBeforeTurningIntoGuide.inc /Vn PrepareFollowHairBeforeTurningIntoGuide_Data  ..\TressFXSimulation.hlsl
"%fxc_exe%" /nologo /T cs_5_0 /E GenerateTransforms /O1 /Fh ..\inc\GenerateTransforms.inc /Vn GenerateTransforms_Data  ..\TressFXSimulation.hlsl

cd "%startdir%"
pause


text:
Rails.application.routes.draw do
  get '/t/:major(.:minor)(.:patch)', :to => 'templates#show'

  mount Refinery::Core::Engine, at: Refinery::Core.mounted_path
end

redpajama_set_name: RedPajamaGithub


text:
class ManageIQ::Providers::Amazon::NetworkManager::NetworkRouter < ::NetworkRouter
end


text:
using Blazored.LocalStorage;
using DX.Blazor.Identity.Models;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace DX.Blazor.Identity.Wasm.Services
{
    public class AuthenticationService : AuthenticationService<RegistrationModel>, IAuthService
    {
        public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider,
            ILocalStorageService localStorage)
            : base(client, authStateProvider, localStorage)
        {

        }
    }

    public class AuthenticationService<TRegistrationModel> : AuthenticationService<TRegistrationModel, AuthenticationModel>, IAuthService<TRegistrationModel>
        where TRegistrationModel : class, new()
    {
        public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider,
            ILocalStorageService localStorage)
            : base(client, authStateProvider, localStorage)
        {

        }
    }

    public class AuthenticationService<TRegistrationModel, TAuthenticationModel>
        : IAuthService<TRegistrationModel, TAuthenticationModel>
        where TRegistrationModel: class, new()
        where TAuthenticationModel : class, new()
    {
        const string authTokenName = "authToken";
        const string refreshTokenName = "refreshToken";
        const string registerEndpoint = "Accounts/Registration";
        const string loginEndpoint = "Accounts/Login";
        //const string logoutEndpoint = "Accounts/Logout";
        const string tokenRefreshEndpoint = "token/refresh";

        private readonly HttpClient _client;
        private readonly JsonSerializerOptions _options;
        private readonly AuthenticationStateProvider _authStateProvider;
        private readonly ILocalStorageService _localStorage;

        public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider,
            ILocalStorageService localStorage)
        {
            _client = client;
            _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _authStateProvider = authStateProvider;
            _localStorage = localStorage;
        }

        public async Task<RegistrationResponseModel> RegisterUser(TRegistrationModel userForRegistration)
        {
            var content = JsonSerializer.Serialize(userForRegistration);
            var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");

            var registrationResult = await _client.PostAsync(registerEndpoint, bodyContent);
            var registrationContent = await registrationResult.Content.ReadAsStringAsync();

            if (!registrationResult.IsSuccessStatusCode)
            {
                var result = JsonSerializer.Deserialize<RegistrationResponseModel>(registrationContent, _options);
                ArgumentNullException.ThrowIfNull(result);
                return result;
            }

            return new RegistrationResponseModel { IsSuccessfulRegistration = true };
        }

        public async Task<AuthResponseModel> Login(TAuthenticationModel userForAuthentication)
        {
            var content = JsonSerializer.Serialize(userForAuthentication);
            var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");

            var authResult = await _client.PostAsync(loginEndpoint, bodyContent);
            var authContent = await authResult.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<AuthResponseModel>(authContent, _options);

            ArgumentNullException.ThrowIfNull(result);

            if (!authResult.IsSuccessStatusCode)
                return result;

            await _localStorage.SetItemAsync(authTokenName, result.Token);
            await _localStorage.SetItemAsync(refreshTokenName, result.RefreshToken);
            ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(result.Token);
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);

            return new AuthResponseModel { IsAuthSuccessful = true };
        }

        public async Task<string> RefreshToken()
        {
            var token = await _localStorage.GetItemAsync<string>(authTokenName);
            var refreshToken = await _localStorage.GetItemAsync<string>(refreshTokenName);

            var refreshModel = JsonSerializer.Serialize(new RefreshTokenModel { Token = token, RefreshToken = refreshToken });
            var bodyContent = new StringContent(refreshModel, Encoding.UTF8, "application/json");

            var refreshResult = await _client.PostAsync(tokenRefreshEndpoint, bodyContent);
            var refreshContent = await refreshResult.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<AuthResponseModel>(refreshContent, _options);

            ArgumentNullException.ThrowIfNull(result);

            if (!refreshResult.IsSuccessStatusCode)
                throw new ApplicationException("Something went wrong during the refresh token action");

            await _localStorage.SetItemAsync(authTokenName, result.Token);
            await _localStorage.SetItemAsync(refreshTokenName, result.RefreshToken);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);
            return result.Token;
        }

        public async Task Logout()
        {
            await _localStorage.RemoveItemAsync(authTokenName);
            await _localStorage.RemoveItemAsync(refreshTokenName);
            ((AuthStateProvider)_authStateProvider).NotifyUserLogout();
            _client.DefaultRequestHeaders.Authorization = null;
        }

    }
}


text:
#include "FailoverTransport.h"

#include <activemq/commands/ConnectionControl.h>
#include <activemq/commands/ShutdownInfo.h>
#include <activemq/commands/RemoveInfo.h>
#include <activemq/transport/TransportRegistry.h>
#include <activemq/threads/DedicatedTaskRunner.h>
#include <activemq/threads/CompositeTaskRunner.h>
#include <activemq/transport/failover/BackupTransportPool.h>
#include <activemq/transport/failover/URIPool.h>
#include <activemq/transport/failover/FailoverTransportListener.h>
#include <activemq/transport/failover/CloseTransportsTask.h>
#include <activemq/transport/failover/URIPool.h>
#include <decaf/util/Random.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/util/LinkedList.h>
#include <decaf/util/StlMap.h>
#include <decaf/util/concurrent/TimeUnit.h>
#include <decaf/util/concurrent/Mutex.h>
#include <decaf/lang/System.h>
#include <decaf/lang/Integer.h>

using namespace std;
using namespace activemq;
using namespace activemq::state;
using namespace activemq::commands;
using namespace activemq::exceptions;
using namespace activemq::threads;
using namespace activemq::transport;
using namespace activemq::transport::failover;
using namespace decaf;
using namespace decaf::io;
using namespace decaf::net;
using namespace decaf::util;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;

////////////////////////////////////////////////////////////////////////////////
namespace activemq {
namespace transport {
namespace failover {

    class FailoverTransportImpl {
    private:

        FailoverTransportImpl(const FailoverTransportImpl&);
        FailoverTransportImpl& operator= (const FailoverTransportImpl&);

        static const int DEFAULT_INITIAL_RECONNECT_DELAY;
        static const int INFINITE_WAIT;

    public:

        bool closed;
        bool connected;
        bool started;

        long long timeout;
        long long initialReconnectDelay;
        long long maxReconnectDelay;
        long long backOffMultiplier;
        bool useExponentialBackOff;
        bool initialized;
        int maxReconnectAttempts;
        int startupMaxReconnectAttempts;
        int connectFailures;
        long long reconnectDelay;
        bool trackMessages;
        bool trackTransactionProducers;
        int maxCacheSize;
        int maxPullCacheSize;
        bool connectionInterruptProcessingComplete;
        bool firstConnection;
        bool updateURIsSupported;
        bool reconnectSupported;
        bool rebalanceUpdateURIs;
        bool priorityBackup;
        bool backupsEnabled;

        bool doRebalance;
        bool connectedToPrioirty;

        mutable Mutex reconnectMutex;
        mutable Mutex sleepMutex;
        mutable Mutex listenerMutex;

        StlMap<int, Pointer<Command> > requestMap;

        Pointer<URIPool> uris;
        Pointer<URIPool> priorityUris;
        Pointer<URIPool> updated;
        Pointer<URI> connectedTransportURI;
        Pointer<Transport> connectedTransport;
        Pointer<Exception> connectionFailure;
        Pointer<BackupTransportPool> backups;
        Pointer<CloseTransportsTask> closeTask;
        Pointer<CompositeTaskRunner> taskRunner;
        Pointer<TransportListener> disposedListener;
        Pointer<TransportListener> myTransportListener;

        TransportListener* transportListener;

        FailoverTransportImpl(FailoverTransport* parent) :
            closed(false),
            connected(false),
            started(false),
            timeout(INFINITE_WAIT),
            initialReconnectDelay(DEFAULT_INITIAL_RECONNECT_DELAY),
            maxReconnectDelay(1000*30),
            backOffMultiplier(2),
            useExponentialBackOff(true),
            initialized(false),
            maxReconnectAttempts(INFINITE_WAIT),
            startupMaxReconnectAttempts(INFINITE_WAIT),
            connectFailures(0),
            reconnectDelay(DEFAULT_INITIAL_RECONNECT_DELAY),
            trackMessages(false),
            trackTransactionProducers(true),
            maxCacheSize(128*1024),
            maxPullCacheSize(10),
            connectionInterruptProcessingComplete(false),
            firstConnection(true),
            updateURIsSupported(true),
            reconnectSupported(true),
            rebalanceUpdateURIs(true),
            priorityBackup(false),
            backupsEnabled(false),
            doRebalance(false),
            connectedToPrioirty(false),
            reconnectMutex(),
            sleepMutex(),
            listenerMutex(),
            requestMap(),
            uris(new URIPool()),
            priorityUris(new URIPool()),
            updated(new URIPool()),
            connectedTransportURI(),
            connectedTransport(),
            connectionFailure(),
            backups(),
            closeTask(new CloseTransportsTask()),
            taskRunner(new CompositeTaskRunner()),
            disposedListener(),
            myTransportListener(new FailoverTransportListener(parent)),
            transportListener(NULL) {

            this->backups.reset(
                new BackupTransportPool(parent, taskRunner, closeTask, uris, updated, priorityUris));

            this->taskRunner->addTask(parent);
            this->taskRunner->addTask(this->closeTask.get());
        }

        bool isPriority(const decaf::net::URI& uri) {
            return priorityUris->contains(uri) || uris->isPriority(uri);
        }

        Pointer<URIPool> getConnectList() {
            // Pick an appropriate URI pool, updated is always preferred if updates are
            // enabled and we have any, otherwise we fallback to our original list so that
            // we ensure we always try something.
            Pointer<URIPool> uris = this->uris;
            if (this->updateURIsSupported && !this->updated->isEmpty()) {
                uris = this->updated;
            }
            return uris;
        }

        void doDelay() {
            if (reconnectDelay > 0) {
                synchronized (&sleepMutex) {
                    try {
                        sleepMutex.wait(reconnectDelay);
                    } catch (InterruptedException& e) {
                        Thread::currentThread()->interrupt();
                    }
                }
            }

            if (useExponentialBackOff) {
                // Exponential increment of reconnect delay.
                reconnectDelay *= backOffMultiplier;
                if (reconnectDelay > maxReconnectDelay) {
                    reconnectDelay = maxReconnectDelay;
                }
            }
        }

        int calculateReconnectAttemptLimit() const {
            int maxReconnectValue = maxReconnectAttempts;
            if (firstConnection && startupMaxReconnectAttempts != INFINITE_WAIT) {
                maxReconnectValue = startupMaxReconnectAttempts;
            }
            return maxReconnectValue;
        }

        bool canReconnect() const {
            return started && 0 != calculateReconnectAttemptLimit();
        }

        /**
         * This must be called with the reconnect mutex locked.
         */
        void propagateFailureToExceptionListener() {
            if (this->transportListener != NULL) {

                Pointer<IOException> ioException;
                try {
                    ioException = this->connectionFailure.dynamicCast<IOException>();
                }
                AMQ_CATCH_NOTHROW( ClassCastException)

                if (ioException != NULL) {
                    transportListener->onException(*this->connectionFailure);
                } else {
                    transportListener->onException(IOException(*this->connectionFailure));
                }
            }

            reconnectMutex.notifyAll();
        }

        void resetReconnectDelay() {
            if (!useExponentialBackOff || reconnectDelay == DEFAULT_INITIAL_RECONNECT_DELAY) {
                reconnectDelay = initialReconnectDelay;
            }
        }

        bool isClosedOrFailed() const {
            return closed || connectionFailure != NULL;
        }

        bool isConnectionStateValid() const {
            return connectedTransport != NULL && !doRebalance && !this->backups->isPriorityBackupAvailable();
        }

        void disconnect() {
            Pointer<Transport> transport;
            transport.swap(this->connectedTransport);

            if (transport != NULL) {

                if (this->disposedListener != NULL) {
                    transport->setTransportListener(this->disposedListener.get());
                }

                // Hand off to the close task so it gets done in a different thread.
                this->closeTask->add(transport);

                if (this->connectedTransportURI != NULL) {
                    this->uris->addURI(*this->connectedTransportURI);
                    this->connectedTransportURI.reset(NULL);
                }
            }
        }

    };

    const int FailoverTransportImpl::DEFAULT_INITIAL_RECONNECT_DELAY = 10;
    const int FailoverTransportImpl::INFINITE_WAIT = -1;

}}}

////////////////////////////////////////////////////////////////////////////////
FailoverTransport::FailoverTransport() : stateTracker(), impl(NULL) {
    this->impl = new FailoverTransportImpl(this);
    this->stateTracker.setTrackTransactions(true);
}

////////////////////////////////////////////////////////////////////////////////
FailoverTransport::~FailoverTransport() {
    try {
        close();
    }
    AMQ_CATCHALL_NOTHROW()

    try {
        delete this->impl;
    }
    AMQ_CATCHALL_NOTHROW()
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::add(bool rebalance, const std::string& uri) {

    try {
        if (this->impl->uris->addURI(URI(uri))) {
            reconnect(rebalance);
        }
    }
    AMQ_CATCHALL_NOTHROW()
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::addURI(bool rebalance, const List<URI>& uris) {

    bool newUri = false;

    std::auto_ptr<Iterator<URI> > iter(uris.iterator());
    while (iter->hasNext()) {
        if (this->impl->uris->addURI(iter->next())) {
            newUri = true;
        }
    }

    if (newUri) {
        reconnect(rebalance);
    }
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::removeURI(bool rebalance, const List<URI>& uris) {

    bool changed = false;

    std::auto_ptr<Iterator<URI> > iter(uris.iterator());
    synchronized( &this->impl->reconnectMutex ) {
        while (iter->hasNext()) {
            if (this->impl->uris->removeURI(iter->next())) {
                changed = true;
            }
        }
    }

    if (changed) {
        reconnect(rebalance);
    }
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::reconnect(const decaf::net::URI& uri) {

    try {
        if (this->impl->uris->addURI(uri)) {
            reconnect(true);
        }
    }
    AMQ_CATCH_RETHROW(IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException)
    AMQ_CATCHALL_THROW(IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setTransportListener(TransportListener* listener) {
    synchronized( &this->impl->listenerMutex ) {
        this->impl->transportListener = listener;
        this->impl->listenerMutex.notifyAll();
    }
}

////////////////////////////////////////////////////////////////////////////////
TransportListener* FailoverTransport::getTransportListener() const {
    synchronized( &this->impl->listenerMutex ) {
        return this->impl->transportListener;
    }

    return NULL;
}

////////////////////////////////////////////////////////////////////////////////
std::string FailoverTransport::getRemoteAddress() const {
    synchronized( &this->impl->reconnectMutex ) {
        if (this->impl->connectedTransport != NULL) {
            return this->impl->connectedTransport->getRemoteAddress();
        }
    }
    return "";
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::oneway(const Pointer<Command> command) {

    Pointer<Exception> error;

    try {

        synchronized(&this->impl->reconnectMutex) {

            if (command != NULL && this->impl->connectedTransport == NULL) {

                if (command->isShutdownInfo()) {
                    // Skipping send of ShutdownInfo command when not connected.
                    return;
                }

                if (command->isRemoveInfo() || command->isMessageAck()) {
                    // Simulate response to RemoveInfo command or Ack as they will be stale.
                    stateTracker.track(command);

                    if (command->isResponseRequired()) {
                        Pointer<Response> response(new Response());
                        response->setCorrelationId(command->getCommandId());
                        this->impl->myTransportListener->onCommand(response);
                    }

                    return;
                } else if (command->isMessagePull()) {
                    // Simulate response to MessagePull if timed as we can't honor that now.
                    Pointer<MessagePull> pullRequest = command.dynamicCast<MessagePull>();
                    if (pullRequest->getTimeout() != 0) {
                        Pointer<MessageDispatch> dispatch(new MessageDispatch());
                        dispatch->setConsumerId(pullRequest->getConsumerId());
                        dispatch->setDestination(pullRequest->getDestination());
                        this->impl->myTransportListener->onCommand(dispatch);
                    }

                    return;
                }
            }

            // Keep trying until the message is sent.
            for (int i = 0; !this->impl->closed; i++) {
                try {

                    // Wait for transport to be connected.
                    Pointer<Transport> transport = this->impl->connectedTransport;
                    long long start = System::currentTimeMillis();
                    bool timedout = false;

                    while (transport == NULL && !this->impl->closed && this->impl->connectionFailure == NULL) {
                        long long end = System::currentTimeMillis();
                        if (this->impl->timeout > 0 && (end - start > this->impl->timeout)) {
                            timedout = true;
                            break;
                        }

                        this->impl->reconnectMutex.wait(100);
                        transport = this->impl->connectedTransport;
                    }

                    if (transport == NULL) {
                        // Previous loop may have exited due to us being disposed.
                        if (this->impl->closed) {
                            error.reset(new IOException(__FILE__, __LINE__, "Transport disposed."));
                        } else if (this->impl->connectionFailure != NULL) {
                            error = this->impl->connectionFailure;
                        } else if (timedout == true) {
                            error.reset(new IOException(__FILE__, __LINE__,
                                "Failover timeout of %d ms reached.", this->impl->timeout));
                        } else {
                            error.reset(new IOException(__FILE__, __LINE__, "Unexpected failure."));
                        }

                        break;
                    }

                    // If it was a request and it was not being tracked by the state
                    // tracker, then hold it in the requestMap so that we can replay
                    // it later.
                    Pointer<Tracked> tracked;
                    try {
                        tracked = stateTracker.track(command);
                        synchronized( &this->impl->requestMap ) {
                            if (tracked != NULL && tracked->isWaitingForResponse()) {
                                this->impl->requestMap.put(command->getCommandId(), tracked);
                            } else if (tracked == NULL && command->isResponseRequired()) {
                                this->impl->requestMap.put(command->getCommandId(), command);
                            }
                        }
                    } catch (Exception& ex) {
                        ex.setMark(__FILE__, __LINE__);
                        error.reset(ex.clone());
                        break;
                    }

                    // Send the message.
                    try {
                        transport->oneway(command);
                        stateTracker.trackBack(command);
                    } catch (IOException& e) {

                        e.setMark(__FILE__, __LINE__);

                        // If the command was not tracked.. we will retry in
                        // this method
                        if (tracked == NULL) {

                            // since we will retry in this method.. take it out of the
                            // request map so that it is not sent 2 times on recovery
                            if (command->isResponseRequired()) {
                                this->impl->requestMap.remove(command->getCommandId());
                            }

                            // re-throw the exception so it will handled by the outer catch
                            throw;
                        } else {
                            // Trigger the reconnect since we can't count on inactivity or
                            // other socket events to trip the failover condition.
                            handleTransportFailure(e);
                        }
                    }

                    return;
                } catch (IOException& e) {
                    e.setMark(__FILE__, __LINE__);
                    handleTransportFailure(e);
                }
            }
        }
    } catch (InterruptedException& ex) {
        Thread::currentThread()->interrupt();
        throw InterruptedIOException(__FILE__, __LINE__, "FailoverTransport oneway() interrupted");
    }
    AMQ_CATCHALL_NOTHROW()

    if (!this->impl->closed) {
        if (error != NULL) {
            throw IOException(*error);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
Pointer<FutureResponse> FailoverTransport::asyncRequest(const Pointer<Command> command AMQCPP_UNUSED,
                                                        const Pointer<ResponseCallback> responseCallback AMQCPP_UNUSED) {
    throw decaf::lang::exceptions::UnsupportedOperationException(__FILE__, __LINE__, "FailoverTransport::asyncRequest - Not Supported");
}

////////////////////////////////////////////////////////////////////////////////
Pointer<Response> FailoverTransport::request(const Pointer<Command> command AMQCPP_UNUSED) {
    throw decaf::lang::exceptions::UnsupportedOperationException(__FILE__, __LINE__, "FailoverTransport::request - Not Supported");
}

////////////////////////////////////////////////////////////////////////////////
Pointer<Response> FailoverTransport::request(const Pointer<Command> command AMQCPP_UNUSED, unsigned int timeout AMQCPP_UNUSED) {
    throw decaf::lang::exceptions::UnsupportedOperationException(__FILE__, __LINE__, "FailoverTransport::request - Not Supported");
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::start() {

    try {

        synchronized(&this->impl->reconnectMutex) {

            if (this->impl->started) {
                return;
            }

            this->impl->started = true;

            if (this->impl->backupsEnabled || this->impl->priorityBackup) {
                this->impl->backups->setEnabled(true);
            }
            this->impl->taskRunner->start();

            stateTracker.setMaxMessageCacheSize(this->getMaxCacheSize());
            stateTracker.setMaxMessagePullCacheSize(this->getMaxPullCacheSize());
            stateTracker.setTrackMessages(this->isTrackMessages());
            stateTracker.setTrackTransactionProducers(this->isTrackTransactionProducers());

            if (this->impl->connectedTransport != NULL) {
                stateTracker.restore(this->impl->connectedTransport);
            } else {
                reconnect(false);
            }
        }
    }
    AMQ_CATCH_RETHROW(IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException)
    AMQ_CATCHALL_THROW(IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::stop() {

    try {
        synchronized(&this->impl->reconnectMutex) {
            this->impl->started = false;
            this->impl->backups->setEnabled(false);
        }
    }
    AMQ_CATCH_RETHROW(IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(Exception, IOException)
    AMQ_CATCHALL_THROW(IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::close() {

    try {

        Pointer<Transport> transportToStop;

        synchronized(&this->impl->reconnectMutex) {

            if (this->impl->closed) {
                return;
            }

            this->impl->started = false;
            this->impl->closed = true;
            this->impl->connected = false;

            this->impl->backups->setEnabled(false);
            this->impl->requestMap.clear();

            if (this->impl->connectedTransport != NULL) {
                transportToStop.swap(this->impl->connectedTransport);
            }

            this->impl->reconnectMutex.notifyAll();
        }

        this->impl->backups->close();

        synchronized( &this->impl->sleepMutex ) {
            this->impl->sleepMutex.notifyAll();
        }

        this->impl->taskRunner->shutdown(TimeUnit::MINUTES.toMillis(5));

        if (transportToStop != NULL) {
            transportToStop->close();
        }
    }
    AMQ_CATCH_RETHROW( IOException)
    AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException)
    AMQ_CATCHALL_THROW( IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::reconnect(bool rebalance) {

    Pointer<Transport> transport;

    synchronized( &this->impl->reconnectMutex ) {
        if (this->impl->started) {

            if (rebalance) {
                this->impl->doRebalance = true;
            }

            try {
                this->impl->taskRunner->wakeup();
            } catch (InterruptedException& ex) {
                Thread::currentThread()->interrupt();
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::restoreTransport(const Pointer<Transport> transport) {

    try {

        transport->start();

        //send information to the broker - informing it we are an ft client
        Pointer<ConnectionControl> cc(new ConnectionControl());
        cc->setFaultTolerant(true);
        transport->oneway(cc);

        stateTracker.restore(transport);

        decaf::util::StlMap<int, Pointer<Command> > commands;
        synchronized(&this->impl->requestMap) {
            commands.copy(this->impl->requestMap);
        }

        Pointer<Iterator<Pointer<Command> > > iter(commands.values().iterator());
        while (iter->hasNext()) {
            transport->oneway(iter->next());
        }
    }
    AMQ_CATCH_RETHROW( IOException)
    AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException)
    AMQ_CATCHALL_THROW( IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::handleTransportFailure(const decaf::lang::Exception& error) {

    Pointer<Transport> transport;
    synchronized(&this->impl->reconnectMutex) {
        this->impl->connectedTransport.swap(transport);
    }

    if (transport != NULL) {

        if (this->impl->disposedListener != NULL) {
            transport->setTransportListener(this->impl->disposedListener.get());
        }

        // Hand off to the close task so it gets done in a different thread.
        this->impl->closeTask->add(transport);

        bool reconnectOk = false;

        synchronized(&this->impl->reconnectMutex) {

            reconnectOk = this->impl->canReconnect();
            URI failedUri = *this->impl->connectedTransportURI;

            this->impl->initialized = false;
            this->impl->uris->addURI(failedUri);
            this->impl->connectedTransportURI.reset(NULL);
            this->impl->connected = false;
            this->impl->connectedToPrioirty = false;

            // Place the State Tracker into a reconnection state.
            this->stateTracker.transportInterrupted();

            // Notify before we attempt to reconnect so that the consumers have a chance
            // to cleanup their state.
            if (this->impl->transportListener != NULL) {
                this->impl->transportListener->transportInterrupted();
            }

            if (reconnectOk) {
                this->impl->updated->removeURI(failedUri);
                this->impl->taskRunner->wakeup();
            } else if (!this->impl->closed) {
                this->impl->connectionFailure.reset(error.clone());
                this->impl->propagateFailureToExceptionListener();
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::handleConnectionControl(const Pointer<Command> control) {

    try {

        Pointer<ConnectionControl> ctrlCommand = control.dynamicCast<ConnectionControl>();

        std::string reconnectStr = ctrlCommand->getReconnectTo();
        if (!reconnectStr.empty()) {

            std::remove(reconnectStr.begin(), reconnectStr.end(), ' ');

            if (reconnectStr.length() > 0) {
                try {
                    if (isReconnectSupported()) {
                        reconnect(URI(reconnectStr));
                    }
                } catch (Exception e) {
                }
            }
        }

        processNewTransports(ctrlCommand->isRebalanceConnection(), ctrlCommand->getConnectedBrokers());
    }
    AMQ_CATCH_RETHROW( Exception)
    AMQ_CATCHALL_THROW( Exception)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::processNewTransports(bool rebalance, std::string newTransports) {

    if (!newTransports.empty()) {

        std::remove(newTransports.begin(), newTransports.end(), ' ');

        if (newTransports.length() > 0 && isUpdateURIsSupported()) {

            LinkedList<URI> list;
            StringTokenizer tokenizer(newTransports, ",");

            while (tokenizer.hasMoreTokens()) {
                std::string str = tokenizer.nextToken();
                try {
                    URI uri(str);
                    list.add(uri);
                } catch (Exception& e) {
                }
            }

            if (!list.isEmpty()) {
                try {
                    updateURIs(rebalance, list);
                } catch (IOException& e) {
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::updateURIs(bool rebalance, const decaf::util::List<decaf::net::URI>& updatedURIs) {

    if (isUpdateURIsSupported()) {

        Pointer<URIPool> copy(new URIPool(*this->impl->updated));
        this->impl->updated->clear();

        if (!updatedURIs.isEmpty()) {

            StlSet<URI> set;

            for (int i = 0; i < updatedURIs.size(); i++) {
                set.add(updatedURIs.get(i));
            }

            Pointer<Iterator<URI> > setIter(set.iterator());
            while (setIter->hasNext()) {
                URI value = setIter->next();
                this->impl->updated->addURI(value);
            }

            if (!(copy->isEmpty() && this->impl->updated->isEmpty()) &&
                !(copy->equals(*this->impl->updated))) {

                synchronized(&this->impl->reconnectMutex) {
                    reconnect(rebalance);
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isPending() const {
    bool result = false;

    synchronized(&this->impl->reconnectMutex) {
        if (!this->impl->isConnectionStateValid() && this->impl->started && !this->impl->isClosedOrFailed()) {

            int maxReconnectAttempts = this->impl->calculateReconnectAttemptLimit();

            if (maxReconnectAttempts != -1 && this->impl->connectFailures >= maxReconnectAttempts) {
                result = false;
            } else {
                result = true;
            }
        }
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::iterate() {

    Pointer<Exception> failure;

    synchronized( &this->impl->reconnectMutex ) {

        if (this->impl->isClosedOrFailed()) {
            this->impl->reconnectMutex.notifyAll();
        }

        if (this->impl->isConnectionStateValid() || this->impl->isClosedOrFailed()) {
            return false;
        } else {

            Pointer<URIPool> connectList = this->impl->getConnectList();

            if (connectList->isEmpty()) {
                failure.reset(new IOException(__FILE__, __LINE__, "No URIs available for reconnect."));
            } else {

                if (this->impl->doRebalance) {
                    if (this->impl->connectedToPrioirty || connectList->getPriorityURI().equals(*this->impl->connectedTransportURI)) {
                        // already connected to first in the list, no need to rebalance
                        this->impl->doRebalance = false;
                        return false;
                    } else {
                        // break any existing connect for rebalance.
                        this->impl->disconnect();
                    }

                    this->impl->doRebalance = false;
                }

                this->impl->resetReconnectDelay();

                LinkedList<URI> failures;
                Pointer<Transport> transport;
                URI uri;

                if (this->impl->backups->isEnabled()) {
                    Pointer<BackupTransport> backupTransport = this->impl->backups->getBackup();
                    if (backupTransport != NULL) {
                        transport = backupTransport->getTransport();
                        uri = backupTransport->getUri();
                        if (this->impl->priorityBackup && this->impl->backups->isPriorityBackupAvailable()) {
                            // A priority connection is available and we aren't connected to
                            // any other priority transports so disconnect and use the backup.
                            this->impl->disconnect();
                        }
                    }
                }

                // Sleep for the reconnectDelay if there's no backup and we aren't trying
                // for the first time, or we were disposed for some reason.
                if (transport == NULL && !this->impl->firstConnection &&
                    (this->impl->reconnectDelay > 0) && !this->impl->closed) {
                    synchronized (&this->impl->sleepMutex) {
                        try {
                            this->impl->sleepMutex.wait(this->impl->reconnectDelay);
                        } catch (InterruptedException& e) {
                            Thread::currentThread()->interrupt();
                        }
                    }
                }

                while (transport == NULL && this->impl->connectedTransport == NULL && !this->impl->closed) {
                    try {
                        // We could be starting the loop with a backup already.
                        if (transport == NULL) {
                            try {
                                uri = connectList->getURI();
                            } catch (NoSuchElementException& ex) {
                                break;
                            }

                            transport = createTransport(uri);
                        }

                        transport->setTransportListener(this->impl->myTransportListener.get());
                        transport->start();

                        if (this->impl->started && !this->impl->firstConnection) {
                            restoreTransport(transport);
                        }

                        this->impl->reconnectDelay = this->impl->initialReconnectDelay;
                        this->impl->connectedTransportURI.reset(new URI(uri));
                        this->impl->connectedTransport = transport;
                        this->impl->reconnectMutex.notifyAll();
                        this->impl->connectFailures = 0;

                        if (isPriorityBackup()) {
                            this->impl->connectedToPrioirty = connectList->getPriorityURI().equals(uri) ||
                                                              this->impl->priorityUris->contains(uri);
                        } else {
                            this->impl->connectedToPrioirty = false;
                        }

                        // Make sure on initial startup, that the transportListener
                        // has been initialized for this instance.
                        synchronized(&this->impl->listenerMutex) {
                            if (this->impl->transportListener == NULL) {
                                // if it isn't set after 2secs - it probably never will be
                                this->impl->listenerMutex.wait(2000);
                            }
                        }

                        if (this->impl->transportListener != NULL) {
                            this->impl->transportListener->transportResumed();
                        }

                        if (this->impl->firstConnection) {
                            this->impl->firstConnection = false;
                        }

                        this->impl->connected = true;
                        return false;

                    } catch (Exception& e) {
                        e.setMark(__FILE__, __LINE__);

                        if (transport != NULL) {
                            if (this->impl->disposedListener != NULL) {
                                transport->setTransportListener(this->impl->disposedListener.get());
                            }

                            try {
                                transport->stop();
                            } catch (...) {
                            }

                            // Hand off to the close task so it gets done in a different thread
                            // this prevents a deadlock from occurring if the Transport happens
                            // to call back through our onException method or locks in some other
                            // way.
                            this->impl->closeTask->add(transport);
                            this->impl->taskRunner->wakeup();
                            transport.reset(NULL);
                        }

                        failures.add(uri);
                        failure.reset(e.clone());
                    }
                }

                // Return the failures to the pool, we will try again on the next iteration.
                connectList->addURIs(failures);
            }
        }

        int reconnectAttempts = this->impl->calculateReconnectAttemptLimit();

        if (reconnectAttempts >= 0 && ++this->impl->connectFailures >= reconnectAttempts) {
            this->impl->connectionFailure = failure;

            // Make sure on initial startup, that the transportListener has been initialized
            // for this instance.
            synchronized(&this->impl->listenerMutex) {
                if (this->impl->transportListener == NULL) {
                    this->impl->listenerMutex.wait(2000);
                }
            }

            this->impl->propagateFailureToExceptionListener();
            return false;
        }
    }

    if (!this->impl->closed) {
        this->impl->doDelay();
    }

    return !this->impl->closed;
}

////////////////////////////////////////////////////////////////////////////////
Pointer<Transport> FailoverTransport::createTransport(const URI& location) const {

    try {

        TransportFactory* factory = TransportRegistry::getInstance().findFactory(location.getScheme());

        if (factory == NULL) {
            throw new IOException(__FILE__, __LINE__, "Invalid URI specified, no valid Factory Found.");
        }

        Pointer<Transport> transport(factory->createComposite(location));

        return transport;
    }
    AMQ_CATCH_RETHROW( IOException)
    AMQ_CATCH_EXCEPTION_CONVERT( Exception, IOException)
    AMQ_CATCHALL_THROW( IOException)
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setConnectionInterruptProcessingComplete(const Pointer<commands::ConnectionId> connectionId) {

    synchronized(&this->impl->reconnectMutex) {
        stateTracker.connectionInterruptProcessingComplete(this, connectionId);
    }
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isConnected() const {
    return this->impl->connected;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isClosed() const {
    return this->impl->closed;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isInitialized() const {
    return this->impl->initialized;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setInitialized(bool value) {
    this->impl->initialized = value;
}

////////////////////////////////////////////////////////////////////////////////
Transport* FailoverTransport::narrow(const std::type_info& typeId) {

    if (typeid( *this ) == typeId) {
        return this;
    }

    if (this->impl->connectedTransport != NULL) {
        return this->impl->connectedTransport->narrow(typeId);
    }

    return NULL;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::processResponse(const Pointer<Response> response) {

    Pointer<Command> object;

    synchronized(&(this->impl->requestMap)) {
        try {
            object = this->impl->requestMap.remove(response->getCorrelationId());
        } catch (NoSuchElementException& ex) {
            // Not tracking this request in our map, not an error.
        }
    }

    if (object != NULL) {
        try {
            Pointer<Tracked> tracked = object.dynamicCast<Tracked>();
            tracked->onResponse();
        }
        AMQ_CATCH_NOTHROW( ClassCastException)
    }
}

////////////////////////////////////////////////////////////////////////////////
Pointer<wireformat::WireFormat> FailoverTransport::getWireFormat() const {

    Pointer<wireformat::WireFormat> result;
    Pointer<Transport> transport = this->impl->connectedTransport;

    if (transport != NULL) {
        result = transport->getWireFormat();
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
long long FailoverTransport::getTimeout() const {
    return this->impl->timeout;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setTimeout(long long value) {
    this->impl->timeout = value;
}

////////////////////////////////////////////////////////////////////////////////
long long FailoverTransport::getInitialReconnectDelay() const {
    return this->impl->initialReconnectDelay;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setInitialReconnectDelay(long long value) {
    this->impl->initialReconnectDelay = value;
}

////////////////////////////////////////////////////////////////////////////////
long long FailoverTransport::getMaxReconnectDelay() const {
    return this->impl->maxReconnectDelay;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setMaxReconnectDelay(long long value) {
    this->impl->maxReconnectDelay = value;
}

////////////////////////////////////////////////////////////////////////////////
long long FailoverTransport::getBackOffMultiplier() const {
    return this->impl->backOffMultiplier;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setBackOffMultiplier(long long value) {
    this->impl->backOffMultiplier = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isUseExponentialBackOff() const {
    return this->impl->useExponentialBackOff;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setUseExponentialBackOff(bool value) {
    this->impl->useExponentialBackOff = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isRandomize() const {
    return this->impl->uris->isRandomize();
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setRandomize(bool value) {
    this->impl->uris->setRandomize(value);
}

////////////////////////////////////////////////////////////////////////////////
int FailoverTransport::getMaxReconnectAttempts() const {
    return this->impl->maxReconnectAttempts;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setMaxReconnectAttempts(int value) {
    this->impl->maxReconnectAttempts = value;
}

////////////////////////////////////////////////////////////////////////////////
int FailoverTransport::getStartupMaxReconnectAttempts() const {
    return this->impl->startupMaxReconnectAttempts;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setStartupMaxReconnectAttempts(int value) {
    this->impl->startupMaxReconnectAttempts = value;
}

////////////////////////////////////////////////////////////////////////////////
long long FailoverTransport::getReconnectDelay() const {
    return this->impl->reconnectDelay;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setReconnectDelay(long long value) {
    this->impl->reconnectDelay = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isBackup() const {
    return this->impl->backupsEnabled;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setBackup(bool value) {
    this->impl->backupsEnabled = value;
}

////////////////////////////////////////////////////////////////////////////////
int FailoverTransport::getBackupPoolSize() const {
    return this->impl->backups->getBackupPoolSize();
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setBackupPoolSize(int value) {
    this->impl->backups->setBackupPoolSize(value);
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isTrackMessages() const {
    return this->impl->trackMessages;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setTrackMessages(bool value) {
    this->impl->trackMessages = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isTrackTransactionProducers() const {
    return this->impl->trackTransactionProducers;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setTrackTransactionProducers(bool value) {
    this->impl->trackTransactionProducers = value;
}

////////////////////////////////////////////////////////////////////////////////
int FailoverTransport::getMaxCacheSize() const {
    return this->impl->maxCacheSize;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setMaxCacheSize(int value) {
    this->impl->maxCacheSize = value;
}

////////////////////////////////////////////////////////////////////////////////
int FailoverTransport::getMaxPullCacheSize() const {
    return this->impl->maxPullCacheSize;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setMaxPullCacheSize(int value) {
    this->impl->maxPullCacheSize = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isReconnectSupported() const {
    return this->impl->reconnectSupported;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setReconnectSupported(bool value) {
    this->impl->reconnectSupported = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isUpdateURIsSupported() const {
    return this->impl->updateURIsSupported;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setUpdateURIsSupported(bool value) {
    this->impl->updateURIsSupported = value;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isRebalanceUpdateURIs() const {
    return this->impl->rebalanceUpdateURIs;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setRebalanceUpdateURIs(bool rebalanceUpdateURIs) {
    this->impl->rebalanceUpdateURIs = rebalanceUpdateURIs;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isPriorityBackup() const {
    return this->impl->priorityBackup;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setPriorityBackup(bool priorityBackup) {
    this->impl->priorityBackup = priorityBackup;
}

////////////////////////////////////////////////////////////////////////////////
bool FailoverTransport::isConnectedToPriority() const {
    return this->impl->connectedToPrioirty;
}

////////////////////////////////////////////////////////////////////////////////
void FailoverTransport::setPriorityURIs(const std::string& priorityURIs AMQCPP_UNUSED) {
    StringTokenizer tokenizer(priorityURIs, ",");
    while (tokenizer.hasMoreTokens()) {
        std::string str = tokenizer.nextToken();
        try {
            this->impl->priorityUris->addURI(URI(str));
        } catch (Exception& e) {
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
const List<URI>& FailoverTransport::getPriorityURIs() const {
    return this->impl->priorityUris->getURIList();
}


text:
FROM scratch
COPY build/ngrokd /
EXPOSE 80 443 4443
VOLUME ["/data"]
ENTRYPOINT ["/ngrokd"]
CMD ["--help"]


text:
#include <iostream>
#include <string_view>
#include "tscpp/api/GlobalPlugin.h"
#include "tscpp/api/TransactionPlugin.h"
#include "tscpp/api/TransformationPlugin.h"
#include "tscpp/api/PluginInit.h"

using namespace atscppapi;
using std::cerr;
using std::endl;
using std::string;

namespace
{
GlobalPlugin *plugin;
}

class PostBufferTransformationPlugin : public TransformationPlugin
{
public:
  explicit PostBufferTransformationPlugin(Transaction &transaction)
    : TransformationPlugin(transaction, REQUEST_TRANSFORMATION), transaction_(transaction)
  {
    buffer_.reserve(1024); // not required, this is an optimization to start the buffer at a slightly higher value.
    (void)transaction_;
  }

  void
  consume(std::string_view data) override
  {
    buffer_.append(data.data(), data.length());
  }

  void
  handleInputComplete() override
  {
    produce(buffer_);
    setOutputComplete();
  }

  ~PostBufferTransformationPlugin() override {}

private:
  Transaction &transaction_;
  string buffer_;
};

class GlobalHookPlugin : public GlobalPlugin
{
public:
  GlobalHookPlugin() { registerHook(HOOK_READ_REQUEST_HEADERS_POST_REMAP); }
  void
  handleReadRequestHeadersPostRemap(Transaction &transaction) override
  {
    cerr << "Read Request Headers Post Remap" << endl;
    cerr << "Path: " << transaction.getClientRequest().getUrl().getPath() << endl;
    cerr << "Method: " << HTTP_METHOD_STRINGS[transaction.getClientRequest().getMethod()] << endl;
    if (transaction.getClientRequest().getMethod() == HTTP_METHOD_POST) {
      transaction.addPlugin(new PostBufferTransformationPlugin(transaction));
    }

    transaction.resume();
  }
};

void
TSPluginInit(int argc ATSCPPAPI_UNUSED, const char *argv[] ATSCPPAPI_UNUSED)
{
  if (!RegisterGlobalPlugin("CPP_Example_PostBuffer", "apache", "dev@trafficserver.apache.org")) {
    return;
  }
  plugin = new GlobalHookPlugin();
}


text:
// Copyright 2009 Thiago H. de Paula Figueiredo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package br.com.arsmachina.tapestrycrud.components;

import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;

/**
 * Simple component that just aggregates the edit object, remove object, new
 * object and back to listing components.
 *
 * @author Thiago H. de Paula Figueiredo
 */
public class ViewPageLinks {

	/**
	 * Show the remove link?
	 */
	@Parameter(value = "true")
	@Property
	@SuppressWarnings("unused")
	private boolean remove;

	/**
	 * Show the edit link?
	 */
	@Parameter(value = "true")
	@Property
	@SuppressWarnings("unused")
	private boolean edit;

	/**
	 * Show the list link?
	 */
	@Parameter(value = "true")
	@Property
	@SuppressWarnings("unused")
	private boolean list;

	/**
	 * Show the new object link?
	 */
	@Parameter(value = "true")
	@Property
	@SuppressWarnings("unused")
	private boolean newObject;

}


text:
require File.expand_path('../boot', __FILE__)

require "action_controller/railtie"
require "rails/test_unit/railtie"

Bundler.require :default, RYGSAEK_ORM

begin
  require "#{RYGSAEK_ORM}/railtie"
rescue LoadError
end

require "rygsaek"

module RailsApp
  class Application < Rails::Application
    # Add additional load paths for your own custom dirs
    config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers views).include?($1) }
    config.autoload_paths += [ "#{config.root}/app/#{RYGSAEK_ORM}" ]

    # Configure generators values. Many other options are available, be sure to check the documentation.
    # config.generators do |g|
    #   g.orm             :active_record
    #   g.template_engine :erb
    #   g.test_framework  :test_unit, fixture: true
    # end

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters << :password
    config.assets.enabled = false

  end
end


text:
package org.apache.polygene.library.sql.generator.grammar.modification;

import org.apache.polygene.library.sql.generator.grammar.common.ValueExpression;

/**
 * This syntax element represents the update source having value of whatever expression it holds.
 *
 *
 */
public interface UpdateSourceByExpression
    extends UpdateSource
{

    /**
     * Returns the value expression to use as value for update source.
     *
     * @return The value expression to use as value for update source.
     */
    ValueExpression getValueExpression();
}


text:
        <button type="button" class="close" data-bind="click: close" data-dismiss="modal" aria-hidden="true">×</button>

        <form role="form" data-bind="submit: save">

                    <input id="email" class="form-control" type="email" data-bind="value: email, attr: { placeholder: language.getValue('email_placeholder') }">

                    <textarea id="message" class="form-control" rows="3" data-bind="value: message, valueUpdate: 'afterkeydown'" style="resize: none;"></textarea>

        </form>

        <button type="button" class="btn btn-default" data-bind="click: close, text: language.getValue('cancel')" data-dismiss="modal"></button>
        <button type="submit" class="btn btn-primary" data-bind="command: save, activity: save.isExecuting"></button>


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateFilterTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('filter', function(Blueprint $table)
		{
			$table->increments('filter_id');
			$table->integer('filter_group_id')->unsigned();
			$table->integer('sort_order')->unsigned();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('filter');
	}

}


text:
class UsersController < ApplicationController

  def index
  end

  def show
  end

  def new
  end

  def edit
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to root_path, :notice => "Signed up!"
    else
      redirect_to root_path
    end
  end

  def update
  end

  def destroy
  end

  private

  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end

end


text:
<?php

declare(strict_types=1);

namespace Novuso\Common\Application\Validation\Rule;

use Novuso\Common\Domain\Specification\CompositeSpecification;

/**
 * Class IsFalsy
 */
class IsFalsy extends CompositeSpecification
{
    /**
     * @inheritDoc
     */
    public function isSatisfiedBy(mixed $candidate): bool
    {
        return !$candidate;
    }
}


text:
namespace abb {
namespace utils {

struct cord_node : noncopyable {
    cord_node():
        cord_prev(this),
        cord_next(this) {}

    void cord_insert(cord_node * elem) {
        cord_node * this_prev = this->cord_prev;
        cord_node * elem_prev = elem->cord_prev;

        elem->cord_prev = this_prev;
        this->cord_prev = elem_prev;
        this_prev->cord_next = elem;
        elem_prev->cord_next = this;
    }

    void cord_detach() {
        cord_node * this_prev = this->cord_prev;
        cord_node * this_next = this->cord_next;

        this_prev->cord_next = this_next;
        this_next->cord_prev = this_prev;
        this->cord_next = this->cord_prev = this;
    }

    cord_node * cord_prev;
    cord_node * cord_next;
};

template<typename Obj>
class cord_iterator {
private:
    typedef typename std::conditional<
        std::is_const<Obj>::value,
        cord_node const*,
        cord_node *
    >::type cord_node_ptr;

public:
    explicit cord_iterator(cord_node_ptr elem): elem(elem) {}

    bool operator!=(cord_iterator<Obj> const& other) const {
        return this->elem != other.elem;
    }

    cord_iterator<Obj> & operator++() {
        this->elem = this->elem->cord_next;
        return *this;
    }

    Obj * operator*() const {
        return static_cast<Obj *>(this->elem);
    }

private:
    cord_node_ptr elem;
};

template<typename Obj>
class cord_list : public cord_node {
public:
    typedef cord_iterator<Obj> iterator;
    typedef cord_iterator<Obj const> const_iterator;

    void insert(Obj * obj) {
        this->cord_insert(obj);
    }

    bool empty() const {
        return this == this->cord_next;
    }

    iterator begin() {
        return iterator(this->cord_next);
    }

    const_iterator begin() const {
        return const_iterator(this->cord_next);
    }

    iterator end() {
        return iterator(this);
    }

    const_iterator end() const {
        return const_iterator(this);
    }
};

} // namespace utils
} // namespace abb

#endif // ABB_UTILS_CORD_H


text:
Finbuckle.MultiTenant integrates with the standard ASP.NET Core [Options pattern](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options) and lets apps customize options distinctly for each tenant. The current tenant determines which options are retrieved via the `IOptions<TOptions>` (or derived) instance's `Value` property and `Get(string name)` method.

 A specialized variation of this is [per-tenant authentication](Authentication).

Per-tenant options will work with *any* options class when using `IOptions<TOptions>`, `IOptionsSnapshot<TOptions>`, or `IOptionsMonitor<TOptions>` with dependency injection or service resolution. This includes an app's own code *and* code internal to ASP.NET Core or other libraries that use the Options pattern. There is one potential caveat: ASP.NET Core and other libraries may internally cache options or exhibit other unexpected behavior resulting in the wrong option values!

Consider a typical scenario in ASP.Net Core, starting with a simple class:

```cs
public class MyOptions
{
    public int Option1 { get; set; }
    public int Option2 { get; set; }
}
```

In the `ConfigureServices` method of the startup class, `services.Configure<MyOptions>` is called with a delegate or `IConfiguration` parameter to set the option values:

```cs
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MyOptions>(options => options.Option1 = 1);

        // Other services configured here...
    }
}
```

Dependency injection of `IOptions<MyOptions>` into a controller (or anywhere DI can be used) provides access to the options values, which are the same for every tenant at this point:

```cs
public MyController : Controller
{
    private readonly MyOptions _myOptions;

    public MyController(IOptionsMonitor<MyOptions> optionsAccessor)
    {
        // Same options regardless of the current tenant.
        _myOptions = optionsAccessor.Value;
    }
}
```

## Customizing Options Per Tenant
This sections assumes Finbuckle.MultiTenant is installed and configured. See [Getting Started](GettingStarted) for details.

Call `WithPerTenantOptions<TOptions>` after `AddMultiTenant<T>` in the `ConfigureServices` method:

```cs
services.AddMultiTenant<TenantInfo>()...
        .WithPerTenantOptions<MyOptions>((options, tenantInfo) =>
        {
            options.MyOption1 = (int)tenantInfo.Items["someValue"];
            options.MyOption2 = (int)tenantInfo.Items["anotherValue"];
        });
```

The type parameter `TOptions` is the options type being customized per-tenant. The method parameter is an `Action<TOptions, TenantInfo>`. This action will modify the options instance *after* the options normal configuration and *before* its [post configuration](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?#ipostconfigureoptions).

`WithPerTenantOptions<TOptions>` can be called multiple times on the same `TOptions`
type and the configuration will run in the respective order.

Now with the same controller example from above, the option values will be specific to the current tenant:

```cs
public MyController : Controller
{
    private readonly MyOptions _myOptions;

    public MyController(IOptionsMonitor<MyOptions> optionsAccessor)
    {
        // _myOptions.MyOptions1 and .MyOptions2 will be specific to the current tenant.
        _myOptions = optionsAccessor.Value;
    }
}
```

## Named Options
Both named and unnamed options are modified per-tenant. The same delegate passed to `WithPerTenantOptions<TOptions>` is applied to all options generated of type `TOptions` regardless of the option name.

## Options Caching
Internally ASP.NET Core caches options, and Finbuckle.MultiTenant extends this to cache options per tenant. Caching occurs when a `TOptions` instance is retrieved via `Value` or `Get` on the injected `IOptions<TOptions>` (or derived) instance for the first time for a tenant.

`IOptions<TOptions>` instances are always regenerated when injected so any caching only lasts as long as the specific instance.

`IOptionsSnapshot<TOptions>` instances are generated once per HTTP request and caching will last throughout the entire request.

`IOptionsMonitor<TOptions>` instances persist across HTTP requests and caching can persist for long periods of time.

In some situations cached options may need to be cleared so that the options can be regenerated.

When using per-tenant options via `IOptions<TOptions>` and `IOptionsSnapshot<TOptions>` the injected instance is of type `MultiTenantOptionsManager<TOptions>`. Casting to this type exposes the `Reset()` method which clears any internal caching for the current tenant and cause the options to be regenerated when next accessed via `Value` or `Get(string name)`.

When using per-tenant options with `IOptionsMonitor<TOptions>` each injected instance uses a shared persistent cache. This cache can be retrieved by injecting or resolving an instance of `IOptionsMonitorCache<TOptions>` which has a `Clear()` method that will clear the cache for the current tenant. Casting the `IOptionsMonitorCache<TOptions>` instance to `MultiTenantOptionsCache<TOptions>` exposes the `Clear(string tenantId)` and `ClearAll()` methods. `Clear(string tenantId)` clears cached options for a specific tenant (or the regular non per-tenant options if the parameter is empty or null). `ClearAll()` clears all cached options (including regular non per-tenant options).


text:
set -euo pipefail

# Copies an AMI to all other regions and outputs a build/mappings.yml file
# Local Usage: .buildkite/steps/copy.sh <linux_ami_id> <windows_ami_id>

copy_ami_to_region() {
  local source_image_id="$1"
  local source_region="$2"
  local destination_image_region="$3"
  local destination_image_name="$4"

  aws ec2 copy-image \
    --source-image-id "$source_image_id" \
    --source-region "$source_region" \
    --name "$destination_image_name" \
    --region "$destination_image_region" \
    --query "ImageId" \
    --output text
}

wait_for_ami_to_be_available() {
  local image_id="$1"
  local region="$2"
  local image_state

  while true; do
    image_state=$(aws ec2 describe-images --region "$region" --image-ids "$image_id" --output text --query 'Images[*].State');
    echo "$image_id ($region) is $image_state"

    if [[ "$image_state" == "available" ]]; then
      break
    elif [[ "$image_state" == "pending" ]]; then
      sleep 10
    else
      exit 1
    fi
  done
}

get_image_name() {
  local image_id="$1"
  local region="$2"

  aws ec2 describe-images \
  --image-ids "$image_id" \
  --output text \
  --region "$region" \
  --query 'Images[*].Name'
}

make_ami_public() {
  local image_id="$1"
  local region="$2"

  aws ec2 modify-image-attribute \
    --region "$region" \
    --image-id "$image_id" \
    --launch-permission "{\"Add\": [{\"Group\":\"all\"}]}"
}

if [[ -z "${BUILDKITE_AWS_STACK_BUCKET}" ]] ; then
  echo "Must set an s3 bucket in BUILDKITE_AWS_STACK_BUCKET for temporary files"
  exit 1
fi

ALL_REGIONS=(
  us-east-1
  us-east-2
  us-west-1
  us-west-2
  af-south-1
  ap-east-1
  ap-south-1
  ap-northeast-2
  ap-northeast-1
  ap-southeast-2
  ap-southeast-1
  ca-central-1
  eu-central-1
  eu-west-1
  eu-west-2
  eu-south-1
  eu-west-3
  eu-north-1
  me-south-1
  sa-east-1
)

IMAGES=(
)

# Configuration
linux_amd64_source_image_id="${1:-}"
linux_arm64_source_image_id="${1:-}"
windows_amd64_source_image_id="${2:-}"

source_region="${AWS_REGION}"
mapping_file="build/mappings.yml"

# Read the source images from meta-data if no arguments are provided
if [ $# -eq 0 ] ; then
    linux_amd64_source_image_id=$(buildkite-agent meta-data get "linux_amd64_image_id")
    linux_arm64_source_image_id=$(buildkite-agent meta-data get "linux_arm64_image_id")
    windows_amd64_source_image_id=$(buildkite-agent meta-data get "windows_amd64_image_id")
fi

# If we're not on the master branch or a tag build skip the copy
if [[ $BUILDKITE_BRANCH != "master" ]] && [[ "$BUILDKITE_TAG" != "$BUILDKITE_BRANCH" ]] ; then
  echo "--- Skipping AMI copy on non-master/tag branch " >&2
  mkdir -p "$(dirname "$mapping_file")"
  cat << EOF > "$mapping_file"
Mappings:
  AWSRegion2AMI:
    ${AWS_REGION} : { linuxamd64: $linux_amd64_source_image_id, linuxarm64: $linux_arm64_source_image_id, windows: $windows_amd64_source_image_id }
EOF
  exit 0
fi

s3_mappings_cache=$(printf "s3://%s/mappings-%s-%s-%s-%s.yml" \
  "${BUILDKITE_AWS_STACK_BUCKET}" \
  "${linux_amd64_source_image_id}" \
  "${linux_arm64_source_image_id}" \
  "${windows_amd64_source_image_id}" \
  "${BUILDKITE_BRANCH}")

# Check if there is a previously copy in the cache bucket
if aws s3 cp "${s3_mappings_cache}" "$mapping_file" ; then
  echo "--- Skipping AMI copy, was previously copied"
  exit 0
fi

# Get the image names to copy to other regions
linux_amd64_source_image_name=$(get_image_name "$linux_amd64_source_image_id" "$source_region")
linux_arm64_source_image_name=$(get_image_name "$linux_arm64_source_image_id" "$source_region")
windows_amd64_source_image_name=$(get_image_name "$windows_amd64_source_image_id" "$source_region")

# Copy to all other regions
for region in ${ALL_REGIONS[*]}; do
  if [[ $region != "$source_region" ]] ; then
    echo "--- :linux: Copying Linux AMD64 $linux_amd64_source_image_id to $region" >&2
    IMAGES+=("$(copy_ami_to_region "$linux_amd64_source_image_id" "$source_region" "$region" "${linux_amd64_source_image_name}-${region}")")

    echo "--- :linux: Copying Linux ARM64 $linux_arm64_source_image_id to $region" >&2
    IMAGES+=("$(copy_ami_to_region "$linux_arm64_source_image_id" "$source_region" "$region" "${linux_arm64_source_image_name}-${region}")")

    echo "--- :windows: Copying Windows AMD64 $windows_amd64_source_image_id to $region" >&2
    IMAGES+=("$(copy_ami_to_region "$windows_amd64_source_image_id" "$source_region" "$region" "${windows_amd64_source_image_name}-${region}")")
  else
    IMAGES+=("$linux_amd64_source_image_id" "$linux_arm64_source_image_id" "$windows_amd64_source_image_id")
  fi
done

# Write yaml preamble
mkdir -p "$(dirname "$mapping_file")"
cat << EOF > "$mapping_file"
Mappings:
  AWSRegion2AMI:
EOF

echo "--- Waiting for AMIs to become available"  >&2

for region in ${ALL_REGIONS[*]}; do
  linux_amd64_image_id="${IMAGES[0]}"
  linux_arm64_image_id="${IMAGES[1]}"
  windows_amd64_image_id="${IMAGES[2]}"

  wait_for_ami_to_be_available "$linux_amd64_image_id" "$region" >&2

  # Make the linux AMI public if it's not the source image
  if [[ $linux_amd64_image_id != "$linux_amd64_source_image_id" ]] ; then
    echo ":linux: Making Linux AMD64 ${linux_amd64_image_id} public" >&2
    make_ami_public "$linux_amd64_image_id" "$region"
  fi

  wait_for_ami_to_be_available "$linux_arm64_image_id" "$region" >&2

  # Make the linux ARM AMI public if it's not the source image
  if [[ $linux_arm64_image_id != "$linux_arm64_source_image_id" ]] ; then
    echo ":linux: Making Linux ARM64 ${linux_arm64_image_id} public" >&2
    make_ami_public "$linux_arm64_image_id" "$region"
  fi

  wait_for_ami_to_be_available "$windows_amd64_image_id" "$region" >&2

  # Make the windows AMI public if it's not the source image
  if [[ $windows_amd64_image_id != "$windows_amd64_source_image_id" ]] ; then
    echo ":windows: Making Windows AMD64 ${windows_amd64_image_id} public" >&2
    make_ami_public "$windows_amd64_image_id" "$region"
  fi

  # Write yaml to file
  echo "    $region : { linuxamd64: $linux_amd64_image_id, linuxarm64: $linux_arm64_image_id, windows: $windows_amd64_image_id }"  >> "$mapping_file"

  # Shift off the processed images
  IMAGES=("${IMAGES[@]:3}")
done

echo "--- Uploading mapping to s3 cache"
aws s3 cp "$mapping_file" "${s3_mappings_cache}"


text:
package org.smartdeveloperhub.vocabulary.publisher.spi;

import org.smartdeveloperhub.vocabulary.util.Module;

public interface DocumentationDeploymentFactory {

	DocumentationDeployment create(Module module);

}


text:
if [ "$TRAVIS_BRANCH" == "master" ]; then
  git config --global user.email "your-github-email@email.com"
  git config --global user.name "travis-ci"
  npm run release
  cd dist
  git init
  git add .
  git commit -m "deployed commit ${TRAVIS_COMMIT} from travis"
  git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:gh-pages > /dev/null 2>&1
fi


text:
layout: page
title: About
permalink: /about/
published: true
order: 1
---

- Computer Engineering graduate from San Jose State Univeristy
- Manufacturing Engineer employed at [Zap Surgical Systems Inc.](https://zapsurgical.com/)
- In my free time I like to play volleyball, vidya games, and listen to audio books.

Meet my long haired tuxedo cat, Maple.

### Contact me

[gishsteven@gmail.com](mailto:gishsteven@gmail.com)


text:
using System;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;

namespace ArcGISRuntime.Samples.QueryFeatureCountAndExtent
{
    [Register("QueryFeatureCountAndExtent")]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Query feature count and extent",
        category: "Analysis",
        description: "Zoom to features matching a query and count the features in the current visible extent.",
        instructions: "Use the button to zoom to the extent of the state specified (by abbreviation) in the textbox or use the button to count the features in the current extent.",
        tags: new[] { "count", "feature layer", "feature table", "features", "filter", "number", "query" })]
    public class QueryFeatureCountAndExtent : UIViewController
    {
        // Hold references to UI controls.
        private MapView _myMapView;
        private UILabel _resultLabel;
        private UIBarButtonItem _countInExtentButton;
        private UIBarButtonItem _zoomToQueryButton;
        private UIAlertController _unionAlert;

        // URL to the feature service.
        private readonly Uri _medicareHospitalSpendLayer =
            new Uri("https://services1.arcgis.com/4yjifSiIG17X0gW4/arcgis/rest/services/Medicare_Hospital_Spending_per_Patient/FeatureServer/0");

        // Feature table to query.
        private ServiceFeatureTable _featureTable;

        public QueryFeatureCountAndExtent()
        {
            Title = "Query feature count and extent";
        }

        private async void Initialize()
        {
            // Create the map with a basemap.
            Map myMap = new Map(BasemapStyle.ArcGISDarkGray);

            // Create the feature table from the service URL.
            _featureTable = new ServiceFeatureTable(_medicareHospitalSpendLayer);

            // Create the feature layer from the table.
            FeatureLayer myFeatureLayer = new FeatureLayer(_featureTable);

            // Add the feature layer to the map.
            myMap.OperationalLayers.Add(myFeatureLayer);

            try
            {
                // Wait for the feature layer to load.
                await myFeatureLayer.LoadAsync();

                // Set the map initial extent to the extent of the feature layer.
                myMap.InitialViewpoint = new Viewpoint(myFeatureLayer.FullExtent);

                // Add the map to the MapView.
                _myMapView.Map = myMap;
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
            }
        }

        private async void ZoomToFeature(string query)
        {
            // Create the query parameters.
            QueryParameters queryStates = new QueryParameters {WhereClause = $"upper(State) LIKE '%{query.ToUpper()}%'"};

            try
            {
                // Get the extent from the query.
                Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);

                // Return if there is no result (might happen if query is invalid).
                if (resultExtent?.SpatialReference == null)
                {
                    return;
                }

                // Create a viewpoint from the extent.
                Viewpoint resultViewpoint = new Viewpoint(resultExtent);

                // Zoom to the viewpoint.
                await _myMapView.SetViewpointAsync(resultViewpoint);

                // Update the UI.
                _resultLabel.Text = $"Zoomed to features in {query}";
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
            }
        }

        private void ZoomToQuery_Click(object sender, EventArgs e)
        {
            // Prompt for the type of convex hull to create.
            if (_unionAlert == null)
            {
                _unionAlert = UIAlertController.Create("Query features", "Enter a state abbreviation (e.g. CA)", UIAlertControllerStyle.Alert);
                _unionAlert.AddTextField(field => field.Placeholder = "e.g. CA");
                _unionAlert.AddAction(UIAlertAction.Create("Submit query", UIAlertActionStyle.Default, action => ZoomToFeature(_unionAlert.TextFields[0].Text)));
                _unionAlert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
            }

            // Show the alert.
            PresentViewController(_unionAlert, true, null);
        }

        private async void CountFeatures_Click(object sender, EventArgs e)
        {
            // Get the current visible extent.
            Geometry currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry;

            // Create the query parameters.
            QueryParameters queryCityCount = new QueryParameters
            {
                Geometry = currentExtent,
                // Specify the interpretation of the Geometry query parameters.
                SpatialRelationship = SpatialRelationship.Intersects
            };

            try
            {
                // Get the count of matching features.
                long count = await _featureTable.QueryFeatureCountAsync(queryCityCount);

                // Update the UI.
                _resultLabel.Text = $"{count} features in extent";
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
            }
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Initialize();
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor};

            _myMapView = new MapView();
            _myMapView.TranslatesAutoresizingMaskIntoConstraints = false;

            _zoomToQueryButton = new UIBarButtonItem();
            _zoomToQueryButton.Title = "Zoom to query";

            _countInExtentButton = new UIBarButtonItem();
            _countInExtentButton.Title = "Count in extent";

            UIToolbar toolbar = new UIToolbar();
            toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
            toolbar.Items = new[]
            {
                _countInExtentButton,
                new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                _zoomToQueryButton
            };

            _resultLabel = new UILabel
            {
                Text = "Press 'Zoom to query' to begin.",
                BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
                TextColor = UIColor.White,
                TextAlignment = UITextAlignment.Center,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            // Add the views.
            View.AddSubviews(_myMapView, toolbar, _resultLabel);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]
            {
                _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),

                toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
                toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),

                _resultLabel.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                _resultLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _resultLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _resultLabel.HeightAnchor.ConstraintEqualTo(40)
            });
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _zoomToQueryButton.Clicked += ZoomToQuery_Click;
            _countInExtentButton.Clicked += CountFeatures_Click;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            _zoomToQueryButton.Clicked -= ZoomToQuery_Click;
            _countInExtentButton.Clicked -= CountFeatures_Click;

            // Remove the reference to the alert, preventing a memory leak.
            _unionAlert = null;
        }
    }
}


text:
package org.wso2.carbon.apimgt.common.gateway.util;

import org.wso2.carbon.apimgt.common.gateway.exception.JWTGeneratorException;
import org.wso2.carbon.apimgt.common.gateway.jwtgenerator.JWTSignatureAlg;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;

/**
 * Helper class for util related to jwt generation.
 */
public final class JWTUtil {
    private static final String NONE = "NONE";
    private static final String SHA256_WITH_RSA = "SHA256withRSA";

    /**
     * Get the JWS compliant signature algorithm code of the algorithm used to sign the JWT.
     *
     * @param signatureAlgorithm - The algorithm used to sign the JWT. If signing is disabled, the value will be NONE.
     * @return - The JWS Compliant algorithm code of the signature algorithm.
     */
    public static String getJWSCompliantAlgorithmCode(String signatureAlgorithm) {

        if (signatureAlgorithm == null || NONE.equals(signatureAlgorithm)) {
            return JWTSignatureAlg.NONE.getJwsCompliantCode();
        } else if (SHA256_WITH_RSA.equals(signatureAlgorithm)) {
            return JWTSignatureAlg.SHA256_WITH_RSA.getJwsCompliantCode();
        } else {
            return signatureAlgorithm;
        }
    }

    /**
     * Utility method to generate JWT header with public certificate thumbprint for signature verification.
     *
     * @param publicCert         - The public certificate which needs to include in the header as thumbprint
     * @param signatureAlgorithm signature algorithm which needs to include in the header
     * @throws JWTGeneratorException
     */
    public static String generateHeader(Certificate publicCert, String signatureAlgorithm) throws
            JWTGeneratorException {

        try {
            //generate the SHA-1 thumbprint of the certificate
            MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
            byte[] der = publicCert.getEncoded();
            digestValue.update(der);
            byte[] digestInBytes = digestValue.digest();
            String publicCertThumbprint = hexify(digestInBytes);
            String base64UrlEncodedThumbPrint;
            base64UrlEncodedThumbPrint = java.util.Base64.getUrlEncoder()
                    .encodeToString(publicCertThumbprint.getBytes("UTF-8"));
            StringBuilder jwtHeader = new StringBuilder();
            /*
             * Sample header
             * {"typ":"JWT", "alg":"SHA256withRSA", "x5t":"a_jhNus21KVuoFx65LmkW2O_l10",
             * "kid":"a_jhNus21KVuoFx65LmkW2O_l10_RS256"}
             * {"typ":"JWT", "alg":"[2]", "x5t":"[1]", "x5t":"[1]"}
             * */
            jwtHeader.append("{\"typ\":\"JWT\",");
            jwtHeader.append("\"alg\":\"");
            jwtHeader.append(getJWSCompliantAlgorithmCode(signatureAlgorithm));
            jwtHeader.append("\",");

            jwtHeader.append("\"x5t\":\"");
            jwtHeader.append(base64UrlEncodedThumbPrint);
            jwtHeader.append("\",");

            jwtHeader.append("\"kid\":\"");
            jwtHeader.append(getKID(base64UrlEncodedThumbPrint, getJWSCompliantAlgorithmCode(signatureAlgorithm)));
            jwtHeader.append("\"");

            jwtHeader.append("}");
            return jwtHeader.toString();

        } catch (NoSuchAlgorithmException | CertificateEncodingException | UnsupportedEncodingException e) {
            throw new JWTGeneratorException("Error in generating public certificate thumbprint", e);
        }
    }

    /**
     * Helper method to hexify a byte array.
     *
     * @param bytes - The input byte array
     * @return hexadecimal representation
     */
    public static String hexify(byte bytes[]) {

        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            buf.append(hexDigits[(aByte & 0xf0) >> 4]);
            buf.append(hexDigits[aByte & 0x0f]);
        }
        return buf.toString();
    }

    /**
     * Helper method to add kid claim into to JWT_HEADER.
     *
     * @param certThumbprint     thumbPrint generated for certificate
     * @param signatureAlgorithm relevant signature algorithm
     * @return KID
     */
    private static String getKID(String certThumbprint, String signatureAlgorithm) {

        return certThumbprint + "_" + signatureAlgorithm;
    }

    /**
     * Utility method to sign a JWT assertion with a particular signature algorithm
     *
     * @param assertion          valid JWT assertion
     * @param privateKey         private key which use to sign the JWT assertion
     * @param signatureAlgorithm signature algorithm which use to sign the JWT assertion
     * @return byte array of the JWT signature
     * @throws JWTGeneratorException
     */
    public static byte[] signJwt(String assertion, PrivateKey privateKey, String signatureAlgorithm) throws
            JWTGeneratorException {

        try {
            //initialize signature with private key and algorithm
            Signature signature = Signature.getInstance(signatureAlgorithm);
            signature.initSign(privateKey);

            //update signature with data to be signed
            byte[] dataInBytes = assertion.getBytes(Charset.defaultCharset());
            signature.update(dataInBytes);

            //sign the assertion and return the signature
            return signature.sign();
        } catch (NoSuchAlgorithmException e) {
            //do not log
            throw new JWTGeneratorException("Signature algorithm not found", e);
        } catch (InvalidKeyException e) {
            //do not log
            throw new JWTGeneratorException("Invalid private key provided for signing", e);
        } catch (SignatureException e) {
            //do not log
            throw new JWTGeneratorException("Error while signing JWT", e);
        }
    }
}


text:
#include "absl/strings/str_cat.h"
#include "tensorflow/core/platform/annotation.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/tracing.h"

namespace tensorflow {
namespace {

TEST(ScopedAnnotation, Simple) {
  {
    tracing::ScopedAnnotation trace("blah");
    EXPECT_EQ(Annotation::CurrentAnnotation(), "");  // not enabled
  }

  {
    tracing::ScopedAnnotation::Enable(true);
    tracing::ScopedAnnotation trace("blah");
    EXPECT_EQ(Annotation::CurrentAnnotation(), "blah");  // enabled
    tracing::ScopedAnnotation::Enable(false);
  }
  {
    tracing::ScopedAnnotation::Enable(true);
    tracing::ScopedAnnotation outer("foo");
    tracing::ScopedAnnotation inner("bar");
    EXPECT_EQ(Annotation::CurrentAnnotation(), "foo::bar");  // enabled
    tracing::ScopedAnnotation::Enable(false);
  }

  EXPECT_EQ(Annotation::CurrentAnnotation(), "");  // not enabled
}

std::string GenerateRandomString(int length) {
  return std::string(length, 'a');
}

void BM_ScopedAnnotationDisabled(int iters, int annotation_size) {
  testing::StopTiming();
  std::string annotation = GenerateRandomString(annotation_size);
  testing::StartTiming();
  for (int i = 0; i < iters; i++) {
    tracing::ScopedAnnotation trace(annotation);
  }
  testing::StopTiming();
}

BENCHMARK(BM_ScopedAnnotationDisabled)->Arg(8)->Arg(32)->Arg(128);

void BM_ScopedAnnotationEnabled(int iters, int annotation_size) {
  testing::StopTiming();
  std::string annotation = GenerateRandomString(annotation_size);
  tracing::ScopedAnnotation::Enable(true);
  testing::StartTiming();
  for (int i = 0; i < iters; i++) {
    tracing::ScopedAnnotation trace(annotation);
  }
  testing::StopTiming();
  tracing::ScopedAnnotation::Enable(false);
}

BENCHMARK(BM_ScopedAnnotationEnabled)->Arg(8)->Arg(32)->Arg(128);

void BM_ScopedAnnotationEnabled_Nested(int iters, int annotation_size) {
  testing::StopTiming();
  std::string annotation = GenerateRandomString(annotation_size);
  tracing::ScopedAnnotation::Enable(true);
  testing::StartTiming();
  for (int i = 0; i < iters; i++) {
    tracing::ScopedAnnotation trace(annotation);
    { tracing::ScopedAnnotation trace(annotation); }
  }
  testing::StopTiming();
  tracing::ScopedAnnotation::Enable(false);
}

BENCHMARK(BM_ScopedAnnotationEnabled_Nested)->Arg(8)->Arg(32)->Arg(128);

void BM_ScopedAnnotationEnabled_Adhoc(int iters, int annotation_size) {
  testing::StopTiming();
  tracing::ScopedAnnotation::Enable(true);
  testing::StartTiming();
  for (int i = 0; i < iters; i++) {
    // generate the annotation on the fly.
    tracing::ScopedAnnotation trace(absl::StrCat(i, "-", i * i));
  }
  testing::StopTiming();
  tracing::ScopedAnnotation::Enable(false);
}

BENCHMARK(BM_ScopedAnnotationEnabled_Adhoc)->Arg(8)->Arg(32)->Arg(128);

void BM_ScopedAnnotationDisabled_Lambda(int iters, int annotation_size) {
  for (int i = 0; i < iters; i++) {
    tracing::ScopedAnnotation trace(
        [&]() { return absl::StrCat(i, "-", i * i); });
  }
}

BENCHMARK(BM_ScopedAnnotationDisabled_Lambda)->Arg(8)->Arg(32)->Arg(128);

void BM_ScopedAnnotationEnabled_Adhoc_Lambda(int iters, int annotation_size) {
  tracing::ScopedAnnotation::Enable(true);
  for (int i = 0; i < iters; i++) {
    tracing::ScopedAnnotation trace(
        [&]() { return absl::StrCat(i, "-", i * i); });
  }
  tracing::ScopedAnnotation::Enable(false);
}

BENCHMARK(BM_ScopedAnnotationEnabled_Adhoc_Lambda)->Arg(8)->Arg(32)->Arg(128);

}  // namespace
}  // namespace tensorflow


text:
{% extends CMS_TEMPLATE %}

{% block content %}
    {% block newsblog_content %}
        {# article_list.html and article_detail.html extend this template #}
    {% endblock %}
{% endblock content %}


text:
package fr.arbi.pp;

import java.util.HashMap;

import lombok.Getter;

@Getter
public class Teams {

    private HashMap<String, Team> teams = new HashMap<>();

    Team getTeam(String teamName) {
        Team ret = teams.get(teamName);
        if (ret == null) {
            ret = new Team(teamName);
            teams.put(teamName, ret);
        }
        return ret;
    }

}