text:
package org.apache.activemq.artemis.core.persistence.impl.nullpm;

import javax.transaction.xa.Xid;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.IOCriticalErrorListener;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.core.journal.Journal;
import org.apache.activemq.artemis.core.journal.JournalLoadInformation;
import org.apache.activemq.artemis.core.paging.PageTransactionInfo;
import org.apache.activemq.artemis.core.paging.PagedMessage;
import org.apache.activemq.artemis.core.paging.PagingManager;
import org.apache.activemq.artemis.core.paging.PagingStore;
import org.apache.activemq.artemis.core.paging.cursor.PagePosition;
import org.apache.activemq.artemis.core.persistence.AddressBindingInfo;
import org.apache.activemq.artemis.core.persistence.GroupingInfo;
import org.apache.activemq.artemis.core.persistence.OperationContext;
import org.apache.activemq.artemis.core.persistence.QueueBindingInfo;
import org.apache.activemq.artemis.core.persistence.QueueStatus;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.persistence.config.PersistedAddressSetting;
import org.apache.activemq.artemis.core.persistence.config.PersistedRoles;
import org.apache.activemq.artemis.core.persistence.impl.PageCountPending;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.PostOffice;
import org.apache.activemq.artemis.core.replication.ReplicationManager;
import org.apache.activemq.artemis.core.server.LargeServerMessage;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.RouteContextList;
import org.apache.activemq.artemis.core.server.files.FileStoreMonitor;
import org.apache.activemq.artemis.core.server.group.impl.GroupBinding;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.server.impl.JournalLoader;
import org.apache.activemq.artemis.core.transaction.ResourceManager;
import org.apache.activemq.artemis.core.transaction.Transaction;

public class NullStorageManager implements StorageManager {

   private final AtomicLong idSequence = new AtomicLong(0);

   private volatile boolean started;

   private final IOCriticalErrorListener ioCriticalErrorListener;

   public NullStorageManager(IOCriticalErrorListener ioCriticalErrorListener) {
      this.ioCriticalErrorListener = ioCriticalErrorListener;
   }

   public NullStorageManager() {
      this(new IOCriticalErrorListener() {
         @Override
         public void onIOException(Throwable code, String message, SequentialFile file) {
            code.printStackTrace();
         }
      });
   }

   @Override
   public void criticalError(Throwable error) {

   }

   @Override
   public long storeQueueStatus(long queueID, QueueStatus status) throws Exception {
      return 0;
   }

   @Override
   public void updateQueueBinding(long tx, Binding binding) throws Exception {
   }

   @Override
   public void deleteQueueStatus(long recordID) throws Exception {

   }

   @Override
   public void injectMonitor(FileStoreMonitor monitor) throws Exception {

   }

   private static final OperationContext dummyContext = new OperationContext() {

      @Override
      public void onError(final int errorCode, final String errorMessage) {
      }

      @Override
      public void done() {
      }

      @Override
      public void executeOnCompletion(IOCallback runnable, boolean storeOnly) {
         runnable.done();
      }

      @Override
      public void storeLineUp() {
      }

      @Override
      public boolean waitCompletion(final long timeout) throws Exception {
         return true;
      }

      @Override
      public void waitCompletion() throws Exception {
      }

      @Override
      public void replicationLineUp() {
      }

      @Override
      public void replicationDone() {
      }

      @Override
      public void pageSyncLineUp() {
      }

      @Override
      public void pageSyncDone() {
      }

      @Override
      public void executeOnCompletion(final IOCallback runnable) {
         runnable.done();
      }
   };

   @Override
   public void deleteQueueBinding(long tx, final long queueBindingID) throws Exception {
   }

   @Override
   public void addAddressBinding(long tx, AddressInfo addressInfo) throws Exception {
   }

   @Override
   public void deleteAddressBinding(long tx, long addressBindingID) throws Exception {
   }

   @Override
   public void commit(final long txID) throws Exception {
   }

   @Override
   public JournalLoadInformation loadBindingJournal(final List<QueueBindingInfo> queueBindingInfos,
                                                    final List<GroupingInfo> groupingInfos,
                                                    final List<AddressBindingInfo> addressBindingInfos) throws Exception {
      return new JournalLoadInformation();
   }

   @Override
   public void prepare(final long txID, final Xid xid) throws Exception {
   }

   @Override
   public void rollback(final long txID) throws Exception {
   }

   @Override
   public void rollbackBindings(final long txID) throws Exception {
   }

   @Override
   public void commitBindings(final long txID) throws Exception {
   }

   @Override
   public void storeReference(final long queueID, final long messageID, final boolean last) throws Exception {
   }

   @Override
   public void storeReferenceTransactional(final long txID, final long queueID, final long messageID) throws Exception {
   }

   @Override
   public void storeAcknowledge(final long queueID, final long messageID) throws Exception {
   }

   @Override
   public void storeAcknowledgeTransactional(final long txID,
                                             final long queueID,
                                             final long messageiD) throws Exception {
   }

   @Override
   public void deleteMessage(final long messageID) throws Exception {
   }

   @Override
   public void storeMessage(final Message message) throws Exception {
   }

   @Override
   public void storeMessageTransactional(final long txID, final Message message) throws Exception {
   }

   @Override
   public void updateScheduledDeliveryTime(final MessageReference ref) throws Exception {
   }

   @Override
   public void updateScheduledDeliveryTimeTransactional(final long txID, final MessageReference ref) throws Exception {
   }

   @Override
   public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception {
   }

   @Override
   public void updateDeliveryCount(final MessageReference ref) throws Exception {
   }

   @Override
   public void storeDuplicateID(final SimpleString address, final byte[] duplID, final long recordID) throws Exception {
   }

   @Override
   public void storeDuplicateIDTransactional(final long txID,
                                             final SimpleString address,
                                             final byte[] duplID,
                                             final long recordID) throws Exception {
   }

   @Override
   public void updateDuplicateIDTransactional(final long txID,
                                              final SimpleString address,
                                              final byte[] duplID,
                                              final long recordID) throws Exception {
   }

   @Override
   public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception {
      return generateID();
   }

   @Override
   public void deleteHeuristicCompletion(final long txID) throws Exception {
   }

   @Override
   public void addQueueBinding(final long tx, final Binding binding) throws Exception {
   }

   @Override
   public LargeServerMessage createLargeMessage() {
      return new NullStorageLargeServerMessage();
   }

   @Override
   public LargeServerMessage createLargeMessage(final long id, final Message message) {
      NullStorageLargeServerMessage largeMessage = new NullStorageLargeServerMessage();

      largeMessage.copyHeadersAndProperties(message);

      largeMessage.setMessageID(id);

      return largeMessage;
   }

   @Override
   public long generateID() {
      long id = idSequence.getAndIncrement();

      return id;
   }

   @Override
   public long getCurrentID() {
      return idSequence.get();
   }

   @Override
   public synchronized void start() throws Exception {
      if (started) {
         throw new IllegalStateException("Already started");
      }

      started = true;
   }

   @Override
   public synchronized void stop() throws Exception {
      if (!started) {
         throw new IllegalStateException("Not started");
      }

      idSequence.set(0);

      started = false;
   }

   @Override
   public synchronized boolean isStarted() {
      return started;
   }

   @Override
   public JournalLoadInformation loadMessageJournal(final PostOffice postOffice,
                                                    final PagingManager pagingManager,
                                                    final ResourceManager resourceManager,
                                                    final Map<Long, QueueBindingInfo> queueInfos,
                                                    final Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap,
                                                    final Set<Pair<Long, Long>> pendingLargeMessages,
                                                    List<PageCountPending> pendingNonTXPageCounter,
                                                    final JournalLoader journalLoader) throws Exception {
      return new JournalLoadInformation();
   }

   @Override
   public void deleteDuplicateIDTransactional(final long txID, final long recordID) throws Exception {
   }

   @Override
   public void deleteDuplicateID(final long recordID) throws Exception {
   }

   @Override
   public void pageClosed(final SimpleString storeName, final int pageNumber) {
   }

   @Override
   public void pageDeleted(final SimpleString storeName, final int pageNumber) {
   }

   @Override
   public void pageWrite(final PagedMessage message, final int pageNumber) {
   }

   @Override
   public void addGrouping(final GroupBinding groupBinding) throws Exception {
   }

   @Override
   public void deleteGrouping(final long tx, final GroupBinding groupBinding) throws Exception {
   }

   @Override
   public boolean waitOnOperations(final long timeout) throws Exception {
      return true;
   }

   @Override
   public void afterCompleteOperations(final IOCallback run) {
      run.done();
   }

   @Override
   public void afterStoreOperations(IOCallback run) {
      run.done();
   }

   @Override
   public void waitOnOperations() throws Exception {
   }

   @Override
   public OperationContext getContext() {
      return NullStorageManager.dummyContext;
   }

   @Override
   public OperationContext newContext(final Executor executor) {
      return NullStorageManager.dummyContext;
   }

   @Override
   public OperationContext newSingleThreadContext() {
      return NullStorageManager.dummyContext;
   }

   @Override
   public void setContext(final OperationContext context) {
   }

   @Override
   public void clearContext() {
   }

   @Override
   public List<PersistedAddressSetting> recoverAddressSettings() throws Exception {
      return Collections.emptyList();
   }

   @Override
   public void storeAddressSetting(final PersistedAddressSetting addressSetting) throws Exception {
   }

   @Override
   public List<PersistedRoles> recoverPersistedRoles() throws Exception {
      return Collections.emptyList();
   }

   @Override
   public void storeSecurityRoles(final PersistedRoles persistedRoles) throws Exception {
   }

   @Override
   public void deleteAddressSetting(final SimpleString addressMatch) throws Exception {
   }

   @Override
   public void deleteSecurityRoles(final SimpleString addressMatch) throws Exception {
   }

   @Override
   public void deletePageTransactional(final long recordID) throws Exception {
   }

   @Override
   public void updatePageTransaction(final long txID,
                                     final PageTransactionInfo pageTransaction,
                                     final int depage) throws Exception {
   }

   @Override
   public void storeCursorAcknowledge(final long queueID, final PagePosition position) {
   }

   @Override
   public void storeCursorAcknowledgeTransactional(final long txID, final long queueID, final PagePosition position) {
   }

   @Override
   public void deleteCursorAcknowledgeTransactional(final long txID, final long ackID) throws Exception {
   }

   @Override
   public void deleteCursorAcknowledge(long ackID) throws Exception {
   }

   @Override
   public void storePageCompleteTransactional(long txID, long queueID, PagePosition position) throws Exception {
   }

   @Override
   public void deletePageComplete(long ackID) throws Exception {
   }

