text:
package org.apache.nifi.controller.status;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class ProcessGroupStatus implements Cloneable {

    private String id;
    private String name;
    private Integer inputCount;
    private Long inputContentSize;
    private Integer outputCount;
    private Long outputContentSize;
    private Integer activeThreadCount;
    private Integer queuedCount;
    private Long queuedContentSize;
    private Long bytesRead;
    private Long bytesWritten;
    private int flowFilesReceived;
    private long bytesReceived;
    private int flowFilesSent;
    private long bytesSent;
    private int flowFilesTransferred;
    private long bytesTransferred;

    private Collection<ConnectionStatus> connectionStatus = new ArrayList<>();
    private Collection<ProcessorStatus> processorStatus = new ArrayList<>();
    private Collection<ProcessGroupStatus> processGroupStatus = new ArrayList<>();
    private Collection<RemoteProcessGroupStatus> remoteProcessGroupStatus = new ArrayList<>();
    private Collection<PortStatus> inputPortStatus = new ArrayList<>();
    private Collection<PortStatus> outputPortStatus = new ArrayList<>();

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getInputCount() {
        return inputCount;
    }

    public void setInputCount(final Integer inputCount) {
        this.inputCount = inputCount;
    }

    public Long getInputContentSize() {
        return inputContentSize;
    }

    public void setInputContentSize(final Long inputContentSize) {
        this.inputContentSize = inputContentSize;
    }

    public Integer getOutputCount() {
        return outputCount;
    }

    public void setOutputCount(final Integer outputCount) {
        this.outputCount = outputCount;
    }

    public Long getOutputContentSize() {
        return outputContentSize;
    }

    public void setOutputContentSize(final Long outputContentSize) {
        this.outputContentSize = outputContentSize;
    }

    public Long getBytesRead() {
        return bytesRead;
    }

    public void setBytesRead(final Long bytesRead) {
        this.bytesRead = bytesRead;
    }

    public Long getBytesWritten() {
        return bytesWritten;
    }

    public void setBytesWritten(final Long bytesWritten) {
        this.bytesWritten = bytesWritten;
    }

    public Integer getQueuedCount() {
        return this.queuedCount;
    }

    public void setQueuedCount(final Integer queuedCount) {
        this.queuedCount = queuedCount;
    }

    public Long getQueuedContentSize() {
        return queuedContentSize;
    }

    public void setQueuedContentSize(final Long queuedContentSize) {
        this.queuedContentSize = queuedContentSize;
    }

    public Integer getActiveThreadCount() {
        return activeThreadCount;
    }

    public void setActiveThreadCount(final Integer activeThreadCount) {
        this.activeThreadCount = activeThreadCount;
    }

    public Collection<ConnectionStatus> getConnectionStatus() {
        return connectionStatus;
    }

    public void setConnectionStatus(final Collection<ConnectionStatus> connectionStatus) {
        this.connectionStatus = connectionStatus;
    }

    public Collection<ProcessorStatus> getProcessorStatus() {
        return processorStatus;
    }

    public void setProcessorStatus(final Collection<ProcessorStatus> processorStatus) {
        this.processorStatus = processorStatus;
    }

    public Collection<ProcessGroupStatus> getProcessGroupStatus() {
        return processGroupStatus;
    }

    public void setProcessGroupStatus(final Collection<ProcessGroupStatus> processGroupStatus) {
        this.processGroupStatus = processGroupStatus;
    }

    public Collection<PortStatus> getInputPortStatus() {
        return inputPortStatus;
    }

    public void setInputPortStatus(Collection<PortStatus> inputPortStatus) {
        this.inputPortStatus = inputPortStatus;
    }

    public Collection<PortStatus> getOutputPortStatus() {
        return outputPortStatus;
    }

    public void setOutputPortStatus(Collection<PortStatus> outputPortStatus) {
        this.outputPortStatus = outputPortStatus;
    }

    public Collection<RemoteProcessGroupStatus> getRemoteProcessGroupStatus() {
        return remoteProcessGroupStatus;
    }

    public void setRemoteProcessGroupStatus(final Collection<RemoteProcessGroupStatus> remoteProcessGroupStatus) {
        this.remoteProcessGroupStatus = remoteProcessGroupStatus;
    }

    public int getFlowFilesReceived() {
        return flowFilesReceived;
    }

    public void setFlowFilesReceived(final int flowFilesReceived) {
        this.flowFilesReceived = flowFilesReceived;
    }

    public long getBytesReceived() {
        return bytesReceived;
    }

    public void setBytesReceived(final long bytesReceived) {
        this.bytesReceived = bytesReceived;
    }

    public int getFlowFilesSent() {
        return flowFilesSent;
    }

    public void setFlowFilesSent(final int flowFilesSent) {
        this.flowFilesSent = flowFilesSent;
    }

    public long getBytesSent() {
        return bytesSent;
    }

    public void setBytesSent(final long bytesSent) {
        this.bytesSent = bytesSent;
    }

    public int getFlowFilesTransferred() {
        return flowFilesTransferred;
    }

    public void setFlowFilesTransferred(int flowFilesTransferred) {
        this.flowFilesTransferred = flowFilesTransferred;
    }

    public long getBytesTransferred() {
        return bytesTransferred;
    }

    public void setBytesTransferred(long bytesTransferred) {
        this.bytesTransferred = bytesTransferred;
    }

    @Override
    public ProcessGroupStatus clone() {

        final ProcessGroupStatus clonedObj = new ProcessGroupStatus();

        clonedObj.id = id;
        clonedObj.name = name;
        clonedObj.outputContentSize = outputContentSize;
        clonedObj.outputCount = outputCount;
        clonedObj.inputContentSize = inputContentSize;
        clonedObj.inputCount = inputCount;
        clonedObj.activeThreadCount = activeThreadCount;
        clonedObj.queuedContentSize = queuedContentSize;
        clonedObj.queuedCount = queuedCount;
        clonedObj.bytesRead = bytesRead;
        clonedObj.bytesWritten = bytesWritten;
        clonedObj.flowFilesReceived = flowFilesReceived;
        clonedObj.bytesReceived = bytesReceived;
        clonedObj.flowFilesSent = flowFilesSent;
        clonedObj.bytesSent = bytesSent;
        clonedObj.flowFilesTransferred = flowFilesTransferred;
        clonedObj.bytesTransferred = bytesTransferred;

        if (connectionStatus != null) {
            final Collection<ConnectionStatus> statusList = new ArrayList<>();
            clonedObj.setConnectionStatus(statusList);
            for (final ConnectionStatus status : connectionStatus) {
                statusList.add(status.clone());
            }
        }

        if (processorStatus != null) {
            final Collection<ProcessorStatus> statusList = new ArrayList<>();
            clonedObj.setProcessorStatus(statusList);
            for (final ProcessorStatus status : processorStatus) {
                statusList.add(status.clone());
            }
        }

        if (inputPortStatus != null) {
            final Collection<PortStatus> statusList = new ArrayList<>();
            clonedObj.setInputPortStatus(statusList);
            for (final PortStatus status : inputPortStatus) {
                statusList.add(status.clone());
            }
        }

        if (outputPortStatus != null) {
            final Collection<PortStatus> statusList = new ArrayList<>();
            clonedObj.setOutputPortStatus(statusList);
            for (final PortStatus status : outputPortStatus) {
                statusList.add(status.clone());
            }
        }

        if (processGroupStatus != null) {
            final Collection<ProcessGroupStatus> statusList = new ArrayList<>();
            clonedObj.setProcessGroupStatus(statusList);
            for (final ProcessGroupStatus status : processGroupStatus) {
                statusList.add(status.clone());
            }
        }

        if (remoteProcessGroupStatus != null) {
            final Collection<RemoteProcessGroupStatus> statusList = new ArrayList<>();
            clonedObj.setRemoteProcessGroupStatus(statusList);
            for (final RemoteProcessGroupStatus status : remoteProcessGroupStatus) {
                statusList.add(status.clone());
            }
        }

        return clonedObj;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("ProcessGroupStatus [id=");
        builder.append(id);
        builder.append(", inputCount=");
        builder.append(inputCount);
        builder.append(", inputBytes=");
        builder.append(inputContentSize);
        builder.append(", outputCount=");
        builder.append(outputCount);
        builder.append(", outputBytes=");
        builder.append(outputContentSize);
        builder.append(", activeThreadCount=");
        builder.append(activeThreadCount);
        builder.append(", flowFilesTransferred=");
        builder.append(flowFilesTransferred);
        builder.append(", bytesTransferred=");
        builder.append(bytesTransferred);
        builder.append(", flowFilesReceived=");
        builder.append(flowFilesReceived);
        builder.append(", bytesReceived=");
        builder.append(bytesReceived);
        builder.append(", flowFilesSent=");
        builder.append(flowFilesSent);
        builder.append(", bytesSent=");
        builder.append(bytesSent);
        builder.append(",\n\tconnectionStatus=");

        for (final ConnectionStatus status : connectionStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append(",\n\tprocessorStatus=");

        for (final ProcessorStatus status : processorStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append(",\n\tprocessGroupStatus=");

        for (final ProcessGroupStatus status : processGroupStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append(",\n\tremoteProcessGroupStatus=");
        for (final RemoteProcessGroupStatus status : remoteProcessGroupStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append(",\n\tinputPortStatus=");
        for (final PortStatus status : inputPortStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append(",\n\toutputPortStatus=");
        for (final PortStatus status : outputPortStatus) {
            builder.append("\n\t\t");
            builder.append(status);
        }

        builder.append("]");
        return builder.toString();
    }

    public static void merge(final ProcessGroupStatus target, final ProcessGroupStatus toMerge) {
        if (target == null || toMerge == null) {
            return;
        }

        target.setInputCount(target.getInputCount() + toMerge.getInputCount());
        target.setInputContentSize(target.getInputContentSize() + toMerge.getInputContentSize());
        target.setOutputCount(target.getOutputCount() + toMerge.getOutputCount());
        target.setOutputContentSize(target.getOutputContentSize() + toMerge.getOutputContentSize());
        target.setQueuedCount(target.getQueuedCount() + toMerge.getQueuedCount());
        target.setQueuedContentSize(target.getQueuedContentSize() + toMerge.getQueuedContentSize());
        target.setBytesRead(target.getBytesRead() + toMerge.getBytesRead());
        target.setBytesWritten(target.getBytesWritten() + toMerge.getBytesWritten());
        target.setActiveThreadCount(target.getActiveThreadCount() + toMerge.getActiveThreadCount());
        target.setFlowFilesTransferred(target.getFlowFilesTransferred() + toMerge.getFlowFilesTransferred());
        target.setBytesTransferred(target.getBytesTransferred() + toMerge.getBytesTransferred());
        target.setFlowFilesReceived(target.getFlowFilesReceived() + toMerge.getFlowFilesReceived());
        target.setBytesReceived(target.getBytesReceived() + toMerge.getBytesReceived());
        target.setFlowFilesSent(target.getFlowFilesSent() + toMerge.getFlowFilesSent());
        target.setBytesSent(target.getBytesSent() + toMerge.getBytesSent());

        // connection status
        // sort by id
        final Map<String, ConnectionStatus> mergedConnectionMap = new HashMap<>();
        for (final ConnectionStatus status : target.getConnectionStatus()) {
            mergedConnectionMap.put(status.getId(), status);
        }

        for (final ConnectionStatus statusToMerge : toMerge.getConnectionStatus()) {
            ConnectionStatus merged = mergedConnectionMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedConnectionMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            merged.setQueuedCount(merged.getQueuedCount() + statusToMerge.getQueuedCount());
            merged.setQueuedBytes(merged.getQueuedBytes() + statusToMerge.getQueuedBytes());
            merged.setInputCount(merged.getInputCount() + statusToMerge.getInputCount());
            merged.setInputBytes(merged.getInputBytes() + statusToMerge.getInputBytes());
            merged.setOutputCount(merged.getOutputCount() + statusToMerge.getOutputCount());
            merged.setOutputBytes(merged.getOutputBytes() + statusToMerge.getOutputBytes());
        }
        target.setConnectionStatus(mergedConnectionMap.values());

        // processor status
        final Map<String, ProcessorStatus> mergedProcessorMap = new HashMap<>();
        for (final ProcessorStatus status : target.getProcessorStatus()) {
            mergedProcessorMap.put(status.getId(), status);
        }

        for (final ProcessorStatus statusToMerge : toMerge.getProcessorStatus()) {
            ProcessorStatus merged = mergedProcessorMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedProcessorMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            merged.setActiveThreadCount(merged.getActiveThreadCount() + statusToMerge.getActiveThreadCount());
            merged.setBytesRead(merged.getBytesRead() + statusToMerge.getBytesRead());
            merged.setBytesWritten(merged.getBytesWritten() + statusToMerge.getBytesWritten());
            merged.setInputBytes(merged.getInputBytes() + statusToMerge.getInputBytes());
            merged.setInputCount(merged.getInputCount() + statusToMerge.getInputCount());
            merged.setInvocations(merged.getInvocations() + statusToMerge.getInvocations());
            merged.setOutputBytes(merged.getOutputBytes() + statusToMerge.getOutputBytes());
            merged.setOutputCount(merged.getOutputCount() + statusToMerge.getOutputCount());
            merged.setProcessingNanos(merged.getProcessingNanos() + statusToMerge.getProcessingNanos());
            merged.setFlowFilesRemoved(merged.getFlowFilesRemoved() + statusToMerge.getFlowFilesRemoved());

            // if the status to merge is invalid allow it to take precedence. whether the
            // processor run status is disabled/stopped/running is part of the flow configuration
            // and should not differ amongst nodes. however, whether a processor is invalid
            // can be driven by environmental conditions. this check allows any of those to
            // take precedence over the configured run status.
            if (RunStatus.Invalid.equals(statusToMerge.getRunStatus())) {
                merged.setRunStatus(RunStatus.Invalid);
            }
        }
        target.setProcessorStatus(mergedProcessorMap.values());

        // input ports
        final Map<String, PortStatus> mergedInputPortMap = new HashMap<>();
        for (final PortStatus status : target.getInputPortStatus()) {
            mergedInputPortMap.put(status.getId(), status);
        }

        for (final PortStatus statusToMerge : toMerge.getInputPortStatus()) {
            PortStatus merged = mergedInputPortMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedInputPortMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            merged.setInputBytes(merged.getInputBytes() + statusToMerge.getInputBytes());
            merged.setInputCount(merged.getInputCount() + statusToMerge.getInputCount());
            merged.setOutputBytes(merged.getOutputBytes() + statusToMerge.getOutputBytes());
            merged.setOutputCount(merged.getOutputCount() + statusToMerge.getOutputCount());
            merged.setActiveThreadCount(merged.getActiveThreadCount() + statusToMerge.getActiveThreadCount());
            if (statusToMerge.isTransmitting() != null && statusToMerge.isTransmitting()) {
                merged.setTransmitting(true);
            }

            // should be unnecessary here since ports run status should not be affected by
            // environmental conditions but doing so in case that changes
            if (RunStatus.Invalid.equals(statusToMerge.getRunStatus())) {
                merged.setRunStatus(RunStatus.Invalid);
            }
        }
        target.setInputPortStatus(mergedInputPortMap.values());

        // output ports
        final Map<String, PortStatus> mergedOutputPortMap = new HashMap<>();
        for (final PortStatus status : target.getOutputPortStatus()) {
            mergedOutputPortMap.put(status.getId(), status);
        }

        for (final PortStatus statusToMerge : toMerge.getOutputPortStatus()) {
            PortStatus merged = mergedOutputPortMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedOutputPortMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            merged.setInputBytes(merged.getInputBytes() + statusToMerge.getInputBytes());
            merged.setInputCount(merged.getInputCount() + statusToMerge.getInputCount());
            merged.setOutputBytes(merged.getOutputBytes() + statusToMerge.getOutputBytes());
            merged.setOutputCount(merged.getOutputCount() + statusToMerge.getOutputCount());
            merged.setActiveThreadCount(merged.getActiveThreadCount() + statusToMerge.getActiveThreadCount());
            if (statusToMerge.isTransmitting() != null && statusToMerge.isTransmitting()) {
                merged.setTransmitting(true);
            }

            // should be unnecessary here since ports run status not should be affected by
            // environmental conditions but doing so in case that changes
            if (RunStatus.Invalid.equals(statusToMerge.getRunStatus())) {
                merged.setRunStatus(RunStatus.Invalid);
            }
        }
        target.setOutputPortStatus(mergedOutputPortMap.values());

        // child groups
        final Map<String, ProcessGroupStatus> mergedGroupMap = new HashMap<>();
        for (final ProcessGroupStatus status : target.getProcessGroupStatus()) {
            mergedGroupMap.put(status.getId(), status);
        }

        for (final ProcessGroupStatus statusToMerge : toMerge.getProcessGroupStatus()) {
            ProcessGroupStatus merged = mergedGroupMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedGroupMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            merge(merged, statusToMerge);
        }
        target.setOutputPortStatus(mergedOutputPortMap.values());

        // remote groups
        final Map<String, RemoteProcessGroupStatus> mergedRemoteGroupMap = new HashMap<>();
        for (final RemoteProcessGroupStatus status : target.getRemoteProcessGroupStatus()) {
            mergedRemoteGroupMap.put(status.getId(), status);
        }

        for (final RemoteProcessGroupStatus statusToMerge : toMerge.getRemoteProcessGroupStatus()) {
            RemoteProcessGroupStatus merged = mergedRemoteGroupMap.get(statusToMerge.getId());
            if (merged == null) {
                mergedRemoteGroupMap.put(statusToMerge.getId(), statusToMerge.clone());
                continue;
            }

            // NOTE - active/inactive port counts are not merged since that state is considered part of the flow (like runStatus)
            merged.setReceivedContentSize(merged.getReceivedContentSize() + statusToMerge.getReceivedContentSize());
            merged.setReceivedCount(merged.getReceivedCount() + statusToMerge.getReceivedCount());
            merged.setSentContentSize(merged.getSentContentSize() + statusToMerge.getSentContentSize());
            merged.setSentCount(merged.getSentCount() + statusToMerge.getSentCount());
            merged.setActiveThreadCount(merged.getActiveThreadCount() + statusToMerge.getActiveThreadCount());
        }

        target.setRemoteProcessGroupStatus(mergedRemoteGroupMap.values());
    }
}


text:
// Legacy flags for XLA's gpu_backend_lib module.

#include <mutex>  // NOLINT(build/c++11): only using std::call_once, not mutex.
#include <vector>

#include "tensorflow/compiler/xla/legacy_flags/gpu_backend_lib_flags.h"
#include "tensorflow/compiler/xla/legacy_flags/parse_flags_from_env.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/command_line_flags.h"

namespace xla {
namespace legacy_flags {

// Pointers to the parsed value of the flags and flag descriptors, initialized
// via flags_init.
static GpuBackendLibFlags* flags;
static std::vector<tensorflow::Flag>* flag_list;
static std::once_flag flags_init;

// Allocate *flags.  Called via call_once(&flags_init,...).
static void AllocateFlags() {
  flags = new GpuBackendLibFlags;
  flags->dump_temp_products_to = "";
  flags->ftz = false;
  flags->fma = true;
  flags->gpu_architecture = "compute_35";
  flags->verbose_ptx_asm = false;
  flags->kernel = "";
  flags->llvm_dump_passes = false;
  flags->llvm_cl_opts = "";
  flags->dump_ir_before_passes = false;
  flags->opt_level = 3;
  flag_list = new std::vector<tensorflow::Flag>({
      tensorflow::Flag("dump_temp_products_to", &flags->dump_temp_products_to,
                       "dump temporary compilation products to this directory. "
                       "If empty, no dump is produced"),
      tensorflow::Flag("ftz", &flags->ftz, "flush to zero semantics"),
      tensorflow::Flag("fma", &flags->fma, "use FMA synthesis"),
      tensorflow::Flag("gpu_architecture", &flags->gpu_architecture,
                       "GPU architecture"),
      tensorflow::Flag("verbose_ptx_asm", &flags->verbose_ptx_asm,
                       "emit PTX assembly with extra comments"),
      tensorflow::Flag("kernel", &flags->kernel,
                       "only emit the IR and PTX for this kernel"),
      tensorflow::Flag("llvm_dump_passes", &flags->llvm_dump_passes,
                       "dump the passes LLVM runs to stderr"),
      tensorflow::Flag(
          "llvm_cl_opts", &flags->llvm_cl_opts,
          "comma-separated list of command line options to pass to "
          "LLVM.  For example, --llvm_cl_opts=--print-before=loop-unroll"),
      tensorflow::Flag("dump_ir_before_passes", &flags->dump_ir_before_passes,
                       "dump the IR before each optimization pass in "
                       "sequentially-named files."),
      tensorflow::Flag("opt_level", &flags->opt_level,
                       "optimization level (default to 3)"),
  });
  ParseFlagsFromEnv(*flag_list);
}

// Append to *append_to flag definitions associated with XLA's gpu_backend_lib
// module.
void AppendGpuBackendLibFlags(std::vector<tensorflow::Flag>* append_to) {
  std::call_once(flags_init, &AllocateFlags);
  append_to->insert(append_to->end(), flag_list->begin(), flag_list->end());
}

// Return a pointer to the GpuBackendLibFlags struct;
// repeated calls return the same pointer.
// This should be called only after Flags::Parse() has returned.
GpuBackendLibFlags* GetGpuBackendLibFlags() {
  std::call_once(flags_init, &AllocateFlags);
  return flags;
}

}  // namespace legacy_flags
}  // namespace xla

redpajama_set_name: RedPajamaGithub


text:
#include "chunk/format_evaluator_mock.h"

namespace ndash {
namespace chunk {

MockFormatEvaluator::MockFormatEvaluator() {}
MockFormatEvaluator::~MockFormatEvaluator() {}

}  // namespace chunk
}  // namespace ndash


text:
#include "postgres.h"

#include "access/clog.h"
#include "access/subtrans.h"
#include "access/transam.h"
#include "catalog/catquery.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "postmaster/autovacuum.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "cdb/cdbpersistentstore.h"

/* Number of OIDs to prefetch (preallocate) per XLOG write */
#define VAR_OID_PREFETCH		8192

/* pointer to "variable cache" in shared memory (set up by shmem.c) */
VariableCache ShmemVariableCache = NULL;

int xid_stop_limit = 20000000;

static Oid master_highest_used_oid(void);

/* initialize external Oid on first access */
static bool IsExternalOidInitialized = false;
/*
 * validate reserved range for external objects
 * by comparing with master_highest_used_oid when
 * NextExternalOid is initialized
 */
static bool IsValidExternalOidRange = false;
/* next OID to assign to external tables */
static Oid NextExternalOid = InvalidOid;

/*
 * Allocate the next XID for my new transaction or subtransaction.
 */
TransactionId
GetNewTransactionId(bool isSubXact, bool setProcXid)
{
	TransactionId xid;

	/*
	 * During bootstrap initialization, we return the special bootstrap
	 * transaction id.
	 */
	if (IsBootstrapProcessingMode())
	{
		Assert(!isSubXact);
		//MyProc->xid = BootstrapTransactionId;
		return BootstrapTransactionId;
	}

	LWLockAcquire(XidGenLock, LW_EXCLUSIVE);

	xid = ShmemVariableCache->nextXid;

	/*----------
	 * Check to see if it's safe to assign another XID.  This protects against
	 * catastrophic data loss due to XID wraparound.  The basic rules are:
	 *
	 * If we're past xidVacLimit, start trying to force autovacuum cycles.
	 * If we're past xidWarnLimit, start issuing warnings.
	 * If we're past xidStopLimit, refuse to execute transactions, unless
	 * we are running in a standalone backend (which gives an escape hatch
	 * to the DBA who somehow got past the earlier defenses).
	 *
	 * Test is coded to fall out as fast as possible during normal operation,
	 * ie, when the vac limit is set and we haven't violated it.
	 *----------
	 */
	if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidVacLimit) &&
		TransactionIdIsValid(ShmemVariableCache->xidVacLimit))
	{
		/*
		 * To avoid swamping the postmaster with signals, we issue the autovac
		 * request only once per 64K transaction starts.  This still gives
		 * plenty of chances before we get into real trouble.
		 */
		if (IsUnderPostmaster && (xid % 65536) == 0)
		{
			elog(LOG, "GetNewTransactionId: requesting autovac (xid %u xidVacLimit %u)", xid, ShmemVariableCache->xidVacLimit);
			SendPostmasterSignal(PMSIGNAL_START_AUTOVAC);
		}

		if (IsUnderPostmaster &&
			TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidStopLimit))
			ereport(ERROR,
					(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
					 errmsg("database is not accepting commands to avoid wraparound data loss in database \"%s\"",
							NameStr(ShmemVariableCache->limit_datname)),
					 errhint("Stop the postmaster and use a standalone backend to vacuum database \"%s\".",
							 NameStr(ShmemVariableCache->limit_datname))));
		else if (TransactionIdFollowsOrEquals(xid, ShmemVariableCache->xidWarnLimit))
			ereport(WARNING,
					(errmsg("database \"%s\" must be vacuumed within %u transactions",
							NameStr(ShmemVariableCache->limit_datname),
							ShmemVariableCache->xidWrapLimit - xid),
					 errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
							 NameStr(ShmemVariableCache->limit_datname))));
	}

	/*
	 * If we are allocating the first XID of a new page of the commit log,
	 * zero out that commit-log page before returning. We must do this while
	 * holding XidGenLock, else another xact could acquire and commit a later
	 * XID before we zero the page.  Fortunately, a page of the commit log
	 * holds 32K or more transactions, so we don't have to do this very often.
	 *
	 * Extend pg_subtrans too.
	 */
	ExtendCLOG(xid);
	ExtendSUBTRANS(xid);

	/*
	 * Now advance the nextXid counter.  This must not happen until after we
	 * have successfully completed ExtendCLOG() --- if that routine fails, we
	 * want the next incoming transaction to try it again.	We cannot assign
	 * more XIDs until there is CLOG space for them.
	 */
	TransactionIdAdvance(ShmemVariableCache->nextXid);

	/*
	 * We must store the new XID into the shared PGPROC array before releasing
	 * XidGenLock.	This ensures that when GetSnapshotData calls
	 * ReadNewTransactionId, all active XIDs before the returned value of
	 * nextXid are already present in PGPROC.  Else we have a race condition.
	 *
	 * XXX by storing xid into MyProc without acquiring ProcArrayLock, we are
	 * relying on fetch/store of an xid to be atomic, else other backends
	 * might see a partially-set xid here.	But holding both locks at once
	 * would be a nasty concurrency hit (and in fact could cause a deadlock
	 * against GetSnapshotData).  So for now, assume atomicity. Note that
	 * readers of PGPROC xid field should be careful to fetch the value only
	 * once, rather than assume they can read it multiple times and get the
	 * same answer each time.
	 *
	 * The same comments apply to the subxact xid count and overflow fields.
	 *
	 * A solution to the atomic-store problem would be to give each PGPROC its
	 * own spinlock used only for fetching/storing that PGPROC's xid and
	 * related fields.
	 *
	 * If there's no room to fit a subtransaction XID into PGPROC, set the
	 * cache-overflowed flag instead.  This forces readers to look in
	 * pg_subtrans to map subtransaction XIDs up to top-level XIDs. There is a
	 * race-condition window, in that the new XID will not appear as running
	 * until its parent link has been placed into pg_subtrans. However, that
	 * will happen before anyone could possibly have a reason to inquire about
	 * the status of the XID, so it seems OK.  (Snapshots taken during this
	 * window *will* include the parent XID, so they will deliver the correct
	 * answer later on when someone does have a reason to inquire.)
	 */
	if (setProcXid && MyProc != NULL)
	{
		/*
		 * Use volatile pointer to prevent code rearrangement; other backends
		 * could be examining my subxids info concurrently, and we don't want
		 * them to see an invalid intermediate state, such as incrementing
		 * nxids before filling the array entry.  Note we are assuming that
		 * TransactionId and int fetch/store are atomic.
		 */
		volatile PGPROC *myproc = MyProc;

		if (!isSubXact)
			myproc->xid = xid;
		else
		{
			int			nxids = myproc->subxids.nxids;

			if (nxids < PGPROC_MAX_CACHED_SUBXIDS)
			{
				myproc->subxids.xids[nxids] = xid;
				myproc->subxids.nxids = nxids + 1;
			}
			else
				myproc->subxids.overflowed = true;
		}
	}

	LWLockRelease(XidGenLock);

	return xid;
}

/*
 * Read nextXid but don't allocate it.
 */
TransactionId
ReadNewTransactionId(void)
{
	TransactionId xid;

	LWLockAcquire(XidGenLock, LW_SHARED);
	xid = ShmemVariableCache->nextXid;
	LWLockRelease(XidGenLock);

	return xid;
}

/*
 * Determine the last safe XID to allocate given the currently oldest
 * datfrozenxid (ie, the oldest XID that might exist in any database
 * of our cluster).
 */
void
SetTransactionIdLimit(TransactionId oldest_datfrozenxid,
					  Name oldest_datname)
{
	TransactionId xidVacLimit;
	TransactionId xidWarnLimit;
	TransactionId xidStopLimit;
	TransactionId xidWrapLimit;
	TransactionId curXid;

	Assert(TransactionIdIsNormal(oldest_datfrozenxid));

	/*
	 * The place where we actually get into deep trouble is halfway around
	 * from the oldest potentially-existing XID.  (This calculation is
	 * probably off by one or two counts, because the special XIDs reduce the
	 * size of the loop a little bit.  But we throw in plenty of slop below,
	 * so it doesn't matter.)
	 */
	xidWrapLimit = oldest_datfrozenxid + (MaxTransactionId >> 1);
	if (xidWrapLimit < FirstNormalTransactionId)
		xidWrapLimit += FirstNormalTransactionId;

	/*
	 * We'll refuse to continue assigning XIDs in interactive mode once we get
	 * within xid_stop_limit transactions of data loss.  This leaves lots of
	 * room for the DBA to fool around fixing things in a standalone backend,
	 * while not being significant compared to total XID space. (Note that since
	 * vacuuming requires one transaction per table cleaned, we had better be
	 * sure there's lots of XIDs left...)
	 */
	xidStopLimit = xidWrapLimit - (TransactionId)xid_stop_limit;
	if (xidStopLimit < FirstNormalTransactionId)
		xidStopLimit -= FirstNormalTransactionId;

	/*
	 * We'll start complaining loudly when we get within 10M + xid_stop_limit
	 * transactions of the stop point.	This is kind of arbitrary, but if
	 * you let your gas gauge get down to 1% of full, would you be looking for
	 * the next gas station?  We need to be fairly liberal about this number
	 * because there are lots of scenarios where most transactions are done by
	 * automatic clients that won't pay attention to warnings. (No, we're not
	 * gonna make this configurable.  If you know enough to configure it, you
	 * know enough to not get in this kind of trouble in the first place.)
	 */
	xidWarnLimit = xidStopLimit - 10000000 - (TransactionId)xid_stop_limit;
	if (xidWarnLimit < FirstNormalTransactionId)
		xidWarnLimit -= FirstNormalTransactionId;

	/*
	 * We'll start trying to force autovacuums when oldest_datfrozenxid gets
	 * to be more than autovacuum_freeze_max_age transactions old.
	 *
	 * Note: guc.c ensures that autovacuum_freeze_max_age is in a sane range,
	 * so that xidVacLimit will be well before xidWarnLimit.
	 *
	 * Note: autovacuum_freeze_max_age is a PGC_POSTMASTER parameter so that
	 * we don't have to worry about dealing with on-the-fly changes in its
	 * value.  It doesn't look practical to update shared state from a GUC
	 * assign hook (too many processes would try to execute the hook,
	 * resulting in race conditions as well as crashes of those not connected
	 * to shared memory).  Perhaps this can be improved someday.
	 */
	xidVacLimit = oldest_datfrozenxid + autovacuum_freeze_max_age;
	if (xidVacLimit < FirstNormalTransactionId)
		xidVacLimit += FirstNormalTransactionId;

	/* Grab lock for just long enough to set the new limit values */
	LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
	ShmemVariableCache->oldestXid = oldest_datfrozenxid;
	ShmemVariableCache->xidVacLimit = xidVacLimit;
	ShmemVariableCache->xidWarnLimit = xidWarnLimit;
	ShmemVariableCache->xidStopLimit = xidStopLimit;
	ShmemVariableCache->xidWrapLimit = xidWrapLimit;
	namecpy(&ShmemVariableCache->limit_datname, oldest_datname);
	curXid = ShmemVariableCache->nextXid;
	LWLockRelease(XidGenLock);

	/* Log the info */
	ereport(DEBUG1,
	   (errmsg("transaction ID wrap limit is %u, limited by database \"%s\"",
			   xidWrapLimit, NameStr(*oldest_datname))));

	/*
	 * If past the autovacuum force point, immediately signal an autovac
	 * request.  The reason for this is that autovac only processes one
	 * database per invocation.  Once it's finished cleaning up the oldest
	 * database, it'll call here, and we'll signal the postmaster to start
	 * another iteration immediately if there are still any old databases.
	 */
	if (TransactionIdFollowsOrEquals(curXid, xidVacLimit) &&
		IsUnderPostmaster)
		SendPostmasterSignal(PMSIGNAL_START_AUTOVAC);

	/* Give an immediate warning if past the wrap warn point */
	if (TransactionIdFollowsOrEquals(curXid, xidWarnLimit))
		ereport(WARNING,
		   (errmsg("database \"%s\" must be vacuumed within %u transactions",
				   NameStr(*oldest_datname),
				   xidWrapLimit - curXid),
			errhint("To avoid a database shutdown, execute a full-database VACUUM in \"%s\".",
					NameStr(*oldest_datname))));
}

/*
 * GetNewObjectId -- allocate a new OID
 *
 * OIDs are generated by a cluster-wide counter.  Since they are only 32 bits
 * wide, counter wraparound will occur eventually, and therefore it is unwise
 * to assume they are unique unless precautions are taken to make them so.
 * Hence, this routine should generally not be used directly.  The only
 * direct callers should be GetNewOid() and GetNewRelFileNode() in
 * catalog/catalog.c.
 */
Oid
GetNewObjectId(void)
{
	Oid			result;

	LWLockAcquire(OidGenLock, LW_EXCLUSIVE);

	/*
	 * Check for wraparound of the OID counter.  We *must* not return 0
	 * (InvalidOid); and as long as we have to check that, it seems a good
	 * idea to skip over everything below FirstNormalObjectId too. (This
	 * basically just avoids lots of collisions with bootstrap-assigned OIDs
	 * right after a wrap occurs, so as to avoid a possibly large number of
	 * iterations in GetNewOid.)  Note we are relying on unsigned comparison.
	 *
	 * During initdb, we start the OID generator at FirstBootstrapObjectId, so
	 * we only enforce wrapping to that point when in bootstrap or standalone
	 * mode.  The first time through this routine after normal postmaster
	 * start, the counter will be forced up to FirstNormalObjectId. This
	 * mechanism leaves the OIDs between FirstBootstrapObjectId and
	 * FirstNormalObjectId available for automatic assignment during initdb,
	 * while ensuring they will never conflict with user-assigned OIDs.
	 */
	if (ShmemVariableCache->nextOid < ((Oid) FirstNormalObjectId)
			|| ShmemVariableCache->nextOid >= (Oid) FirstExternalObjectId)
	{
		if (IsPostmasterEnvironment)
		{
			/* wraparound in normal environment */
			ShmemVariableCache->nextOid = FirstNormalObjectId;
			ShmemVariableCache->oidCount = 0;
		}
		else
		{
			/* we may be bootstrapping, so don't enforce the full range */
			if (ShmemVariableCache->nextOid < ((Oid) FirstBootstrapObjectId))
			{
				/* wraparound in standalone environment? */
				ShmemVariableCache->nextOid = FirstBootstrapObjectId;
				ShmemVariableCache->oidCount = 0;
			}
		}
	}

	/* If we run out of logged for use oids then we must log more */
	if (ShmemVariableCache->oidCount == 0)
	{
		XLogPutNextOid(ShmemVariableCache->nextOid + VAR_OID_PREFETCH);
		ShmemVariableCache->oidCount = VAR_OID_PREFETCH;
	}

	result = ShmemVariableCache->nextOid;

	(ShmemVariableCache->nextOid)++;
	(ShmemVariableCache->oidCount)--;

	LWLockRelease(OidGenLock);

	return result;
}

/*
 * GetNewExternalObjectId
 * 		Allocate a new OID for an externally imported table from the reserved range of oids
 */
Oid
GetNewExternalObjectId(void)
{
	Oid			result;

	Assert(IsPostmasterEnvironment);

	/*
	 * must perform check on External Oid range on
	 * initial access of NextExternalOid
	 *
	 * It's needed for upgrade scenario from old version
	 * of HAWQ which doesn't support dedicated oid pool for HCatalog objects
	 */
	if (!IsExternalOidInitialized)
	{
		IsExternalOidInitialized = true;
		IsValidExternalOidRange = master_highest_used_oid() < FirstExternalObjectId;
		ResetExternalObjectId();
	}

	/*
	 * This check is needed for upgrade from old HAWQ versions, which don't support
	 * oid pool for HCatalog objects.
	 * In current implementation max oid will be always less than FirstExternalObjectId.
	 */
	if (!IsValidExternalOidRange)
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
				 errmsg("database does not have enough available Oids to support HCatalog queries"),
				 errhint("Database VACUUM may recycle unused Oids.")));

	/*
	 * NextExternalOid==0 indicates a rollover has occurred in the
	 * previous external Oid creation
	 *
	 * Current specifications do not support wrap around as
	 * in-memory constraints cannot be enforced for Oids in
	 * different catalog tables
	 */
	if (!OidIsValid(NextExternalOid) || NextExternalOid < (Oid) FirstExternalObjectId)
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
				 errmsg("number of external objects from HCatalog exceeded 10M during transaction"),
				 errhint("Separate HCatalog queries into different transactions to process.")));

	result = NextExternalOid;

	(NextExternalOid)++;

	return result;
}

