public static List<RecordedEvent> readAllEvents(Path path) throws IOException {
        try (RecordingFile r = new RecordingFile(path)) {
            List<RecordedEvent> list = new ArrayList<>();
            while (r.hasMoreEvents()) {
                list.add(r.readEvent());
            }
            return list;
        }
    }

package jdk.jfr.consumer;

import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import jdk.jfr.EventType;
import jdk.jfr.internal.MetadataDescriptor;
import jdk.jfr.internal.Type;
import jdk.jfr.internal.consumer.ChunkHeader;
import jdk.jfr.internal.consumer.ChunkParser;
import jdk.jfr.internal.consumer.FileAccess;
import jdk.jfr.internal.consumer.RecordingInput;

/**
 * A recording file.
 *

 * The following example shows how read and print all events in a recording file.
 *
 *
{@literal
 * try (RecordingFile recordingFile = new RecordingFile(Paths.get("recording.jfr"))) {
 *   while (recordingFile.hasMoreEvents()) {
 *     RecordedEvent event = recordingFile.readEvent();
 *     System.out.println(event);
 *   }
 * }
 * }

 *
 * @since 9
 */
public final class RecordingFile implements Closeable {

    private boolean isLastEventInChunk;

    private final File file;

    private RecordingInput input;

    private ChunkParser chunkParser;

    private RecordedEvent nextEvent;

    private boolean eof;

    /**
     * Creates a recording file.
     *
     * @param file the path of the file to open, not {@code null}
     * @throws IOException if it's not a valid recording file, or an I/O error
     *         occurred
     * @throws NoSuchFileException if the {@code file} can't be located
     *
     * @throws SecurityException if a security manager exists and its
     *         {@code checkRead} method denies read access to the file.
     */
    public RecordingFile(Path file) throws IOException {
        this.file = file.toFile();
        this.input = new RecordingInput(this.file, FileAccess.UNPRIVILEGED);
        findNext();
    }

    /**
     * Reads the next event in the recording.
     *
     * @return the next event, not {@code null}
     *
     * @throws EOFException if no more events exist in the recording file
     * @throws IOException if an I/O error occurs
     *
     * @see #hasMoreEvents()
     */
    public RecordedEvent readEvent() throws IOException {
        if (eof) {
            ensureOpen();
            throw new EOFException();
        }
        isLastEventInChunk = false;
        RecordedEvent event = nextEvent;
        nextEvent = chunkParser.readEvent();
        if (nextEvent == null) {
            isLastEventInChunk = true;
            findNext();
        }
        return event;
    }

    /**
     * Returns {@code true} if unread events exist in the recording file,
     * {@code false} otherwise.
     *
     * @return {@code true} if unread events exist in the recording, {@code false}
     *         otherwise.
     */
    public boolean hasMoreEvents() {
        return !eof;
    }

    /**
     * Returns a list of all event types in this recording.
     *
     * @return a list of event types, not {@code null}
     * @throws IOException if an I/O error occurred while reading from the file
     *
     * @see #hasMoreEvents()
     */
    public List<EventType> readEventTypes() throws IOException {
        ensureOpen();
        MetadataDescriptor previous = null;
        List<EventType> types = new ArrayList<>();
        HashSet<Long> foundIds = new HashSet<>();
        try (RecordingInput ri = new RecordingInput(file, FileAccess.UNPRIVILEGED)) {
            ChunkHeader ch = new ChunkHeader(ri);
            aggregateEventTypeForChunk(ch, null, types, foundIds);
            while (!ch.isLastChunk()) {
                ch = ch.nextHeader();
                previous = aggregateEventTypeForChunk(ch, previous, types, foundIds);
            }
        }
        return types;
    }

    List<Type> readTypes() throws IOException {
        ensureOpen();
        MetadataDescriptor previous = null;
        List<Type> types = new ArrayList<>();
        HashSet<Long> foundIds = new HashSet<>();
        try (RecordingInput ri = new RecordingInput(file, FileAccess.UNPRIVILEGED)) {
            ChunkHeader ch = new ChunkHeader(ri);
            ch.awaitFinished();
            aggregateTypeForChunk(ch, null, types, foundIds);
            while (!ch.isLastChunk()) {
                ch = ch.nextHeader();
                previous = aggregateTypeForChunk(ch, previous, types, foundIds);
            }
        }
        return types;
    }

    private MetadataDescriptor aggregateTypeForChunk(ChunkHeader ch, MetadataDescriptor previous, List<Type> types, HashSet<Long> foundIds) throws IOException {
        MetadataDescriptor m = ch.readMetadata(previous);
        for (Type t : m.getTypes()) {
            if (!foundIds.contains(t.getId())) {
                types.add(t);
                foundIds.add(t.getId());
            }
        }
        return m;
    }

    private static MetadataDescriptor aggregateEventTypeForChunk(ChunkHeader ch, MetadataDescriptor previous, List<EventType> types, HashSet<Long> foundIds) throws IOException {
        MetadataDescriptor m = ch.readMetadata(previous);
        for (EventType t : m.getEventTypes()) {
            if (!foundIds.contains(t.getId())) {
                types.add(t);
                foundIds.add(t.getId());
            }
        }
        return m;
    }

    /**
     * Closes this recording file and releases any system resources that are
     * associated with it.
     *
     * @throws IOException if an I/O error occurred
     */
    public void close() throws IOException {
        if (input != null) {
            eof = true;
            input.close();
            chunkParser = null;
            input = null;
            nextEvent = null;
        }
    }

    /**
     * Returns a list of all events in a file.
     *

     * This method is intended for simple cases where it's convenient to read all
     * events in a single operation. It isn't intended for reading large files.
     *
     * @param path the path to the file, not {@code null}
     *
     * @return the events from the file as a {@code List} object; whether the
     *         {@code List} is modifiable or not is implementation dependent and
     *         therefore not specified, not {@code null}
     *
     * @throws IOException if an I/O error occurred, it's not a Flight Recorder
     *         file or a version of a JFR file that can't be parsed
     *
     * @throws SecurityException if a security manager exists and its
     *         {@code checkRead} method denies read access to the file.
     */

    File getFile() {
        return file;
    }

    boolean isLastEventInChunk() {
        return isLastEventInChunk;
    }

    // either sets next to an event or sets eof to true
    private void findNext() throws IOException {
        while (nextEvent == null) {
            if (chunkParser == null) {
                chunkParser = new ChunkParser(input);
            } else if (!chunkParser.isLastChunk()) {
                chunkParser = chunkParser.nextChunkParser();
            } else {
                eof = true;
                return;
            }
            nextEvent = chunkParser.readEvent();
        }
    }

    private void ensureOpen() throws IOException {
        if (input == null) {
            throw new IOException("Stream Closed");
        }
    }
}


while (!ch.isLastChunk()) {
                ch = ch.nextHeader();
                previous = aggregateEventTypeForChunk(ch, previous, types, foundIds);
            }

package jdk.jfr.consumer;

import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import jdk.jfr.EventType;
import jdk.jfr.internal.MetadataDescriptor;
import jdk.jfr.internal.Type;
import jdk.jfr.internal.consumer.ChunkHeader;
import jdk.jfr.internal.consumer.ChunkParser;
import jdk.jfr.internal.consumer.FileAccess;
import jdk.jfr.internal.consumer.RecordingInput;

/**
 * A recording file.
 *

 * The following example shows how read and print all events in a recording file.
 *
 *
{@literal
 * try (RecordingFile recordingFile = new RecordingFile(Paths.get("recording.jfr"))) {
 *   while (recordingFile.hasMoreEvents()) {
 *     RecordedEvent event = recordingFile.readEvent();
 *     System.out.println(event);
 *   }
 * }
 * }

 *
 * @since 9
 */
public final class RecordingFile implements Closeable {

    private boolean isLastEventInChunk;

    private final File file;

    private RecordingInput input;

    private ChunkParser chunkParser;

    private RecordedEvent nextEvent;

    private boolean eof;

    /**
     * Creates a recording file.
     *
     * @param file the path of the file to open, not {@code null}
     * @throws IOException if it's not a valid recording file, or an I/O error
     *         occurred
     * @throws NoSuchFileException if the {@code file} can't be located
     *
     * @throws SecurityException if a security manager exists and its
     *         {@code checkRead} method denies read access to the file.
     */
    public RecordingFile(Path file) throws IOException {
        this.file = file.toFile();
        this.input = new RecordingInput(this.file, FileAccess.UNPRIVILEGED);
        findNext();
    }

    /**
     * Reads the next event in the recording.
     *
     * @return the next event, not {@code null}
     *
     * @throws EOFException if no more events exist in the recording file
     * @throws IOException if an I/O error occurs
     *
     * @see #hasMoreEvents()
     */
    public RecordedEvent readEvent() throws IOException {
        if (eof) {
            ensureOpen();
            throw new EOFException();
        }
        isLastEventInChunk = false;
        RecordedEvent event = nextEvent;
        nextEvent = chunkParser.readEvent();
        if (nextEvent == null) {
            isLastEventInChunk = true;
            findNext();
        }
        return event;
    }

    /**
     * Returns {@code true} if unread events exist in the recording file,
     * {@code false} otherwise.
     *
     * @return {@code true} if unread events exist in the recording, {@code false}
     *         otherwise.
     */
    public boolean hasMoreEvents() {
        return !eof;
    }

    /**
     * Returns a list of all event types in this recording.
     *
     * @return a list of event types, not {@code null}
     * @throws IOException if an I/O error occurred while reading from the file
     *
     * @see #hasMoreEvents()
     */
    public List<EventType> readEventTypes() throws IOException {
        ensureOpen();
        MetadataDescriptor previous = null;
        List<EventType> types = new ArrayList<>();
        HashSet<Long> foundIds = new HashSet<>();
        try (RecordingInput ri = new RecordingInput(file, FileAccess.UNPRIVILEGED)) {
            ChunkHeader ch = new ChunkHeader(ri);
            aggregateEventTypeForChunk(ch, null, types, foundIds);

        }
        return types;
    }

