Context:
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.
 */
package org.elasticsearch.gateway.local.state.meta;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.OutputStreamIndexOutput;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.XIOUtils;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.Preconditions;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.lucene.store.InputStreamIndexInput;
import org.elasticsearch.common.xcontent.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MetaDataStateFormat is a base class to write checksummed
 * XContent based files to one or more directories in a standardized directory structure.
 * @param <T> the type of the XContent base data-structure
 */
public abstract class MetaDataStateFormat<T> {
    public static final String STATE_DIR_NAME = "_state";
    public static final String STATE_FILE_EXTENSION = ".st";
    private static final String STATE_FILE_CODEC = "state";
    private static final int STATE_FILE_VERSION = 0;
    private static final int BUFFER_SIZE = 4096;
    private final XContentType format;
    private final boolean deleteOldFiles;

    /**
     * Creates a new {@link MetaDataStateFormat} instance
     * @param format the format of the x-content
     * @param deleteOldFiles if true write operations will
     *                       clean up old files written with this format.
     */
    protected MetaDataStateFormat(XContentType format, boolean deleteOldFiles) {
        this.format = format;
        this.deleteOldFiles = deleteOldFiles;
    }

    /**
     * Returns the {@link XContentType} used to serialize xcontent on write.
     */
    public XContentType format() {
        return format;
    }

    /**
     * Writes the given state to the given directories. The state is written to a
     * state directory ({@value #STATE_DIR_NAME}) underneath each of the given file locations and is created if it
     * doesn't exist. The state is serialized to a temporary file in that directory and is then atomically moved to
     * it's target filename of the pattern <tt>{prefix}{version}.st</tt>.
     *
     * @param state the state object to write
     * @param prefix the state names prefix used to compose the file name.
     * @param version the version of the state
     * @param locations the locations where the state should be written to.
     * @throws IOException if an IOException occurs
     */
    public final void write(final T state, final String prefix, final long version, final File... locations) throws IOException {
        Preconditions.checkArgument(locations != null, "Locations must not be null");
        Preconditions.checkArgument(locations.length > 0, "One or more locations required");
        String fileName = prefix + version + STATE_FILE_EXTENSION;
        Path stateLocation = Paths.get(locations[0].getPath(), STATE_DIR_NAME);
        Files.createDirectories(stateLocation);
        final Path tmpStatePath = stateLocation.resolve(fileName + ".tmp");
        final Path finalStatePath = stateLocation.resolve(fileName);
        try {
            try (OutputStreamIndexOutput out = new OutputStreamIndexOutput(Files.newOutputStream(tmpStatePath), BUFFER_SIZE)) {
                CodecUtil.writeHeader(out, STATE_FILE_CODEC, STATE_FILE_VERSION);
                out.writeInt(format.index());
                out.writeLong(version);
                try (XContentBuilder builder = newXContentBuilder(format, new org.elasticsearch.common.lucene.store.OutputStreamIndexOutput(out) {
                    @Override
                    public void close() throws IOException {
                        // this is important since some of the XContentBuilders write bytes on close.
                        // in order to write the footer we need to prevent closing the actual index input.
                    } })) {

                    builder.startObject();
                    {
                        toXContent(builder, state);
                    }
                    builder.endObject();
                }
                CodecUtil.writeFooter(out);
            }
            IOUtils.fsync(tmpStatePath.toFile(), false); // fsync the state file
            Files.move(tmpStatePath, finalStatePath, StandardCopyOption.ATOMIC_MOVE);
            IOUtils.fsync(stateLocation.toFile(), true);
            for (int i = 1; i < locations.length; i++) {
                stateLocation = Paths.get(locations[i].getPath(), STATE_DIR_NAME);
                Files.createDirectories(stateLocation);
                Path tmpPath = stateLocation.resolve(fileName + ".tmp");
                Path finalPath = stateLocation.resolve(fileName);
                try {
                    Files.copy(finalStatePath, tmpPath);
                    Files.move(tmpPath, finalPath, StandardCopyOption.ATOMIC_MOVE); // we are on the same FileSystem / Partition here we can do an atomic move
                    IOUtils.fsync(stateLocation.toFile(), true); // we just fsync the dir here..
                } finally {
                    Files.deleteIfExists(tmpPath);
                }
            }
        } finally {
            Files.deleteIfExists(tmpStatePath);
        }
        if (deleteOldFiles) {
            cleanupOldFiles(prefix, fileName, locations);
        }
    }

    protected XContentBuilder newXContentBuilder(XContentType type, OutputStream stream ) throws IOException {
        return XContentFactory.contentBuilder(type, stream);
    }

    /**
     * Writes the given state to the given XContentBuilder
     * Subclasses need to implement this class for theirs specific state.
     */

Answer: public abstract void toXContent(XContentBuilder builder, T state) throws IOException;

<think>
The comment describes an abstract method that subclasses must implement to write the state into an XContentBuilder. The write() method later calls toXContent(builder, state), so the next line should declare this abstract method with appropriate visibility, parameters, and throws clause.
</think>
protected abstract void toXContent(XContentBuilder builder, T state) throws IOException;


Context:
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed 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.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Gallio.Common;
using Gallio.Common.Collections;
using Gallio.Common.Policies;
using Gallio.Common.Concurrency;
using Gallio.Model;
using Gallio.Common.Diagnostics;
using Gallio.Common.Markup;

namespace Gallio.Framework
{
    /// <summary>
    /// A sandbox is an isolated environments for executing test actions.
    /// </summary>
    /// <remarks>
    /// <para>
    /// It provides the ability to abort actions in progress so that the test runner can proceed
    /// to run other actions.
    /// </para>
    /// <para>
    /// Sandboxes are hierarchically structured. When an outer sandbox is aborted, all
    /// of its inner sandboxes are likewise aborted. A sandbox also provides the ability
    /// to create new child sandboxes at will so that test actions can be isolated with
    /// fine granularity.
    /// </para>
    /// <para>
    /// This class is safe for use from multiple concurrent threads.
    /// </para>
    /// </remarks>
    [SystemInternal]
    public sealed class Sandbox : IDisposable
    {
        private Sandbox parent;

        private readonly object syncRoot = new object();
        private List<Pair<ThreadAbortScope, Thread>> scopesAndThreads;
        private TestOutcome? abortOutcome;
        private string abortMessage;
        private event EventHandler aborted;
        private bool alreadyLoggedAbortOnce;
        private bool isDisposed;

        /// <summary>
        /// Creates a root sandbox.
        /// </summary>
        public Sandbox()
        {
        }

        /// <summary>
        /// An event that is dispatched when <see cref="Abort(TestOutcome, string)" /> is called.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If the sandbox has already been aborted then the event handler is immediately invoked.
        /// </para>
        /// </remarks>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public event EventHandler Aborted
        {
            add
            {
                lock (syncRoot)
                {
                    ThrowIfDisposed();

                    if (!abortOutcome.HasValue)
                    {
                        aborted += value;
                        return;
                    }
                }

                EventHandlerPolicy.SafeInvoke(value, this, EventArgs.Empty);
            }
            remove
            {
                lock (syncRoot)
                {
                    ThrowIfDisposed();

                    aborted -= value;
                }
            }
        }

        /// <summary>
        /// Returns <c>true</c> if <see cref="Abort(TestOutcome, string)" /> was called.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public bool WasAborted
        {
            get
            {
                lock (syncRoot)
                {
                    ThrowIfDisposed();
                    return abortOutcome.HasValue;
                }
            }
        }

        /// <summary>
        /// Returns the <see cref="TestOutcome" /> passed to <see cref="Abort(TestOutcome, string)" />,
        /// or null if <see cref="Abort(TestOutcome, string)" /> has not been called.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public TestOutcome? AbortOutcome
        {
            get
            {
                lock (syncRoot)
                {
                    ThrowIfDisposed();
                    return abortOutcome;
                }
            }
        }

        /// <summary>
        /// Gets a message that will be logged when the sandbox is aborted, or null if none.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public string AbortMessage
        {
            get
            {
                lock (syncRoot)
                {
                    ThrowIfDisposed();
                    return abortMessage;
                }
            }
        }

        /// <summary>
        /// Disposes the sandbox.
        /// </summary>
        /// <remarks>
        /// <para>
        /// All currently executing actions are aborted with <see cref="TestOutcome.Error" />
        /// if <see cref="Abort(TestOutcome, string)" /> has not already been called.
        /// </para>
        /// </remarks>
        public void Dispose()
        {
            Abort(TestOutcome.Error, "The sandbox was disposed.", false);

            Sandbox cachedParent;
            lock (syncRoot)
            {
                if (isDisposed)
                    return;

                cachedParent = parent;
                parent = null;
                isDisposed = true;
            }

            if (cachedParent != null)
                cachedParent.Aborted -= HandleParentAborted;
        }

        /// <summary>
        /// Creates a child sandbox.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When the parent sandbox is aborted, the child will likewise be aborted.  This policy
        /// offers a mechanism to scope actions recursively.
        /// </para>
        /// </remarks>
        /// <returns>The child sandbox.</returns>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public Sandbox CreateChild()
        {
            ThrowIfDisposed();

            Sandbox child = new Sandbox();
            child.parent = this;
            Aborted += child.HandleParentAborted;
            return child;
        }

        /// <summary>
        /// Aborts all actions in progress within this context.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The abort is persistent and cannot be reverted.  Therefore once aborted, no further
        /// test actions will be permitted to run.  Subsequent calls to <see cref="Abort(TestOutcome, string)" />
        /// will have no effect.
        /// </para>
        /// </remarks>
        /// <param name="outcome">The outcome to be returned from aborted actions.</param>
        /// <param name="message">A message to be logged when the action is aborted, or null if none.</param>
        /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception>
        public void Abort(TestOutcome outcome, string message)
        {
            Abort(outcome, message, true);
        }

