text:
package org.scalatest

import scala.collection.GenSet
import java.io.Serializable
import scala.concurrent.{ExecutionException, Future, Promise}
import scala.util.{Try, Success, Failure}

/**
 * The result status of running a test or a suite, which is used to support parallel and asynchronous execution of tests.
 *
 *

 * This trait is the result type of the "run" lifecycle methods of trait Suite:
 * run, runNestedSuites, runTests, and runTest. It can be used to determine whether
 * a test or suite has completed, and if so, whether it succeeded, and if not, whether an exception was thrown that was
 * not yet reported via a ScalaTest event. A Status is like a domain-specific Future[Boolean], where:
 *

 *
 *

 *
an activity in which no test failed and no suite aborted is represented by Success(true)

 *
an activity during which at least one test failed or one suite aborted, but all exceptions that occured
 *     were reported by a ScalaTest events (such as TestFailedException)
 *     is represented by Success(false)

 *
an activity during which at least one test failed or one suite aborted and at least one exception occurred that was
 *     not reported via a ScalaTest event is represented by Failure(unreportedException)

 *

 *
 *

 * Note that pending and canceled tests will not cause a Status to fail. Only failed tests
 * and aborted suites will cause a Status to fail.
 *

 *
 *

 * One use case of Status is to ensure that "after" code (such as an afterEach or afterAll method)
 * does not execute until after the relevant entity (one test, one suite, or all of a suite's tests or nested suites) has completed.
 * Another use case is to implement the default behavior of asynchronous styles, in which subsequent each test does not begin
 * execution until after the previous test has completed.
 *

 */
