text:
/* For more information see:
 * http://stackoverflow.com/questions/7057342/how-to-get-a-progress-bar-for-a-file-upload-with-apache-httpclient-4
 */

package ro.teodorbaciu.commons.client.ws.progress;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

/**
 * Allows the registration of a listener class for data write progress monitoring.
 *
 * @author Teodor Baciu
 *
 */
public class MultipartEntityWithProgressMonitoring extends MultipartEntity {

	private OutputStreamProgress outstream;
	private WriteListener writeListener;

	public MultipartEntityWithProgressMonitoring(WriteListener writeListener) {
		super();
		this.writeListener = writeListener;
	}

	public MultipartEntityWithProgressMonitoring(HttpMultipartMode mode, WriteListener writeListener) {
		super(mode);
		this.writeListener = writeListener;
	}

	public MultipartEntityWithProgressMonitoring(HttpMultipartMode mode, String boundary, Charset charset, WriteListener writeListener) {
		super(mode, boundary, charset);
		this.writeListener = writeListener;
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		this.outstream = new OutputStreamProgress(outstream, writeListener);
		super.writeTo(this.outstream);
	}

}


text:
package com.googlecode.test.phone.sip;

import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.SipListener;
import javax.sip.TimeoutEvent;
import javax.sip.TransactionTerminatedEvent;
import javax.sip.header.CSeqHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;

import org.apache.log4j.Logger;

import com.googlecode.test.phone.AbstractSipPhone;
import com.googlecode.test.phone.sip.handle.uac.ResponseHandlerFacade;
import com.googlecode.test.phone.sip.handle.uas.RequestHandlerFacade;

public class SipListenerImpl implements SipListener {

	private static final Logger LOG = Logger.getLogger(SipListenerImpl.class);

	private ResponseHandlerFacade responseHandlerFacade;
	private RequestHandlerFacade requestHandlerFacade;

	private ReceivedMessages receivedMessages=new ReceivedMessages();

	public SipListenerImpl(AbstractSipPhone sipPhone) {
		this.responseHandlerFacade = new ResponseHandlerFacade(sipPhone);
		this.requestHandlerFacade = new RequestHandlerFacade(sipPhone);
	}

	public ReceivedMessages getReceivedMessages() {
		return receivedMessages;
	}

	@Override
	public void processDialogTerminated(DialogTerminatedEvent arg0) {

	}

	@Override
	public void processIOException(IOExceptionEvent arg0) {
	}