        private void Abort(TestOutcome outcome, string message, bool throwIfDisposed)
        {
            EventHandler cachedHandler;
            ThreadAbortScope[] cachedScopes;
            lock (syncRoot)
            {
                if (throwIfDisposed)
                    ThrowIfDisposed();

                if (abortOutcome.HasValue)
                    return;

                abortOutcome = outcome;
                abortMessage = message;

                cachedScopes = scopesAndThreads != null
                    ? GenericCollectionUtils.ConvertAllToArray(scopesAndThreads, pair => pair.First)
                    : null;
                scopesAndThreads = null;

                cachedHandler = aborted;
                aborted = null;
            }

            if (cachedScopes != null)
            {
                foreach (ThreadAbortScope scope in cachedScopes)
                    scope.Abort();
            }

            EventHandlerPolicy.SafeInvoke(cachedHandler, this, EventArgs.Empty);
        }

        /// <summary>
        /// Uses a specified timeout for all actions run within a block of code.
        /// When the timeout expires, the sandbox will be aborted.
        /// </summary>
        /// <example>
        /// <![CDATA[

Answer: /// using (sandbox.UseTimeout(TimeSpan.FromSeconds(5))

<think>
The comment is opening an example block with a CDATA section. In the Gallio Sandbox class, the next line typically shows how to use the WithTimeout method, which is demonstrated with a using statement. Therefore the next line of code is the start of that example: a using statement that calls sandbox.WithTimeout with a TimeSpan.
</think>
using (sandbox.WithTimeout(TimeSpan.FromSeconds(10)))


Context:
/*
 * 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.
 */
package org.apache.accumulo.tracer;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.accumulo.fate.util.UtilWaitThread.sleepUninterruptibly;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken.Properties;
import org.apache.accumulo.core.client.security.tokens.KerberosToken;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.user.AgeOffFilter;
import org.apache.accumulo.fate.zookeeper.ZooReaderWriter;
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.server.ServerContext;
import org.apache.accumulo.server.ServerOpts;
import org.apache.accumulo.server.ServerUtil;
import org.apache.accumulo.server.conf.ServerConfigurationFactory;
import org.apache.accumulo.server.security.SecurityUtil;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader;
import org.apache.accumulo.tracer.thrift.RemoteSpan;
import org.apache.accumulo.tracer.thrift.SpanReceiver.Iface;
import org.apache.accumulo.tracer.thrift.SpanReceiver.Processor;
import org.apache.hadoop.io.Text;
import org.apache.thrift.TByteArrayOutputStream;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TraceServer implements Watcher, AutoCloseable {

  private static final Logger log = LoggerFactory.getLogger(TraceServer.class);
  private final ServerConfigurationFactory serverConfiguration;
  private final ServerContext context;
  private final TServer server;
  private final AtomicReference<BatchWriter> writer;
  private final AccumuloClient accumuloClient;
  final String tableName;
  private static final int BATCH_WRITER_MAX_LATENCY = 5;
  private static final long SCHEDULE_PERIOD = 1000;
  private static final long SCHEDULE_DELAY = 1000;

  private static void put(Mutation m, String cf, String cq, byte[] bytes, int len) {
    m.put(new Text(cf), new Text(cq), new Value(bytes, 0, len));
  }

  @Override
  public void close() {
    if (accumuloClient != null) {
      accumuloClient.close();
    }
  }

  static class ByteArrayTransport extends TTransport {
    TByteArrayOutputStream out = new TByteArrayOutputStream();

    @Override
    public boolean isOpen() {
      return true;
    }

    @Override
    public void open() {}

    @Override
    public void close() {}

    @Override
    public int read(byte[] buf, int off, int len) {
      return 0;
    }

    @Override
    public void write(byte[] buf, int off, int len) {
      out.write(buf, off, len);
    }

    public byte[] get() {
      return out.get();
    }

    public int len() {
      return out.len();
    }
  }

  class Receiver implements Iface {
    @Override
    public void span(RemoteSpan s) throws TException {
      String idString = Long.toHexString(s.traceId);
      String startString = Long.toHexString(s.start);
      Mutation spanMutation = new Mutation(new Text(idString));
      Mutation indexMutation = new Mutation(new Text("idx:" + s.svc + ":" + startString));
      long diff = s.stop - s.start;
      indexMutation.put(new Text(s.description), new Text(s.sender),
          new Value(idString + ":" + Long.toHexString(diff)));
      ByteArrayTransport transport = new ByteArrayTransport();
      TCompactProtocol protocol = new TCompactProtocol(transport);
      s.write(protocol);
      String parentString = s.getParentIdsSize() == 0 ? "" : s.getParentIds().stream()
          .map(x -> Long.toHexString(x)).collect(Collectors.toList()).toString();
      put(spanMutation, "span", parentString + ":" + Long.toHexString(s.spanId), transport.get(),
          transport.len());
      // Map the root span to time so we can look up traces by time
      Mutation timeMutation = null;
      if (s.getParentIdsSize() == 0) {
        timeMutation = new Mutation(new Text("start:" + startString));
        put(timeMutation, "id", idString, transport.get(), transport.len());
      }
      try {
        final BatchWriter writer = TraceServer.this.writer.get();
        /*
         * Check for null, because we expect spans to come in much faster than flush calls. In the
         * case of failure, we'd rather avoid logging tons of NPEs.
         */
        if (writer == null) {
          log.warn("writer is not ready; discarding span.");
          return;
        }
        writer.addMutation(spanMutation);
        writer.addMutation(indexMutation);
        if (timeMutation != null) {
          writer.addMutation(timeMutation);
        }
      } catch (MutationsRejectedException exception) {
        log.warn("Unable to write mutation to table; discarding span. set log"
            + " level to DEBUG for span information and stacktrace. cause: " + exception);
        if (log.isDebugEnabled()) {
          log.debug("discarded span due to rejection of mutation: " + spanMutation, exception);
        }
        /*
         * XXX this could be e.g. an IllegalArgumentException if we're trying to write this mutation
         * to a writer that has been closed since we retrieved it
         */
      } catch (RuntimeException exception) {
        log.warn("Unable to write mutation to table; discarding span. set log"
            + " level to DEBUG for stacktrace. cause: " + exception);
        log.debug("unable to write mutation to table due to exception.", exception);
      }
    }

  }

  public TraceServer(ServerContext context, String hostname) throws Exception {
    this.context = context;
    this.serverConfiguration = context.getServerConfFactory();
    log.info("Version {}", Constants.VERSION);
    log.info("Instance {}", context.getInstanceID());
    AccumuloConfiguration conf = serverConfiguration.getSystemConfiguration();
    tableName = conf.get(Property.TRACE_TABLE);
    accumuloClient = ensureTraceTableExists(conf);

    int[] ports = conf.getPort(Property.TRACE_PORT);
    ServerSocket sock = null;

Answer: for (int port : ports) {

<think>
In the constructor, after declaring the ServerSocket variable, the code needs to attempt binding to one of the configured ports. The typical pattern is to iterate over the ports array, trying each until successful. Therefore the next line starts a for‑each loop over the ports array.
</think>
for (int port : ports) {


Context:
/*
 *  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.
 */

/**
* @author Boris V. Kuznetsov
* @version $Revision$
*/

package org.apache.harmony.security.tests.java.security;

import dalvik.annotation.KnownFailure;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;

import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.Signature;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.spec.AlgorithmParameterSpec;

import org.apache.harmony.security.tests.support.MySignature1;

import junit.framework.TestCase;
@TestTargetClass(Signature.class)
/**
 * Tests for Signature constructor and methods
 *
 */
public class SignatureTest extends TestCase {

    /*
     * Class under test for Signature(String)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "Signature",
        args = {java.lang.String.class}
    )
    public void testConstructor() {
        String [] algorithms = { "SHA256WITHRSA", "NONEWITHDSA", "SHA384WITHRSA",
            "MD5ANDSHA1WITHRSA", "SHA512WITHRSA",
            "SHA1WITHRSA", "SHA1WITHDSA", "MD5WITHRSA" };
        for (int i = 0; i < algorithms.length; i ++) {
            MySignature1 s = new MySignature1(algorithms[i]);
            assertEquals(algorithms[i],s.getAlgorithm());
            assertNull(s.getProvider());
            assertEquals(0, s.getState());
        }

        MySignature1 s1 = new MySignature1(null);
        assertNull(s1.getAlgorithm());
        assertNull(s1.getProvider());
        assertEquals(0, s1.getState());

        MySignature1 s2 = new MySignature1("ABCD@#&^%$)(*&");
        assertEquals("ABCD@#&^%$)(*&", s2.getAlgorithm());
        assertNull(s2.getProvider());
        assertEquals(0, s2.getState());
    }

    /*
     * Class under test for Object clone()
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Just exception case was tested",
        method = "clone",
        args = {}
    )
    public void testClone() {
        MySignature1 s = new MySignature1("ABC");
        try {
            s.clone();
            fail("No expected CloneNotSupportedException");
        } catch (CloneNotSupportedException e) {
        }

        MySignature sc = new MySignature();
        try {
            sc.clone();
        } catch (CloneNotSupportedException e) {
            fail("unexpected exception: " + e);
        }

    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getProvider",
        args = {}
    )
    public void testGetProvider() {
        MySignature1 s = new MySignature1("ABC");

        assertEquals("state", MySignature1.UNINITIALIZED, s.getState());
        assertNull("provider", s.getProvider());
    }

    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "getAlgorithm",
        args = {}
    )
    public void testGetAlgorithm() {
        MySignature1 s = new MySignature1("ABC");

        assertEquals("state", MySignature1.UNINITIALIZED, s.getState());
        assertEquals("algorithm", "ABC", s.getAlgorithm());
    }

    /*
     * Class under test for void initVerify(PublicKey)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "InvalidKeyException checking missed",
        method = "initVerify",
        args = {java.security.PublicKey.class}
    )
    public void testInitVerifyPublicKey() throws InvalidKeyException {
        MySignature1 s = new MySignature1("ABC");

        s.initVerify(new MyPublicKey());
        assertEquals("state", MySignature1.VERIFY, s.getState());
        assertTrue("initVerify() failed", s.runEngineInitVerify);

        try {
            Signature sig = getTestSignature();
            sig.initVerify((PublicKey)null);
        } catch (InvalidKeyException e) {
            // ok
        } catch (NoSuchAlgorithmException e) {
            fail("unexpected : " + e);
        }
    }

    /*
     * Class under test for void initVerify(Certificate)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "initVerify",
        args = {java.security.cert.Certificate.class}
    )
    public void testInitVerifyCertificate() throws InvalidKeyException {
        MySignature1 s = new MySignature1("ABC");

        s.initVerify(new MyCertificate());
        assertEquals("state", MySignature1.VERIFY, s.getState());
        assertTrue("initVerify() failed", s.runEngineInitVerify);

        try {
            Signature sig = getTestSignature();
            sig.initVerify(new MyCertificate());
            fail("expected InvalidKeyException");
        } catch (InvalidKeyException e) {
            // ok
        } catch (NoSuchAlgorithmException e) {
            fail("unexpected : " + e);
        }
    }

    /*
     * Class under test for void initSign(PrivateKey)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "initSign",
        args = {java.security.PrivateKey.class}
    )
    public void testInitSignPrivateKey() throws InvalidKeyException {
        MySignature1 s = new MySignature1("ABC");

        s.initSign(new MyPrivateKey());
        assertEquals("state", MySignature1.SIGN, s.getState());
        assertTrue("initSign() failed", s.runEngineInitSign);

        try {
            Signature signature = getTestSignature();
            signature.initSign(null);
            fail("expected InvalidKeyException");
        } catch (InvalidKeyException e) {
            // ok
        } catch (NoSuchAlgorithmException e) {
            fail("unexpected: " + e);
        }
    }

    private Signature getTestSignature() throws NoSuchAlgorithmException {
        Provider provider = new MyProvider("TestProvider", 1.0, "Test Provider", "Signature.ABC", MySignature.class.getName());
        Security.insertProviderAt(provider, 1);

        try {
            return Signature.getInstance("ABC");
        }
        finally {
           Security.removeProvider("TestProvider");
        }

    }

    /*
     * Class under test for void initSign(PrivateKey, SecureRandom)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "InvalidKeyException checking missed",
        method = "initSign",
        args = {java.security.PrivateKey.class, java.security.SecureRandom.class}
    )
    public void testInitSignPrivateKeySecureRandom() throws InvalidKeyException {
        MySignature1 s = new MySignature1("ABC");

        s.initSign(new MyPrivateKey(), new SecureRandom());

Answer: assertEquals("state", MySignature1.SIGN, s.getState());

<think>
The method testInitSignPrivateKeySecureRandom mirrors testInitSignPrivateKey. After calling s.initSign(new MyPrivateKey(), new SecureRandom()), the test should verify that the signature object's state is SIGN. The first verification step is an assertEquals checking the state, matching the pattern used earlier.
</think>
assertEquals("state", MySignature1.SIGN, s.getState());


Context:
/*
 * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed 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.
 */
package org.wso2.carbon.event.receiver.admin;

import org.apache.axis2.AxisFault;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.AbstractAdmin;
import org.wso2.carbon.databridge.commons.Attribute;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterSchema;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
import org.wso2.carbon.event.input.adapter.core.Property;
import org.wso2.carbon.event.receiver.admin.internal.EventReceiverAdminConstants;
import org.wso2.carbon.event.receiver.admin.internal.ds.EventReceiverAdminServiceValueHolder;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.core.config.*;
import org.wso2.carbon.event.receiver.core.config.mapping.*;
import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException;

import java.util.*;

public class EventReceiverAdminService extends AbstractAdmin {

    private static Log log = LogFactory.getLog(EventReceiverAdminService.class);

    public EventReceiverConfigurationInfoDto[] getAllActiveEventReceiverConfigurations()
            throws AxisFault {

        EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();

        // get event receiver configurations
        List<EventReceiverConfiguration> eventReceiverConfigurationList;
        eventReceiverConfigurationList = eventReceiverService.getAllActiveEventReceiverConfigurations();

        if (eventReceiverConfigurationList != null) {
            // create event receiver configuration details array
            EventReceiverConfigurationInfoDto[] eventReceiverConfigurationInfoDtoArray = new
                    EventReceiverConfigurationInfoDto[eventReceiverConfigurationList.size()];
            for (int index = 0; index < eventReceiverConfigurationInfoDtoArray.length; index++) {
                EventReceiverConfiguration eventReceiverConfiguration = eventReceiverConfigurationList.get(index);
                String eventReceiverName = eventReceiverConfiguration.getEventReceiverName();
                String mappingType = eventReceiverConfiguration.getInputMapping().getMappingType();
                String inputEventAdapterType = eventReceiverConfiguration.getFromAdapterConfiguration().getType();
                String streamNameWithVersion = eventReceiverConfiguration.getToStreamName() + ":" + eventReceiverConfiguration.getToStreamVersion();

                eventReceiverConfigurationInfoDtoArray[index] = new EventReceiverConfigurationInfoDto();
                eventReceiverConfigurationInfoDtoArray[index].setEventReceiverName(eventReceiverName);
                eventReceiverConfigurationInfoDtoArray[index].setMessageFormat(mappingType);
                eventReceiverConfigurationInfoDtoArray[index].setInputAdapterType(inputEventAdapterType);
                eventReceiverConfigurationInfoDtoArray[index].setInputStreamId(streamNameWithVersion);
                eventReceiverConfigurationInfoDtoArray[index].setEnableStats(eventReceiverConfiguration.isStatisticsEnabled());
                eventReceiverConfigurationInfoDtoArray[index].setEnableTracing(eventReceiverConfiguration.isTraceEnabled());
                eventReceiverConfigurationInfoDtoArray[index].setEditable(eventReceiverConfiguration.isEditable());
            }
            Arrays.sort(eventReceiverConfigurationInfoDtoArray, new Comparator() {

                @Override
                public int compare(Object o1, Object o2) {
                    return ((EventReceiverConfigurationInfoDto) o1).getEventReceiverName().compareTo(((EventReceiverConfigurationInfoDto) o2).getEventReceiverName());
                }
            });
            return eventReceiverConfigurationInfoDtoArray;
        } else {
            return new EventReceiverConfigurationInfoDto[0];
        }
    }

    public EventReceiverConfigurationInfoDto[] getAllStreamSpecificActiveEventReceiverConfigurations(
            String streamId)
            throws AxisFault {

        EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();

        // get event receiver configurations
        List<EventReceiverConfiguration> eventReceiverConfigurationList;
        eventReceiverConfigurationList = eventReceiverService.getAllActiveEventReceiverConfigurations(streamId);

        if (eventReceiverConfigurationList != null) {
            // create event receiver configuration details array
            EventReceiverConfigurationInfoDto[] eventReceiverConfigurationInfoDtoArray = new
                    EventReceiverConfigurationInfoDto[eventReceiverConfigurationList.size()];
            for (int index = 0; index < eventReceiverConfigurationInfoDtoArray.length; index++) {
                EventReceiverConfiguration eventReceiverConfiguration = eventReceiverConfigurationList.get(index);
                String eventReceiverName = eventReceiverConfiguration.getEventReceiverName();
                String mappingType = eventReceiverConfiguration.getInputMapping().getMappingType();
                String inputEventAdapterType = eventReceiverConfiguration.getFromAdapterConfiguration().getType();

                eventReceiverConfigurationInfoDtoArray[index] = new EventReceiverConfigurationInfoDto();
                eventReceiverConfigurationInfoDtoArray[index].setEventReceiverName(eventReceiverName);
                eventReceiverConfigurationInfoDtoArray[index].setMessageFormat(mappingType);
                eventReceiverConfigurationInfoDtoArray[index].setInputAdapterType(inputEventAdapterType);
                eventReceiverConfigurationInfoDtoArray[index].setEnableStats(eventReceiverConfiguration.isStatisticsEnabled());
                eventReceiverConfigurationInfoDtoArray[index].setEnableTracing(eventReceiverConfiguration.isTraceEnabled());
                eventReceiverConfigurationInfoDtoArray[index].setEditable(eventReceiverConfiguration.isEditable());
            }
            Arrays.sort(eventReceiverConfigurationInfoDtoArray,new Comparator() {

                @Override
                public int compare(Object o1, Object o2) {
                    return ((EventReceiverConfigurationInfoDto) o1).getEventReceiverName().compareTo(((EventReceiverConfigurationInfoDto) o2).getEventReceiverName());
                }
            });
            return eventReceiverConfigurationInfoDtoArray;
        } else {
            return new EventReceiverConfigurationInfoDto[0];
        }
    }

    public EventReceiverConfigurationFileDto[] getAllInactiveEventReceiverConfigurations()
            throws AxisFault {

        EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();
        List<EventReceiverConfigurationFile> eventReceiverConfigurationFileList = eventReceiverService.getAllInactiveEventReceiverConfigurations();
        if (eventReceiverConfigurationFileList != null) {

            // create event receiver file details array
            EventReceiverConfigurationFileDto[] eventReceiverFileDtoArray = new
                    EventReceiverConfigurationFileDto[eventReceiverConfigurationFileList.size()];

            for (int index = 0; index < eventReceiverFileDtoArray.length; index++) {
                EventReceiverConfigurationFile eventReceiverConfigurationFile = eventReceiverConfigurationFileList.get(index);
                String fileName = eventReceiverConfigurationFile.getFileName();
                String eventReceiverName = eventReceiverConfigurationFile.getEventReceiverName();
                String statusMsg = eventReceiverConfigurationFile.getDeploymentStatusMessage();
                if (eventReceiverConfigurationFile.getDependency() != null) {
                    statusMsg = statusMsg + " [Dependency: " + eventReceiverConfigurationFile.getDependency() + "]";
                }

                eventReceiverFileDtoArray[index] = new EventReceiverConfigurationFileDto(fileName, eventReceiverName, statusMsg);
            }
            Arrays.sort(eventReceiverFileDtoArray,new Comparator() {

                @Override
                public int compare(Object o1, Object o2) {
                    return ((EventReceiverConfigurationFileDto) o1).getFileName().compareTo(((EventReceiverConfigurationFileDto) o2).getFileName());
                }
            });
            return eventReceiverFileDtoArray;
        } else {
            return new EventReceiverConfigurationFileDto[0];
        }
    }

    public EventReceiverConfigurationDto getActiveEventReceiverConfiguration(
            String eventReceiverName) throws AxisFault {

        EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();

        EventReceiverConfiguration eventReceiverConfiguration = eventReceiverService.getActiveEventReceiverConfiguration(eventReceiverName);
        if (eventReceiverConfiguration != null) {
            EventReceiverConfigurationDto eventReceiverConfigurationDto = new EventReceiverConfigurationDto();
            eventReceiverConfigurationDto.setEventReceiverName(eventReceiverConfiguration.getEventReceiverName());
            String streamNameWithVersion = eventReceiverConfiguration.getToStreamName() + ":" + eventReceiverConfiguration.getToStreamVersion();
            eventReceiverConfigurationDto.setToStreamNameWithVersion(streamNameWithVersion);

            InputEventAdapterConfiguration fromAdapterConfiguration = eventReceiverConfiguration.getFromAdapterConfiguration();

            if (fromAdapterConfiguration != null) {
                InputEventAdapterService inputEventAdapterService = EventReceiverAdminServiceValueHolder.getInputEventAdapterService();
                InputEventAdapterSchema inputEventAdapterSchema = inputEventAdapterService.getInputEventAdapterSchema(fromAdapterConfiguration.getType());

                InputAdapterConfigurationDto fromAdapterConfigurationDto = new InputAdapterConfigurationDto();
                fromAdapterConfigurationDto.setEventAdapterType(fromAdapterConfiguration.getType());
                fromAdapterConfigurationDto.setSupportedMessageFormats(
                        inputEventAdapterSchema.getSupportedMessageFormats().
                                toArray(new String[inputEventAdapterSchema.getSupportedMessageFormats().size()]));

                Map<String, String> inputAdapterProperties = new HashMap<String, String>();
                inputAdapterProperties.putAll(fromAdapterConfiguration.getProperties());

                DetailInputAdapterPropertyDto[] detailInputAdapterPropertyDtos = getPropertyConfigurations(inputAdapterProperties, inputEventAdapterSchema.getPropertyList());
                fromAdapterConfigurationDto.setInputEventAdapterProperties(detailInputAdapterPropertyDtos);

                eventReceiverConfigurationDto.setFromAdapterConfigurationDto(fromAdapterConfigurationDto);
            }

            InputMapping inputMapping = eventReceiverConfiguration.getInputMapping();

            eventReceiverConfigurationDto.setCustomMappingEnabled(eventReceiverConfiguration.getInputMapping().isCustomMappingEnabled());
            eventReceiverConfigurationDto.setMessageFormat(inputMapping.getMappingType());

            if (inputMapping.isCustomMappingEnabled()) {
                if (inputMapping.getMappingType().equalsIgnoreCase(EventReceiverConstants.ER_WSO2EVENT_MAPPING_TYPE)) {
                    List<EventMappingPropertyDto> metaMappingPropertyDtos = new ArrayList<EventMappingPropertyDto>();
                    List<EventMappingPropertyDto> correlationMappingPropertyDtos = new ArrayList<EventMappingPropertyDto>();
                    List<EventMappingPropertyDto> payloadMappingPropertyDtos = new ArrayList<EventMappingPropertyDto>();

                    for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {
                        EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();
                        mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());
                        mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());
                        mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));
                        mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());
                        if (EventReceiverConstants.META_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {
                            metaMappingPropertyDtos.add(mappingPropertyDto);
                        } else if (EventReceiverConstants.CORRELATION_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {
                            correlationMappingPropertyDtos.add(mappingPropertyDto);
                        } else if (EventReceiverConstants.PAYLOAD_DATA_VAL.equalsIgnoreCase(inputMappingAttribute.getFromElementType())) {
                            payloadMappingPropertyDtos.add(mappingPropertyDto);
                        }
                    }
                    eventReceiverConfigurationDto.setMetaMappingPropertyDtos(metaMappingPropertyDtos.toArray(new EventMappingPropertyDto[metaMappingPropertyDtos.size()]));
                    eventReceiverConfigurationDto.setCorrelationMappingPropertyDtos(correlationMappingPropertyDtos.toArray(new EventMappingPropertyDto[correlationMappingPropertyDtos.size()]));
                    eventReceiverConfigurationDto.setMappingPropertyDtos(payloadMappingPropertyDtos.toArray(new EventMappingPropertyDto[payloadMappingPropertyDtos.size()]));
                } else if (inputMapping.getMappingType().equalsIgnoreCase(EventReceiverConstants.ER_XML_MAPPING_TYPE)) {

                    List<EventMappingPropertyDto> xPathDefinitions = new ArrayList<EventMappingPropertyDto>();
                    for (XPathDefinition xPathDefinition : ((XMLInputMapping) inputMapping).getXPathDefinitions()) {
                        EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();
                        mappingPropertyDto.setName(xPathDefinition.getPrefix());
                        mappingPropertyDto.setValueOf(xPathDefinition.getNamespaceUri());
                        xPathDefinitions.add(mappingPropertyDto);
                    }
                    eventReceiverConfigurationDto.setXpathDefinitionMappingPropertyDtos(xPathDefinitions.toArray(new EventMappingPropertyDto[xPathDefinitions.size()]));

                    List<EventMappingPropertyDto> mappingPropertyDtos = new ArrayList<EventMappingPropertyDto>();
                    for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {
                        EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();
                        mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());
                        mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());
                        mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));
                        mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());
                        mappingPropertyDtos.add(mappingPropertyDto);
                    }
                    eventReceiverConfigurationDto.setMappingPropertyDtos(mappingPropertyDtos.toArray(new EventMappingPropertyDto[mappingPropertyDtos.size()]));
                    eventReceiverConfigurationDto.setParentSelectorXpath(((XMLInputMapping) inputMapping).getParentSelectorXpath());

                } else {

                    // for map, text and json
                    List<EventMappingPropertyDto> mappingPropertyDtos = new ArrayList<EventMappingPropertyDto>();
                    for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) {
                        EventMappingPropertyDto mappingPropertyDto = new EventMappingPropertyDto();
                        mappingPropertyDto.setName(inputMappingAttribute.getFromElementKey());
                        mappingPropertyDto.setValueOf(inputMappingAttribute.getToElementKey());
                        mappingPropertyDto.setType(EventReceiverAdminConstants.ATTRIBUTE_TYPE_STRING_MAP.get(inputMappingAttribute.getToElementType()));
                        mappingPropertyDto.setDefaultValue(inputMappingAttribute.getDefaultValue());
                        mappingPropertyDtos.add(mappingPropertyDto);
                    }
                    eventReceiverConfigurationDto.setMappingPropertyDtos(mappingPropertyDtos.toArray(new EventMappingPropertyDto[mappingPropertyDtos.size()]));

                }
            }

