text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Aplicacao.Dto;
using Aplicacao.Servico.Fachada;
using Apresentacao.Web.Mvc.Excecao;
using Apresentacao.Web.Mvc.Models;

namespace Apresentacao.Web.Mvc.Controllers
{
	public class TarefaController : Controller
	{
		#region Atributos

		private ITarefaAplicServico tarefaAplicacaoServico;

		#endregion

		#region Construtores
		public TarefaController(ITarefaAplicServico tarefaAplicacaoServico)
		{
			this.tarefaAplicacaoServico = tarefaAplicacaoServico;
		}

		#endregion

		#region Actions

		[HttpPost]
		public ActionResult CadastrarTarefa(TarefaCadastroModel model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					TarefaDto dto = Montador.MontaModeloDominioEViceVersa.Monta(model);

					tarefaAplicacaoServico.CadastrarTarefa(dto);

					return Json(new {TarefaModel = dto},"application/json",Encoding.UTF8);
				}
				else
				{
					HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
					IList<String> erros = new List<String>();
					foreach (ModelState modelState in ViewData.ModelState.Values)
					{
						foreach (ModelError error in modelState.Errors)
						{
							erros.Add(error.ErrorMessage);
						}
					}

					throw new ExcecaoTarefa(Json(erros,"application/json", Encoding.UTF8).ToString());
				}

			}
			catch(ExcecaoTarefa et)
			{
				return Json(new {ExcecaoTarefa = String.Format("Erro: {0}", et.Message)},"application/json",Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		[HttpPut]
		public ActionResult EditarTarefa(TarefaEdicaoModel model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					TarefaDto dto = Montador.MontaModeloDominioEViceVersa.Monta(model);

					tarefaAplicacaoServico.AlterarTarefa(dto);

					return Json(new { TarefaModel = dto },"application/json",Encoding.UTF8);
				}
				else
				{
					HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;

					IList<String> erros = new List<String>();
					foreach (ModelState modelState in ViewData.ModelState.Values)
					{
						foreach (ModelError error in modelState.Errors)
						{
							erros.Add(error.ErrorMessage);
						}
					}

					throw new ExcecaoTarefa(Json(erros,"application/json",Encoding.UTF8).ToString());
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		[HttpDelete]
		public ActionResult ExcluirTarefa(TarefaExcluirModel model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					TarefaDto dto = Montador.MontaModeloDominioEViceVersa.Monta(model);

					tarefaAplicacaoServico.ApagarTarefa(dto);

					return Json(string.Format("Tarefa {0} excluída com sucesso!", dto.Nome),"application/json",Encoding.UTF8);
				}
				else
				{
					HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;

					IList<String> erros = new List<String>();
					foreach (ModelState modelState in ViewData.ModelState.Values)
					{
						foreach (ModelError error in modelState.Errors)
						{
							erros.Add(error.ErrorMessage);
						}
					}

					throw new ExcecaoTarefa(Json(erros,"application/json",Encoding.UTF8).ToString());
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		[HttpPatch]
		public ActionResult ExecutarTarefa(TarefaEdicaoModel model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					TarefaDto dto = Montador.MontaModeloDominioEViceVersa.Monta(model);
					tarefaAplicacaoServico.MarcarTarefaComoConcluida(dto);

					return Json(String.Format("Tarefa {0} marcada como 'Executada'!", dto.Nome),"application/json",Encoding.UTF8);
				}
				else
				{
					HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;

					IList<String> erros = new List<String>();
					foreach (ModelState modelState in ViewData.ModelState.Values)
					{
						foreach (ModelError error in modelState.Errors)
						{
							erros.Add(error.ErrorMessage);
						}
					}

					throw new ExcecaoTarefa(Json(erros,"application/json",Encoding.UTF8).ToString());
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		/// <summary>
		/// Lista todas as tarefas
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		public ActionResult TodasAsTarefas(Nullable<long> idUsuario)
		{
			try
			{
				TarefaDto dto = new TarefaDto()
				{
					Usuario = new UsuarioDto()
					{
						Id = idUsuario
					}
				};

				ICollection<TarefaDto> dtos = tarefaAplicacaoServico.ListarTodasAsTarefasDoUsuario(dto);

				if (dtos != null && dtos.Count > 0)
				{
					ICollection<TarefaListarModel> models = Montador.MontaModeloDominioEViceVersa.Monta(dtos);

					return Json(new { TarefaModel = dtos },"application/json",Encoding.UTF8);
				}
				else
				{
					return null;
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		[HttpGet]
		public ActionResult TarefasExecutadas(Nullable<long> idUsuario)
		{
			try
			{
				TarefaDto dto = new TarefaDto()
				{
					Usuario = new UsuarioDto()
					{
						Id = idUsuario
					}
				};

				ICollection<TarefaDto> dtos = tarefaAplicacaoServico.ListarTarefasConcluidas(dto);

				if (dtos != null && dtos.Count > 0)
				{
					ICollection<TarefaListarModel> models = Montador.MontaModeloDominioEViceVersa.Monta(dtos);

					return Json(new { TarefaModel = dtos }, "application/json", Encoding.UTF8);
				}
				else
				{
					return null;
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}

		}

		[HttpGet]
		public ActionResult TarefasVencidas(Nullable<long> idUsuario)
		{
			try
			{
				TarefaDto dto = new TarefaDto()
				{
					Usuario = new UsuarioDto()
					{
						Id = idUsuario
					}
				};

				ICollection<TarefaDto> dtos = tarefaAplicacaoServico.ListarTarefasAtrasadas(dto);

				if (dtos != null && dtos.Count > 0)
				{
					ICollection<TarefaListarModel> models = Montador.MontaModeloDominioEViceVersa.Monta(dtos);

					return Json(new { TarefaModel = dtos }, "application/json", Encoding.UTF8);
				}
				else
				{
					return null;
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		[HttpGet]
		public ActionResult TarefasAVencer(Nullable<long> idUsuario)
		{
			try
			{
				TarefaDto dto = new TarefaDto()
				{
					Usuario = new UsuarioDto()
					{
						Id = idUsuario
					}
				};

				ICollection<TarefaDto> dtos = tarefaAplicacaoServico.ListarTarefasAVencer(dto);

				if (dtos != null && dtos.Count > 0)
				{
					ICollection<TarefaListarModel> models = Montador.MontaModeloDominioEViceVersa.Monta(dtos);

					return Json(new { TarefaModel = dtos }, "application/json", Encoding.UTF8);
				}
				else
				{
					return null;
				}
			}
			catch (ExcecaoTarefa et)
			{
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", et.Message) }, "application/json", Encoding.UTF8);
			}
			catch (Exception ex)
			{
				HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
				return Json(new { ExcecaoTarefa = String.Format("Erro: {0}", ex.Message) }, "application/json", Encoding.UTF8);
			}
		}

		#endregion
	}
}


text:
namespace velox {
template <class T>
void optimization_barrier(T &&t) {
  const char *p = reinterpret_cast<const char *>(&t);
  std::atomic_signal_fence(std::memory_order_seq_cst);

  if (volatile bool b = false) {
    _exit(*p);
  }
}

// On windows XP and up QueryPerformanceFrequency and QueryPerformanceCounter are documented to
// never fail so the return values are not checked
namespace {
  const double QPC_NANOS_PER_TICK = []() -> double {
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    return 1000000000.0 / frequency.QuadPart;
  }();
}

struct WindowsHighResolutionClock {
  using rep = std::int64_t;
  using period = std::nano;
  using duration = std::chrono::duration<rep, period>;
  using time_point = std::chrono::time_point<WindowsHighResolutionClock>;
  static const bool is_steady = true;

  static time_point now() {
    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return time_point(duration(static_cast<rep>(count.QuadPart * QPC_NANOS_PER_TICK)));
  }
};

using DefaultClock = WindowsHighResolutionClock;

struct ProcessCPUClock {
  using rep = std::int64_t;
  using period = std::nano;
  using duration = std::chrono::duration<rep, period>;
  using time_point = std::chrono::time_point<ProcessCPUClock>;
  static const bool is_steady = true;

  static time_point now() {
    FILETIME creation, exit, kernel, user;
    if (GetProcessTimes(GetCurrentProcess(), &creation, &exit, &kernel, &user)) {
      auto to_nanos = [](FILETIME ft) -> ULONGLONG {
        ULARGE_INTEGER li;
        li.LowPart = ft.dwLowDateTime;
        li.HighPart = ft.dwHighDateTime;
        // ft has units of 100ns
        return li.QuadPart * 100;
      };

      return time_point(duration(static_cast<rep>(to_nanos(kernel) + to_nanos(user))));
    }

    assert(false && "GetProcessTimes failed");
    return time_point();
  }
};

namespace detail {
  template <class T>
  std::string unmangled_name() {
    return typeid(T).name();
  }
}
}

#endif // VELOX_MSVC_UTIL_H_INCLUDED

redpajama_set_name: RedPajamaGithub


text:
from gi.repository import MesonSub

if __name__ == "__main__":
    s = MesonSub.Sample.new("Hello, sub/meson/py!")
    s.print_message()


text:
#pragma once

#include <windows.h>
#include <d3d11_1.h>

namespace DX
{
	//--------------------------------------------------------------------------------------
	// Helper for compiling shaders with D3DCompile
	//
	// With VS 11, we could load up prebuilt .cso files instead...
	//--------------------------------------------------------------------------------------
	inline HRESULT CompileShaderFromFile(
		WCHAR* szFileName,
		LPCSTR szEntryPoint,
		LPCSTR szShaderModel,
		ID3DBlob** ppBlobOut)
	{
		HRESULT hr = S_OK;

		DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
		// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
		// Setting this flag improves the shader debugging experience, but still allows
		// the shaders to be optimized and to run exactly the way they will run in
		// the release configuration of this program.
		dwShaderFlags |= D3DCOMPILE_DEBUG;

		// Disable optimizations to further improve shader debugging
		dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif

		ID3DBlob* pErrorBlob = nullptr;
		hr = D3DCompileFromFile(szFileName, nullptr, nullptr, szEntryPoint, szShaderModel,
			dwShaderFlags, 0, ppBlobOut, &pErrorBlob);

		if (FAILED(hr))
		{
			if (pErrorBlob)
			{
				OutputDebugStringA(reinterpret_cast<const char*>(pErrorBlob->GetBufferPointer()));
				pErrorBlob->Release();
			}

			return hr;
		}

		if (pErrorBlob)
		{
			pErrorBlob->Release();
		}

		return S_OK;
	}
}


text:
package com.github.ambry.router;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.github.ambry.clustermap.ClusterMap;
import com.github.ambry.clustermap.PartitionId;
import com.github.ambry.clustermap.ReplicaId;
import com.github.ambry.commons.BlobId;
import com.github.ambry.commons.ResponseHandler;
import com.github.ambry.commons.ServerErrorCode;
import com.github.ambry.config.RouterConfig;
import com.github.ambry.messageformat.MessageFormatFlags;
import com.github.ambry.network.ResponseInfo;
import com.github.ambry.protocol.GetOption;
import com.github.ambry.protocol.GetRequest;
import com.github.ambry.protocol.GetResponse;
import com.github.ambry.protocol.PartitionRequestInfo;
import com.github.ambry.utils.Time;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An abstract class for a get operation.
 */
abstract class GetOperation {
  protected final RouterConfig routerConfig;
  protected final NonBlockingRouterMetrics routerMetrics;
  protected final ClusterMap clusterMap;
  protected final ResponseHandler responseHandler;
  protected final Callback<GetBlobResultInternal> getOperationCallback;
  protected final BlobId blobId;
  protected final GetBlobOptionsInternal options;
  protected final Time time;
  private final Histogram localColoTracker;
  private final Histogram crossColoTracker;
  private final Counter pastDueCounter;
  protected volatile boolean operationCompleted = false;
  protected final AtomicReference<Exception> operationException = new AtomicReference<>();
  protected GetBlobResultInternal operationResult;
  protected final long submissionTimeMs;

  private static final Logger logger = LoggerFactory.getLogger(GetOperation.class);

  /**
   * Construct a GetOperation
   * @param routerConfig the {@link RouterConfig} containing the configs for put operations.
   * @param routerMetrics The {@link NonBlockingRouterMetrics} to be used for reporting metrics.
   * @param clusterMap the {@link ClusterMap} of the cluster
   * @param responseHandler the {@link ResponseHandler} responsible for failure detection.
   * @param blobIdStr the blobId of the associated blob in string form.
   * @param options the {@link GetBlobOptionsInternal} associated with this operation.
   * @param getOperationCallback the callback that is to be called when the operation completes.
   * @param localColoTracker the {@link Histogram} that tracks intra datacenter latencies for this class of requests.
   * @param crossColoTracker the {@link Histogram} that tracks inter datacenter latencies for this class of requests.
   * @param pastDueCounter the {@link Counter} that tracks the number of times a request is past due.
   * @param time the {@link Time} instance to use.
   * @throws RouterException if there is an error with any of the parameters, such as an invalid blob id.
   */
  GetOperation(RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ClusterMap clusterMap,
      ResponseHandler responseHandler, String blobIdStr, GetBlobOptionsInternal options,
      Callback<GetBlobResultInternal> getOperationCallback, Histogram localColoTracker, Histogram crossColoTracker,
      Counter pastDueCounter, Time time) throws RouterException {
    this.routerConfig = routerConfig;
    this.routerMetrics = routerMetrics;
    this.clusterMap = clusterMap;
    this.responseHandler = responseHandler;
    this.options = options;
    this.getOperationCallback = getOperationCallback;
    this.localColoTracker = localColoTracker;
    this.crossColoTracker = crossColoTracker;
    this.pastDueCounter = pastDueCounter;
    this.time = time;
    submissionTimeMs = time.milliseconds();
    blobId = RouterUtils.getBlobIdFromString(blobIdStr, clusterMap);
    validateTrackerType();
  }

  /**
   * Return the {@link Callback} associated with this operation.
   * @return the {@link Callback} associated with this operation.
   */
  Callback<GetBlobResultInternal> getCallback() {
    return getOperationCallback;
  }

  /**
   * The exception associated with this operation if it failed; null otherwise.
   * @return exception associated with this operation if it failed; null otherwise.
   */
  Exception getOperationException() {
    return operationException.get();
  }

  /**
   * Return the result of the operation.
   * @return the operation result.
   */
  GetBlobResultInternal getOperationResult() {
    return operationResult;
  }

  /**
   * Return the blob id string
   * @return return the blob id string
   */
  String getBlobIdStr() {
    return blobId.getID();
  }

  /**
   * @return The {@link GetBlobOptions} associated with this operation.
   */
  GetBlobOptionsInternal getOptions() {
    return options;
  }

  /**
   * returns whether the operation has completed.
   * @return whether the operation has completed.
   */
  boolean isOperationComplete() {
    return operationCompleted;
  }

  /**
   * For this operation, create and populate get requests to send out.
   * @param requestRegistrationCallback the {@link RequestRegistrationCallback} to call for every request that gets
   *                                    created as part of this poll operation.
   */
  abstract void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback);

  /**
   * Handle the given {@link ResponseInfo} received for a request that was sent out.
   * @param responseInfo the {@link ResponseInfo} to be handled.
   * @param getResponse the {@link GetResponse} associated with this response.
   */
  abstract void handleResponse(ResponseInfo responseInfo, GetResponse getResponse);

  /**
   * Abort operation by invoking any callbacks and updating futures with an exception.
   * @param abortCause the exception that is the cause for the abort.
   */
  abstract void abort(Exception abortCause);

  /**
   * Set the exception associated with this operation.
   * A {@link ServerErrorCode#Blob_Deleted} or {@link ServerErrorCode#Blob_Expired} error overrides any other
   * previously received exception.
   * @param exception the {@link RouterException} to possibly set.
   */
  void setOperationException(Exception exception) {
    if (exception instanceof RouterException) {
      RouterErrorCode routerErrorCode = ((RouterException) exception).getErrorCode();
      if (operationException.get() == null || routerErrorCode == RouterErrorCode.BlobDeleted
          || routerErrorCode == RouterErrorCode.BlobExpired) {
        operationException.set(exception);
      }
    } else {
      if (operationException.get() == null) {
        operationException.set(exception);
      }
    }
  }

  /**
   * Create and return the {@link GetRequest} associated with the given blobId.
   * @return the created {@link GetRequest}.
   * @param blobId The {@link BlobId} for which the {@link GetRequest} is being created.
   * @param flag The {@link MessageFormatFlags} to be set with the GetRequest.
   * @return the created GetRequest.
   */
  protected GetRequest createGetRequest(BlobId blobId, MessageFormatFlags flag, GetOption getOption) {
    List<BlobId> blobIds = Collections.singletonList(blobId);
    List<PartitionRequestInfo> partitionRequestInfoList =
        Collections.singletonList(new PartitionRequestInfo(blobId.getPartition(), blobIds));
    return new GetRequest(NonBlockingRouter.correlationIdGenerator.incrementAndGet(), routerConfig.routerHostname, flag,
        partitionRequestInfoList, getOption);
  }

  /**
   * Gets an {@link OperationTracker} based on the config and {@code partitionId}.
   * @param partitionId the {@link PartitionId} for which a tracker is required.
   * @return an {@link OperationTracker} based on the config and {@code partitionId}.
   */
  protected OperationTracker getOperationTracker(PartitionId partitionId) {
    OperationTracker operationTracker;
    String trackerType = routerConfig.routerGetOperationTrackerType;
    if (trackerType.equals(SimpleOperationTracker.class.getSimpleName())) {
      operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId,
          routerConfig.routerGetCrossDcEnabled, routerConfig.routerGetSuccessTarget,
          routerConfig.routerGetRequestParallelism);
    } else if (trackerType.equals(AdaptiveOperationTracker.class.getSimpleName())) {
      operationTracker = new AdaptiveOperationTracker(routerConfig.routerDatacenterName, partitionId,
          routerConfig.routerGetCrossDcEnabled, routerConfig.routerGetSuccessTarget,
          routerConfig.routerGetRequestParallelism, time, localColoTracker, crossColoTracker, pastDueCounter,
          routerConfig.routerLatencyToleranceQuantile);
    } else {
      throw new IllegalArgumentException("Unrecognized tracker type: " + trackerType);
    }
    return operationTracker;
  }

  /**
   * Validates the tracker type in config.
   */
  private void validateTrackerType() {
    String trackerType = routerConfig.routerGetOperationTrackerType;
    if (!trackerType.equals(SimpleOperationTracker.class.getSimpleName()) && !trackerType.equals(
        AdaptiveOperationTracker.class.getSimpleName())) {
      throw new IllegalArgumentException("Unrecognized tracker type: " + trackerType);
    }
  }
}

/**
 * A class that holds information about the get requests sent out.
 */
class GetRequestInfo {
  final ReplicaId replicaId;
  final long startTimeMs;

  /**
   * Construct a GetRequestInfo
   * @param replicaId the replica to which this request is being sent.
   * @param startTimeMs the time at which this request was created.
   */
  GetRequestInfo(ReplicaId replicaId, long startTimeMs) {
    this.replicaId = replicaId;
    this.startTimeMs = startTimeMs;
  }
}


text:
""" Transformer
    - Contains the code to implement a transformer cell
"""
# Adapted from: https://github.com/openai/gpt-2/blob/master/src/model.py - MIT License
import collections
import logging
import sys
assert 'tensorflow' in sys.modules, 'You need to import TF before importing this module.'

from diplomacy_research.utils.tensorflow import ops
from diplomacy_research.utils.tensorflow import pad_axis
from diplomacy_research.utils.tensorflow import tensor_shape
from diplomacy_research.utils.tensorflow import array_ops, gen_array_ops
from diplomacy_research.utils.tensorflow import contrib_framework
from diplomacy_research.utils.tensorflow import core
from diplomacy_research.utils.tensorflow import dtypes
from diplomacy_research.utils.tensorflow import embedding_lookup
from diplomacy_research.utils.tensorflow import gelu
from diplomacy_research.utils.tensorflow import init_ops
from diplomacy_research.utils.tensorflow import math_ops, gen_math_ops
from diplomacy_research.utils.tensorflow import nn_ops
from diplomacy_research.utils.tensorflow import nest
from diplomacy_research.utils.tensorflow import rnn_cell_impl
from diplomacy_research.utils.tensorflow import variable_scope

# Constants
LOGGER = logging.getLogger(__name__)

def _get_embedding_fn(embedding):
    """ Returns a callable embedding function """
    return embedding if callable(embedding) else (lambda ids: embedding_lookup(embedding, ids))

class TransformerCellState(
        collections.namedtuple('TransformerCellState', ('past_attentions',      # Past attentions
                                                        'feeder_state',         # The state of the feeder cell
                                                        'time'))):              # The current time step
    """ `namedtuple` storing the state of a `TransformerCellState`. """

    def clone(self, **kwargs):
        """ Clone this object, overriding components provided by kwargs. """
        def with_same_shape(old, new):
            """Check and set new tensor's shape."""
            if isinstance(old, ops.Tensor) and isinstance(new, ops.Tensor):
                return contrib_framework.with_same_shape(old, new)
            return new
        return nest.map_structure(with_same_shape, self, super(TransformerCellState, self)._replace(**kwargs))

class TransformerCell(rnn_cell_impl.RNNCell):
    """ Transformer RNN cell that conditions optionally on a previous context and feeder cell
        This is a uni-directional implementation, where attention is only on the current and previous outputs
    """

    def __init__(self, nb_layers, nb_heads, word_embedding, position_embedding, batch_size, feeder_cell=None,
                 feeder_init_state=None, past_attentions=None, context=None, context_word_embedding=None,
                 past_seq_lengths=None, scope=None, name=None):
        """ Uni-directional transformer cell
            :param nb_layers: The number of layers to use
            :param nb_heads: The number of attention heads to use
            :param word_embedding: The word embedding vector - [vocab_size, emb_size]
            :param position_embedding: The position embedding vector - [context_size, emb_size]
            :param batch_size: The current batch size - Scalar
            :param feeder_cell: Optional. An other RNN cell that returns additional inputs to condition on.
            :param feeder_init_state: Optional. The initial state of the feeder.
            :param past_attentions: Optional. The past_attention tensor from the final state of another cell.
            :param context: Optional. A list of tokens to use as context (initial input of the sequence) - (b, seq_len)
            :param context_word_embedding: The word embedding vector to embed words in the context - [ctxt_voc, emb_sz]
            :param past_seq_lengths: Optional. The len of each item in the past_attentions or context (b,)
            :param scope: Optional. Scope to use to properly share parameters.
            :param name: Optional scope name.
        """
        # pylint: disable=too-many-arguments
        # Initializing RNN Cell
        super(TransformerCell, self).__init__(name=name)

        # Setting values
        self._nb_layers = nb_layers
        self._nb_heads = nb_heads
        self._word_embedding = word_embedding                                               # [vocab_size, emb_size]
        self._position_embedding_fn = _get_embedding_fn(position_embedding)
        self._feeder_cell = feeder_cell
        self._feeder_init_state = feeder_init_state
        self._past_attns = past_attentions
        self._context = None
        self._context_word_embedding_fn = lambda ids: ids
        self._past_seq_lengths = past_seq_lengths
        self._scope = scope

        # Infering shapes
        self._batch_size = batch_size
        self._vocab_size = word_embedding.shape.as_list()[0]
        self._emb_size = word_embedding.shape.as_list()[1]
        self._position_emb_size = position_embedding.shape.as_list()[0]
        assert self._emb_size % self._nb_heads == 0, 'The embedding size must be perfectly divisible by the nb of heads'

        # Cannot provide both a context and a past_attentions tensor array
        assert past_attentions is None or context is None, 'Cannot provide both a context and past_attentions'

        # Validating context
        if context is not None:
            assert context_word_embedding is not None, 'Arg "context_word_embedding" is required when context provided.'
            if feeder_cell is not None:
                LOGGER.warning('The feeder cell will not be applied on the context.')
                LOGGER.warning('Otherwise, use "past_attentions" on the output of another transformer cell.')
            self._context = context
            self._context_word_embedding_fn = _get_embedding_fn(context_word_embedding)

    @property
    def output_size(self):
        """ Returns the cell output size """
        return self._emb_size

    @property
    def state_size(self):
        """ The `state_size` property of `TransformerCell` """
        past_attns_shape = [self._nb_layers, 2, self._nb_heads, None, self._emb_size // self._nb_heads]
        feeder_state_shape = tensor_shape.TensorShape([]) if self._feeder_cell is None else self._feeder_cell.state_size
        return TransformerCellState(past_attentions=tensor_shape.TensorShape(past_attns_shape),
                                    feeder_state=feeder_state_shape,
                                    time=tensor_shape.TensorShape([]))

    def zero_state(self, batch_size, dtype):
        """ Return an initial (zero) state tuple for this `IdentityCell`.
            :param batch_size: `0D` integer tensor: the batch size.
            :param dtype: The internal state data type.
            :return: A zeroed out scalar representing the initial state of the cell.
        """
        with ops.name_scope(type(self).__name__ + 'ZeroState', values=[batch_size]):
            if self._feeder_cell is None:
                feeder_init_state = array_ops.zeros([], dtype=dtype)
            elif self._feeder_init_state is not None:
                feeder_init_state = self._feeder_init_state
            else:
                feeder_init_state = self._feeder_cell.zero_state(batch_size, dtype)

            # Empty past attentions
            if self._past_attns is None:
                head_size = self._emb_size // self._nb_heads
                past_attns_shape = [batch_size, self._nb_layers, 2, self._nb_heads, 0 * batch_size, head_size]
                self._past_attns = array_ops.zeros(past_attns_shape, dtype=dtypes.float32)

            # No Context - Returning a zero past attention
            if self._context is None:
                return TransformerCellState(past_attentions=self._past_attns,
                                            feeder_state=feeder_init_state,
                                            time=array_ops.zeros([], dtype=dtypes.int32))

            # Context provided - Computing attention by running a single block step
            _, present_attns, _ = self._step(inputs=self._context_word_embedding_fn(self._context),
                                             past_attns=self._past_attns,
                                             time=0,
                                             feeder_cell=None,
                                             feeder_state=None)
            return TransformerCellState(past_attentions=present_attns,
                                        feeder_state=feeder_init_state,
                                        time=array_ops.zeros([], dtype=dtypes.int32))

    def compute_output_shape(self, input_shape):
        """ Computes the output shape of the given layer """
        input_shape = tensor_shape.TensorShape(input_shape)
        input_shape = input_shape.with_rank_at_least(2)
        return input_shape[:-1].concatenate(self.output_size)

    def call(self, inputs, state):  # pylint: disable=arguments-differ
        """ Runs the identity cell
            :param inputs: Tensor of shpae - [batch, emb_size]
            :param state: The state from the previous time step.
            :return: The cell output and the next state
        """
        if not isinstance(state, TransformerCellState):
            raise TypeError('Expected state to be instance of TransformerCellState. Received type %s instead.'
                            % type(state))

        past_attns, feeder_state, time = state
        cell_outputs, present_attns, next_feeder_state = self._step(inputs[:, None, :], past_attns, time,
                                                                    feeder_cell=self._feeder_cell,
                                                                    feeder_state=feeder_state)
        cell_outputs = array_ops.squeeze(cell_outputs, axis=1)

        # Updating feeder cell state - 'feeder' processing mode.
        if self._feeder_cell is not None and hasattr(self._feeder_cell, 'update_state'):
            next_feeder_state = getattr(self._feeder_cell, 'update_state')(time, cell_outputs, next_feeder_state)

        # Computing next_state
        next_state = TransformerCellState(past_attentions=array_ops.concat([past_attns, present_attns], axis=-2),
                                          feeder_state=next_feeder_state,
                                          time=time + 1)
        return cell_outputs, next_state

    def _step(self, inputs, past_attns, time, feeder_cell, feeder_state):
        """ Performs the block operation on n-layers
            :param inputs: The tensor inputs (embedding of each word) - [batch, seq_len, emb_size]
            :param past_attns: The past attentions - [batch, nb_layers, 2, nb_heads. past_length, emb_size // nb_heads]
            :param time: A tensor representing the current time step
            :param feeder_cell: None or A feeder cell that returns a RNN cell output to use for conditioning
            :param feeder_state: None or the initial state of the feeder cell
            :param name: Name of the scope - To share weights between calls
            :return: A tuple consisting of:
                        1) The cell outputs - [batch, seq_len, emb_size]
                        2) The present attention - [batch, nb_layers, 2, nb_heads. seq_len, emb_size // nb_heads]
                        3) The new state of the feeder cell
        """
        with variable_scope.variable_scope(self._scope, default_name='step'):
            past_length = array_ops.shape(past_attns)[-2]       # How many past attention steps we have
            seq_len = array_ops.shape(inputs)[-2]               # How many steps are we computing for the current time
            emb_size = inputs.shape[-1].value                   # The size of the embedding
            assert emb_size == self._emb_size, 'Expected an embedding size of %d' % self._emb_size

            # 1) Computing the word embedding of each token
            assert inputs.shape.ndims == 3, 'Expected [batch, seq_len, emb_size]'                   # [bz, seq, emb]
            out_h = inputs

            # 2) Computing the position embedding of each token
            # If we know the context was padded, the effective past length is the context length + nb of time steps
            if self._past_seq_lengths is not None:
                past_length = gen_math_ops.minimum(past_length, self._past_seq_lengths + time)[:, None]     # [bz, 1]
            else:
                past_length = gen_array_ops.fill([self._batch_size, 1], value=past_length)                  # [bz, 1]
            step_ix = math_ops.range(seq_len)[None, :]                                              # [1, seq_len]
            token_positions = gen_math_ops.add(past_length, step_ix)                                # [batch, seq_len]
            token_positions = gen_math_ops.minimum(self._position_emb_size - 1, token_positions)    # [batch, seq_len]
            h_pos = self._position_embedding_fn(token_positions)                                    # [bz, seq, emb]
            out_h = out_h + h_pos

            # 3) If we have a feeder cell, we also need to condition 'h' on it.
            next_feeder_state = feeder_state
            if feeder_cell is not None:
                assert feeder_state is not None, 'A feeder state is required if a feeder cell is provided.'
                assert inputs.shape[1].value == 1, 'The seq dimension must be 1 to use a feeder_cell'
                feeder_outputs, next_feeder_state = feeder_cell(array_ops.squeeze(inputs, axis=1), feeder_state)
                h_feed = feeder_outputs                                                             # [bz, feeder_sz]
                if feeder_outputs.shape[-1].value != emb_size:
                    h_feed = core.Dense(emb_size, activation=None, name='h_feed')(h_feed)           # [bz, emb]
                h_feed = gen_array_ops.tile(h_feed[:, None, :], [1, seq_len, 1])                    # [bz, seq, emb]
                out_h = out_h + h_feed

            # Transformer
            presents = []
            pasts = array_ops.unstack(past_attns, axis=1)                # list of [batch, 2, heads, past_len, head_sz]
            assert len(pasts) == self._nb_layers, 'Expected the past attention to have %d layers.' % self._nb_layers

            for layer_ix, past_attn in enumerate(pasts):
                out_h, present = self._block(out_h, past_attn, 'layer.%d' % layer_ix)
                presents += [present]
            presents = array_ops.stack(presents, axis=1)

            # Normalizing and returning
            cell_outputs = self._norm(out_h, 'norm_h')                                          # [batch, seq, emb]
            return cell_outputs, presents, next_feeder_state

    @staticmethod
    def _conv1d(inputs, output_dim, name=None):
        """ Performs 1d convolution
            :param inputs: The tensor inputs - [axis_0, ..., axis_n-1, input_dim]
            :param output_dim: The size of the 1d convoltuion
            :param name: Name of the scope - To share weights between calls
            :return: The tensors after the convolution - [axis_0, ..., axis_n-1, output_dim]
        """
        with variable_scope.variable_scope(name):
            input_dims = [array_ops.shape(inputs)[axis] if dim.value is None else dim.value
                          for axis, dim in enumerate(inputs.shape)]
            input_prefix_dims, input_last_dim = input_dims[:-1], input_dims[-1]
            weight = variable_scope.get_variable('w',
                                                 shape=[input_last_dim, output_dim],
                                                 initializer=init_ops.random_normal_initializer(0.02))
            beta = variable_scope.get_variable('b',
                                               shape=[output_dim],
                                               initializer=init_ops.constant_initializer(0.))

            inputs = gen_array_ops.reshape(inputs, [-1, input_last_dim])                    # [B, input_last_dim]
            outputs = math_ops.matmul(inputs, weight) + beta                                # [B, output_dim]
            return gen_array_ops.reshape(outputs, input_prefix_dims + [output_dim])         # [..., output_dim]

    @staticmethod
    def _norm(inputs, name, axis=-1):
        """ Applies normalization to the input tensor by normalizing to mean=0, std_dev=1, then applying a gamma, beta
            :param inputs: The tensor inputs to normalize
            :param name: Name of the scope - To share weights between calls
            :param axis: Axis to normalize. Defaults to last one.
            :return: A tensor of the same shape as inputs, but normalized and transformed
        """
        with variable_scope.variable_scope(name):
            axis_dim = inputs.shape[axis].value
            gamma = variable_scope.get_variable('gamma', [axis_dim], initializer=init_ops.constant_initializer(1.))
            beta = variable_scope.get_variable('beta', [axis_dim], initializer=init_ops.constant_initializer(0.))
            mean = math_ops.reduce_mean(inputs, axis=axis, keepdims=True)
            var = math_ops.reduce_mean(gen_math_ops.square(inputs - mean), axis=axis, keepdims=True)
            norm_inputs = (inputs - mean) * gen_math_ops.rsqrt(var + 1e-8)
            outputs = gamma * norm_inputs + beta
            return outputs

    def _mask_attn_weights(self, attn_weights):
        """ Masks the attention weights
            :param attn_weights: The attention weights - [batch, nb_head, seq_len, seq_len + past_length]
            :return: A tensor of 0 and 1. of the same shape and dtype as attn_weights
        """
        seq_len = array_ops.shape(attn_weights)[-2]
        total_len = array_ops.shape(attn_weights)[-1]

        # 1) Creating the attention mask matrix (with the lower triangle set to 1. on the right)
        # e.g. if seq_len == 3, and total_len == 10
        # the attention mask would be:       - [seq_len, total_len]
        # [[1., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
        #  [1., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
        #  [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]
        num_lower = math_ops.cast(-1, dtypes.int32)
        num_upper = total_len - seq_len
        attn_mask = gen_array_ops.matrix_band_part(array_ops.ones([seq_len, total_len]), num_lower, num_upper)

        # No past_attentions/context - We just add two leading dimensions to attn_mask and can return it
        if self._past_seq_lengths is None:
            return attn_mask[None, None, :, :]

        # If we have a context with varying sequence length, we also need to mask the items after the end of sequence
        # e.g.
        # [[1., 1., 1., 0., 0., 0., 0., 1., 1., 1.],            # => length of 3 (padded to 7) + seq_len of 3
        #  [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],            # => length of 7 (padded to 7) + seq_len of 3
        #  [1., 1., 1., 1., 1., 0., 0., 1., 1., 1.]]            # => length of 5 (padded to 7) + seq_len of 3
        #
        # The resulting attention mask would be the product of the two.
        # [[1., 1., 1., 0., 0., 0., 0., 1., 0., 0.],
        #  [1., 1., 1., 1., 1., 1., 1., 1., 1., 0.],
        #  [1., 1., 1., 1., 1., 0., 0., 1., 1., 1.]]
        seq_mask = array_ops.sequence_mask(self._past_seq_lengths, dtype=dtypes.float32)        # [b, max_len]
        seq_mask = pad_axis(seq_mask, axis=-1, min_size=total_len)                              # [b, total_len]

        # Returning the multiplication of the two masks
        return gen_math_ops.mul(attn_mask[None, None, :, :], seq_mask[:, None, None, :])    # [b, nb_heads, seq, total]

    def _attn(self, inputs, attn_dim, past_attn, name):
        """ Performs multi-head attention inside a transformer block
            :param inputs: The tensor inputs - [batch, seq_len, emb_size]
            :param attn_dim: The dimension of the attention (and output)
            :param past_attn: The past attention - [batch, 2, nb_heads. seq_len, emb_size // nb_heads]
            :param name: Name of the scope - To share weights between calls
            :return: A tuple consisting of:
                    1) The output of the attention - [batch, seq_len, attn_dim]
                    2) The present attention - [batch, 2, nb_heads, seq_len, emb_size // nb_heads]
        """
        assert inputs.shape.ndims == 3, 'Expected [batch, seq_len, emb_size]'
        with variable_scope.variable_scope(name):

            # Computing the query, key, and value vectors
            query_keys_values = self._conv1d(inputs, 3 * attn_dim, 'attn_fc1')      # [batch, seq_len, 3 * attn_dim]
            query, keys, values = array_ops.split(query_keys_values, 3, axis=-1)    # 3x [batch, seq_len, attn_dim]

            # Splitting into nb_heads of size attn_dim // nb_heads
            # Output format is [batch, nb_heads, seq_len, attn_dim // nb_heads]
            query = self._split_in_heads(query)                                     # [bz, nb_heads, seq_len, head_sz]
            keys = self._split_in_heads(keys)                                       # [bz, nb_heads, seq_len, head_sz]
            values = self._split_in_heads(values)                                   # [bz, nb_heads, seq_len, head_sz]
            head_size = query.shape[-1].value

            # Stacking keys and values to get the present_attn
            present_attn = array_ops.stack([keys, values], axis=1)              # [bz, 2, nb_heads, seq_len, head_sz]

            # Adding past_attn to keys and values
            past_keys, past_values = array_ops.unstack(past_attn, 2, axis=1)    # 2x [bz, nb_heads, past_len, head_sz]
            keys = array_ops.concat([past_keys, keys], axis=-2)                 # [bz, nb_heads, total_len, head_sz]
            values = array_ops.concat([past_values, values], axis=-2)           # [bz, nb_heads, total_len, head_sz]

            # Performing multi-head attention
            attn_w = math_ops.matmul(query, keys, transpose_b=True)             # [bz. nb_heads, seq_len, total_len]
            attn_w = attn_w * gen_math_ops.rsqrt(math_ops.cast(head_size, attn_w.dtype) + 1e-8)
            attn_mask = self._mask_attn_weights(attn_w)                         # [bz, 1, seq_len, total_len]
            attn_w = attn_w * attn_mask + math_ops.cast(1e-10, attn_w.dtype) * (1. - attn_mask)
            attn_w = nn_ops.softmax(attn_w)
            attn = math_ops.matmul(attn_w, values)                              # [bz, nb_heads, seq_len, head_sz]

            # Merging attention heads, then 1d conv before returning
            out_attn = self._merge_heads(attn)                                  # [bz, seq_len, attn_dim]
            out_attn = self._conv1d(out_attn, attn_dim, 'attn_fc2')             # [bz, seq_len, attn_dim]

            # Returning
            return out_attn, present_attn

    def _block(self, inputs, past_attn, name):
        """ Computes a transformer block
            :param inputs: The inputs tensor - [batch, seq_len, emb_dim]
            :param past_attn: The past attention - [batch, 2, nb_heads, emb_size // nb_heads]
            :param name: Name of the scope - To share weights between calls
            :return: A tuple consisting of:
                    1) The output of the transformer block - [batch, seq_len, emb_dim]
                    2) The present attention - [batch, 2, nb_heads, 1, emb_size // nb_heads]
        """
        with variable_scope.variable_scope(name):
            input_dim = inputs.shape[-1].value
            h_out = inputs
            h_attn, present_attn = self._attn(self._norm(h_out, 'block_norm1'), input_dim, past_attn, 'block_attn')
            h_out = h_out + h_attn
            h_mlp = self._linear(self._norm(h_out, 'block_norm2'), input_dim * 4, 'block_mlp')
            h_out = h_out + h_mlp
            return h_out, present_attn

    def _linear(self, inputs, proj_dim, name):
        """ Computes a linear unit inside a full block - Projects to 'proj_dim' and back to 'input_dim'
            :param inputs: The inputs tensor -  [axis_0, ..., axis_n-1, input_dim]
            :param proj_dim: The dimension of the projection
            :param name: Name of the scope - To share weights between calls
            :return: A tensor of shape -  [axis_0, ..., axis_n-1, input_dim]
        """
        with variable_scope.variable_scope(name):
            input_dim = inputs.shape[-1].value
            output_h1 = gelu(self._conv1d(inputs, proj_dim, 'mlp_fc1'))
            output_h2 = self._conv1d(output_h1, input_dim, 'mlp_fc2')
            return output_h2

    def _split_in_heads(self, inputs):
        """ Splits the tensor into heads of size attn_dim / heads
            :param inputs: The tensor to split - [batch, seq_len, attn_dim]
            :return: A tensor in the format - [batch, nb_heads, seq_len, attn_dim // nb_heads]
        """
        assert inputs.shape.ndims == 3, 'Expected inputs to be [batch, seq_len, attn_dim]'
        attn_dim = inputs.shape[-1].value
        assert attn_dim % self._nb_heads == 0, 'The attn_dim must be evenly divisible by the nb of heads'

        # Reshaping to [batch, seq_len, nb_heads, head_size]
        batch_size = array_ops.shape(inputs)[0]
        seq_len = array_ops.shape(inputs)[1]
        head_size = attn_dim // self._nb_heads
        inputs = gen_array_ops.reshape(inputs, [batch_size, seq_len, self._nb_heads, head_size])

        # Transposing to [batch, nb_heads, seq_len, head_size]
        return array_ops.transpose(inputs, [0, 2, 1, 3])

    def _merge_heads(self, inputs):
        """ Merges the attn heads of the tensor into a single dimension
            :param inputs: The tensor to merge - [batch, nb_heads, seq_len, head_size]
            :return: A tensor in the format - [batch, seq_len, nb_heads * head_size]
        """
        assert inputs.shape.ndims == 4, 'Expected inputs to be [batch, nb_heads, seq_len, head_size]'
        assert inputs.shape[1].value == self._nb_heads, 'Expected the 2nd dimension to be the number of heads'

        # Transposing to [batch, seq_len, nb_heads, head_size]
        inputs = array_ops.transpose(inputs, [0, 2, 1, 3])

        # Merging last 2 dims
        batch_size = array_ops.shape(inputs)[0]
        seq_len = array_ops.shape(inputs)[1]
        head_size = inputs.shape[-1].value
        return gen_array_ops.reshape(inputs, [batch_size, seq_len, self._nb_heads * head_size])


text:
import * as ui from "../../ui";
import * as csx from "../../base/csx";
import * as React from "react";
var ReactDOM = require("react-dom");
import * as tab from "./tab";
import { server, cast } from "../../../socket/socketClient";
import * as commands from "../../commands/commands";
import * as utils from "../../../common/utils";
import * as d3 from "d3";
import * as $ from "jquery";
import * as styles from "../../styles/styles";
import * as onresize from "onresize";
import { Clipboard } from "../../components/clipboard";
import { Types } from "../../../socket/socketContract";
import { Icon } from "../../components/icon";
import * as Mousetrap from "mousetrap";
import { Robocop } from "../../components/robocop";
import * as pure from "../../../common/pure";
import * as buttons from "../../components/buttons";
import * as types from "../../../common/types";
import * as gls from "../../base/gls";
import * as typestyle from "typestyle";

type NodeDisplay = Types.NodeDisplay;
let EOL = '\n';

/**
 * The styles
 */
import { inputCodeStyle, searchOptionsLabelStyle }
    from "../../findAndReplace";

let {inputBlackStyleBase} = styles.Input;
const inputBlackClassName = typestyle.style(inputBlackStyleBase);

namespace ResultsStyles {
    export const rootClassName = typestyle.style(
        csx.flex,
        csx.scroll as any,
        styles.padded1,
        {
            border: '1px solid grey',
            $nest: {
                '&:focus': {
                    outline: 'none',
                    border: '1px solid ' + styles.highlightColor,
                }
            }
        }
    );

    export const header = csx.extend(
        styles.padded1,
        {
            cursor: 'default',
            fontSize: '1.5em',
            fontWeight: 'bold',
            color: styles.textColor,
            background: 'black',
            border: '2px solid grey',
        }
    );

    export let preview = {
        padding: '3px',
        background: 'black',
        cursor: 'pointer',
        userSelect: 'text',
    }

    export let selected = {
        backgroundColor: styles.selectedBackgroundColor
    };

    export const noFocusClassName = typestyle.style(
        {
            $nest: {
                '&:focus': {
                    outline: 'none'
                }
            }
        }
    )
}

/**
 * Props / State
 */
export interface Props extends tab.TabProps {
}
export interface State {
    completed?: boolean;
    results?: Types.FarmResultDetails[];
    config?: Types.FarmConfig;
    farmResultByFilePath?: Types.FarmResultsByFilePath;

    /**
     * Results view state
     */
    collapsedState?: { [filePath: string]: boolean };
    selected?: {
        filePath?: string;
        /* If we have a filePath selected (instead of a search result) we set this to -1*/
        line?: number;
    };
    queryRegex?: RegExp;

    /**
     * Search state
     */
    findQuery?: string;
    replaceQuery?: string;
    isRegex?: boolean;
    isCaseSensitive?: boolean;
    isFullWord?: boolean;
}

export class FindAndReplaceView extends ui.BaseComponent<Props, State> {
    constructor(props: Props) {
        super(props);
        let {protocol, filePath} = utils.getFilePathAndProtocolFromUrl(props.url);
        this.filePath = filePath;
        this.state = {
            completed: true,
            farmResultByFilePath: {},

            collapsedState: {},
            selected: {},
        };
    }

    filePath: string;
    mode: Types.ASTMode;
    componentDidMount() {
        /**
         * Keyboard: Focus
         */
        this.focusOnInput(); // On initial mount as well :)
        this.disposible.add(commands.findAndReplace.on(this.focusOnInput));
        this.disposible.add(commands.findAndReplaceMulti.on(this.focusOnInput));

        /**
         * Keyboard: Stop
         */
        this.disposible.add(commands.esc.on(() => {
            // Disabled as esc is used to focus search results as well
            // this.cancelAnyRunningSearch();
        }));

        /**
         * Initial load && keeping it updated
         */
        server.farmResults({}).then(res => {
            this.parseResults(res);
        });
        this.disposible.add(cast.farmResultsUpdated.on(res => {
            this.parseResults(res);
        }));

        /**
         * Handle the keyboard in the search results
         */
        let treeRoot = this.refs.results;
        let handlers = new Mousetrap(treeRoot);

        let selectFirst = () => {
            if (this.state.results && this.state.results.length) {
                this.setSelected(this.state.results[0].filePath, -1);
            }
        }
        handlers.bind('up', () => {
            // initial state
            if (!this.state.results || !this.state.results.length) return false;
            if (!this.state.selected.filePath) {
                selectFirst();
                return false;
            }
            /** If we have an actual line go to previous or filePath */
            if (this.state.selected.line !== -1) {
                const relevantResults = this.state.farmResultByFilePath[this.state.selected.filePath];
                const indexInResults
                    = relevantResults
                        .map(x => x.line)
                        .indexOf(this.state.selected.line);
                if (indexInResults === 0) {
                    this.setSelected(this.state.selected.filePath, -1)
                }
                else {
                    this.setSelected(this.state.selected.filePath, relevantResults[indexInResults - 1].line);
                }
            }
            /** Else go to the previous filePath (if any)
                (collapsed) the filePath
                (expanded) last child
             */
            else {
                let filePaths = Object.keys(this.state.farmResultByFilePath);
                let filePathIndex = filePaths.indexOf(this.state.selected.filePath);
                if (filePathIndex === 0) return false;
                let previousFilePath = filePaths[filePathIndex - 1];
                if (this.state.collapsedState[previousFilePath]) {
                    this.setSelected(previousFilePath, -1);
                }
                else {
                    let results = this.state.farmResultByFilePath[previousFilePath];
                    this.setSelected(previousFilePath, results[results.length - 1].line);
                }
            }
            return false;
        });
        handlers.bind('down', () => {
            if (!this.state.results || !this.state.results.length) return false;
            if (!this.state.selected.filePath) {
                selectFirst();
                return false;
            }
            /** If we are on a filePath
                (collaped) go to next filePath if any
                (expanded) go to first child */
            if (this.state.selected.line === -1) {
                if (this.state.collapsedState[this.state.selected.filePath]) {
                    let filePaths = Object.keys(this.state.farmResultByFilePath);
                    let filePathIndex = filePaths.indexOf(this.state.selected.filePath);
                    if (filePathIndex === filePaths.length - 1) return false;
                    let nextFilePath = filePaths[filePathIndex + 1];
                    this.setSelected(nextFilePath, -1);
                }
                else {
                    let results = this.state.farmResultByFilePath[this.state.selected.filePath];
                    this.setSelected(results[0].filePath, results[0].line);
                }
            }
            /** Else if last in the group go to next filePath if any, otherwise goto next sibling */
            else {
                let results = this.state.farmResultByFilePath[this.state.selected.filePath];
                let indexIntoResults = results.map(x => x.line).indexOf(this.state.selected.line);
                if (indexIntoResults === results.length - 1) {
                    // Goto next filePath if any
                    let filePaths = Object.keys(this.state.farmResultByFilePath);
                    let filePathIndex = filePaths.indexOf(this.state.selected.filePath);
                    if (filePathIndex === filePaths.length - 1) return false;
                    let nextFilePath = filePaths[filePathIndex + 1];
                    this.setSelected(nextFilePath, -1);
                }
                else {
                    let nextResult = results[indexIntoResults + 1];
                    this.setSelected(nextResult.filePath, nextResult.line);
                }
            }
            return false;
        });
        handlers.bind('left', () => {
            /** Just select and collapse the folder irrespective of our current state */
            if (!this.state.results || !this.state.results.length) return false;
            if (!this.state.selected.filePath) return false;
            this.state.collapsedState[this.state.selected.filePath] = true;
            this.setState({ collapsedState: this.state.collapsedState });
            this.setSelected(this.state.selected.filePath, -1);
            return false;
        });
        handlers.bind('right', () => {
            /** Expand only if a filePath root is currently selected  */
            if (!this.state.results || !this.state.results.length) return false;
            this.state.collapsedState[this.state.selected.filePath] = false;
            this.setState({ collapsedState: this.state.collapsedState });
            return false;
        });
        handlers.bind('enter', () => {
            /** Enter always takes you into the filePath */
            if (!this.state.results || !this.state.results.length) return false;
            if (!this.state.selected.filePath) {
                selectFirst();
            }
            this.openSearchResult(this.state.selected.filePath, this.state.selected.line);
            return false;
        });

        // Listen to tab events
        const api = this.props.api;
        this.disposible.add(api.resize.on(this.resize));
        this.disposible.add(api.focus.on(this.focus));
        this.disposible.add(api.save.on(this.save));
        this.disposible.add(api.close.on(this.close));
        this.disposible.add(api.gotoPosition.on(this.gotoPosition));
        // Listen to search tab events
        this.disposible.add(api.search.doSearch.on(this.search.doSearch));
        this.disposible.add(api.search.hideSearch.on(this.search.hideSearch));
        this.disposible.add(api.search.findNext.on(this.search.findNext));
        this.disposible.add(api.search.findPrevious.on(this.search.findPrevious));
        this.disposible.add(api.search.replaceNext.on(this.search.replaceNext));
        this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious));
        this.disposible.add(api.search.replaceAll.on(this.search.replaceAll));
    }

    refs: {
        [string: string]: any;
        results: HTMLDivElement;

        find: JSX.Element;
        replace: JSX.Element;
        regex: { refs: { input: JSX.Element } };
        caseInsensitive: { refs: { input: JSX.Element } };
        fullWord: { refs: { input: JSX.Element } };
    }
    findInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.find);
    replaceInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.replace);
    regexInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.regex.refs.input);
    caseInsensitiveInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.caseInsensitive.refs.input);
    fullWordInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.fullWord.refs.input);

    replaceWith = () => this.replaceInput().value;

    render() {
        let hasSearch = !!this.state.config;

        let rendered = (

                    {
                        hasSearch
                            ? this.renderSearchResults()
                            :
No Search

                    }

                    {
                        this.renderSearchControls()
                    }

        );

        return rendered;
    }

    renderSearchControls() {
        return (

                            <input tabIndex={1} ref="find"
                                placeholder="Find"
                                className={inputBlackClassName}
                                style={csx.extend(inputCodeStyle, csx.flex)}
                                onKeyDown={this.findKeyDownHandler}
                                onChange={this.findChanged} defaultValue={''} />

                                <ui.Toggle
                                    tabIndex={3}
                                    ref="regex"
                                    onChange={this.handleRegexChange} />

                                    .*

                                <ui.Toggle
                                    tabIndex={4}
                                    ref="caseInsensitive"
                                    onChange={this.handleCaseSensitiveChange} />

                                    Aa

                                <ui.Toggle
                                    tabIndex={5}
                                    ref="fullWord"
                                    onKeyDown={this.fullWordKeyDownHandler}
                                    onChange={this.handleFullWordChange} />

                                    <Icon name="text-width" />

                        Controls:
                    {' '}Esc to focus on results
                    {' '}Enter to start/restart search
                    {' '}Toggle 🔘 switches start/restart search

                        Results:
                    {' '}Up/Down to go through results
                    {' '}Enter to open a search result

                    {
                        /* Disabled Replace as that is not the core focus of my work at the moment
                        {' '}{commands.modName} + Enter to replace
                        {' '}{commands.modName} + Shift + Enter to replace all
                        */
                    }

        );
    }

    renderSearchResults() {
        let filePaths = Object.keys(this.state.farmResultByFilePath);
        let queryRegex = this.state.queryRegex;
        let queryRegexStr = (this.state.queryRegex && this.state.queryRegex.toString()) || '';
        queryRegexStr = queryRegexStr && ` (Query : ${queryRegexStr}) `

        return (

                    Total Results ({this.state.results.length})
                    {
                        (this.state.results.length >= types.maxCountFindAndReplaceMultiResults)
                        && <span className="hint--info hint--bottom" data-hint={`(search limited to ${types.maxCountFindAndReplaceMultiResults})`}>(+)
                    }
                    {
                        !this.state.completed &&

                            <gls.SmallHorizontalSpace />
                            <buttons.ButtonBlack
                                key="button"
                                onClick={this.cancelAnyRunningSearch}
                                text={"Cancel"} />

                    }

                    {queryRegexStr}

                {
                    filePaths.map((filePath, i) => {
                        let results = this.state.farmResultByFilePath[filePath];
                        let selectedRoot = filePath === this.state.selected.filePath && this.state.selected.line == -1
                        let selectedResultLine =
                            filePath === this.state.selected.filePath ? this.state.selected.line : -2 /* -2 means not selected */;

                        return (
                            <FileResults.FileResults
                                key={i}
                                ref={filePath}
                                filePath={filePath}
                                results={results}
                                queryRegex={this.state.queryRegex}
                                expanded={!this.state.collapsedState[filePath]}
                                onClickFilePath={this.toggleFilePathExpansion}
                                openSearchResult={this.openSearchResult}
                                selectedRoot={selectedRoot}
                                selectedResultLine={selectedResultLine}
                                />
                        );
                    })
                }

        );
    }

    toggleFilePathExpansion = (filePath: string) => {
        this.state.collapsedState[filePath] = !this.state.collapsedState[filePath];
        this.setState({ collapsedState: this.state.collapsedState, selected: { filePath, line: -1 } });
    }

    /**
     * Scrolling through results
     */
    resultRef(filePath: string) {
        const ref = filePath;
        return this.refs[ref] as FileResults.FileResults;
    }

    /**
     * Input Change handlers
     */
    fullWordKeyDownHandler = (e: React.SyntheticEvent<any>) => {
        let {tab, shift, enter} = ui.getKeyStates(e);

        if (tab && !shift) {
            this.findInput().focus();
            e.preventDefault();
            return;
        }
    };
    findKeyDownHandler = (e: React.SyntheticEvent<any>) => {
        let {tab, shift, enter, mod} = ui.getKeyStates(e);

        if (shift && tab) {
            this.fullWordInput() && this.fullWordInput().focus();
            e.preventDefault();
            return;
        }

        /**
         * Handling commit
         */
        if (!this.state.findQuery) {
            return;
        }
        if (enter) {
            this.startSearch();
        }
    };
    findChanged = () => {
        let val = this.findInput().value.trim();
        this.setState({ findQuery: val });
    };
    handleRegexChange = (e) => {
        let val: boolean = e.target.checked;
        this.setState({ isRegex: val });
        this.startSearch();
    }
    handleCaseSensitiveChange = (e) => {
        let val: boolean = e.target.checked;
        this.setState({ isCaseSensitive: val });
        this.startSearch();
    }
    handleFullWordChange = (e) => {
        let val: boolean = e.target.checked;
        this.setState({ isFullWord: val });
        this.startSearch();
    }

    /**
     * Sends the search query
     * debounced as state needs to be set before this execs
     */
    startSearch = utils.debounce(() => {
        const config: Types.FarmConfig = {
            query: this.state.findQuery,
            isRegex: this.state.isRegex,
            isFullWord: this.state.isFullWord,
            isCaseSensitive: this.state.isCaseSensitive,
            globs: []
        };

        server.startFarming(config);

        this.setState({
            // Clear previous search
            collapsedState: {},
            selected: {},
            // Set new results preemptively
            results: [],
            config,
            queryRegex: utils.findOptionsToQueryRegex({
                query: config.query,
                isRegex: config.isRegex,
                isFullWord: config.isFullWord,
                isCaseSensitive: config.isCaseSensitive,
            }),
            completed: false,
            farmResultByFilePath: {},
        });
    }, 100);

    cancelAnyRunningSearch = () => {
        server.stopFarmingIfRunning({});
    };

    /** Parses results as they come and puts them into the state */
    parseResults(response: Types.FarmNotification) {
        // Convert as needed
        // console.log(response); // DEBUG
        let results = response.results;
        let loaded: Types.FarmResultsByFilePath
            = utils.createMapByKey(results, result => result.filePath);

        let queryRegex = response.config ? utils.findOptionsToQueryRegex({
            query: response.config.query,
            isRegex: response.config.isRegex,
            isFullWord: response.config.isFullWord,
            isCaseSensitive: response.config.isCaseSensitive,
        }) : null;

        // Finally rerender
        this.setState({
            results: results,
            config: response.config,
            queryRegex,
            completed: response.completed,
            farmResultByFilePath: loaded
        });
    }

    openSearchResult = (filePath: string, line: number) => {
        commands.doOpenOrFocusFile.emit({ filePath, position: { line: line - 1, ch: 0 } });
        this.setSelected(filePath, line);
    }

    setSelected = (filePath: string, line: number) => {
        this.setState({ selected: { filePath, line } });
        this.focusFilePath(filePath, line);
    }

    focusFilePath = (filePath: string, line: number) => {
        this.resultRef(filePath).focus(filePath, line);
    };

    /**
     * TAB implementation
     */
    resize = () => {
        // This layout doesn't need it
    }

    /** Allows us to focus on input on certain keystrokes instead of search results */
    focusOnInput = () => setTimeout(() => this.findInput().focus(), 500);
    focus = () => {
        this.refs.results.focus();
    }

    save = () => {
    }

    close = () => {
    }

    gotoPosition = (position: EditorPosition) => {
    }

    search = {
        doSearch: (options: FindOptions) => {
            // not needed
        },

        hideSearch: () => {
            // not needed
        },

        findNext: (options: FindOptions) => {
        },

        findPrevious: (options: FindOptions) => {
        },

        replaceNext: ({newText}: { newText: string }) => {
        },

        replacePrevious: ({newText}: { newText: string }) => {
        },

        replaceAll: ({newText}: { newText: string }) => {
        }
    }
}

namespace FileResults {
    export interface Props {
        filePath: string;
        results: Types.FarmResultDetails[];

        expanded: boolean;
        onClickFilePath: (filePath: string) => any;
        openSearchResult: (filePath: string, line: number) => any;

        selectedRoot: boolean;
        selectedResultLine: number;

        queryRegex: RegExp;
    }
    export interface State {
    }
    export class FileResults extends React.PureComponent<Props, State>{
        render() {

            let selectedStyle = this.props.selectedRoot
                ? ResultsStyles.selected
                : {};

            return (

 this.props.onClickFilePath(this.props.filePath)}>
                    <div
                        ref={this.props.filePath + ':' + -1}
                        tabIndex={0}
                        className={ResultsStyles.noFocusClassName}
                        style={
                            csx.extend(
                                selectedStyle,
                                styles.errorsPanel.filePath,
                                {
                                    margin: '8px 0px',
                                    padding: '3px'
                                }
                            )
                        }>
                        {!this.props.expanded ? "+" : "-"} {this.props.filePath} ({this.props.results.length})

                    {!this.props.expanded ?  : this.renderResultsForFilePath(this.props.results)}

            );
        }

        renderResultsForFilePath = (results: Types.FarmResultDetails[]) => {
            return results.map((result, i) => {
                let selectedStyle = this.props.selectedResultLine === result.line
                    ? ResultsStyles.selected
                    : {};

                return (
                    <div
                        key={i}
                        ref={result.filePath + ':' + result.line}
                        tabIndex={0}
                        className={ResultsStyles.noFocusClassName}
                        style={
                            csx.extend(
                                styles.padded1,
                                {
                                    cursor: 'pointer',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                    whiteSpace: 'pre',
                                },
                                selectedStyle
                            )
                        }
                        onClick={(e) => { e.stopPropagation(); this.props.openSearchResult(result.filePath, result.line) } }>
                        {utils.padLeft((result.line).toString(), 6)} : {this.renderMatched(result.preview, this.props.queryRegex)}

                );
            })
        }

        focus(filePath: string, line: number) {
            let dom = this.refs[this.props.filePath + ':' + line] as HTMLDivElement;
            dom.scrollIntoViewIfNeeded(false);
        }

        renderMatched(preview: string, queryRegex: RegExp) {
            let matched = this.getMatchedSegments(preview, queryRegex);
            let matchedStyle = { fontWeight: 'bold' as 'bold', color: '#66d9ef' };
            return matched.map((item, i) => {
                return {item.str};
            });
        }

        getMatchedSegments(preview: string, queryRegex: RegExp) {
            // A data structure which is efficient to render
            type MatchedSegments = { str: string, matched: boolean }[];
            let result: MatchedSegments = [];

            var match;
            let previewCollectedIndex = 0;
            let collectUnmatched = (matchStart: number, matchLength: number) => {
                if (previewCollectedIndex < matchStart) {
                    result.push({
                        str: preview.substring(previewCollectedIndex, matchStart),
                        matched: false
                    });
                    previewCollectedIndex = (matchStart + matchLength);
                }
            };

            while (match = queryRegex.exec(preview)) {
                let matchStart = match.index;
                let matchLength = match[0].length;
                // let nextMatchStart = queryRegex.lastIndex; // Since we don't need it

                // If we have an unmatched string portion that is still not collected
                // Collect it :)
                collectUnmatched(matchStart, matchLength);

                result.push({
                    str: preview.substr(matchStart, matchLength),
                    matched: true
                });
            }

            // If we still have some string portion uncollected, collect it
            if (previewCollectedIndex !== preview.length) {
                collectUnmatched(preview.length, 0);
            }

            return result;
        }
    }
}


text:
/*
 * Copyright 2009-2012 the original author or authors.
 *
 * 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 org.cloudfoundry.client.lib.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Some helper utilities used by the Cloud Foundry Java client.
 *
 * @author Ramnivas Laddad
 * @author A.B.Srinivasan
 *
 */
public class CloudUtil {

    public static final int BUFFER_SIZE = 16 * 1024;

	private static Double DEFAULT_DOUBLE = new Double(0.0);

	private static Integer DEFAULT_INTEGER = new Integer(0);

	private static Long DEFAULT_LONG = new Long(0);

	private static final String HEX_CHARS = "0123456789ABCDEF";

	private static final char EXTENSION_SEPARATOR = '.';

	public static String parse(Object object) {
		return parse(String.class, object);
	}

	@SuppressWarnings("unchecked")
	public static <T> T parse(Class<T> clazz, Object object) {
		T defaultValue = null;
		try {
			if (clazz == Date.class) {
				String stringValue = parse(String.class, object);
				return clazz.cast(new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy",
						Locale.US).parse(stringValue));
			}

			if (clazz == Integer.class) {
				defaultValue = (T) DEFAULT_INTEGER;
			} else if (clazz == Long.class) {
				defaultValue = (T) DEFAULT_LONG;
			} else if (clazz == Double.class) {
				defaultValue = (T) DEFAULT_DOUBLE;
			}

			if (object == null) {
				return defaultValue;
			}

			// special handling for int and long since smaller numbers become ints
			// but may be requested as long and vice versa
			if (clazz == Integer.class) {
				return clazz.cast(Integer.valueOf(((Number)object).intValue()));
			}
			if (clazz == Long.class) {
				return clazz.cast(Long.valueOf(((Number)object).longValue()));
			}

			return clazz.cast(object);
		} catch (ClassCastException e) {
			// ignore
		} catch (ParseException e) {
			// ignore
		}
		return defaultValue;
	}

	public static boolean isWar(String filePath) {
	    return "war".equalsIgnoreCase(extension(filePath));
	}

	public static String computeSha1Digest(InputStream in) throws IOException {
	    MessageDigest digest;
	    try {
	        digest = MessageDigest.getInstance("SHA-1");
	    } catch (NoSuchAlgorithmException e) {
	        throw new RuntimeException(e);
	    }

	    byte[] buffer = new byte[CloudUtil.BUFFER_SIZE];
	    while(true) {
	        int read = in.read(buffer);
	        if (read == -1) {
	            break;
	        }
	        digest.update(buffer, 0, read);
	    }
	    in.close();
	    return bytesToHex(digest.digest());
	}

	private static String bytesToHex(byte[] bytes) {
	    if (bytes == null) {
	        return null;
	    }
	    final StringBuilder hex = new StringBuilder(2 * bytes.length);
	    for (final byte b : bytes) {
	        hex.append(HEX_CHARS.charAt((b & 0xF0) >> 4)).append(HEX_CHARS.charAt((b & 0x0F)));
	    }
	    return hex.toString();
	}

	private static String extension(String filePath) {
	    int dot = filePath.lastIndexOf(EXTENSION_SEPARATOR);
	    return filePath.substring(dot + 1);
	}

}


text:
package org.keycloak.validate.validators;

import org.keycloak.provider.ConfiguredProvider;
import org.keycloak.validate.ValidatorConfig;

/**
 *
 * Validate input being integer number {@link Integer} or {@link Long}. Accepts String also if convertible to
 * {@link Long} by common {@link Long#parseLong(String)} operation.
 *
 * @author Vlastimil Elias <velias@redhat.com>
 */
public class IntegerValidator extends AbstractNumberValidator implements ConfiguredProvider {