    List<Type> readTypes() throws IOException {
        ensureOpen();
        MetadataDescriptor previous = null;
        List<Type> types = new ArrayList<>();
        HashSet<Long> foundIds = new HashSet<>();
        try (RecordingInput ri = new RecordingInput(file, FileAccess.UNPRIVILEGED)) {
            ChunkHeader ch = new ChunkHeader(ri);
            ch.awaitFinished();
            aggregateTypeForChunk(ch, null, types, foundIds);
            while (!ch.isLastChunk()) {
                ch = ch.nextHeader();
                previous = aggregateTypeForChunk(ch, previous, types, foundIds);
            }
        }
        return types;
    }

    private MetadataDescriptor aggregateTypeForChunk(ChunkHeader ch, MetadataDescriptor previous, List<Type> types, HashSet<Long> foundIds) throws IOException {
        MetadataDescriptor m = ch.readMetadata(previous);
        for (Type t : m.getTypes()) {
            if (!foundIds.contains(t.getId())) {
                types.add(t);
                foundIds.add(t.getId());
            }
        }
        return m;
    }

    private static MetadataDescriptor aggregateEventTypeForChunk(ChunkHeader ch, MetadataDescriptor previous, List<EventType> types, HashSet<Long> foundIds) throws IOException {
        MetadataDescriptor m = ch.readMetadata(previous);
        for (EventType t : m.getEventTypes()) {
            if (!foundIds.contains(t.getId())) {
                types.add(t);
                foundIds.add(t.getId());
            }
        }
        return m;
    }

    /**
     * Closes this recording file and releases any system resources that are
     * associated with it.
     *
     * @throws IOException if an I/O error occurred
     */
    public void close() throws IOException {
        if (input != null) {
            eof = true;
            input.close();
            chunkParser = null;
            input = null;
            nextEvent = null;
        }
    }

    /**
     * Returns a list of all events in a file.
     * <p>
     * This method is intended for simple cases where it's convenient to read all
     * events in a single operation. It isn't intended for reading large files.
     *
     * @param path the path to the file, not {@code null}
     *
     * @return the events from the file as a {@code List} object; whether the
     *         {@code List} is modifiable or not is implementation dependent and
     *         therefore not specified, not {@code null}
     *
     * @throws IOException if an I/O error occurred, it's not a Flight Recorder
     *         file or a version of a JFR file that can't be parsed
     *
     * @throws SecurityException if a security manager exists and its
     *         {@code checkRead} method denies read access to the file.
     */
    public static List<RecordedEvent> readAllEvents(Path path) throws IOException {
        try (RecordingFile r = new RecordingFile(path)) {
            List<RecordedEvent> list = new ArrayList<>();
            while (r.hasMoreEvents()) {
                list.add(r.readEvent());
            }
            return list;
        }
    }

    File getFile() {
        return file;
    }

    boolean isLastEventInChunk() {
        return isLastEventInChunk;
    }

    // either sets next to an event or sets eof to true
    private void findNext() throws IOException {
        while (nextEvent == null) {
            if (chunkParser == null) {
                chunkParser = new ChunkParser(input);
            } else if (!chunkParser.isLastChunk()) {
                chunkParser = chunkParser.nextChunkParser();
            } else {
                eof = true;
                return;
            }
            nextEvent = chunkParser.readEvent();
        }
    }

    private void ensureOpen() throws IOException {
        if (input == null) {
            throw new IOException("Stream Closed");
        }
    }
}


public Class<?> getServiceInterface() {
        return this.serviceInterface;
    }

package org.springframework.remoting.support;

/**
 * Abstract base class for classes that access a remote service.
 * Provides a "serviceInterface" bean property.
 *
 *
Note that the service interface being used will show some signs of
 * remotability, like the granularity of method calls that it offers.
 * Furthermore, it has to have serializable arguments etc.
 *
 *
Accessors are supposed to throw Spring's generic
 * {@link org.springframework.remoting.RemoteAccessException} in case
 * of remote invocation failure, provided that the service interface
 * does not declare {@code java.rmi.RemoteException}.
 *
 * @author Juergen Hoeller
 * @since 13.05.2003
 * @see org.springframework.remoting.RemoteAccessException
 * @see java.rmi.RemoteException
 */
public abstract class RemoteAccessor extends RemotingSupport {

    private Class<?> serviceInterface;

    /**
     * Set the interface of the service to access.
     * The interface must be suitable for the particular service and remoting strategy.
     *
Typically required to be able to create a suitable service proxy,
     * but can also be optional if the lookup returns a typed proxy.
     */
    public void setServiceInterface(Class<?> serviceInterface) {
        if (serviceInterface != null && !serviceInterface.isInterface()) {
            throw new IllegalArgumentException("'serviceInterface' must be an interface");
        }
        this.serviceInterface = serviceInterface;
    }

    /**
     * Return the interface of the service to access.
     */


public MediaFormat createMediaFormat(String encoding) {
        return createMediaFormat(encoding, CLOCK_RATE_NOT_SPECIFIED);
    }

/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * See terms of license at gnu.org.
 */
package org.jitsi.impl.neomedia.format;

import java.util.*;
import javax.media.*;
import javax.media.format.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.service.neomedia.format.*;
import org.jitsi.util.*;

/**
 * Implements <tt>MediaFormatFactory</tt> for the JMF <tt>Format</tt> types.
 *
 * @author Lyubomir Marinov
 */
public class MediaFormatFactoryImpl implements MediaFormatFactory {

    /**
     * The <tt>Logger</tt> used by the <tt>MediaFormatFactoryImpl</tt> class and
     * its instances for logging output.
     */
    private static final Logger logger = Logger.getLogger(MediaFormatFactoryImpl.class);

    /**
     * Creates an unknown <tt>MediaFormat</tt>.
     *
     * @param type <tt>MediaType</tt>
     * @return unknown <tt>MediaFormat</tt>
     */
    public MediaFormat createUnknownMediaFormat(MediaType type) {
        Format unknown = null;
        /*
         * FIXME Why is a VideoFormat instance created for MediaType.AUDIO and
         * an AudioFormat instance for MediaType.VIDEO?
         */
        if (type.equals(MediaType.AUDIO))
            unknown = new VideoFormat("unknown");
        else if (type.equals(MediaType.VIDEO))
            unknown = new AudioFormat("unknown");
        return MediaFormatImpl.createInstance(unknown);
    }

    /**
     * Creates a <tt>MediaFormat</tt> for the specified <tt>encoding</tt> with
     * default clock rate and set of format parameters. If <tt>encoding</tt> is
     * known to this <tt>MediaFormatFactory</tt>, returns a
     * <tt>MediaFormat</tt> which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance. Otherwise, returns <tt>null</tt>.
     *
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt> which
     * is either an <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt>
     * instance if <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(String)
     */

    /**
     * Creates a <tt>MediaFormat</tt> for the specified RTP payload type with
     * default clock rate and set of format parameters. If
     * <tt>rtpPayloadType</tt> is known to this <tt>MediaFormatFactory</tt>,
     * returns a <tt>MediaFormat</tt> which is either an
     * <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt> instance.
     * Otherwise, returns <tt>null</tt>.
     *
     * @param rtpPayloadType the RTP payload type of the <tt>MediaFormat</tt> to
     * create
     * @return a <tt>MediaFormat</tt> with the specified <tt>rtpPayloadType</tt>
     * which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance if <tt>rtpPayloadType</tt> is known to
     * this <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(byte)
     */
    public MediaFormat createMediaFormat(byte rtpPayloadType) {
        /*
         * We know which are the MediaFormat instances with the specified
         * rtpPayloadType but we cannot directly return them because they do not
         * reflect the user's configuration with respect to being enabled and
         * disabled.
         */
        for (MediaFormat rtpPayloadTypeMediaFormat : MediaUtils.getMediaFormats(rtpPayloadType)) {
            MediaFormat mediaFormat = createMediaFormat(rtpPayloadTypeMediaFormat.getEncoding(), rtpPayloadTypeMediaFormat.getClockRate());
            if (mediaFormat != null)
                return mediaFormat;
        }
        return null;
    }

    /**
     * Creates a <tt>MediaFormat</tt> for the specified <tt>encoding</tt> with
     * the specified <tt>clockRate</tt> and a default set of format parameters.
     * If <tt>encoding</tt> is known to this <tt>MediaFormatFactory</tt>,
     * returns a <tt>MediaFormat</tt> which is either an
     * <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt> instance.
     * Otherwise, returns <tt>null</tt>.
     *
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for
     * @param clockRate the clock rate in Hz to create a <tt>MediaFormat</tt>
     * for
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt> and
     * <tt>clockRate</tt> which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance if <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(String, double)
     */
    public MediaFormat createMediaFormat(String encoding, double clockRate) {
        return createMediaFormat(encoding, clockRate, 1);
    }

    /**
     * Creates a <tt>MediaFormat</tt> for the specified <tt>encoding</tt>,
     * <tt>clockRate</tt> and <tt>channels</tt> and a default set of format
     * parameters. If <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>, returns a <tt>MediaFormat</tt> which is
     * either an <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt>
     * instance. Otherwise, returns <tt>null</tt>.
     *
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for
     * @param clockRate the clock rate in Hz to create a <tt>MediaFormat</tt>
     * for
     * @param channels the number of available channels (1 for mono, 2 for
     * stereo) if it makes sense for the <tt>MediaFormat</tt> with the specified
     * <tt>encoding</tt>; otherwise, ignored
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt>,
     * <tt>clockRate</tt> and <tt>channels</tt> and a default set of format
     * parameters which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance if <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(String, double, int)
     */
    public MediaFormat createMediaFormat(String encoding, double clockRate, int channels) {
        return createMediaFormat(encoding, clockRate, channels, null);
    }