	@Override
	public void processRequest(RequestEvent requestEvent) {
		Request request = requestEvent.getRequest();
		receivedMessages.getReceivedRequests().add(request);

		LOG.info(request);

		if (request.getMethod().equals(Request.REFER)) {
			try {
				requestHandlerFacade.getReferRequestHandler().handle(requestEvent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}

		if (request.getMethod().equals(Request.BYE)) {
			requestHandlerFacade.getByeRequestHandler().handle(requestEvent);
			return;
		}

		if (request.getMethod().equals(Request.INVITE)) {
			requestHandlerFacade.getInviteRequestHandler().handle(requestEvent);
			return;
		}

		if (request.getMethod().equals(Request.ACK)) {
			requestHandlerFacade.getAckRequestHandler().handle(requestEvent);
			return;
		}

		if (request.getMethod().equals(Request.OPTIONS)) {
			requestHandlerFacade.getOptionRequestHandler().handle(requestEvent);
		}
	}

	@Override
	public void processResponse(ResponseEvent responseEvent) {
		Response response = responseEvent.getResponse();
		LOG.info(response);
		receivedMessages.getReceivedResponses().add(response);

		CSeqHeader cseqHeader = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
		if (cseqHeader.getMethod().equals(Request.INVITE)) {
			responseHandlerFacade.getInviteResponseHandler().handle(responseEvent);
			return;
		}

		if (cseqHeader.getMethod().equals(Request.BYE)) {
			responseHandlerFacade.getByeResponseHandler().handle(responseEvent);
			return;
		}

		if (cseqHeader.getMethod().equals(Request.REGISTER)) {
			responseHandlerFacade.getRegisterResponseHandler().handle(responseEvent);
			return;
		}

	}

	@Override
	public void processTimeout(TimeoutEvent arg0) {

	}

	@Override
	public void processTransactionTerminated(TransactionTerminatedEvent arg0) {

	}

}

redpajama_set_name: RedPajamaGithub


text:
class APIException(Exception):

    MESSAGE = 'An unknown error has occured'
    CODE = 400

    def __init__(self, blame=None, message=None):
        self.blame = blame
        self.message = message
        pass

    def serialize(self):
        return {
            'type': self.__class__.__name__,
            'message': self.message if self.message is not None else self.MESSAGE,
            'blame': self.blame
        }

class ForbiddenException(APIException):
    MESSAGE = "You do not have access to this API"
    CODE = 403

class NotFoundException(APIException):
    MESSAGE = 'This API does not exist'
    CODE = 404

class FormattingException(APIException):
    MESSAGE = 'We could not parse your request'

class InvalidMethodException(APIException):
    MESSAGE = 'This API can not be called with this method'

class FieldMissingException(APIException):
    MESSAGE = 'Field is missing'

class ValueInvalidException(APIException):
    MESSAGE = 'Field value is invalid'


text:
import * as refs from "./refs";

/**
 * Interface for representing a metric to be rendered by the extension's CLI.
 */
export interface BucketedMetric {
  ref: refs.Ref;
  valueToday: Bucket | undefined;
  value7dAgo: Bucket | undefined;
  value28dAgo: Bucket | undefined;
}

/**
 * Bucket is the range that a raw number falls under.
 *
 * Valid bucket sizes are:
 * 0
 * 0 - 10
 * 10 - 20
 * 20 - 30
 * ...
 * 90 - 100
 * 100 - 200
 * 200 - 300
 * every 100...
 *
 * Note the buckets overlaps intentionally as a UX-optimization.
 */
export interface Bucket {
  low: number;
  high: number;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceská Mykol. 42(3): 145 (1988)

#### Original name
Unguicularia aconiti Svrcek

### Remarks
null


text:
package org.apache.ibatis.annotations;

import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.cache.impl.PerpetualCache;

import java.lang.annotation.*;

/**
 * 缓存注解
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CacheNamespace {
  Class<? extends org.apache.ibatis.cache.Cache> implementation() default PerpetualCache.class;

  Class<? extends org.apache.ibatis.cache.Cache> eviction() default LruCache.class;

  long flushInterval() default 0;

  int size() default 1024;

  boolean readWrite() default true;

  boolean blocking() default false;

  /**
   * Property values for a implementation object.
   * @since 3.4.2
   */
  Property[] properties() default {};

}


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Serilog;
using Thinktecture.Relay.Server.Communication;
using Thinktecture.Relay.Server.OnPremise;

namespace Thinktecture.Relay.Server.SignalR
{
	internal class OnPremisesConnection : PersistentConnection
	{
		private readonly ILogger _logger;
		private readonly IBackendCommunication _backendCommunication;

		public OnPremisesConnection(ILogger logger, IBackendCommunication backendCommunication)
		{
			_logger = logger;
			_backendCommunication = backendCommunication ?? throw new ArgumentNullException(nameof(backendCommunication));
		}

		protected override bool AuthorizeRequest(IRequest request)
		{
			if ((request.User?.Identity.IsAuthenticated ?? false) && request.User is ClaimsPrincipal principal)
			{
				var linkId = principal.FindFirst("OnPremiseId")?.Value;
				return !String.IsNullOrWhiteSpace(linkId) && Guid.TryParse(linkId, out var _);
			}

			return false;
		}

		protected override async Task OnConnected(IRequest request, string connectionId)
		{
			var onPremiseClaims = GetOnPremiseClaims(request);
			_logger?.Debug("On-premise connected. connection-id={ConnectionId}, link-id={LinkId}, user-name={UserName}, role={Role}", connectionId, onPremiseClaims.OnPremiseId, onPremiseClaims.UserName, onPremiseClaims.Role);

			await RegisterOnPremiseAsync(request, connectionId, onPremiseClaims).ConfigureAwait(false);

			await base.OnConnected(request, connectionId).ConfigureAwait(false);
		}

		protected override async Task OnReconnected(IRequest request, string connectionId)
		{
			var onPremiseClaims = GetOnPremiseClaims(request);
			_logger?.Debug("On-premise reconnected. connection-id={ConnectionId}, link-id={LinkId}, user-name={UserName}, role={Role}", connectionId, onPremiseClaims.OnPremiseId, onPremiseClaims.UserName, onPremiseClaims.Role);

			await RegisterOnPremiseAsync(request, connectionId, onPremiseClaims).ConfigureAwait(false);

			await base.OnReconnected(request, connectionId).ConfigureAwait(false);
		}

		protected override async Task OnDisconnected(IRequest request, string connectionId, bool stopCalled)
		{
			var onPremiseClaims = GetOnPremiseClaims(request);
			_logger?.Debug("On-premise disconnected. connection-id={ConnectionId}, link-id={LinkId}, user-name={UserName}, role={Role}", connectionId, onPremiseClaims.OnPremiseId, onPremiseClaims.UserName, onPremiseClaims.Role);

			await _backendCommunication.UnregisterOnPremiseConnectionAsync(connectionId).ConfigureAwait(false);

			await base.OnDisconnected(request, connectionId, stopCalled).ConfigureAwait(false);
		}

		private async Task ForwardClientRequestAsync(string connectionId, IOnPremiseConnectorRequest request)
		{
			_logger?.Verbose("Forwarding client request to connection. connection-id={ConnectionId}, request-id={RequestId}, http-method={RequestMethod}, url={RequestUrl}, origin-id={OriginId}, body-length={RequestContentLength}",
				connectionId, request.RequestId, request.HttpMethod, request.Url, request.OriginId, request.ContentLength);

			await Connection.Send(connectionId, request).ConfigureAwait(false);
		}

		private static OnPremiseClaims GetOnPremiseClaims(IRequest request)
		{
			var claimsPrincipal = (ClaimsPrincipal)request.User;
			var onPremiseId = claimsPrincipal.FindFirst("OnPremiseId")?.Value;

			if (!Guid.TryParse(onPremiseId, out var linkId))
				throw new ArgumentException($"The claim \"OnPremiseId\" is not valid: {onPremiseId}.");

			return new OnPremiseClaims(claimsPrincipal.FindFirst(ClaimTypes.Name)?.Value, linkId, claimsPrincipal.FindFirst(ClaimTypes.Role)?.Value);
		}

		private async Task RegisterOnPremiseAsync(IRequest request, string connectionId, OnPremiseClaims claims)
		{
			await _backendCommunication.RegisterOnPremiseAsync(new OnPremiseConnectionContext()
			{
				ConnectionId = connectionId,
				LinkId = claims.OnPremiseId,
				UserName = claims.UserName,
				Role = claims.Role,
				RequestAction = (cr, cancellationToken) => ForwardClientRequestAsync(connectionId, cr),
				IpAddress = GetIpAddressFromOwinEnvironment(request.Environment),
				ConnectorVersion = GetConnectorVersionFromRequest(request),
				ConnectorAssemblyVersion = GetConnectorAssemblyVersionFromRequest(request),
			}).ConfigureAwait(false);
		}

		// Adopted from http://stackoverflow.com/questions/11044361/signalr-get-caller-ip-address
		private string GetIpAddressFromOwinEnvironment(IDictionary<string, object> environment)
		{
			return Get<string>(environment, "server.RemoteIpAddress");
		}

		private int GetConnectorVersionFromRequest(IRequest request)
		{
			Int32.TryParse(request.QueryString["cv"], out var version);
			return version;
		}

		private string GetConnectorAssemblyVersionFromRequest(IRequest request)
		{
			return request.QueryString["av"] ?? "Unknown";
		}

		private static T Get<T>(IDictionary<string, object> env, string key)
		{
			return env.TryGetValue(key, out var value) ? (T)value : default;
		}

		private class OnPremiseClaims
		{
			public string UserName { get; }
			public Guid OnPremiseId { get; }
			public string Role { get; }

			public OnPremiseClaims(string userName, Guid onPremiseId, string role)
			{
				UserName = userName;
				OnPremiseId = onPremiseId;
				Role = role;
			}
		}
	}
}


text:
package com.gs.collections.impl.utility.internal;

import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import com.gs.collections.api.RichIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.Function3;
import com.gs.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.ObjectIntProcedure;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.list.PartitionMutableList;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.api.tuple.Twin;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.multimap.list.FastListMultimap;
import com.gs.collections.impl.partition.list.PartitionFastList;
import com.gs.collections.impl.tuple.Tuples;
import com.gs.collections.impl.utility.Iterate;

/**
 * The ListIterate class provides a few of the methods from the Smalltalk Collection Protocol for use with ArrayLists.
 * This includes do:, select:, reject:, collect:, inject:into:, detect:, detect:ifNone:, anySatisfy: and allSatisfy:
 */
public final class RandomAccessListIterate
{
    private RandomAccessListIterate()
    {
        throw new AssertionError("Suppress default constructor for noninstantiability");
    }

    public static <T> void toArray(List<T> list, T[] target, int startIndex, int sourceSize)
    {
        for (int i = 0; i < sourceSize; i++)
        {
            target[startIndex + i] = list.get(i);
        }
    }

    /**
     * @see Iterate#select(Iterable, Predicate)
     */
    public static <T> MutableList<T> select(List<T> list, Predicate<? super T> predicate)
    {
        return RandomAccessListIterate.select(list, predicate, FastList.<T>newList());
    }

    /**
     * @see Iterate#selectWith(Iterable, Predicate2, Object)
     */
    public static <T, IV> MutableList<T> selectWith(
            List<T> list,
            Predicate2<? super T, ? super IV> predicate,
            IV injectedValue)
    {
        return RandomAccessListIterate.selectWith(list, predicate, injectedValue, FastList.<T>newList());
    }

    /**
     * @see Iterate#select(Iterable, Predicate, Collection)
     */
    public static <T, R extends Collection<T>> R select(
            List<T> list,
            Predicate<? super T> predicate,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (predicate.accept(item))
            {
                targetCollection.add(item);
            }
        }
        return targetCollection;
    }

    /**
     * @see Iterate#selectWith(Iterable, Predicate2, Object, Collection)
     */
    public static <T, P, R extends Collection<T>> R selectWith(
            List<T> list,
            Predicate2<? super T, ? super P> predicate,
            P parameter,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (predicate.accept(item, parameter))
            {
                targetCollection.add(item);
            }
        }
        return targetCollection;
    }