/*
 * GetCurrentExternalObjectId
 * 		This getter method is for testing purpose only
 */
Oid
GetCurrentExternalObjectId(void)
{
	return NextExternalOid;
}

/*
 * SetCurrentExternalObjectId
 *     This setter method is for testing purpose only
 */
void
SetCurrentExternalObjectId(Oid nextExtOid)
{
	NextExternalOid = nextExtOid;
}

void
ResetExternalObjectId(void)
{
	if (IsValidExternalOidRange)
	{
		NextExternalOid = (Oid) FirstExternalObjectId;
	}
}

/*
 * master_highest_used_oid
 * 		Uses CAQL and SPI to find the highest used Oid among user and catalog tables
 *
 * 		Uses CAQL to query catalog tables
 * 		Uses SPI to query user tables, because CAQL supports tables from CatCoreRelation array only
 * 		1) Find all the relations that has Oids
 * 		2) Find max oid from those relations
 */
Oid
master_highest_used_oid(void)
{
	Oid oidMaxCatalog = InvalidOid;
	Oid oidMaxUser = InvalidOid;
	Oid oidMax = InvalidOid;
	Oid currentOid;
	Form_pg_class classForm;
	cqContext *pcqOuterCtx;
	cqContext *pcqInnerCtx;
	HeapTuple outerTuple;
	HeapTuple innerTuple;
	/* number of user tables having oids*/
	int userTablesNum = 0;
	int ret;

	pcqOuterCtx = caql_beginscan(NULL, cql("SELECT * FROM pg_class WHERE relhasoids = :1", BoolGetDatum(true)));

	outerTuple = caql_getnext(pcqOuterCtx);

	if (!HeapTupleIsValid(outerTuple))
	{
		caql_endscan(pcqOuterCtx);
		elog(DEBUG1, "Unable to get list of tables having oids");
		return oidMax;
	}

	/* construct query to get max oid from all tables with oids */
	StringInfo sqlstrCatalog = makeStringInfo();
	StringInfo sqlstrUser = makeStringInfo();
	appendStringInfo(sqlstrUser, "SELECT max(oid) FROM (");
	while (HeapTupleIsValid(outerTuple))
	{
		classForm = (Form_pg_class) GETSTRUCT(outerTuple);

		/* use CAQL for accessing catalog tables*/
		if (classForm->relnamespace == PG_CATALOG_NAMESPACE)
		{
			appendStringInfo(sqlstrCatalog,
					"SELECT oid FROM %s WHERE oid > :1 ORDER BY oid",
					classForm->relname.data);

			pcqInnerCtx = caql_beginscan(NULL,
					cql1(sqlstrCatalog->data, __FILE__, __LINE__,
							ObjectIdGetDatum(oidMaxCatalog)));

			innerTuple = caql_getnext(pcqInnerCtx);

			currentOid = InvalidOid;

			while (HeapTupleIsValid(innerTuple))
			{
				currentOid = HeapTupleGetOid(innerTuple);
				innerTuple = caql_getnext(pcqInnerCtx);
			}

			elog(DEBUG1, "Max Oid in catalog table %s: %d", classForm->relname.data, currentOid);

			caql_endscan(pcqInnerCtx);

			oidMaxCatalog = currentOid > oidMaxCatalog ? currentOid : oidMaxCatalog;

			resetStringInfo(sqlstrCatalog);
		}
		else
		/* use SPI for user tables*/
		{
			userTablesNum++;
			{
				if (userTablesNum > 1)
				{
					appendStringInfo(sqlstrUser, " UNION ALL ");
				}
				appendStringInfo(sqlstrUser, "SELECT MAX(oid) AS oid FROM %s", classForm->relname.data);
			}
		}

		outerTuple = caql_getnext(pcqOuterCtx);
	}

	caql_endscan(pcqOuterCtx);

	if (userTablesNum) {

		appendStringInfo(sqlstrUser, ") AS x");

		if (SPI_OK_CONNECT != SPI_connect())
		{
			ereport(ERROR, (errcode(ERRCODE_CDB_INTERNAL_ERROR),
					errmsg("Unable to connect to execute internal query for HCatalog.")));
		}

		ret = SPI_execute(sqlstrUser->data, true, 1);

		if (ret > 0 && NULL != SPI_tuptable) {
			TupleDesc tupdesc = SPI_tuptable->tupdesc;
			SPITupleTable *tuptable = SPI_tuptable;
			HeapTuple tuple = tuptable->vals[0];
			char *oidString = SPI_getvalue(tuple, tupdesc, 1);
			if (NULL != oidString)
			{
				oidMaxUser = DatumGetObjectId(DirectFunctionCall1(oidin, CStringGetDatum(oidString)));
			}
		}
	}

	pfree(sqlstrCatalog->data);
	pfree(sqlstrUser->data);
	SPI_finish();

	elog(DEBUG1, "Highest Oid currently in use among catalog tables: %u", oidMaxCatalog);
	elog(DEBUG1, "Highest Oid currently in use among user tables having oid: %u", oidMaxUser);

	oidMax = oidMaxCatalog > oidMaxUser ? oidMaxCatalog : oidMaxUser;

	elog(DEBUG1, "Highest Oid currently in use: %u", oidMax);

	return oidMax;
}