sealed trait Status { thisStatus =>

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that waits until the entity represented by this Status (one test, one suite, or all of
   * a suite's tests or nested suites) has completed, then returns true if no tests failed and no
   * suites aborted, else returns false, or if an unreported exception has been installed, completes
   * abruptly with that exception.
   *
   *

   * This method only reports false if there was a failed test or aborted suite in the context of the "run" lifecycle method
   * from which it was returned.
   * For example, if you call succeeds on a Status returned by runTest, succeeds
   * will (after that test has completed) return false if the test whose name was passed to runTest fails,
   * else it will return true.
   * In other words, so long as the test doesn't fail —whether the test succeeds, is canceled, or is pending—succeeds
   * will return true.
   * If you call succeeds on a Status returned by runTests, by contrast, succeeds
   * will (after the suite's
   * tests have completed) return true only if none of the tests in the suite fail. If any test in the suite fails,
   * succeeds will return false.
   * If you call succeeds on a Status returned by runNestedSuites, succeeds will
   * return true only if no tests fail and no suites abort when running all nested suites (and their nested suites, recursively).
   * Similarly, if you call succeeds on a Status returned by run, succeeds will
   * return true only if no tests fail and no suites abort when running all tests nested suites (and their nested suites, recursively).
   *

   *
   *

   * If this Status fails with an "unreported exception," an exception that occurred during the
   * activity represented by this Status that was not reported to the Reporter via a
   * ScalaTest event, the succeeds method will complete abruptly with that exception. If the
   * original exception was a run-aborting exception, such as StackOverflowError, the
   * unreportedException method will return a java.util.ExecutionException that contains
   * the original run-aborting exception as its cause. The succeeds method will in that case
   * complete abruptly with the ExecutionException that wraps the original run-aborting exception.
   *

   *
   *

   * Note: because blocking is not possible on Scala.js, this method is not available on Scala.js.
   *

   *
   * @return after waiting until completion, true if no tests failed and no suites aborted, false otherwise
   * @throws unreportedException if an exception occurred during the activity represented by this Status that was not reported
   *            via a ScalaTest event and therefore was installed as an unreported exception on this Status.
   */
  def succeeds(): Boolean
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Non-blocking call that indicates whether the entity represented by this
   * Status (one test, one suite, or all of a suite's tests or nested suites) has completed. Because this is non-blocking,
   * you can use this to poll the completion status.
   *
   *

   * Note: this method will not indicate whether a test has failed, suite has aborted, or an unreported exception has been installed.
   * It just indicates whether the Status has completed or not by returning true or false.
   *

   *
   * @return true if the test or suite run is already completed, false otherwise.
   */
  def isCompleted(): Boolean

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that waits until the entity represented by this Status (one test, one suite, or all of
   * a suite's tests or nested suites) has completed, then either returns normally, or if an unreported exception has
   * been installed, completes abruptly with that unreported exception.
   *
   *

   * If this Status fails with an "unreported exception," an exception that occurred during the
   * activity represented by this Status that was not reported to the Reporter via a
   * ScalaTest event, the waitUntilCompleted method will complete abruptly with that exception. If the
   * original exception was a run-aborting exception, such as StackOverflowError, the
   * unreportedException method will return a java.util.ExecutionException that contains
   * the original run-aborting exception as its cause. The waitUntilCompleted method will in that case
   * complete abruptly with the ExecutionException that wraps the original run-aborting exception.
   *

   *
   *

   * Note: because blocking is not possible on Scala.js, this method is not available on Scala.js.
   *

   *
   * @throws unreportedException if an exception occurred during the activity represented by this Status that was not reported
   *            via a ScalaTest event and therefore was installed as an unreported exception on this Status.
   */
  def waitUntilCompleted(): Unit
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Registers the passed callback function to be executed when this status completes.
   *
   *

   * If an unreported exception has been installed on this Status, the
   * Try passed into the callback function will be a Failure containing that exception. Otherwise
   * the Try will be a Success containing true if no tests failed
   * or suites aborted during the activity represented by this Status, else false.
   *

   *
   *

   * The callback functions registered with whenCompleted will be executed after the Status
   * has completed, in an undefined order. If the Status has already completed, functions passed to this method will be
   * executed immediately by the calling thread before returning.
   *

   *
   *

   * Any exception thrown by a callback function will be propagated back on the thread used to invoke the callback.
   *

   *
   *

   * Internally ScalaTest uses this method to register callbacks that
   * fire completion events (TestSucceeded, TestFailed,
   * SuiteCompleted, etc.) to the Reporter.
   *

   *
   * @param callback the callback function to execute once this Status has completed
   */
  def whenCompleted(callback: Try[Boolean] => Unit): Unit

  // TODO: We are not yet propagating installed unreported exceptions in thenRun. Write the tests and implement the code.
  /**
   * Registers a Status-producing by-name function to execute after this
   * Status completes, returning a Status that mirrors the Status
   * returned by the by-name.
   *
   *

   * The Status returned by this method will complete when the status produced by the
   * Status produced by the passed-by name completes. The returned Status
   * will complete with the same succeeds and unreportedException values.
   * But unlike the Status produced by the by-name, the returned Status will
   * be available immediately.
   *

   *
   *

   * If the by-name function passed to this method completes abruptly with a non-run-aborting exception,
   * that exception will be caught and installed as the unreportedException on the
   * Status returned by this method. The Status returned by this method
   * will then complete. The thread that attempted to evaluate the by-name function will be allowed
   * to continue (i.e., the non-run-aborting exception will not be rethrown
   * on that thread).
   *

   *
   *

   * If the by-name function passed to this method completes abruptly with a run-aborting exception,
   * such as StackOverflowError, that exception will be caught and a new
   * java.util.concurrent.ExecutionException that contains the run-aborting exception as its
   * cause will be installed as the unreportedException on the
   * Status returned by this method. The Status returned by this method
   * will then complete. The original run-aborting exception will then be rethrown on the
   * thread that attempted to evaluate the by-name function.
   *

   *
   *

   * If an unreported exception is installed on this Status, the passed by-name function will
   * still be executed.
   *

   *
   *

   * Internally, ScalaTest uses this method in async styles to ensure that by default, each subsequent test in an async-style
   * suite begins execution only after the previous test has completed. This method is not used if
   * ParallelTestExection is mixed into an async style. Instead, tests are allowed to begin
   * execution concurrently.
   *

   *
   * @param status A Status-producing by-name function to invoke after this Status has completed.
   * @return a Status  that represents the status of executing the by-name function passed to this method.
   */
  final def thenRun(f: => Status): Status = {
    val returnedStatus = new ScalaTestStatefulStatus
    // Ignore the completion status of this Status, because regardless of whether it
    // represents a failure, we want to for sure run the next Status. For example, if
    // some test fails, we still want to run the next test.
    whenCompleted { _ =>
      try {
        val innerStatus = f
        innerStatus.whenCompleted { tri =>
          tri match {
            case Success(false) =>
              returnedStatus.setFailed()
            case Failure(ex) =>
              returnedStatus.setFailed()
              returnedStatus.setFailedWith(ex)
            case _ =>
          }
          returnedStatus.setCompleted()
        }
      }
      catch {
        case ex: Throwable =>
          if (Suite.anExceptionThatShouldCauseAnAbort(ex)) {
            returnedStatus.setFailedWith(new ExecutionException(ex))
            returnedStatus.setCompleted()
            throw ex
          }
          else {
            returnedStatus.setFailedWith(ex)
            returnedStatus.setCompleted()
          }
      }
    }
    returnedStatus
  }

  /**
   * Converts this Status to a Future[Boolean] where Success(true) means
   * no tests failed and suites aborted, Success(false), means at least one test failed or one
   * suite aborted and any thrown exception was was reported to the Reporter via a ScalaTest
   * event, Failure(unreportedException) means
   * an exception, unreportedException, was thrown that was not reported to the Reporter
   * via a ScalaTest event.
   *
   * @return a Future[Boolean] representing this Status.
   */
  final def toFuture: Future[Boolean] = {
    val promise = Promise[Boolean]
    whenCompleted { t => promise.complete(t) }
    promise.future
  }

  // TODO: Make sure to test what happens when before and after code throw exceptions.
  /**
   * An exception that was thrown during the activity represented by this Status that
   * was not reported via a ScalaTest event fired to the Reporter.
   *
   *

   * When a test executes, "non-run-aborting" thrown exceptions are reported by events
   * fired to the reporter. A TestPendingException is reported via a
   * TestPending event. A TestCanceledException is reported via a
   * TestCanceled event. Any other non-run-aborting exceptions, including
   * TestFailedException will be reported via a
   * TestFailed event.
   *

   *
   *

   * Run-aborting exceptions indicate critical
   * problems, such as OutOfMemoryError, that instead of being reported via a test completion event
   * should instead cause the entire suite to abort. In synchronous testing styles, this exception will be allowed
   * to just propagate up the call stack. But in async styles, the thread or threads executing the test will often
   * be taken from the async suite's execution context. Instead of propagating these run-aborting exceptions up
   * the call stack, they will be installed as an "unreported exception" in the test's Status.
   * They are "unreported" because no test completion event will be fired to report them. For more explanation and
   * a list of run-aborting exception types, see Treatment of java.lang.Errors.
   *

   *
   *

   * Another way for an unreported exception to occur is if an exception of any type is thrown outside of the
   * body of an actual test. For example, traits BeforeAndAfter,  BeforeAndAfterEach,
   * and BeforeAndAfterEachTestData execute code before and after tests. Traits
   * BeforeAndAfterAll and
BeforeAndAfterAllConfigMap execute code before
   * and after all tests and nested suites of a suite. If any "before" or "after"
   * code completes abruptly with an exception (of any type, not just run-aborting types) on a thread taken
   * from an async suite's execution context, this exception will
   * installed as an unreportedException of the relevant Status.
   *

   *
   *

   * In addition, ScalaTest Suite exposes four "run" lifecycle methods--run,
   * runNestedSuites, runTests, and runTest--that users can override to customize
   * the framework. If a "run" lifecycle methods completes abruptly with an exception, that exception occurs outside
   * the context of a test body. As a result, such exceptions will be
   * installed as an unreportedException of the relevant Status.
   *

   *
   *

   * The toFuture method on Status returns a Future[Boolean]. If the Future
   * succeeds with the Boolean value of true, that indicates no tests failed and no suites aborted
   * during the activity represented
   * by this Status. If a test failed or suite aborted, and that event was reported by a fired ScalaTest
   * Event, the
   * Future will succeed with the value false. If an unreported exception has been installed
   * on the Status, however, the Future will fail with that exception.
   *

   *
   * @return a optional unreported Throwable
   */
  def unreportedException: Option[Throwable] = None

  /**
   * Registers a by-name function (producing an optional exception) to execute
   * after this Status completes.
   *
   *

   * If the by-name function passed to this method completes abruptly with a non-run-aborting exception,
   * that exception will be caught and installed as the unreportedException on the
   * Status returned by this method. The Status returned by this method
   * will then complete. The thread that attempted to evaluate the by-name function will be allowed
   * to continue (i.e., the non-run-aborting exception will not be rethrown
   * on that thread).
   *

   *
   *

   * If the by-name function passed to this method completes abruptly with a run-aborting exception,
   * such as StackOverflowError, that exception will be caught and a new
   * java.util.concurrent.ExecutionException that contains the run-aborting exception as its
   * cause will be installed as the unreportedException on the
   * Status returned by this method. The Status returned by this method
   * will then complete. The original run-aborting exception will then be rethrown on the
   * thread that attempted to evaluate the by-name function.
   *

   *
   *

   * If an unreported exception is installed on this Status, the passed by-name function will
   * not be executed. Instead, the same unreported exception will be installed on the Status
   * returned by this method.
   *

   *
   *

   * Internally, ScalaTest uses this method in traits BeforeAndAfter,
   * BeforeAndAfterEach, and BeforeAndAfterEachTestData to ensure "after" code is
   * executed after the relevant test has completed, and in traits BeforeAndAfterAll and
   * BeforeAndAfterAllConfigMap to ensure "after" code is executed after the
   * relevant tests and nested suites have completed.
   *

   *
   * @param f A by-name function to invoke after this Status has completed.
   * @return a Status that represents this Status,
   *         modified by any exception thrown by the passed by-name function.
   */
  final def withAfterEffect(f: => Unit): Status = {
    val returnedStatus = new ScalaTestStatefulStatus
    whenCompleted { tri =>
      tri match {
        case Success(result) =>
          try {
            f
            if (!result) returnedStatus.setFailed()
          }
          catch {
            case ex: Throwable if Suite.anExceptionThatShouldCauseAnAbort(ex) =>
              val execEx = new ExecutionException(ex)
              returnedStatus.setFailedWith(execEx)
              throw ex

            case ex: Throwable => returnedStatus.setFailedWith(ex)
          }
          finally {
            returnedStatus.setCompleted()
          }

        case Failure(originalEx) =>
          try {
            f
            returnedStatus.setFailedWith(originalEx)
          }
          catch {
            case ex: Throwable =>
              returnedStatus.setFailedWith(originalEx)
              println("ScalaTest can't report this exception because another preceded it, so printing its stack trace:")
              ex.printStackTrace()
          }
          finally {
            returnedStatus.setCompleted()
          }
      }
    }
    returnedStatus
  }
}

private[scalatest] object Status {
  def executeQueue(queue: ConcurrentLinkedQueue[Try[Boolean] => Unit], result: Try[Boolean]): Unit = {
    while (!queue.isEmpty) {
      val f = queue.poll
      if (f != null)
        f(result)
    }
  }
}

/**
 * Singleton status that represents an already completed run with no tests failed and no suites aborted.
 *
 *

 * Note: the difference between this SucceededStatus object and the similarly named Succeeded
 * object is that the Succeeded object indicates one test succeeded, whereas this SucceededStatus object indicates the absence
 * of any failed tests or aborted suites during a run. Both are used as the result type of Suite lifecycle methods, but Succeeded
 * is a possible result of withFixture, whereas SucceededStatus is a possible result of run, runNestedSuites,
 * runTests, or runTest. In short, Succeeded is always just about one test, whereas SucceededStatus could be
 * about something larger: multiple tests or an entire suite.
 *

 */
object SucceededStatus extends Status with Serializable {

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Always returns true.
   *
   * @return true
   */
  def succeeds() = true
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Always returns true.
   *
   * @return true
   */
  def isCompleted() = true

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Always returns immediately.
   */
  def waitUntilCompleted(): Unit = {}
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Executes the passed function immediately on the calling thread.
   */
  def whenCompleted(f: Try[Boolean] => Unit): Unit = { f(Success(true)) }
}

/**
 * Singleton status that represents an already completed run with at least one failed test or aborted suite.
 *
 *

 * Note: the difference between this FailedStatus object and the similarly named Failed
 * class is that a Failed instance indicates one test failed, whereas this FailedStatus object indicates either one or more tests failed
 * and/or one or more suites aborted during a run. Both are used as the result type of Suite lifecycle methods, but Failed
 * is a possible result of withFixture, whereas FailedStatus is a possible result of run, runNestedSuites,
 * runTests, or runTest. In short, Failed is always just about one test, whereas FailedStatus could be
 * about something larger: multiple tests or an entire suite.
 *

 */
object FailedStatus extends Status with Serializable {

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Always returns false.
   *
   * @return true
   */
  def succeeds() = false
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Always returns true.
   *
   * @return true
   */
  def isCompleted() = true

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Always returns immediately.
   */
  def waitUntilCompleted(): Unit = {}
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Executes the passed function immediately on the calling thread.
   */
  def whenCompleted(f: Try[Boolean] => Unit): Unit = { f(Success(false)) }
}

// Used internally in ScalaTest. We don't use the StatefulStatus, because
// then user code could pattern match on it and then access the setCompleted
// and setFailed methods. We wouldn't want that.
private[scalatest] final class ScalaTestStatefulStatus extends Status with Serializable {

  // Safely published
  @transient private final val latch = new CountDownLatch(1)

  // protected by synchronized blocks
  private var succeeded = true

  // Safely published
  private final val queue = new ConcurrentLinkedQueue[Try[Boolean] => Unit]

  // protected by synchronized blocks
  private var asyncException: Option[Throwable] = None

  // Safely published
  private final val setCompletedMutex: AnyRef = new AnyRef with Serializable

  override def unreportedException: Option[Throwable] = {
    synchronized {
      asyncException
    }
  }

  // SKIP-SCALATESTJS,NATIVE-START
  def succeeds() = {
    waitUntilCompleted()
    synchronized { succeeded }
  }
  // SKIP-SCALATESTJS,NATIVE-END

  def isCompleted() = latch.getCount == 0L

  // SKIP-SCALATESTJS,NATIVE-START
  def waitUntilCompleted(): Unit = {
    latch.await()
    unreportedException match {
      case Some(ue) => throw ue
      case None => // Do nothing
    }
  }
  // SKIP-SCALATESTJS,NATIVE-END

  def setFailed(): Unit = {
    synchronized {
      if (isCompleted())
        throw new IllegalStateException("status is already completed")
      succeeded = false
    }
  }

  /**
   * Sets the status to failed with an unreported exception, without changing the completion status.
   *
   *

   * This method may be invoked repeatedly, even though invoking it once is sufficient to set the state of the Status to failed, but only
   * up until setCompleted has been called. Once setCompleted has been called, invoking this method will result in a
   * thrown IllegalStateException. Also, only the first exception passed will be reported as the unreported exception. Any exceptions
   * passed via subsequent invocations of setFailedWith after the first will have their stack traces printed to standard output.
   *

   *
   * @throws IllegalStateException if this method is invoked on this instance after setCompleted has been invoked on this instance.
   * @param ex an unreported exception
   */
  def setFailedWith(ex: Throwable): Unit = {
    synchronized {
      if (isCompleted())
        throw new IllegalStateException("status is already completed")
      succeeded = false
      if (asyncException.isEmpty)
        asyncException = Some(ex)
      else {
        println("ScalaTest can't report this exception because another preceded it, so printing its stack trace:")
        ex.printStackTrace()
      }
    }
  }

  def setCompleted(): Unit = {

    val tri: Try[Boolean] =
      unreportedException match {
        case Some(ex) => Failure(ex)
        case None => Success(succeeded)
      }

    // If setCompleted is called twice by two different threads concurrently, ensure
    // one will execute all the callbacks in order before letting the second one proceed
    // rather than allowing both to race through the queue concurrently.
    setCompletedMutex.synchronized {
      Status.executeQueue(queue, tri)

      // Synchronize this latch count down so that it is serialized with the code
      // in whenCompleted that checks the status of the latch by calling isCompleted,
      // then either adds to the queue or sets executeLocally to true:
      //
      // val executeLocally =
      //   synchronized {
      //     if (!isCompleted()) {
      //       queue.add(f)
      //       false
      //     }
      //     else true
      //   }
      //
      // This way either one or the other will go first. If this method goes first, then isCompleted will return false,
      // and the callback will be executed locally. If the whenCompleted method goes first, then isCompleted will
      // return false and the callback will be added to the queue. Once whenCompleted executes past the end of its
      // synchronized block, this method will count down the latch, and the next line will execute the callback
      // that was added. This way no callbacks should ever be lost.
      synchronized { latch.countDown() }

      // Execute any callbacks that were registered by whenCompleted after executeQueue above finishes, but
      // before the latch was counted down.
      Status.executeQueue(queue, tri)
    }
  }

  def whenCompleted(f: Try[Boolean] => Unit): Unit = {
    // This synchronized block serializes this method's check of the latch via
    // the isCompleted method, followed by a potential queue insertion, with
    // the count down of the latch in the setCompleted method. This ensures no
    // callback is lost. It will either be executed later by the setCompleted method
    // or now by this method.
    val executeLocally =
      synchronized {
        if (!isCompleted()) {
          queue.add(f)
          false
        }
        else true
      }
    if (executeLocally) {
      val tri: Try[Boolean] =
        unreportedException match {
          case Some(ex) => Failure(ex)
          case None => Success(succeeded)
        }
      f(tri)
    }
  }
}

/**
 * Status implementation that can change its state over time.
 *
 *

 * A StatefulStatus begins its life in a successful state, and will remain successful unless setFailed is called.
 * Once setFailed is called, the status will remain at failed. The setFailed method can be called multiple times (even
 * though invoking it once is sufficient to permanently set the status to failed), but only up until setCompleted has been called.
 * After setCompleted has been called, any invocation of setFailed will be greeted with an IllegalStateException.
 *

 *
 *

 * Instances of this class are thread safe.
 *

 */
final class StatefulStatus extends Status with Serializable {
  // Safely published
  @transient private final val latch = new CountDownLatch(1)

  // protected by synchronized blocks
  private var succeeded = true

  // Safely published
  private final val queue = new ConcurrentLinkedQueue[Try[Boolean] => Unit]

  // protected by synchronized blocks
  private var asyncException: Option[Throwable] = None

  // Safely published
  private final val setCompletedMutex: AnyRef = new AnyRef with Serializable

  override def unreportedException: Option[Throwable] = {
    synchronized {
      asyncException
    }
  }

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that waits until completion, as indicated by an invocation of setCompleted on this instance, then returns false
   * if setFailed was called on this instance, else returns true.
   *
   * @return true if no tests failed and no suites aborted, false otherwise
   */
  def succeeds() = {
    waitUntilCompleted()
    synchronized { succeeded }
  }
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Non-blocking call that returns true if setCompleted has been invoked on this instance, false otherwise.
   *
   * @return true if the test or suite run is already completed, false otherwise.
   */
  def isCompleted() = latch.getCount == 0L

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that returns only after setCompleted has been invoked on this StatefulStatus instance.
   */
  def waitUntilCompleted(): Unit = {
    latch.await()
    unreportedException match {
      case Some(ue) => throw ue
      case None => // Do nothing
    }
  }
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Sets the status to failed without changing the completion status.
   *
   *

   * This method may be invoked repeatedly, even though invoking it once is sufficient to set the state of the Status to failed, but only
   * up until setCompleted has been called. Once setCompleted has been called, invoking this method will result in a
   * thrown IllegalStateException.
   *

   *
   * @throws IllegalStateException if this method is invoked on this instance after setCompleted has been invoked on this instance.
   */
  def setFailed(): Unit = {
    synchronized {
      if (isCompleted())
        throw new IllegalStateException("status is already completed")
      succeeded = false
    }
  }

  /**
   * Sets the status to failed with an unreported exception, without changing the completion status.
   *
   *

   * This method may be invoked repeatedly, even though invoking it once is sufficient to set the state of the Status to failed, but only
   * up until setCompleted has been called. Once setCompleted has been called, invoking this method will result in a
   * thrown IllegalStateException. Also, only the first exception passed will be reported as the unreported exception. Any exceptions
   * passed via subsequent invocations of setFailedWith after the first will have their stack traces printed to standard output.
   *

   *
   * @throws IllegalStateException if this method is invoked on this instance after setCompleted has been invoked on this instance.
   * @param ex an unreported exception
   */
  def setFailedWith(ex: Throwable): Unit = {
    synchronized {
      if (isCompleted())
        throw new IllegalStateException("status is already completed")
      succeeded = false
      if (asyncException.isEmpty)
        asyncException = Some(ex)
      else {
        println("ScalaTest can't report this exception because another preceded it, so printing its stack trace:")
        ex.printStackTrace()
      }
    }
  }

  /**
   * Sets the status to completed.
   *
   *

   * This method may be invoked repeatedly, even though invoking it once is sufficient to set the state of the Status to completed.
   *

   *
   *

   * This method invokes any callbacks that have been registered with whenCompleted using the thread that invoked
   * this method prior to declaring this status as completed. This method then executes any callbacks that were registered between
   * thie time this method decided it was done executing previously registered callbacks and the time it declared this status as
   * completed. This second pass ensures no callbacks are lost. Any subsequent callbacks registered with whenCompleted
   * will be executed using the thread that invoked whenCompleted.
   *

   */
  def setCompleted(): Unit = {

    val tri: Try[Boolean] =
      unreportedException match {
        case Some(ex) => Failure(ex)
        case None => Success(succeeded)
      }

    // If setCompleted is called twice by two different threads concurrently, ensure
    // one will execute all the callbacks in order before letting the second one proceed
    // rather than allowing both to race through the queue concurrently.
    setCompletedMutex.synchronized {
      Status.executeQueue(queue, tri)

      // Synchronize this latch count down so that it is serialized with the code
      // in whenCompleted that checks the status of the latch by calling isCompleted,
      // then either adds to the queue or sets executeLocally to true:
      //
      // val executeLocally =
      //   synchronized {
      //     if (!isCompleted()) {
      //       queue.add(f)
      //       false
      //     }
      //     else true
      //   }
      //
      // This way either one or the other will go first. If this method goes first, then isCompleted will return false,
      // and the callback will be executed locally. If the whenCompleted method goes first, then isCompleted will
      // return false and the callback will be added to the queue. Once whenCompleted executes past the end of its
      // synchronized block, this method will count down the latch, and the next line will execute the callback
      // that was added. This way no callbacks should ever be lost.
      synchronized { latch.countDown() }

      // Execute any callbacks that were registered by whenCompleted after executeQueue above finishes, but
      // before the latch was counted down.
      Status.executeQueue(queue, tri)
    }
  }

  /**
   * Registers the passed function to be executed when this status completes.
   *
   *

   * You may register multiple functions, which on completion will be executed in an undefined
   * order.
   *

   */
  def whenCompleted(f: Try[Boolean] => Unit): Unit = {
    // This synchronized block serializes this method's check of the latch via
    // the isCompleted method, followed by a potential queue insertion, with
    // the count down of the latch in the setCompleted method. This ensures no
    // callback is lost. It will either be executed later by the setCompleted method
    // or now by this method.
    val executeLocally =
      synchronized {
        if (!isCompleted()) {
          queue.add(f)
          false
        }
        else true
      }
    if (executeLocally) {
      val tri: Try[Boolean] =
        unreportedException match {
          case Some(ex) => Failure(ex)
          case None => Success(succeeded)
        }
      f(tri)
    }
  }
}

import java.util.concurrent.atomic.AtomicReference

/**
 * Composite Status that aggregates its completion and failed states of set of other Statuses passed to its constructor.
 *
 * @param statuses the Statuses out of which this status is composed.
 */
final class CompositeStatus(statuses: Set[Status]) extends Status with Serializable {

  import CompositeStatus._

  // Before you can use the AtomicReference or ConcurrentLinkedQueue, you must acquire
  // the lock on this mutex. You need not acquire it to use the CountDownLatch or the
  // statuses passed to the constructor.
  private final val mutex: AnyRef = new AnyRef

  // You must acquire the mutex to use this queue.
  private final val queue: ConcurrentLinkedQueue[Try[Boolean] => Unit] = new ConcurrentLinkedQueue[Try[Boolean] => Unit]

  // When this latch reaches zero, that means this Status has completed. You need
  // not acquire the mutex to look at the latch.
  private final val latch: CountDownLatch = new CountDownLatch(statuses.size)

  // You must acquire the mutex to use this atomic reference.
  // The asyncException contained in this bundle is set possibly by the whenCompleted function
  // registered on all the inner statuses. If any of them are Failures, then the first one to
  // fail goes in as this Composite's unreported exception. Any subsequent exceptions are just printed
  // to the standard output.  Then if it is the last inner status to complete, that unreported
  // exception is passed to the callback functions registered with this composite status.
  private final val bundleRef: AtomicReference[Bundle] =
    new AtomicReference(
      Bundle(
        succeeded = true,
        asyncException = None
      )
    )

  // The this reference cannot escape during construction, because the this reference is not passed
  // to the initializeBundle method.
  intializeBundle(statuses, mutex, queue, latch, bundleRef)

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that waits until all composite Statuses have completed, then returns
   * true only if all of the composite Statuses succeeded. If any Status
   * passed in the statuses set fails, this method will return false.
   *
   * @return true if all composite Statuses succeed, false otherwise.
   */
  def succeeds(): Boolean = {
    latch.await()
    statuses.forall(_.succeeds())
  }
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Non-blocking call to check if the test or suite run is completed, returns true if all composite Statuses have completed,
   * false otherwise.  You can use this to poll the run status.
   *
   * @return true if all composite Statuses have completed, false otherwise.
   */
  def isCompleted(): Boolean = latch.getCount == 0
  // Note, the previous implementation did this, grabbing statuses within a synchronized block, which makes no sense:
  // statuses.forall(_.isCompleted())
  // I think that was a fuzzy design if not a buggy one. In this implementation, the latch is the ultimate arbiter
  // of whether the status has completed.

  // SKIP-SCALATESTJS,NATIVE-START
  /**
   * Blocking call that returns only after all composite Statuss have completed.
   */
  def waitUntilCompleted(): Unit = latch.await()
  // SKIP-SCALATESTJS,NATIVE-END

  /**
   * Registers the passed function to be executed when this status completes.
   *
   *

   * You may register multiple functions, which on completion will be executed in an undefined
   * order.
   *

   */
  def whenCompleted(f: Try[Boolean] => Unit): Unit = {
    val executeLocally =
      mutex.synchronized {
        // Check the latch (by calling isCompleted) inside a mutex.synchronized to prevent
        // a race condition between this decision to either 1) add the callback, f, to the queue
        // or 2) execute it locally, with the execution of the final callback registered with the
        // nested statuses that will execute the callbacks in the queue.
        if (!isCompleted()) {
          queue.add(f)
          false
        }
        else true
      }
    if (executeLocally) {
      // Once this status is completed, the asyncException in the Bundle, if any, is the exception
      // to be passed to the callback f. Note: StatefulStatus (and ScalaTestStatefulStatus) can
      // fail without an exception via the setFailed method that takes no parameters. This supports
      // tests that do not use exceptions to determine success or failure.
      val bundle = bundleRef.get
      val tri: Try[Boolean] =
        bundle.asyncException match {
          case Some(ex) => Failure(ex)
          case None => Success(bundle.succeeded)
        }
      f(tri)
    }
  }

  /**
   * An optional exception that has not been reported to the reporter for this run.
   *
   *

   * This will be defined if any of the composite Statuss (passed to this Status's
   * constructor) has a defined unreportedException. If more than one composite Status
   * has a defined unreportedException, one of them (not specified) will be reported by this method
   * and the others will have their stack traces printed to standard output.
   *

   */
  override def unreportedException: Option[Throwable] = {
    mutex.synchronized {
      val bundle = bundleRef.get
      if (bundle.asyncException.isDefined) bundle.asyncException
      else {
        val optStatusWithUnrepEx = statuses.find(_.unreportedException.isDefined)
        for {
          status <- optStatusWithUnrepEx
          unrepEx <- status.unreportedException
        } yield unrepEx
      }
    }
  }
}

private[scalatest] object CompositeStatus {

  case class Bundle(
    succeeded: Boolean,
    asyncException: Option[Throwable]
  )

  // The asyncException is set possibly by the whenCompleted function registered on all the
  // inner statuses. If any of them are Failures, then that first one goes in
  // as this Composite's unreported exception. Any subsequent ones are just printed.
  // Then if it is the last inner status to complete, that unreported exception is passed
  // to the callback functions registered with this composite status.
  def intializeBundle(
    statuses: Set[Status],
    mutex: AnyRef,
    queue: ConcurrentLinkedQueue[Try[Boolean] => Unit],
    latch: CountDownLatch,
    bundleRef: AtomicReference[Bundle]
  ): Unit = {

    for (status <- statuses) {
      status.whenCompleted { tri =>
        mutex.synchronized {
          val bundle = bundleRef.get
          val (newSucceeded, newAsyncException) =
            tri match {
              case Success(res) =>
                // Set succeeded to false if it either is already false or res is false.
                // Given this tri is a Success, there's no new exception to deal with, so
                // just keep the existing Option[Throwable] in place as the asyncException.
                (bundle.succeeded && res, bundle.asyncException)
              case Failure(ex) =>
                // Given it is a failure, set succeeded to false (it may already be false, but
                // it doesn't matter.
                if (bundle.asyncException.isEmpty)
                  // Given there's no asyncException currently in the bundle, add it.
                  (false, Some(ex))
                else {
                  // Given there's already an asyncException in the bundle, just print this one
                  // and keep the "winner" exception nit he bundle.
                  println("ScalaTest can't report this exception because another preceded it, so printing its stack trace:")
                  ex.printStackTrace()
                  (false, bundle.asyncException)
                }
            }
          bundleRef.set(Bundle(newSucceeded, newAsyncException))

          if (latch.getCount == 1) {

            // Because the latch is at 1, once we count it down the status will be completed.
            // First execute the queue. We're doing this in the mutex.synchronized to mostly
            // serialize async activities. This status will not be observed to complete until
            // any callbacks in the queue are drained.
            val completionTri: Try[Boolean] =
              newAsyncException match {
                case Some(ex) => Failure(ex)
                case None => Success(newSucceeded)
              }

            import Status.executeQueue

            // This will execute all callbacks currently in the queue. Because this is done in
            // the mutex.synchronized, no others can be added until after we countdown the
            // latch to zero. If a thread is currently blocked waiting to acquire the mutex
            // in the whenCompleted method, it will observe the status as completed and
            // therefore execute that callback locally.
            executeQueue(queue, completionTri)
          }

          // Once this latch counts down to zero, other threads will see it because we don't synchronize
          // on the mutex to look at the latch in CompositeStatus's methods.
          latch.countDown()
        }
      }
    }
  }
}


text:
import React from 'react';
import {Flex as Flex_} from 'antd-mobile';
import {FlexProps} from './PropsType';

export default class Flex extends React.Component<FlexProps, any> {
  static Item: any;
  static defaultProps = {
    prefixCls: 'yy-flexbox',
  };

  render() {
    return <Flex_ {...this.props} />;
  }
}

redpajama_set_name: RedPajamaGithub


text:
Package.describe({
  name: 'angular-templates',
  summary: 'Compile angular templates into the template cache',
  version: '1.0.9',
  git: 'https://github.com/Urigo/angular-meteor.git',
  documentation: 'README.md'
});

Package.registerBuildPlugin({
  name: 'compileNGTemplate',
  sources: [
    'plugin.js'
  ],
  use: [
    'urigo:static-html-compiler@0.1.8',
    'ecmascript@0.2.0'
  ]
});

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.2.0.1');
  api.use('isobuild:compiler-plugin@1.0.0');
  api.use('angular-meteor-data@1.3.9', 'client', { weak: true });
  api.use('angular:angular@1.4.8', 'client', { weak: true });

  api.addFiles('templates-handler.js', 'client');
});


text:
package gov.nih.nci.clinicalconnector.dao;

public interface HotLinkDAO {