   @Override
   public long storePageCounter(final long txID, final long queueID, final long value) throws Exception {
      return 0;
   }

   @Override
   public long storePendingCounter(long queueID, long pageID, int inc) throws Exception {
      return -1;
   }

   @Override
   public void deleteIncrementRecord(final long txID, final long recordID) throws Exception {
   }

   @Override
   public void deletePageCounter(final long txID, final long recordID) throws Exception {
   }

   @Override
   public void deletePendingPageCounter(long txID, long recordID) throws Exception {
   }

   @Override
   public long storePageCounterInc(final long txID, final long queueID, final int add) throws Exception {
      return 0;
   }

   @Override
   public long storePageCounterInc(final long queueID, final int add) throws Exception {
      return 0;
   }

   @Override
   public void commit(final long txID, final boolean lineUpContext) throws Exception {
   }

   @Override
   public void lineUpContext() {
   }

   @Override
   public void confirmPendingLargeMessageTX(final Transaction transaction,
                                            final long messageID,
                                            final long recordID) throws Exception {
   }

   @Override
   public void confirmPendingLargeMessage(final long recordID) throws Exception {
   }

   @Override
   public void stop(final boolean ioCriticalError, boolean sendFailover) throws Exception {
   }

   @Override
   public Journal getBindingsJournal() {
      return null;
   }

   @Override
   public Journal getMessageJournal() {
      return null;
   }

   @Override
   public void startReplication(final ReplicationManager replicationManager,
                                final PagingManager pagingManager,
                                final String nodeID,
                                final boolean autoFailBack,
                                long initialReplicationSyncTimeout) throws Exception {
      // no-op
   }

   @Override
   public boolean addToPage(PagingStore store,
                            Message msg,
                            Transaction tx,
                            RouteContextList listCtx) throws Exception {
      /**
       * Exposing the read-lock here is an encapsulation violation done in order to keep the code
       * simpler. The alternative would be to add a second method, say 'verifyPaging', to
       * PagingStore.
       *

       * Adding this second method would also be more surprise prone as it would require a certain
       * calling order.
       *

       * The reasoning is that exposing the lock is more explicit and therefore `less bad`.
       */
      return store.page(msg, tx, listCtx, null);
   }

   @Override
   public void stopReplication() {
      // no-op
   }

   @Override
   public SequentialFile createFileForLargeMessage(final long messageID, final LargeMessageExtension extension) {
      throw new UnsupportedOperationException();
   }

   @Override
   public void addBytesToLargeMessage(SequentialFile appendFile, long messageID, byte[] bytes) throws Exception {
      // no-op
   }

   @Override
   public void beforePageRead() throws Exception {
   }

   @Override
   public void afterPageRead() throws Exception {
   }

   @Override
   public ByteBuffer allocateDirectBuffer(final int size) {
      return ByteBuffer.allocateDirect(size);
   }

   @Override
   public void freeDirectBuffer(final ByteBuffer buffer) {
      // We can just have hope on GC here :-)
   }

   @Override
   public void storeID(final long journalID, final long id) throws Exception {
      // no-op
   }

   @Override
   public void readLock() {
      // no-op
   }

   @Override
   public void readUnLock() {
      // no-op
   }

   @Override
   public void persistIdGenerator() {
      // no-op
   }