    /**
     * @see Iterate#count(Iterable, Predicate)
     */
    public static <T> int count(
            List<T> list,
            Predicate<? super T> predicate)
    {
        int count = 0;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i)))
            {
                count++;
            }
        }
        return count;
    }

    public static <T, IV> int countWith(
            List<T> list,
            Predicate2<? super T, ? super IV> predicate,
            IV injectedValue)
    {
        int count = 0;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i), injectedValue))
            {
                count++;
            }
        }
        return count;
    }

    /**
     * @see Iterate#collectIf(Iterable, Predicate, Function)
     */
    public static <T, A> MutableList collectIf(
            List<T> list,
            Predicate<? super T> predicate,
            Function<? super T, ? extends A> function)
    {
        return RandomAccessListIterate.collectIf(list, predicate, function, FastList.newList());
    }

    /**
     * @see Iterate#collectIf(Iterable, Predicate, Function, Collection)
     */
    public static <T, A, R extends Collection> R collectIf(
            List<T> list,
            Predicate<? super T> predicate,
            Function<? super T, ? extends A> function,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (predicate.accept(item))
            {
                targetCollection.add(function.valueOf(item));
            }
        }
        return targetCollection;
    }

    /**
     * @see Iterate#reject(Iterable, Predicate)
     */
    public static <T> MutableList<T> reject(List<T> list, Predicate<? super T> predicate)
    {
        return RandomAccessListIterate.reject(list, predicate, FastList.<T>newList());
    }

    /**
     * @see Iterate#rejectWith(Iterable, Predicate2, Object)
     */
    public static <T, IV> MutableList<T> rejectWith(
            List<T> list,
            Predicate2<? super T, ? super IV> predicate,
            IV injectedValue)
    {
        return RandomAccessListIterate.rejectWith(list, predicate, injectedValue, FastList.<T>newList());
    }

    /**
     * @see Iterate#reject(Iterable, Predicate, Collection)
     */
    public static <T, R extends Collection<T>> R reject(
            List<T> list,
            Predicate<? super T> predicate,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (!predicate.accept(item))
            {
                targetCollection.add(item);
            }
        }
        return targetCollection;
    }

    /**
     * @see Iterate#reject(Iterable, Predicate, Collection)
     */
    public static <T, P, R extends Collection<T>> R rejectWith(
            List<T> list,
            Predicate2<? super T, ? super P> predicate,
            P parameter,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (!predicate.accept(item, parameter))
            {
                targetCollection.add(item);
            }
        }
        return targetCollection;
    }

    /**
     * @see Iterate#collect(Iterable, Function)
     */
    public static <T, A> MutableList collect(
            List<T> list,
            Function<? super T, ? extends A> function)
    {
        return collect(list, function, FastList.newList(list.size()));
    }

    /**
     * @see Iterate#collect(Iterable, Function, Collection)
     */
    public static <T, A, R extends Collection> R collect(
            List<T> list,
            Function<? super T, ? extends A> function,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            targetCollection.add(function.valueOf(list.get(i)));
        }
        return targetCollection;
    }

    /**
     * @see Iterate#flatCollect(Iterable, Function)
     */
    public static <T, A> MutableList flatCollect(
            List<T> list,
            Function<? super T, ? extends Iterable> function)
    {
        return flatCollect(list, function, FastList.newList(list.size()));
    }

    /**
     * @see Iterate#flatCollect(Iterable, Function, Collection)
     */
    public static <T, A, R extends Collection> R flatCollect(
            List<T> list,
            Function<? super T, ? extends Iterable> function,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            Iterate.addAllTo(function.valueOf(list.get(i)), targetCollection);
        }
        return targetCollection;
    }

    /**
     * Returns the last element of a list.
     */
    public static <T> T getLast(List<T> collection)
    {
        return Iterate.isEmpty(collection) ? null : collection.get(collection.size() - 1);
    }

    /**
     * @see Iterate#forEach(Iterable, Procedure)
     */
    public static <T> void forEach(List<T> list, Procedure<? super T> procedure)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            procedure.value(list.get(i));
        }
    }

    /**
     * Iterates over the section of the list covered by the specified indexes.  The indexes are both inclusive.  If the
     * from is less than the to, the list is iterated in forward order. If the from is greater than the to, then the
     * list is iterated in the reverse order.
     *

     *

     *
e.g.
     * MutableList<People> people = FastList.newListWith(ted, mary, bob, sally);
     * ListIterate.forEach(people, 0, 1, new Procedure<Person>()
     * {
     *     public void value(Person person)
     *     {
     *          LOGGER.info(person.getName());
     *     }
     * });
     *

     *

     * This code would output ted and mary's names.
     */
    public static <T> void forEach(List<T> list, int from, int to, Procedure<? super T> procedure)
    {
        if (from < 0 || to < 0)
        {
            throw new IllegalArgumentException("Neither from nor to may be negative.");
        }
        if (from <= to)
        {
            for (int i = from; i <= to; i++)
            {
                procedure.value(list.get(i));
            }
        }
        else
        {
            for (int i = from; i >= to; i--)
            {
                procedure.value(list.get(i));
            }
        }
    }

    /**
     * Iterates over the section of the list covered by the specified indexes.  The indexes are both inclusive.  If the
     * from is less than the to, the list is iterated in forward order. If the from is greater than the to, then the
     * list is iterated in the reverse order. The index passed into the ObjectIntProcedure is the actual index of the
     * range.
     *

     *

     *
e.g.
     * MutableList<People> people = FastList.newListWith(ted, mary, bob, sally);
     * ListIterate.forEachWithIndex(people, 0, 1, new ObjectIntProcedure<Person>()
     * {
     *     public void value(Person person, int index)
     *     {
     *          LOGGER.info(person.getName() + " at index: " + index);
     *     }
     * });
     *

     *

     * This code would output ted and mary's names.
     */
    public static <T> void forEachWithIndex(List<T> list, int from, int to, ObjectIntProcedure<? super T> objectIntProcedure)
    {
        if (from < 0 || to < 0)
        {
            throw new IllegalArgumentException("Neither from nor to may be negative.");
        }
        if (from <= to)
        {
            for (int i = from; i <= to; i++)
            {
                objectIntProcedure.value(list.get(i), i);
            }
        }
        else
        {
            for (int i = from; i >= to; i--)
            {
                objectIntProcedure.value(list.get(i), i);
            }
        }
    }

    /**
     * For each element in both of the Lists, operation is evaluated with both elements as parameters.
     */
    public static <T1, T2> void forEachInBoth(List<T1> list1, List<T2> list2, Procedure2<? super T1, ? super T2> procedure)
    {
        if (list1 != null && list2 != null)
        {
            if (list1.size() == list2.size())
            {
                for (int i = 0, size = list1.size(); i < size; i++)
                {
                    procedure.value(list1.get(i), list2.get(i));
                }
            }
            else
            {
                throw new IllegalArgumentException("Attempt to call forEachInBoth with two Lists of different sizes :"
                        + list1.size()
                        + ':'
                        + list2.size());
            }
        }
    }

    /**
     * Iterates over a collection passing each element and the current relative int index to the specified instance of
     * ObjectIntProcedure.
     */
    public static <T> void forEachWithIndex(List<T> list, ObjectIntProcedure<? super T> objectIntProcedure)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            objectIntProcedure.value(list.get(i), i);
        }
    }

    public static <T> T detect(List<T> list, Predicate<? super T> predicate)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (predicate.accept(item))
            {
                return item;
            }
        }
        return null;
    }

    public static <T, IV> T detectWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            if (predicate.accept(item, injectedValue))
            {
                return item;
            }
        }
        return null;
    }

    public static <T, IV> IV injectInto(IV injectValue, List<T> list, Function2<? super IV, ? super T, ? extends IV> function)
    {
        IV result = injectValue;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            result = function.value(result, list.get(i));
        }
        return result;
    }

    public static <T> int injectInto(int injectValue, List<T> list, IntObjectToIntFunction<? super T> function)
    {
        int result = injectValue;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            result = function.intValueOf(result, list.get(i));
        }
        return result;
    }

    public static <T> long injectInto(long injectValue, List<T> list, LongObjectToLongFunction<? super T> function)
    {
        long result = injectValue;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            result = function.longValueOf(result, list.get(i));
        }
        return result;
    }

    public static <T> double injectInto(double injectValue, List<T> list, DoubleObjectToDoubleFunction<? super T> function)
    {
        double result = injectValue;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            result = function.doubleValueOf(result, list.get(i));
        }
        return result;
    }

    public static <T> boolean anySatisfy(List<T> list, Predicate<? super T> predicate)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i)))
            {
                return true;
            }
        }
        return false;
    }

    public static <T, IV> boolean anySatisfyWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i), injectedValue))
            {
                return true;
            }
        }
        return false;
    }

    public static <T> boolean allSatisfy(List<T> list, Predicate<? super T> predicate)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (!predicate.accept(list.get(i)))
            {
                return false;
            }
        }
        return true;
    }

    public static <T, IV> boolean allSatisfyWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (!predicate.accept(list.get(i), injectedValue))
            {
                return false;
            }
        }
        return true;
    }

    public static <T, IV> Twin<MutableList<T>> selectAndRejectWith(
            List<T> list,
            Predicate2<? super T, ? super IV> predicate,
            IV injectedValue)
    {
        MutableList<T> positiveResult = Lists.mutable.of();
        MutableList<T> negativeResult = Lists.mutable.of();
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            (predicate.accept(item, injectedValue) ? positiveResult : negativeResult).add(item);
        }
        return Tuples.twin(positiveResult, negativeResult);
    }

    public static <T> PartitionMutableList<T> partition(
            List<T> list,
            Predicate<? super T> predicate)
    {
        PartitionFastList<T> partitionFastList = new PartitionFastList<T>(predicate);

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

        return partitionFastList;
    }

    public static <T> List<T> removeIf(List<T> list, Predicate<? super T> predicate)
    {
        for (int i = 0; i < list.size(); i++)
        {
            T each = list.get(i);
            if (predicate.accept(each))
            {
                list.remove(i--);
            }
        }
        return list;
    }

    public static <T, P> List<T> removeIfWith(List<T> list, Predicate2<? super T, ? super P> predicate, P parameter)
    {
        for (int i = 0; i < list.size(); i++)
        {
            T each = list.get(i);
            if (predicate.accept(each, parameter))
            {
                list.remove(i--);
            }
        }
        return list;
    }

    public static <T> List<T> removeIf(List<T> list, Predicate<? super T> predicate, Procedure<? super T> procedure)
    {
        for (int i = 0; i < list.size(); i++)
        {
            T each = list.get(i);
            if (predicate.accept(each))
            {
                procedure.value(each);
                list.remove(i--);
            }
        }
        return list;
    }

    /**
     * Searches for the first occurence where the predicate evaluates to true.
     */
    public static <T> int detectIndex(List<T> list, Predicate<? super T> predicate)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i)))
            {
                return i;
            }
        }
        return -1;
    }

    /**
     * Searches for the first occurence where the predicate evaluates to true.
     */
    public static <T, IV> int detectIndexWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            if (predicate.accept(list.get(i), injectedValue))
            {
                return i;
            }
        }
        return -1;
    }

    public static <T, IV, P> IV injectIntoWith(
            IV injectedValue,
            List<T> list,
            Function3<? super IV, ? super T, ? super P, ? extends IV> function,
            P parameter)
    {
        IV result = injectedValue;
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            result = function.value(result, list.get(i), parameter);
        }
        return result;
    }

    public static <T, P> void forEachWith(List<T> list, Procedure2<? super T, ? super P> procedure, P parameter)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            procedure.value(list.get(i), parameter);
        }
    }

    public static <T, P, A, R extends Collection> R collectWith(
            List<T> list,
            Function2<? super T, ? super P, ? extends A> function,
            P parameter,
            R targetCollection)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            targetCollection.add(function.value(list.get(i), parameter));
        }
        return targetCollection;
    }

    /**
     * @see Iterate#take(Iterable, int)
     */
    public static <T> MutableList<T> take(List<T> list, int count)
    {
        if (count < 0)
        {
            throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
        }
        return RandomAccessListIterate.take(list, count, FastList.<T>newList(Math.min(list.size(), count)));
    }

    /**
     * @see Iterate#take(Iterable, int)
     */
    public static <T, R extends Collection<T>> R take(List<T> list, int count, R targetList)
    {
        if (count < 0)
        {
            throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
        }
        int end = Math.min(list.size(), count);
        for (int i = 0; i < end; i++)
        {
            targetList.add(list.get(i));
        }
        return targetList;
    }

    /**
     * @see Iterate#drop(Iterable, int)
     */
    public static <T> MutableList<T> drop(List<T> list, int count)
    {
        return RandomAccessListIterate.drop(list, count, FastList.<T>newList(list.size() - Math.min(list.size(), count)));
    }

    /**
     * @see Iterate#drop(Iterable, int)
     */
    public static <T, R extends Collection<T>> R drop(List<T> list, int count, R targetList)
    {
        if (count < 0)
        {
            throw new IllegalArgumentException("Count must be greater than zero, but was: " + count);
        }
        int start = Math.min(list.size(), count);
        targetList.addAll(list.subList(start, list.size()));
        return targetList;
    }

    /**
     * @see RichIterable#appendString(Appendable, String, String, String)
     */
    public static <T> void appendString(
            List<T> list,
            Appendable appendable,
            String start,
            String separator,
            String end)
    {
        try
        {
            appendable.append(start);

            if (Iterate.notEmpty(list))
            {
                appendable.append(IterableIterate.stringValueOfItem(list, list.get(0)));

                for (int i = 1, size = list.size(); i < size; i++)
                {
                    appendable.append(separator);
                    appendable.append(IterableIterate.stringValueOfItem(list, list.get(i)));
                }
            }

            appendable.append(end);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see Iterate#groupBy(Iterable, Function)
     */
    public static <T, V> FastListMultimap<V, T> groupBy(
            List<T> list,
            Function<? super T, ? extends V> function)
    {
        return RandomAccessListIterate.groupBy(list, function, FastListMultimap.<V, T>newMultimap());
    }

    /**
     * @see Iterate#groupBy(Iterable, Function, MutableMultimap)
     */
    public static <T, V, R extends MutableMultimap<V, T>> R groupBy(
            List<T> list,
            Function<? super T, ? extends V> function,
            R target)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            target.put(function.valueOf(item), item);
        }
        return target;
    }

    public static <T, V> FastListMultimap<V, T> groupByEach(
            List<T> list,
            Function<? super T, ? extends Iterable<V>> function)
    {
        return RandomAccessListIterate.groupByEach(list, function, FastListMultimap.<V, T>newMultimap());
    }

    public static <T, V, R extends MutableMultimap<V, T>> R groupByEach(
            List<T> list,
            Function<? super T, ? extends Iterable<V>> function,
            R target)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            T item = list.get(i);
            Iterable<V> iterable = function.valueOf(item);
            for (V key : iterable)
            {
                target.put(key, item);
            }
        }
        return target;
    }

    public static <T> T min(List<T> list, Comparator<? super T> comparator)
    {
        if (list.isEmpty())
        {
            throw new NoSuchElementException();
        }

        T candidate = list.get(0);
        for (int i = 1, size = list.size(); i < size; i++)
        {
            T next = list.get(i);
            if (comparator.compare(next, candidate) < 0)
            {
                candidate = next;
            }
        }
        return candidate;
    }

    public static <T> T max(List<T> list, Comparator<? super T> comparator)
    {
        if (list.isEmpty())
        {
            throw new NoSuchElementException();
        }

        T candidate = list.get(0);
        for (int i = 1, size = list.size(); i < size; i++)
        {
            T next = list.get(i);
            if (comparator.compare(next, candidate) > 0)
            {
                candidate = next;
            }
        }
        return candidate;
    }

    public static <T> T min(List<T> list)
    {
        if (list.isEmpty())
        {
            throw new NoSuchElementException();
        }

        T candidate = list.get(0);
        for (int i = 1, size = list.size(); i < size; i++)
        {
            T next = list.get(i);
            if (((Comparable<? super T>) next).compareTo(candidate) < 0)
            {
                candidate = next;
            }
        }
        return candidate;
    }

    public static <T> T max(List<T> list)
    {
        if (list.isEmpty())
        {
            throw new NoSuchElementException();
        }

        T candidate = list.get(0);
        for (int i = 1, size = list.size(); i < size; i++)
        {
            T next = list.get(i);
            if (((Comparable<T>) next).compareTo(candidate) > 0)
            {
                candidate = next;
            }
        }
        return candidate;
    }

    public static <X, Y> MutableList<Pair<X, Y>> zip(
            List<X> list,
            Iterable<Y> iterable)
    {
        return RandomAccessListIterate.zip(list, iterable, FastList.<Pair<X, Y>>newList());
    }

    public static <X, Y, R extends Collection<Pair<X, Y>>> R zip(
            List<X> list,
            Iterable<Y> iterable,
            R target)
    {
        Iterator<Y> yIterator = iterable.iterator();
        for (int i = 0, size = list.size(); i < size && yIterator.hasNext(); i++)
        {
            target.add(Tuples.pair(list.get(i), yIterator.next()));
        }
        return target;
    }

    public static <T> MutableList<Pair<T, Integer>> zipWithIndex(List<T> list)
    {
        return RandomAccessListIterate.zipWithIndex(list, FastList.<Pair<T, Integer>>newList());
    }

    public static <T, R extends Collection<Pair<T, Integer>>> R zipWithIndex(
            List<T> list,
            R target)
    {
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
            target.add(Tuples.pair(list.get(i), i));
        }
        return target;
    }
}