	public String createTransaction(String userName, String password, String study, String patientPosition, String patientId);

}


text:
<bill session="115" type="h" number="1126" updated="2017-06-19T21:00:10Z">
  <state datetime="2017-02-16">REFERRED</state>
  <status>
    <introduced datetime="2017-02-16"/>
  </status>
  <introduced datetime="2017-02-16"/>
  <titles>
    <title type="short" as="introduced">Aged Distilled Spirits Competitiveness Act</title>
    <title type="short" as="introduced">Aged Distilled Spirits Competitiveness Act</title>
    <title type="official" as="introduced">To exempt the aging process of distilled spirits from the production period for purposes of capitalization of interest costs.</title>
    <title type="display">Aged Distilled Spirits Competitiveness Act</title>
  </titles>
  <sponsor bioguide_id="B001282"/>
  <cosponsors>
    <cosponsor bioguide_id="C001108" joined="2017-02-16"/>
    <cosponsor bioguide_id="G000558" joined="2017-02-16"/>
    <cosponsor bioguide_id="M001184" joined="2017-02-16"/>
    <cosponsor bioguide_id="R000395" joined="2017-02-16"/>
    <cosponsor bioguide_id="Y000062" joined="2017-02-27"/>
  </cosponsors>
  <actions>
    <action datetime="2017-02-16">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-02-16" state="REFERRED">
      <text>Referred to the House Committee on Ways and Means.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSWM" name="House Ways and Means" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="unknown" number="747"/>
    <bill type="s" session="115" relation="unknown" number="429"/>
  </relatedbills>
  <subjects>
    <term name="Taxation"/>
    <term name="Alcoholic beverages"/>
    <term name="Business investment and capital"/>
    <term name="Income tax deductions"/>
    <term name="Interest, dividends, interest rates"/>
  </subjects>
  <amendments/>
  <summary date="2017-02-16T05:00:00Z" status="Introduced in House">Aged Distilled Spirits Competitiveness Act

This bill amends the Internal Revenue Code to exclude the aging period from the production period for distilled spirits that are fit to be used as a beverage, for purposes of determining whether a taxpayer can expense, rather than capitalize, interest costs paid or incurred during the production period.</summary>
  <committee-reports/>
</bill>


text:
<?php

declare(strict_types=1);

namespace StructType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for DeletedOccurrenceInfoType StructType
 * @package Ews
 * @subpackage Structs
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsDeletedOccurrenceInfoType extends AbstractStructBase
{
    /**
     * The Start
     * @var string|null
     */
    protected ?string $Start = null;
    /**
     * Constructor method for DeletedOccurrenceInfoType
     * @uses EwsDeletedOccurrenceInfoType::setStart()
     * @param string $start
     */
    public function __construct(?string $start = null)
    {
        $this
            ->setStart($start);
    }
    /**
     * Get Start value
     * @return string|null
     */
    public function getStart(): ?string
    {
        return $this->Start;
    }
    /**
     * Set Start value
     * @param string $start
     * @return \StructType\EwsDeletedOccurrenceInfoType
     */
    public function setStart(?string $start = null): self
    {
        // validation for constraint: string
        if (!is_null($start) && !is_string($start)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($start, true), gettype($start)), __LINE__);
        }
        $this->Start = $start;