   @Override
   public void deleteID(long journalD) throws Exception {

   }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace TWSLib
{
    [ComVisible(true), Guid("25D97F3D-2C4D-4080-9250-D2FB8071BE58")]
    public interface IOrder
    {
        [DispId(1)]
        int orderId { get; set; }
        [DispId(2)]
        int clientId { get; set; }
        [DispId(3)]
        int permId { get; set; }
        [DispId(4)]
        string action { get; set; }
        [DispId(5)]
        int totalQuantity { get; set; }
        [DispId(6)]
        string orderType { get; set; }
        [DispId(7)]
        double lmtPrice { get; set; }
        [DispId(8)]
        double auxPrice { get; set; }

        // extended order fields
        [DispId(20)]
        string timeInForce { get; set; }
        [DispId(140)]//!!!
        string activeStartTime { get; set; }
        [DispId(141)]//!!!
        string activeStopTime { get; set; }
        [DispId(21)]
        string ocaGroup { get; set; }
        [DispId(22)]
        int ocaType { get; set; }
        [DispId(23)]
        string orderRef { get; set; }
        [DispId(24)]
        bool transmit { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(25)]
        int parentId { get; set; }
        [DispId(26)]
        bool blockOrder { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(27)]
        bool sweepToFill { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(28)]
        int displaySize { get; set; }
        [DispId(29)]
        int triggerMethod { get; set; }
        [DispId(30)]
        bool outsideRth { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(31)]
        bool hidden { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(32)]
        string goodAfterTime { get; set; }
        [DispId(33)]
        string goodTillDate { get; set; }
        [DispId(35)]
        bool overridePercentageConstraints { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(36)]
        string rule80A { get; set; }
        [DispId(37)]
        bool allOrNone { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(38)]
        int minQty { get; set; }
        [DispId(39)]
        double percentOffset { get; set; }
        [DispId(40)]
        double trailStopPrice { get; set; }
        [DispId(44)]
        double trailingPercent { get; set; }
        [DispId(41)]
        bool whatIf { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(42)]
        bool notHeld { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }

        // Financial advisors only
        [DispId(60)]
        string faGroup { get; set; }
        [DispId(61)]
        string faProfile { get; set; }
        [DispId(62)]
        string faMethod { get; set; }
        [DispId(63)]
        string faPercentage { get; set; }

        // Institutional orders only
        [DispId(72)]
        string openClose { get; set; }
        [DispId(73)]
        int origin { get; set; }
        [DispId(74)]
        int shortSaleSlot { get; set; }
        [DispId(75)]
        string designatedLocation { get; set; }
        [DispId(76)]
        int exemptCode { get; set; }

        // SMART routing only
        [DispId(80)]
        double discretionaryAmt { get; set; }
        [DispId(81)]
        bool eTradeOnly { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(82)]
        bool firmQuoteOnly { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(83)]
        double nbboPriceCap { get; set; }
        [DispId(84)]
        bool optOutSmartRouting { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }

        // BOX or VOL orders only
        [DispId(90)]
        int auctionStrategy { get; set; }

        // BOX order only
        [DispId(91)]
        double startingPrice { get; set; }
        [DispId(92)]
        double stockRefPrice { get; set; }
        [DispId(93)]
        double delta { get; set; }

        // pegged to stock or VOL orders
        [DispId(94)]
        double stockRangeLower { get; set; }
        [DispId(95)]
        double stockRangeUpper { get; set; }

        // VOLATILITY orders only
        [DispId(96)]
        double volatility { get; set; }
        [DispId(97)]
        int volatilityType { get; set; }
        [DispId(98)]
        bool continuousUpdate { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(99)]
        int referencePriceType { get; set; }
        [DispId(100)]
        string deltaNeutralOrderType { get; set; }
        [DispId(101)]
        double deltaNeutralAuxPrice { get; set; }
        [DispId(123)]
        int deltaNeutralConId { get; set; }
        [DispId(124)]
        string deltaNeutralSettlingFirm { get; set; }
        [DispId(125)]
        string deltaNeutralClearingAccount { get; set; }
        [DispId(126)]
        string deltaNeutralClearingIntent { get; set; }
        [DispId(135)]
        string deltaNeutralOpenClose { get; set; }
        [DispId(136)]
        bool deltaNeutralShortSale { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(137)]
        int deltaNeutralShortSaleSlot { get; set; }
        [DispId(138)]
        string deltaNeutralDesignatedLocation { get; set; }

        // COMBO orders only
        [DispId(102)]
        double basisPoints { get; set; }
        [DispId(103)]
        int basisPointsType { get; set; }

        // SCALE orders only
        [DispId(104)]
        int scaleInitLevelSize { get; set; }
        [DispId(105)]
        int scaleSubsLevelSize { get; set; }
        [DispId(106)]
        double scalePriceIncrement { get; set; }
        [DispId(127)]
        double scalePriceAdjustValue { get; set; }
        [DispId(128)]
        int scalePriceAdjustInterval { get; set; }
        [DispId(129)]
        double scaleProfitOffset { get; set; }
        [DispId(130)]
        bool scaleAutoReset { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(131)]
        int scaleInitPosition { get; set; }
        [DispId(132)]
        int scaleInitFillQty { get; set; }
        [DispId(133)]
        bool scaleRandomPercent { [return: MarshalAs(UnmanagedType.Bool)] get; [param: MarshalAs(UnmanagedType.Bool)] set; }
        [DispId(139)]//!!
        string scaleTable { get; set; }

        // HEDGE orders only
        [DispId(107)]
        string hedgeType { get; set; }
        [DispId(108)]
        string hedgeParam { get; set; }

        // Clearing info
        [DispId(110)]
        string account { get; set; }
        [DispId(111)]
        string settlingFirm { get; set; }
        [DispId(112)]
        string clearingAccount { get; set; }
        [DispId(113)]
        string clearingIntent { get; set; }

        // ALGO orders only
        [DispId(120)]
        string algoStrategy { get; set; }
        [DispId(121)]
        object algoParams { [return: MarshalAs(UnmanagedType.IDispatch)] get; [param: MarshalAs(UnmanagedType.IDispatch)] set; }

        // Smart combo routing params
        [DispId(122)]
        object smartComboRoutingParams { [return: MarshalAs(UnmanagedType.IDispatch)] get; [param: MarshalAs(UnmanagedType.IDispatch)] set; }

        // order combo legs
        [DispId(134)]
        object orderComboLegs { [return: MarshalAs(UnmanagedType.IDispatch)] get; [param: MarshalAs(UnmanagedType.IDispatch)] set; }

        [DispId(142)]
        object orderMiscOptions { [return: MarshalAs(UnmanagedType.IDispatch)] get; [param: MarshalAs(UnmanagedType.IDispatch)] set; }
        [DispId(143)]
        string algoId { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace Sparky.Model
{
    public interface IConfiguration
    {
        string Resolve(string key);

        IExternProvider ExternProvider { get; }
    }
}


text:
package introspection

import (
	context "context"

	api "github.com/containerd/containerd/api/services/introspection/v1"
	"github.com/containerd/containerd/errdefs"
	ptypes "github.com/gogo/protobuf/types"
)

type Service interface {
	Plugins(context.Context, []string) (*api.PluginsResponse, error)
	Server(context.Context, *ptypes.Empty) (*api.ServerResponse, error)
}

type introspectionRemote struct {
	client api.IntrospectionClient
}

var _ = (Service)(&introspectionRemote{})

func NewIntrospectionServiceFromClient(c api.IntrospectionClient) Service {
	return &introspectionRemote{client: c}
}

func (i *introspectionRemote) Plugins(ctx context.Context, filters []string) (*api.PluginsResponse, error) {
	resp, err := i.client.Plugins(ctx, &api.PluginsRequest{
		Filters: filters,
	})

	if err != nil {
		return nil, errdefs.FromGRPC(err)
	}

	return resp, nil
}

func (i *introspectionRemote) Server(ctx context.Context, in *ptypes.Empty) (*api.ServerResponse, error) {
	resp, err := i.client.Server(ctx, in)

	if err != nil {
		return nil, errdefs.FromGRPC(err)
	}

	return resp, nil
}


text:
import { Editor } from "@ckeditor/ckeditor5-core";
import { ExportWord } from "@ckeditor/ckeditor5-export-word";
import { ExportWordConfig } from "@ckeditor/ckeditor5-export-word/src/exportword";

class MyEditor extends Editor {}

const bool: boolean = ExportWord.isContextPlugin;
const plugin = new ExportWord(new MyEditor());
const promise = plugin.destroy?.();
if (promise != null) {
    promise.then(() => {});
}

let config: ExportWordConfig = {};
config = {
    converterOptions: {},
};
config = {
    converterOptions: {
        margin_top: 0,
        margin_bottom: "15cm",
        margin_right: "1cm",
        margin_left: 0,
        format: "A6",
        auto_pagination: bool,
    },
};
config = {
    converterUrl: "",
    fileName: "",
    stylesheets: [""],
    tokenUrl: false,
};

config = {
    tokenUrl() {
        return Promise.resolve("");
    },
};
config = {
    tokenUrl: "",
};


text:
RSpec.configure do |c|
  c.alias_it_behaves_like_to :it_returns, 'returns'
end


text:
package com.kk.binding.listener;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author xuanjue.hk
 * @date 2013-2-28
 * */
public class OnItemClickListenerImp extends ListenerToCommand implements OnItemClickListener {
	@Override
	public void registerToView(View v) {
		if (!(v instanceof AdapterView<?>))
			return;
		((AdapterView<?>) v).setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		executeCommand(arg0, arg1, arg2, arg3);
	}
}


text:
package acm

import (
	"bytes"
	"io"
	"io/ioutil"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

func GbkToUtf8(s []byte) ([]byte, error) {
	reader := GbkToUtf8Reader(bytes.NewReader(s))
	return ioutil.ReadAll(reader)
}

func Utf8ToGbk(s []byte) ([]byte, error) {
	reader := Utf8ToGbkReader(bytes.NewReader(s))
	return ioutil.ReadAll(reader)
}

//return utf8
func GbkToUtf8Reader(s io.Reader) io.Reader {
	return transform.NewReader(s, simplifiedchinese.GBK.NewDecoder())
}

//return gbk
func Utf8ToGbkReader(s io.Reader) io.Reader {
	return transform.NewReader(s, simplifiedchinese.GBK.NewEncoder())
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// System.Security.Cryptography.RSA
struct RSA_t1557565273;
// System.String
struct String_t;

#include "mscorlib_System_Security_Cryptography_AsymmetricSi3229527040.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.Security.Cryptography.RSAPKCS1SignatureDeformatter
struct  RSAPKCS1SignatureDeformatter_t1504052144  : public AsymmetricSignatureDeformatter_t3229527040
{
public:
	// System.Security.Cryptography.RSA System.Security.Cryptography.RSAPKCS1SignatureDeformatter::rsa
	RSA_t1557565273 * ___rsa_0;
	// System.String System.Security.Cryptography.RSAPKCS1SignatureDeformatter::hashName
	String_t* ___hashName_1;

public:
	inline static int32_t get_offset_of_rsa_0() { return static_cast<int32_t>(offsetof(RSAPKCS1SignatureDeformatter_t1504052144, ___rsa_0)); }
	inline RSA_t1557565273 * get_rsa_0() const { return ___rsa_0; }
	inline RSA_t1557565273 ** get_address_of_rsa_0() { return &___rsa_0; }
	inline void set_rsa_0(RSA_t1557565273 * value)
	{
		___rsa_0 = value;
		Il2CppCodeGenWriteBarrier(&___rsa_0, value);
	}

	inline static int32_t get_offset_of_hashName_1() { return static_cast<int32_t>(offsetof(RSAPKCS1SignatureDeformatter_t1504052144, ___hashName_1)); }
	inline String_t* get_hashName_1() const { return ___hashName_1; }
	inline String_t** get_address_of_hashName_1() { return &___hashName_1; }
	inline void set_hashName_1(String_t* value)
	{
		___hashName_1 = value;
		Il2CppCodeGenWriteBarrier(&___hashName_1, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
package stormpot;

import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.lang.management.*;
import java.util.List;

/**
 * A TestRule that ensures that any failing tests have their stack-trace
 * printed to stderr.
 *
 * This is useful for when the tests are running on a build-server, and you'd
 * like the details of any failure to be printed to the build-log. A nice thing
 * if the build system does not make the build artifacts with the test failures
 * available.
 *
 * @author cvh
 */
public class FailurePrinterTestRule implements TestRule {
  @Override
  public Statement apply(final Statement base, final Description description) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        CompilationMXBean compilationMXBean = ManagementFactory.getCompilationMXBean();
        List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
        OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();

        long startCpuTimeNs = getCpuTimeNs(threadMXBean);
        long startUserTimeNs = getUserTimeNs(threadMXBean);
        int startThreadCount = threadMXBean.getThreadCount();
        long startCompilationTimeMs = getCompilationTimeMs(compilationMXBean);
        long startCollectionTimeMs = collectionTimeMs(garbageCollectorMXBeans);
        double loadAverage = operatingSystemMXBean.getSystemLoadAverage();

        int cores = operatingSystemMXBean.getAvailableProcessors();

        try {
          base.evaluate();
        } catch (AssumptionViolatedException ignore) {
          // This is fine.
        } catch (Throwable th) {
          long cpuTimeNs = getCpuTimeNs(threadMXBean) - startCpuTimeNs;
          long userTimeNs = getUserTimeNs(threadMXBean) - startUserTimeNs;
          int threadCount = threadMXBean.getThreadCount();
          long compilationTimeMs = getCompilationTimeMs(compilationMXBean) - startCompilationTimeMs;
          long collectionTimeMs = collectionTimeMs(garbageCollectorMXBeans) - startCollectionTimeMs;
          double newLoadAverage = operatingSystemMXBean.getSystemLoadAverage();
          System.err.printf("Failed test:%n" +
              "\tcpu-cores = %s%n" +
              "\tcpuTimeNs = %s%n" +
              "\tuserTimeNs = %s%n" +
              "\tcompilationTimeMs = %s%n" +
              "\tcollectionTimeMs = %s%n" +
              "\tload average = %s -> %s%n" +
              "\tthreads = %s -> %s%n",
              cores,
              cpuTimeNs,
              userTimeNs,
              compilationTimeMs,
              collectionTimeMs,
              loadAverage, newLoadAverage,
              startThreadCount, threadCount);
          th.printStackTrace();
          System.err.flush();
          throw th;
        }
      }
    };
  }

  private long collectionTimeMs(List<GarbageCollectorMXBean> garbageCollectorMXBeans) {
    long sum = 0L;
    for (GarbageCollectorMXBean gc : garbageCollectorMXBeans) {
      long collectionTime = gc.getCollectionTime();
      if (collectionTime != -1) {
        sum += collectionTime;
      }
    }
    return sum;
  }

  private long getCompilationTimeMs(CompilationMXBean compilationMXBean) {
    return compilationMXBean.isCompilationTimeMonitoringSupported()?
        compilationMXBean.getTotalCompilationTime() : 0;
  }

  private long getUserTimeNs(ThreadMXBean threadMXBean) {
    return threadMXBean.isCurrentThreadCpuTimeSupported()?
        threadMXBean.getCurrentThreadUserTime() : 0;
  }

  private long getCpuTimeNs(ThreadMXBean threadMXBean) {
    return threadMXBean.isCurrentThreadCpuTimeSupported()?
        threadMXBean.getCurrentThreadCpuTime() : 0;
  }
}


text:
namespace formulate.app.Forms
{

    // Namespaces.
    using System.Collections.Generic;

    /// <summary>
    /// A contract for creating a Form field that requires additional, uncommon functionality.
    /// </summary>
    public interface IFormFieldTypeExtended
    {
        /// <summary>
        /// Gets a value indicating whether this is transitory (i.e., they aren't used for data)
        /// </summary>
        /// <remarks>
        /// Some examples include buttons and read only text fields.
        /// </remarks>
        bool IsTransitory { get; }

        /// <summary>
        /// Gets a value indicating whether this is server-side only (i.e., they aren't rendered on the frontend of the website).
        /// </summary>
        bool IsServerSideOnly { get; }

        /// <summary>
        /// Gets a value indicating whether this is hidden during data entry.
        /// </summary>
        bool IsHidden { get; }

        /// <summary>
        /// Gets a value indicating whether this is field value is stored (e.g., reCAPTCHA values would not be stored).
        /// </summary>
        bool IsStored { get; }

        /// <summary>
        /// Is the field value valid?
        /// </summary>
        /// <param name="value">The value submitted with the form.</param>
        /// <returns>
        /// True, if the value is valid; otherwise, false.
        /// </returns>
        bool IsValid(IEnumerable<string> value);

        /// <summary>
        /// Returns a validation message that is shown for fields that have validation
        /// built in (i.e., rather than relying on the messages specific to validations
        /// that can be attached to any field).
        /// </summary>
        /// <returns>
        /// The validation error message.
        /// </returns>
        string GetNativeFieldValidationMessage();
    }
}


text:
<!DOCTYPE html>

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>

		<script>

			"use strict";

			// function Person() {
			//
			// }
			//
			// // static
			// Person.createSmith = function(firstName) {
			// 	return new Person(firstName, "Smith");
			// };
			//
			// var p = Person.createSmith("Jonathan");

			class Person {

			}

			var Person = class {

			}

			class Person {

				constructor(firstName, lastName) {
					this._firstName = firstName; // instance properties
					this._lastName = lastName;
				}

				// prototype properties
				getFullName() {
					return this.firstName + " " + this.lastName;
				}

				static create(firstName, lastName) {
					return new Person(firstName, lastName);
				}

				get firstName() {
					return this._firstName;
				}

				set firstName(value) {
					this._firstName = value;
				}

				get lastName() {
					return this._lastName;
				}

				set lastName(value) {
					this._lastName = value;
				}

			}

			class Student extends Person {

				constructor(studentId, firstName, lastName) {
					super(firstName, lastName);
					this.studentId = studentId;
				}

			}

			var p = Person.create("Bob", "Martin");
			console.dir(p);
			console.dir(Person);

		</script>

	</body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-fragment version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd">

  <name>togglz_console</name>

  <distributable/>

  <servlet>
    <servlet-name>TogglzConsoleServlet</servlet-name>
    <servlet-class>org.togglz.console.TogglzConsoleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TogglzConsoleServlet</servlet-name>
    <url-pattern>/togglz/*</url-pattern>
  </servlet-mapping>

</web-fragment>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'objectmancy'

require 'minitest/autorun'
require 'minitest/pride'

# Setup test classes
module ObjTestClasses
  class Book
    include Objectmancy

    attribute :title
    attribute :author
  end

  class Cat
    attr_reader :name

    def initialize(name)
      @name = name
    end

    def ==(other)
      self.class == other.class &&
        name == other.name
    end
  end

  class Game
    attr_reader :title, :developer

    def initialize(title, developer)
      @title = title
      @developer = developer
    end

    def self.from_string(str)
      values = str.split '/'
      new(values.first, values.last)
    end

    def ==(other)
      self.class == other.class &&
        title == other.title &&
        developer == other.developer
    end
  end

  class TestObject
    include Objectmancy::Objectable

    attr_reader :before_init,
                :after_init,
                :before_mass_update_set,
                :after_mass_update_set

    attribute :name

    attribute :update_date, type: :datetime
    attribute :book, type: Book
    attribute :pet, type: Cat
    attribute :video_game, type: Game, objectable: :from_string
    attribute :primes

    multiples :birth_dates, type: :datetime
    multiples :library, type: Book
    multiples :menagerie, type: Cat
    multiples :board_games, type: Game, objectable: :from_string

    def before_initialize
      @before_init = :before_set
    end

    def after_initialize
      @after_init = :after_set
    end

    def before_mass_update
      @before_mass_update_set = :before_update_set
    end

    def after_mass_update
      @after_mass_update_set = :after_update_set
    end
  end
end


text:
package com.facebook.infer.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * A method annotated with @Cleanup should always be permitted to nullify fields, even if they are
 * not nullable. Combined with the @Initializer annotation, this allows devs to specify
 * acquire/release methods.
 */
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Cleanup {}


text:
'''
Created on 2016-5-27

@author: hustcc
'''

from datetime import datetime
from datetime import date
from datetime import time

__ALL__ = ['parse']

def parse(input):
    '''
    parse input to datetime
    '''
    if isinstance(input, datetime):
        return input
    if isinstance(input, date):
        return date_to_datetime(input)
    if isinstance(input, time):
        return time_to_datetime(input)
    if isinstance(input, (int, float)):
        return timestamp_to_datetime(input)
    if isinstance(input, (str)):
        return string_to_data_time(input)
    return None

def date_to_datetime(d):
    return _combine_date_time(d, time(0, 0, 0))

def time_to_datetime(t):
    return _combine_date_time(date.today(), t)

def timestamp_to_datetime(ts):
    '''
    parse timestamp to datetime
    '''
    return datetime.fromtimestamp(ts)

def _combine_date_time(d, t):
    if (d is not None) and (t is not None):
        return datetime(d.year, d.month, d.day, t.hour, t.minute, t.second)
    return None

def _string_to_date(date_string):
    if not date_string:
        return None
    try:
        d_array = date_string.split('-')
        return date(int(d_array[0]), int(d_array[1]), int(d_array[2]))
    except:
        return None

def _string_to_time(time_string):
    if not time_string:
        return None
    try:
        t_array = time_string.split(':')
        return time(int(t_array[0]), int(t_array[1]), int(t_array[2]))
    except:
        return None

def string_to_data_time(d):
    '''
    simple parse date string, such as:
    2016-5-27 21:22:20
    2016-05-27 21:22:2
    2016/05/27 21:22:2

    2016-05-27
    2016/5/27

    21:22:2
    '''
    if d:
        d = d.replace('/', '-')
        if ' ' in d:
            _datetime = d.split(' ')
            if len(_datetime) == 2:
                _d = _string_to_date(_datetime[0])
                _t = _string_to_time(_datetime[1])
                return _combine_date_time(_d, _t)
        else:
            # no space
            if '-' in d:
                return date_to_datetime(_string_to_date(d))
            elif ':' in d:
                return time_to_datetime(_string_to_time(d))
    return None


text:
import BlendingState from "./BlendingState.js";
import Buffer from "../Renderer/Buffer.js";
import BufferUsage from "../Renderer/BufferUsage.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ComputeCommand from "../Renderer/ComputeCommand.js";
import CloudType from "./CloudType.js";
import CloudCollectionFS from "../Shaders/CloudCollectionFS.js";
import CloudCollectionVS from "../Shaders/CloudCollectionVS.js";
import CloudNoiseFS from "../Shaders/CloudNoiseFS.js";
import CloudNoiseVS from "../Shaders/CloudNoiseVS.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import CumulusCloud from "./CumulusCloud.js";
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import DrawCommand from "../Renderer/DrawCommand.js";
import EncodedCartesian3 from "../Core/EncodedCartesian3.js";
import IndexDatatype from "../Core/IndexDatatype.js";
import Pass from "../Renderer/Pass.js";
import PixelDatatype from "../Renderer/PixelDatatype.js";
import PixelFormat from "../Core/PixelFormat.js";
import RenderState from "../Renderer/RenderState.js";
import Sampler from "../Renderer/Sampler.js";
import ShaderSource from "../Renderer/ShaderSource.js";
import ShaderProgram from "../Renderer/ShaderProgram.js";
import Texture from "../Renderer/Texture.js";
import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
import TextureWrap from "../Renderer/TextureWrap.js";
import VertexArray from "../Renderer/VertexArray.js";
import VertexArrayFacade from "../Renderer/VertexArrayFacade.js";
import WebGLConstants from "../Core/WebGLConstants.js";

let attributeLocations;
const scratchTextureDimensions = new Cartesian3();

const attributeLocationsBatched = {
  positionHighAndScaleX: 0,
  positionLowAndScaleY: 1,
  packedAttribute0: 2, // show, brightness, direction
  packedAttribute1: 3, // cloudSize, slice
  color: 4,
};

const attributeLocationsInstanced = {
  direction: 0,
  positionHighAndScaleX: 1,
  positionLowAndScaleY: 2,
  packedAttribute0: 3, // show, brightness
  packedAttribute1: 4, // cloudSize, slice
  color: 5,
};

const SHOW_INDEX = CumulusCloud.SHOW_INDEX;
const POSITION_INDEX = CumulusCloud.POSITION_INDEX;
const SCALE_INDEX = CumulusCloud.SCALE_INDEX;
const MAXIMUM_SIZE_INDEX = CumulusCloud.MAXIMUM_SIZE_INDEX;
const SLICE_INDEX = CumulusCloud.SLICE_INDEX;
const BRIGHTNESS_INDEX = CumulusCloud.BRIGHTNESS_INDEX;
const NUMBER_OF_PROPERTIES = CumulusCloud.NUMBER_OF_PROPERTIES;
const COLOR_INDEX = CumulusCloud.COLOR_INDEX;

/**
 * A renderable collection of clouds in the 3D scene.
 *

 *

 *

 * Example cumulus clouds
 *

 *

 * Clouds are added and removed from the collection using {@link CloudCollection#add}
 * and {@link CloudCollection#remove}.
 * @alias CloudCollection
 * @constructor
 *
 * @param {Object} [options] Object with the following properties:
 * @param {Boolean} [options.show=true] Whether to display the clouds.
 * @param {Number} [options.noiseDetail=16.0] Desired amount of detail in the noise texture.
 * @param {Number} [options.noiseOffset=Cartesian3.ZERO] Desired translation of data in noise texture.
 * @param {Boolean} [options.debugBillboards=false] For debugging only. Determines if the billboards are rendered with an opaque color.
 * @param {Boolean} [options.debugEllipsoids=false] For debugging only. Determines if the clouds will be rendered as opaque ellipsoids.
 * @see CloudCollection#add
 * @see CloudCollection#remove
 * @see CumulusCloud
 *
 * @demo {@link https://sandcastle.cesium.com/index.html?src=Clouds.html|Cesium Sandcastle Clouds Demo}
 * @demo {@link https://sandcastle.cesium.com/index.html?src=Cloud%20Parameters.html|Cesium Sandcastle Cloud Parameters Demo}
 *
 * @example
 * // Create a cloud collection with two cumulus clouds
 * const clouds = scene.primitives.add(new Cesium.CloudCollection());
 * clouds.add({
 *   position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
 *   maximumSize: new Cesium.Cartesian3(20.0, 12.0, 8.0)
 * });
 * clouds.add({
 *   position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
 *   maximumSize: new Cesium.Cartesian3(15.0, 9.0, 9.0),
 *   slice: 0.5
 * });
 *
 */
function CloudCollection(options) {
  options = defaultValue(options, defaultValue.EMPTY_OBJECT);

  this._clouds = [];
  this._cloudsToUpdate = [];
  this._cloudsToUpdateIndex = 0;
  this._cloudsRemoved = false;
  this._createVertexArray = false;

  this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES);

  this._noiseTexture = undefined;
  this._textureSliceWidth = 128;
  this._noiseTextureRows = 4;

  /**
   *

   * Controls the amount of detail captured in the precomputed noise texture
   * used to render the cumulus clouds. In order for the texture to be tileable,
   * this must be a power of two. For best results, set this to be a power of two
   * between 8.0 and 32.0 (inclusive).
   *

   *
   *

   *

   *
   *   clouds.noiseDetail = 8.0;

   *
   *
   *
   *   clouds.noiseDetail = 32.0;

   *
   *
   *

   *

   *
   * @type {Number}
   *
   * @default 16.0
   */
  this.noiseDetail = defaultValue(options.noiseDetail, 16.0);

  /**
   *

   * Applies a translation to noise texture coordinates to generate different data.
   * This can be modified if the default noise does not generate good-looking clouds.
   *

   *
   *

   *

   *
   *   default

   *
   *
   *
   *   clouds.noiseOffset = new Cesium.Cartesian3(10, 20, 10);

   *
   *
   *

   *

   * @type {Cartesian3}
   *
   * @default Cartesian3.ZERO
   */
  this.noiseOffset = Cartesian3.clone(
    defaultValue(options.noiseOffset, Cartesian3.ZERO)
  );

  this._loading = false;
  this._ready = false;

  const that = this;
  this._uniforms = {
    u_noiseTexture: function () {
      return that._noiseTexture;
    },
    u_noiseTextureDimensions: getNoiseTextureDimensions(that),
    u_noiseDetail: function () {
      return that.noiseDetail;
    },
  };

  this._vaNoise = undefined;
  this._spNoise = undefined;

  this._spCreated = false;
  this._sp = undefined;
  this._rs = undefined;

  /**
   * Determines if billboards in this collection will be shown.
   *
   * @type {Boolean}
   * @default true
   */
  this.show = defaultValue(options.show, true);

  this._colorCommands = [];

  /**
   * This property is for debugging only; it is not for production use nor is it optimized.
   *

   * Renders the billboards with one opaque color for the sake of debugging.
   *

   *
   * @type {Boolean}
   *
   * @default false
   */
  this.debugBillboards = defaultValue(options.debugBillboards, false);
  this._compiledDebugBillboards = false;

  /**
   * This property is for debugging only; it is not for production use nor is it optimized.
   *

   * Draws the clouds as opaque, monochrome ellipsoids for the sake of debugging.
   * If debugBillboards is also true, then the ellipsoids will draw on top of the billboards.
   *

   *
   * @type {Boolean}
   *
   * @default false
   */
  this.debugEllipsoids = defaultValue(options.debugEllipsoids, false);
  this._compiledDebugEllipsoids = false;
}

// Wraps useful texture metrics into a single vec3 for less overhead.
function getNoiseTextureDimensions(collection) {
  return function () {
    scratchTextureDimensions.x = collection._textureSliceWidth;
    scratchTextureDimensions.y = collection._noiseTextureRows;
    scratchTextureDimensions.z = 1.0 / collection._noiseTextureRows;
    return scratchTextureDimensions;
  };
}

Object.defineProperties(CloudCollection.prototype, {
  /**
   * Returns the number of clouds in this collection.
   * @memberof CloudCollection.prototype
   * @type {Number}
   */
  length: {
    get: function () {
      removeClouds(this);
      return this._clouds.length;
    },
  },
});

function destroyClouds(clouds) {
  const length = clouds.length;
  for (let i = 0; i < length; ++i) {
    if (clouds[i]) {
      clouds[i]._destroy();
    }
  }
}

/**
 * Creates and adds a cloud with the specified initial properties to the collection.
 * The added cloud is returned so it can be modified or removed from the collection later.
 *
 * @param {Object}[options] A template describing the cloud's properties as shown in Example 1.
 * @returns {CumulusCloud} The cloud that was added to the collection.
 *
 * @performance Calling add is expected constant time.  However, the collection's vertex buffer
 * is rewritten - an O(n) operation that also incurs CPU to GPU overhead.  For
 * best performance, add as many clouds as possible before calling update.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * // Example 1:  Add a cumulus cloud, specifying all the default values.
 * const c = clouds.add({
 *   show : true,
 *   position : Cesium.Cartesian3.ZERO,
 *   scale : new Cesium.Cartesian2(20.0, 12.0),
 *   maximumSize: new Cesium.Cartesian3(20.0, 12.0, 12.0),
 *   slice: -1.0,
 *   cloudType : CloudType.CUMULUS
 * });
 *
 * @example
 * // Example 2:  Specify only the cloud's cartographic position.
 * const c = clouds.add({
 *   position : Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
 * });
 *
 * @see CloudCollection#remove
 * @see CloudCollection#removeAll
 */
CloudCollection.prototype.add = function (options) {
  options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  const cloudType = defaultValue(options.cloudType, CloudType.CUMULUS);
  //>>includeStart('debug', pragmas.debug);
  if (!CloudType.validate(cloudType)) {
    throw new DeveloperError("invalid cloud type");
  }
  //>>includeEnd('debug');

  let cloud;
  if (cloudType === CloudType.CUMULUS) {
    cloud = new CumulusCloud(options, this);
    cloud._index = this._clouds.length;
    this._clouds.push(cloud);
    this._createVertexArray = true;
  }

  return cloud;
};

/**
 * Removes a cloud from the collection.
 *
 * @param {CumulusCloud} cloud The cloud to remove.
 * @returns {Boolean} true if the cloud was removed; false if the cloud was not found in the collection.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * const c = clouds.add(...);
 * clouds.remove(c);  // Returns true
 *
 * @see CloudCollection#add
 * @see CloudCollection#removeAll
 * @see CumulusCloud#show
 */
CloudCollection.prototype.remove = function (cloud) {
  if (this.contains(cloud)) {
    this._clouds[cloud._index] = undefined; // Removed later in removeClouds()
    this._cloudsRemoved = true;
    this._createVertexArray = true;
    cloud._destroy();
    return true;
  }

  return false;
};

/**
 * Removes all clouds from the collection.
 *
 * @performance O(n).  It is more efficient to remove all the clouds
 * from a collection and then add new ones than to create a new collection entirely.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 * @example
 * clouds.add(...);
 * clouds.add(...);
 * clouds.removeAll();
 *
 * @see CloudCollection#add
 * @see CloudCollection#remove
 */
CloudCollection.prototype.removeAll = function () {
  destroyClouds(this._clouds);
  this._clouds = [];
  this._cloudsToUpdate = [];
  this._cloudsToUpdateIndex = 0;
  this._cloudsRemoved = false;

  this._createVertexArray = true;
};

function removeClouds(cloudCollection) {
  if (cloudCollection._cloudsRemoved) {
    cloudCollection._cloudsRemoved = false;

    const newClouds = [];
    const clouds = cloudCollection._clouds;
    const length = clouds.length;
    for (let i = 0, j = 0; i < length; ++i) {
      const cloud = clouds[i];
      if (defined(cloud)) {
        clouds._index = j++;
        newClouds.push(cloud);
      }
    }

    cloudCollection._clouds = newClouds;
  }
}

CloudCollection.prototype._updateCloud = function (cloud, propertyChanged) {
  if (!cloud._dirty) {
    this._cloudsToUpdate[this._cloudsToUpdateIndex++] = cloud;
  }

  ++this._propertiesChanged[propertyChanged];
};

/**
 * Check whether this collection contains a given cloud.
 *
 * @param {CumulusCloud} [cloud] The cloud to check for.
 * @returns {Boolean} true if this collection contains the cloud, false otherwise.
 *
 * @see CloudCollection#get
 */
CloudCollection.prototype.contains = function (cloud) {
  return defined(cloud) && cloud._cloudCollection === this;
};

/**
 * Returns the cloud in the collection at the specified index. Indices are zero-based
 * and increase as clouds are added. Removing a cloud shifts all clouds after
 * it to the left, changing their indices. This function is commonly used with
 * {@link CloudCollection#length} to iterate over all the clouds in the collection.
 *
 * @param {Number} index The zero-based index of the cloud.
 * @returns {CumulusCloud} The cloud at the specified index.
 *
 * @performance Expected constant time. If clouds were removed from the collection and
 * {@link CloudCollection#update} was not called, an implicit O(n)
 * operation is performed.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * // Toggle the show property of every cloud in the collection
 * const len = clouds.length;
 * for (let i = 0; i < len; ++i) {
 *   const c = clouds.get(i);
 *   c.show = !c.show;
 * }
 *
 * @see CloudCollection#length
 */
CloudCollection.prototype.get = function (index) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("index", index);
  //>>includeEnd('debug');

  removeClouds(this);
  return this._clouds[index];
};

const texturePositions = new Float32Array([
  -1.0,
  -1.0,
  1.0,
  -1.0,
  1.0,
  1.0,
  -1.0,
  1.0,
]);

const textureIndices = new Uint16Array([0, 1, 2, 0, 2, 3]);

function createTextureVA(context) {
  const positionBuffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: texturePositions,
    usage: BufferUsage.STATIC_DRAW,
  });
  const indexBuffer = Buffer.createIndexBuffer({
    context: context,
    typedArray: textureIndices,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  });

  const attributes = [
    {
      index: 0,
      vertexBuffer: positionBuffer,
      componentsPerAttribute: 2,
      componentDatatype: ComponentDatatype.FLOAT,
    },
  ];

  return new VertexArray({
    context: context,
    attributes: attributes,
    indexBuffer: indexBuffer,
  });
}

let getIndexBuffer;

function getIndexBufferBatched(context) {
  const sixteenK = 16 * 1024;

  let indexBuffer = context.cache.cloudCollection_indexBufferBatched;
  if (defined(indexBuffer)) {
    return indexBuffer;
  }

  // Subtract 6 because the last index is reserved for primitive restart.
  // https://www.khronos.org/registry/webgl/specs/latest/2.0/#5.18
  const length = sixteenK * 6 - 6;
  const indices = new Uint16Array(length);
  for (let i = 0, j = 0; i < length; i += 6, j += 4) {
    indices[i] = j;
    indices[i + 1] = j + 1;
    indices[i + 2] = j + 2;

    indices[i + 3] = j;
    indices[i + 4] = j + 2;
    indices[i + 5] = j + 3;
  }

  indexBuffer = Buffer.createIndexBuffer({
    context: context,
    typedArray: indices,
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  });
  indexBuffer.vertexArrayDestroyable = false;
  context.cache.cloudCollection_indexBufferBatched = indexBuffer;
  return indexBuffer;
}

function getIndexBufferInstanced(context) {
  let indexBuffer = context.cache.cloudCollection_indexBufferInstanced;
  if (defined(indexBuffer)) {
    return indexBuffer;
  }

  indexBuffer = Buffer.createIndexBuffer({
    context: context,
    typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
    usage: BufferUsage.STATIC_DRAW,
    indexDatatype: IndexDatatype.UNSIGNED_SHORT,
  });

  indexBuffer.vertexArrayDestroyable = false;
  context.cache.cloudCollection_indexBufferInstanced = indexBuffer;
  return indexBuffer;
}

function getVertexBufferInstanced(context) {
  let vertexBuffer = context.cache.cloudCollection_vertexBufferInstanced;
  if (defined(vertexBuffer)) {
    return vertexBuffer;
  }

  vertexBuffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: new Float32Array([0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]),
    usage: BufferUsage.STATIC_DRAW,
  });