    public static final String ID = "integer";
    public static final IntegerValidator INSTANCE = new IntegerValidator();

    public IntegerValidator() {
        super();
    }

    public IntegerValidator(ValidatorConfig config) {
        super(config);
    }

    @Override
    protected Number convert(Object value, ValidatorConfig config) {
        if (value instanceof Integer || value instanceof Long) {
            return (Number) value;
        }
        return new Long(value.toString());
    }

    @Override
    public String getId() {
        return ID;
    }

    @Override
    protected Number getMinMaxConfig(ValidatorConfig config, String key) {
        return config != null ? config.getLong(key) : null;
    }

    @Override
    protected boolean isFirstGreaterThanToSecond(Number n1, Number n2) {
        return n1.longValue() > n2.longValue();
    }

    @Override
    public String getHelpText() {
        return "Validator to check Integer number format and optionally min and max values";
    }

}


text:
namespace Microsoft.Azure.Management.Reservations
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ReservationOrderOperations operations.
    /// </summary>
    public partial interface IReservationOrderOperations
    {
        /// <summary>
        /// Calculate price for a `ReservationOrder`.
        /// </summary>
        /// <remarks>
        /// Calculate price for placing a `ReservationOrder`.
        /// </remarks>
        /// <param name='body'>
        /// Information needed for calculate or purchase reservation
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<CalculatePriceResponse>> CalculateWithHttpMessagesAsync(PurchaseRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get all `ReservationOrder`s.
        /// </summary>
        /// <remarks>
        /// List of all the `ReservationOrder`s that the user has access to in
        /// the current tenant.
        /// </remarks>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<ReservationOrderResponse>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Purchase `ReservationOrder`
        /// </summary>
        /// <remarks>
        /// Purchase `ReservationOrder` and create resource under the specified
        /// URI.
        /// </remarks>
        /// <param name='reservationOrderId'>
        /// Order Id of the reservation
        /// </param>
        /// <param name='body'>
        /// Information needed for calculate or purchase reservation
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ReservationOrderResponse>> PurchaseWithHttpMessagesAsync(string reservationOrderId, PurchaseRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get a specific `ReservationOrder`.
        /// </summary>
        /// <remarks>
        /// Get the details of the `ReservationOrder`.
        /// </remarks>
        /// <param name='reservationOrderId'>
        /// Order Id of the reservation
        /// </param>
        /// <param name='expand'>
        /// May be used to expand the planInformation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ReservationOrderResponse>> GetWithHttpMessagesAsync(string reservationOrderId, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Purchase `ReservationOrder`
        /// </summary>
        /// <remarks>
        /// Purchase `ReservationOrder` and create resource under the specified
        /// URI.
        /// </remarks>
        /// <param name='reservationOrderId'>
        /// Order Id of the reservation
        /// </param>
        /// <param name='body'>
        /// Information needed for calculate or purchase reservation
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ReservationOrderResponse>> BeginPurchaseWithHttpMessagesAsync(string reservationOrderId, PurchaseRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get all `ReservationOrder`s.
        /// </summary>
        /// <remarks>
        /// List of all the `ReservationOrder`s that the user has access to in
        /// the current tenant.
        /// </remarks>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<ReservationOrderResponse>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
.. _upgrade:

Upgrade guide
=============

The |version| release of |project| is not compatible with the legacy
django-registration (previously maintained by James Bennett).

Django version requirement
--------------------------

As of |version|, |project| requires Django 1.8 or newer;
older Django releases may work, but are officially unsupported. Additionally,
|project| officially supports Python 2.7, 3.3, 3.4, and 3.5.

Backwards-incompatible changes
------------------------------

Version 1.5
```````````

- Support for Django 1.7 is removed, and Django 1.8 or newer is required.

Version 1.4
```````````

- Remove unnecessary `_RequestPassingFormView`.
  See `#56 <https://github.com/macropin/django-registration/pull/56>`_. Please
  ensure that you update any subclassed views to reference ``self.request``
  instead of accepting ``request`` as an argument.

Version 1.3
```````````
- Django 1.7 or newer is required. Please ensure you upgrade your Django
  version before upgrading.

Version 1.2
```````````
- **Native migration support breaks South compatibility**: An initial native
  migration for Django > 1.7 has been provided. South users will need to
  configure a null migration with (`SOUTH_MIGRATION_MODULES`) in
  `settings.py` as shown below:

  ::

      SOUTH_MIGRATION_MODULES = {
          'registration': 'registration.south_migrations',

- **register method in RegistrationView has different parameters**: The
  parameters of the`register` method in RegistrationView have changed.

Version 1.1
```````````

- **base.html template required**: A `base.html` template is now assumed to
  exist. Please ensure that your project provides one for |project| to inherit
  from.
- **HTML email templates**: |project| now uses HTML email templates. If you
  previously customized text email templates, you need to do the same with
  the new HTML templates.


text:
package com.beatsportable.beats;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;

public class ToolsUnzipperActivity extends Activity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unzipper);
		Tools.setContext(this);

		// Extract
		String filePath;
		Intent extractIntent = getIntent();
		if (extractIntent.getData() != null &&
			(filePath = extractIntent.getData().getPath()) != null// &&
			//Tools.isStepfilePack(filePath)) {
			) {
			this.setTitle(
					Tools.getString(R.string.ToolsUnzipperActivity_install) +
					extractIntent.getData().getLastPathSegment()
					);
			// Create with finishCallingActivity = true
			new ToolsUnzipper(this, filePath, false, true).unzip();
		} else {
			Tools.toast(
					Tools.getString(R.string.ToolsUnzipperActivity_unsupported)
					);
			finish();
		}

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
}