    private MediaFormat createMediaFormat(String encoding, double clockRate, int channels, Map<String, String> fmtps) {
        for (MediaFormat format : getSupportedMediaFormats(encoding, clockRate)) {
            /*
             * The mediaType, encoding and clockRate properties are sure to
             * match because format is the result of the search for encoding and
             * clockRate. We just want to make sure that the channels and the
             * format parameters match.
             */
            if (format.matches(format.getMediaType(), format.getEncoding(), format.getClockRate(), channels, fmtps))
                return format;
        }
        return null;
    }

    /**
     * Creates a <tt>MediaFormat</tt> for the specified <tt>encoding</tt>,
     * <tt>clockRate</tt> and set of format parameters. If <tt>encoding</tt> is
     * known to this <tt>MediaFormatFactory</tt>, returns a <tt>MediaFormat</tt>
     * which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance. Otherwise, returns <tt>null</tt>.
     *
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for
     * @param clockRate the clock rate in Hz to create a <tt>MediaFormat</tt>
     * for
     * @param formatParams any codec specific parameters which have been
     * received via SIP/SDP or XMPP/Jingle
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt>,
     * <tt>clockRate</tt> and set of format parameters which is either an
     * <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt> instance if
     * <tt>encoding</tt> is known to this <tt>MediaFormatFactory</tt>;
     * otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(String, double, Map, Map)
     */
    public MediaFormat createMediaFormat(String encoding, double clockRate, Map<String, String> formatParams, Map<String, String> advancedParams) {
        return createMediaFormat(encoding, clockRate, 1, -1, formatParams, advancedParams);
    }

    /**
     * Creates a <tt>MediaFormat</tt> for the specified <tt>encoding</tt>,
     * <tt>clockRate</tt>, <tt>channels</tt> and set of format parameters. If
     * <tt>encoding</tt> is known to this <tt>MediaFormatFactory</tt>, returns a
     * <tt>MediaFormat</tt> which is either an <tt>AudioMediaFormat</tt> or a
     * <tt>VideoMediaFormat</tt> instance. Otherwise, returns <tt>null</tt>.
     *
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for
     * @param clockRate the clock rate in Hz to create a <tt>MediaFormat</tt>
     * for
     * @param frameRate the frame rate in number of frames per second to
     * create a <tt>MediaFormat</tt> for
     * @param channels the number of available channels (1 for mono, 2 for
     * stereo) if it makes sense for the <tt>MediaFormat</tt> with the specified
     * <tt>encoding</tt>; otherwise, ignored
     * @param formatParams any codec specific parameters which have been
     * received via SIP/SDP or XMPP/Jingle
     * @param advancedParams any parameters which have been
     * received via SIP/SDP or XMPP/Jingle
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt>,
     * <tt>clockRate</tt>, <tt>channels</tt> and set of format parameters which
     * is either an <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt>
     * instance if <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     * @see MediaFormatFactory#createMediaFormat(String, double, int, float, Map, Map)
     */
    public MediaFormat createMediaFormat(String encoding, double clockRate, int channels, float frameRate, Map<String, String> formatParams, Map<String, String> advancedParams) {
        MediaFormat mediaFormat = createMediaFormat(encoding, clockRate, channels, formatParams);
        if (mediaFormat == null)
            return null;
        /*
          * MediaFormatImpl is immutable so if the caller wants to change the
          * format parameters and/or the advanced attributes, we'll have to
          * create a new MediaFormatImpl.
          */
        Map<String, String> formatParameters = null;
        Map<String, String> advancedParameters = null;
        if ((formatParams != null) && !formatParams.isEmpty())
            formatParameters = formatParams;
        if ((advancedParams != null) && !advancedParams.isEmpty())
            advancedParameters = advancedParams;
        if ((formatParameters != null) || (advancedParameters != null)) {
            switch(mediaFormat.getMediaType()) {
                case AUDIO:
                    mediaFormat = new AudioMediaFormatImpl(((AudioMediaFormatImpl) mediaFormat).getFormat(), formatParameters, advancedParameters);
                    break;
                case VIDEO:
                    VideoMediaFormatImpl videoMediaFormatImpl = (VideoMediaFormatImpl) mediaFormat;
                    /*
                 * If the format of VideoMediaFormatImpl is
                 * a ParameterizedVideoFormat, it's possible for the format
                 * parameters of that ParameterizedVideoFormat and of the new
                 * VideoMediaFormatImpl (to be created) to be out of sync. While
                 * it's not technically perfect, it should be practically safe
                 * for the format parameters which distinguish VideoFormats with
                 * the same encoding and clock rate because mediaFormat has
                 * already been created in sync with formatParams (with respect
                 * to the format parameters which distinguish VideoFormats with
                 * the same encoding and clock rate).
                 */
                    mediaFormat = new VideoMediaFormatImpl(videoMediaFormatImpl.getFormat(), videoMediaFormatImpl.getClockRate(), frameRate, formatParameters, advancedParameters);
                    break;
                default:
                    mediaFormat = null;
            }
        }
        return mediaFormat;
    }

    /**
     * Creates a <tt>MediaFormat</tt> either for the specified
     * <tt>rtpPayloadType</tt> or for the specified <tt>encoding</tt>,
     * <tt>clockRate</tt>, <tt>channels</tt> and set of format parameters. If
     * <tt>encoding</tt> is known to this <tt>MediaFormatFactory</tt>, ignores
     * <tt>rtpPayloadType</tt> and returns a <tt>MediaFormat</tt> which is
     * either an <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt>
     * instance. If <tt>rtpPayloadType</tt> is not
     * {@link MediaFormat#RTP_PAYLOAD_TYPE_UNKNOWN} and <tt>encoding</tt> is
     * <tt>null</tt>, uses the encoding associated with <tt>rtpPayloadType</tt>.
     *
     * @param rtpPayloadType the RTP payload type to create a
     * <tt>MediaFormat</tt> for; {@link MediaFormat#RTP_PAYLOAD_TYPE_UNKNOWN} if
     * <tt>encoding</tt> is not <tt>null</tt>. If <tt>rtpPayloadType</tt> is not
     * <tt>MediaFormat#RTP_PAYLOAD_TYPE_UNKNOWN</tt> and <tt>encoding</tt> is
     * not <tt>null</tt>, <tt>rtpPayloadType</tt> is ignored
     * @param encoding the well-known encoding (name) to create a
     * <tt>MediaFormat</tt> for; <tt>null</tt>
     * @param clockRate the clock rate in Hz to create a <tt>MediaFormat</tt>
     * for
     * @param frameRate the frame rate in number of frames per second to
     * create a <tt>MediaFormat</tt> for
     * @param channels the number of available channels (1 for mono, 2 for
     * stereo) if it makes sense for the <tt>MediaFormat</tt> with the specified
     * <tt>encoding</tt>; otherwise, ignored
     * @param formatParams any codec specific parameters which have been
     * received via SIP/SDP or XMPP/Jingle
     * @param advancedParams any parameters which have been
     * received via SIP/SDP or XMPP/Jingle
     * @return a <tt>MediaFormat</tt> with the specified <tt>encoding</tt>,
     * <tt>clockRate</tt>, <tt>channels</tt> and set of format parameters which
     * is either an <tt>AudioMediaFormat</tt> or a <tt>VideoMediaFormat</tt>
     * instance if <tt>encoding</tt> is known to this
     * <tt>MediaFormatFactory</tt>; otherwise, <tt>null</tt>
     */
    public MediaFormat createMediaFormat(byte rtpPayloadType, String encoding, double clockRate, int channels, float frameRate, Map<String, String> formatParams, Map<String, String> advancedParams) {
        /*
         * If rtpPayloadType is specified, use it only to figure out encoding
         * and/or clockRate in case either one of them is unknown.
         */
        if ((MediaFormat.RTP_PAYLOAD_TYPE_UNKNOWN != rtpPayloadType) && ((encoding == null) || (CLOCK_RATE_NOT_SPECIFIED == clockRate))) {
            MediaFormat[] rtpPayloadTypeMediaFormats = MediaUtils.getMediaFormats(rtpPayloadType);
            if (rtpPayloadTypeMediaFormats.length > 0) {
                if (encoding == null)
                    encoding = rtpPayloadTypeMediaFormats[0].getEncoding();
                // Assign or check the clock rate.
                if (CLOCK_RATE_NOT_SPECIFIED == clockRate)
                    clockRate = rtpPayloadTypeMediaFormats[0].getClockRate();
                else {
                    boolean clockRateIsValid = false;
                    for (MediaFormat rtpPayloadTypeMediaFormat : rtpPayloadTypeMediaFormats) if (rtpPayloadTypeMediaFormat.getEncoding().equals(encoding) && (rtpPayloadTypeMediaFormat.getClockRate() == clockRate)) {
                        clockRateIsValid = true;
                        break;
                    }
                    if (!clockRateIsValid)
                        return null;
                }
            }
        }
        return createMediaFormat(encoding, clockRate, channels, frameRate, formatParams, advancedParams);
    }