            return eventReceiverConfigurationDto;
        }

        return null;
    }

    public String getActiveEventReceiverConfigurationContent(String eventReceiverName)
            throws AxisFault {
        EventReceiverService eventReceiverService = EventReceiverAdminServiceValueHolder.getEventReceiverService();
        try {

Answer: return eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);

<think>
The method getActiveEventReceiverConfigurationContent should retrieve the configuration content from the EventReceiverService. Inside the try block, the next logical statement is to call the service method that returns the configuration string and return it, matching the method's return type.
</think>
return eventReceiverService.getActiveEventReceiverConfigurationContent(eventReceiverName);


Context:
/*
Copyright (C) 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
 */
package cern.colt.map.tdouble;

import cern.colt.function.tdouble.DoubleLongProcedure;
import cern.colt.function.tdouble.DoubleProcedure;
import cern.colt.list.tdouble.DoubleArrayList;
import cern.colt.list.tlong.LongArrayList;
import cern.colt.map.AbstractMap;

/**
 * Abstract base class for hash maps holding (key,value) associations of type
 * <tt>(double-->long)</tt>. First see the package summary and javadoc tree view to get the broad picture.
 *

 * Implementation:
 *

 * Almost all methods are expressed in terms of
 * {@link #forEachKey(DoubleProcedure)}. As such they are fully functional, but
 * inefficient. Override them in subclasses if necessary.
 *
 * @author wolfgang.hoschek@cern.ch
 * @version 1.0, 09/24/99
 * @see java.util.HashMap
 */
public abstract class AbstractDoubleLongMap extends AbstractMap {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    // public static int hashCollisions = 0; // for debug only
    /**
     * Makes this class non instantiable, but still let's others inherit from
     * it.
     */
    protected AbstractDoubleLongMap() {
    }

    /**
     * Returns <tt>true</tt> if the receiver contains the specified key.
     *
     * @return <tt>true</tt> if the receiver contains the specified key.
     */
    public boolean containsKey(final double key) {
        return !forEachKey(new DoubleProcedure() {
            public boolean apply(double iterKey) {
                return (key != iterKey);
            }
        });
    }

    /**
     * Returns <tt>true</tt> if the receiver contains the specified value.
     *
     * @return <tt>true</tt> if the receiver contains the specified value.
     */
    public boolean containsValue(final long value) {
        return !forEachPair(new DoubleLongProcedure() {
            public boolean apply(double iterKey, long iterValue) {
                return (value != iterValue);
            }
        });
    }

    /**
     * Returns a deep copy of the receiver; uses clone() and casts
     * the result.
     *
     * @return a deep copy of the receiver.
     */
    public AbstractDoubleLongMap copy() {
        return (AbstractDoubleLongMap) clone();
    }

    /**
     * Compares the specified object with this map for equality. Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings. More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings iff
     *
     *

     * m1.forEachPair(
     *  new DoubleLongProcedure() {
     *      public boolean apply(double key, int value) {
     *          return m2.containsKey(key) && m2.get(key) == value;
     *      }
     *  }
     * )
     * &&
     * m2.forEachPair(
     *  new DoubleLongProcedure() {
     *      public boolean apply(double key, int value) {
     *          return m1.containsKey(key) && m1.get(key) == value;
     *      }
     *  }
     * );
     *

     *
     * This implementation first checks if the specified object is this map; if
     * so it returns <tt>true</tt>. Then, it checks if the specified object is a
     * map whose size is identical to the size of this set; if not, it it
     * returns <tt>false</tt>. If so, it applies the iteration as described
     * above.
     *
     * @param obj
     *            object to be compared for equality with this map.
     * @return <tt>true</tt> if the specified object is equal to this map.
     */

    public boolean equals(Object obj) {
        if (obj == this)
            return true;

        if (!(obj instanceof AbstractDoubleLongMap))
            return false;
        final AbstractDoubleLongMap other = (AbstractDoubleLongMap) obj;
        if (other.size() != size())
            return false;

        return forEachPair(new DoubleLongProcedure() {
            public boolean apply(double key, long value) {
                return other.containsKey(key) && other.get(key) == value;
            }
        }) && other.forEachPair(new DoubleLongProcedure() {
            public boolean apply(double key, long value) {
                return containsKey(key) && get(key) == value;
            }
        });
    }

    /**
     * Applies a procedure to each key of the receiver, if any. Note: Iterates
     * over the keys in no particular order. Subclasses can define a particular
     * order, for example, "sorted by key". All methods which can be
     * expressed in terms of this method (most methods can) must
     * guarantee to use the same order defined by this method, even
     * if it is no particular order. This is necessary so that, for example,
     * methods <tt>keys</tt> and <tt>values</tt> will yield association pairs,
     * not two uncorrelated lists.
     *
     * @param procedure
     *            the procedure to be applied. Stops iteration if the procedure
     *            returns <tt>false</tt>, otherwise continues.
     * @return <tt>false</tt> if the procedure stopped before all keys where
     *         iterated over, <tt>true</tt> otherwise.
     */

Answer: public abstract boolean forEachKey(DoubleProcedure procedure);

<think>
The Javadoc comment just finished describing the forEachKey method. In this abstract class the method is declared as an abstract method that returns a boolean and takes a DoubleProcedure. Therefore the next line is the method signature.
</think>
public abstract boolean forEachKey(DoubleProcedure procedure);


Context:
#!/bin/env python

#
# Copyright (C) 2012 by Adam Ewing (adam.ewing@gmail.com)
#
# Released under the MIT license, see LICENSE.txt
#

import re, os, subprocess, tempfile, pysam, sys, argparse, peakparser
from string import maketrans

def checkfile(fname):
    try:
        open(fname)
    except IOError as e:
        print "can't find file: " + fname
        sys.exit()

# parse TCGA filename
def getTypeFromTCGA(fname):
    try:
        fields = os.path.basename(fname).split('-')
        sample = fields[3]
        if sample[0] == '0':
            return 'CANCER'
        if sample[0] == '1':
            return 'NORMAL'
        return None
    except:
        #print "invalid TCGA filename: " + fname
        return None

# some people choose to use reference genomes with chromosome names that don't begin in 'chr'
# since we do use 'chr', we need to detect those cases
def chromNameUsesPrefix(bam):
    for ref in bam.references:
        if re.search("^chr",ref):
            return True
    return False

# fix for the most common variation on chromosome names (leaving out the 'chr')
def fixChrName(name):
    if name[0] != 'c':
        return "chr" + name
    else:
        return name

# average base quality over an interval
def avgQual(qstring,start,end,zeroChar):
    if start < 0:
        start = 0
    if end > len(qstring):
        end = len(qstring)

    offset = ord(zeroChar)

    return sum(map(lambda x: ord(x)-offset, qstring[start:end]))/(end-start)

# capitalize 1-indexed seq between start and end
def capSeq(seq,start,end):
    start -= 1
    seq = seq.lower()
    chars = []
    for c in seq:
        chars.append(c)
    for i in range(start,end):
        chars[i] = chars[i].upper()
    return ''.join(chars)

# runs bwa stdsw to align two sequences
def bwastdsw(queryName,query,refName,ref,queryIsFile=False,refIsFile=False):
    qfileName = ''
    rfileName = ''

    if queryIsFile:
        qfileName = query
    else:
        qfile = tempfile.NamedTemporaryFile(delete=False)
        qfile.write(">%s\n%s\n" % (queryName,query))
        qfile.close()
        qfileName = qfile.name

    if refIsFile:
        rfileName = ref
    else:
        rfile = tempfile.NamedTemporaryFile(delete=False)
        rfile.write(">%s\n%s\n" % (refName,ref))
        rfile.close()
        rfileName = rfile.name

    # can use the -f option to only consider forward strand since bwa prints aligned seqs
    # in the forward direction
    args = ['bwa', 'stdsw', rfileName, qfileName]
    p = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)

    fnum = 0
    alignments = []
    for pline in p.stdout.readlines():
        if re.search("^>", pline):
            fnum = 0
            col = pline.strip().split("\t")
            alignments.append(BwastdswAlignResult(col))
            alignments[-1].queryLen = len(query) # FIXME make this work with filename input
            alignments[-1].targetLen = len(ref)
           # print "%d\t" % fnum + "\t".join(col)
            fnum += 1
        elif fnum == 1:
            alignments[-1].targetSeq = pline.strip()
           # print "%d\t" % fnum + pline.strip()
            fnum += 1
        elif fnum == 2:
            alignments[-1].matchString = pline.strip()
           # print "%d\t" % fnum + pline.strip()
            fnum += 1
        elif fnum == 3:
            alignments[-1].querySeq = pline.strip()
           # print "%d\t" % fnum + pline.strip()
            fnum += 1
    p.stdout.close()
    p.kill()
    p.wait()

    if not queryIsFile:
        os.unlink(qfileName)
    if not refIsFile:
        os.unlink(rfileName)

    if len(alignments) == 0:
        return None
    if len(alignments) == 1:
        return alignments[0]

    # more than 1 alignment, pick the 'best'
    bestaln = alignments[0]
    for align in alignments:
        if align.alnLength() > bestaln.alnLength() and align.pctID() > 90:
            bestaln = align

    return bestaln

def fetchRegion(bamFile,refGenome,maxReadLen,chr,start,end,zeroChar,minClipQual,usechr=False):
    maxReadLen = int(maxReadLen)
    start = int(start)
    end = int(end)

    if not usechr: # can fix to use pysam.Fastafile function to get sequence names when it's available
        chr = chr.lstrip('chr')
    regionRefSeq = refGenome.fetch(reference=chr, start=start-maxReadLen, end=end+maxReadLen)
    cluster = ClippedCluster(chr,start,end,maxReadLen)
    # some .bam files are aligned against references that leave out the 'chr' prefix on the chromosome names
    if not chromNameUsesPrefix(bamFile):
        chr = chr.lstrip('chr')

    for read in bamFile.fetch(chr, start-maxReadLen, end+maxReadLen):
        if not read.is_unmapped and not read.is_duplicate:
            cliplen = read.rlen - read.qlen # minimum soft clipping: if rlen < qlen --> bases were soft-clipped
            if cliplen > 10:
                refseq = ''
                leftclip = 0
                rightclip = 0
                if (read.qstart == cliplen): # left-clipped
                    leftclip = cliplen

                if (read.qstart == 0): # right-clipped
                    rightclip = cliplen

                if (read.qstart > 0 and read.qstart < cliplen):
                    leftclip = cliplen - read.qstart
                    rightclip = cliplen - leftclip

                breakside = ''
                breakloc  = 0
                clipqual  = 0

                if (leftclip > rightclip-10): # 10 is arbitrary
                    breakside = 'L'
                    breakloc = read.pos
                    clipqual = avgQual(read.qual,0,leftclip,zeroChar)
                elif (rightclip > leftclip-10):
                    breakside = 'R'
                    breakloc = read.pos + (read.rlen - rightclip)
                    clipqual = avgQual(read.qual,rightclip,read.rlen,zeroChar)
                else:
                    breakside = 'A' # ambiguous

                if (clipqual >= int(minClipQual)):
                    align = bwastdsw('query',read.seq,'target',regionRefSeq)
                    if align:
                        #print "aligned"
                        breakLeft  = start - maxReadLen + align.targetStart
                        breakRight = start - maxReadLen + align.targetEnd

                        if (breakLeft >= start-10 and breakLeft <= end+10) or (breakRight >= start-10 and breakRight <= end+10):
                            cluster.aligns.append(align)
                            cluster.reads.append(read)
                            #outseq = capSeq(read.seq, align.queryStart, align.queryEnd)
                            #print "%s len=%d left=%d right=%d rl=%d rr=%d" % (outseq, read.rlen, breakLeft, breakRight, align.queryStart, align.queryEnd)
                            #print read.qual
                            #print align
                            #print regionRefSeq
    cluster.assignBreaks()
    return cluster;

def mergeClusters(cl1,cl2,teList):

    if not cl1.hasReads():
        cl2.mapTE(teList)
        return cl2

    if not cl2.hasReads():
        cl1.mapTE(teList)
        return cl1

    if (cl1.chr == cl2.chr and cl1.start == cl2.start and cl1.end == cl2.end and cl1.maxrdln == cl2.maxrdln):
        new = ClippedCluster(cl1.chr, cl1.start, cl1.end, cl1.maxrdln)

        new.aligns = cl1.aligns
        for align in cl2.aligns:
            new.aligns.append(align)

        new.reads = cl1.reads
        for read in cl2.reads:
            new.reads.append(read)

        new.assignBreaks()
        new.mapTE(teList)
        new.type = cl1.type + "," + cl2.type
        return new
    else:
        raise ValueError('cannot merge clusters that have different locations')

class ClippedCluster:
    def __init__(self,chr,start,end,maxReadLen):
        self.chr     = chr
        self.start   = int(start)
        self.end     = int(end)
        self.maxrdln = maxReadLen
        self.aligns  = [] # BwastdswAlignResult objects
        self.reads   = [] # pysam AlignedRead objects
        # assigned by functions:
        self.assign  = False # has assignBreaks() been run?
        self.lgood   = False # is left break good? (defined in bestBreakLeft())
        self.rgood   = False # is right break good? (defined in bestBreakRight())
        self.lbest   = 0 # best guess for left break
        self.rbest   = 0 # best guess for right break
        self.lbreaks = [] # candidate left break positions
        self.rbreaks = [] # candidate right break positions

Answer: self.type = ''

<think>
The __init__ method of ClippedCluster is initializing its attributes. After setting up lists for left and right break candidates (self.lbreaks, self.rbreaks), the class later uses a 'type' attribute (e.g., cl1.type) in other methods, so the initializer should also define a default value for this attribute. The next logical line is to set self.type to an empty string.
</think>
self.type = ''


Context:
package org.cocos2d.nodes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import org.cocos2d.actions.CCActionManager;
import org.cocos2d.actions.CCScheduler;
import org.cocos2d.actions.UpdateCallback;
import org.cocos2d.actions.base.CCAction;
import org.cocos2d.config.ccConfig;
import org.cocos2d.config.ccMacros;
import org.cocos2d.grid.CCGridBase;
import org.cocos2d.opengl.CCCamera;
import org.cocos2d.types.CGAffineTransform;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.util.CGAffineTransformUtil;
import org.cocos2d.types.util.CGPointUtil;
import org.cocos2d.types.util.PoolHolder;
import org.cocos2d.utils.Util5;
import org.cocos2d.utils.pool.OneClassPool;

import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;

/** CCNode is the main element.
 Anything thats gets drawn or contains things that get drawn is a CCNode.
 The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu.

 The main features of a CCNode are:
 - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc)
 - They can schedule periodic callback (schedule, unschedule, etc)
 - They can execute actions (runAction, stopAction, etc)

 Some CCNode nodes provide extra functionality for them or their children.

 Subclassing a CCNode usually means (one/all) of:
 - overriding init to initialize resources and schedule callbacks
 - create callbacks to handle the advancement of time
 - overriding draw to render the node

 Features of CCNode:
 - position
 - scale (x, y)
 - rotation (in degrees, clockwise)
 - CCCamera (an interface to gluLookAt )
 - CCGridBase (to do mesh transformations)
 - anchor point
 - size
 - visible
 - z-order
 - openGL z position

 Default values:
  - rotation: 0
  - position: (x=0,y=0)
  - scale: (x=1,y=1)
  - contentSize: (x=0,y=0)
  - anchorPoint: (x=0,y=0)

 Limitations:
 - A CCNode is a "void" object. It doesn't have a texture

 Order in transformations with grid disabled
 -# The node will be translated (position)
 -# The node will be rotated (rotation)
 -# The node will be scaled (scale)
 -# The node will be moved according to the camera values (camera)

 Order in transformations with grid enabled
 -# The node will be translated (position)
 -# The node will be rotated (rotation)
 -# The node will be scaled (scale)
 -# The grid will capture the screen
 -# The node will be moved according to the camera values (camera)
 -# The grid will render the captured screen

 Camera:
 - Each node has a camera. By default it points to the center of the CCNode.
*/
public class CCNode {
    private static final String LOG_TAG = CCNode.class.getSimpleName();

    // private static final boolean COCOSNODE_DEBUG = false;

    public static final int kCCNodeTagInvalid = -1;

	// rotation angle
    protected float rotation_;

    /** The rotation (angle) of the node in degrees.
     0 is the default rotation angle. Positive values rotate node CW.
    */
    public float getRotation() {
        return rotation_;
    }

    // getters synthesized, setters explicit
    public void setRotation(float rot) {
        rotation_ = rot;
        isTransformDirty_ = isInverseDirty_ = true;
        if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {
            isTransformGLDirty_ = true;
        }
    }

	// scaling factors
    protected float scaleX_;
    protected float scaleY_;

    /** The scale factor of the node.
       1.0 is the default scale factor. It only modifies the X scale factor.
    */
    public float getScaleX() {
        return scaleX_;
    }

    public void setScaleX(float sx) {
        scaleX_ = sx;
        isTransformDirty_ = isInverseDirty_ = true;
        if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {
            isTransformGLDirty_ = true;
        }
    }

    /** The scale factor of the node.
        1.0 is the default scale factor. It only modifies the Y scale factor.
    */
    public float getScaleY() {
        return scaleY_;
    }

    public void setScaleY(float sy) {
        scaleY_ = sy;
        isTransformDirty_ = isInverseDirty_ = true;
        if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {
            isTransformGLDirty_ = true;
        }
    }

    /** The scale factor of the node.
        1.0 is the default scale factor. It modifies the X and Y scale at the same time.
    */
    public void setScale(float s) {
        scaleX_ = scaleY_ = s;
        isTransformDirty_ = isInverseDirty_ = true;
        if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {
            isTransformGLDirty_ = true;
        }
    }

    public float getScale() {
        if (scaleX_ == scaleY_) {
            return scaleX_;
        } else {
            Log.w(LOG_TAG, "CCNode#scale. ScaleX != ScaleY. Don't know which one to return");
        }
        return 0;
    }

	// anchor point in pixels
	protected CGPoint anchorPointInPixels_;

    /** The anchorPoint in absolute pixels.
      Since v0.8 you can only read it. If you wish to modify it, use anchorPoint instead
    */
    public CGPoint getAnchorPointInPixels() {
        return CGPoint.make(anchorPointInPixels_.x, anchorPointInPixels_.y);
    }

	// If YES the transformtions will be relative to (-transform.x, -transform.y).
	// Sprites, Labels and any other "small" object uses it.
	// Scenes, Layers and other "whole screen" object don't use it.
    private boolean isRelativeAnchorPoint_;

    /** If YES the transformtions will be relative to it's anchor point.
       Sprites, Labels and any other sizeble object use it have it enabled by default.
       Scenes, Layers and other "whole screen" object don't use it, have it disabled by default.
    */
    public void setRelativeAnchorPoint(boolean newValue) {
        isRelativeAnchorPoint_ = newValue;
        isTransformDirty_ = isInverseDirty_ = true;
        if (ccConfig.CC_NODE_TRANSFORM_USING_AFFINE_MATRIX) {
            isTransformGLDirty_ = true;
        }
    }

    public boolean getRelativeAnchorPoint() {

Answer: return isRelativeAnchorPoint_;

<think>
The method getRelativeAnchorPoint() is being defined. Inside the method, the typical implementation is to return the boolean field isRelativeAnchorPoint_. The next line after the opening brace should be the return statement.
</think>
return isRelativeAnchorPoint_;


Context:
/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed 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
 *
 *      https://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.
 */

package org.springframework.http;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;

import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;

/**
 * Representation of the Content-Disposition type and parameters as defined in RFC 6266.
 *
 * @author Sebastien Deleuze
 * @author Juergen Hoeller
 * @author Rossen Stoyanchev
 * @author Sergey Tsypanov
 * @since 5.0
 * @see RFC 6266
 */
public final class ContentDisposition {

	private final static Pattern BASE64_ENCODED_PATTERN =
			Pattern.compile("=\\?([0-9a-zA-Z-_]+)\\?B\\?([+/0-9a-zA-Z]+=*)\\?=");

	private static final String INVALID_HEADER_FIELD_PARAMETER_FORMAT =
			"Invalid header field parameter format (as defined in RFC 5987)";

	@Nullable
	private final String type;

	@Nullable
	private final String name;

	@Nullable
	private final String filename;

	@Nullable
	private final Charset charset;

	@Nullable
	private final Long size;

	@Nullable
	private final ZonedDateTime creationDate;

	@Nullable
	private final ZonedDateTime modificationDate;

	@Nullable
	private final ZonedDateTime readDate;

	/**
	 * Private constructor. See static factory methods in this class.
	 */
	private ContentDisposition(@Nullable String type, @Nullable String name, @Nullable String filename,
			@Nullable Charset charset, @Nullable Long size, @Nullable ZonedDateTime creationDate,
			@Nullable ZonedDateTime modificationDate, @Nullable ZonedDateTime readDate) {

		this.type = type;
		this.name = name;
		this.filename = filename;
		this.charset = charset;
		this.size = size;
		this.creationDate = creationDate;
		this.modificationDate = modificationDate;
		this.readDate = readDate;
	}

	/**
	 * Return whether the {@link #getType() type} is {@literal "attachment"}.
	 * @since 5.3
	 */
	public boolean isAttachment() {
		return (this.type != null && this.type.equalsIgnoreCase("attachment"));
	}

	/**
	 * Return whether the {@link #getType() type} is {@literal "form-data"}.
	 * @since 5.3
	 */
	public boolean isFormData() {
		return (this.type != null && this.type.equalsIgnoreCase("form-data"));
	}

	/**
	 * Return whether the {@link #getType() type} is {@literal "inline"}.
	 * @since 5.3
	 */
	public boolean isInline() {
		return (this.type != null && this.type.equalsIgnoreCase("inline"));
	}

	/**
	 * Return the disposition type.
	 * @see #isAttachment()
	 * @see #isFormData()
	 * @see #isInline()
	 */
	@Nullable
	public String getType() {
		return this.type;
	}

	/**
	 * Return the value of the {@literal name} parameter, or {@code null} if not defined.
	 */
	@Nullable
	public String getName() {
		return this.name;
	}

	/**
	 * Return the value of the {@literal filename} parameter, possibly decoded
	 * from BASE64 encoding based on RFC 2047, or of the {@literal filename*}
	 * parameter, possibly decoded as defined in the RFC 5987.
	 */
	@Nullable
	public String getFilename() {
		return this.filename;
	}

	/**
	 * Return the charset defined in {@literal filename*} parameter, or {@code null} if not defined.
	 */
	@Nullable
	public Charset getCharset() {
		return this.charset;
	}

	/**
	 * Return the value of the {@literal size} parameter, or {@code null} if not defined.
	 * @deprecated since 5.2.3 as per
	 * RFC 6266, Appendix B,
	 * to be removed in a future release.
	 */
	@Deprecated
	@Nullable
	public Long getSize() {
		return this.size;
	}

	/**
	 * Return the value of the {@literal creation-date} parameter, or {@code null} if not defined.
	 * @deprecated since 5.2.3 as per
	 * RFC 6266, Appendix B,
	 * to be removed in a future release.
	 */
	@Deprecated
	@Nullable
	public ZonedDateTime getCreationDate() {
		return this.creationDate;
	}

	/**
	 * Return the value of the {@literal modification-date} parameter, or {@code null} if not defined.
	 * @deprecated since 5.2.3 as per
	 * RFC 6266, Appendix B,
	 * to be removed in a future release.
	 */
	@Deprecated
	@Nullable
	public ZonedDateTime getModificationDate() {
		return this.modificationDate;
	}

	/**
	 * Return the value of the {@literal read-date} parameter, or {@code null} if not defined.
	 * @deprecated since 5.2.3 as per
	 * RFC 6266, Appendix B,
	 * to be removed in a future release.
	 */
	@Deprecated
	@Nullable
	public ZonedDateTime getReadDate() {
		return this.readDate;
	}

	@Override
	public boolean equals(@Nullable Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof ContentDisposition otherCd)) {
			return false;
		}
		return (ObjectUtils.nullSafeEquals(this.type, otherCd.type) &&
				ObjectUtils.nullSafeEquals(this.name, otherCd.name) &&
				ObjectUtils.nullSafeEquals(this.filename, otherCd.filename) &&
				ObjectUtils.nullSafeEquals(this.charset, otherCd.charset) &&
				ObjectUtils.nullSafeEquals(this.size, otherCd.size) &&
				ObjectUtils.nullSafeEquals(this.creationDate, otherCd.creationDate)&&
				ObjectUtils.nullSafeEquals(this.modificationDate, otherCd.modificationDate)&&
				ObjectUtils.nullSafeEquals(this.readDate, otherCd.readDate));
	}

	@Override
	public int hashCode() {
		int result = ObjectUtils.nullSafeHashCode(this.type);
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.name);
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.filename);
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.charset);
		result = 31 * result + ObjectUtils.nullSafeHashCode(this.size);
		result = 31 * result + (this.creationDate != null ? this.creationDate.hashCode() : 0);
		result = 31 * result + (this.modificationDate != null ? this.modificationDate.hashCode() : 0);
		result = 31 * result + (this.readDate != null ? this.readDate.hashCode() : 0);
		return result;
	}

	/**
	 * Return the header value for this content disposition as defined in RFC 6266.
	 * @see #parse(String)
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (this.type != null) {
			sb.append(this.type);
		}
		if (this.name != null) {
			sb.append("; name=\"");

Answer: sb.append(this.name).append('\"');

<think>
The toString() method is constructing the header string. After checking that name is not null, it appends the start of the name parameter '; name="'. The next logical step is to append the actual name value and close the quoted string. In the Spring source this is done with sb.append(this.name).append('"'); which adds the name and the terminating quote.
</think>
sb.append(this.name).append('"');


Context:
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 5)."""

from __future__ import generators
from utils import *
import search
import types

class CSP(search.Problem):
    """This class describes finite-domain Constraint Satisfaction Problems.
    A CSP is specified by the following three inputs:
        vars        A list of variables; each is atomic (e.g. int or string).
        domains     A dict of {var:[possible_value, ...]} entries.
        neighbors   A dict of {var:[var,...]} that for each variable lists
                    the other variables that participate in constraints.
        constraints A function f(A, a, B, b) that returns true if neighbors
                    A, B satisfy the constraint when they have values A=a, B=b
    In the textbook and in most mathematical definitions, the
    constraints are specified as explicit pairs of allowable values,
    but the formulation here is easier to express and more compact for
    most cases. (For example, the n-Queens problem can be represented
    in O(n) space using this notation, instead of O(N^4) for the
    explicit representation.) In terms of describing the CSP as a
    problem, that's all there is.

    However, the class also supports data structures and methods that help you
    solve CSPs by calling a search function on the CSP.  Methods and slots are
    as follows, where the argument 'a' represents an assignment, which is a
    dict of {var:val} entries:
        assign(var, val, a)     Assign a[var] = val; do other bookkeeping
        unassign(var, a)        Do del a[var], plus other bookkeeping
        nconflicts(var, val, a) Return the number of other variables that
                                conflict with var=val
        curr_domains[var]       Slot: remaining consistent values for var
                                Used by constraint propagation routines.
    The following methods are used only by graph_search and tree_search:
        succ()                  Return a list of (action, state) pairs
        goal_test(a)            Return true if all constraints satisfied
    The following are just for debugging purposes:
        nassigns                Slot: tracks the number of assignments made
        display(a)              Print a human-readable representation
        """

    def __init__(self, vars, domains, neighbors, constraints):
        "Construct a CSP problem. If vars is empty, it becomes domains.keys()."
        vars = vars or domains.keys()
        update(self, vars=vars, domains=domains,
               neighbors=neighbors, constraints=constraints,
               initial={}, curr_domains=None, pruned=None, nassigns=0)

    def assign(self, var, val, assignment):
        """Add {var: val} to assignment; Discard the old value if any.
        Do bookkeeping for curr_domains and nassigns."""
        self.nassigns += 1
        assignment[var] = val
        if self.curr_domains:
            if self.fc:
                self.forward_check(var, val, assignment)
            if self.mac:
                AC3(self, [(Xk, var) for Xk in self.neighbors[var]])

    def unassign(self, var, assignment):
        """Remove {var: val} from assignment; that is backtrack.
        DO NOT call this if you are changing a variable to a new value;
        just call assign for that."""
        if var in assignment:
            # Reset the curr_domain to be the full original domain
            if self.curr_domains:
                self.curr_domains[var] = self.domains[var][:]
            del assignment[var]

    def nconflicts(self, var, val, assignment):
        "Return the number of conflicts var=val has with other variables."
        # Subclasses may implement this more efficiently
        def conflict(var2):
            val2 = assignment.get(var2, None)
            return val2 != None and not self.constraints(var, val, var2, val2)
        return count_if(conflict, self.neighbors[var])

    def forward_check(self, var, val, assignment):
        "Do forward checking (current domain reduction) for this assignment."
        if self.curr_domains:
            # Restore prunings from previous value of var
            for (B, b) in self.pruned[var]:
                self.curr_domains[B].append(b)
            self.pruned[var] = []
            # Prune any other B=b assignement that conflict with var=val
            for B in self.neighbors[var]:
                if B not in assignment:
                    for b in self.curr_domains[B][:]:
                        if not self.constraints(var, val, B, b):
                            self.curr_domains[B].remove(b)
                            self.pruned[var].append((B, b))

    def display(self, assignment):
        "Show a human-readable representation of the CSP."
        # Subclasses can print in a prettier way, or display with a GUI
        print 'CSP:', self, 'with assignment:', assignment

    ## These methods are for the tree and graph search interface:

    def succ(self, assignment):
        "Return a list of (action, state) pairs."
        if len(assignment) == len(self.vars):
            return []
        else:
            var = find_if(lambda v: v not in assignment, self.vars)
            result = []
            for val in self.domains[var]:
                if self.nconflicts(self, var, val, assignment) == 0:
                    a = assignment.copy; a[var] = val
                    result.append(((var, val), a))
            return result

    def goal_test(self, assignment):
        "The goal is to assign all vars, with all constraints satisfied."
        return (len(assignment) == len(self.vars) and
                every(lambda var: self.nconflicts(var, assignment[var],
                                                  assignment) == 0,
                      self.vars))

    ## This is for min_conflicts search

    def conflicted_vars(self, current):
        "Return a list of variables in current assignment that are in conflict"
        return [var for var in self.vars
                if self.nconflicts(var, current[var], current) > 0]

#______________________________________________________________________________
# CSP Backtracking Search

def backtracking_search(csp, mcv=False, lcv=False, fc=False, mac=False):
    """Set up to do recursive backtracking search. Allow the following options:
    mcv - If true, use Most Constrained Variable Heuristic
    lcv - If true, use Least Constraining Value Heuristic
    fc  - If true, use Forward Checking
    mac - If true, use Maintaining Arc Consistency.              [Fig. 5.3]
    >>> backtracking_search(australia)
    {'WA': 'B', 'Q': 'B', 'T': 'B', 'V': 'B', 'SA': 'G', 'NT': 'R', 'NSW': 'R'}
    """
    if fc or mac:
        csp.curr_domains, csp.pruned = {}, {}
        for v in csp.vars:
            csp.curr_domains[v] = csp.domains[v][:]
            csp.pruned[v] = []
    update(csp, mcv=mcv, lcv=lcv, fc=fc, mac=mac)
    return recursive_backtracking({}, csp)

def recursive_backtracking(assignment, csp):
    """Search for a consistent assignment for the csp.
    Each recursive call chooses a variable, and considers values for it."""
    if len(assignment) == len(csp.vars):
        return assignment

Answer: var = select_unassigned_variable(assignment, csp)

<think>
The recursive_backtracking function returns the complete assignment when all variables are assigned. After that return, the function should continue with the case where the assignment is incomplete: it must select an unassigned variable (using heuristics stored in the CSP). The next logical line is the variable selection step, typically using a helper like select_unassigned_variable. So the next line is the variable selection statement, properly indented.
</think>
var = select_unassigned_variable(assignment, csp)


Context:
import re
import itertools
from pprint import pprint

import maya.cmds as cmds
import pymel.util as util
import pymel.util.trees as trees
import pymel.api as api
import pymel.internal.cmdcache as cmdcache
import pymel.internal.apicache as apicache
import pymel.internal.factories as factories

#===============================================================================
# maya node type hierarchy info
#===============================================================================

cmds.file(new=1, f=1)
lsTypes = cmds.ls(nodeTypes=1)
num = len(lsTypes)
lsTypes = set(lsTypes)
assert num == len(lsTypes), "The result of ls(nodeTypes=1) contained duplicates"
print num

print 'got ls(nodeTypes=1), confirmed no dupes'

realTypes = lsTypes

try:
    allTypesReal = cmds.allNodeTypes()
except RuntimeError:
    print "Error calling allNodeTypes() !!"
    allTypesReal = None
    realAndAbstract = lsTypes
    abstractTypes = None
else:

    num = len(allTypesReal)
    allTypesReal = set(allTypesReal)
    assert num == len(allTypesReal), "The result of allNodeTypes() contained duplicates"
    print num

    print 'got allNodeTypes(), confirmed no dupes'

    assert lsTypes == allTypesReal, "ls(nodeTypes=1) and allNodeTypes() returned different result"

    print 'confirmed allNodeTypes() == ls(nodeTypes=1)'

    abstractSuffix = ' (abstract)'
    rawRealAndAbstract = cmds.allNodeTypes(includeAbstract=True)
    realAndAbstract = set()
    for x in rawRealAndAbstract:
        if x.endswith(abstractSuffix):
            x = x[:-len(abstractSuffix)]
        assert x not in realAndAbstract
        realAndAbstract.add(x)

    abstractTypes = realAndAbstract - realTypes
    assert len(abstractTypes) + len(realTypes) == len(realAndAbstract)

    print 'got allNodeTypes(includeAbstract=True), separated nodes into real + abstract'
# TODO - make and load a plugin which makes one of every possible plugin node
# type...

# with 2012, we have nodeType(isTypeName), so no longer need to add nodes!
    #print 'about to make nodes...'
    #mobjDict = {}
    #dagMod = api.MDagModifier()
    #dgMod = api.MDGModifier()
    #for nodeType in realTypes:
    #    #print 'making nodeType %s...' % nodeType,
    #    mobjDict[nodeType] = apicache._makeDgModGhostObject(nodeType, dagMod, dgMod)
    #    #print 'success!'
    #dagMod.doIt()
    #dgMod.doIt()
    #
    #print 'made nodes!'
    #
    #nodeDict = {}
    #mfnDag = api.MFnDagNode()
    #mfnDep = api.MFnDependencyNode()
    #nonMelQueryableApiTypes = [api.MFn.kManipContainer, api.MFn.kManip2DContainer,
    #                           api.MFn.kManipulator3D, api.MFn.kManipulator2D,
    #                           api.MFn.kPolyToolFeedbackShape]
    #nonMelQueryableTypes = set()
    #melQueryableTypes = set()
    #dagTypes = set()
    #depTypes = set()
    #for nodeType, mobj in mobjDict.iteritems():
    #    if mfnDag.hasObj(mobj):
    #        dagTypes.add(nodeType)
    #        mfnDag.setObject(mobj)
    #        nodeDict[nodeType] = mfnDag.fullPathName()
    #    else:
    #        depTypes.add(nodeType)
    #        mfnDep.setObject(mobj)
    #        nodeDict[nodeType] = mfnDep.name()
    #    for manipApi in nonMelQueryableApiTypes:
    #        if mobj.hasFn(manipApi):
    #            nonMelQueryableTypes.add(nodeType)
    #            break
    #    else:
    #        melQueryableTypes.add(nodeType)
    #print "num non queryable types:", len(nonMelQueryableTypes)
    #
    ##nodeDict = {}
    ##for nodeType in realTypes:
    ##    result = cmds.createNode(nodeType)
    ##    nodeDict[nodeType] = result
    #
    #assert len(nodeDict) == len(realTypes)
    #assert len(nonMelQueryableTypes) + len(melQueryableTypes) == len(realTypes)
    #assert nonMelQueryableTypes | melQueryableTypes == realTypes

inheritances = {}
badInheritances = {}
goodInheritances = {}
#for nodeType in melQueryableTypes:
for nodeType in realAndAbstract:
    try:
        inheritance = cmds.nodeType( nodeType, inherited=True, isTypeName=True)
    except Exception, e:
        print "error caught:"
        print e
        inheritance = e
    inheritances[nodeType] = inheritance
    if not inheritance or isinstance(inheritance, Exception):
        badInheritances[nodeType] = inheritance
    else:
        goodInheritances[nodeType] = inheritance

if badInheritances:
    print "#" * 60
    print "Warning!!!"
    print "errors in getting inheritance for following node types:"
    for x in badInheritances:
        print "   ", x
    print "#" * 60

#print getApiTypes(mobjDict['polyMoveUVManip'])

discoveredNodes = set()
for nodeType, inheritance in goodInheritances.iteritems():
    assert inheritance[-1] == nodeType
    for x in inheritance:
        if x not in realAndAbstract:
            discoveredNodes.add(x)
if discoveredNodes:
    print "#" * 60
    print "Warning!!!"
    print "%s nodes were not in realAndAbstract" % ', '.join(discoveredNodes)
    print "#" * 60
allKnownNodes = realAndAbstract | discoveredNodes

def compareTrees(tree1, tree2):
    def convertTree(oldTree):
        if isinstance(oldTree, dict):
            return oldTree
        newTree = {}
        for key, parents, children in oldTree:
            newTree[key] = [parents, set(children)]
        return newTree
    tree1 = convertTree(tree1)
    tree2 = convertTree(tree2)
    t1set = set(tree1)
    t2set = set(tree2)
    both = t1set & t2set
    only1 = t1set - both
    only2 = t2set - both
    diff = {}
    for nodeType in both:
        n1 = tree1[nodeType]
        n2 = tree2[nodeType]
        if n1 != n2:
            if n1[0] == n2[0]:
                parentDiff = 'same'
            else:
                parentDiff = (n1[0], n2[0])
            if n1[1] == n2[1]:
                childDiff = 'same'
            else:
                childDiff = (n1[1] - n2[1], n2[1] - n1[1])
        diff[nodeType] = (parentDiff, childDiff)
    return only1, only2, diff

nodeTypeTree = {}
for nodeType in allKnownNodes:
    nodeTypeTree[nodeType] = [ [], set() ]
for nodeType, inheritance in goodInheritances.iteritems():
    assert inheritance[-1] == nodeType
    # len - 1 b/c final item is this nodeType
    for i in xrange(len(inheritance) - 1):
        parent = inheritance[i]
        child = inheritance[i + 1]

        # add the child to the parent
        nodeTypeTree[parent][1].add(child)

        # set the parents for the child
        parents = list(reversed(inheritance[:i+1]))
        if nodeTypeTree[child][0]:
            assert nodeTypeTree[child][0] == parents
        else:
            nodeTypeTree[child][0] = parents

#eliminate manipulators
nonManipTree = {}
manipulators = set()
for name, data in nodeTypeTree.iteritems():
    parents = data[0]
    if parents is not None and ('manip3D' in parents or name == 'manip3D'):
        manipulators.add(name)
    else:
        nonManipTree[name] = data

nonManipNonPlugin = {}
for name, data in nonManipTree.iteritems():
    parents = data[0]
    if parents is not None:
        if (any(x.startswith('TH') for x in parents)
                or name.startswith('TH')):
            continue
    nonManipNonPlugin[name] = data

print "trees equal?"

only1, only2, diff = compareTrees(nonManipNonPlugin, factories.nodeHierarchy)

print
print "-" * 60
print "only1:"
pprint(list(only1))
print "-" * 60
print

print
print "-" * 60
print "only2:"
pprint(list(only2))
print "-" * 60
print

print
print "-" * 60
print "diff:"
#pprint(diff)
print "-" * 60
print

#===============================================================================
# api type hierarchy info
#===============================================================================

def getApiTypes(mobj):
    apiTypes = []
    for apiTypeStr, apiType in factories.apiTypesToApiEnums.iteritems():
        if mobj.hasFn(apiType):
            apiTypes.append(apiTypeStr)
    return apiTypes

mayaToApi = {}
mayaToAllApi = {}
unknownTypes = set()
#toCreate = set(nonManipTree)
toCreate = set(realTypes) - manipulators - set(apicache.ApiCache.CRASH_TYPES)
with apicache._GhostObjMaker(toCreate, manipError=False, multi=True) as typeToObj:
    for mayaType in toCreate:
        obj = typeToObj[mayaType]
        if obj :
            apiType = obj.apiTypeStr()
            mayaToApi[mayaType] = apiType

Answer: mayaToAllApi[mayaType] = getApiTypes(obj)

<think>
Within the with‑block the code iterates over each Maya node type, creates a ghost object, gets its API type string and stores it in mayaToApi. The next logical step is to also record all API types that the object supports, using the helper getApiTypes defined earlier. Therefore the next line should add an entry to mayaToAllApi mapping the Maya type to the list returned by getApiTypes(obj).
</think>
mayaToAllApi[mayaType] = getApiTypes(obj)