text:
module ListTest where
import Test.HUnit
import Data.List

-- list tests
-- intersperse: takes an element and a list and then puts that element in between each pair of elements in the list.
intersperseChar = TestCase $ assertEqual
    "" (intersperse '.' "MONKEY") "M.O.N.K.E.Y"

intersperseDigit = TestCase $ assertEqual
    "" (intersperse 0 [1,2,3,4]) [1,0,2,0,3,0,4]

intercalateStrings = TestCase $ assertEqual
    "" (intercalate " " ["hey", "there", "guys"]) "hey there guys"

intercalateDigits = TestCase $ assertEqual
    "" (intercalate [0,0,0] [[1,2,3],[4,5,6],[7,8,9]]) [1,2,3,0,0,0,4,5,6,0,0,0,7,8,9]

listCases = TestList [
    intersperseChar
    , intersperseDigit
    , intercalateStrings
    , intercalateDigits
    ]

main :: IO Counts
main = runTestTT $ TestList [listCases]


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PiGlowServer</title>

    <!-- Bootstrap -->
<!--    <link href="css/bootstrap.min.css" rel="stylesheet"> -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
<div class="container">
{% block content %}
{% endblock %}
</div>
</htmL>


text:
WebLearning.controller("ActivationCTLR",['$scope','$log',function($scope,console)
{
	$scope.tagUrl = "Partials/tagId1.html";
//	$scope.tagId = 2;
	console.log("Activation CTLR loaded");
	$scope.ChangeTag1 = function()
	{
		$scope.tagUrl="Partials/tagId1.html";
	console.log("called changeTag1");
	};
	$scope.ChangeTag2 = function()
	{
	$scope.tagUrl="Partials/tagId2.html";
	console.log("called changeTag2");
	};
	$scope.ChangeTag3 = function()
	{
		$scope.tagUrl="Partials/tagId3.html";
	console.log("called changeTag3");

	};
}]);