    /**
     * Gets the <tt>MediaFormat</tt>s among the specified <tt>mediaFormats</tt>
     * which have the specified <tt>encoding</tt> and, optionally,
     * <tt>clockRate</tt>.
     *
     * @param mediaFormats the <tt>MediaFormat</tt>s from which to filter out
     * only the ones which have the specified <tt>encoding</tt> and, optionally,
     * <tt>clockRate</tt>
     * @param encoding the well-known encoding (name) of the
     * <tt>MediaFormat</tt>s to be retrieved
     * @param clockRate the clock rate of the <tt>MediaFormat</tt>s to be
     * retrieved; {@link #CLOCK_RATE_NOT_SPECIFIED} if any clock rate is
     * acceptable
     * @return a <tt>List</tt> of the <tt>MediaFormat</tt>s among
     * <tt>mediaFormats</tt> which have the specified <tt>encoding</tt> and,
     * optionally, <tt>clockRate</tt>
     */
    private List<MediaFormat> getMatchingMediaFormats(MediaFormat[] mediaFormats, String encoding, double clockRate) {
        /*
         * XXX Use String#equalsIgnoreCase(String) because some clients transmit
         * some of the codecs starting with capital letters.
         */
        /*
         * As per RFC 3551.4.5.2, because of a mistake in RFC 1890 and for
         * backward compatibility, G.722 should always be announced as 8000 even
         * though it is wideband. So, if someone is looking for G722/16000,
         * then: Forgive them, for they know not what they do!
         */
        if ("G722".equalsIgnoreCase(encoding) && (16000 == clockRate)) {
            clockRate = 8000;
            if (logger.isInfoEnabled())
                logger.info("Suppressing erroneous 16000 announcement for G.722");
        }
        List<MediaFormat> supportedMediaFormats = new ArrayList<MediaFormat>();
        for (MediaFormat mediaFormat : mediaFormats) {
            if (mediaFormat.getEncoding().equalsIgnoreCase(encoding) && ((CLOCK_RATE_NOT_SPECIFIED == clockRate) || (mediaFormat.getClockRate() == clockRate))) {
                supportedMediaFormats.add(mediaFormat);
            }
        }
        return supportedMediaFormats;
    }

    /**
     * Gets the <tt>MediaFormat</tt>s supported by this
     * <tt>MediaFormatFactory</tt> and the <tt>MediaService</tt> associated with
     * it and having the specified <tt>encoding</tt> and, optionally,
     * <tt>clockRate</tt>.
     *
     * @param encoding the well-known encoding (name) of the
     * <tt>MediaFormat</tt>s to be retrieved
     * @param clockRate the clock rate of the <tt>MediaFormat</tt>s to be
     * retrieved; {@link #CLOCK_RATE_NOT_SPECIFIED} if any clock rate is
     * acceptable
     * @return a <tt>List</tt> of the <tt>MediaFormat</tt>s supported by the
     * <tt>MediaService</tt> associated with this <tt>MediaFormatFactory</tt>
     * and having the specified encoding and, optionally, clock rate
     */
    private List<MediaFormat> getSupportedMediaFormats(String encoding, double clockRate) {
        EncodingConfiguration encodingConfiguration = NeomediaServiceUtils.getMediaServiceImpl().getCurrentEncodingConfiguration();
        List<MediaFormat> supportedMediaFormats = getMatchingMediaFormats(encodingConfiguration.getAllEncodings(MediaType.AUDIO), encoding, clockRate);
        if (supportedMediaFormats.isEmpty())
            supportedMediaFormats = getMatchingMediaFormats(encodingConfiguration.getAllEncodings(MediaType.VIDEO), encoding, clockRate);
        return supportedMediaFormats;
    }
}


public static Mesh latheCurve(Curve curve, int axis, int segments, double angle, double radius) {
        return LatheDialog.latheCurve(curve, axis, segments, angle, radius);
    }

package artofillusion.tools;

import artofillusion.*;
import artofillusion.object.*;
import artofillusion.ui.*;
import buoy.widget.*;

/**
 * The lathe tool creates new objects by rotating a curve around an axis.
 */
public class LatheTool implements ModellingTool {

    public static final int X_AXIS = 0;

    public static final int Y_AXIS = 1;

    public static final int Z_AXIS = 2;

    public static final int AXIS_THROUGH_ENDS = 3;

    public LatheTool() {
    }

    /* Get the text that appear as the menu item.*/
    @Override
    public String getName() {
        return Translate.text("menu.lathe");
    }

    /* See whether an appropriate object is selected and either display an error
     message, or bring up the extrude window. */
    @Override
    public void commandSelected(LayoutWindow window) {
        Scene scene = window.getScene();
        int[] selection = window.getSelectedIndices();
        if (selection.length == 1) {
            ObjectInfo obj = scene.getObject(selection[0]);
            if (obj.getObject() instanceof Curve) {
                new LatheDialog(window, obj);
                return;
            }
        }
        new BStandardDialog("", "You must select a single curve to lathe.", BStandardDialog.INFORMATION).showMessageDialog(window.getFrame());
    }

    /**
     * Create a mesh by rotating a curve around an axis.
     *
     * @param curve      the Curve to lathe
     * @param axis       the axis around which to rotate the curve.  This should be one of the constants
     *                   defined by this class: X_AXIS, Y_AXIS, Z_AXIS, or AXIS_THROUGH_ENDS.
     * @param segments   the number of segments the lathed mesh should include.  The larger this number,
     *                   the higher the resolution of the resulting mesh.
     * @param angle      the total angle by which to rotate the curve, in degrees.
     * @param radius     the radius by which to offset the rotation axis from the curve before performing
     *                   the lathe operation.
     * @return the mesh created by lathing the curve
     */


public SQLQuery<T> toSQLQuery(ITypeDesc typeDesc) {
        throw new UnsupportedOperationException("This method is not supported. ");
    }

package com.gigaspaces.internal.query;

import com.gigaspaces.internal.metadata.ITypeDesc;
import com.gigaspaces.internal.query.predicate.ISpacePredicate;
import com.gigaspaces.server.ServerEntry;
import com.j_spaces.core.cache.CacheManager;
import com.j_spaces.core.client.SQLQuery;

@com.gigaspaces.api.InternalApi
public class CustomSpaceQuery<T> extends AbstractSpaceQuery<T> {

    private static final long serialVersionUID = 2166424609217572245L;

    public CustomSpaceQuery() {
        super();
    }

    public CustomSpaceQuery(String entryClassName, ISpacePredicate predicate) {
        super(entryClassName, predicate);
    }

    public CustomSpaceQuery(Class<?> entryClass, ISpacePredicate predicate) {
        super(entryClass, predicate);
    }

    public boolean matches(CacheManager cacheManager, ServerEntry entry, String skipAlreadyMatchedIndexPath) {
        return getPredicate().execute(entry);
    }

    /* (non-Javadoc)
     * @see com.gigaspaces.internal.query_poc.server.ICustomQuery#toSQLQuery(com.gigaspaces.internal.metadata.ITypeDesc)
     */


@Override
    protected void addParameterDefinitions(List<ParameterDefinition> paramList) {
        paramList.add(new ParameterDefinitionImpl(PARAM_TYPE, DataTypeDefinition.QNAME, true, getParamDisplayLabel(PARAM_TYPE), false, "ac-types"));
    }

/*
 * #%L
 * Alfresco Repository
 * %%
 * %%
 * This file is part of the Alfresco software.
 * If the software was purchased under a paid Alfresco license, the terms of
 *
 * #L%
 */
package org.alfresco.repo.action.evaluator;

import java.util.List;
import org.alfresco.repo.action.ParameterDefinitionImpl;
import org.alfresco.service.cmr.action.ActionCondition;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.QName;

/**
 * No condition evaluator implementation.
 *
 * @author Roy Wetherall
 */
public class IsSubTypeEvaluator extends ActionConditionEvaluatorAbstractBase {

    public static final String NAME = "is-subtype";

    public static final String PARAM_TYPE = "type";

    /**
     * The node service
     */
    private NodeService nodeService;

    /**
     * The dictionary service
     */
    private DictionaryService dictionaryService;

    /**
     * Set node service
     *
     * @param nodeService  the node service
     */
    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    /**
     * Set dictionary service
     *
     * @param dictionaryService  the dictionary service
     */
    public void setDictionaryService(DictionaryService dictionaryService) {
        this.dictionaryService = dictionaryService;
    }

    /**
     * @see org.alfresco.repo.action.evaluator.ActionConditionEvaluatorAbstractBase#evaluateImpl(org.alfresco.service.cmr.action.ActionCondition, org.alfresco.service.cmr.repository.NodeRef)
     */
    public boolean evaluateImpl(ActionCondition ruleCondition, NodeRef actionedUponNodeRef) {
        boolean result = false;
        if (this.nodeService.exists(actionedUponNodeRef) == true) {
            // TODO: Move this type check into its own Class Evaluator
            QName nodeType = nodeService.getType(actionedUponNodeRef);
            if (dictionaryService.isSubClass(nodeType, (QName) ruleCondition.getParameterValue(PARAM_TYPE))) {
                result = true;
            }
        }
        return result;
    }