  vertexBuffer.vertexArrayDestroyable = false;
  context.cache.cloudCollection_vertexBufferInstanced = vertexBuffer;
  return vertexBuffer;
}

function createVAF(context, numberOfClouds, instanced) {
  const attributes = [
    {
      index: attributeLocations.positionHighAndScaleX,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype.FLOAT,
      usage: BufferUsage.STATIC_DRAW,
    },
    {
      index: attributeLocations.positionLowAndScaleY,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype.FLOAT,
      usage: BufferUsage.STATIC_DRAW,
    },
    {
      index: attributeLocations.packedAttribute0,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype.FLOAT,
      usage: BufferUsage.STATIC_DRAW,
    },
    {
      index: attributeLocations.packedAttribute1,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype.FLOAT,
      usage: BufferUsage.STATIC_DRAW,
    },
    {
      index: attributeLocations.color,
      componentsPerAttribute: 4,
      componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
      normalize: true,
      usage: BufferUsage.STATIC_DRAW,
    },
  ];

  if (instanced) {
    attributes.push({
      index: attributeLocations.direction,
      componentsPerAttribute: 2,
      componentDatatype: ComponentDatatype.FLOAT,
      vertexBuffer: getVertexBufferInstanced(context),
    });
  }

  const sizeInVertices = instanced ? numberOfClouds : 4 * numberOfClouds;
  return new VertexArrayFacade(context, attributes, sizeInVertices, instanced);
}