text:
#region License
//Copyright(c) Paul Biccherai
//Licensed under the MIT license. See LICENSE file in the project root for full license information.
#endregion

using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Moq;
using PaulMiami.AspNetCore.Authentication.Authenticator;
using System;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace PaulMiami.AspNetCore.Identity.Authenticator.Test
{
    public class AuthenticatorUserManagerTest
    {
        internal static AuthenticatorUserManager<TUser> GetAuthenticatorUserManager<TUser>(
            out Mock<IUserAuthenticatorStore<TUser>> userStore,
            out Mock<IDataProtectionProvider> dataProtectionProvider,
            out Mock<IAuthenticatorService> authenticatorService,
            MockBehavior mockBehavior = MockBehavior.Default,
            Action<Mock<IUserAuthenticatorStore<TUser>>, Mock<IDataProtectionProvider>, Mock<IAuthenticatorService>> setup = null) where TUser: class
        {
            userStore = new Mock<IUserAuthenticatorStore<TUser>>(mockBehavior);
            dataProtectionProvider = new Mock<IDataProtectionProvider>(mockBehavior);
            authenticatorService = new Mock<IAuthenticatorService>(mockBehavior);

            setup?.Invoke(userStore, dataProtectionProvider, authenticatorService);

            var authenticatorUserManager = new AuthenticatorUserManager<TUser>(
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dataProtectionProvider.Object,
                authenticatorService.Object
                );

            return authenticatorUserManager;
        }

        internal static AuthenticatorUserManager<TUser> GetAuthenticatorUserManager<TUser>(
            out Mock<IUserAuthenticatorStore<TUser>> userStore,
            out Mock<IDataProtector> dataProtector,
            out Mock<IAuthenticatorService> authenticatorService,
            MockBehavior mockBehavior = MockBehavior.Default) where TUser : class
        {
            userStore = new Mock<IUserAuthenticatorStore<TUser>>(mockBehavior);
            var dataProtectionProvider = new Mock<IDataProtectionProvider>(mockBehavior);
            dataProtector = new Mock<IDataProtector>(mockBehavior);
            authenticatorService = new Mock<IAuthenticatorService>(mockBehavior);

            dataProtectionProvider
                .Setup(s => s.CreateProtector("AuthenticatorUserManager"))
                .Returns(dataProtector.Object)
                .Verifiable();

            var authenticatorUserManager = new AuthenticatorUserManager<TUser>(
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dataProtectionProvider.Object,
                authenticatorService.Object
                );

            return authenticatorUserManager;
        }

        internal static Mock<AuthenticatorUserManager<TUser>> GetAuthenticatorUserManagerMock<TUser>(
            out Mock<IUserAuthenticatorStore<TUser>> userStore,
            out Mock<IDataProtector> dataProtector,
            out Mock<IAuthenticatorService> authenticatorService,
            MockBehavior mockBehavior = MockBehavior.Default) where TUser : class
        {
            userStore = new Mock<IUserAuthenticatorStore<TUser>>(mockBehavior);
            var dataProtectionProvider = new Mock<IDataProtectionProvider>(mockBehavior);
            dataProtector = new Mock<IDataProtector>(mockBehavior);
            authenticatorService = new Mock<IAuthenticatorService>(mockBehavior);

            dataProtectionProvider
                .Setup(s => s.CreateProtector("AuthenticatorUserManager"))
                .Returns(dataProtector.Object)
                .Verifiable();

            var authenticatorUserManager = new Mock<AuthenticatorUserManager<TUser>>(
                MockBehavior.Default,
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dataProtectionProvider.Object,
                authenticatorService.Object
                );

            return authenticatorUserManager;
        }

        [Fact]
        public void SuccessConstructor()
        {
            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtectionProvider> dataProtectionProvider;
            Mock<IAuthenticatorService> authenticatorService;
            var dataProtector = new Mock<IDataProtector>(MockBehavior.Strict);

            var authenticatorUserManager = GetAuthenticatorUserManager(
                out userStore,
                out dataProtectionProvider,
                out authenticatorService,
                MockBehavior.Strict,
                (u, d, a)=>
                {
                    d
                    .Setup(s => s.CreateProtector("AuthenticatorUserManager"))
                    .Returns(dataProtector.Object)
                    .Verifiable();
                });

            dataProtector.Verify();
            dataProtectionProvider.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public void NullAuthenticatorServiceConstructor()
        {
            var userStore = new Mock<IUserStore<string>>(MockBehavior.Strict);
            var dataProtectionProvider = new Mock<IDataProtectionProvider>(MockBehavior.Strict);

            Assert.Throws<ArgumentNullException>(() =>
                new AuthenticatorUserManager<string>(
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dataProtectionProvider.Object,
                null
                ));

            userStore.Verify();
            dataProtectionProvider.Verify();
        }

        [Fact]
        public void NullDataProtectionProviderConstructor()
        {
            var userStore = new Mock<IUserStore<string>>(MockBehavior.Strict);
            var authenticatorService = new Mock<IAuthenticatorService>(MockBehavior.Strict);

            Assert.Throws<ArgumentNullException>(() =>
                new AuthenticatorUserManager<string>(
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                authenticatorService.Object
                ));

            userStore.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task MethodsThrowWhenDisposedTest()
        {
            var userStore = new Mock<IUserStore<string>>();
            var dataProtectionProvider = new Mock<IDataProtectionProvider>();
            var authenticatorService = new Mock<IAuthenticatorService>();
            var dataProtector = new Mock<IDataProtector>();

            dataProtectionProvider
                .Setup(s => s.CreateProtector("AuthenticatorUserManager"))
                .Returns(dataProtector.Object)
                .Verifiable();

            var authenticatorUserManager = new AuthenticatorUserManager<string>(
                userStore.Object,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                dataProtectionProvider.Object,
                authenticatorService.Object
                );

            Action<Exception> validateMessage = (x) => Assert.Equal("Store does not implement IUserAuthenticatorStore<TUser>.", x.Message);

            var ex = await Assert.ThrowsAsync<NotSupportedException>(() => authenticatorUserManager.GetAuthenticatorEnabledAsync(null));
            validateMessage(ex);
            ex = await Assert.ThrowsAsync<NotSupportedException>(() => authenticatorUserManager.GetAuthenticatorParamsAsync(null));
            validateMessage(ex);
            ex = await Assert.ThrowsAsync<NotSupportedException>(() => authenticatorUserManager.EnableAuthenticatorAsync(null, new Authenticator(), string.Empty));
            validateMessage(ex);
            ex = await Assert.ThrowsAsync<NotSupportedException>(() => authenticatorUserManager.DisableAuthenticatorAsync(null, string.Empty));
            validateMessage(ex);
            ex = await Assert.ThrowsAsync<NotSupportedException>(() => authenticatorUserManager.CreateAuthenticatorAsync(null));
            validateMessage(ex);
        }

        [Fact]
        public async Task UserAuthenticatorStoreNotImplemented()
        {
            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtectionProvider> dataProtectionProvider;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtectionProvider, out authenticatorService);

            authenticatorUserManager.Dispose();
            await Assert.ThrowsAsync<ObjectDisposedException>(() => authenticatorUserManager.GetAuthenticatorEnabledAsync(null));
            await Assert.ThrowsAsync<ObjectDisposedException>(() => authenticatorUserManager.GetAuthenticatorParamsAsync(null));
            await Assert.ThrowsAsync<ObjectDisposedException>(() => authenticatorUserManager.EnableAuthenticatorAsync(null, null, null));
            await Assert.ThrowsAsync<ObjectDisposedException>(() => authenticatorUserManager.DisableAuthenticatorAsync(null, null));
            await Assert.ThrowsAsync<ObjectDisposedException>(() => authenticatorUserManager.CreateAuthenticatorAsync(null));
        }

        [Fact]
        public async Task SuccessEnableGetAuthenticatorEnabledAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticatorParams = new AuthenticatorParams
            {
                Secret = new byte[0]
            };

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            userStore.Setup(a => a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParams))
                .Verifiable();

            Assert.True(await authenticatorUserManager.GetAuthenticatorEnabledAsync(user, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task SuccessDisableGetAuthenticatorEnabledAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticatorParams = new AuthenticatorParams
            {
                Secret = null
            };

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            userStore.Setup(a => a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParams))
                .Verifiable();

            Assert.False(await authenticatorUserManager.GetAuthenticatorEnabledAsync(user, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task NullUserGetAuthenticatorEnabledAsync()
        {
            var cancellationToken = new System.Threading.CancellationToken();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            await Assert.ThrowsAnyAsync<ArgumentNullException>(()=> authenticatorUserManager.GetAuthenticatorEnabledAsync(null, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task SuccessGetAuthenticatorParamsAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticatorParamsActual = new AuthenticatorParams
            {
                Secret = Encoding.UTF8.GetBytes("ENCRYPTED")
            };

            var unprotectedData = Encoding.UTF8.GetBytes("CLEARTEXT");

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            userStore.Setup(a => a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParamsActual))
                .Verifiable();

            dataProtector.Setup(a => a.Unprotect(authenticatorParamsActual.Secret))
                .Returns(unprotectedData)
                .Verifiable();

            var authenticatorParams = await authenticatorUserManager.GetAuthenticatorParamsAsync(user, cancellationToken);

            Assert.Equal(authenticatorParams, authenticatorParamsActual);
            Assert.Equal(unprotectedData, authenticatorParamsActual.Secret);

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task NullUserGetAuthenticatorParamsAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticatorParamsActual = new AuthenticatorParams
            {
                Secret = Encoding.UTF8.GetBytes("ENCRYPTED")
            };

            var unprotectedData = Encoding.UTF8.GetBytes("CLEARTEXT");

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            await Assert.ThrowsAsync<ArgumentNullException>(()=> authenticatorUserManager.GetAuthenticatorParamsAsync(null, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Theory]
        [InlineData(HashAlgorithmType.SHA1, 30, 6)]
        [InlineData(HashAlgorithmType.SHA256, 45, 7)]
        [InlineData(HashAlgorithmType.SHA512, 60, 8)]
        public async Task SuccessEnableAuthenticatorAsync(HashAlgorithmType HashAlgorithm, byte periodInSeconds, byte numberOfDigits)
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var code = ran.Next(999999);
            var codeInput = code.ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticator = new Authenticator
            {
                Secret = Encoding.UTF8.GetBytes("CLEARTEXT"),
                HashAlgorithm = HashAlgorithm,
                PeriodInSeconds = periodInSeconds,
                NumberOfDigits = numberOfDigits
            };
            var authenticatorParams = new AuthenticatorParams();
            var protectedData = Encoding.UTF8.GetBytes("ENCRYPTED");

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(false))
                .Verifiable();

            authenticatorService
                .Setup(a => a.GetCode(authenticator.HashAlgorithm, authenticator.Secret, authenticator.NumberOfDigits, authenticator.PeriodInSeconds))
                .Returns(code)
                .Verifiable();

            dataProtector
                .Setup(a => a.Protect(authenticator.Secret))
                .Returns(protectedData)
                .Verifiable();

            userStore
                .Setup(a => a.SetAuthenticatorParamsAsync(user, It.Is<AuthenticatorParams>((auth) =>
                    auth.HashAlgorithm == authenticator.HashAlgorithm &&
                    auth.NumberOfDigits == authenticator.NumberOfDigits &&
                    auth.PeriodInSeconds == authenticator.PeriodInSeconds &&
                    auth.Secret == protectedData
                ), cancellationToken))
                .Returns(Task.FromResult(0))
                .Verifiable();

            authenticatorUserManagerMock
                .Setup(a => a.UpdateAsync(user))
                .Returns(Task.FromResult(new IdentityResult()))
                .Verifiable();

            var result = await authenticatorUserManager.EnableAuthenticatorAsync(user, authenticator, codeInput, cancellationToken);

            Assert.True(result);

            authenticatorUserManagerMock.Verify();
            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task FailWrongCodeEnableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var code = ran.Next(999999);
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticator = new Authenticator();
            var authenticatorParams = new AuthenticatorParams();
            var protectedData = Encoding.UTF8.GetBytes("ENCRYPTED");

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(false))
                .Verifiable();

            authenticatorService
                .Setup(a => a.GetCode(authenticator.HashAlgorithm, authenticator.Secret, authenticator.NumberOfDigits, authenticator.PeriodInSeconds))
                .Returns(code)
                .Verifiable();

            var result = await authenticatorUserManager.EnableAuthenticatorAsync(user, authenticator, codeInput, cancellationToken);

            Assert.False(result);

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
            authenticatorUserManagerMock.Verify();
        }

        [Fact]
        public async Task FailAuthenticatorEnableCodeEnableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticator = new Authenticator();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(true))
                .Verifiable();

            var ex = await Assert.ThrowsAsync<InvalidOperationException>(()=>authenticatorUserManager.EnableAuthenticatorAsync(user, authenticator, codeInput, cancellationToken));
            Assert.Equal("This user already has an authenticator enabled.", ex.Message);

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
            authenticatorUserManagerMock.Verify();
        }

        [Fact]
        public async Task NullUserEnableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticator = new Authenticator();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

             await Assert.ThrowsAsync<ArgumentNullException>(()=>authenticatorUserManager.EnableAuthenticatorAsync(null, authenticator, codeInput, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task NullAuthenticatorEnableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            await Assert.ThrowsAsync<ArgumentNullException>(() => authenticatorUserManager.EnableAuthenticatorAsync(user, null, codeInput, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task SuccessDisableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var code = ran.Next(999999);
            var codeInput = code.ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var unprotectedData = Encoding.UTF8.GetBytes("CLEARTEXT");
            var authenticatorParams = new AuthenticatorParams
            {
                Secret = unprotectedData
            };

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a=>a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParams))
                .Verifiable();

            authenticatorService
                .Setup(a => a.GetCode(authenticatorParams.HashAlgorithm, unprotectedData, authenticatorParams.NumberOfDigits, authenticatorParams.PeriodInSeconds))
                .Returns(code)
                .Verifiable();

            userStore
                .Setup(a => a.SetAuthenticatorParamsAsync(user, It.Is<AuthenticatorParams>((auth) =>
                    auth.HashAlgorithm == HashAlgorithmType.SHA1 &&
                    auth.NumberOfDigits == 0 &&
                    auth.PeriodInSeconds == 0 &&
                    auth.Secret == null
                ), cancellationToken))
                .Returns(Task.FromResult(0))
                .Verifiable();

            authenticatorUserManagerMock
                .Setup(a => a.UpdateAsync(user))
                .Returns(Task.FromResult(new IdentityResult()))
                .Verifiable();

            var result = await authenticatorUserManager.DisableAuthenticatorAsync(user, codeInput, cancellationToken);

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
            authenticatorUserManagerMock.Verify();

            Assert.True(result);
        }

        [Fact]
        public async Task FailDisableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var user = Guid.NewGuid().ToString();
            var code = ran.Next(999999);
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var unprotectedData = Encoding.UTF8.GetBytes("CLEARTEXT");
            var authenticatorParams = new AuthenticatorParams
            {
                Secret = unprotectedData
            };

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParams))
                .Verifiable();

            authenticatorService
                .Setup(a => a.GetCode(authenticatorParams.HashAlgorithm, unprotectedData, authenticatorParams.NumberOfDigits, authenticatorParams.PeriodInSeconds))
                .Returns(code)
                .Verifiable();

            var result = await authenticatorUserManager.DisableAuthenticatorAsync(user, codeInput, cancellationToken);

            Assert.False(result);

            authenticatorUserManagerMock.Verify();
            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task NullUserDisableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var codeInput = ran.Next(999999).ToString();
            var cancellationToken = new System.Threading.CancellationToken();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            await Assert.ThrowsAsync<ArgumentNullException>(()=>authenticatorUserManager.DisableAuthenticatorAsync(null, codeInput, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task BadCodeDisableAuthenticatorAsync()
        {
            var ran = new Random(DateTime.Today.Millisecond);
            var codeInput = "Bad";
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var authenticatorParams = new AuthenticatorParams();
            var unprotectedData = Encoding.UTF8.GetBytes("CLEARTEXT");

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManager = GetAuthenticatorUserManager(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);

            userStore
                .Setup(a => a.GetAuthenticatorParamsAsync(user, cancellationToken))
                .Returns(Task.FromResult(authenticatorParams))
                .Verifiable();

            dataProtector
                .Setup(a => a.Unprotect(authenticatorParams.Secret))
                .Returns(unprotectedData)
                .Verifiable();

            Assert.False(await authenticatorUserManager.DisableAuthenticatorAsync(user, codeInput, cancellationToken));

            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Theory]
        [InlineData(HashAlgorithmType.SHA1, 30, 6, 20)]
        [InlineData(HashAlgorithmType.SHA256, 45, 7, 32)]
        [InlineData(HashAlgorithmType.SHA512, 60, 8, 64)]
        public async Task SuccessCreateAuthenticatorAsync(HashAlgorithmType hashAlgorithm, byte periodInSeconds, byte numberOfDigits, int secretLength)
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var email = Guid.NewGuid().ToString();
            var uri = Guid.NewGuid().ToString();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(false))
                .Verifiable();

            authenticatorUserManagerMock
                .Setup(a => a.GetEmailAsync(user))
                .Returns(Task.FromResult(email))
                .Verifiable();

            authenticatorService
                .Setup(a => a.HashAlgorithm)
                .Returns(hashAlgorithm)
                .Verifiable();

            authenticatorService
                .Setup(a => a.NumberOfDigits)
                .Returns(numberOfDigits)
                .Verifiable();

            authenticatorService
                .Setup(a => a.PeriodInSeconds)
                .Returns(periodInSeconds)
                .Verifiable();

            authenticatorService
                .Setup(a => a.GetUri(email, It.Is<byte[]>(b=>b.Length == secretLength)))
                .Returns(uri)
                .Verifiable();

            var result = await authenticatorUserManager.CreateAuthenticatorAsync(user, cancellationToken);

            authenticatorUserManagerMock.Verify();
            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();

            Assert.Equal(hashAlgorithm, result.HashAlgorithm);
            Assert.Equal(numberOfDigits, result.NumberOfDigits);
            Assert.Equal(periodInSeconds, result.PeriodInSeconds);
            Assert.Equal(uri, result.Uri);
            Assert.Equal(secretLength, result.Secret.Length);
        }

        [Fact]
        public async Task InvalidHasAlgorithmCreateAuthenticatorAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var email = Guid.NewGuid().ToString();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(false))
                .Verifiable();

            authenticatorUserManagerMock
                .Setup(a => a.GetEmailAsync(user))
                .Returns(Task.FromResult(email))
                .Verifiable();

            authenticatorService
                .Setup(a => a.HashAlgorithm)
                .Returns((HashAlgorithmType)100)
                .Verifiable();

            await Assert.ThrowsAsync<ArgumentException>(() => authenticatorUserManager.CreateAuthenticatorAsync(user, cancellationToken));

            authenticatorUserManagerMock.Verify();
            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }

        [Fact]
        public async Task FailAuthenticatorEnableCreateAuthenticatorAsync()
        {
            var user = Guid.NewGuid().ToString();
            var cancellationToken = new System.Threading.CancellationToken();
            var email = Guid.NewGuid().ToString();

            Mock<IUserAuthenticatorStore<string>> userStore;
            Mock<IDataProtector> dataProtector;
            Mock<IAuthenticatorService> authenticatorService;

            var authenticatorUserManagerMock = GetAuthenticatorUserManagerMock(out userStore, out dataProtector, out authenticatorService, MockBehavior.Strict);
            authenticatorUserManagerMock.CallBase = true;
            var authenticatorUserManager = authenticatorUserManagerMock.Object;

            authenticatorUserManagerMock
                .Setup(a => a.GetAuthenticatorEnabledAsync(user, cancellationToken))
                .Returns(Task.FromResult(true))
                .Verifiable();

            var ex = await Assert.ThrowsAsync<InvalidOperationException>(()=>authenticatorUserManager.CreateAuthenticatorAsync(user, cancellationToken));
            Assert.Equal("This user already has an authenticator enabled.", ex.Message);

            authenticatorUserManagerMock.Verify();
            userStore.Verify();
            dataProtector.Verify();
            authenticatorService.Verify();
        }
    }
}