    /**
     * @see org.alfresco.repo.action.ParameterizedItemAbstractBase#addParameterDefinitions(java.util.List)
     */


public static void inputToOutput(InputStream inputStream, OutputStream outputStream) throws IOException {
        int read = 0;
        byte[] bytes = new byte[1024 * 1024];
        while ((read = inputStream.read(bytes)) > 0) {
            byte[] readBytes = new byte[read];
            System.arraycopy(bytes, 0, readBytes, 0, read);
            outputStream.write(readBytes);
        }
    }

package com.hccake.ballcat.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @author lingting 2021/4/21 17:45
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtils {

    /**
     * 克隆文件流
     * @param stream 源流
     * @param amounts 数量
     * @author lingting 2021-04-16 16:18
     */
    public static InputStream[] clone(InputStream stream, Integer amounts) throws IOException {
        InputStream[] streams = new InputStream[amounts];
        ByteArrayOutputStream[] outs = new ByteArrayOutputStream[amounts];
        byte[] buffer = new byte[1024];
        int len;
        while ((len = stream.read(buffer)) > -1) {
            for (int i = 0, outsLength = outs.length; i < outsLength; i++) {
                ByteArrayOutputStream out = outs[i];
                if (out == null) {
                    out = new ByteArrayOutputStream();
                    outs[i] = out;
                }
                out.write(buffer, 0, len);
            }
        }
        for (int i = 0; i < outs.length; i++) {
            streams[i] = new ByteArrayInputStream(outs[i].toByteArray());
        }
        return streams;
    }

    /**
     * 流转字符串
     * @author lingting 2021-04-29 18:07
     */
    public static String toString(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    /**
     * 将输入流内容写入输出流
     * @param inputStream 输入流
     * @param outputStream 输出流
     * @author lingting 2021-10-19 22:41
     */

    /**
     * 从流中读取 int
     * @author lingting 2021-07-22 14:54
     */
    public static int readInt(InputStream is, int noOfBytes, boolean bigEndian) throws IOException {
        int ret = 0;
        int sv = bigEndian ? ((noOfBytes - 1) * 8) : 0;
        int cnt = bigEndian ? -8 : 8;
        for (int i = 0; i < noOfBytes; i++) {
            ret |= is.read() << sv;
            sv += cnt;
        }
        return ret;
    }
}


while ((read = inputStream.read(bytes)) > 0) {
            byte[] readBytes = new byte[read];
            System.arraycopy(bytes, 0, readBytes, 0, read);
            outputStream.write(readBytes);
        }

package com.hccake.ballcat.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * @author lingting 2021/4/21 17:45
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtils {

    /**
     * 克隆文件流
     * @param stream 源流
     * @param amounts 数量
     * @author lingting 2021-04-16 16:18
     */
    public static InputStream[] clone(InputStream stream, Integer amounts) throws IOException {
        InputStream[] streams = new InputStream[amounts];
        ByteArrayOutputStream[] outs = new ByteArrayOutputStream[amounts];
        byte[] buffer = new byte[1024];
        int len;
        while ((len = stream.read(buffer)) > -1) {
            for (int i = 0, outsLength = outs.length; i < outsLength; i++) {
                ByteArrayOutputStream out = outs[i];
                if (out == null) {
                    out = new ByteArrayOutputStream();
                    outs[i] = out;
                }
                out.write(buffer, 0, len);
            }
        }
        for (int i = 0; i < outs.length; i++) {
            streams[i] = new ByteArrayInputStream(outs[i].toByteArray());
        }
        return streams;
    }

    /**
     * 流转字符串
     * @author lingting 2021-04-29 18:07
     */
    public static String toString(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    /**
     * 将输入流内容写入输出流
     * @param inputStream 输入流
     * @param outputStream 输出流
     * @author lingting 2021-10-19 22:41
     */
    public static void inputToOutput(InputStream inputStream, OutputStream outputStream) throws IOException {
        int read = 0;
        byte[] bytes = new byte[1024 * 1024];

    }

    /**
     * 从流中读取 int
     * @author lingting 2021-07-22 14:54
     */
    public static int readInt(InputStream is, int noOfBytes, boolean bigEndian) throws IOException {
        int ret = 0;
        int sv = bigEndian ? ((noOfBytes - 1) * 8) : 0;
        int cnt = bigEndian ? -8 : 8;
        for (int i = 0; i < noOfBytes; i++) {
            ret |= is.read() << sv;
            sv += cnt;
        }
        return ret;
    }
}


private void new_estimators() {
        for (int i = 0; i < m_numClusters; i++) {
            for (int j = 0; j < m_numAttribs; j++) {
                m_modelNormal[i][j][0] = m_modelNormal[i][j][1] = m_modelNormal[i][j][2] = 0.0;
            }
        }
    }

/*
 * ------------------------------------------------------------------------
 *
 *  Website: http://www.knime.org; Email: example@nnthink.com
 *
 *
 *  KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
 *  Hence, KNIME and ECLIPSE are both independent programs and are not
 *  KNIME and ECLIPSE being a combined program, KNIME GMBH herewith grants
 *  you the additional permission to use and propagate KNIME together with
 *  ECLIPSE with only the license terms in place for ECLIPSE applying to
 *  license terms of ECLIPSE themselves allow for the respective use and
 *  propagation of ECLIPSE together with KNIME.
 *
 *  Additional permission relating to nodes for KNIME that extend the Node
 *  Extension (and in particular that are based on subclasses of NodeModel,
 *  NodeDialog, and NodeView) and that only interoperate with KNIME through
 *  standard APIs ("Nodes"):
 *  Nodes are deemed to be separate and independent programs and to not be
 *  covered works.  Notwithstanding anything to the contrary in the
 *  License, the License does not apply to Nodes, you are not required to
 *  prepare and propagate Nodes, in each case even if such Nodes are
 *  propagated with or for interoperation with KNIME.  The owner of a Node
 *  may freely choose the license terms applicable to such Node, including
 *  when such Node is propagated with or for interoperation with KNIME.
 * --------------------------------------------------------------------- *
 *
 */
package org.knime.knip.core.algorithm.extendedem;

import java.util.Random;

/**
 *  Simple EM (expectation maximisation) class.

 *

 * EM assigns a probability distribution to each instance which indicates the probability of it belonging to each of the
 * clusters. EM can decide how many clusters to create by cross validation, or you may specify apriori how many clusters
 * to generate.

 *

 * The cross validation performed to determine the number of clusters is done in the following steps:

 * 1. the number of clusters is set to 1

 * 2. the training set is split randomly into 10 folds.

 * 3. EM is performed 10 times using the 10 folds the usual CV way.

 * 4. the loglikelihood is averaged over all 10 results.

 * 5. if loglikelihood has increased the number of clusters is increased by 1 and the program continues at step 2.

 *

 * The number of folds is fixed to 10, as long as the number of instances in the training set is not smaller 10. If this
 * is the case the number of folds is set equal to the number of instances.
 *

 *
 *
 *  Valid options are:
 *

 *
 *

 * -N <num>
 *  number of clusters. If omitted or -1 specified, then
 *  cross validation is used to select the number of clusters.
 *

 *
 *

 * -I <num>
 *  max iterations.
 * (default 100)
 *

 *
 *

 * -V
 *  verbose.
 *

 *
 *

 * -M <num>
 *  minimum allowable standard deviation for normal density
 *  computation
 *  (default 1e-6)
 *

 *
 *

 * -O
 *  Display model in old format (good when there are many clusters)
 *

 *
 *

 * -S <num>
 *  Random number seed.
 *  (default 100)
 *

 *
 *
 *
 * @version $Revision: 6298 $
 * @author Christian Dietz
 * @author Martin Horn
 * @author Michael Zinsmaier
 * @author Mark Hall (example@nnthink.com)
 * @author Eibe Frank (example@nnthink.com)
 */
public class ExtendedEM {

    private static final long serialVersionUID = 8348181483812829475L;

    /**
     * hold the normal estimators for each cluster
     */
    private double[][][] m_modelNormal;

    /**
     * default minimum standard deviation
     */
    private final double m_minStdDev = 1e-6;

    private double[] m_minStdDevPerAtt;

    /**
     * hold the weights of each instance for each cluster
     */
    private double[][] m_weights;

    /**
     * the prior probabilities for clusters
     */
    private double[] m_priors;

    /**
     * training instances
     */
    private InstancesTmp m_theInstances = null;

    /**
     * number of clusters selected by the user or cross validation
     */
    private int m_numClusters;

    /**
     * number of attributes
     */
    private int m_numAttribs;

    /**
     * maximum iterations to perform
     */
    private int m_maxIterations;

    /**
     * attribute min values
     */
    private double[] m_minValues;

    /**
     * attribute max values
     */
    private double[] m_maxValues;

    /**
     * random number generator
     */
    private Random m_rr;

    private boolean m_verbose;

    /**
     * the default seed value
     */
    private int m_seedDefault = 1;

    /**
     * The random number seed.
     */
    private final int m_seed = m_seedDefault;

    private void normalize(final double[] doubles) {
        double sum = 0;
        for (int i = 0; i < doubles.length; i++) {
            sum += doubles[i];
        }
        normalize(doubles, sum);
    }

    private void normalize(final double[] doubles, final double sum) {
        if (Double.isNaN(sum)) {
            throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
        }
        if (sum == 0) {
            // Maybe this should just be a return.
            throw new IllegalArgumentException("Can't normalize array. Sum is zero.");
        }
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] /= sum;
        }
    }

    /**
     * Set the number of clusters (-1 to select by CV).
     *
     * @param n the number of clusters
     * @throws Exception if n is 0
     */
    public void setNumClusters(final int n) {
        if (n == 0) {
            throw new RuntimeException("Number of clusters must be > 0. (or -1 to " + "select by cross validation).");
        }
        if (n < 0) {
            m_numClusters = -1;
        } else {
            m_numClusters = n;
        }
    }

    /**
     * Set start centers of the EM Algo
     *
     * @param inst
     */
    private InstancesTmp m_centers;

    public void setCenters(final InstancesTmp inst) {
        m_centers = inst;
    }

    private int[] m_clusterSizes;

    public void setClusterSizes(final int[] clusterSizes) {
        m_clusterSizes = clusterSizes.clone();
    }

    public void setMaxInterations(final int max) {
        m_maxIterations = max;
    }

    /**
     * Initialise estimators and storage.
     *
     * @param inst the instances
     * @throws Exception if initialization fails
     */
    private void EM_Init(final InstancesTmp inst) {
        int i, j;
        m_weights = new double[inst.numInstances()][m_numClusters];
        m_modelNormal = new double[m_numClusters][m_numAttribs][3];
        m_priors = new double[m_numClusters];
        final int[] clusterSizes = m_clusterSizes;
        final InstancesTmp centers = m_centers;
        for (i = 0; i < m_numClusters; i++) {
            final InstanceTmp center = centers.instance(i);
            for (j = 0; j < m_numAttribs; j++) {
                final double minStdD = (m_minStdDevPerAtt != null) ? m_minStdDevPerAtt[j] : m_minStdDev;
                final double mean = (center.isMissing(j)) ? inst.meanOrMode(j) : center.value(j);
                m_modelNormal[i][j][0] = mean;
                double stdv = ((m_maxValues[j] - m_minValues[j]) / (2 * m_numClusters));
                if (stdv < minStdD) {
                    stdv = inst.attributeStats(j).m_numericStats.getStdDev();
                    if (Double.isInfinite(stdv)) {
                        stdv = minStdD;
                    }
                    if (stdv < minStdD) {
                        stdv = minStdD;
                    }
                }
                if (stdv <= 0) {
                    stdv = m_minStdDev;
                }
                m_modelNormal[i][j][1] = stdv;
                m_modelNormal[i][j][2] = 1.0;
            }
        }
        for (j = 0; j < m_numClusters; j++) {
            m_priors[j] = clusterSizes[j];
        }
        normalize(m_priors);
    }

    /**
     * calculate prior probabilites for the clusters
     *
     * @param inst the instances
     * @throws Exception if priors can't be calculated
     */
    private void estimate_priors(final InstancesTmp inst) {
        for (int i = 0; i < m_numClusters; i++) {
            m_priors[i] = 0.0;
        }
        for (int i = 0; i < inst.numInstances(); i++) {
            for (int j = 0; j < m_numClusters; j++) {
                m_priors[j] += inst.instance(i).weight() * m_weights[i][j];
            }
        }
        normalize(m_priors);
    }

    /**
     * New probability estimators for an iteration
     */

/**
     * The M step of the EM algorithm.
     *
     * @param inst the training instances
     * @throws Exception if something goes wrong
     */
    private void M(final InstancesTmp inst) {
        int i, j, l;
        new_estimators();
        estimate_priors(inst);
        for (i = 0; i < m_numClusters; i++) {
            for (j = 0; j < m_numAttribs; j++) {
                for (l = 0; l < inst.numInstances(); l++) {
                    final InstanceTmp in = inst.instance(l);
                    if (!in.isMissing(j)) {
                        m_modelNormal[i][j][0] += (in.value(j) * in.weight() * m_weights[l][i]);
                        m_modelNormal[i][j][2] += in.weight() * m_weights[l][i];
                        m_modelNormal[i][j][1] += (in.value(j) * in.value(j) * in.weight() * m_weights[l][i]);
                    }
                }
            }
        }
        // calcualte mean and std deviation for numeric attributes
        for (j = 0; j < m_numAttribs; j++) {
            if (!inst.attribute(j).isNominal()) {
                for (i = 0; i < m_numClusters; i++) {
                    if (m_modelNormal[i][j][2] <= 0) {
                        m_modelNormal[i][j][1] = Double.MAX_VALUE;
                        m_modelNormal[i][j][0] = m_minStdDev;
                    } else {
                        // variance
                        m_modelNormal[i][j][1] = (m_modelNormal[i][j][1] - ((m_modelNormal[i][j][0] * m_modelNormal[i][j][0]) / m_modelNormal[i][j][2])) / (m_modelNormal[i][j][2]);
                        if (m_modelNormal[i][j][1] < 0) {
                            m_modelNormal[i][j][1] = 0;
                        }
                        // std dev
                        final double minStdD = (m_minStdDevPerAtt != null) ? m_minStdDevPerAtt[j] : m_minStdDev;
                        m_modelNormal[i][j][1] = Math.sqrt(m_modelNormal[i][j][1]);
                        if ((m_modelNormal[i][j][1] <= minStdD)) {
                            m_modelNormal[i][j][1] = inst.attributeStats(j).m_numericStats.getStdDev();
                            if ((m_modelNormal[i][j][1] <= minStdD)) {
                                m_modelNormal[i][j][1] = minStdD;
                            }
                        }
                        if ((m_modelNormal[i][j][1] <= 0)) {
                            m_modelNormal[i][j][1] = m_minStdDev;
                        }
                        if (Double.isInfinite(m_modelNormal[i][j][1])) {
                            m_modelNormal[i][j][1] = m_minStdDev;
                        }
                        // mean
                        m_modelNormal[i][j][0] /= m_modelNormal[i][j][2];
                    }
                }
            }
        }
    }

    /**
     * The E step of the EM algorithm. Estimate cluster membership probabilities.
     *
     * @param inst the training instances
     * @param change_weights whether to change the weights
     * @return the average log likelihood
     * @throws Exception if computation fails
     */
    private double E(final InstancesTmp inst, final boolean change_weights) {
        double loglk = 0.0, sOW = 0.0;
        for (int l = 0; l < inst.numInstances(); l++) {
            final InstanceTmp in = inst.instance(l);
            loglk += in.weight() * logDensityForInstance(in);
            sOW += in.weight();
            if (change_weights) {
                m_weights[l] = distributionForInstance(in);
            }
        }
        return loglk / sOW;
    }

    public ExtendedEM() {
        m_seedDefault = 100;
        m_maxIterations = 100;
    }

    /**
     * Return the normal distributions for the cluster models
     *
     * @return a double[][][] value
     */
    public double[][][] getClusterModelsNumericAtts() {
        return m_modelNormal;
    }

    /**
     * Updates the minimum and maximum values for all the attributes based on a new instance.
     *
     * @param instance the new instance
     */
    private void updateMinMax(final InstanceTmp instance) {
        for (int j = 0; j < m_theInstances.numAttributes(); j++) {
            if (!instance.isMissing(j)) {
                if (Double.isNaN(m_minValues[j])) {
                    m_minValues[j] = instance.value(j);
                    m_maxValues[j] = instance.value(j);
                } else {
                    if (instance.value(j) < m_minValues[j]) {
                        m_minValues[j] = instance.value(j);
                    } else {
                        if (instance.value(j) > m_maxValues[j]) {
                            m_maxValues[j] = instance.value(j);
                        }
                    }
                }
            }
        }
    }

    /**
     * Generates a clusterer. Has to initialize all fields of the clusterer that are not being set via options.
     *
     * @param data set of instances serving as training data
     * @throws Exception if the clusterer has not been generated successfully
     */
    public void buildClusterer(final InstancesTmp data) {
        m_theInstances = data;
        // calculate min and max values for attributes
        m_minValues = new double[m_theInstances.numAttributes()];
        m_maxValues = new double[m_theInstances.numAttributes()];
        for (int i = 0; i < m_theInstances.numAttributes(); i++) {
            m_minValues[i] = m_maxValues[i] = Double.NaN;
        }
        for (int i = 0; i < m_theInstances.numInstances(); i++) {
            updateMinMax(m_theInstances.instance(i));
        }
        doEM();
        // save memory
        m_theInstances = new InstancesTmp(m_theInstances, 0);
    }

    /**
     * Perform the EM algorithm
     *
     * @throws Exception if something goes wrong
     */
    private void doEM() {
        m_rr = new Random(getSeed());
        // throw away numbers to avoid problem of similar initial
        // numbers
        // from a similar seed
        for (int i = 0; i < 10; i++) {
            m_rr.nextDouble();
        }
        m_numAttribs = m_theInstances.numAttributes();
        // fit full training set
        EM_Init(m_theInstances);
        iterate(m_theInstances, m_verbose);
    }

    /**
     * iterates the E and M steps until the log likelihood of the data converges.
     *
     * @param inst the training instances.
     * @param report be verbose.
     * @return the log likelihood of the data
     * @throws Exception if something goes wrong
     */
    private double iterate(final InstancesTmp inst, final boolean report) {
        int i;
        double llkold = 0.0;
        double llk = 0.0;
        boolean ok = false;
        int seed = getSeed();
        int restartCount = 0;
        while (!ok) {
            try {
                for (i = 0; i < m_maxIterations; i++) {
                    llkold = llk;
                    llk = E(inst, true);
                    if (report) {
                        System.out.println("Loglikely: " + llk);
                    }
                    if (i > 0) {
                        if ((llk - llkold) < 1e-6) {
                            break;
                        }
                    }
                    M(inst);
                }
                ok = true;
            } catch (final Exception ex) {
                ex.printStackTrace();
                seed++;
                restartCount++;
                m_rr = new Random(seed);
                for (int z = 0; z < 10; z++) {
                    m_rr.nextDouble();
                    m_rr.nextInt();
                }
                if (restartCount > 5) {
                    m_numClusters--;
                    restartCount = 0;
                }
                EM_Init(m_theInstances);
            }
        }
        return llk;
    }

    /**
     * Gets the seed for the random number generations
     *
     * @return the seed for the random number generation
     */
    public int getSeed() {
        return m_seed;
    }

    /**
     * Computes the density for a given instance.
     *
     * @param instance the instance to compute the density for
     * @return the density.
     * @exception Exception if the density could not be computed successfully
     */
    private int maxIndex(final double[] doubles) {
        double maximum = 0;
        int maxIndex = 0;
        for (int i = 0; i < doubles.length; i++) {
            if ((i == 0) || (doubles[i] > maximum)) {
                maxIndex = i;
                maximum = doubles[i];
            }
        }
        return maxIndex;
    }

    public double logDensityForInstance(final InstanceTmp instance) {
        final double[] a = logJointDensitiesForInstance(instance);
        final double max = a[maxIndex(a)];
        double sum = 0.0;
        for (int i = 0; i < a.length; i++) {
            sum += Math.exp(a[i] - max);
        }
        return max + Math.log(sum);
    }

    private double[] logs2probs(final double[] a) {
        final double max = a[maxIndex(a)];
        double sum = 0.0;
        final double[] result = new double[a.length];
        for (int i = 0; i < a.length; i++) {
            result[i] = Math.exp(a[i] - max);
            sum += result[i];
        }
        normalize(result, sum);
        return result;
    }

    /**
     * Computes the log of the conditional density (per cluster) for a given instance.
     *
     * @param inst the instance to compute the density for
     * @return an array containing the estimated densities
     * @throws Exception if the density could not be computed successfully
     */
    public double[] logDensityPerClusterForInstance(final InstanceTmp inst) {
        int i, j;
        double logprob;
        final double[] wghts = new double[m_numClusters];
        for (i = 0; i < m_numClusters; i++) {
            logprob = 0.0;
            for (j = 0; j < m_numAttribs; j++) {
                if (!inst.isMissing(j)) {
                    logprob += logNormalDens(inst.value(j), m_modelNormal[i][j][0], m_modelNormal[i][j][1]);
                }
            }
            wghts[i] = logprob;
        }
        return wghts;
    }

    /**
     * Returns the cluster priors.
     *
     * @return the cluster priors
     */
    public double[] clusterPriors() {
        final double[] n = new double[m_priors.length];
        System.arraycopy(m_priors, 0, n, 0, n.length);
        return n;
    }

    /**
     * Constant for normal distribution.
     */
    private static double m_normConst = Math.log(Math.sqrt(2 * Math.PI));

    /**
     * Density function of normal distribution.
     *
     * @param x input value
     * @param mean mean of distribution
     * @param stdDev standard deviation of distribution
     * @return the density
     */
    private double logNormalDens(final double x, final double mean, final double stdDev) {
        final double diff = x - mean;
        return -((diff * diff) / (2 * stdDev * stdDev)) - m_normConst - Math.log(stdDev);
    }

    public class DiscreteEstimator {

        private final double[] m_Counts;

        private double m_SumOfCounts;

        public DiscreteEstimator(final int numSymbols, final boolean laplace) {
            m_Counts = new double[numSymbols];
            m_SumOfCounts = 0;
            if (laplace) {
                for (int i = 0; i < numSymbols; i++) {
                    m_Counts[i] = 1;
                }
                m_SumOfCounts = numSymbols;
            }
        }

        public void addValue(final double data, final double weight) {
            m_Counts[(int) data] += weight;
            m_SumOfCounts += weight;
        }

        public double getProbability(final double data) {
            if (m_SumOfCounts == 0) {
                return 0;
            }
            return m_Counts[(int) data] / m_SumOfCounts;
        }
    }

    public double[] distributionForInstance(final InstanceTmp instance) {
        return logs2probs(logJointDensitiesForInstance(instance));
    }

    /**
     * Returns the logs of the joint densities for a given instance.
     *
     * @param inst the instance
     * @return the array of values
     * @exception Exception if values could not be computed
     */
    public double[] logJointDensitiesForInstance(final InstanceTmp inst) {
        final double[] weights = logDensityPerClusterForInstance(inst);
        final double[] priors = clusterPriors();
        for (int i = 0; i < weights.length; i++) {
            if (priors[i] > 0) {
                weights[i] += Math.log(priors[i]);
            }
        }
        return weights;
    }
}


DataSource lookupNonTxDataSource(String dataSourceName) throws NamingException;

package org.glassfish.persistence.jpa;

import jakarta.persistence.spi.ClassTransformer;
import jakarta.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import javax.naming.NamingException;
import jakarta.validation.ValidatorFactory;
import org.glassfish.api.deployment.DeploymentContext;
import org.glassfish.deployment.common.RootDeploymentDescriptor;

/**
 * @author Mitesh Meswani
 * This encapsulates information needed  to load or unload persistence units.
 */
public interface ProviderContainerContractInfo {