const writePositionScratch = new EncodedCartesian3();

function writePositionAndScale(cloudCollection, frameState, vafWriters, cloud) {
  let i;
  const positionHighWriter =
    vafWriters[attributeLocations.positionHighAndScaleX];
  const positionLowWriter = vafWriters[attributeLocations.positionLowAndScaleY];
  const position = cloud.position;

  EncodedCartesian3.fromCartesian(position, writePositionScratch);
  const scale = cloud.scale;

  const high = writePositionScratch.high;
  const low = writePositionScratch.low;

  if (cloudCollection._instanced) {
    i = cloud._index;
    positionHighWriter(i, high.x, high.y, high.z, scale.x);
    positionLowWriter(i, low.x, low.y, low.z, scale.y);
  } else {
    i = cloud._index * 4;
    positionHighWriter(i + 0, high.x, high.y, high.z, scale.x);
    positionHighWriter(i + 1, high.x, high.y, high.z, scale.x);
    positionHighWriter(i + 2, high.x, high.y, high.z, scale.x);
    positionHighWriter(i + 3, high.x, high.y, high.z, scale.x);

    positionLowWriter(i + 0, low.x, low.y, low.z, scale.y);
    positionLowWriter(i + 1, low.x, low.y, low.z, scale.y);
    positionLowWriter(i + 2, low.x, low.y, low.z, scale.y);
    positionLowWriter(i + 3, low.x, low.y, low.z, scale.y);
  }
}

function writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud) {
  let i;
  const writer = vafWriters[attributeLocations.packedAttribute0];
  const show = cloud.show;
  const brightness = cloud.brightness;

  if (cloudCollection._instanced) {
    i = cloud._index;
    writer(i, show, brightness, 0.0, 0.0);
  } else {
    i = cloud._index * 4;
    writer(i + 0, show, brightness, 0.0, 0.0);
    writer(i + 1, show, brightness, 1.0, 0.0);
    writer(i + 2, show, brightness, 1.0, 1.0);
    writer(i + 3, show, brightness, 0.0, 1.0);
  }
}

function writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud) {
  let i;
  const writer = vafWriters[attributeLocations.packedAttribute1];
  const maximumSize = cloud.maximumSize;
  const slice = cloud.slice;

  if (cloudCollection._instanced) {
    i = cloud._index;
    writer(i, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  } else {
    i = cloud._index * 4;
    writer(i + 0, maximumSize.x, maximumSize.y, maximumSize.z, slice);
    writer(i + 1, maximumSize.x, maximumSize.y, maximumSize.z, slice);
    writer(i + 2, maximumSize.x, maximumSize.y, maximumSize.z, slice);
    writer(i + 3, maximumSize.x, maximumSize.y, maximumSize.z, slice);
  }
}

function writeColor(cloudCollection, frameState, vafWriters, cloud) {
  let i;
  const writer = vafWriters[attributeLocations.color];
  const color = cloud.color;
  const red = Color.floatToByte(color.red);
  const green = Color.floatToByte(color.green);
  const blue = Color.floatToByte(color.blue);
  const alpha = Color.floatToByte(color.alpha);

  if (cloudCollection._instanced) {
    i = cloud._index;
    writer(i, red, green, blue, alpha);
  } else {
    i = cloud._index * 4;
    writer(i + 0, red, green, blue, alpha);
    writer(i + 1, red, green, blue, alpha);
    writer(i + 2, red, green, blue, alpha);
    writer(i + 3, red, green, blue, alpha);
  }
}
function writeCloud(cloudCollection, frameState, vafWriters, cloud) {
  writePositionAndScale(cloudCollection, frameState, vafWriters, cloud);
  writePackedAttribute0(cloudCollection, frameState, vafWriters, cloud);
  writePackedAttribute1(cloudCollection, frameState, vafWriters, cloud);
  writeColor(cloudCollection, frameState, vafWriters, cloud);
}

function createNoiseTexture(cloudCollection, frameState, vsSource, fsSource) {
  const that = cloudCollection;

  const textureSliceWidth = that._textureSliceWidth;
  const noiseTextureRows = that._noiseTextureRows;
  //>>includeStart('debug', pragmas.debug);
  if (
    textureSliceWidth / noiseTextureRows < 1 ||
    textureSliceWidth % noiseTextureRows !== 0
  ) {
    throw new DeveloperError(
      "noiseTextureRows must evenly divide textureSliceWidth"
    );
  }
  //>>includeEnd('debug');

  const context = frameState.context;
  that._vaNoise = createTextureVA(context);
  that._spNoise = ShaderProgram.fromCache({
    context: context,
    vertexShaderSource: vsSource,
    fragmentShaderSource: fsSource,
    attributeLocations: {
      position: 0,
    },
  });

  const noiseDetail = that.noiseDetail;
  const noiseOffset = that.noiseOffset;

  that._noiseTexture = new Texture({
    context: context,
    width: (textureSliceWidth * textureSliceWidth) / noiseTextureRows,
    height: textureSliceWidth * noiseTextureRows,
    pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
    pixelFormat: PixelFormat.RGBA,
    sampler: new Sampler({
      wrapS: TextureWrap.REPEAT,
      wrapT: TextureWrap.REPEAT,
      minificationFilter: TextureMinificationFilter.NEAREST,
      magnificationFilter: TextureMagnificationFilter.NEAREST,
    }),
  });

  const textureCommand = new ComputeCommand({
    vertexArray: that._vaNoise,
    shaderProgram: that._spNoise,
    outputTexture: that._noiseTexture,
    uniformMap: {
      u_noiseTextureDimensions: getNoiseTextureDimensions(that),
      u_noiseDetail: function () {
        return noiseDetail;
      },
      u_noiseOffset: function () {
        return noiseOffset;
      },
    },
    persists: false,
    owner: cloudCollection,
    postExecute: function (texture) {
      that._ready = true;
      that._loading = false;
    },
  });

  frameState.commandList.push(textureCommand);
  that._loading = true;
}

function createVertexArray(cloudCollection, frameState) {
  const that = cloudCollection;
  const context = frameState.context;
  that._createVertexArray = false;
  that._vaf = that._vaf && that._vaf.destroy();

  const clouds = cloudCollection._clouds;
  const cloudsLength = clouds.length;
  if (cloudsLength > 0) {
    that._vaf = createVAF(context, cloudsLength, that._instanced);
    const vafWriters = that._vaf.writers;

    let i;
    // Rewrite entire buffer if clouds were added or removed.
    for (i = 0; i < cloudsLength; ++i) {
      const cloud = clouds[i];
      writeCloud(cloudCollection, frameState, vafWriters, cloud);
    }

    // Different cloud collections share the same index buffer.
    that._vaf.commit(getIndexBuffer(context));
  }
}

const scratchWriterArray = [];

function updateClouds(cloudCollection, frameState) {
  const context = frameState.context;
  const that = cloudCollection;
  const clouds = that._clouds;
  const cloudsLength = clouds.length;
  const cloudsToUpdate = that._cloudsToUpdate;
  const cloudsToUpdateLength = that._cloudsToUpdateIndex;

  const properties = that._propertiesChanged;

  const writers = scratchWriterArray;
  writers.length = 0;

  if (properties[POSITION_INDEX] || properties[SCALE_INDEX]) {
    writers.push(writePositionAndScale);
  }

  if (properties[SHOW_INDEX] || properties[BRIGHTNESS_INDEX]) {
    writers.push(writePackedAttribute0);
  }

  if (properties[MAXIMUM_SIZE_INDEX] || properties[SLICE_INDEX]) {
    writers.push(writePackedAttribute1);
  }

  if (properties[COLOR_INDEX]) {
    writers.push(writeColor);
  }

  const numWriters = writers.length;
  const vafWriters = that._vaf.writers;

  let i, c, w;
  if (cloudsToUpdateLength / cloudsLength > 0.1) {
    // Like BillboardCollection, if more than 10% of clouds change,
    // rewrite the entire buffer.

    for (i = 0; i < cloudsToUpdateLength; ++i) {
      c = cloudsToUpdate[i];
      c._dirty = false;

      for (w = 0; w < numWriters; ++w) {
        writers[w](cloudCollection, frameState, vafWriters, c);
      }
    }

    that._vaf.commit(getIndexBuffer(context));
  } else {
    for (i = 0; i < cloudsToUpdateLength; ++i) {
      c = cloudsToUpdate[i];
      c._dirty = false;

      for (w = 0; w < numWriters; ++w) {
        writers[w](cloudCollection, frameState, vafWriters, c);
      }

      if (that._instanced) {
        that._vaf.subCommit(c._index, 1);
      } else {
        that._vaf.subCommit(c._index * 4, 4);
      }
    }
    that._vaf.endSubCommits();
  }

  that._cloudsToUpdateIndex = 0;
}

function createShaderProgram(cloudCollection, frameState, vsSource, fsSource) {
  const context = frameState.context;
  const that = cloudCollection;
  const vs = new ShaderSource({
    defines: [],
    sources: [vsSource],
  });

  if (that._instanced) {
    vs.defines.push("INSTANCED");
  }

  const fs = new ShaderSource({
    defines: [],
    sources: [fsSource],
  });

  if (that.debugBillboards) {
    fs.defines.push("DEBUG_BILLBOARDS");
  }

  if (that.debugEllipsoids) {
    fs.defines.push("DEBUG_ELLIPSOIDS");
  }

  that._sp = ShaderProgram.replaceCache({
    context: context,
    shaderProgram: that._sp,
    vertexShaderSource: vs,
    fragmentShaderSource: fs,
    attributeLocations: attributeLocations,
  });

  that._rs = RenderState.fromCache({
    depthTest: {
      enabled: true,
      func: WebGLConstants.LESS,
    },
    depthMask: false,
    blending: BlendingState.ALPHA_BLEND,
  });

  that._spCreated = true;
  that._compiledDebugBillboards = that.debugBillboards;
  that._compiledDebugEllipsoids = that.debugEllipsoids;
}

function createDrawCommands(cloudCollection, frameState) {
  const that = cloudCollection;
  const pass = frameState.passes;
  const uniforms = that._uniforms;
  const commandList = frameState.commandList;
  if (pass.render) {
    const colorList = that._colorCommands;

    const va = that._vaf.va;
    const vaLength = va.length;
    colorList.length = vaLength;
    for (let i = 0; i < vaLength; i++) {
      let command = colorList[i];
      if (!defined(command)) {
        command = colorList[i] = new DrawCommand();
      }
      command.pass = Pass.TRANSLUCENT;
      command.owner = cloudCollection;
      command.uniformMap = uniforms;
      command.count = va[i].indicesCount;
      command.vertexArray = va[i].va;
      command.shaderProgram = that._sp;
      command.renderState = that._rs;
      if (that._instanced) {
        command.count = 6;
        command.instanceCount = that._clouds.length;
      }

      commandList.push(command);
    }
  }
}

/**
 * @private
 */
CloudCollection.prototype.update = function (frameState) {
  removeClouds(this);
  if (!this.show) {
    return;
  }

  const debugging = this.debugBillboards || this.debugEllipsoids;
  this._ready = debugging ? true : defined(this._noiseTexture);

  if (!this._ready && !this._loading && !debugging) {
    createNoiseTexture(this, frameState, CloudNoiseVS, CloudNoiseFS);
  }

  this._instanced = frameState.context.instancedArrays;
  attributeLocations = this._instanced
    ? attributeLocationsInstanced
    : attributeLocationsBatched;
  getIndexBuffer = this._instanced
    ? getIndexBufferInstanced
    : getIndexBufferBatched;

  const clouds = this._clouds;
  const cloudsLength = clouds.length;
  const cloudsToUpdate = this._cloudsToUpdate;
  const cloudsToUpdateLength = this._cloudsToUpdateIndex;

  if (this._createVertexArray) {
    createVertexArray(this, frameState);
  } else if (cloudsToUpdateLength > 0) {
    // Clouds were modified, but none were added or removed.
    updateClouds(this, frameState);
  }

  // If the number of total clouds ever shrinks considerably,
  // truncate cloudsToUpdate so that we free memory that
  // we are no longer using.
  if (cloudsToUpdateLength > cloudsLength * 1.5) {
    cloudsToUpdate.length = cloudsLength;
  }

  if (
    !defined(this._vaf) ||
    !defined(this._vaf.va) ||
    !this._ready & !debugging
  ) {
    return;
  }

  if (
    !this._spCreated ||
    this.debugBillboards !== this._compiledDebugBillboards ||
    this.debugEllipsoids !== this._compiledDebugEllipsoids
  ) {
    createShaderProgram(this, frameState, CloudCollectionVS, CloudCollectionFS);
  }

  createDrawCommands(this, frameState);
};

/**
 * Returns true if this object was destroyed; otherwise, false.
 *

 * If this object was destroyed, it should not be used; calling any function other than
 * isDestroyed will result in a {@link DeveloperError} exception.
 *
 * @returns {Boolean} true if this object was destroyed; otherwise, false.
 *
 * @see CloudCollection#destroy
 */
CloudCollection.prototype.isDestroyed = function () {
  return false;
};

/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 *

 * Once an object is destroyed, it should not be used; calling any function other than
 * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (undefined) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * clouds = clouds && clouds.destroy();
 *
 * @see CloudCollection#isDestroyed
 */
CloudCollection.prototype.destroy = function () {
  this._noiseTexture = this._noiseTexture && this._noiseTexture.destroy();
  this._sp = this._sp && this._sp.destroy();
  this._vaf = this._vaf && this._vaf.destroy();

  destroyClouds(this._clouds);

  return destroyObject(this);
};

export default CloudCollection;


text:
package org.orekit.propagation.events;

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.orekit.Utils;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.TopocentricFrame;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.analytical.EcksteinHechlerPropagator;
import org.orekit.propagation.events.EventsLogger.LoggedEvent;
import org.orekit.propagation.events.handlers.ContinueOnEvent;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;

public class ElevationExtremumDetectorTest {

    @Test
    public void testLEO() {

        final OneAxisEllipsoid earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                                                            Constants.WGS84_EARTH_FLATTENING,
                                                            FramesFactory.getITRF(IERSConventions.IERS_2010, true));

        final GeodeticPoint gp = new GeodeticPoint(FastMath.toRadians(51.0), FastMath.toRadians(66.6), 300.0);
        final ElevationExtremumDetector raw =
                new ElevationExtremumDetector(new TopocentricFrame(earth, gp, "test")).
                withMaxCheck(60).
                withThreshold(1.e-6).
                withHandler(new ContinueOnEvent<ElevationExtremumDetector>());
        final EventSlopeFilter<ElevationExtremumDetector> maxElevationDetector =
                new EventSlopeFilter<ElevationExtremumDetector>(raw, FilterType.TRIGGER_ONLY_DECREASING_EVENTS);

        Assertions.assertEquals(60.0, raw.getMaxCheckInterval(), 1.0e-15);
        Assertions.assertEquals(1.0e-6, raw.getThreshold(), 1.0e-15);
        Assertions.assertEquals(AbstractDetector.DEFAULT_MAX_ITER, raw.getMaxIterationCount());
        Assertions.assertEquals("test", raw.getTopocentricFrame().getName());

        final TimeScale utc = TimeScalesFactory.getUTC();
        final Vector3D position = new Vector3D(-6142438.668, 3492467.56, -25767.257);
        final Vector3D velocity = new Vector3D(505.848, 942.781, 7435.922);
        final AbsoluteDate date = new AbsoluteDate(2003, 9, 16, utc);
        final Orbit orbit = new EquinoctialOrbit(new PVCoordinates(position,  velocity),
                                                 FramesFactory.getEME2000(), date,
                                                 Constants.EIGEN5C_EARTH_MU);

        Propagator propagator =
            new EcksteinHechlerPropagator(orbit,
                                          Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS,
                                          Constants.EIGEN5C_EARTH_MU,
                                          Constants.EIGEN5C_EARTH_C20,
                                          Constants.EIGEN5C_EARTH_C30,
                                          Constants.EIGEN5C_EARTH_C40,
                                          Constants.EIGEN5C_EARTH_C50,
                                          Constants.EIGEN5C_EARTH_C60);

        EventsLogger logger = new EventsLogger();
        propagator.addEventDetector(logger.monitorDetector(maxElevationDetector));

        propagator.propagate(date.shiftedBy(Constants.JULIAN_DAY));
        int visibleEvents = 0;
        for (LoggedEvent e : logger.getLoggedEvents()) {
            final double eMinus = raw.getElevation(e.getState().shiftedBy(-10.0));
            final double e0     = raw.getElevation(e.getState());
            final double ePlus  = raw.getElevation(e.getState().shiftedBy(+10.0));
            if (e0 > FastMath.toRadians(5.0)) {
                ++visibleEvents;
            }
            Assertions.assertTrue(e0 > eMinus);
            Assertions.assertTrue(e0 > ePlus);
        }
        Assertions.assertEquals(15, logger.getLoggedEvents().size());
        Assertions.assertEquals( 6, visibleEvents);

    }

    @BeforeEach
    public void setUp() {
        Utils.setDataRoot("regular-data");
    }

}


