text:
package routemgr

import (
	"context"
	"encoding/base32"
	"encoding/binary"
	"sync"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/pkg/gateway/control"
)

const (
	DefaultDeviceName = "tun0"
	IATunDevicePrefix = "s."
)

type destructionCallback func()

// deviceHandle wraps reference counting around a base device handler.
//
// Access this object only through its methods.
type deviceHandle struct {
	// mtx protects access to the reference counter and base device handle. API calls to the
	// base handle are made without holding the lock. However, the handle is checked before and
	// after the API call to see if it was destroyed, and the
	// ObjectDestroyedError error is returned in this case. The error will wrap
	// any error returned by the call. This allows for callers to easily check
	// whether the resource was destroyed without knowing the type of the underlying device.
	//
	// To ensure that io.Reader and io.Writer semantics are preserved, the
	// number of bytes read/written is always returned irrespective of whether
	// ObjectDestroyedError or a device error occurred.
	mtx      sync.RWMutex
	base     control.DeviceHandle
	refCount int
	// destructionCallback is a function that runs exactly once after the base
	// handle has been freed. The callback executes outside the mutex. If nil,
	// no callback is executed. The callback needs to be safe for concurrent
	// calls by multiple goroutines.
	destructionCallback destructionCallback
}

func (h *deviceHandle) Close() error {
	// The callback runs outside the mutex, thus avoiding deadlocks in deviceHandle
	// methods if for whatever reason the destruction callback blocks.
	err, destructionF := h.innerClose()
	if destructionF != nil {
		destructionF()
	}
	return err
}

// innerClose closes the base handle and returns a cleanup function. The cleanup
// function must always be executed, even if the error return value is non-nil.
func (h *deviceHandle) innerClose() (error, destructionCallback) {
	h.mtx.Lock()
	defer h.mtx.Unlock()

	if h.refCount == 0 {
		return serrors.New("handle closed too many times"), nil
	}

	h.refCount--
	if h.refCount == 0 {
		return h.base.Close(), h.destructionCallback
	}
	return nil, nil
}

// newDeviceHandle creates a new reference counting handle on top of base.
// If destructionCallback is not nil, it will be called after base is closed.
func newDeviceHandle(base control.DeviceHandle,
	destructionCallback destructionCallback) *deviceHandle {

	return &deviceHandle{
		base:                base,
		destructionCallback: destructionCallback,
		refCount:            1,
	}
}

func (h *deviceHandle) incRefs() {
	h.mtx.Lock()
	defer h.mtx.Unlock()

	if h.refCount == 0 {
		panic("bug: attempted to get reference to destroyed object")
	}
	h.refCount++
}

func (h *deviceHandle) destroyed() bool {
	h.mtx.RLock()
	defer h.mtx.RUnlock()

	return h.refCount == 0
}

func (h *deviceHandle) Read(b []byte) (int, error) {
	return h.ioWrapper(h.base.Read, b)
}

func (h *deviceHandle) Write(b []byte) (int, error) {
	return h.ioWrapper(h.base.Write, b)
}

// ioWrapper is a type-safe invoker of io.Reader/io.Writer ops. It calls f on b
// and returns the result.
func (h *deviceHandle) ioWrapper(f func([]byte) (int, error), b []byte) (int, error) {
	if h.destroyed() {
		return 0, control.ObjectDestroyedError
	}
	n, err := f(b)
	if err != nil && h.destroyed() {
		// always give the correct number of bytes to the caller (e.g., so it can know up to
		// where it read/wrote on a device which supports streaming).
		return n, serrors.Wrap(control.ObjectDestroyedError, err)
	}
	return n, err
}

func (h *deviceHandle) AddRoute(ctx context.Context, r *control.Route) error {
	return h.routeWrapper(ctx, h.base.AddRoute, r)
}

func (h *deviceHandle) DeleteRoute(ctx context.Context, r *control.Route) error {
	return h.routeWrapper(ctx, h.base.DeleteRoute, r)
}

// ioWrapper is a type-safe invoker of route creation/deletion ops. It calls f
// on r and returns the result.
func (h *deviceHandle) routeWrapper(ctx context.Context,
	f func(context.Context, *control.Route) error, r *control.Route) error {

	if h.destroyed() {
		return control.ObjectDestroyedError
	}
	err := f(ctx, r)
	if err != nil && h.destroyed() {
		return serrors.Wrap(control.ObjectDestroyedError, err)
	}
	return err
}

// SingleDeviceManager opens a single device for all ISD-ASes.
type SingleDeviceManager struct {
	// DeviceOpener is the object used to create new handles.
	DeviceOpener control.DeviceOpener

	mtx    sync.Mutex
	device *deviceHandle
}

// Get returns a handle to the device for the ISD-AS. If no device exists, one will be created.
// If a device already exists, a handle to the existing device is returned. The caller must
// Close the handle to guarantee that resources will be cleaned up.
func (m *SingleDeviceManager) Get(
	ctx context.Context,
	ia addr.IA,
) (control.DeviceHandle, error) {

	m.mtx.Lock()
	defer m.mtx.Unlock()

	if m.DeviceOpener == nil {
		return nil, serrors.New("no DeviceOpener set")
	}

	if m.device != nil && !m.device.destroyed() {
		m.device.incRefs()
		return m.device, nil
	}

	device, err := m.DeviceOpener.Open(ctx, ia)
	if err != nil {
		return nil, err
	}
	m.device = newDeviceHandle(device, nil)
	return m.device, nil
}

// MultiDeviceManager opens one device for each ISD-AS.
type MultiDeviceManager struct {
	// DeviceOpener is used to create new resources for handles returned by Get.
	DeviceOpener control.DeviceOpener

	mtx     sync.Mutex
	devices map[addr.IA]*deviceHandle
}

// Get returns a handle to the device for the ISD-AS. If no device exists, one will be created.
// If a device already exists, a handle to the existing device is returned. The caller must
// Close the handle to guarantee that resources will be cleaned up.
//
// Devices are created with a name composed of the default tunnel device prefix and
// an unpadded base32 representation of the ISD-AS.
func (m *MultiDeviceManager) Get(ctx context.Context, ia addr.IA) (control.DeviceHandle, error) {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	if m.DeviceOpener == nil {
		return nil, serrors.New("DeviceManager not set")
	}

	if m.devices == nil {
		m.devices = make(map[addr.IA]*deviceHandle)
	}

	if m.devices[ia] == nil || m.devices[ia].destroyed() {
		device, err := m.DeviceOpener.Open(ctx, ia)
		if err != nil {
			return nil, err
		}
		m.devices[ia] = newDeviceHandle(device, m.newDeletionCallback(ia))
	} else {
		m.devices[ia].incRefs()
	}

	return m.devices[ia], nil
}

// Size returns the number of existing devices.
func (m *MultiDeviceManager) Size() int {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	return len(m.devices)
}

func (m *MultiDeviceManager) newDeletionCallback(ia addr.IA) destructionCallback {
	return func() {
		m.mtx.Lock()
		defer m.mtx.Unlock()

		delete(m.devices, ia)
	}
}

// Base32TunnelName is a device naming function that constructs Linux tun names using
// the base32 encoding of an IA number.
func Base32TunnelName(ia addr.IA) string {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, uint64(ia))
	return IATunDevicePrefix + base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)
}

// FixedTunnelName returns a device naming function that uses name for every IA.
func FixedTunnelName(name string) func(addr.IA) string {
	return func(addr.IA) string {
		return name
	}
}


text:
// @link http://schemas.gdbots.io/json-schema/gdbots/ncr/request/get-node-history-request/1-0-1.json#
import Fb from '@gdbots/pbj/FieldBuilder.js';
import Format from '@gdbots/pbj/enums/Format.js';
import GdbotsPbjxRequestV1Mixin from '@gdbots/schemas/gdbots/pbjx/mixin/request/RequestV1Mixin.js';
import Message from '@gdbots/pbj/Message.js';
import Schema from '@gdbots/pbj/Schema.js';
import T from '@gdbots/pbj/types/index.js';