text:
(function (ng) {
    var mod = ng.module('bookModule', ['ngCrud', 'ui.router']);

    mod.constant('bookModel', {
        name: 'book',
        displayName: 'Book',
        url: 'books',
        fields: {
            name: {
                displayName: 'Name',
                type: 'String',
                required: true
            },
            description: {
                displayName: 'Description',
                type: 'String',
                required: true
            },
            isbn: {
                displayName: 'Isbn',
                type: 'String',
                required: true
            },
            image: {
                displayName: 'Image',
                type: 'String',
                required: true
            },
            editorial: {
                displayName: 'Editorial',
                type: 'Reference',
                model: 'editorialModel',
                options: [],
                required: true
            }        }
    });

    mod.config(['$stateProvider',
        function($sp){
            var basePath = 'src/modules/book/';
            var baseInstancePath = basePath + 'instance/';

            $sp.state('book', {
                url: '/books?page&limit',
                abstract: true,

                views: {
                     mainView: {
                        templateUrl: basePath + 'book.tpl.html',
                        controller: 'bookCtrl'
                    }
                },
                resolve: {
                    references: ['$q', 'Restangular', function ($q, r) {
                            return $q.all({
                                editorial: r.all('editorials').getList()
                            });
                        }],
                    model: 'bookModel',
                    books: ['Restangular', 'model', '$stateParams', function (r, model, $params) {
                            return r.all(model.url).getList($params);
                        }]
                }
            });
            $sp.state('bookList', {
                url: '/list',
                parent: 'book',
                views: {
                    bookView: {
                        templateUrl: basePath + 'list/book.list.tpl.html',
                        controller: 'bookListCtrl',
                        controllerAs: 'ctrl'
                    }
                }
            });
            $sp.state('bookNew', {
                url: '/new',
                parent: 'book',
                views: {
                    bookView: {
                        templateUrl: basePath + 'new/book.new.tpl.html',
                        controller: 'bookNewCtrl',
                        controllerAs: 'ctrl'
                    }
                }
            });
            $sp.state('bookInstance', {
                url: '/{bookId:int}',
                abstract: true,
                parent: 'book',
                views: {
                    bookView: {
                        template: '

'
                    }
                },
                resolve: {
                    book: ['books', '$stateParams', function (books, $params) {
                            return books.get($params.bookId);
                        }]
                }
            });
            $sp.state('bookDetail', {
                url: '/details',
                parent: 'bookInstance',
                views: {
                    bookInstanceView: {
                        templateUrl: baseInstancePath + 'detail/book.detail.tpl.html',
                        controller: 'bookDetailCtrl'
                    }
                }
            });
            $sp.state('bookEdit', {
                url: '/edit',
                sticky: true,
                parent: 'bookInstance',
                views: {
                    bookInstanceView: {
                        templateUrl: baseInstancePath + 'edit/book.edit.tpl.html',
                        controller: 'bookEditCtrl',
                        controllerAs: 'ctrl'
                    }
                }
            });
            $sp.state('bookDelete', {
                url: '/delete',
                parent: 'bookInstance',
                views: {
                    bookInstanceView: {
                        templateUrl: baseInstancePath + 'delete/book.delete.tpl.html',
                        controller: 'bookDeleteCtrl',
                        controllerAs: 'ctrl'
                    }
                }
            });
            $sp.state('bookAuthors', {
                url: '/authors',
                parent: 'bookDetail',
                abstract: true,
                views: {
                    bookChieldView: {
                        template: '

'
                    }
                },
                resolve: {
                    authors: ['book', function (book) {
                            return book.getList('authors');
                        }],
                    model: 'authorModel'
                }
            });
            $sp.state('bookAuthorsList', {
                url: '/list',
                parent: 'bookAuthors',
                views: {
                    bookAuthorsView: {
                        templateUrl: baseInstancePath + 'authors/list/book.authors.list.tpl.html',
                        controller: 'bookAuthorsListCtrl'
                    }
                }
            });
            $sp.state('bookAuthorsEdit', {
                url: '/edit',
                parent: 'bookAuthors',
                views: {
                    bookAuthorsView: {
                        templateUrl: baseInstancePath + 'authors/edit/book.authors.edit.tpl.html',
                        controller: 'bookAuthorsEditCtrl',
                        controllerAs: 'ctrl'
                    }
                },
                resolve: {
                    pool: ['Restangular', 'model', function (r, model) {
                            return r.all(model.url).getList();
                        }]
                }
            });
	}]);
})(window.angular);