    static final String DEFAULT_DS_NAME = "jdbc/__default";

    /**
     * @return a class loader that is used to load persistence entities
     * bundled in this application.
     */
    ClassLoader getClassLoader();

    /**
     * @return a temp class loader that is used to load persistence entities
     * bundled in this application.
     */
    ClassLoader getTempClassloader();

    /**
     * Adds ClassTransformer to underlying Application's classloader
     */
    void addTransformer(ClassTransformer transformer);

    /**
     * @return absolute path of the location where application is exploded.
     */
    String getApplicationLocation();

    /**
     * Looks up DataSource with JNDI name given by dataSourceName
     * @param dataSourceName
     * @return DataSource with JNDI name given by dataSourceName
     * @throws javax.naming.NamingException
     */
    DataSource lookupDataSource(String dataSourceName) throws NamingException;

    /**
     * Looks up Non transactional DataSource with JNDI name given by dataSourceName
     * @param dataSourceName
     * @return Non transactional DataSource with JNDI name given by dataSourceName
     * @throws NamingException
     */

    /**
     * get instance of ValidatorFactory for this environment
     */
    ValidatorFactory getValidatorFactory();

    /**
     * Will be called while loading an application.
     * @return true if java2DB is required false otherwise
     */
    boolean isJava2DBRequired();