text:
package v2

import (
	"sync"
	"time"

	"github.com/influxdata/telegraf"
	serializer "github.com/influxdata/telegraf/plugins/serializers/prometheus"
	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
)

type Metric struct {
	family *dto.MetricFamily
	metric *dto.Metric
}

func (m *Metric) Desc() *prometheus.Desc {
	labelNames := make([]string, 0, len(m.metric.Label))
	for _, label := range m.metric.Label {
		labelNames = append(labelNames, *label.Name)
	}

	desc := prometheus.NewDesc(*m.family.Name, *m.family.Help, labelNames, nil)

	return desc
}

func (m *Metric) Write(out *dto.Metric) error {
	out.Label = m.metric.Label
	out.Counter = m.metric.Counter
	out.Untyped = m.metric.Untyped
	out.Gauge = m.metric.Gauge
	out.Histogram = m.metric.Histogram
	out.Summary = m.metric.Summary
	out.TimestampMs = m.metric.TimestampMs
	return nil
}

type Collector struct {
	sync.Mutex
	expireDuration time.Duration
	coll           *serializer.Collection
}

func NewCollector(expire time.Duration, stringsAsLabel bool, exportTimestamp bool) *Collector {
	config := serializer.FormatConfig{}
	if stringsAsLabel {
		config.StringHandling = serializer.StringAsLabel
	}

	if exportTimestamp {
		config.TimestampExport = serializer.ExportTimestamp
	}

	return &Collector{
		expireDuration: expire,
		coll:           serializer.NewCollection(config),
	}
}