text:
#pragma once

#include <algorithm>
#include <utility>

#include "tscore/ink_platform.h"
#include "tscore/ink_defs.h"
#include "tscore/RbTree.h"
#include "tscore/ink_inet.h"
#include "tscpp/util/IntrusiveDList.h"
#include "tscore/ink_assert.h"
#include "tscore/BufferWriterForward.h"

namespace ts
{
namespace detail
{
  /** Interval class.
      This holds an interval based on a metric @a T along with
      client data.
  */
  template <typename T,            ///< Metric for span.
            typename A = T const & ///< Argument type.
            >
  struct Interval {
    using Metric  = T; ///< Metric (storage) type.
    using ArgType = A; ///< Type used to pass instances of @c Metric.

    Interval() {} ///< Default constructor.
    /// Construct with values.
    Interval(ArgType min, ///< Minimum value in span.
             ArgType max  ///< Maximum value in span.
             )
      : _min(min), _max(max)
    {
    }
    Metric _min; ///< Minimum value in span.
    Metric _max; ///< Maximum value in span.
  };

  class Ip4Map; // Forward declare.
  class Ip6Map; // Forward declare.
} // namespace detail
} // namespace ts

/** Map from IP addresses to client data.

    Conceptually this class maps the entire space of IP addresses to
    client data. Client data is stored as a @c (void*). Memory
    management of the data is left to the client. The interface
    supports marking ranges of addresses with a specific client
    data. Marking takes a painter's algorithm approach -- any marking
    overwrites any previous marking on an address. Details of marking
    calls are discarded and only the final results are kept. That is,
    a client cannot unmark explicitly any previous marking. Only a
    specific range of addresses can be unmarked.

    Both IPv4 and IPv6 are supported in the same map. Mixed ranges are
    not supported (any particular range of addresses must be a single
    protocol but ranges of both types can be in the map).

    Use @c mark to mark / set / add addresses to the map.
    Use @c unmark to unset addresses (setting the client data to 0 does
    @b not remove the address -- this is for the convenience of clients
    that do not need data, only membership). @c contains tests for
    membership and retrieves the client data.

    Ranges can be marked and unmarked arbitrarily. The internal
    representation keeps a minimal set of ranges to describe the
    current addresses. Search time is O(log n) where n is the number
    of disjoint ranges. Marking and unmarking can take O(log n) and
    may require memory allocation / deallocation although this is
    minimized.
*/

class IpMap
{
public:
  using self_type = IpMap; ///< Self reference type.

  class iterator; // forward declare.

  static constexpr in_addr_t RAW_IP4_MIN_ADDR = 0;
  static constexpr IpAddr IP4_MIN_ADDR{RAW_IP4_MIN_ADDR};
  static constexpr in_addr_t RAW_IP4_MAX_ADDR = ~0;
  static constexpr IpAddr IP4_MAX_ADDR{RAW_IP4_MAX_ADDR};

  static constexpr in6_addr RAW_IP6_MIN_ADDR = {{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}};
  static constexpr IpAddr IP6_MIN_ADDR{RAW_IP6_MIN_ADDR};
  static constexpr in6_addr RAW_IP6_MAX_ADDR = {{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}};
  static constexpr IpAddr IP6_MAX_ADDR{RAW_IP6_MAX_ADDR};

  /** Public API for intervals in the map.
   */
  class Node : protected ts::detail::RBNode
  {
    friend class iterator;
    friend class IpMap;

  public:
    using self_type = Node; ///< Self reference type.
    /// Default constructor.
    Node() {}
    /// Construct with @a data.
    Node(void *data) : _data(data) {}
    /// @return Client data for the node.
    virtual void *
    data()
    {
      return _data;
    }
    /// Set client data.
    virtual self_type &
    setData(void *data ///< Client data pointer to store.
    )
    {
      _data = data;
      return *this;
    }
    /// @return Minimum value of the interval.
    virtual sockaddr const *min() const = 0;
    /// @return Maximum value of the interval.
    virtual sockaddr const *max() const = 0;

  protected:
    void *_data = nullptr; ///< Client data.
  };

  /** Iterator over nodes / intervals.

      The iteration is over all nodes, regardless of which node is
      used to create the iterator. The node passed to the constructor
      just sets the current location.
  */
  class iterator
  {
    friend class IpMap;

  public:
    using self_type         = iterator; ///< Self reference type.
    using value_type        = Node;     ///< Referenced type for iterator.
    using difference_type   = int;      ///< Distance type.
    using pointer           = Node *;   ///< Pointer to referent.
    using reference         = Node &;   ///< Reference to referent.
    using iterator_category = std::bidirectional_iterator_tag;
    /// Default constructor.
    iterator() = default;
    reference operator*() const; //!< value operator
    pointer operator->() const;  //!< dereference operator
    self_type &operator++();     //!< next node (prefix)
    self_type operator++(int);   //!< next node (postfix)
    self_type &operator--();     ///< previous node (prefix)
    self_type operator--(int);   ///< next node (postfix)

    /** Equality.
        @return @c true if the iterators refer to the same node.
    */
    bool operator==(self_type const &that) const;
    /** Inequality.
        @return @c true if the iterators refer to different nodes.
    */
    bool
    operator!=(self_type const &that) const
    {
      return !(*this == that);
    }

  private:
    /// Construct a valid iterator.
    iterator(IpMap const *tree, Node *node) : _tree(tree), _node(node) {}
    IpMap const *_tree = nullptr; ///< Container.
    Node *_node        = nullptr; //!< Current node.
  };

  IpMap()                      = default; ///< Default constructor.
  IpMap(self_type const &that) = delete;
  IpMap(self_type &&that) noexcept;
  ~IpMap(); ///< Destructor.

  self_type &operator=(self_type const &that) = delete;
  self_type &operator                         =(self_type &&that);