export default class GetNodeHistoryRequestV1 extends Message {
  /**
   * @private
   *
   * @returns {Schema}
   */
  static defineSchema() {
    return new Schema(this.SCHEMA_ID, this,
      [
        Fb.create('request_id', T.UuidType.create())
          .required()
          .build(),
        Fb.create('occurred_at', T.MicrotimeType.create())
          .build(),
        /*
         * Multi-tenant apps can use this field to track the tenant id.
         */
        Fb.create('ctx_tenant_id', T.StringType.create())
          .pattern('^[\\w\\/\\.:-]+$')
          .build(),
        /*
         * The "ctx_retries" field is used to keep track of how many attempts were
         * made to handle this request. In some cases, the service or transport
         * that handles the request may be down or over capacity and is being retried.
         */
        Fb.create('ctx_retries', T.TinyIntType.create())
          .build(),
        Fb.create('ctx_causator_ref', T.MessageRefType.create())
          .build(),
        Fb.create('ctx_correlator_ref', T.MessageRefType.create())
          .build(),
        Fb.create('ctx_user_ref', T.MessageRefType.create())
          .build(),
        /*
         * The "ctx_app" refers to the application used to make the request. This is
         * different from ctx_ua (user_agent) because the agent used (Safari, Firefox)
         * is not necessarily the app used (cms, iOS app, website)
         */
        Fb.create('ctx_app', T.MessageType.create())
          .anyOfCuries([
            'gdbots:contexts::app',
          ])
          .build(),
        /*
         * The "ctx_cloud" is set by the server making the request and is generally
         * only used internally for tracking and performance monitoring.
         */
        Fb.create('ctx_cloud', T.MessageType.create())
          .anyOfCuries([
            'gdbots:contexts::cloud',
          ])
          .build(),
        Fb.create('ctx_ip', T.StringType.create())
          .format(Format.IPV4)
          .overridable(true)
          .build(),
        Fb.create('ctx_ipv6', T.StringType.create())
          .format(Format.IPV6)
          .overridable(true)
          .build(),
        Fb.create('ctx_ua', T.TextType.create())
          .overridable(true)
          .build(),
        /*
         * Field names to dereference, this serves as a hint to the server and is not
         * necessarily gauranteed since authorization, availability, etc. are determined
         * by the server not the client.
         */
        Fb.create('derefs', T.StringType.create())
          .asASet()
          .pattern('^[\\w\\.-]+$')
          .build(),
        Fb.create('node_ref', T.NodeRefType.create())
          .required()
          .build(),
        /*
         * Return events since this time (exclusive greater than if forward=true, less than if forward=false)
         */
        Fb.create('since', T.MicrotimeType.create())
          .useTypeDefault(false)
          .build(),
        /*
         * The number of events to return.
         */
        Fb.create('count', T.TinyIntType.create())
          .withDefault(25)
          .build(),
        /*
         * When true, the events are read from oldest to newest, otherwise newest to oldest.
         */
        Fb.create('forward', T.BooleanType.create())
          .build(),
        Fb.create('topic', T.StringType.create())
          .pattern('^[\\w\\.-]+$')
          .build(),
        Fb.create('partition', T.StringType.create())
          .pattern('^[\\w\\.-]+$')
          .build(),
        Fb.create('sub_partition', T.StringType.create())
          .pattern('^[\\w\\.-]+$')
          .build(),
      ],
      this.MIXINS,
    );
  }
}

const M = GetNodeHistoryRequestV1;
M.prototype.SCHEMA_ID = M.SCHEMA_ID = 'pbj:gdbots:ncr:request:get-node-history-request:1-0-1';
M.prototype.SCHEMA_CURIE = M.SCHEMA_CURIE = 'gdbots:ncr:request:get-node-history-request';
M.prototype.SCHEMA_CURIE_MAJOR = M.SCHEMA_CURIE_MAJOR = 'gdbots:ncr:request:get-node-history-request:v1';
M.prototype.MIXINS = M.MIXINS = [
  'gdbots:pbjx:mixin:request:v1',
  'gdbots:pbjx:mixin:request',
];

GdbotsPbjxRequestV1Mixin(M);

Object.freeze(M);
Object.freeze(M.prototype);

redpajama_set_name: RedPajamaGithub


text:
package org.openhubframework.openhub.common.synchronization;

/**
 * Method {@link #syncBlock()} in this interface can be synchronized by one value in
 * {@link SynchronizationExecutor#execute(SynchronizationBlock, String, Object)}.
 * <p>
 * If you need {@code void} method, use {@link SynchronizationNoResultBlock}.
 * </p>
 *
 * @author Roman Havlicek
 * @see SynchronizationExecutor#execute(SynchronizationBlock, String, Object)
 * @see SynchronizationNoResultBlock
 * @since 2.0
 */
public interface SynchronizationBlock {

    /**
     * Method will be synchronized by one value calling
     * {@link SynchronizationExecutor#execute(SynchronizationBlock, String, Object)}.
     *
     * @param <T> type of return object
     * @return returned object of calling this method
     */
    <T> T syncBlock();
}


text:
\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[brazil]{babel}
\usepackage{indentfirst}
\usepackage{color}
\usepackage{hyperref}
\usepackage{graphicx}
\usepackage{mathtools}
\begin{document}
\section{Quick Sort}
O Quick Sort é um eficiente algoritmo de ordenação, servindo como um método sistemático
para colocar os elementos de uma lista em ordem. Embora tenha sido desenvolvido em
1959, ele ainda é um algoritmo muito usado para ordenação.
O Quick é um algoritmo de ordenação por comparação, o que significa que ele pode ordenar
elementos de qualquer tipo em que uma relação \textbf{menor que} é definida. Algumas análises
matemáticas do Quick mostram que, no caso médio, o algoritmo leva \textbf{O(n log n)} comparações
para ordenar n elementos. No seu pior caso, ele faz \textbf{O($n^{2}$)}, porém este comportamento não
é usual.

Este é um algoritmo de dividir para conquistar. O Quick Sort primeiro divide uma lista
em sublistas: os menores elementos e os maiores elementos. Após a divisão, o algoritmo pode
fazer a ordenação das sublistas. A divisão é dada tomando por base um elemento chamado \textbf{pivô}.

Aqui, três métodos diferentes para a escolha do pivô foram implementados para as versões
recursivas e iterativas do Quick.

\subsection{A escolha do pivô}
Nas primeiras implementações do Quick Sort, o elemento mais a esquerda das listas era
comumente escolhido como pivô. Esta escolha provoca o pior caso do algoritmo para listas
que já estão ordenadas. O problema foi facilmente resolvido escolhendo ou um elemento
aleatório dentro da lista para o pivô, ou escolhendo a mediana entre o primeiro, o central e o
último elementos da lista \textit{(recomendado por Sedgewick)}. A mediana de três elementos
evita ambos os casos em que a lista está ordenada ou ordenada reversamente, além de dar
uma melhor estimativa do pivô ótimo (a verdadeira mediana) do que escolher um único elemento
sem qualquer informação à respeito do conjunto a ser ordenado.
\subsubsection{Primeiro elemento da partição}
Para cada partição criada pelo Quick, seu primeiro elemento é usado como pivô para a ordenação.
Esta escolha traz os piores casos do Quick quando as listas estão ordenadas ou ordenadas
reversamente, pois serão criadas \textbf{n} partições com elementos menores ou maiores que o pivô.
\subsubsection{Elemento central da partição}
Para cada partição criada pelo Quick, seu elemento central é usado como pivô para a ordenação.
Esta escolha, quase sempre, consegue evitar o pior caso do algoritmo.
\subsubsection{Mediana de três elementos da partição}
A mediana de três é um dos melhores métodos para a escolha do pivô.
Ela consiste em escolher a mediana entre o \textbf{primeiro} elemento, o elemento \textbf{central}
e o \textbf{último} elemento da partição, e usá-lo como pivô. Esta escolha traz o número de
comparações necessárias para $C_{n, 2} = 1.188 . n . log n$, com um aumento de 3\% no número de trocas esperadas.
\subsection{Quick Sort Recursivo}
Os passos para a implementação de um Quick recursivo são descritos a seguir:
\begin{itemize}
 \item Pegue um elemento da lista e o chame de \textbf{pivô}.
 \item Reorganize a lista para que todos os valores menores do que o pivô apareçam
 antes dele, enquanto todos os valroes maiores do que o pivô apareçam depois dele (valores iguais podem estar de qualquer lado).
 \item Recursivamente aplique os passos acima para as sublistas de elementos criadas.
\end{itemize}

O caso base da recursão é quando o tamanho da lista é zero ou um, que nunca precisa ser ordenada.
Uma representação dos passos acima em pseudocódigo pode ser:

      procedure quicksort (A, lo, hi)

	if lo $\le$ hi then

	  p = partition(A, lo, hi)

	  quicksort(A, lo, p - 1)

	  quicksort(A, p + 1, hi)

	end if

      end procedure

A ordenação é feita chamando \textbf{quicksort (A, 0, length(A) - 1)}. O procedimento
de \textbf{partição} implementa algum dos três citados acima.
\subsection{Quick Sort Iterativo}
Uma possível implementação para o Quick Sort Iterativo usa uma pilha auxiliar para ajudar na ordenação.
O tamanho usado para a pilha auxiliar nesta implementação é de \textbf{64 elementos}, o que
garante uma ordenação de até $2^{64/2}$ elementos. Porém, o tamanho usado durante a execução
é menor do que $2.log_{2}n$ entradas \textit{(cerca de 99\% de probabilidade)}. Se a pilha
sofrer um overflow, a ordenação simplesmente recomeça.