func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
	// Sending no descriptor at all marks the Collector as "unchecked",
	// i.e. no checks will be performed at registration time, and the
	// Collector may yield any Metric it sees fit in its Collect method.
	return
}

func (c *Collector) Collect(ch chan<- prometheus.Metric) {
	c.Lock()
	defer c.Unlock()

	// Expire metrics, doing this on Collect ensure metrics are removed even if no
	// new metrics are added to the output.
	if c.expireDuration != 0 {
		c.coll.Expire(time.Now(), c.expireDuration)
	}

	for _, family := range c.coll.GetProto() {
		for _, metric := range family.Metric {
			ch <- &Metric{family: family, metric: metric}
		}
	}
}

func (c *Collector) Add(metrics []telegraf.Metric) error {
	c.Lock()
	defer c.Unlock()

	for _, metric := range metrics {
		c.coll.Add(metric, time.Now())
	}

	// Expire metrics, doing this on Add ensure metrics are removed even if no
	// one is querying the data.
	if c.expireDuration != 0 {
		c.coll.Expire(time.Now(), c.expireDuration)
	}

	return nil
}


text:
import {Routes,RouterModule} from '@angular/router';

import { ActiveVehComponent } from "app/pages/active-veh/active-veh.component";
import { ModuleWithProviders } from '@angular/core'