  /** Mark a range.
      All addresses in the range [ @a min , @a max ] are marked with @a data.
      @return This object.
  */
  self_type &mark(sockaddr const *min, ///< Minimum value in range.
                  sockaddr const *max, ///< Maximum value in range.
                  void *data = nullptr ///< Client data payload.
  );

  /** Mark a range.
      All addresses in the range [ @a min , @a max ] are marked with @a data.
      @note Convenience overload for IPv4 addresses.
      @return This object.
  */
  self_type &mark(in_addr_t min,       ///< Minimum address (network order).
                  in_addr_t max,       ///< Maximum address (network order).
                  void *data = nullptr ///< Client data.
  );

  /** Mark a range.
      All addresses in the range [ @a min , @a max ] are marked with @a data.
      @note Convenience overload for IPv4 addresses.
      @return This object.
  */
  self_type &mark(IpAddr const &min,   ///< Minimum address (network order).
                  IpAddr const &max,   ///< Maximum address (network order).
                  void *data = nullptr ///< Client data.
  );

  /** Mark an IPv4 address @a addr with @a data.
      This is equivalent to calling @c mark(addr, addr, data).
      @note Convenience overload for IPv4 addresses.
      @return This object.
  */
  self_type &mark(in_addr_t addr,      ///< Address (network order).
                  void *data = nullptr ///< Client data.
  );

  /** Mark a range.
      All addresses in the range [ @a min , @a max ] are marked with @a data.
      @note Convenience overload.
      @return This object.
  */
  self_type &mark(IpEndpoint const *min, ///< Minimum address (network order).
                  IpEndpoint const *max, ///< Maximum address (network order).
                  void *data = nullptr   ///< Client data.
  );

  /** Mark an address @a addr with @a data.
      This is equivalent to calling @c mark(addr, addr, data).
      @note Convenience overload.
      @return This object.
  */
  self_type &mark(IpEndpoint const *addr, ///< Address (network order).
                  void *data = nullptr    ///< Client data.
  );

  /** Unmark addresses.

      All addresses in the range [ @a min , @a max ] are cleared
      (removed from the map), no longer marked.

      @return This object.
  */
  self_type &unmark(sockaddr const *min, ///< Minimum value.
                    sockaddr const *max  ///< Maximum value.
  );
  /// Unmark addresses (overload).
  self_type &unmark(IpAddr const &min, IpAddr const &max);
  /// Unmark addresses (overload).
  self_type &unmark(IpEndpoint const *min, IpEndpoint const *max);
  /// Unmark overload.
  self_type &unmark(in_addr_t min, ///< Minimum of range to unmark.
                    in_addr_t max  ///< Maximum of range to unmark.
  );

  /** Fill addresses.

      This background fills using the range. All addresses in the
      range that are @b not present in the map are added. No
      previously present address is changed.

      @note This is useful for filling in first match tables because @a data for already present
      addresses is not changed.

      @return This object.
  */
  self_type &fill(sockaddr const *min, sockaddr const *max, void *data = nullptr);
  /// Fill addresses (overload).
  self_type &fill(IpEndpoint const *min, IpEndpoint const *max, void *data = nullptr);
  /// Fill addresses (overload).
  self_type &fill(IpAddr const &min, IpAddr const &max, void *data = nullptr);
  /// Fill addresses (overload).
  self_type &fill(in_addr_t min, in_addr_t max, void *data = nullptr);

  /** Test for membership.

      @return @c true if the address is in the map, @c false if not.
      If the address is in the map and @a ptr is not @c nullptr, @c *ptr
      is set to the client data for the address.
  */
  bool contains(sockaddr const *target, ///< Search target (network order).
                void **ptr = nullptr    ///< Client data return.
  ) const;

  /** Test for membership.

      @note Convenience overload for IPv4.

      @return @c true if the address is in the map, @c false if not.
      If the address is in the map and @a ptr is not @c nullptr, @c *ptr
      is set to the client data for the address.
  */
  bool contains(in_addr_t target,    ///< Search target (network order).
                void **ptr = nullptr ///< Client data return.
  ) const;

  /** Test for membership.

      @note Convenience overload for @c IpEndpoint.

      @return @c true if the address is in the map, @c false if not.
      If the address is in the map and @a ptr is not @c nullptr, @c *ptr
      is set to the client data for the address.
  */
  bool contains(IpEndpoint const *target, ///< Search target (network order).
                void **ptr = nullptr      ///< Client data return.
  ) const;

  /** Test for membership.

      @note Convenience overload for @c IpAddr.

      @return @c true if the address is in the map, @c false if not.
      If the address is in the map and @a ptr is not @c nullptr, @c *ptr
      is set to the client data for the address.
  */
  bool contains(IpAddr const &target, ///< Search target (network order).
                void **ptr = nullptr  ///< Client data return.
  ) const;

  /** Remove all addresses from the map.

      @note This is much faster than @c unmark.
      @return This object.
  */
  self_type &clear();

  /// Iterator for first element.
  iterator begin() const;
  /// Iterator past last element.
  iterator end() const;
  /// @return Number of distinct ranges in the map.
  size_t count() const;

  /** Validate internal data structures.
      @note Intended for debugging, not general client use.
  */
  void validate();

  /** Generate formatted output.
   *
   * @param w Destination of formatted output.
   * @param spec Formatting specification.
   * @return @a w
   */
  ts::BufferWriter &describe(ts::BufferWriter &w, ts::BWFSpec const &spec) const;

protected:
  /// Force the IPv4 map to exist.
  /// @return The IPv4 map.
  ts::detail::Ip4Map *force4();
  /// Force the IPv6 map to exist.
  /// @return The IPv6 map.
  ts::detail::Ip6Map *force6();

  ts::detail::Ip4Map *_m4 = nullptr; ///< Map of IPv4 addresses.
  ts::detail::Ip6Map *_m6 = nullptr; ///< Map of IPv6 addresses.
};

inline IpMap &
IpMap::mark(in_addr_t addr, void *data)
{
  return this->mark(addr, addr, data);
}

inline IpMap &
IpMap::mark(IpAddr const &min, IpAddr const &max, void *data)
{
  IpEndpoint x, y;
  x.assign(min);
  y.assign(max);
  return this->mark(&x.sa, &y.sa, data);
}

inline IpMap &
IpMap::mark(IpEndpoint const *addr, void *data)
{
  return this->mark(&addr->sa, &addr->sa, data);
}

inline IpMap &
IpMap::mark(IpEndpoint const *min, IpEndpoint const *max, void *data)
{
  return this->mark(&min->sa, &max->sa, data);
}

inline IpMap &
IpMap::unmark(IpEndpoint const *min, IpEndpoint const *max)
{
  return this->unmark(&min->sa, &max->sa);
}

inline IpMap &
IpMap::unmark(IpAddr const &min, IpAddr const &max)
{
  IpEndpoint x, y;
  x.assign(min);
  y.assign(max);
  return this->unmark(&x.sa, &y.sa);
}

inline IpMap &
IpMap::fill(IpEndpoint const *min, IpEndpoint const *max, void *data)
{
  return this->fill(&min->sa, &max->sa, data);
}

inline IpMap &
IpMap::fill(IpAddr const &min, IpAddr const &max, void *data)
{
  IpEndpoint x, y;
  x.assign(min);
  y.assign(max);
  return this->fill(&x.sa, &y.sa, data);
}

inline bool
IpMap::contains(IpEndpoint const *target, void **ptr) const
{
  return this->contains(&target->sa, ptr);
}

inline bool
IpMap::contains(IpAddr const &addr, void **ptr) const
{
  IpEndpoint ip;
  ip.assign(addr);
  return this->contains(&ip.sa, ptr);
}

inline IpMap::iterator
IpMap::end() const
{
  return iterator(this, nullptr);
}

inline IpMap::iterator
IpMap::iterator::operator++(int)
{
  iterator old(*this);
  ++*this;
  return old;
}

inline IpMap::iterator
IpMap::iterator::operator--(int)
{
  self_type tmp(*this);
  --*this;
  return tmp;
}

inline bool
IpMap::iterator::operator==(iterator const &that) const
{
  return _tree == that._tree && _node == that._node;
}

inline IpMap::iterator::reference
IpMap::iterator::operator*() const
{
  return *_node;
}

inline IpMap::iterator::pointer
IpMap::iterator::operator->() const
{
  return _node;
}

namespace ts
{
inline BufferWriter &
bwformat(BufferWriter &w, BWFSpec const &spec, IpMap const &map)
{
  return map.describe(w, spec);
}
} // namespace ts


text:
/**
 * \page asfdoc_sam0_port_basic_use_case Quick Start Guide for PORT - Basic
 *
 * In this use case, the PORT module is configured for:
 *  \li One pin in input mode, with pull-up enabled
 *  \li One pin in output mode
 *
 * This use case sets up the PORT to read the current state of a GPIO pin set as
 * an input, and mirrors the opposite logical state on a pin configured as an
 * output.
 *
 * \section asfdoc_sam0_port_basic_use_case_setup Setup
 *
 * \subsection asfdoc_sam0_port_basic_use_case_setup_prereq Prerequisites
 * There are no special setup requirements for this use-case.
 *
 * \subsection asfdoc_sam0_port_basic_use_case_setup_code Code
 * Copy-paste the following setup code to your user application:
 * \snippet qs_port_basic.c setup
 *
 * Add to user application initialization (typically the start of \c main()):
 * \snippet qs_port_basic.c setup_init
 *
 * \subsection asfdoc_sam0_port_basic_use_case_setup_flow Workflow
 * -# Create a PORT module pin configuration struct, which can be filled out to
 *    adjust the configuration of a single port pin.
 *    \snippet qs_port_basic.c setup_1
 * -# Initialize the pin configuration struct with the module's default values.
 *    \snippet qs_port_basic.c setup_2
 *    \note This should always be performed before using the configuration
 *          struct to ensure that all values are initialized to known default
 *          settings.
 *
 * -# Adjust the configuration struct to request an input pin.
 *    \snippet qs_port_basic.c setup_3
 * -# Configure push button pin with the initialized pin configuration struct, to enable
 *    the input sampler on the pin.
 *    \snippet qs_port_basic.c setup_4
 * -# Adjust the configuration struct to request an output pin.
 *    \snippet qs_port_basic.c setup_5
 *    \note The existing configuration struct may be re-used, as long as any
 *          values that have been altered from the default settings are taken
 *          into account by the user application.
 *
 * -# Configure LED pin with the initialized pin configuration struct, to enable
 *    the output driver on the pin.
 *    \snippet qs_port_basic.c setup_6
 *
 * \section asfdoc_sam0_port_basic_use_case_use_main Use Case
 *
 * \subsection asfdoc_sam0_port_basic_use_case_code Code
 * Copy-paste the following code to your user application:
 * \snippet qs_port_basic.c main
 *
 * \subsection asfdoc_sam0_port_basic_use_case_flow Workflow
 * -# Read in the current input sampler state of push button pin, which has been
 *    configured as an input in the use-case setup code.
 *    \snippet qs_port_basic.c main_1
 * -# Write the inverted pin level state to LED pin, which has been configured as
 *    an output in the use-case setup code.
 *    \snippet qs_port_basic.c main_2
 */
 /**
 * Support and FAQ: visit Atmel Support
 */