        return $this;
    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.7.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 */
package backtype.storm.generated;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift7.TEnum;

public enum TopologyInitialStatus implements org.apache.thrift7.TEnum {
  ACTIVE(1),
  INACTIVE(2);

  private final int value;

  private TopologyInitialStatus(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static TopologyInitialStatus findByValue(int value) {
    switch (value) {
      case 1:
        return ACTIVE;
      case 2:
        return INACTIVE;
      default:
        return null;
    }
  }
}


text:
package tbax.baxshops;

import org.bukkit.inventory.ItemStack;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;

/**
 * A ShopSelection represents a user's selected shop.
 * Shops are selected by right- or left-clicking on them in-game.
 */
public final class ShopSelection
{
    /**
     * The selected shop
     */
    private BaxShop shop;

    /**
     * The displayed inventory page number
     */
    private int page = 0;

    /**
     * Whether the player who selected this shop owns it
     */
    private boolean owner;

    private Location location;

    public ShopSelection()
    {
    }

    public void setLocation(Location value)
    {
        location = value;
    }

    public Location getLocation()
    {
        return location;
    }

    public boolean isOwner()
    {
        return owner;
    }

    public void setIsOwner(boolean value)
    {
        owner = value;
    }

    public void setShop(BaxShop value)
    {
        shop = value;
    }

    public BaxShop getShop()
    {
        return shop;
    }

    public void setPage(int value)
    {
        page = value;
    }

    public int getPage()
    {
        return page;
    }

    public void showListing(CommandSender sender)
    {
        int pages = shop.getPages();
        if (pages == 0) {
            sender.sendMessage(Format.header("Empty"));
            sender.sendMessage("");
            sender.sendMessage("This shop has no items");
            int stop = BaxShop.ITEMS_PER_PAGE - 2;
            if (owner) {
                sender.sendMessage("Use /shop add to add items");
                stop--;
            }
            for (int i = 0; i < stop; ++i) {
                sender.sendMessage("");
            }
            return;
        }
        sender.sendMessage(Format.header(String.format("Showing page %d of %d", page + 1, pages)));
        int i = page * BaxShop.ITEMS_PER_PAGE,
                stop = (page + 1) * BaxShop.ITEMS_PER_PAGE,
                max = Math.min(stop, shop.size());
        for (; i < max; i++) {
            sender.sendMessage(shop.getEntry(i).toString(i + 1, shop.hasFlagInfinite()));
        }
        for (; i < stop; i++) {
            sender.sendMessage("");
        }
    }

    public ItemStack toItem()
    {
        return shop.toItem(location);
    }
}


text:
namespace message_network {

// Internal implementation detail -- do not call these.
void  protobuf_AddDesc_message_5fnetwork_2eproto();
void protobuf_AssignDesc_message_5fnetwork_2eproto();
void protobuf_ShutdownFile_message_5fnetwork_2eproto();

class ScanVirusInfo;

enum ScanVirusInfo_ScanStatusType {
  ScanVirusInfo_ScanStatusType_REGISTER = 1,
  ScanVirusInfo_ScanStatusType_SCAN = 2,
  ScanVirusInfo_ScanStatusType_CLOSE_CONNECTION = 3,
  ScanVirusInfo_ScanStatusType_REGISTER_SUCCESS = 4,
  ScanVirusInfo_ScanStatusType_REGISTER_UNSUCCESS = 5,
  ScanVirusInfo_ScanStatusType_SCAN_SUCCESS = 6,
  ScanVirusInfo_ScanStatusType_SCAN_UNSUCCESS = 7,
  ScanVirusInfo_ScanStatusType_RESULT = 8
};
bool ScanVirusInfo_ScanStatusType_IsValid(int value);
const ScanVirusInfo_ScanStatusType ScanVirusInfo_ScanStatusType_ScanStatusType_MIN = ScanVirusInfo_ScanStatusType_REGISTER;
const ScanVirusInfo_ScanStatusType ScanVirusInfo_ScanStatusType_ScanStatusType_MAX = ScanVirusInfo_ScanStatusType_RESULT;
const int ScanVirusInfo_ScanStatusType_ScanStatusType_ARRAYSIZE = ScanVirusInfo_ScanStatusType_ScanStatusType_MAX + 1;

const ::google::protobuf::EnumDescriptor* ScanVirusInfo_ScanStatusType_descriptor();
inline const ::std::string& ScanVirusInfo_ScanStatusType_Name(ScanVirusInfo_ScanStatusType value) {
  return ::google::protobuf::internal::NameOfEnum(
    ScanVirusInfo_ScanStatusType_descriptor(), value);
}
inline bool ScanVirusInfo_ScanStatusType_Parse(
    const ::std::string& name, ScanVirusInfo_ScanStatusType* value) {
  return ::google::protobuf::internal::ParseNamedEnum<ScanVirusInfo_ScanStatusType>(
    ScanVirusInfo_ScanStatusType_descriptor(), name, value);
}
// ===================================================================

class ScanVirusInfo : public ::google::protobuf::Message {
 public:
  ScanVirusInfo();
  virtual ~ScanVirusInfo();