text:
using System.Runtime.CompilerServices;

[assembly:InternalsVisibleTo("Deputy.UnitTests")]


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Web;
using Semver;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Migrations.Upgrade;
using Umbraco.Core.Persistence;
using Umbraco.Core.Services.Implement;
using Umbraco.Core.Sync;

namespace Umbraco.Core
{
    /// <summary>
    /// Represents the state of the Umbraco runtime.
    /// </summary>
    internal class RuntimeState : IRuntimeState
    {
        private readonly ILogger _logger;
        private readonly IUmbracoSettingsSection _settings;
        private readonly IGlobalSettings _globalSettings;
        private readonly HashSet<string> _applicationUrls = new HashSet<string>();
        private readonly Lazy<IMainDom> _mainDom;
        private readonly Lazy<IServerRegistrar> _serverRegistrar;
        private RuntimeLevel _level = RuntimeLevel.Unknown;

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeState"/> class.
        /// </summary>
        public RuntimeState(ILogger logger, IUmbracoSettingsSection settings, IGlobalSettings globalSettings,
            Lazy<IMainDom> mainDom, Lazy<IServerRegistrar> serverRegistrar)
        {
            _logger = logger;
            _settings = settings;
            _globalSettings = globalSettings;
            _mainDom = mainDom;
            _serverRegistrar = serverRegistrar;
        }

        /// <summary>
        /// Gets the server registrar.
        /// </summary>
        /// <remarks>
        /// <para>This is NOT exposed in the interface.</para>
        /// </remarks>
        private IServerRegistrar ServerRegistrar => _serverRegistrar.Value;

        /// <summary>
        /// Gets the application MainDom.
        /// </summary>
        /// <remarks>
        /// <para>This is NOT exposed in the interface as MainDom is internal.</para>
        /// </remarks>
        public IMainDom MainDom => _mainDom.Value;

        /// <inheritdoc />
        public Version Version => UmbracoVersion.Current;

        /// <inheritdoc />
        public string VersionComment => UmbracoVersion.Comment;

        /// <inheritdoc />
        public SemVersion SemanticVersion => UmbracoVersion.SemanticVersion;

        /// <inheritdoc />
        public bool Debug { get; } = GlobalSettings.DebugMode;

        /// <inheritdoc />
        public bool IsMainDom => MainDom.IsMainDom;

        /// <inheritdoc />
        public ServerRole ServerRole => ServerRegistrar.GetCurrentServerRole();

        /// <inheritdoc />
        public Uri ApplicationUrl { get; private set; }

        /// <inheritdoc />
        public string ApplicationVirtualPath { get; } = HttpRuntime.AppDomainAppVirtualPath;

        /// <inheritdoc />
        public string CurrentMigrationState { get; internal set; }

        /// <inheritdoc />
        public string FinalMigrationState { get; internal set; }

        /// <inheritdoc />
        public RuntimeLevel Level
        {
            get => _level;
            internal set { _level = value; if (value == RuntimeLevel.Run) _runLevel.Set(); }
        }