    /**
     * @return DeploymentContext associated with this instance.
     */
    DeploymentContext getDeploymentContext();

    /**
     * Register the give emf with underlying container
     * @param unitName Name of correspoding PersistenceUnit
     * @param persistenceRootUri URI within application (excluding META-INF) for root of corresponding PersistenceUnit
     * @param containingBundle The bundle that contains PU for the given EMF
     * @param emf The emf that needs to be registered
     */
    void registerEMF(String unitName, String persistenceRootUri, RootDeploymentDescriptor containingBundle, EntityManagerFactory emf);

    /**
     * @return JTA DataSource override if any
     */
    String getJTADataSourceOverride();

    /**
     * @return default data source name to be used if user has not defined a data source
     */
    String getDefaultDataSourceName();

    /**
     * @return true if weaving is enabled for the current environment false otherwise
     */
    boolean isWeavingEnabled();
}


while (scheduledTasks.isEmpty()) {
                    System.out.println("Thread: " + Thread.currentThread().getId() + " waiting");
                    scheduledTasks.wait();
                }

package customThreadPoolExecutor;

import customThreadPoolExecutor.constants.ScheduledTaskType;
import customThreadPoolExecutor.model.ScheduledTask;
import kafka.handlers.SubscriberWorker;
import java.util.PriorityQueue;

/**
 * @author priyamvora
 * @created 29/05/2021
 */
public class ScheduledExecutorQueue {

    private final PriorityQueue<ScheduledTask> scheduledTasks;

    private final Thread[] workerThreads;

    public ScheduledExecutorQueue(int poolSize) {
        this.scheduledTasks = new PriorityQueue<>();
        workerThreads = new Thread[poolSize];
        intializeWorkerThreads();
    }