  ScanVirusInfo(const ScanVirusInfo& from);

  inline ScanVirusInfo& operator=(const ScanVirusInfo& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const ScanVirusInfo& default_instance();

  void Swap(ScanVirusInfo* other);

  // implements Message ----------------------------------------------

  ScanVirusInfo* New() const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const ScanVirusInfo& from);
  void MergeFrom(const ScanVirusInfo& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  public:

  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  typedef ScanVirusInfo_ScanStatusType ScanStatusType;
  static const ScanStatusType REGISTER = ScanVirusInfo_ScanStatusType_REGISTER;
  static const ScanStatusType SCAN = ScanVirusInfo_ScanStatusType_SCAN;
  static const ScanStatusType CLOSE_CONNECTION = ScanVirusInfo_ScanStatusType_CLOSE_CONNECTION;
  static const ScanStatusType REGISTER_SUCCESS = ScanVirusInfo_ScanStatusType_REGISTER_SUCCESS;
  static const ScanStatusType REGISTER_UNSUCCESS = ScanVirusInfo_ScanStatusType_REGISTER_UNSUCCESS;
  static const ScanStatusType SCAN_SUCCESS = ScanVirusInfo_ScanStatusType_SCAN_SUCCESS;
  static const ScanStatusType SCAN_UNSUCCESS = ScanVirusInfo_ScanStatusType_SCAN_UNSUCCESS;
  static const ScanStatusType RESULT = ScanVirusInfo_ScanStatusType_RESULT;
  static inline bool ScanStatusType_IsValid(int value) {
    return ScanVirusInfo_ScanStatusType_IsValid(value);
  }
  static const ScanStatusType ScanStatusType_MIN =
    ScanVirusInfo_ScanStatusType_ScanStatusType_MIN;
  static const ScanStatusType ScanStatusType_MAX =
    ScanVirusInfo_ScanStatusType_ScanStatusType_MAX;
  static const int ScanStatusType_ARRAYSIZE =
    ScanVirusInfo_ScanStatusType_ScanStatusType_ARRAYSIZE;
  static inline const ::google::protobuf::EnumDescriptor*
  ScanStatusType_descriptor() {
    return ScanVirusInfo_ScanStatusType_descriptor();
  }
  static inline const ::std::string& ScanStatusType_Name(ScanStatusType value) {
    return ScanVirusInfo_ScanStatusType_Name(value);
  }
  static inline bool ScanStatusType_Parse(const ::std::string& name,
      ScanStatusType* value) {
    return ScanVirusInfo_ScanStatusType_Parse(name, value);
  }

  // accessors -------------------------------------------------------

  // required bytes ip = 1;
  inline bool has_ip() const;
  inline void clear_ip();
  static const int kIpFieldNumber = 1;
  inline const ::std::string& ip() const;
  inline void set_ip(const ::std::string& value);
  inline void set_ip(const char* value);
  inline void set_ip(const void* value, size_t size);
  inline ::std::string* mutable_ip();
  inline ::std::string* release_ip();
  inline void set_allocated_ip(::std::string* ip);

  // required bytes uuid = 2;
  inline bool has_uuid() const;
  inline void clear_uuid();
  static const int kUuidFieldNumber = 2;
  inline const ::std::string& uuid() const;
  inline void set_uuid(const ::std::string& value);
  inline void set_uuid(const char* value);
  inline void set_uuid(const void* value, size_t size);
  inline ::std::string* mutable_uuid();
  inline ::std::string* release_uuid();
  inline void set_allocated_uuid(::std::string* uuid);

  // required bytes mac_addr = 3;
  inline bool has_mac_addr() const;
  inline void clear_mac_addr();
  static const int kMacAddrFieldNumber = 3;
  inline const ::std::string& mac_addr() const;
  inline void set_mac_addr(const ::std::string& value);
  inline void set_mac_addr(const char* value);
  inline void set_mac_addr(const void* value, size_t size);
  inline ::std::string* mutable_mac_addr();
  inline ::std::string* release_mac_addr();
  inline void set_allocated_mac_addr(::std::string* mac_addr);

  // optional .message_network.ScanVirusInfo.ScanStatusType scan_status = 4;
  inline bool has_scan_status() const;
  inline void clear_scan_status();
  static const int kScanStatusFieldNumber = 4;
  inline ::message_network::ScanVirusInfo_ScanStatusType scan_status() const;
  inline void set_scan_status(::message_network::ScanVirusInfo_ScanStatusType value);

  // @@protoc_insertion_point(class_scope:message_network.ScanVirusInfo)
 private:
  inline void set_has_ip();
  inline void clear_has_ip();
  inline void set_has_uuid();
  inline void clear_has_uuid();
  inline void set_has_mac_addr();
  inline void clear_has_mac_addr();
  inline void set_has_scan_status();
  inline void clear_has_scan_status();

  ::google::protobuf::UnknownFieldSet _unknown_fields_;

  ::std::string* ip_;
  ::std::string* uuid_;
  ::std::string* mac_addr_;
  int scan_status_;

  mutable int _cached_size_;
  ::google::protobuf::uint32 _has_bits_[(4 + 31) / 32];

  friend void  protobuf_AddDesc_message_5fnetwork_2eproto();
  friend void protobuf_AssignDesc_message_5fnetwork_2eproto();
  friend void protobuf_ShutdownFile_message_5fnetwork_2eproto();

  void InitAsDefaultInstance();
  static ScanVirusInfo* default_instance_;
};
// ===================================================================

// ===================================================================

// ScanVirusInfo

// required bytes ip = 1;
inline bool ScanVirusInfo::has_ip() const {
  return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void ScanVirusInfo::set_has_ip() {
  _has_bits_[0] |= 0x00000001u;
}
inline void ScanVirusInfo::clear_has_ip() {
  _has_bits_[0] &= ~0x00000001u;
}
inline void ScanVirusInfo::clear_ip() {
  if (ip_ != &::google::protobuf::internal::kEmptyString) {
    ip_->clear();
  }
  clear_has_ip();
}
inline const ::std::string& ScanVirusInfo::ip() const {
  return *ip_;
}
inline void ScanVirusInfo::set_ip(const ::std::string& value) {
  set_has_ip();
  if (ip_ == &::google::protobuf::internal::kEmptyString) {
    ip_ = new ::std::string;
  }
  ip_->assign(value);
}
inline void ScanVirusInfo::set_ip(const char* value) {
  set_has_ip();
  if (ip_ == &::google::protobuf::internal::kEmptyString) {
    ip_ = new ::std::string;
  }
  ip_->assign(value);
}
inline void ScanVirusInfo::set_ip(const void* value, size_t size) {
  set_has_ip();
  if (ip_ == &::google::protobuf::internal::kEmptyString) {
    ip_ = new ::std::string;
  }
  ip_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* ScanVirusInfo::mutable_ip() {
  set_has_ip();
  if (ip_ == &::google::protobuf::internal::kEmptyString) {
    ip_ = new ::std::string;
  }
  return ip_;
}
inline ::std::string* ScanVirusInfo::release_ip() {
  clear_has_ip();
  if (ip_ == &::google::protobuf::internal::kEmptyString) {
    return NULL;
  } else {
    ::std::string* temp = ip_;
    ip_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
    return temp;
  }
}
inline void ScanVirusInfo::set_allocated_ip(::std::string* ip) {
  if (ip_ != &::google::protobuf::internal::kEmptyString) {
    delete ip_;
  }
  if (ip) {
    set_has_ip();
    ip_ = ip;
  } else {
    clear_has_ip();
    ip_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
  }
}

// required bytes uuid = 2;
inline bool ScanVirusInfo::has_uuid() const {
  return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void ScanVirusInfo::set_has_uuid() {
  _has_bits_[0] |= 0x00000002u;
}
inline void ScanVirusInfo::clear_has_uuid() {
  _has_bits_[0] &= ~0x00000002u;
}
inline void ScanVirusInfo::clear_uuid() {
  if (uuid_ != &::google::protobuf::internal::kEmptyString) {
    uuid_->clear();
  }
  clear_has_uuid();
}
inline const ::std::string& ScanVirusInfo::uuid() const {
  return *uuid_;
}
inline void ScanVirusInfo::set_uuid(const ::std::string& value) {
  set_has_uuid();
  if (uuid_ == &::google::protobuf::internal::kEmptyString) {
    uuid_ = new ::std::string;
  }
  uuid_->assign(value);
}
inline void ScanVirusInfo::set_uuid(const char* value) {
  set_has_uuid();
  if (uuid_ == &::google::protobuf::internal::kEmptyString) {
    uuid_ = new ::std::string;
  }
  uuid_->assign(value);
}
inline void ScanVirusInfo::set_uuid(const void* value, size_t size) {
  set_has_uuid();
  if (uuid_ == &::google::protobuf::internal::kEmptyString) {
    uuid_ = new ::std::string;
  }
  uuid_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* ScanVirusInfo::mutable_uuid() {
  set_has_uuid();
  if (uuid_ == &::google::protobuf::internal::kEmptyString) {
    uuid_ = new ::std::string;
  }
  return uuid_;
}
inline ::std::string* ScanVirusInfo::release_uuid() {
  clear_has_uuid();
  if (uuid_ == &::google::protobuf::internal::kEmptyString) {
    return NULL;
  } else {
    ::std::string* temp = uuid_;
    uuid_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
    return temp;
  }
}
inline void ScanVirusInfo::set_allocated_uuid(::std::string* uuid) {
  if (uuid_ != &::google::protobuf::internal::kEmptyString) {
    delete uuid_;
  }
  if (uuid) {
    set_has_uuid();
    uuid_ = uuid;
  } else {
    clear_has_uuid();
    uuid_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
  }
}

// required bytes mac_addr = 3;
inline bool ScanVirusInfo::has_mac_addr() const {
  return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void ScanVirusInfo::set_has_mac_addr() {
  _has_bits_[0] |= 0x00000004u;
}
inline void ScanVirusInfo::clear_has_mac_addr() {
  _has_bits_[0] &= ~0x00000004u;
}
inline void ScanVirusInfo::clear_mac_addr() {
  if (mac_addr_ != &::google::protobuf::internal::kEmptyString) {
    mac_addr_->clear();
  }
  clear_has_mac_addr();
}
inline const ::std::string& ScanVirusInfo::mac_addr() const {
  return *mac_addr_;
}
inline void ScanVirusInfo::set_mac_addr(const ::std::string& value) {
  set_has_mac_addr();
  if (mac_addr_ == &::google::protobuf::internal::kEmptyString) {
    mac_addr_ = new ::std::string;
  }
  mac_addr_->assign(value);
}
inline void ScanVirusInfo::set_mac_addr(const char* value) {
  set_has_mac_addr();
  if (mac_addr_ == &::google::protobuf::internal::kEmptyString) {
    mac_addr_ = new ::std::string;
  }
  mac_addr_->assign(value);
}
inline void ScanVirusInfo::set_mac_addr(const void* value, size_t size) {
  set_has_mac_addr();
  if (mac_addr_ == &::google::protobuf::internal::kEmptyString) {
    mac_addr_ = new ::std::string;
  }
  mac_addr_->assign(reinterpret_cast<const char*>(value), size);
}
inline ::std::string* ScanVirusInfo::mutable_mac_addr() {
  set_has_mac_addr();
  if (mac_addr_ == &::google::protobuf::internal::kEmptyString) {
    mac_addr_ = new ::std::string;
  }
  return mac_addr_;
}
inline ::std::string* ScanVirusInfo::release_mac_addr() {
  clear_has_mac_addr();
  if (mac_addr_ == &::google::protobuf::internal::kEmptyString) {
    return NULL;
  } else {
    ::std::string* temp = mac_addr_;
    mac_addr_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
    return temp;
  }
}
inline void ScanVirusInfo::set_allocated_mac_addr(::std::string* mac_addr) {
  if (mac_addr_ != &::google::protobuf::internal::kEmptyString) {
    delete mac_addr_;
  }
  if (mac_addr) {
    set_has_mac_addr();
    mac_addr_ = mac_addr;
  } else {
    clear_has_mac_addr();
    mac_addr_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
  }
}

// optional .message_network.ScanVirusInfo.ScanStatusType scan_status = 4;
inline bool ScanVirusInfo::has_scan_status() const {
  return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void ScanVirusInfo::set_has_scan_status() {
  _has_bits_[0] |= 0x00000008u;
}
inline void ScanVirusInfo::clear_has_scan_status() {
  _has_bits_[0] &= ~0x00000008u;
}
inline void ScanVirusInfo::clear_scan_status() {
  scan_status_ = 1;
  clear_has_scan_status();
}
inline ::message_network::ScanVirusInfo_ScanStatusType ScanVirusInfo::scan_status() const {
  return static_cast< ::message_network::ScanVirusInfo_ScanStatusType >(scan_status_);
}
inline void ScanVirusInfo::set_scan_status(::message_network::ScanVirusInfo_ScanStatusType value) {
  assert(::message_network::ScanVirusInfo_ScanStatusType_IsValid(value));
  set_has_scan_status();
  scan_status_ = value;
}

// @@protoc_insertion_point(namespace_scope)

}  // namespace message_network

#ifndef SWIG
namespace google {
namespace protobuf {

template <>
inline const EnumDescriptor* GetEnumDescriptor< ::message_network::ScanVirusInfo_ScanStatusType>() {
  return ::message_network::ScanVirusInfo_ScanStatusType_descriptor();
}

}  // namespace google
}  // namespace protobuf
#endif  // SWIG

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_message_5fnetwork_2eproto__INCLUDED


text:
namespace remoting {
namespace protocol {

class AudioWriter;
class HostControlDispatcher;
class HostEventDispatcher;
class HostVideoDispatcher;
class VideoFeedbackStub;
class VideoFramePump;

// This class represents a remote viewer connection to the chromoting
// host. It sets up all protocol channels and connects them to the
// stubs.
class IceConnectionToClient : public ConnectionToClient,
                              public Session::EventHandler,
                              public IceTransport::EventHandler,
                              public ChannelDispatcherBase::EventHandler {
 public:
  IceConnectionToClient(
      std::unique_ptr<Session> session,
      scoped_refptr<TransportContext> transport_context,
      scoped_refptr<base::SingleThreadTaskRunner> video_encode_task_runner,
      scoped_refptr<base::SingleThreadTaskRunner> audio_task_runner);
  ~IceConnectionToClient() override;

  // ConnectionToClient interface.
  void SetEventHandler(
      ConnectionToClient::EventHandler* event_handler) override;
  Session* session() override;
  void Disconnect(ErrorCode error) override;
  std::unique_ptr<VideoStream> StartVideoStream(
      std::unique_ptr<webrtc::DesktopCapturer> desktop_capturer) override;
  std::unique_ptr<AudioStream> StartAudioStream(
      std::unique_ptr<AudioSource> audio_source) override;
  ClientStub* client_stub() override;
  void set_clipboard_stub(ClipboardStub* clipboard_stub) override;
  void set_host_stub(HostStub* host_stub) override;
  void set_input_stub(InputStub* input_stub) override;

 private:
  // Session::EventHandler interface.
  void OnSessionStateChange(Session::State state) override;

  // IceTransport::EventHandler interface.
  void OnIceTransportRouteChange(const std::string& channel_name,
                                 const TransportRoute& route) override;
  void OnIceTransportError(ErrorCode error) override;

  // ChannelDispatcherBase::EventHandler interface.
  void OnChannelInitialized(ChannelDispatcherBase* channel_dispatcher) override;
  void OnChannelClosed(ChannelDispatcherBase* channel_dispatcher) override;

  // Callback passed to |event_dispatcher_|
  void OnInputEventReceived(int64_t timestamp);

  void NotifyIfChannelsReady();

  void CloseChannels();

  base::ThreadChecker thread_checker_;

  // Event handler for handling events sent from this object.
  ConnectionToClient::EventHandler* event_handler_;

  std::unique_ptr<Session> session_;

  scoped_refptr<base::SingleThreadTaskRunner> video_encode_task_runner_;
  scoped_refptr<base::SingleThreadTaskRunner> audio_task_runner_;

  IceTransport transport_;

  std::unique_ptr<HostControlDispatcher> control_dispatcher_;
  std::unique_ptr<HostEventDispatcher> event_dispatcher_;
  std::unique_ptr<HostVideoDispatcher> video_dispatcher_;
  std::unique_ptr<AudioWriter> audio_writer_;

  DISALLOW_COPY_AND_ASSIGN(IceConnectionToClient);
};

}  // namespace protocol
}  // namespace remoting

#endif  // REMOTING_PROTOCOL_ICE_CONNECTION_TO_CLIENT_H_


text:
using namespace std;
using namespace seqan;

int main(){
	String<String<Dna>> reads;
	addValue(reads,"ACGTAGACGATGAC");
	addValue(reads,"ACGCGATAGACGTC");

	return 0;
}


text:
/* 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.flowable.cmmn.editor.json.converter;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter.CmmnModelIdHelper;
import org.flowable.cmmn.editor.json.converter.util.CmmnModelJsonConverterUtil;
import org.flowable.cmmn.model.BaseElement;
import org.flowable.cmmn.model.CaseElement;
import org.flowable.cmmn.model.CmmnModel;
import org.flowable.cmmn.model.SendEventServiceTask;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class SendEventTaskJsonConverter extends BaseCmmnJsonConverter {

    public static void fillTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap) {

        fillJsonTypes(convertersToCmmnMap);
    }

    public static void fillJsonTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToBpmnMap) {
        convertersToBpmnMap.put(STENCIL_TASK_SEND_EVENT, SendEventTaskJsonConverter.class);
    }

    @Override
    protected String getStencilId(BaseElement baseElement) {
        return STENCIL_TASK_SEND_EVENT;
    }

    @Override
    protected CaseElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor,
                    BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnJsonConverterContext converterContext, CmmnModelIdHelper cmmnModelIdHelper) {

        SendEventServiceTask task = new SendEventServiceTask();

        String eventKey = getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_EVENT_KEY, elementNode);
        if (StringUtils.isNotEmpty(eventKey)) {
            task.setEventType(eventKey);
            addFlowableExtensionElementWithValue("eventName", getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_EVENT_NAME, elementNode), task);
            CmmnModelJsonConverterUtil.convertJsonToInParameters(elementNode, task);

            addFlowableExtensionElementWithValue("channelKey", getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_CHANNEL_KEY, elementNode), task);
            addFlowableExtensionElementWithValue("channelName", getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_CHANNEL_NAME, elementNode), task);
            addFlowableExtensionElementWithValue("channelType", getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_CHANNEL_TYPE, elementNode), task);
            addFlowableExtensionElementWithValue("channelDestination", getPropertyValueAsString(PROPERTY_EVENT_REGISTRY_CHANNEL_DESTINATION, elementNode), task);
        }

        return task;
    }

    @Override
    protected void convertElementToJson(ObjectNode elementNode, ObjectNode propertiesNode, ActivityProcessor processor,
            BaseElement baseElement, CmmnModel cmmnModel, CmmnJsonConverterContext converterContext) {

    }

}


text:
package org.apache.ignite.ml.math.impls.storage.vector;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import org.apache.ignite.internal.util.offheap.GridOffHeapMap;
import org.apache.ignite.internal.util.offheap.GridOffHeapMapFactory;
import org.apache.ignite.ml.math.VectorStorage;
import org.apache.ignite.ml.math.exceptions.UnsupportedOperationException;
import org.apache.ignite.ml.math.impls.vector.SparseLocalOffHeapVector;

/**
 * {@link VectorStorage} implementation for {@link SparseLocalOffHeapVector}.
 */
public class SparseLocalOffHeapVectorStorage implements VectorStorage {
    /** Assume 10% density. */
    private static final int INIT_DENSITY = 10;

    /** Storage capacity. */
    private int size;

    /** Local off heap map. */
    private GridOffHeapMap gridOffHeapMap;

    /** */
    public SparseLocalOffHeapVectorStorage() {
        //No-op.
    }

    /**
     * @param cap Initial capacity.
     */
    public SparseLocalOffHeapVectorStorage(int cap) {
        assert cap > 0;

        gridOffHeapMap = GridOffHeapMapFactory.unsafeMap(cap / INIT_DENSITY);
        size = cap;
    }

    /** {@inheritDoc} */
    @Override public int size() {
        return size;
    }

    /** {@inheritDoc} */
    @Override public double get(int i) {
        byte[] bytes = gridOffHeapMap.get(hash(i), intToByteArray(i));
        return bytes == null ? 0 : ByteBuffer.wrap(bytes).getDouble();
    }

    /** {@inheritDoc} */
    @Override public void set(int i, double v) {
        if (v != 0.0)
            gridOffHeapMap.put(hash(i), intToByteArray(i), doubleToByteArray(v));
        else if (gridOffHeapMap.contains(hash(i), intToByteArray(i)))
            gridOffHeapMap.remove(hash(i), intToByteArray(i));
    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        throw new UnsupportedOperationException(); // TODO: add externalization support.
    }

    /** {@inheritDoc} */
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    @Override public boolean isSequentialAccess() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isRandomAccess() {
        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean isDense() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isArrayBased() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public boolean isDistributed() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public void destroy() {
        gridOffHeapMap.destruct();
    }

    /** */
    private int hash(int h) {
        // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
        // Despite two multiplies, this is often faster than others
        // with comparable bit-spread properties.
        h ^= h >>> 16;
        h *= 0x85ebca6b;
        h ^= h >>> 13;
        h *= 0xc2b2ae35;

        return (h >>> 16) ^ h;
    }

    /** */
    private byte[] intToByteArray(int val) {
        return new byte[] {
            (byte)(val >>> 24),
            (byte)(val >>> 16),
            (byte)(val >>> 8),
            (byte)val};
    }

    /** */
    private byte[] doubleToByteArray(double val) {
        long l = Double.doubleToRawLongBits(val);
        return new byte[] {
            (byte)((l >> 56) & 0xff),
            (byte)((l >> 48) & 0xff),
            (byte)((l >> 40) & 0xff),
            (byte)((l >> 32) & 0xff),
            (byte)((l >> 24) & 0xff),
            (byte)((l >> 16) & 0xff),
            (byte)((l >> 8) & 0xff),
            (byte)((l) & 0xff),
        };
    }
}


text:
from __future__ import print_function
from __future__ import unicode_literals

import os
try:
    from ConfigParser import RawConfigParser
except ImportError:
    def RawConfigParser():
        import configparser
        return configparser.ConfigParser(interpolation=None)

from .repos import BadRepo, DirectoryRepo, HttpRepo
from .constants import REPO, REPOTYPE

class UnknownRepoError(NameError):
    '''Repo is not defined at all'''

class Network(object):

    REPO_TYPES = {
        REPOTYPE.DIRECTORY,
        REPOTYPE.HTTP,
    }

    REPO_ATTRIBUTES = set(
        DirectoryRepo.ATTRIBUTES
    ).union(
        set(HttpRepo.ATTRIBUTES)
    )

    REPO_SECTION_PREFIX = 'repo:'

    TYPE_TO_CLASS = {
        REPOTYPE.DIRECTORY: DirectoryRepo,
        REPOTYPE.HTTP: HttpRepo,
    }

    # name of active/default/ repo
    active_repo = None

    def __init__(self, filename):
        self._repo_store_filename = filename
        self._config = None
        self.active_repo = None
        self.reload()

    def reload(self):
        self._config = RawConfigParser()
        if os.path.exists(self._repo_store_filename):
            self._config.read(self._repo_store_filename)

    def _save(self):
        with open(self._repo_store_filename, 'wt') as f:
            self._config.write(f)

    def check_repo_exists(self, repo_name):
        repokey = self.REPO_SECTION_PREFIX + repo_name
        if not self._config.has_section(repokey):
            raise UnknownRepoError(repo_name)

    def get_repo(self, repo_name):
        repo_name = repo_name or self.active_repo
        self.check_repo_exists(repo_name)

        attributes = self.get_attributes(repo_name)
        repo_type = attributes.get(REPO.TYPE)

        repo_class = self.TYPE_TO_CLASS.get(repo_type, BadRepo)
        return repo_class(repo_name, attributes)

    def define(self, repo_name):
        repokey = self.REPO_SECTION_PREFIX + repo_name
        self._config.add_section(repokey)
        self._save()

    def forget(self, repo_name):
        repokey = self.REPO_SECTION_PREFIX + repo_name
        self._config.remove_section(repokey)
        self._save()

    def set(self, repo_name, attribute, value):
        self.check_repo_exists(repo_name)
        repokey = self.REPO_SECTION_PREFIX + repo_name
        self._config.set(repokey, attribute, value)
        self._save()

    def unset(self, repo_name, attribute):
        repokey = self.REPO_SECTION_PREFIX + repo_name
        self._config.remove_option(repokey, attribute)
        self._save()

    @property
    def repo_names(self):
        return [
            section[len(self.REPO_SECTION_PREFIX):]
            for section in self._config.sections()
            if section.startswith(self.REPO_SECTION_PREFIX)
        ]

    def get_attributes(self, repo_name):
        repokey = self.REPO_SECTION_PREFIX + repo_name
        if not self._config.has_section(repokey):
            raise UnknownRepoError(repo_name)

        attributes = {
            attribute: self._config.get(repokey, attribute)
            for attribute in self._config.options(repokey)
        }
        return attributes

    # more complicated operations
    def define_http_repo(self, repo):
        self.define(repo)
        self.set(repo, REPO.TYPE, REPOTYPE.HTTP)

    def define_directory_repo(self, repo):
        self.define(repo)
        self.set(repo, REPO.TYPE, REPOTYPE.DIRECTORY)

    def setup_for_pypi_python_org(self, repo):
        self.set(repo, REPO.TYPE, REPOTYPE.HTTP)
        self.set(repo, REPO.DOWNLOAD_URL, 'https://pypi.python.org/simple/')
        self.set(repo, REPO.UPLOAD_URL, 'https://pypi.python.org/pypi')

    def setup_for_pip_local(self, repo):
        piplocal = os.path.expanduser('~/.pip/local')
        self.set(repo, REPO.TYPE, REPOTYPE.DIRECTORY)
        self.set(repo, REPO.DIRECTORY, piplocal)

    def import_pypirc(self, pypirc_filename):
        pypirc = RawConfigParser()
        pypirc.read(pypirc_filename)

        def copy_attr(repo, key, repoattr):
            if pypirc.has_option(repo, key):
                value = pypirc.get(repo, key)
                self.set(repo, repoattr, value)

        for repo in pypirc.sections():
            if repo != 'distutils':
                self.define(repo)
                self.set(repo, REPO.TYPE, REPOTYPE.HTTP)
                copy_attr(repo, 'repository', REPO.UPLOAD_URL)
                copy_attr(repo, 'username', REPO.USERNAME)
                copy_attr(repo, 'password', REPO.PASSWORD)

    def add_known_repos(self, dot_pypirc):
        self.import_pypirc(dot_pypirc)

        PYPI = 'pypi'
        if PYPI not in self.repo_names:
            self.define_http_repo(PYPI)
            self.setup_for_pypi_python_org(PYPI)

        LOCAL = 'local'
        if LOCAL not in self.repo_names:
            self.define_directory_repo(LOCAL)
            self.setup_for_pip_local(LOCAL)


text:
<?php

/**
 * Formatter
 */
class FormatterUtil
{

	public static function combineNonEmpty($combiner, $details)
	{
		$nonemptys = array();

		foreach ($details as $value) {
			if (!empty($value) && $value != ' ') {
				$nonemptys[] = $value;
			}
		}

		return implode($combiner, $nonemptys);
	}

}


text:
FROM rust-iml-base as builder

FROM imlteam/systemd-base:6.2.0
COPY --from=builder /build/target/release/iml-report /bin/
COPY docker/iml-report/iml-report.service /etc/systemd/system/
COPY docker/iml-report/iml-report.conf /etc/systemd/system/
COPY iml-report.conf /usr/lib/tmpfiles.d/
COPY docker/wait-for-dependencies.sh /usr/local/bin/

RUN systemctl enable iml-report

ENTRYPOINT ["wait-for-dependencies.sh"]

CMD ["/usr/sbin/init"]


text:
package ro.pub.cs.aipi.lab09.model;

import java.util.ArrayList;
import java.util.List;

import javafx.beans.property.SimpleStringProperty;

public class InvoiceHeader extends Model {

    final private SimpleStringProperty id;
    final private SimpleStringProperty identification_number;
    final private SimpleStringProperty issue_date;
    final private SimpleStringProperty state;
    final private SimpleStringProperty user_id;

    public InvoiceHeader(String id, String identification_number, String issue_date, String state, String user_id) {
        this.id = new SimpleStringProperty(id);
        this.identification_number = new SimpleStringProperty(identification_number);
        this.issue_date = new SimpleStringProperty(issue_date);
        this.state = new SimpleStringProperty(state);
        this.user_id = new SimpleStringProperty(user_id);
    }

    public InvoiceHeader(List<String> invoiceHeader) {
        this.id = new SimpleStringProperty(invoiceHeader.get(0));
        this.identification_number = new SimpleStringProperty(invoiceHeader.get(1));
        this.issue_date = new SimpleStringProperty(invoiceHeader.get(2));
        this.state = new SimpleStringProperty(invoiceHeader.get(3));
        this.user_id = new SimpleStringProperty(invoiceHeader.get(4));
    }

    public String getId() {
        return id.get();
    }

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

    public String getIdentification_number() {
        return identification_number.get();
    }

    public void setIdentification_number(String identification_number) {
        this.identification_number.set(identification_number);
    }

    public String getIssue_date() {
        return issue_date.get();
    }

    public void setIssue_date(String issue_date) {
        this.issue_date.set(issue_date);
    }

    public String getState() {
        return state.get();
    }

    public void setState(String state) {
        this.state.set(state);
    }

    public String getUser_id() {
        return user_id.get();
    }

    public void setUser_id(String user_id) {
        this.user_id.set(user_id);
    }

    @Override
    public List<String> getValues() {
        List<String> values = new ArrayList<>();
        values.add(id.get());
        values.add(identification_number.get());
        values.add(issue_date.get());
        values.add(state.get());
        values.add(user_id.get());
        return values;
    }
}


text:
<?php

namespace Sonata\UserBundle\Tests\Menu;

use Sonata\UserBundle\Menu\ProfileMenuBuilder;

/**
 * Class ProfileMenuBuilderTest
 *
 * @package Sonata\UserBundle\Tests\Menu
 *
 * @author Hugo Briand <briand@ekino.com>
 */
class ProfileMenuBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateProfileMenu()
    {
        $menu = $this->getMock('Knp\Menu\ItemInterface');
        $factory = $this->getMock('Knp\Menu\FactoryInterface');

        $factory->expects($this->once())
            ->method('createItem')
            ->will($this->returnValue($menu));

        $translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
        $eventDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');

        $builder = new ProfileMenuBuilder($factory, $translator, array(), $eventDispatcher);

        $genMenu = $builder->createProfileMenu();

        $this->assertInstanceOf('Knp\Menu\ItemInterface', $genMenu);
    }
}


text:
<?php

namespace MMiic\GeTui\Igetui\Reqs;

use MMiic\GeTui\Protobuf\PBMessage;

class SingleBatchRequest extends PBMessage
{
    var $wired_type = PBMessage::WIRED_LENGTH_DELIMITED;
    public function __construct($reader=null)
    {
        parent::__construct($reader);
        $this->fields["1"] = "PBString";
        $this->values["1"] = "";
        $this->fields["2"] = "SingleBatchItem";
        $this->values["2"] = array();
    }
    function batchId()
    {
        return $this->_get_value("1");
    }
    function set_batchId($value)
    {
        return $this->_set_value("1", $value);
    }
    function batchItem($offset)
    {
        return $this->_get_arr_value("2", $offset);
    }
    function add_batchItem()
    {
        return $this->_add_arr_value("2");
    }
    function set_batchItem($index, $value)
    {
        $this->_set_arr_value("2", $index, $value);
    }
    function remove_last_batchItem()
    {
        $this->_remove_last_arr_value("2");
    }
    function batchItem_size()
    {
        return $this->_get_arr_size("2");
    }
}

?>


text:
package com.google.errorprone.bugpatterns;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.errorprone.CompilationTestHelper;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
import java.util.stream.Collectors;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * @author awturner@google.com (Andy Turner)
 */
@RunWith(JUnit4.class)
public class ThreeLetterTimeZoneIDTest {

  private final CompilationTestHelper compilationHelper =
      CompilationTestHelper.newInstance(ThreeLetterTimeZoneID.class, getClass());

  @Test
  public void testAllThreeLetterIdsAreCoveredByZoneIdShortIds() {
    // The check's logic is predicated on there being an entry in SHORT_IDS for all three-letter
    // IDs in TimeZone.getAvailableIDs() that aren't in ZoneId.getAvailableZoneIds().
    Set<String> availableZoneIds = new HashSet<>(ZoneId.getAvailableZoneIds());
    Set<String> expectedIds =
        Arrays.stream(TimeZone.getAvailableIDs())
            .filter(s -> s.length() == 3)
            .filter(s -> !availableZoneIds.contains(s))
            .collect(Collectors.toSet());

    assertThat(ZoneId.SHORT_IDS.keySet()).containsExactlyElementsIn(expectedIds);
  }

  @Test
  @Ignore
  public void printMappings() {
    // This is here for debugging, to allow printing of the suggested replacements.
    for (String id : TimeZone.getAvailableIDs()) {
      if (id.length() == 3) {
        System.out.printf("%s %s %s%n", id, replacements(id, false), replacements(id, true));
      }
    }
  }

  @Test
  public void testPositiveCase() {
    compilationHelper
        .addSourceLines(
            "a/A.java",
            "package a;",
            "import java.util.TimeZone;",
            "class A {",
            "  public static void test_PST() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Los_Angeles\")",
            "    TimeZone.getTimeZone(\"PST\");",
            "  }",
            "  public static void test_EST() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Etc/GMT+5\")",
            "    TimeZone.getTimeZone(\"EST\");",
            "  }",
            "  public static void test_noPreferredReplacements() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Asia/Dhaka\")",
            "    TimeZone.getTimeZone(\"BST\");",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testPositiveCaseJodaTime() {
    compilationHelper
        .addSourceLines(
            "a/A.java",
            "package a;",
            "import java.util.TimeZone;",
            "import org.joda.time.DateTimeZone;",
            "class A {",
            "  public static void test_EST() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/New_York\")",
            "    DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"EST\"));",
            "  }",
            "  public static void test_HST() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"Pacific/Honolulu\")",
            "    DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"HST\"));",
            "  }",
            "  public static void test_MST() {",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Denver\")",
            "    DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"MST\"));",
            "  }",
            "  public static void test_PST() {",
            "    // Not a special case, but should still work.",
            "    // BUG: Diagnostic contains: TimeZone.getTimeZone(\"America/Los_Angeles\")",
            "    DateTimeZone.forTimeZone(TimeZone.getTimeZone(\"PST\"));",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCase() {
    compilationHelper
        .addSourceLines(
            "a/A.java",
            "package a;",
            "import java.util.TimeZone;",
            "class A {",
            "  public static void notThreeLetter() {",
            "    TimeZone.getTimeZone(\"\");",
            "    TimeZone.getTimeZone(\"America/Los_Angeles\");",
            "  }",
            "  public static void threeLetterButAllowed() {",
            "    TimeZone.getTimeZone(\"GMT\");",
            "    TimeZone.getTimeZone(\"UTC\");",
            "    TimeZone.getTimeZone(\"CET\");",
            "    TimeZone.getTimeZone(\"PRC\");",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testReplacements_PST() {
    ImmutableList<String> replacements = replacements("PST", false);
    // Suggests IANA ID first, then the fixed offset.
    assertThat(replacements).containsExactly("America/Los_Angeles", "Etc/GMT+8").inOrder();
  }

  @Test
  public void testReplacements_EST() {
    ImmutableList<String> replacements = replacements("EST", false);
    // Suggests fixed offset first, then the IANA ID, because this the former has the same rules as
    // TimeZone.getTimeZone("EST").
    assertThat(replacements).containsExactly("Etc/GMT+5", "America/New_York").inOrder();
  }

  @Test
  public void testReplacements_IST() {
    ImmutableList<String> replacements = replacements("IST", false);
    assertThat(replacements).containsExactly("Asia/Kolkata").inOrder();
  }

  @Test
  public void testReplacements_CST() {
    // Only rule-equivalent suggestions are made (unless we have explicitly provided suggestions) -
    // we don't suggest "China Standard Time" for CST, because the existing code is semantically
    // equivalent to US "Central Standard Time".
    ImmutableList<String> replacements = replacements("CST", false);
    assertThat(replacements).contains("America/Chicago");
    assertThat(replacements).doesNotContain("Asia/Shanghai");
  }

  private static ImmutableList<String> replacements(String zone, boolean inJodaTimeContext) {
    return ThreeLetterTimeZoneID.getReplacement(zone, inJodaTimeContext, "message").replacements;
  }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>GLSL array equality test</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="canvas" width="64" height="64"> </canvas>


text:
package abi42_0_0.expo.modules.camera.events;

import android.os.Bundle;
import androidx.core.util.Pools;

import abi42_0_0.org.unimodules.core.interfaces.services.EventEmitter;
import abi42_0_0.expo.modules.camera.CameraViewManager;

public class PictureSavedEvent extends EventEmitter.BaseEvent {
  private static final Pools.SynchronizedPool<PictureSavedEvent> EVENTS_POOL =
      new Pools.SynchronizedPool<>(3);

  private Bundle mResponse;

  private PictureSavedEvent() {}

  public static PictureSavedEvent obtain(Bundle response) {
    PictureSavedEvent event = EVENTS_POOL.acquire();
    if (event == null) {
      event = new PictureSavedEvent();
    }
    event.init(response);
    return event;
  }

  private void init(Bundle response) {
    mResponse = response;
  }

  @Override
  public short getCoalescingKey() {
    short fallback = -1;
    Bundle data = mResponse.getBundle("data");
    if (data == null || !data.containsKey("uri")) {
      return fallback;
    }
    String uri = data.getString("uri");
    if (uri == null) {
      return fallback;
    }
    return (short) (uri.hashCode() % Short.MAX_VALUE);
  }

  @Override
  public String getEventName() {
    return CameraViewManager.Events.EVENT_ON_PICTURE_SAVED.toString();
  }

  @Override
  public Bundle getEventBody() {
    return mResponse;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Elench. fung. (Halle), cont. prim. 127, tab. 20:102 (1786)

#### Original name
Agaricus obsolescens Batsch

### Remarks
null


text: A simple example of how volley works


text:
PGAdapter supports the [Go pgx driver](https://github.com/jackc/pgx) version 4.15.0 and higher.

## Usage

First start PGAdapter:

```shell
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
docker pull gcr.io/cloud-spanner-pg-adapter/pgadapter
docker run \
  -d -p 5432:5432 \
  -v ${GOOGLE_APPLICATION_CREDENTIALS}:${GOOGLE_APPLICATION_CREDENTIALS}:ro \
  -e GOOGLE_APPLICATION_CREDENTIALS \
  gcr.io/cloud-spanner-pg-adapter/pgadapter \
  -p my-project -i my-instance \
  -x
```

Then connect to PGAdapter using TCP like this:

```go
// pwd:uid is not used by PGAdapter, but it is required in the connection string.
// Replace localhost and 5432 with the host and port number where PGAdapter is running.
// sslmode=disable instructs pgx to try plain text mode directly. Otherwise, pgx will try two times
// with SSL enabled before trying plain text.
connString := "postgres://uid:pwd@localhost:5432/my-database?sslmode=disable"
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
    return err
}
defer conn.Close(ctx)

var greeting string
err = conn.QueryRow(ctx, "select 'Hello world!' as hello").Scan(&greeting)
if err != nil {
    return err
}
fmt.Printf("Greeting from Cloud Spanner PostgreSQL: %v\n", greeting)
```

You can also connect to PGAdapter using Unix Domain Sockets if PGAdapter is running on the same host
as the client application:

```go
// '/tmp' is the default domain socket directory for PGAdapter. This can be changed using the -dir
// command line argument. 5432 is the default port number used by PGAdapter. Change this in the
// connection string if PGAdapter is running on a custom port.
connString := "host=/tmp port=5432 database=my-database"
ctx := context.Background()
conn, err := pgx.Connect(ctx, connString)
if err != nil {
    return err
}
defer conn.Close(ctx)

var greeting string
err = conn.QueryRow(ctx, "select 'Hello world!' as hello").Scan(&greeting)
if err != nil {
    return err
}
fmt.Printf("Greeting from Cloud Spanner PostgreSQL: %v\n", greeting)
```

## Running PGAdapter

This example uses the pre-built Docker image to run PGAdapter.
See [README](../README.md) for more possibilities on how to run PGAdapter.

## Performance Considerations

The following will give you the best possible performance when using pgx with PGAdapter.

### Unix Domain Sockets
Use Unix Domain Socket connections for the lowest possible latency when PGAdapter and the client
application are running on the same host. See https://pkg.go.dev/github.com/jackc/pgx#ConnConfig
for more information on connection options for pgx.

### Batching
Use the pgx batching API when executing multiple DDL or DML statements. PGAdapter will combine
DML and DDL statements that are executed in a batch into a single request on Cloud Spanner.
This can significantly reduce the overhead of executing multiple DML or DDL statements.

Example for DML statements:

```go
batch := &pgx.Batch{}
batch.Queue("insert into my_table (key, value) values ($1, $2)", "k1", "value1")
batch.Queue("insert into my_table (key, value) values ($1, $2)", "k2", "value2")
res := conn.SendBatch(context.Background(), batch)
```

Example for DDL statements:

```go
batch := &pgx.Batch{}
batch.Queue("create table singers (singerid varchar primary key, name varchar)")
batch.Queue("create index idx_singers_name on singers (name)")
res := conn.SendBatch(context.Background(), batch)
```

## Limitations
- Server side [prepared statements](https://www.postgresql.org/docs/current/sql-prepare.html) are limited to at most 50 parameters.
  `pgx` uses server side prepared statements for all parameterized statements in extended query mode.
  You can use the [simple query protocol](https://pkg.go.dev/github.com/jackc/pgx/v4#QuerySimpleProtocol) to work around this limitation.