\section{Bucket Sort}
O Bucket Sort é um algoritmo que funciona particionando uma lista em um conjunto de baldes.
Ele é um primo do Radix Sort na forma do digito mais significante para o menos significante.

O algoritmo pode ser visto como uma generalização do Rank Sort; de fato, se cada balde tiver tamanho igual a 1
então o Bucket é reduzido a um Rank Sort. O número variado de tamanhos de balde permite
que o Bucket use uma quantidade \textbf{O(n)} de memória, ao contrário do Rank que usa
uma quantidade \textbf{O(M)}, onde \textit{M} é o número de valores distintos.
Nesta troca, ele deixa de ter o pior caso do Rank Sort, onde a memória usada é \textbf{O(n + M)}.

O \textit{top-down} Radix pode ser visto como um caso especial do Bucket, onde o número de baldes é visto como uma potência de dois.

\section{Rank Sort}
O Rank Sort é um algoritmo que ordena uma coleção de objetos \textbf{(contáveis)} contando
o número de elementos da coleção que possui valores distintos. Seu tempo de execução é linear
no número de elementos e na diferença entre os valores do maior e menor elementos.

Pelo fato de que o Rank Sort usa os valores das chaves como índices de uma lista, ele
não é um algoritmo comparativo. Em suma, o algoritmo itera sobre os elementos, computando um
histograma do número de vezes que cada chave aparece na lista de entrada. Em seguida, ele usa
um segundo loop para determinar, para cada chave, sua posição inicial na lista de saída.
Por fim, ele itera novamente sobre a lista de entrada, movendo cada elemento para sua posição na lista ordenada.

Algumas variações do Rank Sort para inteiros conseguem combinar o segundo e o terceiro loop, desde que
os elementos a serem ordenados sejam números inteiros e que seus valores sejam usados como chaves.

\section{Radix Sort}
\subsection{Radix Sort para números inteiros}
O Radix Sort é um algoritmo não comparativo que ordena dados com chaves inteiras agrupando
chaves por seus dígitos individuais que compartilham o mesmo valor relativo. Como inteiros
podem representar strings de caracteres e também partes do formato de um ponto flutuante,
o Radix Sort não é limitado apenas para inteiros.
Sua primeira implementação data de \textbf{1887}, com a máquina de ordenação de \textit{Herman Hollerith}.

\subsection{Radix Binário}
A maioria dos computadores digitais armazenam seus dados internamente como números binários. Isso
significa que processar os digitos de representações inteiras por grupos de dígitos binários é
mais conveniente. Com esta ideia em mente, uma otimização do Radix é implementar uma versão
que realize a ordenação olhando para os \textit{bits} ao invés dos valores como inteiros.