    private void intializeWorkerThreads() {
        for (int i = 0; i < workerThreads.length; i++) {
            workerThreads[i] = new Thread(() -> {
                try {
                    polling();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            workerThreads[i].start();
        }
    }

    public void addScheduledTask(ScheduledTask task) {
        synchronized (scheduledTasks) {
            System.out.println("Add task to queue: " + task);
            scheduledTasks.add(task);
            scheduledTasks.notifyAll();
        }
    }

    private void polling() throws InterruptedException {
        while (true) {
            ScheduledTask taskToExecute = null;
            System.out.println("Thread: " + Thread.currentThread().getId() + " trying to acquire lock");
            synchronized (scheduledTasks) {
                System.out.println("Thread: " + Thread.currentThread().getId() + " acquired lock");

                ScheduledTask task = scheduledTasks.peek();
                if (task.getScheduledExecutionTime() <= System.currentTimeMillis()) {
                    taskToExecute = scheduledTasks.poll();
                }
            }
            if (taskToExecute == null) {
                // System.out.println("Thread: " + Thread.currentThread().getId() + " going to sleep");
                Thread.sleep(2000);
                continue;
            }
            // For fixed rate add at initialDelay + period, initialDelay + 2*period
            if (taskToExecute != null && taskToExecute.getScheduledTaskType().equals(ScheduledTaskType.FIXED_RATE)) {
                ScheduledTask scheduledTask = cloneScheduledTask(taskToExecute);
                scheduledTask.setScheduledExecutionTime(System.currentTimeMillis() + scheduledTask.getSchedulePeriodInMillis());
                addScheduledTask(scheduledTask);
            }
            System.out.println("Thread: " + Thread.currentThread().getId() + " executing a task");
            taskToExecute.getTask().run();
            // For fixed delay add at currentEndTime + period;
            if (taskToExecute != null && taskToExecute.getScheduledTaskType().equals(ScheduledTaskType.FIXED_DELAY)) {
                ScheduledTask scheduledTask = cloneScheduledTask(taskToExecute);
                scheduledTask.setScheduledExecutionTime(System.currentTimeMillis() + scheduledTask.getSchedulePeriodInMillis());
                addScheduledTask(scheduledTask);
            }
        }
    }

    private ScheduledTask cloneScheduledTask(ScheduledTask scheduledTask) {
        ScheduledTask clone = new ScheduledTask(scheduledTask.getTask(), scheduledTask.getScheduledExecutionTime(), scheduledTask.getScheduledTaskType(), scheduledTask.getSchedulePeriodInMillis());
        return clone;
    }
}


public C getResult() {
        C copied = copier.apply(root);
        actions.forEach(action -> action.execute(copied));
        return copied;
    }

package com.diffplug.gradle;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import org.gradle.api.Action;

/**
 * Represents a mutable element, probably
 * a collection, which can be mutated directly,
 * or lazily using the {@link Action} mechanism.
 *
 * If the actions are applied to the root mutable element,
 * then it can be evaluated only once.  Lazyable allows
 * the actions to be evaluated many times, without modifying
 * the underlying root.
 */
public class Lazyable<C> {

    final Function<? super C, ? extends C> copier;

    final C root;

    final List<Action<? super C>> actions = new ArrayList<Action<? super C>>();

    /**
     * @param root		The original element.
     * @param copier	Copies the type, so the actions can be applied to it.
     */
    public Lazyable(C root, Function<? super C, ? extends C> copier) {
        this.root = Objects.requireNonNull(root);
        this.copier = Objects.requireNonNull(copier);
    }

    /**
     * Returns the root object.
     */
    public C getRoot() {
        return root;
    }

    /**
     * Adds an action which will act on a copy of the root collection.
     */
    public void addLazyAction(Action<? super C> action) {
        actions.add(action);
    }

    /**
     * Returns the final result.
     */

    /**
     * Returns a Lazyable wrapper around a list.
     */
    @SuppressWarnings("unchecked")
    public static <T> Lazyable<List<T>> ofList() {
        return (Lazyable<List<T>>) (Object) ofArrayList();
    }

    /**
     * Returns a Lazyable wrapper around an ArrayList.
     */
    public static <T> Lazyable<ArrayList<T>> ofArrayList() {
        return new Lazyable<>(new ArrayList<>(), toCopy -> new ArrayList<>(toCopy));
    }
}


protected abstract CompressedSizeInfo coCodeColumns(CompressedSizeInfo colInfos, int k);

package org.apache.sysds.runtime.compress.cocode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sysds.runtime.compress.CompressionSettings;
import org.apache.sysds.runtime.compress.cost.ICostEstimate;
import org.apache.sysds.runtime.compress.estim.CompressedSizeEstimator;
import org.apache.sysds.runtime.compress.estim.CompressedSizeInfo;
import org.apache.sysds.runtime.compress.estim.CompressedSizeInfoColGroup;

public abstract class AColumnCoCoder {

    protected static final Log LOG = LogFactory.getLog(AColumnCoCoder.class.getName());

    final protected CompressedSizeEstimator _sest;

    final protected ICostEstimate _cest;

    final protected CompressionSettings _cs;

    protected AColumnCoCoder(CompressedSizeEstimator sizeEstimator, ICostEstimate costEstimator, CompressionSettings cs) {
        _sest = sizeEstimator;
        _cest = costEstimator;
        _cs = cs;
    }

    /**
     * CoCode columns into groups.
     *
     * @param colInfos The current individually sampled and evaluated column groups.
     * @param k        The parallelization available to the underlying implementation.
     * @return CoCoded column groups.
     */

    protected CompressedSizeInfoColGroup join(int[] joined, CompressedSizeInfoColGroup lhs, CompressedSizeInfoColGroup rhs, boolean analyze) {
        return analyze ? _sest.estimateJoinCompressedSize(joined, lhs, rhs) : joinWithoutAnalysis(joined, lhs, rhs);
    }

    protected CompressedSizeInfoColGroup joinWithoutAnalysis(int[] joined, CompressedSizeInfoColGroup lhs, CompressedSizeInfoColGroup rhs) {
        final int lhsV = lhs.getNumVals();
        final int rhsV = rhs.getNumVals();
        final int joinedMaxDistinct = (int) Math.min((long) lhsV * (long) rhsV, (long) _sest.getNumRows());
        return new CompressedSizeInfoColGroup(joined, joinedMaxDistinct, _sest.getNumRows());
    }

    protected CompressedSizeInfoColGroup analyze(CompressedSizeInfoColGroup g) {
        if (g.getBestCompressionType() == null)
            return _sest.estimateCompressedColGroupSize(g.getColumns());
        else
            return g;
    }
}


public Builder invocationCallback(com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder> invocationCallback) {
            this.invocationCallback = invocationCallback;
            return this;
        }

package com.oracle.bmc.datacatalog.requests;

import com.oracle.bmc.datacatalog.model.*;

/**
 * Example: Click here to see how to use GetPatternRequest.
 */
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20190325")
@lombok.Builder(builderClassName = "Builder", buildMethodName = "buildWithoutInvocationCallback", toBuilder = true)
@lombok.ToString(callSuper = true)
@lombok.EqualsAndHashCode(callSuper = true)
@lombok.Getter
public class GetPatternRequest extends com.oracle.bmc.requests.BmcRequest<java.lang.Void> {

    /**
     * Unique catalog identifier.
     */
    private String catalogId;

    /**
     * Unique pattern key.
     */
    private String patternKey;

    /**
     * Specifies the fields to return in a pattern response.
     */
    private java.util.List<Fields> fields;

    /**
     * Specifies the fields to return in a pattern response.
     */
    public enum Fields {

        Key("key"),
        DisplayName("displayName"),
        Description("description"),
        CatalogId("catalogId"),
        Expression("expression"),
        LifecycleState("lifecycleState"),
        TimeCreated("timeCreated"),
        TimeUpdated("timeUpdated"),
        CreatedById("createdById"),
        UpdatedById("updatedById"),
        Properties("properties");

        private final String value;

        private static java.util.Map<String, Fields> map;

        static {
            map = new java.util.HashMap<>();
            for (Fields v : Fields.values()) {
                map.put(v.getValue(), v);
            }
        }

        Fields(String value) {
            this.value = value;
        }

        @com.fasterxml.jackson.annotation.JsonValue
        public String getValue() {
            return value;
        }

        @com.fasterxml.jackson.annotation.JsonCreator
        public static Fields create(String key) {
            if (map.containsKey(key)) {
                return map.get(key);
            }
            throw new IllegalArgumentException("Invalid Fields: " + key);
        }
    }

    /**
     * The client request ID for tracing.
     */
    private String opcRequestId;

    public static class Builder implements com.oracle.bmc.requests.BmcRequest.Builder<GetPatternRequest, java.lang.Void> {

        private com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder> invocationCallback = null;

        private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;

        private java.util.List<Fields> fields = null;

        /**
         * Specifies the fields to return in a pattern response.
         *
         * @return this builder instance
         */
        public Builder fields(java.util.List<Fields> fields) {
            this.fields = fields;
            return this;
        }

        /**
         * Singular setter. Specifies the fields to return in a pattern response.
         *
         * @return this builder instance
         */
        public Builder fields(Fields singularValue) {
            return this.fields(java.util.Arrays.asList(singularValue));
        }

        /**
         * Set the invocation callback for the request to be built.
         * @param invocationCallback the invocation callback to be set for the request
         * @return this builder instance
         */

        /**
         * Set the retry configuration for the request to be built.
         * @param retryConfiguration the retry configuration to be used for the request
         * @return this builder instance
         */
        public Builder retryConfiguration(com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {
            this.retryConfiguration = retryConfiguration;
            return this;
        }

        /**
         * Copy method to populate the builder with values from the given instance.
         * @return this builder instance
         */
        public Builder copy(GetPatternRequest o) {
            catalogId(o.getCatalogId());
            patternKey(o.getPatternKey());
            fields(o.getFields());
            opcRequestId(o.getOpcRequestId());
            invocationCallback(o.getInvocationCallback());
            retryConfiguration(o.getRetryConfiguration());
            return this;
        }

        /**
         * Build the instance of GetPatternRequest as configured by this builder
         *
         * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,
         * while the method {@link Builder#buildWithoutInvocationCallback} does not.
         *
         * This is the preferred method to build an instance.
         *
         * @return instance of GetPatternRequest
         */
        public GetPatternRequest build() {
            GetPatternRequest request = buildWithoutInvocationCallback();
            request.setInvocationCallback(invocationCallback);
            request.setRetryConfiguration(retryConfiguration);
            return request;
        }
    }
}


public void setFixData(FixData fixData) {
        errorSidebar.setFixData(fixData);
    }

/**
 * ****************************************************************************
 *  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 * *****************************************************************************
 */
package jsettlers.mapcreator.main.window.sidebar;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import jsettlers.mapcreator.localization.EditorLabels;
import jsettlers.mapcreator.mapvalidator.IScrollToAble;
import jsettlers.mapcreator.mapvalidator.ValidationResultListener;
import jsettlers.mapcreator.mapvalidator.result.ValidationListModel;
import jsettlers.mapcreator.mapvalidator.result.fix.FixData;

/**
 * The sidebar with all tabs
 *
 * @author Andreas Butti
 */
public class Sidebar extends JTabbedPane implements ValidationResultListener {

    private static final long serialVersionUID = 1L;

    /**
     * Sidebar with the tools
     */
    private final ToolSidebar toolSidebar;

    /**
     * Sidebar with the erros
     */
    private final ErrorSidebar errorSidebar;

    /**
     * Drop down icon
     */
    private final Icon errorIcon = new ImageIcon(ErrorListRenderer.class.getResource("error.png"));

    /**
     * Drop down icon
     */
    private final Icon warningIcon = new ImageIcon(ErrorListRenderer.class.getResource("warning.png"));

    /**
     * Errot ab header
     */
    private final JLabel lbErrorHeader = new JLabel(EditorLabels.getLabel("sidebar.errors"));

    /**
     * Constructor
     *
     * @param toolSidebar
     *            Sidebar with the tools
     * @param scrollTo
     *            Interface to scroll to position
     */
    public Sidebar(ToolSidebar toolSidebar, IScrollToAble scrollTo) {
        this.toolSidebar = toolSidebar;
        this.errorSidebar = new ErrorSidebar(scrollTo);
        addTab(EditorLabels.getLabel("sidebar.tools"), toolSidebar);
        addTab("<errors>", errorSidebar);
        lbErrorHeader.setIconTextGap(5);
        lbErrorHeader.setHorizontalTextPosition(SwingConstants.RIGHT);
        setTabComponentAt(1, lbErrorHeader);
    }

    /**
     * @param fixData
     *            Fix data helper
     */

    /**
     * Select the error tab
     */
    public void selectError() {
        setSelectedComponent(errorSidebar);
    }

    /**
     * Select the tools tab
     */
    public void showTools() {
        setSelectedComponent(toolSidebar);
    }

    @Override
    public void validationFinished(ValidationListModel list) {
        if (list.getErrorCount() > 0) {
            lbErrorHeader.setIcon(errorIcon);
        } else if (list.getWarningCount() > 0) {
            lbErrorHeader.setIcon(warningIcon);
        } else {
            lbErrorHeader.setIcon(null);
        }
        errorSidebar.validationFinished(list);
    }
}