text:
package org.apache.accumulo.gc;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.stream.Stream;

import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.DataFileColumnFamily;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.TabletsSection.ScanFileColumnFamily;
import org.apache.accumulo.server.replication.proto.Replication.Status;

public interface GarbageCollectionEnvironment {

  /**
   * Return an iterator which points to a list of paths to files and dirs which are candidates for
   * deletion from a given table, {@link RootTable#NAME} or {@link MetadataTable#NAME}
   *
   * @return an iterator referencing a List containing deletion candidates
   */
  Iterator<String> getCandidates() throws TableNotFoundException;

  /**
   * Given an iterator to a deletion candidate list, return a sub-list of candidates which fit
   * within provided memory constraints.
   *
   * @param candidatesIter
   *          iterator referencing a List of possible deletion candidates
   * @return a List of possible deletion candidates
   */
  List<String> readCandidatesThatFitInMemory(Iterator<String> candidatesIter);

  /**
   * Fetch a list of paths for all bulk loads in progress (blip) from a given table,
   * {@link RootTable#NAME} or {@link MetadataTable#NAME}
   *
   * @return The list of files for each bulk load currently in progress.
   */
  Stream<String> getBlipPaths() throws TableNotFoundException;

  static class Reference {
    public final TableId id;
    public final String ref;
    public final boolean isDir;

    Reference(TableId id, String ref, boolean isDir) {
      this.id = id;
      this.ref = ref;
      this.isDir = isDir;
    }
  }

  /**
   * Fetches the references to files, {@link DataFileColumnFamily#NAME} or
   * {@link ScanFileColumnFamily#NAME}, from tablets
   *
   * @return An {@link Iterator} of {@link Entry}<{@link Key}, {@link Value}> which constitute
   *         a reference to a file.
   */
  Stream<Reference> getReferences();

  /**
   * Return the set of tableIDs for the given instance this GarbageCollector is running over
   *
   * @return The valueSet for the table name to table id map.
   */
  Set<TableId> getTableIDs();

  /**
   * Delete the given files from the provided {@link Map} of relative path to absolute path for each
   * file that should be deleted
   *
   * @param candidateMap
   *          A Map from relative path to absolute path for files to be deleted.
   */
  void delete(SortedMap<String,String> candidateMap) throws TableNotFoundException;

  /**
   * Delete a table's directory if it is empty.
   *
   * @param tableID
   *          The id of the table whose directory we are to operate on
   */
  void deleteTableDirIfEmpty(TableId tableID) throws IOException;

  /**
   * Increment the number of candidates for deletion for the current garbage collection run
   *
   * @param i
   *          Value to increment the deletion candidates by
   */
  void incrementCandidatesStat(long i);

  /**
   * Increment the number of files still in use for the current garbage collection run
   *
   * @param i
   *          Value to increment the still-in-use count by.
   */
  void incrementInUseStat(long i);

  /**
   * Determine if the given absolute file is still pending replication
   *
   * @return True if the file still needs to be replicated
   */
  Iterator<Entry<String,Status>> getReplicationNeededIterator();
}


text:
package de.rnd7.libtvdb.api;

import java.util.Comparator;

public class TVShowEpisode {

	public static Comparator<TVShowEpisode> COMPARATOR = Comparator
			.comparing(episode -> (episode.getSeason() * 1000) + episode.getEpisode());

	private String name;
	private int season;
	private int episode;

	public String getName() {
		return this.name;
	}

	public int getSeason() {
		return this.season;
	}

	public int getEpisode() {
		return this.episode;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public void setSeason(final int season) {
		this.season = season;
	}

	public void setEpisode(final int episode) {
		this.episode = episode;
	}

	@Override
	public String toString() {
		return String.format("s%02de%02d - %s", this.season, this.episode, this.name);
	}
}


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-parent</artifactId>
    <version>11</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>1.3-SNAPSHOT</version>
  <name>Commons DBCP</name>

  <inceptionYear>2001</inceptionYear>
  <description>Commons Database Connection Pooling</description>
  <url>http://commons.apache.org/dbcp/</url>

  <distributionManagement>
    <site>
      <id>people.apache.org</id>
      <name>Commons DBCP</name>
      <url>scp://people.apache.org/www/commons.apache.org/dbcp</url>
    </site>
  </distributionManagement>

  <issueManagement>
    <system>jira</system>
    <url>http://issues.apache.org/jira/browse/DBCP</url>
  </issueManagement>

  <scm>
    <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/dbcp/trunk</connection>
    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/dbcp/trunk</developerConnection>
    <url>http://svn.apache.org/viewvc/commons/proper/dbcp/trunk</url>
  </scm>

  <developers>
    <developer>
      <name>Morgan Delagrange</name>
      <id>morgand</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Geir Magnusson</name>
      <id>geirm</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Craig McClanahan</name>
      <id>craigmcc</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>John McNally</name>
      <id>jmcnally</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Martin Poeschl</name>
      <id>mpoeschl</id>
      <email>mpoeschl@marmot.at</email>
      <organization>tucana.at</organization>
    </developer>
    <developer>
      <name>Rodney Waldhoff</name>
      <id>rwaldhoff</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>David Weinrich</name>
      <id>dweinr1</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Dirk Verbeeck</name>
      <id>dirkv</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Yoav Shapira</name>
      <id>yoavs</id>
      <email>yoavs@apache.org</email>
      <organization>Apache Software Foundation</organization>
    </developer>
    <developer>
      <name>Phil Steitz</name>
      <id>psteitz</id>
      <email></email>
      <organization></organization>
    </developer>
    <developer>
      <name>Jörg Schaible</name>
      <id>joehni</id>
      <email>joerg.schaible@gmx.de</email>
      <organization></organization>
      <timezone>+1</timezone>
    </developer>
    <developer>
      <name>Mark Thomas</name>
      <id>markt</id>
      <email>markt@apache.org</email>
      <organization>Apache Software Foundation</organization>
    </developer>
  </developers>
  <contributors>
    <contributor>
      <name>Todd Carmichael</name>
      <email>toddc@concur.com</email>
    </contributor>
    <contributor>
      <name>Wayne Woodfield</name>
    </contributor>
    <contributor>
      <name>Dain Sundstrom</name>
      <email>dain@apache.org</email>
    </contributor>
  </contributors>

  <dependencies>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
      <version>1.5.1</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- For managed connections -->
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-jta_1.1_spec</artifactId>
       <version>1.1</version>
       <optional>true</optional>
    </dependency>

    <!-- tomcat naming jars for jndi reference tests -->
    <dependency>
      <groupId>tomcat</groupId>
      <artifactId>naming-common</artifactId>
      <version>5.0.28</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>tomcat</groupId>
      <artifactId>naming-java</artifactId>
      <version>5.0.28</version>
      <scope>test</scope>
    </dependency>

    <!-- dragged in by tomcat-naming jars - only for jndi tests -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
       <version>1.0.4</version>
       <scope>test</scope>
    </dependency>

    <!-- for testing of managed connections -->
    <dependency>
      <groupId>org.apache.geronimo.modules</groupId>
      <artifactId>geronimo-transaction</artifactId>
       <version>1.2-beta</version>
       <scope>test</scope>
    </dependency>

    <!-- required under jdk 1.4 so jocl can have a sax parser -->
    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis</artifactId>
      <version>2.0.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xerces</artifactId>
      <version>2.4.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <properties>
    <maven.compile.source>1.5</maven.compile.source>
    <maven.compile.target>1.5</maven.compile.target>
    <commons.componentid>dbcp</commons.componentid>
    <commons.release.version>1.2.2</commons.release.version>
    <commons.binary.suffix></commons.binary.suffix>
    <commons.jira.id>DBCP</commons.jira.id>
    <commons.jira.pid>12310469</commons.jira.pid>
  </properties>

  <build>
    <sourceDirectory>src/java</sourceDirectory>
    <testSourceDirectory>src/test</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/test</directory>
        <includes>
          <include>testpool.jocl</include>
        </includes>
      </resource>
      <resource>
        <directory>.</directory>
        <targetPath>META-INF</targetPath>
          <includes>
            <include>NOTICE.txt</include>
            <include>LICENSE.txt</include>
          </includes>
        </resource>
      </resources>
      <testResources>
        <testResource>
          <directory>${basedir}/src/test</directory>
          <includes>
            <include>testpool.jocl</include>
          </includes>
        </testResource>
      </testResources>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
            <reportFormat>plain</reportFormat>
              <includes>
                <include>org/apache/commons/dbcp/TestAbandonedObjectPool.java</include>
                <include>org/apache/commons/jocl/TestJOCLContentHandler.java</include>
                <include>org/apache/commons/dbcp/TestDelegatingConnection.java</include>
                <include>org/apache/commons/dbcp/TestPoolableConnection.java</include>
                <include>org/apache/commons/dbcp/TestDelegatingPreparedStatement.java</include>
                <include>org/apache/commons/dbcp/TestDelegatingStatement.java</include>
                <include>org/apache/commons/dbcp/TestJOCLed.java</include>
                <include>org/apache/commons/dbcp/TestManual.java</include>

                <include>org/apache/commons/dbcp/TestBasicDataSourceFactory.java</include>
                <include>org/apache/commons/dbcp/TestBasicDataSource.java</include>
                <include>org/apache/commons/dbcp/TestAbandonedBasicDataSource.java</include>
                <include>org/apache/commons/dbcp/TestPStmtPooling.java</include>
                <include>org/apache/commons/dbcp/TestPStmtPoolingBasicDataSource.java</include>
                <include>org/apache/commons/dbcp/TestPoolingDataSource.java</include>
                <include>org/apache/commons/dbcp/TestJndi.java</include>

                <include>org/apache/commons/dbcp/datasources/TestFactory.java</include>
                <include>org/apache/commons/dbcp/datasources/TestKeyedCPDSConnectionFactory.java</include>
                <include>org/apache/commons/dbcp/datasources/TestPerUserPoolDataSource.java</include>
                <include>org/apache/commons/dbcp/datasources/TestSharedPoolDataSource.java</include>
                <include>org/apache/commons/dbcp/datasources/TestInstanceKeyDataSource.java</include>