        /// <summary>
        /// Ensures that the <see cref="ApplicationUrl"/> property has a value.
        /// </summary>
        /// <param name="request"></param>
        internal void EnsureApplicationUrl(HttpRequestBase request = null)
        {
            // see U4-10626 - in some cases we want to reset the application url
            // (this is a simplified version of what was in 7.x)
            // note: should this be optional? is it expensive?
            var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request, _globalSettings);
            var change = url != null && !_applicationUrls.Contains(url);
            if (change)
            {
                _logger.Info(typeof(ApplicationUrlHelper), "New url {Url} detected, re-discovering application url.", url);
                _applicationUrls.Add(url);
            }

            if (ApplicationUrl != null && !change) return;
            ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, _globalSettings, _settings, ServerRegistrar, request));
        }

        private readonly ManualResetEventSlim _runLevel = new ManualResetEventSlim(false);

        /// <summary>
        /// Waits for the runtime level to become RuntimeLevel.Run.
        /// </summary>
        /// <param name="timeout">A timeout.</param>
        /// <returns>True if the runtime level became RuntimeLevel.Run before the timeout, otherwise false.</returns>
        internal bool WaitForRunLevel(TimeSpan timeout)
        {
            return _runLevel.WaitHandle.WaitOne(timeout);
        }

        /// <inheritdoc />
        public BootFailedException BootFailedException { get; internal set; }

        /// <summary>
        /// Determines the runtime level.
        /// </summary>
        public void DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, ILogger logger)
        {
            var localVersion = UmbracoVersion.LocalVersion; // the local, files, version
            var codeVersion = SemanticVersion; // the executing code version
            var connect = false;

            if (localVersion == null)
            {
                // there is no local version, we are not installed
                logger.Debug<RuntimeState>("No local version, need to install Umbraco.");
                Level = RuntimeLevel.Install;
                return;
            }

            if (localVersion < codeVersion)
            {
                // there *is* a local version, but it does not match the code version
                // need to upgrade
                logger.Debug<RuntimeState>("Local version '{LocalVersion}' < code version '{CodeVersion}', need to upgrade Umbraco.", localVersion, codeVersion);
                Level = RuntimeLevel.Upgrade;
            }
            else if (localVersion > codeVersion)
            {
                logger.Warn<RuntimeState>("Local version '{LocalVersion}' > code version '{CodeVersion}', downgrading is not supported.", localVersion, codeVersion);

                // in fact, this is bad enough that we want to throw
                throw new BootFailedException($"Local version \"{localVersion}\" > code version \"{codeVersion}\", downgrading is not supported.");
            }
            else if (databaseFactory.Configured == false)
            {
                // local version *does* match code version, but the database is not configured
                // install (again? this is a weird situation...)
                logger.Debug<RuntimeState>("Database is not configured, need to install Umbraco.");
                Level = RuntimeLevel.Install;
                return;
            }

            // else, keep going,
            // anything other than install wants a database - see if we can connect
            // (since this is an already existing database, assume localdb is ready)
            for (var i = 0; i < 5; i++)
            {
                connect = databaseFactory.CanConnect;
                if (connect) break;
                logger.Debug<RuntimeState>("Could not immediately connect to database, trying again.");
                Thread.Sleep(1000);
            }

            if (connect == false)
            {
                // cannot connect to configured database, this is bad, fail
                logger.Debug<RuntimeState>("Could not connect to database.");

                // in fact, this is bad enough that we want to throw
                throw new BootFailedException("A connection string is configured but Umbraco could not connect to the database.");
            }

            // if we already know we want to upgrade,
            // still run EnsureUmbracoUpgradeState to get the states
            // (v7 will just get a null state, that's ok)

            // else
            // look for a matching migration entry - bypassing services entirely - they are not 'up' yet
            // fixme - in a LB scenario, ensure that the DB gets upgraded only once!
            bool noUpgrade;
            try
            {
                noUpgrade = EnsureUmbracoUpgradeState(databaseFactory, logger);
            }
            catch (Exception e)
            {
                // can connect to the database but cannot check the upgrade state... oops
                logger.Warn<RuntimeState>(e, "Could not check the upgrade state.");
                throw new BootFailedException("Could not check the upgrade state.", e);
            }

            if (noUpgrade)
            {
                // the database version matches the code & files version, all clear, can run
                Level = RuntimeLevel.Run;
                return;
            }

            // the db version does not match... but we do have a migration table
            // so, at least one valid table, so we quite probably are installed & need to upgrade

            // although the files version matches the code version, the database version does not
            // which means the local files have been upgraded but not the database - need to upgrade
            logger.Debug<RuntimeState>("Has not reached the final upgrade step, need to upgrade Umbraco.");
            Level = RuntimeLevel.Upgrade;
        }

        protected virtual bool EnsureUmbracoUpgradeState(IUmbracoDatabaseFactory databaseFactory, ILogger logger)
        {
            var upgrader = new UmbracoUpgrader();
            var stateValueKey = upgrader.StateValueKey;

            // no scope, no service - just directly accessing the database
            using (var database = databaseFactory.CreateDatabase())
            {
                CurrentMigrationState = KeyValueService.GetValue(database, stateValueKey);
                FinalMigrationState = upgrader.Plan.FinalState;
            }

            logger.Debug<RuntimeState>("Final upgrade state is {FinalMigrationState}, database contains {DatabaseState}", CurrentMigrationState, FinalMigrationState ?? "<null>");

            return CurrentMigrationState == FinalMigrationState;
        }
    }
}


text:
using System.Collections.Generic;
using Microsoft.AspNet.Identity;

namespace TotaMoviesRental.Core.ViewModels
{
    public class IndexViewModel
    {
        public bool HasPassword { get; set; }
        public IList<UserLoginInfo> Logins { get; set; }
        public string PhoneNumber { get; set; }
        public bool TwoFactor { get; set; }
        public bool BrowserRemembered { get; set; }
    }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<script>
(function () {
  var DATE_CACHE = {};

  Polymer({
    is: 'ha-logbook-data',

    properties: {
      hass: {
        type: Object,
        observer: 'hassChanged',
      },

      filterDate: {
        type: String,
        observer: 'filterDateChanged',
      },

      isLoading: {
        type: Boolean,
        value: true,
        readOnly: true,
        notify: true,
      },

      entries: {
        type: Object,
        value: null,
        readOnly: true,
        notify: true,
      },
    },

    hassChanged: function (newHass, oldHass) {
      if (!oldHass && this.filterDate) {
        this.filterDateChanged(this.filterDate);
      }
    },

    filterDateChanged: function (filterDate) {
      if (!this.hass) return;

      this._setIsLoading(true);

      this.getDate(filterDate).then(function (logbookEntries) {
        this._setEntries(logbookEntries);
        this._setIsLoading(false);
      }.bind(this));
    },

    getDate: function (date) {
      if (!DATE_CACHE[date]) {
        DATE_CACHE[date] = this.hass.callApi('GET', 'logbook/' + date).then(
          function (logbookEntries) {
            logbookEntries.reverse();
            return logbookEntries;
          },
          function () {
            DATE_CACHE[date] = false;
            return null;
          }
        );
      }

      return DATE_CACHE[date];
    },
  });
}());
</script>


text:
package org.opencds.vmr.v1_0.internal.concepts;

public class RaceConcept extends VmrOpenCdsConcept {

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "RaceConcept [Id=" + Id + ", conceptTargetId=" + conceptTargetId
				+ ", openCdsConceptCode=" + openCdsConceptCode
				+ ", determinationMethodCode=" + determinationMethodCode + "]";
	}
}


text:
package org.camunda.bpm.integrationtest.functional.cdi;

import org.camunda.bpm.engine.cdi.impl.util.ProgrammaticBeanLookup;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.integrationtest.functional.cdi.beans.ExampleSignallableActivityBehaviorBean;
import org.camunda.bpm.integrationtest.util.AbstractFoxPlatformIntegrationTest;
import org.camunda.bpm.integrationtest.util.DeploymentHelper;
import org.camunda.bpm.integrationtest.util.TestContainer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 *
 *
 * @author Daniel Meyer
 *
 */
@RunWith(Arquillian.class)
public class CdiBeanSignallableActivityBehaviorResolutionTest extends AbstractFoxPlatformIntegrationTest {

  @Deployment
  public static WebArchive createProcessArchiveDeplyoment() {
    return initWebArchiveDeployment()
            .addClass(ExampleSignallableActivityBehaviorBean.class)
            .addAsResource("org/camunda/bpm/integrationtest/functional/cdi/CdiBeanSignallableActivityBehaviorResolutionTest.testResolveBean.bpmn20.xml");
  }

  @Deployment(name="clientDeployment")
  public static WebArchive clientDeployment() {
    WebArchive deployment = ShrinkWrap.create(WebArchive.class, "client.war")
            .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
            .addClass(AbstractFoxPlatformIntegrationTest.class)
            .addAsLibraries(DeploymentHelper.getEngineCdi());

    TestContainer.addContainerSpecificResourcesForNonPa(deployment);

    return deployment;
  }

  @Test
  @OperateOnDeployment("clientDeployment")
  public void testResolveClass() {
    // assert that we cannot resolve the bean here:
    Assert.assertNull(ProgrammaticBeanLookup.lookup("exampleSignallableActivityBehaviorBean"));

    // but the process can since it performs context switch to the process archive for execution
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testResolveBean");

    runtimeService.signal(processInstance.getId());

  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Generator" content="Bashworks mdocs" />
<title>foomodule Documentation - Bashworks</title>

Files

foomodule/source.sh

Module index

        Show/Hide

example

foomodule

foomodule documentation

Files


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

import { DashboardComponent }   from './components/dashboard/dashboard.component';
import { HeroesComponent }      from './components/heroes/heroes.component';
import { HeroDetailComponent }  from './components/heroDetail/hero-detail.component';
import { HomepageComponent }  from './components/homepage/homepage.component';

const appRoutes: Routes = [
  {
    path: '',
    redirectTo: '/homepage',
    pathMatch: 'full'
  },
  {
    path: 'homepage',
    component: HomepageComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent
  },
  {
    path: 'detail/:id',
    component: HeroDetailComponent
  },
  {
    path: 'heroes',
    component: HeroesComponent
  }
];

export const routing = RouterModule.forRoot(appRoutes, { useHash: true });


text:
Returns the index at which value is last found in array.  If fromIndex is given, it starts its search at that point.

###Arguments

array (Array): The array to search.

value : The value to search for.

fromIndex = 0 (number) : An optional start index

###returns

(number): Returns the index where value is found.

```javascript
bland.lastIndexOf([2,4,8,9,4],4)
// => 4

bland.lastIndexOf([2,4,8,9,4],4,2)
// => 2

```