Existem duas classificações para as implementações do Radix Sort Binário: \textbf{MSD} (Most significant digit e
\textbf{LSD} (least significant digit). O Radix LSD começa analisando o bit menos significativo e
e o MSD começa analisando o bit mais signficativo.

Implementações do Radix MSD usam ordem \textbf{lexicográfica}. Se a ordenação lexicográfica for usada
para odernar inteiros com representações variáveis de tamanho, então a representação dos números de 1 a 10 ordenados
seria \textbf{1, 10, 2, 3, 4, 5, 6, 7, 8, 9}. Isso ocorre porque as chaves menores foram justificadas
à esquerda e alinhadas à direita com caracteres em branco para que fiquem tão longas quanto a chave mais longa.

\subsection{Permutation Sort}
O Permutation Sort pode ser implementado gerando, em um loop, a próxima permutação lexicográfica da lista de entrada até que a última seja encontrada.
Esta, por sua vez, é odenada por definição.

A noção de permutação remete ao ato de rearranjar, ou permutar, todos os elementos de um conjunto em uma ordem ou sequência.
O número de permutações de \textbf{n} objetos distintos é $n!$, que significa o produto de todos os inteiros positivos menores ou iguais a n.

\section{Shake Sort}
O Shake Sort, a.k.a. Bubble Sort bidirecional é uma variação estável e comparativa do Bubble Sort.
Sua principal diferença é que ele faz a ordenação em duas direções. Suas melhorias em termos de desempenho são
ínfimas e não há melhorias na performance assintótica do algoritmo.

Sua complexidade também é \textbf{O($n^{2}$)} no pior caso e no caso médio. Porém, ela pode fica próxima de
\textbf{O(n)} se a lista estiver quase ordenada antes de aplicar o algoritmo.

O Shake Sort é brevemente discutido no livro \textit{The Art of Computer Programming}, por D.E. Knuth.

\textit{[...] In short, the bubble sort seems to have nothing to recommend it, except a catchy name and the factd that it leads to some interesting theorical problems.}

\end{document}


text:
require_relative "support/helpers"

setup("origin", "user_a")
change_repo("user_a")
run("change start bar")
run("change start foo")

result = `change delete --complete`

if result.lines.collect(&:strip).sort != [ "bar", "foo" ]
  raise "Expected `change delete --complete` to list all changes."
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Sql.Models;

namespace Azure.ResourceManager.Sql
{
    /// <summary>
    /// A class representing a collection of <see cref="ExtendedServerBlobAuditingPolicyResource" /> and their operations.
    /// Each <see cref="ExtendedServerBlobAuditingPolicyResource" /> in the collection will belong to the same instance of <see cref="SqlServerResource" />.
    /// To get an <see cref="ExtendedServerBlobAuditingPolicyCollection" /> instance call the GetExtendedServerBlobAuditingPolicies method from an instance of <see cref="SqlServerResource" />.
    /// </summary>
    public partial class ExtendedServerBlobAuditingPolicyCollection : ArmCollection, IEnumerable<ExtendedServerBlobAuditingPolicyResource>, IAsyncEnumerable<ExtendedServerBlobAuditingPolicyResource>
    {
        private readonly ClientDiagnostics _extendedServerBlobAuditingPolicyClientDiagnostics;
        private readonly ExtendedServerBlobAuditingPoliciesRestOperations _extendedServerBlobAuditingPolicyRestClient;

        /// <summary> Initializes a new instance of the <see cref="ExtendedServerBlobAuditingPolicyCollection"/> class for mocking. </summary>
        protected ExtendedServerBlobAuditingPolicyCollection()
        {
        }

        /// <summary> Initializes a new instance of the <see cref="ExtendedServerBlobAuditingPolicyCollection"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
        internal ExtendedServerBlobAuditingPolicyCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _extendedServerBlobAuditingPolicyClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ExtendedServerBlobAuditingPolicyResource.ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ExtendedServerBlobAuditingPolicyResource.ResourceType, out string extendedServerBlobAuditingPolicyApiVersion);
            _extendedServerBlobAuditingPolicyRestClient = new ExtendedServerBlobAuditingPoliciesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, extendedServerBlobAuditingPolicyApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != SqlServerResource.ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SqlServerResource.ResourceType), nameof(id));
        }

        /// <summary>
        /// Creates or updates an extended server's blob auditing policy.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="data"> Properties of extended blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<ArmOperation<ExtendedServerBlobAuditingPolicyResource>> CreateOrUpdateAsync(WaitUntil waitUntil, BlobAuditingPolicyName blobAuditingPolicyName, ExtendedServerBlobAuditingPolicyData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.CreateOrUpdate");
            scope.Start();
            try
            {
                var response = await _extendedServerBlobAuditingPolicyRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, data, cancellationToken).ConfigureAwait(false);
                var operation = new SqlArmOperation<ExtendedServerBlobAuditingPolicyResource>(new ExtendedServerBlobAuditingPolicyOperationSource(Client), _extendedServerBlobAuditingPolicyClientDiagnostics, Pipeline, _extendedServerBlobAuditingPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Creates or updates an extended server's blob auditing policy.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_CreateOrUpdate
        /// </summary>
        /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="data"> Properties of extended blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual ArmOperation<ExtendedServerBlobAuditingPolicyResource> CreateOrUpdate(WaitUntil waitUntil, BlobAuditingPolicyName blobAuditingPolicyName, ExtendedServerBlobAuditingPolicyData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.CreateOrUpdate");
            scope.Start();
            try
            {
                var response = _extendedServerBlobAuditingPolicyRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, data, cancellationToken);
                var operation = new SqlArmOperation<ExtendedServerBlobAuditingPolicyResource>(new ExtendedServerBlobAuditingPolicyOperationSource(Client), _extendedServerBlobAuditingPolicyClientDiagnostics, Pipeline, _extendedServerBlobAuditingPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, data).Request, response, OperationFinalStateVia.Location);
                if (waitUntil == WaitUntil.Completed)
                    operation.WaitForCompletion(cancellationToken);
                return operation;
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Gets an extended server's blob auditing policy.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_Get
        /// </summary>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<ExtendedServerBlobAuditingPolicyResource>> GetAsync(BlobAuditingPolicyName blobAuditingPolicyName, CancellationToken cancellationToken = default)
        {
            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.Get");
            scope.Start();
            try
            {
                var response = await _extendedServerBlobAuditingPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new ExtendedServerBlobAuditingPolicyResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Gets an extended server's blob auditing policy.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_Get
        /// </summary>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<ExtendedServerBlobAuditingPolicyResource> Get(BlobAuditingPolicyName blobAuditingPolicyName, CancellationToken cancellationToken = default)
        {
            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.Get");
            scope.Start();
            try
            {
                var response = _extendedServerBlobAuditingPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new ExtendedServerBlobAuditingPolicyResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Lists extended auditing settings of a server.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings
        /// Operation Id: ExtendedServerBlobAuditingPolicies_ListByServer
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="ExtendedServerBlobAuditingPolicyResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual AsyncPageable<ExtendedServerBlobAuditingPolicyResource> GetAllAsync(CancellationToken cancellationToken = default)
        {
            async Task<Page<ExtendedServerBlobAuditingPolicyResource>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.GetAll");
                scope.Start();
                try
                {
                    var response = await _extendedServerBlobAuditingPolicyRestClient.ListByServerAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value.Select(value => new ExtendedServerBlobAuditingPolicyResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<ExtendedServerBlobAuditingPolicyResource>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.GetAll");
                scope.Start();
                try
                {
                    var response = await _extendedServerBlobAuditingPolicyRestClient.ListByServerNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value.Select(value => new ExtendedServerBlobAuditingPolicyResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary>
        /// Lists extended auditing settings of a server.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings
        /// Operation Id: ExtendedServerBlobAuditingPolicies_ListByServer
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="ExtendedServerBlobAuditingPolicyResource" /> that may take multiple service requests to iterate over. </returns>
        public virtual Pageable<ExtendedServerBlobAuditingPolicyResource> GetAll(CancellationToken cancellationToken = default)
        {
            Page<ExtendedServerBlobAuditingPolicyResource> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.GetAll");
                scope.Start();
                try
                {
                    var response = _extendedServerBlobAuditingPolicyRestClient.ListByServer(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value.Select(value => new ExtendedServerBlobAuditingPolicyResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<ExtendedServerBlobAuditingPolicyResource> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.GetAll");
                scope.Start();
                try
                {
                    var response = _extendedServerBlobAuditingPolicyRestClient.ListByServerNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
                    return Page.FromValues(response.Value.Value.Select(value => new ExtendedServerBlobAuditingPolicyResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <summary>
        /// Checks to see if the resource exists in azure.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_Get
        /// </summary>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<bool>> ExistsAsync(BlobAuditingPolicyName blobAuditingPolicyName, CancellationToken cancellationToken = default)
        {
            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.Exists");
            scope.Start();
            try
            {
                var response = await _extendedServerBlobAuditingPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, cancellationToken: cancellationToken).ConfigureAwait(false);
                return Response.FromValue(response.Value != null, response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Checks to see if the resource exists in azure.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}
        /// Operation Id: ExtendedServerBlobAuditingPolicies_Get
        /// </summary>
        /// <param name="blobAuditingPolicyName"> The name of the blob auditing policy. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<bool> Exists(BlobAuditingPolicyName blobAuditingPolicyName, CancellationToken cancellationToken = default)
        {
            using var scope = _extendedServerBlobAuditingPolicyClientDiagnostics.CreateScope("ExtendedServerBlobAuditingPolicyCollection.Exists");
            scope.Start();
            try
            {
                var response = _extendedServerBlobAuditingPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, blobAuditingPolicyName, cancellationToken: cancellationToken);
                return Response.FromValue(response.Value != null, response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        IEnumerator<ExtendedServerBlobAuditingPolicyResource> IEnumerable<ExtendedServerBlobAuditingPolicyResource>.GetEnumerator()
        {
            return GetAll().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetAll().GetEnumerator();
        }

        IAsyncEnumerator<ExtendedServerBlobAuditingPolicyResource> IAsyncEnumerable<ExtendedServerBlobAuditingPolicyResource>.GetAsyncEnumerator(CancellationToken cancellationToken)
        {
            return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
        }
    }
}


text:
package com.github.kmbulebu.dsc.it100.commands.read;

import com.github.kmbulebu.dsc.it100.commands.ICommandHelp;

public class PartitionReadyCommand extends BasePartitionCommand implements
		ICommandHelp {

	/**
	 *
	 */
	private static final long serialVersionUID = 6061154668565761211L;

	public static final String CODE = "650";

	public String getDescription() {
		return "This command indicates that the partition can now be armed (all zones restored, no troubles, etc). Also issued at the end of Bell Timeout if the par- tition was READY when an alarm occurred.";
	}

	@Override
	public String toString() {
		return "PartitionReadyCommand [toString()=" + super.toString() + "]";
	}

}


text:
![Static Logo](docs/static.png)

[![Version](https://img.shields.io/github/release/venmo/Static.svg)](https://github.com/venmo/Static/releases) ![Status](https://travis-ci.org/venmo/Static.svg?branch=master) ![Swift Version](https://img.shields.io/badge/swift-4.2-orange.svg) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Simple static table views for iOS in Swift. Static's goal is to separate model data from presentation. `Row`s and `Section`s are your "view models" for your cells. You simply specify a cell class to use and that handles all of the presentation. See the [usage](#usage) section below for details.

## Version Compatibility

| Swift Version | Static Version |
| ------------- | -------------- |
| 5.0+          | 4.0.0          |
| 4.2+          | 3.0.1          |
| 3.2+          | 2.1            |
| 3.0.1         | 2.0.1          |
| 3.0           | 2.0            |
| 2.3           | 1.2            |
| 2.2           | 1.1            |
| 2.0 - 2.1     | 1.0            |

## Installation

### Carthage

[Carthage](https://github.com/carthage/carthage) is the recommended way to install Static. Add the following to your Cartfile:

``` ruby
github "venmo/Static"
```

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. To install Static with CocoaPods:

Make sure CocoaPods is installed (Static requires version 0.37 or greater).

Update your Podfile to include the following:

```ruby
use_frameworks!
pod 'Static', git: 'https://github.com/venmo/Static'
```

Run `pod install`.

### Manual

For manual installation, it's recommended to add the project as a subproject to your project or workspace and adding the appropriate framework as a target dependency.

## Usage

An [example app](Example) is included demonstrating Static's functionality.

### Getting Started

To use Static, you need to define [`Row`s](Static/Row.swift) and [`Section`s](Static/Section.swift) to describe your data. Here's a simple example:

```swift
import Static

Section(rows: [
    Row(text: "Hello")
])
```

You can configure `Section`s and `Row`s for anything you want. Here's another example:

```swift
Section(header: "Money", rows: [
    Row(text: "Balance", detailText: "$12.00", accessory: .disclosureIndicator, selection: {
        // Show statement
    }),
    Row(text: "Transfer to Bank…", cellClass: ButtonCell.self, selection: {
        [unowned self] in
        let viewController = ViewController()
        self.presentViewController(viewController, animated: true, completion: nil)
    })
], footer: "Transfers usually arrive within 1-3 business days.")
```

Since this is Swift, we can provide instance methods instead of inline blocks for selections. This makes things really nice. You don't have to switch on index paths in a `tableView:didSelectRowAtIndexPath:` any more!

### Customizing Appearance

The `Row` never has access to the cell. This is by design. The `Row` shouldn't care about its appearance other than specifying what will handle it. In practice, this has been really nice. Our cells have one responsibility.

There are several custom cells provided:

* `Value1Cell` — This is the default cell. It's a plain `UITableViewCell` with the `.Value1` style.
* `Value2Cell` — Plain `UITableViewCell` with the `.Value2` style.
* `SubtitleCell` — Plain `UITableViewCell` with the `.Subtitle` style.
* `ButtonCell` — Plain `UITableViewCell` with the `.Default` style. The `textLabel`'s `textColor` is set to the cell's `tintColor`.

All of these conform to [`Cell`](Static/Cell.swift). The gist of the protocol is one method:

```swift
func configure(row row: Row)
```

This gets called by [`DataSource`](Static/DataSource.swift) (which we'll look at more in a minute) to set the row on the cell. There is a default implementation provided by the protocol that simply sets the `Row`'s `text` on the cell's `textLabel`, etc. If you need to do custom things, this is a great place to hook in.

`Row` also has a `context` property. You can put whatever you want in here that the cell needs to know. You should try to use this as sparingly as possible.

### Custom Row Accessories

`Row` has an `accessory` property that is an `Accessory` enum. This has cases for all of `UITableViewCellAccessoryType`. Here's a row with a checkmark:

```swift
Row(text: "Buy milk", accessory: .checkmark)
```

Easy enough. Some of the system accessory types are selectable (like that little *i* button with a circle around it). You can make those and handle the selection like this:

```swift
Row(text: "Sam Soffes", accessory: .detailButton({
  // Show info about this contact
}))
```

Again, you could use whatever function here. Instance methods are great for this.

There is an additional case called `.view` that takes a custom view. Here's a `Row` with a custom accessory view:

```swift
Row(text: "My Profile", accessory: .view(someEditButton))
```

### Custom Section Header & Footer Views

`Section` has properties for `header` and `footer`. These take a `Section.Extremity`. This is an enum with `Title` and `View` cases. `Extremity` is `StringLiteralConvertible` you can simply specify strings if you want titles like we did the [Getting Started](#getting-started) section.

For a custom view, you can simply specify the `View` case:

```swift
Section(header: .view(yourView))
```

The height returned to the table view will be the view's `bounds.height` so be sure it's already sized properly.

### Working with the Data Source

To hook up your `Section`s and `Row`s to a table view, simply initialize a `DataSource`:

```swift
let dataSource = DataSource()
dataSource.sections = [
    Section(rows: [
        Row(text: "Hello")
    ])
]
```

Now assign your table view:

```swift
dataSource.tableView = tableView
```

Easy as that! If you modify your data source later, it will automatically update the table view for you. It is important that you don't change the table view's `dataSource` or `delegate`. The `DataSource` needs to be those so it can handle events correctly. The purpose of `Static` is to abstract all of that away from you.

### Wrapping Up

There is a provided [`TableViewController`](Static/TableViewController.swift) that sets up a `DataSource` for you. Here's a short example:

```swift
class SomeViewController: TableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        dataSource.sections = [
            Section(rows: [
                Row(text: "Hi")
            ]),
            // ...
        ]
    }
}
```

Enjoy.


text:
> Left pad a string with zeros or a specified string. Fastest implementation.

## Install with [npm](npmjs.org)

```bash
npm i pad-left --save
```

## Usage

```js
var pad = require('pad-left');
pad('abc', 10);
//=> '          abc'

pad('abc', 10, '~');
//=> '~~~~~~~~~~abc'
```

## Related projects

Other awesome node.js libraries for padding and aligning strings.

* [align-text](https://github.com/jonschlinkert/align-text): Align the text in a string.
* [center-align](https://github.com/jonschlinkert/center-align): Center-align the text in a string.
* [justified](https://github.com/jonschlinkert/justified): Wrap words to a specified length and justified the text.
* [pad-right](https://github.com/jonschlinkert/pad-right): Right pad a string with zeros or a specified string. Fastest implementation.
* [repeat-string](https://github.com/jonschlinkert/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string.
* [right-align](https://github.com/jonschlinkert/right-align): Right-align the text in a string.
* [word-wrap](https://github.com/jonschlinkert/word-wrap): Wrap words to a specified length.

## Running tests

Install dev dependencies:

```bash
npm i -d && npm test
```

## Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/pad-left/issues)

## Author

**Jon Schlinkert**

+ [github/jonschlinkert](https://github.com/jonschlinkert)
+ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)

## License

Copyright (c) 2014-2015 Jon Schlinkert
Released under the MIT license.

***

_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on April 27, 2015._

<!-- reflinks generated by verb-reflinks plugin -->

[assemble]: http://assemble.io
[template]: https://github.com/jonschlinkert/template
[verb]: https://github.com/assemble/verb


text:
#pragma once

/*  BOSS Algorithm implementation
 *  Reference:
 *
 *  A Bayesian Sampling Approach to Exploration in Reinforcement Learning
 *  John Asmuth, Lihong Li, Michael L. Littman, Ali Nouri, David Wingate
 *  UAI 2009
 */

class SIMULATOR;
class SamplerFactory;

typedef unsigned int uint;

class BOSS
{
public:

    struct PARAMS
    {
        PARAMS();

        int Verbose;
				uint K;
				uint B;
				double epsilon;
    };

    BOSS(const SIMULATOR& simulator, const PARAMS& params,
				SamplerFactory& sampFact);
    ~BOSS();

    uint SelectAction(uint state);
    bool Update(uint state, uint action, uint observation, double reward);

		void createMergedModel();

	private:
		uint* counts;
    const SIMULATOR& Simulator;

		//BOSS-specific
		bool do_sample;
		uint* qcounts;
		PARAMS Params;

		//Merged model
		uint Am;
		double* Pm;
		double* Rm;
		uint* RLPI;
		double* V;

		//Cached values
		uint S,A,SA,SAS,SAm;

		SamplerFactory& SampFact;
};


text:
package org.jbpm.compiler.xml.processes;

import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.node.DynamicNode;

public class DynamicNodeHandler extends CompositeNodeHandler {

    protected Node createNode() {
        return new DynamicNode();
    }

    public Class<?> generateNodeFor() {
        return DynamicNode.class;
    }

    protected String getNodeName() {
    	return "dynamic";
    }

}


text:
// This file was generated by Mendix Business Modeler.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.

package communitycommons.actions;

import communitycommons.Misc;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;

/**
 * Returns the runtime version of this application.
 */
public class GetRuntimeVersion extends CustomJavaAction<String>
{
	public GetRuntimeVersion(IContext context)
	{
		super(context);
	}

	@Override
	public String executeAction() throws Exception
	{
		// BEGIN USER CODE
		return Misc.getRuntimeVersion();
		// END USER CODE
	}

	/**
	 * Returns a string representation of this action
	 */
	@Override
	public String toString()
	{
		return "GetRuntimeVersion";
	}

	// BEGIN EXTRA CODE
	// END EXTRA CODE
}


text:
package com.woniukeji.jianmerchant.entity;

/**
 * Created by invinjun on 2016/3/9.
 * 用户实名表
 t_user_realname
 id           ID
 login_id     用户登录表关联ID
 front_image  正面
 behind_image 反面
 realname     真实姓名
 id_number    身份证号
 sex	     性别
 */
public class RealName {
    public T_user_realname getT_user_realname() {
        return t_user_realname;
    }

    public void setT_user_realname(T_user_realname t_user_realname) {
        this.t_user_realname = t_user_realname;
    }

    private T_user_realname t_user_realname;
    public  class T_user_realname{
        private String id;
        private String login_id;
        private String front_image;
        private String behind_image;
        private String realname;
        private String id_number;
        private String sex;

        public String getId() {
            return id;
        }

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

        public String getLogin_id() {
            return login_id;
        }

        public void setLogin_id(String login_id) {
            this.login_id = login_id;
        }

        public String getFront_image() {
            return front_image;
        }

        public void setFront_image(String front_image) {
            this.front_image = front_image;
        }

        public String getBehind_image() {
            return behind_image;
        }

        public void setBehind_image(String behind_image) {
            this.behind_image = behind_image;
        }

        public String getRealname() {
            return realname;
        }

        public void setRealname(String realname) {
            this.realname = realname;
        }

        public String getId_number() {
            return id_number;
        }

        public void setId_number(String id_number) {
            this.id_number = id_number;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }
    }

}


text:
/*
	Initialisation functions for exception handlers, PLL and MAM

	Partially copied from Jim Lynch's tutorial
*/

/**********************************************************
                  Header files
 **********************************************************/

#include "startup.h"

#define MAMCR		*(volatile unsigned int *)0xE01FC000
#define MAMTIM		*(volatile unsigned int *)0xE01FC004

#define PLLCON		*(volatile unsigned int *)0xE01FC080
#define PLLCFG		*(volatile unsigned int *)0xE01FC084
#define PLLSTAT		*(volatile unsigned int *)0xE01FC088
#define PLLFEED		*(volatile unsigned int *)0xE01FC08C

#define VPBDIV		*(volatile unsigned int *)0xE01FC100

void IRQ_Routine (void)   __attribute__ ((interrupt("IRQ")));
void FIQ_Routine (void)   __attribute__ ((interrupt("FIQ")));
void SWI_Routine (void)   __attribute__ ((interrupt("SWI")));
void UNDEF_Routine (void) __attribute__ ((interrupt("UNDEF")));

/*  Stubs for various interrupts (may be replaced later)  */
/*  ----------------------------------------------------  */

void IRQ_Routine (void) {
	while (1) ;
}

void FIQ_Routine (void)  {
	while (1) ;
}

void SWI_Routine (void)  {
	while (1) ;
}

void UNDEF_Routine (void) {
	while (1) ;
}

/**********************************************************
                      Initialize
**********************************************************/

#define PLOCK 0x400

static void feed(void)
{
	PLLFEED = 0xAA;
	PLLFEED = 0x55;
}

void Initialize(void)
{

	// 				Setting the Phased Lock Loop (PLL)
	//               ----------------------------------
	//
	// Olimex LPC-P2148 has a 12.0000 mhz crystal
	//
	// We'd like the LPC2148 to run at 60 mhz (has to be an even multiple of crystal)
	//
	// According to the Philips LPC2148 manual:   M = cclk / Fosc	where:	M    = PLL multiplier (bits 0-4 of PLLCFG)
	//																		cclk = 60000000 hz
	//																		Fosc = 12000000 hz
	//
	// Solving:	M = 60000000 / 12000000 = 5
	//
	//			Note: M - 1 must be entered into bits 0-4 of PLLCFG (assign 4 to these bits)
	//
	//
	// The Current Controlled Oscilator (CCO) must operate in the range 156 mhz to 320 mhz
	//
	// According to the Philips LPC2148 manual:	Fcco = cclk * 2 * P    where:	Fcco = CCO frequency
	//																			cclk = 60000000 hz
	//																			P = PLL divisor (bits 5-6 of PLLCFG)
	//
	// Solving:	Fcco = 60000000 * 2 * P
	//			P = 2  (trial value)
	//			Fcco = 60000000 * 2 * 2
	//			Fcc0 = 240000000 hz    (good choice for P since it's within the 156 mhz to 320 mhz range)
	//
	// From Table 22 (page 34) of Philips LPC2148 manual    P = 2, PLLCFG bits 5-6 = 1  (assign 1 to these bits)
	//
	// Finally:      PLLCFG = 0  01  00100  =  0x24
	//
	// Final note: to load PLLCFG register, we must use the 0xAA followed 0x55 write sequence to the PLLFEED register
	//             this is done in the short function feed() below
	//

 /* // COMENTAMOS ESTA PARTE PORQUE YA LA HACE EL STARTUP.S
	// Setting Multiplier and Divider values
  	PLLCFG = 0x24;
  	feed();

	// Enabling the PLL
	PLLCON = 0x1;
	feed();

	// Wait for the PLL to lock to set frequency
	while(!(PLLSTAT & PLOCK)) ;

	// Connect the PLL as the clock source
	PLLCON = 0x3;
	feed();

	// Enabling MAM and setting number of clocks used for Flash memory fetch
	MAMTIM = 0x3;
	MAMCR = 0x2;

*/
	// Setting peripheral Clock (pclk) to System Clock (cclk)
	VPBDIV = 0x1;
}


text:
get https://www.portal.brou.com.uy/web/guest/cotizaciones

parse

push

### cron task

Send a push notification each 10 minutos

`*/10 * * * * /home/matungos/ebrou-notifier-server/run.sh`


text:
using namespace std;

VictoryStand::VictoryStand(int originX, int originY, Texture* texture) :
	Tetramino(originX, originY, 2, texture)
{
	setOrigin(originX, originY);
}

void VictoryStand::setOrigin(int x, int y)
{
	blockPositions[0].setX(x);
	blockPositions[0].setY(y - texture->getHeight());

	blockPositions[1].setX(x - texture->getWidth());
	blockPositions[1].setY(y);

	blockPositions[2].setX(x);
	blockPositions[2].setY(y);

	blockPositions[3].setX(x + texture->getWidth());
	blockPositions[3].setY(y);
}


text:
package org.fest.swing.driver;

import static java.lang.String.valueOf;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.swing.test.core.CommonAssertions.failWhenExpectingException;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Strings.concat;

import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests for {@link JListDriver#selectItems(javax.swing.JList, int, int)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
@RunWith(Parameterized.class)
public class JListDriver_selectItemsByRange_withInvalidIndex_Test extends JListDriver_TestCase {
  private final int index;

  @Parameters
  public static Collection<Object[]> indices() {
    return newArrayList(indicesOutOfBounds());
  }

  public JListDriver_selectItemsByRange_withInvalidIndex_Test(int index) {
    this.index = index;
  }

  @Test
  public void should_throw_error_if_starting_index_is_out_of_bounds() {
    try {
      driver.selectItems(list, index, 1);
      failWhenExpectingException();
    } catch (IndexOutOfBoundsException e) {
      assertThat(e.getMessage()).isEqualTo(
          concat("Item index (", valueOf(index), ") should be between [0] and [2] (inclusive)"));
    }
  }

  @Test
  public void should_throw_error_if_endng_index_is_out_of_bounds() {
    try {
      driver.selectItems(list, 0, index);
      failWhenExpectingException();
    } catch (IndexOutOfBoundsException e) {
      assertThat(e.getMessage()).isEqualTo(
          concat("Item index (", valueOf(index), ") should be between [0] and [2] (inclusive)"));
    }
  }

  @Test
  public void should_keep_original_selection_if_index_is_out_of_bounds() {
    select(1);
    showWindow();
    try {
      driver.selectItems(list, 0, index);
      failWhenExpectingException();
    } catch (IndexOutOfBoundsException e) {
    }
    assertThat(selectedValue()).isEqualTo("two");
  }
}


text:
#import "UIImage+ImageEffects.h"

@import Accelerate;
#import <float.h>

@implementation UIImage (ImageEffects)

+ (UIImage *)screenshot
{
    CGSize imageSize = CGSizeZero;

    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        imageSize = [UIScreen mainScreen].bounds.size;
    } else {
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    }

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            CGContextRotateCTM(context, (float)M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            CGContextRotateCTM(context, (float)-M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, (float)M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        } else {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)applyLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3f];
    return [self applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
}

- (UIImage *)applyExtraLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.97f alpha:0.82f];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
}

- (UIImage *)applyDarkEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.11f alpha:0.73f];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8f maskImage:nil];
}

- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
{
    const CGFloat EffectColorAlpha = 0.6f;
    UIColor *effectColor = tintColor;
    int componentCount = (NSInteger)CGColorGetNumberOfComponents(tintColor.CGColor);
    if (componentCount == 2) {
        CGFloat b;
        if ([tintColor getWhite:&b alpha:NULL]) {
            effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
        }
    }
    else {
        CGFloat r, g, b;
        if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
            effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
        }
    }
    return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
}

- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
{
    // Check pre-conditions.
    if (self.size.width < 1 || self.size.height < 1) {
        NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
        return nil;
    }
    if (!self.CGImage) {
        NSLog (@"*** error: image must be backed by a CGImage: %@", self);
        return nil;
    }
    if (maskImage && !maskImage.CGImage) {
        NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
        return nil;
    }

    CGRect imageRect = { CGPointZero, self.size };
    UIImage *effectImage = self;

    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
    BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
    if (hasBlur || hasSaturationChange) {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectInContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(effectInContext, 1.0, -1.0);
        CGContextTranslateCTM(effectInContext, 0, -self.size.height);
        CGContextDrawImage(effectInContext, imageRect, self.CGImage);

        vImage_Buffer effectInBuffer;
        effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
        effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
        effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
        effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
        vImage_Buffer effectOutBuffer;
        effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
        effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
        effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
        effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

        if (hasBlur) {
            // A description of how to compute the box kernel width from the Gaussian
            // radius (aka standard deviation) appears in the SVG spec:
            // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
            //
            // For larger values of 's' (s >= 2.0), an approximation can be used: Three
            // successive box-blurs build a piece-wise quadratic convolution kernel, which
            // approximates the Gaussian kernel to within roughly 3%.
            //
            // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
            //
            // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
            //
            CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
            NSUInteger radius = (NSUInteger)floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
            if (radius % 2 != 1) {
                radius += 1; // force radius to be odd so that the three box-blur methodology works.
            }
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
        }
        BOOL effectImageBuffersAreSwapped = NO;
        if (hasSaturationChange) {
            CGFloat s = saturationDeltaFactor;
            CGFloat floatingPointSaturationMatrix[] = {
                0.0722f + 0.9278f * s,  0.0722f - 0.0722f * s,  0.0722f - 0.0722f * s,  0,
                0.7152f - 0.7152f * s,  0.7152f + 0.2848f * s,  0.7152f - 0.7152f * s,  0,
                0.2126f - 0.2126f * s,  0.2126f - 0.2126f * s,  0.2126f + 0.7873f * s,  0,
                                  0,                    0,                    0,  1,
            };
            const int32_t divisor = 256;
            NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
            int16_t saturationMatrix[matrixSize];
            for (NSUInteger i = 0; i < matrixSize; ++i) {
                saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
            }
            if (hasBlur) {
                vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                effectImageBuffersAreSwapped = YES;
            }
            else {
                vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
            }
        }
        if (!effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if (effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Set up output context.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef outputContext = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -self.size.height);

    // Draw base image.
    CGContextDrawImage(outputContext, imageRect, self.CGImage);

    // Draw effect image.
    if (hasBlur) {
        CGContextSaveGState(outputContext);
        if (maskImage) {
            CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
        }
        CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
        CGContextRestoreGState(outputContext);
    }

    // Add in color tint.
    if (tintColor) {
        CGContextSaveGState(outputContext);
        CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
        CGContextFillRect(outputContext, imageRect);
        CGContextRestoreGState(outputContext);
    }

    // Output image is ready.
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outputImage;
}

@end


text:
package org.kie.workbench.common.screens.datamodeller.model;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.guvnor.common.services.shared.metadata.model.Overview;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.kie.workbench.common.services.datamodeller.core.AnnotationDefinition;
import org.kie.workbench.common.services.datamodeller.core.DataModel;
import org.kie.workbench.common.services.datamodeller.core.DataObject;
import org.kie.workbench.common.services.datamodeller.core.PropertyType;
import org.kie.workbench.common.services.shared.project.KieProject;
import org.uberfire.backend.vfs.Path;

@Portable
public class EditorModelContent extends DataModelerResult {

    /**
     * Data model for current project at the time the DataObject was loaded.
     */
    DataModel dataModel;

    /**
     * Model for the .java file being edited.
     */
    private DataObject dataObject;

    private String originalClassName;

    private String originalPackageName;

    /**
     * Path for the file that is being edited.
     */
    private Path path;

    /**
     * Source of the .java file being edited.
     */
    private String source;

    private Overview overview;

    private long elapsedTime;

    private KieProject currentProject;

    private Set<String> currentProjectPackages = new HashSet<String>(  );

    private Map<String, Path> dataObjectPaths = new HashMap<String, Path>(  );

    private Map<String, AnnotationDefinition> annotationDefinitions = null;

    private List<PropertyType> propertyTypes = null;

    public EditorModelContent() {
    }

    public DataModel getDataModel() {
        return dataModel;
    }

    public void setDataModel( DataModel dataModel ) {
        this.dataModel = dataModel;
    }

    public DataObject getDataObject() {
        return dataObject;
    }

    public void setDataObject( DataObject dataObject ) {
        this.dataObject = dataObject;
    }

    public String getOriginalClassName() {
        return originalClassName;
    }

    public void setOriginalClassName( String originalClassName ) {
        this.originalClassName = originalClassName;
    }

    public String getOriginalPackageName() {
        return originalPackageName;
    }

    public void setOriginalPackageName( String originalPackageName ) {
        this.originalPackageName = originalPackageName;
    }

    public Path getPath() {
        return path;
    }

    public void setPath( Path path ) {
        this.path = path;
    }

    public String getSource() {
        return source;
    }

    public void setSource( String source ) {
        this.source = source;
    }

    public long getElapsedTime() {
        return elapsedTime;
    }

    public void setElapsedTime( long elapsedTime ) {
        this.elapsedTime = elapsedTime;
    }

    public KieProject getCurrentProject() {
        return currentProject;
    }

    public void setCurrentProject( KieProject currentProject ) {
        this.currentProject = currentProject;
    }

    public Set<String> getCurrentProjectPackages() {
        return currentProjectPackages;
    }

    public void setCurrentProjectPackages( Set<String> currentProjectPackages ) {
        this.currentProjectPackages = currentProjectPackages;
    }

    public Overview getOverview() {
        return overview;
    }

    public void setOverview( Overview overview ) {
        this.overview = overview;
    }

    public Map<String, Path> getDataObjectPaths() {
        return dataObjectPaths;
    }

    public void setDataObjectPaths( Map<String, Path> dataObjectPaths ) {
        this.dataObjectPaths = dataObjectPaths;
    }

    public Map<String, AnnotationDefinition> getAnnotationDefinitions() {
        return annotationDefinitions;
    }

    public void setAnnotationDefinitions( Map<String, AnnotationDefinition> annotationDefinitions ) {
        this.annotationDefinitions = annotationDefinitions;
    }

    public List<PropertyType> getPropertyTypes() {
        return propertyTypes;
    }

    public void setPropertyTypes( List<PropertyType> propertyTypes ) {
        this.propertyTypes = propertyTypes;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Atas Inst. Micol. Univ. Recife 5: 261 (1967)

#### Original name
Trichopeltospora reticulata Bat., J.L. Bezerra & Valle

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// TODO this should be fully commented; however it's not part of the main public API

#pragma warning disable 1591
#pragma warning disable 1570

namespace CsQuery.EquationParser
{
    public interface IEquationParser
    {
        bool TryParse(string text, out IOperand operand);
        IOperand Parse(string text);
        IOperand Parse<T>(string text) where T : IConvertible;
        string Error { get; }
    }
    public interface IEquationParser<T> : IEquationParser where T : IConvertible
    {
        bool TryParse(string text, out IOperand<T> operand);
        new IOperand<T> Parse(string text);
    }
}


text:
layout: post
title: "A red-green-refactor checklist"
description: "A simple read-do checklist for test-driven development."
date: 2019-10-21 6:49 UTC
tags: [Unit Testing]
---
{% include JB/setup %}

		{{ page.description }}

		I recently read The Checklist Manifesto, a book about the power of checklists. That may sound off-putting and tedious, but I actually found it inspiring. It explains how checklists empower skilled professionals to focus on difficult problems, while preventing avoidable mistakes.

		Since I read the book with the intent to see if there were ideas that we could apply in software development, I thought about checklists one might create for software development. Possibly the simplest checklist is one that describes the red-green-refactor cycle of test-driven development.

		Types of checklists #

		As the book describes, there's basically two types of checklists:

Do-confirm. With such a checklist, you perform a set of tasks, and then subsequently, at a sufficient pause point go through the checklist to verify that you remembered to perform all the tasks on the list.

Read-do. With this type of checklist, you read each item for instructions and then perform the task. Only when you've performed the task do you move on to the next item on the list.

		I find it most intuitive to describe the red-green-refactor cycle as a read-do list. I did, however, find it expedient to include a do-confirm sub-list for one of the overall steps.

		This list is, I think, mostly useful if you're still learning test-driven development. It can be easily internalised. As such, I offer this for inspiration, and as a learning aid.

		Red-green-refactor checklist #

		Read each of the steps in the list and perform the task.

Write a failing test.

Did you run the test?

Did it fail?

Did it fail because of an assertion?

Did it fail because of the last assertion?

Make all tests pass by doing the simplest thing that could possibly work.

Consider the resulting code. Can it be improved? If so, do it, but make sure that all tests still pass.

Repeat

		Perhaps the most value this checklist provides isn't so much the overall read-do list, but rather the subordinate do-confirm list associated with the first step.

		I regularly see people write failing tests as an initial step. The reason the test fails, however, is because the implementation throws an exception.

		Improperly failing tests #

		Consider, as an example, the first test you might write when doing the FizzBuzz kata.

[Fact]
public void One()
{
    string actual = FizzBuzz.Convert(1);
    Assert.Equal("1", actual);
}

		I wrote this test first (i.e. before the 'production' code) and used Visual Studio's refactoring tools to generate the implied type and method.

		When I run the test, it fails.

		Further investigation, however, reveals that the test fails when Convert is called:

Ploeh.Katas.FizzBuzzKata.FizzBuzzTests.One
   Source: FizzBuzzTests.cs line: 11
   Duration: 8 ms

  Message:
    System.NotImplementedException : The method or operation is not implemented.
  Stack Trace:
    at FizzBuzz.Convert(Int32 i) in FizzBuzz.cs line: 9
    at FizzBuzzTests.One() in FizzBuzzTests.cs line: 13

		This is hardly surprising, since this is the current 'implementation':

public static string Convert(int i)
{
    throw new NotImplementedException();
}

		This is what the subordinate do-confirm checklist is for. Did the test fail because of an assertion? In this case, the answer is no.

		This means that you're not yet done with the read phase.

		Properly failing tests #

		You can address the issue by changing the Convert method:

public static string Convert(int i)
{
    return "";
}

		This causes the test to fail because of an assertion:

 Ploeh.Katas.FizzBuzzKata.FizzBuzzTests.One
   Source: FizzBuzzTests.cs line: 11
   Duration: 13 ms

  Message:
    Assert.Equal() Failure
              ↓ (pos 0)
    Expected: 1
    Actual:
              ↑ (pos 0)
  Stack Trace:
    at FizzBuzzTests.One() in FizzBuzzTests.cs line: 14

		Not only does the test fail because of an assertion - it fails because of the last assertion (since there's only one assertion). This completes the do-confirm checklist, and you're now ready to make the simplest change that could possibly work:

public static string Convert(int i)
{
    return "1";
}

		This passes the test suite.

		Conclusion #

		It's important to see tests fail. Particularly, it's important to see tests fail for the reason you expect them to fail. You'd be surprised how often you inadvertently write an assertion that can never fail.

		Once you've seen the test fail for the proper reason, make it pass.

		Finally, refactor the code if necessary.

    Comments

Tyson Williams

        I remember the first time that I realized that I did the red step wrong because my test didn't fail for the intended reason (i.e. it didn't fail because of an assertion).  Before that, I didn't realize that I needed to   This is a nice programming checklist.  Thanks for sharing it :)

	    3. Consider the resulting code. Can it be improved? If so, do it, but make sure that all tests still pass.

	    Finally, refactor the code if necessary.

	    If I can be a Devil's advocate for a moment, then I would say that code can always be improved and few things are necessary.  In all honesty though, I think the refactoring step is the most interesting.  All three steps include aspects of science and art, but I think the refactor step includes the most of both.  On the one hand, it is extremely creative and full of judgement calls about what code should be refactored and what properties the resulting code should have.  On the other hand, much of the work of how to (properly) refactor is laid out in books like Martin Fowler's Refacoring and is akin to algebraic manipulations of an algebraic formula.

        In other words, I feel like there is room to expand on this checklist in the refactor step.  Do you have any thoughts about you might expand it?

2019-10-25 00:33 UTC

Mark Seemann

				Tyson, thank you for writing. I agree that the refactoring step is both important and compelling. I can't, however, imagine how a checklist would be useful.

				The point of The Checklist Manifesto is that checklists help identify avoidable mistakes. A checklist isn't intended to describe an algorithm, but rather to make sure that crucial steps aren't forgotten.

				Another important point from The Checklist Manifesto is that a checklist is only effective if it's not too big. A checklist that tries to cover every eventuality isn't useful, because then people don't follow it.

				As you write, refactoring is a big topic, covered by several books. All the creativity and experience that goes into refactoring doesn't seem like something that can easily be expressed as an effective checklist.

				I don't mind being proven wrong, though, so by all means give it a go.

2019-10-25 21:51 UTC


text:
#ifndef __NVME_PCI_H__
#define __NVME_PCI_H__

#include "nvme_common.h"

#include <pciaccess.h>

#define NVME_PCI_PATH_MAX		256
#define NVME_PCI_CFG_SIZE		256
#define NVME_PCI_EXT_CAP_ID_SN		0x03

#define NVME_PCI_ANY_ID			0xffff
#define NVME_PCI_VID_INTEL		0x8086
#define NVME_PCI_VID_MEMBLAZE		0x1c5f

/*
 * PCI class code for NVMe devices.
 *
 * Base class code 01h: mass storage
 * Subclass code 08h: non-volatile memory
 * Programming interface 02h: NVM Express
 */
#define NVME_PCI_CLASS				0x010802

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB0	0x3c20
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB1	0x3c21
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB2	0x3c22
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB3	0x3c23
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB4	0x3c24
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB5	0x3c25
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB6	0x3c26
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB7	0x3c27
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB8	0x3c2e
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_SNB9	0x3c2f

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB0	0x0e20
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB1	0x0e21
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB2	0x0e22
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB3	0x0e23
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB4	0x0e24
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB5	0x0e25
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB6	0x0e26
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB7	0x0e27
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB8	0x0e2e
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_IVB9	0x0e2f

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW0	0x2f20
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW1	0x2f21
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW2	0x2f22
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW3	0x2f23
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW4	0x2f24
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW5	0x2f25
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW6	0x2f26
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW7	0x2f27
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW8	0x2f2e
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_HSW9	0x2f2f

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BWD0	0x0C50
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BWD1	0x0C51
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BWD2	0x0C52
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BWD3	0x0C53

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDXDE0	0x6f50
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDXDE1	0x6f51
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDXDE2	0x6f52
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDXDE3	0x6f53

#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX0	0x6f20
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX1	0x6f21
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX2	0x6f22
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX3	0x6f23
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX4	0x6f24
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX5	0x6f25
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX6	0x6f26
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX7	0x6f27
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX8	0x6f2e
#define NVME_PCI_DEVICE_ID_INTEL_IOAT_BDX9	0x6f2f

struct pci_device;
struct pci_slot_match;

struct pci_id {
	uint16_t  vendor_id;
	uint16_t  device_id;
	uint16_t  subvendor_id;
	uint16_t  subdevice_id;
};

/*
 * Initialize PCI subsystem.
 */
extern int nvme_pci_init(void);

/*
 * Search a PCI device and grab it if found.
 */
extern struct pci_device *
nvme_pci_device_probe(const struct pci_slot_match *slot);

/*
 * Reset a PCI device.
 */
extern int nvme_pci_device_reset(struct pci_device *dev);

/*
 * Get a device serial number.
 */
extern int nvme_pci_device_get_serial_number(struct pci_device *dev,
					     char *sn, size_t len);

/*
 * Compare two devices.
 * Return 0 if the devices are the same, 1 otherwise.
 */
static inline int nvme_pci_dev_cmp(struct pci_device *pci_dev1,
				   struct pci_device *pci_dev2)
{
	if (pci_dev1 == pci_dev2)
		return 0;

	if (pci_dev1->domain == pci_dev2->domain &&
	    pci_dev1->bus == pci_dev2->bus &&
	    pci_dev1->dev == pci_dev2->dev &&
	    pci_dev1->func == pci_dev2->func)
		return 0;

	return 1;
}

/*
 * Get a device PCI ID.
 */
static inline void nvme_pci_get_pci_id(struct pci_device *pci_dev,
				       struct pci_id *pci_id)
{
	pci_id->vendor_id = pci_dev->vendor_id;
	pci_id->device_id = pci_dev->device_id;
	pci_id->subvendor_id = pci_dev->subvendor_id;
	pci_id->subdevice_id = pci_dev->subdevice_id;
}

/*
 * Read a device config register.
 */
static inline int nvme_pcicfg_read8(struct pci_device *dev,
				    uint8_t *value, uint32_t offset)
{
	return pci_device_cfg_read_u8(dev, value, offset);
}

/*
 * Write a device config register.
 */
static inline int nvme_pcicfg_write8(struct pci_device *dev,
				     uint8_t value, uint32_t offset)
{
	return pci_device_cfg_write_u8(dev, value, offset);
}

/*
 * Read a device config register.
 */
static inline int nvme_pcicfg_read16(struct pci_device *dev,
				     uint16_t *value, uint32_t offset)
{
	return pci_device_cfg_read_u16(dev, value, offset);
}

/*
 * Write a device config register.
 */
static inline int nvme_pcicfg_write16(struct pci_device *dev,
				      uint16_t value, uint32_t offset)
{
	return pci_device_cfg_write_u16(dev, value, offset);
}

/*
 * Read a device config register.
 */
static inline int nvme_pcicfg_read32(struct pci_device *dev,
				     uint32_t *value, uint32_t offset)
{
	return pci_device_cfg_read_u32(dev, value, offset);
}

/*
 * Write a device config register.
 */
static inline int nvme_pcicfg_write32(struct pci_device *dev,
				      uint32_t value, uint32_t offset)
{
	return pci_device_cfg_write_u32(dev, value, offset);
}

/*
 * Map a device PCI BAR.
 */
static inline int nvme_pcicfg_map_bar(void *devhandle, unsigned int bar,
				      bool read_only, void **mapped_addr)
{
	struct pci_device *dev = devhandle;
	uint32_t flags = (read_only ? 0 : PCI_DEV_MAP_FLAG_WRITABLE);

	return pci_device_map_range(dev, dev->regions[bar].base_addr,
				    dev->regions[bar].size, flags, mapped_addr);
}

/*
 * Map a device PCI BAR (write combine).
 */
static inline int nvme_pcicfg_map_bar_write_combine(void *devhandle,
						    unsigned int bar,
						    void **mapped_addr)
{
	struct pci_device *dev = devhandle;
	uint32_t flags = PCI_DEV_MAP_FLAG_WRITABLE |
		PCI_DEV_MAP_FLAG_WRITE_COMBINE;

	return pci_device_map_range(dev, dev->regions[bar].base_addr,
				    dev->regions[bar].size, flags, mapped_addr);
}

/*
 * Unmap a device PCI BAR.
 */
static inline int nvme_pcicfg_unmap_bar(void *devhandle, unsigned int bar,
					void *addr)
{
	struct pci_device *dev = devhandle;

	return pci_device_unmap_range(dev, addr, dev->regions[bar].size);
}

/*
 * Get a device PCI BAR address and length.
 */
static inline void nvme_pcicfg_get_bar_addr_len(void *devhandle,
						unsigned int bar,
						uint64_t *addr, uint64_t *size)
{
	struct pci_device *dev = devhandle;

	*addr = (uint64_t)dev->regions[bar].base_addr;
	*size = (uint64_t)dev->regions[bar].size;
}

#endif /* __NVME_PCI_H__ */