export const routes: Routes = [
    {
        path:'',
        component:ActiveVehComponent
    }
];
export const routing:ModuleWithProviders = RouterModule.forChild(routes)


text:
bioscholar
==========

The BioScholar web application, first described in Russ et al. 2011 (http://www.biomedcentral.com/1471-2105/12/351), but further developed here.


text:
//************************* RUBEN ***********************************

package es.tid.ospf.ospfv2.lsa.tlv.subtlv;

import es.tid.bgp.bgp4.update.tlv.BGP4TLVFormat;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.LinkStateAttributeTLVTypes;

public class MF_OTPAttribSubTLV extends OSPFSubTLV{

	private int MatrixID;			//8
	private int RstType;			//8
	private int Swcap;				//8
	private int Encoding;			//8
	private int TxSubTrnsp;			//8
	private int RxSubTrnsp;			//8
	private int AvailTxSTrnsp;		//8
	private int AvailRxTrnsp;		//8
	private int CFG;				//8
	private int SWG;				//8
	private int Reserved;			//16
	private int MinWidth;			//16
	private int MaxWidth;			//16

	private LabelTypeTLV txAggregatedOpticalSpec;

	private LabelTypeTLV rxAggregatedOpticalSpec;

	public MF_OTPAttribSubTLV(){
		super();
		this.setTLVType(26);
	}

	public MF_OTPAttribSubTLV(byte[] bytes, int offset){
		super(bytes,offset);
		decode();
	}

	@Override
	public void encode() {

		int valueLength = 16;

		log.info("******************* Codificando MF OTP *****************");

		if (txAggregatedOpticalSpec != null){

			txAggregatedOpticalSpec.encode();
			valueLength += txAggregatedOpticalSpec.getTotalTLVLength();
		}

		if (rxAggregatedOpticalSpec != null){

			rxAggregatedOpticalSpec.encode();
			valueLength += rxAggregatedOpticalSpec.getTotalTLVLength();
		}

		this.setTLVValueLength(valueLength);

		this.tlv_bytes = new byte[this.getTotalTLVLength()];

		this.encodeHeader();
		int offset = 4;
		tlv_bytes[offset]=(byte)((MatrixID) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((RstType) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((Swcap) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((Encoding) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((TxSubTrnsp) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((RxSubTrnsp) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((AvailTxSTrnsp) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((AvailRxTrnsp) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((CFG) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((SWG) & 0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((Reserved>>8)&0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)(Reserved&0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((MinWidth>>8)&0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)(MinWidth&0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)((MaxWidth>>8)&0xFF);

		offset = offset + 1;

		tlv_bytes[offset]=(byte)(MaxWidth&0xFF);

		offset = offset + 1;

		if (txAggregatedOpticalSpec != null){

			System.arraycopy(this.txAggregatedOpticalSpec.getTlv_bytes(),0 , this.tlv_bytes,offset,txAggregatedOpticalSpec.getTotalTLVLength() );
		}
		offset= offset+txAggregatedOpticalSpec.getTotalTLVLength() ;
		if (rxAggregatedOpticalSpec != null){

			System.arraycopy(this.rxAggregatedOpticalSpec.getTlv_bytes(),0 , this.tlv_bytes,offset,rxAggregatedOpticalSpec.getTotalTLVLength() );
		}

		log.info("***************** FIN Codificando MF OTP ***************");

	}

	protected void decode(){

		int offset = 4;

		log.info("******************* Decodificando MF OTP *****************");

	   	MatrixID = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de MatrixID del MF_OTP: "+MatrixID+".");

		offset = offset + 1;

		RstType = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de RstType del MF_OTP: "+RstType+".");

		offset = offset + 1;

		Swcap = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de Swcap del MF_OTP: "+Swcap+".");

		offset = offset + 1;

		Encoding = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de Encoding del MF_OTP: "+Encoding+".");

		offset = offset + 1;

		TxSubTrnsp = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de TxSubTrnsp del MF_OTP: "+TxSubTrnsp+".");

		offset = offset + 1;

		RxSubTrnsp = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de RxSubTrnsp del MF_OTP: "+RxSubTrnsp+".");

		offset = offset + 1;

		AvailTxSTrnsp = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de AvailTxSTrnsp del MF_OTP: "+AvailTxSTrnsp+".");

		offset = offset + 1;

		AvailRxTrnsp = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de AvailRxTrnsp del MF_OTP: "+AvailRxTrnsp+".");

		offset = offset + 1;

		CFG = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de CFG del MF_OTP: "+CFG+".");

		offset = offset + 1;

		SWG = (((int)tlv_bytes[offset]&(int)0xFF));
		log.info("Valor de SWG del MF_OTP: "+SWG+".");

		offset = offset + 1;

		Reserved = (((int)tlv_bytes[offset]&(int)0xFF)<<8) | ((int)tlv_bytes[offset+1]&(int)0xFF);
		log.info("Valor de Reserved del MF_OTP: "+Reserved+".");

		offset = offset +1 + 1;

		MinWidth = (((int)tlv_bytes[offset]&(int)0xFF)<<8) | ((int)tlv_bytes[offset+1]&(int)0xFF);
		log.info("Valor de MinWidth del MF_OTP: "+MinWidth+".");

		offset = offset + 1 + 1;

		MaxWidth = (((int)tlv_bytes[offset]&(int)0xFF)<<8) | ((int)tlv_bytes[offset+1]&(int)0xFF);
		log.info("Valor de MaxWidth del MF_OTP: "+MaxWidth+".");

		offset = offset + 1 + 1;

		log.info("Lenght: "+this.getTotalTLVLength());
		log.info("offset: "+offset);

		txAggregatedOpticalSpec = new LabelTypeTLV(tlv_bytes,offset);

		offset += txAggregatedOpticalSpec.getTotalTLVLength();

		rxAggregatedOpticalSpec = new LabelTypeTLV(tlv_bytes,offset);

		log.info("***************** FIN Decodificando MF OTP ***************");
	}

	public LabelTypeTLV getTxAggregatedOpticalSpec() {
		return txAggregatedOpticalSpec;
	}

	public void setTxAggregatedOpticalSpec(LabelTypeTLV txAggregatedOpticalSpec) {
		this.txAggregatedOpticalSpec = txAggregatedOpticalSpec;
	}

	public LabelTypeTLV getRxAggregatedOpticalSpec() {
		return rxAggregatedOpticalSpec;
	}

	public void setRxAggregatedOpticalSpec(LabelTypeTLV rxAggregatedOpticalSpec) {
		this.rxAggregatedOpticalSpec = rxAggregatedOpticalSpec;
	}

	public String toString(){
		String str =  "<MFOTP" + "\n MatrixID: " + MatrixID +
								  "| RstType:  " + RstType +
								  "| Swcap: " + Swcap +
								  "\n Encoding:   " + Encoding +
								  "| TxST:    " + TxSubTrnsp +
								  "| RxST:  " + RxSubTrnsp +
								  "\n AvTxST:    " + AvailTxSTrnsp +
								  "| AvRxST:  " + AvailRxTrnsp +
								  "| CFG:   " + CFG +
								  "\n SWG:        " + SWG +
								  "| Reserved: " + Reserved +
								  "| MinW:  " + MinWidth +
								  "\n MaxW:       " + MaxWidth +"|" +
								  "\n -------------------"+
								  "\n TxAggOptSpec: " + txAggregatedOpticalSpec.toString() +
								    "\n -------------------"+
								  "\n RxAggOptSpec: " + rxAggregatedOpticalSpec.toString();
		str+="\n>";
		return str;
	}

	public int getMatrixID() {
		return MatrixID;
	}

	public void setMatrixID(int matrixID) {
		MatrixID = matrixID;
	}

	public int getRstType() {
		return RstType;
	}

	public void setRstType(int rstType) {
		RstType = rstType;
	}

	public int getSwcap() {
		return Swcap;
	}

	public void setSwcap(int swcap) {
		Swcap = swcap;
	}

	public int getEncoding() {
		return Encoding;
	}

	public void setEncoding(int encoding) {
		Encoding = encoding;
	}

	public int getTxSubTrnsp() {
		return TxSubTrnsp;
	}

	public void setTxSubTrnsp(int txSubTrnsp) {
		TxSubTrnsp = txSubTrnsp;
	}

	public int getRxSubTrnsp() {
		return RxSubTrnsp;
	}

	public void setRxSubTrnsp(int rxSubTrnsp) {
		RxSubTrnsp = rxSubTrnsp;
	}

	public int getAvailTxSTrnsp() {
		return AvailTxSTrnsp;
	}

	public void setAvailTxSTrnsp(int availTxSTrnsp) {
		AvailTxSTrnsp = availTxSTrnsp;
	}

	public int getAvailRxTrnsp() {
		return AvailRxTrnsp;
	}

	public void setAvailRxTrnsp(int availRxTrnsp) {
		AvailRxTrnsp = availRxTrnsp;
	}

	public int getCFG() {
		return CFG;
	}

	public void setCFG(int cFG) {
		CFG = cFG;
	}

	public int getSWG() {
		return SWG;
	}

	public void setSWG(int sWG) {
		SWG = sWG;
	}

	public int getReserved() {
		return Reserved;
	}

	public void setReserved(int reserved) {
		Reserved = reserved;
	}

	public int getMinWidth() {
		return MinWidth;
	}

	public void setMinWidth(int minWidth) {
		MinWidth = minWidth;
	}

	public int getMaxWidth() {
		return MaxWidth;
	}

	public void setMaxWidth(int maxWidth) {
		MaxWidth = maxWidth;
	}

	public MF_OTPAttribSubTLV duplicate(){
		MF_OTPAttribSubTLV mm=new MF_OTPAttribSubTLV();
		  mm.AvailRxTrnsp=this.AvailRxTrnsp;
		  mm.AvailTxSTrnsp=this.AvailTxSTrnsp;
		  mm.CFG=this.CFG;
		  mm.Encoding=this.Encoding;
		  mm.MatrixID=this.MatrixID;
		  mm.MaxWidth=this.MaxWidth;
		  mm.MinWidth=this.MinWidth;
		  mm.Reserved=this.Reserved;
		  mm.RstType=this.RstType;
		  mm.SWG=this.SWG;
		  mm.Swcap=this.Swcap;
		  mm.TxSubTrnsp=this.TxSubTrnsp;
		  mm.RxSubTrnsp=this.RxSubTrnsp;
		  mm.txAggregatedOpticalSpec = this.txAggregatedOpticalSpec.duplicate();
		  mm.rxAggregatedOpticalSpec = this.rxAggregatedOpticalSpec.duplicate();

		  return mm;

	}

}


text:
title: Reflect isExtensible
localeTitle: Reflect isExtensible
---
## Reflect isExtensible

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/reflect/reflect-isextensible/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Mais Informações:


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MGUI.Math;

namespace MGUI
{
	public class Button : Element
	{
		public Button( Element parentElement )
		{
			Handle = API.mgui_create_button( parentElement.Handle );
		}

		public Button( Element parentElement, VectorScreen absPos, VectorScreen absSize, ELEMFLAG flags, Colour col, string text )
		{
			Handle = API.mgui_create_button_ex( parentElement.Handle, absPos.x, absPos.y, (ushort)absSize.x, (ushort)absSize.y, (uint)flags, col.AsHex(), text );
		}
	}
}