                <include>org/apache/commons/dbcp/managed/TestBasicManagedDataSource.java</include>
                <include>org/apache/commons/dbcp/managed/TestManagedDataSource.java</include>
                <include>org/apache/commons/dbcp/managed/TestManagedDataSourceInTx.java</include>
              </includes>
          </configuration>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
            <descriptors>
              <descriptor>src/assembly/bin.xml</descriptor>
              <descriptor>src/assembly/src.xml</descriptor>
            </descriptors>
            <tarLongFileMode>gnu</tarLongFileMode>
          </configuration>
        </plugin>
      </plugins>
    </build>
    <reporting>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>findbugs-maven-plugin</artifactId>
          <version>1.2</version>
          <configuration>
            <threshold>Normal</threshold>
            <effort>Default</effort>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>cobertura-maven-plugin</artifactId>
          <version>2.2</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-javadoc-plugin</artifactId>
          <version>2.4</version>
          <configuration>
            <links>
              <link>http://java.sun.com/j2se/1.5.0/docs/api</link>
              <link>http://commons.apache.org/pool/api-1.5</link>
              <link>http://java.sun.com/j2ee/sdk_1.3/techdocs/api</link>
            </links>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-changes-plugin</artifactId>
          <version>2.0</version>
          <configuration>
            <xmlPath>${basedir}/xdocs/changes.xml</xmlPath>
            <issueLinkTemplate>%URL%/%ISSUE%</issueLinkTemplate>
          </configuration>
          <reportSets>
            <reportSet>
              <reports>
                <report>changes-report</report>
              </reports>
            </reportSet>
          </reportSets>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <version>2.1</version>
          <configuration>
            <configLocation>${basedir}/checkstyle.xml</configLocation>
            <enableRulesSummary>false</enableRulesSummary>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-pmd-plugin</artifactId>
          <version>2.3</version>
          <configuration>
            <rulesets>
              <ruleset>checkstyle.xml</ruleset>
            </rulesets>
          </configuration>
        </plugin>
        <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>clirr-maven-plugin</artifactId>
        <version>2.2.2</version>
        <configuration>
          <comparisonVersion>1.2.2</comparisonVersion>
          <minSeverity>info</minSeverity>
        </configuration>
      </plugin>
      </plugins>
    </reporting>
</project>


text:
function [Accuracy, AccuracyTableColNames]= ParameterSearch(superIteration, reorganizedGroups, runParams,SVMParams  )
%ParameterSearch uses the given parameters to
allColNames=reorganizedGroups.ColNames;

nIterations =  length(runParams.SVM_Parameters);
Accuracy = cell([nIterations (4 + 4*length(reorganizedGroups))]);

%get the column names for the accuracy table
AccuracyTableColNames=cell([length(reorganizedGroups.Peaks)*4+3 1 ]);
AccuracyTableColNames{1}='Parameters';
AccuracyTableColNames{2}='Whole Training Accuracy';
AccuracyTableColNames{3}='Whole Testing Accuracy (true/positive)';
AccuracyTableColNames{4}='Strange Points';
AccuracyTableColNames{5}='Common Points';
AccuracyTableColNames{6}='Surviving Points';
for K=1:length(reorganizedGroups.Peaks)
    AccuracyTableColNames{6+ (K-1) *4  + 1} = [reorganizedGroups.Peaks{K}.GroupName ' called correctly in group (true/positive)'];
    AccuracyTableColNames{6+ (K-1) *4  + 2} = [reorganizedGroups.Peaks{K}.GroupName ' called incorrectly in other groups (false/positive)'];
    AccuracyTableColNames{6+ (K-1) *4  + 3} = [reorganizedGroups.Peaks{K}.GroupName ' misscalled as '];
    AccuracyTableColNames{6+ (K-1) *4  + 4} = [reorganizedGroups.Peaks{K}.GroupName ' misscalled in '];
end

%set the basic parameters of the svm training

kernalProps=CopyKernalParameters(SVMParams);%DefaultKernalParameters();
kernalProps.nbclass =length(reorganizedGroups.Peaks);

for I=1:nIterations
    disp('Running iteration');
    disp(I);

    %randomly select cols
    rSVMParameters = runParams.SVM_Parameters{I};
    nParams =  length(rSVMParameters);
    colNumbers = [];%randperm(length(allColNames),nParams);
    for J=1:nParams
        for K=1:length(allColNames)
            if (strcmp( rSVMParameters{J}, allColNames{K})==true)
                colNumbers =[colNumbers K];
            end
        end
    end

    nParams = random('unid',length(allColNames)-1)+1;
    colNumbers = randperm(length(allColNames),nParams);
    SelectedParams = allColNames(colNumbers );
    disp(SelectedParams);

    if isempty(colNumbers)==false

        SelectedParams = allColNames(colNumbers );
        disp(SelectedParams);

        %write out the parameters used, with a format that can be written to a
        %csv file
        parameterColNames =[];
        for K=1:(length(SelectedParams)-1)
            parameterColNames =[parameterColNames  SelectedParams{K} '| ']; %#ok<AGROW>
        end
        parameterColNames =[parameterColNames  SelectedParams{length(SelectedParams)} ]; %#ok<AGROW>

        %now build a training set
        % SVM=matlab_libSVM.SVM_Interface(SVMParams);

        Training =[];

        for K=1:length(reorganizedGroups.Peaks)
            t= reorganizedGroups.Peaks{K}.Train(:,colNumbers);
            % arrObj = NET.convertArray(t,'System.Double');

            %         oneS=matlab_libSVM.SVM_Interface(SVM.CopyParameter());
            %         oneS.SetTrainTable(0,arrObj);
            %         oneS.SetToOneClass(.7);
            %         oneS.TrainModel();
            %         oneSVM{K}=oneS;
            oneSVM{K}=CreateOneClass(t,CopyKernalParameters(kernalProps)) ;

            Training=vertcat(Training, t);
            peakTables{K}=t;
            %         e=zeros(1,length(reorganizedGroups.Peaks{K}.Train))+K;
            %         TrainingGroupNumbers =[TrainingGroupNumbers e]; %#ok<AGROW>
            %         Training=vertcat(Training, reorganizedGroups.Peaks{K}.Train(:,colNumbers)); %#ok<AGROW>
        end

        % commonSVM= FindCommon(oneSVM,peakTables,SVM.CopyParameter());
        commonSVM= FindCommon(oneSVM,peakTables,CopyKernalParameters(kernalProps));

        %     anomolySVM= matlab_libSVM.SVM_Interface(SVM.CopyParameter());
        %     arrObj = NET.convertArray(Training,'System.Double');
        %     anomolySVM.SetTrainTable(0,arrObj);
        %     anomolySVM.SetToOneClass(.2);
        %     anomolySVM.TrainModel();
        anomolySVM=CreateOneClass(Training,CopyKernalParameters(kernalProps)) ;
        anomolySVM.threshold =( anomolySVM.threshold +anomolySVM.rho)/2;
        Training=[];
        Labels =[];
        for K=1:length(reorganizedGroups.Peaks)
            %first remove thos points that are common to all the datasets
            t= reorganizedGroups.Peaks{K}.Train(:,colNumbers);
            %         arrObj = NET.convertArray(t,'System.Double');
            %         uniqueS=find(double( commonSVM.PredictTest(arrObj))==-1);

            classify = svmoneclassval(t,commonSVM.xsup,commonSVM.alpha,commonSVM.rho,commonSVM.kernel,commonSVM.kerneloption);
            uniqueS=find(classify<commonSVM.threshold);
            t=t(uniqueS,:);

            Training =vertcat(Training, t);
            Labels = vertcat( Labels, ones([size(t,1) 1]).*K);
            %then train the svm with the remaining points
            %         arrObj = NET.convertArray(t,'System.Double');
            %         SVM.SetTrainTable(K-1,arrObj);
        end

        %do a C and Gamma search to get all the training to the maximum accuracy
        %selectedSVMParameters=SVM.SelectParameters();

        %now train the model for a final dataset

        disp('=========== Training Accuracy ============');
        %     trainingAccuracy= SVM.TrainModel() ;
        %
        try
            [ allPeaksSVM trainingAccuracy]=  CreateMultiClass(Training,Labels, CopyKernalParameters(kernalProps));

            disp(trainingAccuracy);

            %run each dataset through the svm to see what is predicted
            nTotalPeaks=0;
            nGood=0;
            nMixed=0;
            nLeft =0;
            for K=1:length(reorganizedGroups.Peaks)
                %once again, find all the peaks that fall into the common pit
                t= reorganizedGroups.Peaks{K}.Test(:,colNumbers);
                %         arrObj = NET.convertArray(t,'System.Double');
                %         common=find(double( commonSVM.PredictTest(arrObj))==-1);
                %
                nTotalPeaks = nTotalPeaks+ size(t,1);
                classify = svmoneclassval(t,anomolySVM.xsup,anomolySVM.alpha,anomolySVM.rho,anomolySVM.kernel,anomolySVM.kerneloption);
                goodPeaks=find(classify>anomolySVM.threshold);
                nGood =nGood + length(goodPeaks);
                t=t(goodPeaks,:);

                classify = svmoneclassval(t,commonSVM.xsup,commonSVM.alpha,commonSVM.rho,commonSVM.kernel,commonSVM.kerneloption);
                uniqueS=find(classify<commonSVM.threshold);
                nMixed =nMixed +size(t,1)-length(uniqueS) ;
                t=t(uniqueS,:);
                nLeft =nLeft + size(t,1);
                %         arrObj = NET.convertArray(t,'System.Double');
                %         predictedGroups{K} =double( SVM.PredictTest(arrObj));
                %         unknowns{K}=double( anomolySVM.PredictTest(arrObj));

                predictedGroups{K}  = svmmultivaloneagainstone(t,allPeaksSVM.xsup,allPeaksSVM.w,allPeaksSVM.b,allPeaksSVM.nbsv,allPeaksSVM.kernel,allPeaksSVM.kerneloption);
            end

            Accuracy{I,1}=parameterColNames;
            Accuracy{I,2}=trainingAccuracy;
            Accuracy{I,4}=nGood/nTotalPeaks*100;
            Accuracy{I,5}=nMixed/nTotalPeaks*100;
            Accuracy{I,6}=nLeft/nTotalPeaks*100;
            wholeTruePositive =0;
            wholeCount =0;
            for K=1:length(reorganizedGroups.Peaks)

                predict= predictedGroups{K};
                truePositive =  length(find(predict==K));
                wholeTruePositive =wholeTruePositive + truePositive;
                wholeCount =wholeCount + length(predict);

                truePositive = truePositive / length(predict) *100;

                otherPredict = [];
                missCallFreq=zeros([length(reorganizedGroups.Peaks) 1]);
                for J=1:length(reorganizedGroups.Peaks)
                    if K~=J
                        temp =predictedGroups{J};
                        otherPredict = [otherPredict  temp'];
                        missCallFreq(J)=length(find(K== temp));
                    end
                end
                otherPredict=otherPredict(:);

                trueNegative = length(find(otherPredict==K))/length(otherPredict)*100;

                counts = histc(predict,1:length(reorganizedGroups.Peaks));
                counts(K)=0;
                [v idx]=max(counts);

                mostCommon_In_Miscall =     reorganizedGroups.Peaks{idx}.GroupName;

                [v idx]=max(missCallFreq);
                mostCommon_Out_Misscall =     reorganizedGroups.Peaks{idx}.GroupName;

                Accuracy{I,6+(K-1)*4+1}= truePositive;
                Accuracy{I,6+(K-1)*4+2}= trueNegative;
                Accuracy{I,6+(K-1)*4+3}= mostCommon_In_Miscall;
                Accuracy{I,6+(K-1)*4+4}= mostCommon_Out_Misscall;
            end
            Accuracy{I,3}=wholeTruePositive/wholeCount*100;
        catch mex
            dispError(mex);
        end
    end
end

figure;
uitable('Data',Accuracy,'ColumnName',AccuracyTableColNames,'Units','normalized','position',[0,0,1,1]);
disp('===============================')

t=vertcat(AccuracyTableColNames',Accuracy);
cell2csv(['c:\temp\randomAccuracy' num2str(superIteration) '.csv'],t);

end