text:
package de.oliver_heger.linedj.archivehttp

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.http.scaladsl.model._
import akka.pattern.{AskTimeoutException, ask}
import akka.stream.scaladsl.Source
import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
import akka.util.{ByteString, Timeout}
import com.github.cloudfiles.core.http.HttpRequestSender.FailedResponseException
import de.oliver_heger.linedj.ForwardTestActor.ForwardedMessage
import de.oliver_heger.linedj.archivehttp.config.HttpArchiveConfig
import de.oliver_heger.linedj.archivehttp.impl._
import de.oliver_heger.linedj.archivehttp.impl.download.HttpDownloadManagementActor
import de.oliver_heger.linedj.archivehttp.io.MediaDownloader
import de.oliver_heger.linedj.archivehttp.temp.TempPathGenerator
import de.oliver_heger.linedj.io.stream.AbstractStreamProcessingActor.CancelStreams
import de.oliver_heger.linedj.io.{CloseAck, CloseRequest}
import de.oliver_heger.linedj.shared.archive.media._
import de.oliver_heger.linedj.shared.archive.metadata.{GetMetaDataFileInfo, MetaDataFileInfo}
import de.oliver_heger.linedj.shared.archive.union.{UpdateOperationCompleted, UpdateOperationStarts}
import de.oliver_heger.linedj.utils.ChildActorFactory
import de.oliver_heger.linedj.{AsyncTestHelper, ForwardTestActor, StateTestHelper}
import org.mockito.ArgumentMatchers.{any, eq => argEq}
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfterAll
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.mockito.MockitoSugar

import java.io.IOException
import java.nio.file.Paths
import java.util.concurrent.LinkedBlockingQueue
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

object HttpArchiveManagementActorSpec {

  /** The value of the propagation buffer size config property. */
  private val PropBufSize = 4

  /**
    * The template for the test archive configuration. (Some properties are
    * modified by specific tests.
    */
  private val ArchiveConfig =
    HttpArchiveConfig(archiveBaseUri = "https://some.archive.org/data/music",
      archiveName = "test", processorCount = 1, processorTimeout = Timeout(1.minute), propagationBufSize = PropBufSize,
      maxContentSize = 1024, downloadBufferSize = 1000, downloadMaxInactivity = 10.seconds,
      downloadReadChunkSize = 8192, timeoutReadSize = 111, downloadConfig = null, downloader = null,
      contentPath = Uri.Path("archiveContent.json"), mediaPath = Uri.Path("media"), metaDataPath = Uri.Path("meta"))

  /** Constant for an archive name. */
  private val ArchiveName = ArchiveConfig.archiveName

  /** Constant for a sequence number. */
  private val SeqNo = 20180621

  /** Class for the content processor actor. */
  private val ClsContentProcessor = classOf[HttpArchiveContentProcessorActor]

  /** Class for the medium info processor actor. */
  private val ClsMediumInfoProcessor = classOf[MediumInfoResponseProcessingActor]

  /** Class for the meta data processor actor. */
  private val ClsMetaDataProcessor = classOf[MetaDataResponseProcessingActor]

  /** Class for the content propagation actor. */
  private val ClsContentPropagationActor = classOf[ContentPropagationActor]

  /** Class for the download management actor. */
  private val ClsDownloadManagementActor =
    HttpDownloadManagementActor(null, null, null, null).actorClass()

  /** A state indicating that a scan operation is in progress. */
  private val ProgressState = ContentProcessingUpdateServiceImpl.InitialState
    .copy(scanInProgress = true)

  /**
    * A class for storing information about child actors created by the
    * management actor.
    *
    * @param props the creation Props of the child
    * @param child the child actor that was actually created
    */
  private case class ChildActorCreation(props: Props, child: ActorRef)

  /**
    * Checks that no further messages have been sent to the specified test
    * probe.
    *
    * @param probe the test probe
    */
  private def expectNoMoreMsg(probe: TestProbe): Unit = {
    val msg = new Object
    probe.ref ! msg
    probe.expectMsg(msg)
  }

  /**
    * Creates a list with test medium descriptions.
    *
    * @return the list with test descriptions
    */
  private def createMediumDescriptions(): List[HttpMediumDesc] =
    (1 to 4).map(i => HttpMediumDesc("descPath" + i, "metaDataPath" + i)).toList

  /**
    * Returns a JSON representation for a medium description.
    *
    * @param md the description
    * @return the JSON representation
    */
  private def createMediumDescriptionJson(md: HttpMediumDesc): String =
    s"""{ "mediumDescriptionPath": "${md.mediumDescriptionPath}",
       |"metaDataPath": "${md.metaDataPath}"}
   """.stripMargin

  /**
    * Generates a JSON representation of the test medium descriptions.
    *
    * @return the JSON description
    */
  private def createMediumDescriptionsJson(): String =
    createMediumDescriptions().map(md => createMediumDescriptionJson(md))
      .mkString("[", ", ", "]")

  /**
    * Creates a response data source for a successful request to the content
    * document of the test archive.
    *
    * @return the data source with the content document
    */
  private def createSuccessResponse(): Source[ByteString, Any] = {
    val data = ByteString(createMediumDescriptionsJson()).grouped(128)
    Source(data.toList)
  }

}

/**
  * Test class for ''HttpArchiveManagementActor''.
  */
class HttpArchiveManagementActorSpec(testSystem: ActorSystem) extends TestKit(testSystem)
  with ImplicitSender with AnyFlatSpecLike with BeforeAndAfterAll with Matchers with MockitoSugar
  with AsyncTestHelper {

  import HttpArchiveManagementActorSpec._

  def this() = this(ActorSystem("HttpArchiveManagementActorSpec"))

  override protected def afterAll(): Unit = {
    TestKit shutdownActorSystem system
  }

  "A HttpArchiveManagementActor" should "create correct Props" in {
    val mediaManager = TestProbe()
    val metaManager = TestProbe()
    val monitoringActor = TestProbe()
    val removeActor = TestProbe()
    val pathGenerator = new TempPathGenerator(Paths get "temp")
    val props = HttpArchiveManagementActor(ArchiveConfig, pathGenerator, mediaManager.ref,
      metaManager.ref, monitoringActor.ref, removeActor.ref)
    classOf[HttpArchiveManagementActor].isAssignableFrom(props.actorClass()) shouldBe true
    classOf[ChildActorFactory].isAssignableFrom(props.actorClass()) shouldBe true
    props.args should be(List(ContentProcessingUpdateServiceImpl, ArchiveConfig, pathGenerator,
      mediaManager.ref, metaManager.ref, monitoringActor.ref, removeActor.ref))
  }

  /**
    * Checks a processing operation on a test archive.
    *
    * @param helper the prepared helper
    */
  private def checkProcessing(helper: HttpArchiveManagementActorTestHelper): Unit = {
    val request = helper.stub((), ProgressState)(_.processingDone())
      .triggerScan().expectProcessingRequest()
    request.archiveConfig should be(helper.config)
    request.settingsProcessorActor should be(helper.probeMediumInfoProcessor.ref)
    request.metaDataProcessorActor should be(helper.probeMetaDataProcessor.ref)

    val futureDescriptions = request.mediaSource.runFold(
      List.empty[HttpMediumDesc])((lst, md) => md :: lst)
    val descriptions = Await.result(futureDescriptions, 5.seconds)
    val expDescriptions = createMediumDescriptions()
    descriptions should contain only (expDescriptions: _*)

    val result = mock[MediumProcessingResult]
    helper.stub(ProcessingStateTransitionData(None, None), mock[ContentProcessingState]) { svc =>
      svc.handleResultAvailable(argEq(result), any(), argEq(PropBufSize))
    }
    val srcResults = Source.single(result)
    srcResults.runWith(request.sink)
    helper.expectStateUpdate(ContentProcessingUpdateServiceImpl.InitialState)
      .expectStateUpdate(ProgressState)
    verify(helper.updateService).handleResultAvailable(argEq(result), any(), argEq(PropBufSize))
  }

  it should "pass a process request to the content processor actor" in {
    checkProcessing(new HttpArchiveManagementActorTestHelper)
  }

  it should "notify the union archive about a started scan operation" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub((), ProgressState)(_.processingDone())
      .triggerScan()
    helper.probeUnionMetaDataManager.expectMsg(UpdateOperationStarts(None))
  }

  it should "notify the union archive about a completed scan operation" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub((), ProgressState)(_.processingDone())
      .post(HttpArchiveProcessingComplete(HttpArchiveStateConnected))
    helper.probeUnionMetaDataManager.expectMsg(UpdateOperationCompleted(None))
  }

  it should "not send a process request for a response error" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub((), ProgressState)(_.processingDone())
      .initFailedArchiveResponse(new Exception)
      .triggerScan(initSuccessResponse = false)
      .expectNoProcessingRequest()
  }

  it should "recover from an error, so that a new request can be processed" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub((), ProgressState)(_.processingDone())
      .initFailedArchiveResponse(new Exception)
      .triggerScan() // initializes a success response
      .triggerScan(stubProcStarts = false, initSuccessResponse = false)
      .expectProcessingRequest()
  }

  it should "ignore a process request if a scan is ongoing" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub(false, ProgressState)(_.processingStarts())
      .triggerScan(stubProcStarts = false)
      .expectNoProcessingRequest()
    expectNoMoreMsg(helper.probeUnionMetaDataManager)
  }

  it should "answer an archive processing init message" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.post(HttpArchiveProcessingInit)
    expectMsg(HttpArchiveMediumAck)
  }

  it should "handle incoming medium results" in {
    val res1 = mock[MediumProcessingResult]
    val res2 = mock[MediumProcessingResult]
    val propRes = PropagateMediumResult(mock[MediumProcessingResult], removeContent = false)
    val state2 = ProgressState.copy(mediaInProgress = 2, ack = Some(testActor),
      propagateMsg = Some(propRes))
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub(ProcessingStateTransitionData(None, None), ProgressState) { svc =>
      svc.handleResultAvailable(res1, testActor, PropBufSize)
    }.stub(ProcessingStateTransitionData(Some(propRes), Some(testActor)), state2) { svc =>
      svc.handleResultAvailable(res2, testActor, PropBufSize)
    }.post(res1)
      .expectStateUpdate(ContentProcessingUpdateServiceImpl.InitialState)
      .post(res2)
      .expectStateUpdate(ProgressState)
      .expectPropagation(propRes)
    expectMsg(HttpArchiveMediumAck)
  }

  it should "handle confirmation about propagated media" in {
    val res = mock[MediumProcessingResult]
    val propRes = PropagateMediumResult(res, removeContent = false)
    val state2 = ProgressState.copy(mediaInProgress = 28)
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub(ProcessingStateTransitionData(Some(propRes), Some(testActor)),
      ProgressState)(_.handleResultPropagated(SeqNo, PropBufSize))
      .stub(ProcessingStateTransitionData(None, None), state2) { svc =>
        svc.handleResultAvailable(res, testActor, PropBufSize)
      }
      .post(MediumPropagated(SeqNo))
      .expectStateUpdate(ContentProcessingUpdateServiceImpl.InitialState)
      .expectPropagation(propRes)
      .post(res)
      .expectStateUpdate(ProgressState)
    expectMsg(HttpArchiveMediumAck)
  }

  it should "handle a stream end notification" in {
    val state = ProgressState.copy(mediaInProgress = 3)
    val helper = new HttpArchiveManagementActorTestHelper

    helper.stub((), ProgressState)(_.processingDone())
      .stub(false, state)(_.processingStarts())
      .post(HttpArchiveProcessingComplete(HttpArchiveStateConnected))
      .expectStateUpdate(ContentProcessingUpdateServiceImpl.InitialState)
      .triggerScan(stubProcStarts = false)
      .expectStateUpdate(ProgressState)
      .checkArchiveState(HttpArchiveStateConnected)
  }

  it should "handle and propagate a cancel message" in {
    val helper = new HttpArchiveManagementActorTestHelper
    helper.triggerScan().expectProcessingRequest()

    helper post CloseRequest
    expectMsg(CloseAck(helper.manager))
    helper.probeContentProcessor.expectMsg(CancelStreams)
    helper.probeMediumInfoProcessor.expectMsg(CancelStreams)
    helper.probeMetaDataProcessor.expectMsg(CancelStreams)
  }

  it should "forward a file download request to the download manager" in {
    val request = MediumFileRequest(MediaFileID(MediumID("aMedium", None), "fileUri"),
      withMetaData = true)
    val helper = new HttpArchiveManagementActorTestHelper

    helper.post(request)
    expectMsg(ForwardedMessage(request))
  }

  it should "return the correct initial state" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.checkArchiveState(HttpArchiveStateDisconnected)
  }

  it should "switch to a success state as soon as data comes in" in {
    val state = ProgressState.copy(contentInArchive = true)
    val result = mock[MediumProcessingResult]
    val helper = new HttpArchiveManagementActorTestHelper

    helper
      .stub(ProcessingStateTransitionData(None, None), state) { svc =>
        svc.handleResultAvailable(result, testActor, PropBufSize)
      }
      .triggerScan()
      .post(result)
    helper.checkArchiveState(HttpArchiveStateConnected)
  }

  it should "not answer a state request while loading data" in {
    implicit val timeout: Timeout = Timeout(100.millis)
    val helper = new HttpArchiveManagementActorTestHelper
    helper.triggerScan()

    val futState = helper.manager ? HttpArchiveStateRequest
    intercept[AskTimeoutException] {
      Await.result(futState, 10.seconds)
    }
  }

  it should "answer a state request when the state becomes available" in {
    val probe = TestProbe()
    val result = mock[MediumProcessingResult]
    val state = ProgressState.copy(contentInArchive = true)
    val helper = new HttpArchiveManagementActorTestHelper
    helper.stub(ProcessingStateTransitionData(None, None), state) { svc =>
      svc.handleResultAvailable(result, testActor, PropBufSize)
    }
      .triggerScan()
      .expectProcessingRequest()

    helper.manager.tell(HttpArchiveStateRequest, probe.ref)
    helper.manager ! HttpArchiveStateRequest
    helper.manager.tell(HttpArchiveStateRequest, probe.ref)
    helper post result
    val expState = HttpArchiveStateResponse(ArchiveName, HttpArchiveStateConnected)
    expectMsg(expState)
    probe.expectMsg(expState)
    expectNoMoreMsg(probe) // check that message was sent only once
  }

  it should "reset the set of pending archive state clients" in {
    val probe = TestProbe()
    val state = ProgressState.copy(contentInArchive = true)
    val helper = new HttpArchiveManagementActorTestHelper
    helper.stub(ProcessingStateTransitionData(None, None),
      state)(_.handleResultPropagated(SeqNo, PropBufSize))
      .triggerScan()
      .expectProcessingRequest()
    helper.manager.tell(HttpArchiveStateRequest, probe.ref)
    helper.post(MediumPropagated(SeqNo))
    probe.expectMsgType[HttpArchiveStateResponse]

    helper.post(MediumPropagated(SeqNo))
    expectNoMoreMsg(probe)
  }

  it should "return a server error state if the server could not be contacted" in {
    val helper = new HttpArchiveManagementActorTestHelper
    val exception = new IOException("Crashed")

    helper.stub((), ContentProcessingUpdateServiceImpl.InitialState)(_.processingDone())
      .initFailedArchiveResponse(exception)
      .triggerScan(initSuccessResponse = false)
      .checkArchiveState(HttpArchiveStateServerError(exception))
    verify(helper.updateService).processingDone()
  }

  it should "return a request failed state if the request was not successful" in {
    val helper = new HttpArchiveManagementActorTestHelper
    val status = StatusCodes.Unauthorized
    val response = HttpResponse(status = status)

    helper.stub((), ContentProcessingUpdateServiceImpl.InitialState)(_.processingDone())
      .initFailedArchiveResponse(FailedResponseException(response))
      .triggerScan(initSuccessResponse = false)
      .checkArchiveState(HttpArchiveStateFailedRequest(status))
    verify(helper.updateService).processingDone()
  }

  it should "forward a DownloadActorAlive notification to the monitoring actor" in {
    val aliveMsg = DownloadActorAlive(TestProbe().ref,
      MediaFileID(MediumID("testMediumURI", Some("settings.set")), "someFileUri"))
    val helper = new HttpArchiveManagementActorTestHelper

    helper.post(aliveMsg)
      .expectDownloadMonitoringMessage(aliveMsg)
  }

  it should "answer a GetMetaDataFileInfo message with a dummy response" in {
    val helper = new HttpArchiveManagementActorTestHelper

    helper.post(GetMetaDataFileInfo)
    expectMsg(MetaDataFileInfo(Map.empty, Set.empty, None))
  }

  /**
    * A test helper class managing all dependencies of a test actor instance.
    *
    * @param archiveConfig the archive configuration to be used
    */
  private class HttpArchiveManagementActorTestHelper(archiveConfig: HttpArchiveConfig = ArchiveConfig)
    extends StateTestHelper[ContentProcessingState, ContentProcessingUpdateService] {
    /** Mock for the update service. */
    override val updateService: ContentProcessingUpdateService = mock[ContentProcessingUpdateService]

    /** Test probe for the union media manager actor. */
    val probeUnionMediaManager: TestProbe = TestProbe()

    /** Test probe for the union meta data manager actor. */
    val probeUnionMetaDataManager: TestProbe = TestProbe()

    /** Test probe for the content processor actor. */
    val probeContentProcessor: TestProbe = TestProbe()

    /** Test probe for the meta data processor actor. */
    val probeMetaDataProcessor: TestProbe = TestProbe()

    /** Test probe for the medium info processor actor. */
    val probeMediumInfoProcessor: TestProbe = TestProbe()

    /** Test probe for the monitoring actor. */
    private val probeMonitoringActor = TestProbe()

    /** Test probe for the remove file actor. */
    private val probeRemoveActor = TestProbe()

    /** Test probe for the content propagation actor. */
    private val probeContentPropagationActor = TestProbe()

    /** Mock for the temp path generator. */
    private val pathGenerator = mock[TempPathGenerator]

    /** The actor simulating the download management actor. */
    private val downloadManagementActor = ForwardTestActor()

    /** The mock for the media downloader. */
    private val downloader = mock[MediaDownloader]

    /** A queue for recording the child actors that have been created. */
    private val childCreationQueue = new LinkedBlockingQueue[ChildActorCreation]

    /** The final configuration for the archive. */
    val config: HttpArchiveConfig = archiveConfig.copy(downloader = downloader)

    /** The actor to be tested. */
    val manager: TestActorRef[HttpArchiveManagementActor] = createTestActor()

    /**
      * Sends a message directly to the test actor.
      *
      * @param msg the message to be sent
      * @return this test helper
      */
    def send(msg: Any): HttpArchiveManagementActorTestHelper = {
      manager receive msg
      this
    }

    /**
      * Sends a message via the ! method to the test actor.
      *
      * @param msg the message to be sent
      * @return this test helper
      */
    def post(msg: Any): HttpArchiveManagementActorTestHelper = {
      manager ! msg
      this
    }

    /**
      * Sends a message to start a new scan to the test actor.
      *
      * @param stubProcStarts      flag whether processing start should be stubbed
      * @param initSuccessResponse flag whether the test request actor should
      *                            be configured to expect a successful request
      * @return this test helper
      */
    def triggerScan(stubProcStarts: Boolean = true, initSuccessResponse: Boolean = true):
    HttpArchiveManagementActorTestHelper = {
      if (stubProcStarts) {
        stub(true, ProgressState) { svc => svc.processingStarts() }
      }
      if (initSuccessResponse) {
        initSuccessArchiveResponse()
      }
      send(ScanAllMedia)
    }

    /**
      * Expects that a request to process the archive has been sent to the
      * content processor actor and returns the message.
      *
      * @return the request message
      */
    def expectProcessingRequest(): ProcessHttpArchiveRequest =
      probeContentProcessor.expectMsgType[ProcessHttpArchiveRequest]

    /**
      * Expects that no processing request is sent to the content processor
      * actor.
      *
      * @return this test helper
      */
    def expectNoProcessingRequest(): HttpArchiveManagementActorTestHelper = {
      probeContentProcessor.expectNoMessage(1.second)
      this
    }

    /**
      * Expects that a result was passed to the propagation actor.
      *
      * @param msg the propagation message
      * @return this test helper
      */
    def expectPropagation(msg: PropagateMediumResult): HttpArchiveManagementActorTestHelper = {
      probeContentPropagationActor.expectMsg(msg)
      this
    }

    /**
      * Prepares the mock request actor to return a successful response for a
      * request to the archive's content file.
      *
      * @return this test helper
      */
    def initSuccessArchiveResponse(): HttpArchiveManagementActorTestHelper =
      initArchiveContentResponse(Future.successful(createSuccessResponse()))

    /**
      * Prepares the mock request actor to return an exception response for a
      * request to the archive's content file.
      *
      * @param exception the exception to be returned as response
      * @return this test helper
      */
    def initFailedArchiveResponse(exception: Throwable): HttpArchiveManagementActorTestHelper =
      initArchiveContentResponse(Future.failed(exception))

    /**
      * Queries the current state from the test archive and compares it with
      * the expected state.
      *
      * @param expState the expected state
      * @return this test helper
      */
    def checkArchiveState(expState: HttpArchiveState): HttpArchiveManagementActorTestHelper = {
      post(HttpArchiveStateRequest)
      val stateResponse = expectMsgType[HttpArchiveStateResponse]
      stateResponse.archiveName should be(ArchiveName)
      stateResponse.state should be(expState)
      this
    }

    /**
      * Expects a message to be passed to the download monitoring actor.
      *
      * @param msg the expected message
      * @return this test helper
      */
    def expectDownloadMonitoringMessage(msg: Any): HttpArchiveManagementActorTestHelper = {
      probeMonitoringActor.expectMsg(msg)
      this
    }

    /**
      * Prepares the mock for the downloader to handle a download request for
      * the archive's main content file.
      *
      * @param result the result to answer the request
      * @return this test helper
      */
    private def initArchiveContentResponse(result: Future[Source[ByteString, Any]]):
    HttpArchiveManagementActorTestHelper = {
      when(downloader.downloadMediaFile(ArchiveConfig.contentPath)).thenReturn(result)
      this
    }

    /**
      * Creates the test actor.
      *
      * @return the test actor
      */
    private def createTestActor(): TestActorRef[HttpArchiveManagementActor] =
      TestActorRef(createProps())

    /**
      * Creates the properties for the test actor.
      *
      * @return creation Props for the test actor
      */
    private def createProps(): Props =
      Props(new HttpArchiveManagementActor(updateService, config, pathGenerator,
        probeUnionMediaManager.ref, probeUnionMetaDataManager.ref,
        probeMonitoringActor.ref, probeRemoveActor.ref)
        with ChildActorFactory {

        /**
          * @inheritdoc Checks creation properties and returns test probes for
          *             the child actors
          */
        override def createChildActor(p: Props): ActorRef = {
          val child = p.actorClass() match {
            case ClsContentProcessor =>
              p.args should have size 0
              probeContentProcessor.ref

            case ClsMediumInfoProcessor =>
              p.args should have size 0
              probeMediumInfoProcessor.ref

            case ClsMetaDataProcessor =>
              p.args should have size 0
              probeMetaDataProcessor.ref

            case ClsDownloadManagementActor =>
              p.args should be(List(config, pathGenerator, probeMonitoringActor.ref, probeRemoveActor.ref))
              downloadManagementActor

            case ClsContentPropagationActor =>
              p.args should be(List(probeUnionMediaManager.ref, probeUnionMetaDataManager.ref,
                ArchiveConfig.archiveName))
              probeContentPropagationActor.ref
          }
          childCreationQueue offer ChildActorCreation(p, child)
          child
        }
      })
  }

}


text:
package signature.chemistry;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class MoleculeWriter {

    public static void writeMolfile(String filename, Molecule molecule) {
        File file = new File(filename);
        try {
            writeToStream(new FileOutputStream(file), molecule);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void writeToStream(OutputStream stream, Molecule molecule) {
        try {
            BufferedWriter writer =
                new BufferedWriter(new OutputStreamWriter(stream));
            writeHeader(writer, molecule);
            for (int i = 0; i < molecule.getAtomCount(); i++) {
                writeAtom(writer, molecule, i);
            }
            for (int i = 0; i < molecule.getBondCount(); i++) {
                writeBond(writer, molecule, i);
            }
            writer.write("M  END");
            writer.newLine();
            writer.close();
        } catch (IOException ioe) {

        }
    }

    private static void writeHeader(
            BufferedWriter writer, Molecule molecule) throws IOException {
        writer.newLine();
        writer.write(" Writen by signature package");
        writer.newLine();
        writer.newLine();
        int a = molecule.getAtomCount();
        int b = molecule.getBondCount();
        writer.write(
                String.format("%3d%3d  0  0  0  0  0  0  0  0999 V2000", a, b));
        writer.newLine();
    }

    private static void writeAtom(
            BufferedWriter writer, Molecule molecule, int i) throws IOException {
        String empty3DCoords = "    0.0000    0.0000    0.0000 ";
        String emptyTail = " 0  0  0  0  0  0  0  0  0  0  0  0";
        String symbol = molecule.getSymbolFor(i);
        writer.write(empty3DCoords + String.format("%-3s", symbol) + emptyTail);
        writer.newLine();
    }

    private static void writeBond(
            BufferedWriter writer, Molecule molecule, int i) throws IOException {
        int f = molecule.getFirstInBond(i) + 1;
        int s = molecule.getSecondInBond(i) + 1;
        int o = molecule.getBondOrderAsInt(i);
        writer.write(String.format("%3d%3d%3d  0  0  0  0", f, s, o));
        writer.newLine();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.clz.tool

/**
  * Created by zhangming on 2017/4/4.
  */

import java.util.concurrent.TimeUnit
import org.openqa.selenium.chrome.{ChromeDriver, ChromeDriverService, ChromeOptions}
import org.openqa.selenium.remote.{CapabilityType, DesiredCapabilities}
import org.openqa.selenium.{By, WebDriver}
import sys.process._
import scala.util.Random

/**
  * 概要   :
  * 作者   : ming.zhang
  * 作成日 : 10/29/16.
  */
class ChromeBrowser {
  private var remoteWebDriver: ChromeDriver = null
  private var baseWindowHandle: String = null
  private val chromeOptions = new ChromeOptions()
  private val capabilities = DesiredCapabilities.chrome()
  private var isMobile: Boolean = false

  def init(): Unit = {
    val randomUserAgent = "python3 /Users/zhangming/Projects/taobao-tool/bin/random_useragent.py".!!

    println(s"randomUserAgent: $randomUserAgent")

    // configure chrome options
    chromeOptions.addArguments("--test-type")
    chromeOptions.addArguments("--no-sandbox")
    chromeOptions.addArguments("--ignore-certificate-errors")
    chromeOptions.addArguments("--disable-impl-side-painting")
    chromeOptions.addArguments("--dns-prefetch-disable")
    chromeOptions.addArguments("--incognito")
    chromeOptions.addArguments(s"--user-agent=$randomUserAgent");

    capabilities.setJavascriptEnabled(true)
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true)
    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions)

    capabilities.setCapability(
      ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,
      "/driver/chromeDriver"
    )
  }

  def isMobile(isMobile: Boolean): Unit = {
    this.isMobile = isMobile
  }

  def useProxy(ip: String, port: Int): Unit = {
    this.chromeOptions.addArguments(s"--proxy-server=$ip:$port")
  }

  def stop(): Unit = {
    remoteWebDriver.quit()
    remoteWebDriver = null
  }

  def start(): Unit = {
    if (this.isMobile) {
      chromeOptions.setExperimentalOption("mobileEmulation", Map("deviceName" -> "Mobile"))
    }

    // configure it as a desired capability
    capabilities.setJavascriptEnabled(true)
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true)
    capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions)

    remoteWebDriver = new ChromeDriver(this.capabilities)
    remoteWebDriver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS)
    baseWindowHandle = remoteWebDriver.getWindowHandle
  }

  def getCapability = this.capabilities

  def getOptions = this.chromeOptions

  def switchToNewWindow = {
    remoteWebDriver.switchTo.window(remoteWebDriver.getWindowHandles.toArray.last.asInstanceOf[String])
  }

  def findARandomLinkInCurrentPage = {
    val links = remoteWebDriver.findElements(By.cssSelector("a"))
    if (links != null) {
      val size = links.size()
      val randomIndex = Random.nextInt(size)
      links.get(randomIndex)
    } else {
      null
    }
  }

  def getLinksContain(keyword: String) = remoteWebDriver.findElements(By.cssSelector(s"a[href*='$keyword']"))

  def getDriver : WebDriver = {
    remoteWebDriver
  }
}


text:
package com.jme3.animation;

import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This class is intended as a UserData added to a Spatial that is referenced by a Track.
 * (ParticleEmitter for EffectTrack and AudioNode for AudioTrack)
 * It holds the list of tracks that are directly referencing the Spatial.
 *
 * This is used when loading a Track to find the cloned reference of a Spatial in the cloned model returned by the assetManager.
 *
 * @author Nehon
 */
public class TrackInfo implements Savable, JmeCloneable {

    ArrayList<Track> tracks = new ArrayList<Track>();

    public TrackInfo() {
    }

    public void write(JmeExporter ex) throws IOException {
        OutputCapsule c = ex.getCapsule(this);
        c.writeSavableArrayList(tracks, "tracks", null);
    }

    public void read(JmeImporter im) throws IOException {
        InputCapsule c = im.getCapsule(this);
        tracks = c.readSavableArrayList("tracks", null);
    }

    public ArrayList<Track> getTracks() {
        return tracks;
    }

    public void addTrack(Track track) {
        tracks.add(track);
    }

    @Override
    public Object jmeClone() {
        try {
            return super.clone();
        } catch( CloneNotSupportedException e ) {
            throw new RuntimeException("Error cloning", e);
        }
    }

    @Override
    public void cloneFields( Cloner cloner, Object original ) {
        this.tracks = cloner.clone(tracks);
    }
}


text:
<template name="afObjectField_semanticUI">
  {{#with afFieldLabelText name=this.name}}

{{this}}

  {{/with}}

    {{#if afFieldIsInvalid name=this.name}}

{{{afFieldMessage name=this.name}}}

    {{/if}}
    {{> afQuickFields quickFieldsAtts}}

</template>


text:
#include <stdlib.h>
#include <stdio.h>

/*
** A function to provide a command interface with gnuplot
*/
int gnuplot(const char *gnucommand)
{
  char syscommand[1024];

  /* Build the gnuplot command: leaving gnuplot running after the
     program finishes execution. */
  sprintf(syscommand, "echo \"%s\" | gnuplot -persist", gnucommand);

  /* Use a system call to run gnuplot */
  return system(syscommand);
}


text:
{% extends "v9/layoutv9.html" %}

{% set title = "Water abstraction licence" %}

{% block page_title %}
    {{title}} - GOV.UK
{% endblock %}

{% block content %}

      BETA
      This is an BETA prototype, details may be missing whilst we build the service. Your feedback will help us improve this service.

Your services

Abstraction licences

          Sign out
          Change password

  All water abstraction licences

{% block searchform %}

  {% block emailfield %}

      User email address
      View licence list by user account.
      <input type="text" class="form-control form-control--block" name="emailAddress" id="emailAddress" />

  {% endblock %}

      Search licences
      Search by licence name or number.
      <input type="text" class="form-control form-control--block" name="licenseNumber" id="licenseNumber" />

    <input id="searchButton" class="button button button-license-search" type="submit" value="Search">

{% endblock %}

          Licence serial number ▾

          User defined name

03/28/60/0002

H2GO Power

View

03/28/60/0003

West field

View

03/28/60/0004

Bridge Farm

View

03/28/60/0005

Valley's Water

View

03/28/60/0002

Water License

View

03/28/60/0003

Daisy Farm

View

03/28/60/0004

Public 12845

View

03/28/60/0005

Water Company

View

{% endblock %}


text:
id: 5900f3a61000cf542c50feb9
challengeType: 5
isHidden: false
title: 'Problem 58: Spiral primes'
forumTopicId: 302169
---

## Description

Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.

  37 36 35 34 33 32 31

  38 17 16 15 14 13 30

  39 18  5  4  3 12 29

  40 19  6  1  2 11 28

  41 20  7  8  9 10 27

  42 21 22 23 24 25 26

  43 44 45 46 47 48 49

It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?

## Instructions

## Tests

```yml
tests:
  - text: <code>spiralPrimes()</code> should return a number.
    testString: assert(typeof spiralPrimes() === 'number');
  - text: <code>spiralPrimes()</code> should return 26241.
    testString: assert.strictEqual(spiralPrimes(), 26241);

```

## Challenge Seed

```js
function spiralPrimes() {
  // Good luck!
  return true;
}

spiralPrimes();
```

## Solution

```js
// solution required
```


text:
<?xml version="1.0"?>
<!--

    Copyright 2005-2015 The Kuali Foundation

    Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.kuali.rice</groupId>
    <artifactId>rice-it</artifactId>
   <version>2.5.3.1506.2-kckualico-SNAPSHOT</version>
  </parent>
  <artifactId>rice-it-vc</artifactId>
  <name>Rice Integration Test Version Compatibility</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.kuali.rice</groupId>
      <version>${project.version}</version>
      <artifactId>rice-core-impl</artifactId>
    </dependency>
    <dependency>
      <groupId>org.kuali.rice</groupId>
      <version>${project.version}</version>
      <artifactId>rice-it-internal-tools</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>${mysql.jdbc.artifactId}</artifactId>
    </dependency>
    <dependency>
      <groupId>com.predic8</groupId>
      <artifactId>soa-model-core</artifactId>
      <version>${soa.model.core.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <exclusions>
        <exclusion>
          <artifactId>commons-logging</artifactId>
          <groupId>commons-logging</groupId>
        </exclusion>
      </exclusions>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
<?php include_once __DIR__ . '/loged_test.php';?>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="shortcut icon" href="images/favicon.ico">
    <title>BuscaRep</title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="../vendors/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet">

    <link href="../vendors/normalize-css/normalize.css" rel="stylesheet">
    <link href="../vendors/ion.rangeSlider/css/ion.rangeSlider.css" rel="stylesheet">
    <link href="../vendors/ion.rangeSlider/css/ion.rangeSlider.skinFlat.css" rel="stylesheet">

    <link href="../vendors/mjolnic-bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css" rel="stylesheet">

    <link href="../vendors/cropper/dist/cropper.min.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">

  BuscaRep

                Bem Vindo,

Usuário

Menu

 República

 Nova República+

Sua República

Galeria

Avaliações

Caixa de Menssagem

                    Usuário

 Perfil

                        Opções

Ajuda

 Log Out

  4

                          Usuário
                          1 min ago

                          Se fudeu...

                          Usuário
                          3 mins ago

                          Sua mãe é minha...

                          Usuário
                          10 mins ago

                          Why so serious?!

                          Usuário
                          1 mounth ago

                          Me fudi no Peruano...

                          See All Alerts

RepúblicaEditando

                    <form class="form-horizontal form-label-left">

                        Imagem

                			<image id="profileImage" src="images/user.png" />

                			<input id="image" class="form-control col-md-7 col-xs-12" type="file" name="profile_photo" placeholder="Photo" required="" capture>

                        Tipo de República

                          <select id="repType" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2" name="repType">
                            <option> Escolha um tipo </option>
                            <option>Masculina</option>
                            <option>Feminina</option>
                            <option>Masculina / Feminina</option>
                          </select>

                        Rua

                          <input id="street" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2" name="street" placeholder="Nome da Rua" type="text">

                        Bairro

                          <input id="neighborhood" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2" name="neighborhood" placeholder="Nome do Bairro" type="text">

                        Número

                          <input id="number" class="form-control col-md-7 col-xs-12" name="number" placeholder="Número da Residência" type="number" step=1>

                        Complemento

                          <input id="complement" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="2" name="complement" placeholder="Informações Adicionais" type="text">

                        E-mail

                          <input type="email" id="email" name="email" placeholder="Endereço de e-mail" class="form-control col-md-7 col-xs-12">

                        Telefone Fixo

                          <input type="text" id="phone" name:"phone" class="form-control" placeholder="(__) ____-____" data-inputmask="'mask' : '(99) 9999-9999'">

                        Celular

                          <input type="text" id="cellphone" name:"cellphone" class="form-control" placeholder="(__) _____-____" data-inputmask="'mask' : '(99) 99999-9999'">

                        Quantidade de Vagas

                          <input id="slots" class="form-control col-md-7 col-xs-12" name="slots" placeholder="Número de Vagas"  type="number" step=1>

                        Serviços e Gerais

                              <input type="checkbox" class="flat" checked="checked"> TV a Cabo

                              <input type="checkbox" class="flat"> Lavanderia

                              <input type="checkbox" class="flat" checked="checked"> Empregada

                              <input type="checkbox" class="flat" checked="checked"> Jardineiro

                              <input type="checkbox" class="flat" checked="checked"> Salão de Jogos (Bilhar, Pebolin e etc)

                              <input type="checkbox" class="flat" checked="checked"> Consoles (Playstation, Xbox e etc)

                              <input type="checkbox" class="flat" checked="checked"> Piscina

                              <input type="checkbox" class="flat" checked="checked"> Área de Churrasco / Churrasqueira

                        Locadora

                          <input id="office" class="form-control col-md-7 col-xs-12" data-validate-length-range="6" data-validate-words="1" name="office" placeholder="Nome da empresa / pessoa locadora" type="text">

                      Outros (Nomes de Estabelecimentos Próximos) :
                          <textarea id="message" class="form-control" name="message" data-parsley-trigger="keyup" data-parsley-minlength="20" data-parsley-maxlength="100" data-parsley-
                          data-parsley-validation-threshold="10"></textarea>

                          <button type="submit" class="btn btn-primary">Cancel</button>
                          <button type="submit" class="btn btn-success">Submit</button>

                    </form>

           Sistema BuscaRep - Developed by Antares IT


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

namespace InfoBridge.SuperLinq.Core.Projection
{
    public class DateTimeConverter : IDateTimeConverter
    {
        /// <summary>
        /// Convert the SuperOffice database time to UTC time
        /// </summary>
        /// <param name="fromConvertTimeUTC"></param>
        /// <returns></returns>
        public DateTime ConvertFromTimeZone(DateTime fromConvertTimeUTC)
        {
            //convert the UTC time to local time first
            DateTime fromConvertTime = fromConvertTimeUTC.ToLocalTime();

            if (fromConvertTime == DateTime.MinValue || fromConvertTime == DateTime.MaxValue)
            {
                return fromConvertTime;
            }
            int tZOffset = GetTenantDataBaseTimeZone().GetTZOffset(fromConvertTime);
            DateTime convertedTime = fromConvertTime.AddMinutes(-((double)(tZOffset * 1)));

            //create utc
            return new DateTime(convertedTime.Ticks, DateTimeKind.Utc);
        }

        private TimeZoneData GetTenantDataBaseTimeZone()
        {
            if (SoContext.CurrentPrincipal == null) {
                throw new Exception("Unable to retrieve timezonedata from current NetServer session. No current principal found.");
            }
            return TimeConverter.GetTimeZoneDataById(SoContext.CurrentPrincipal.TimeZone);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
    xmlns:script="http://www.mulesoft.org/schema/mule/scripting"
    xmlns:test="http://www.mulesoft.org/schema/mule/test"
    xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
        http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
        http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
        http://www.mulesoft.org/schema/mule/test http://www.mulesoft.org/schema/mule/test/current/mule-test.xsd">

    <flow name="add-attachments">
        <vm:inbound-endpoint path="add-attachments.in" exchange-pattern="request-response" />
        <script:transformer>
            <script:script engine="groovy">
                def filePath = message.getInboundProperty('pdfFilePath')
                def file = new File(filePath)
                message.addOutboundAttachment(file.name,
                                              file,
                                              'application/pdf')
            </script:script>
        </script:transformer>
    </flow>

    <vm:endpoint name="email-orders" path="email.orders.in" exchange-pattern="one-way" />
    <vm:endpoint name="pdf-orders" path="pdf-order-handler.in" exchange-pattern="one-way" />

    <!--<start id="lis_02_eval_attach"/>-->
    <flow name="email-order-processor">
        <inbound-endpoint ref="email-orders" /><!--<co id="lis_02_eval_attach_1"/>-->
        <expression-transformer
                    expression="#[message.inboundAttachments.values()]" /><!--<co id="lis_02_eval_attach_2"/>-->
        <collection-splitter /><!--<co id="lis_02_eval_attach_3"/>-->
        <outbound-endpoint ref="pdf-orders" /><!--<co id="lis_02_eval_attach_4"/>-->
    </flow>
    <!--<end id="lis_02_eval_attach"/>-->

    <flow name="pdf-order-handler">
        <inbound-endpoint ref="pdf-orders" />
        <test:component />
    </flow>
</mule>


text:
from social.p3 import quote
from social.utils import sanitize_redirect, user_is_authenticated, \
                         user_is_active

def do_auth(strategy, redirect_name='next'):
    # Save any defined next value into session
    data = strategy.request_data(merge=False)
    # Save extra data into session.
    for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []):
        if field_name in data:
            strategy.session_set(field_name, data[field_name])

    if redirect_name in data:
        # Check and sanitize a user-defined GET/POST next field value
        redirect_uri = data[redirect_name]
        if strategy.setting('SANITIZE_REDIRECTS', True):
            redirect_uri = sanitize_redirect(strategy.request_host(),
                                             redirect_uri)
        strategy.session_set(
            redirect_name,
            redirect_uri or strategy.setting('LOGIN_REDIRECT_URL')
        )
    return strategy.start()

def do_complete(strategy, login, user=None, redirect_name='next',
                *args, **kwargs):
    # pop redirect value before the session is trashed on login()
    data = strategy.request_data()
    redirect_value = strategy.session_get(redirect_name, '') or \
                     data.get(redirect_name, '')

    is_authenticated = user_is_authenticated(user)
    user = is_authenticated and user or None
    default_redirect = strategy.setting('LOGIN_REDIRECT_URL')
    url = default_redirect
    login_error_url = strategy.setting('LOGIN_ERROR_URL') or \
                      strategy.setting('LOGIN_URL')
    if strategy.session_get('partial_pipeline'):
        idx, backend, xargs, xkwargs = strategy.from_session(
            strategy.session_pop('partial_pipeline')
        )
        if backend == strategy.backend_name:
            kwargs = kwargs.copy()
            kwargs.setdefault('user', user)
            kwargs.update(xkwargs)
            user = strategy.continue_pipeline(pipeline_index=idx,
                                              *xargs, **xkwargs)
        else:
            strategy.clean_partial_pipeline()
            user = strategy.complete(user=user, request=strategy.request,
                                     *args, **kwargs)
    else:
        user = strategy.complete(user=user, request=strategy.request,
                                 *args, **kwargs)

    if strategy.is_response(user):
        return user

    if is_authenticated:
        if not user:
            url = redirect_value or default_redirect
        else:
            url = redirect_value or \
                  strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \
                  default_redirect
    elif user:
        if user_is_active(user):
            # catch is_new/social_user in case login() resets the instance
            is_new = getattr(user, 'is_new', False)
            social_user = user.social_user
            login(strategy, user)
            # store last login backend name in session
            strategy.session_set('social_auth_last_login_backend',
                                 social_user.provider)

            # Remove possible redirect URL from session, if this is a new
            # account, send him to the new-users-page if defined.
            new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL')
            if new_user_redirect and is_new:
                url = new_user_redirect
            else:
                url = redirect_value or default_redirect
        else:
            url = strategy.setting('INACTIVE_USER_URL', login_error_url)
    else:
        url = login_error_url

    if redirect_value and redirect_value != url:
        redirect_value = quote(redirect_value)
        url += ('?' in url and '&' or '?') + \
               '%s=%s' % (redirect_name, redirect_value)
    if url == '/':
        url = '/' + user.username
    return strategy.redirect(url)

def do_disconnect(strategy, user, association_id=None, redirect_name='next'):
    strategy.disconnect(user=user, association_id=association_id)
    data = strategy.request_data()
    return strategy.redirect(data.get(redirect_name, '') or
                             strategy.setting('DISCONNECT_REDIRECT_URL') or
                             strategy.setting('LOGIN_REDIRECT_URL'))


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Profile.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.WindowsAzure.Commands.Common;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Profile
{
    [Cmdlet(VerbsLifecycle.Enable, "AzureRmDataCollection", SupportsShouldProcess = true)]
    public class EnableAzureRmDataCollectionCommand : AzureRMCmdlet
    {
        protected override void BeginProcessing()
        {
            // do not call begin processing there is no context needed for this cmdlet
        }

        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Resources.EnableDataCollection, Resources.DataCollectionEnabledWarning,
                string.Empty))
            {

                SetDataCollectionProfile(true);
            }
        }

        protected void SetDataCollectionProfile(bool enable)
        {
            var profile = _dataCollectionProfile;
            profile.EnableAzureDataCollection = enable;
            var session = AzureSession.Instance;
            DataCollectionController.WritePSDataCollectionProfile(session, profile);
            AzureSession.Instance.RegisterComponent(DataCollectionController.RegistryKey, () => DataCollectionController.Create(profile), true);
        }
    }
}


text:
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.cl._
import Array._
import scala.math._
import org.apache.spark.rdd._
import java.net._

object SparkSimple {
    def main(args : Array[String]) {
        if (args.length < 1) {
            println("usage: SparkSimple cmd")
            return;
        }

        val cmd = args(0)

        if (cmd == "convert") {
            convert(args.slice(1, args.length))
        } else if (cmd == "run") {
            run_simple(args.slice(2, args.length), args(1).toBoolean)
        } else if (cmd == "check") {
            val correct : Array[Double] = run_simple(args.slice(1, args.length), false)
            val actual : Array[Double] = run_simple(args.slice(1, args.length), true)
            assert(correct.length == actual.length)
            for (i <- 0 until correct.length) {
                val a : Double = correct(i)
                val b : Double = actual(i)
                var error : Boolean = false

                if (a != b) {
                    System.err.println(i + " expected " + a + " but got " + b)
                    error = true
                }

                if (error) System.exit(1)
            }
            System.err.println("PASSED")
        }
    }

    def get_spark_context(appName : String) : SparkContext = {
        val conf = new SparkConf()
        conf.setAppName(appName)

        val localhost = InetAddress.getLocalHost
        conf.setMaster("spark://" + localhost.getHostName + ":7077") // 7077 is the default port

        return new SparkContext(conf)
    }

    def run_simple(args : Array[String], useSwat : Boolean) : Array[Double] = {
        if (args.length != 1) {
            println("usage: SparkSimple run input-path");
            return new Array[Double](0);
        }
        val sc = get_spark_context("Spark Simple");

        val inputPath = args(0)
        val inputs_raw : RDD[Array[Double]] = sc.objectFile[Array[Double]](inputPath).cache
        val inputs = if (useSwat) CLWrapper.cl[Array[Double]](inputs_raw) else inputs_raw

        val outputs : RDD[Double] = inputs.map(v => {
            var i = 0
            var sum = 0.0
            while (i < v.length) {
                sum += v(i)
                i += 1
            }
            sum
          })
        val outputs2 : Array[Double] = outputs.collect
        var i = 0
        while (i < 10) {
            System.err.println(outputs2(i))
            i += 1
        }
        System.err.println("...")
        sc.stop
        outputs2
    }

    def convert(args : Array[String]) {
        if (args.length != 2) {
            println("usage: SparkSimple convert input-dir output-dir");
            return
        }
        val sc = get_spark_context("Spark KMeans Converter");

        val inputDir = args(0)
        var outputDir = args(1)
        val input = sc.textFile(inputDir)

        val converted = input.map(line => {
            val tokens : Array[String] = line.split(" ")
            val arr : Array[Double] = new Array[Double](tokens.length)
            for (i <- 0 until tokens.length) {
                arr(i) = tokens(i).toDouble
            }
            arr
        })
        converted.saveAsObjectFile(outputDir)
    }
}


text:
@class XPhoto;

@protocol XPhotoDelegate <NSObject>

@optional
- (void)photoCompleteSelected:(XPhoto *)x_Photo image:(UIImage *)image sourceType:(UIImagePickerControllerSourceType)sourceType;
- (void)photoFailureSelected:(XPhoto *)x_Photo;

@end

@interface XPhoto : NSObject

typedef void (^XPhotoSelectedCompleteBlock)(XPhoto *x_Photo, UIImage *image, UIImagePickerControllerSourceType sourceType);
typedef void (^XPhotoSelectedFailureBlock)(XPhoto *x_Photo);

@property (nonatomic, weak) id<XPhotoDelegate> delegate;
@property (nonatomic, assign) BOOL shouldSaveToAlbum;
@property (nonatomic, assign) BOOL allowEdit;

- (void)selectPhotoInViewController:(UIViewController *)viewController
                              title:(NSString *)title
                  cancelButtonTitle:(NSString *)cancelButtonTitle
                  cameraButtonTitle:(NSString *)cameraButtonTitle
              localAlbumButtonTitle:(NSString *)localAlbumButtonTitle
         photoCompleteSelectedBlock:(XPhotoSelectedCompleteBlock)selectedCompleteBlock
          photoFailureSelectedBlock:(XPhotoSelectedFailureBlock)selectedFailureBlock;

@end


text:
using Xunit;

namespace Yaapii.Atoms.Enumerable.Tests
{
    public sealed class SkippedTest
    {
        [Fact]
        public void SkipIterable()
        {
            Assert.True(
                new Text.Joined(
                    ", ",
                    new Skipped<string>(
                        new ManyOf<string>("one", "two", "three", "four"),
                        2
                    )
                ).AsString() == "three, four");
        }
    }
}


text:
We love pull requests from everyone. By participating in this project, you agree
to abide by its [code of conduct].

[code of conduct]: https://github.com/calleerlandsson/pick.vim/blob/master/CODE_OF_CONDUCT.md

## Contributing

- Fork and clone the repo.
- Make your changes.
- Update `README.md` in accordance to your changes.
- Submit a pull request on GitHub.

At this point you're waiting on us. We like to at least comment on, if not
accept, pull requests within three business days (and, typically, one business
day). We may suggest some changes or improvements or alternatives.


text:
package com.onboard.service.collaboration;

import java.util.Date;
import java.util.List;

import com.onboard.domain.mapper.model.CommentExample;
import com.onboard.domain.model.Comment;
import com.onboard.domain.model.type.Commentable;
import com.onboard.service.base.BaseService;

/**
 * {@link Comment}服务接口
 *
 * @author yewei
 *
 */
public interface CommentService extends BaseService<Comment, CommentExample> {

    /**
     * 获取某一对象的评论数量
     *
     * @param attachType
     * @param attachId
     * @return
     */
    public int getCountOfCommentsByTopic(String attachType, int attachId);

    /**
     * 获取某一个对象的所有评论
     *
     * @param attachType
     * @param attachId
     * @param start
     * @param limit
     * @return
     */
    public List<Comment> getCommentsByTopic(String attachType, int attachId, int start, int limit);

    /**
     * 获取单个评论的对象信息
     *
     * @param targetType
     * @param id
     * @return
     */
    public Commentable getCommentTarget(String targetType, int id);

    /**
     * 获取单个评论的对象名称
     *
     * @param targetType
     * @param id
     * @return
     */
    public String getCommentTargetName(String targetType, int id);

    /**
     * 获取某一个对象的所有评论
     *
     * @param commentable
     * @param start
     * @param limit
     */
    void fillCommentable(Commentable commentable, int start, int limit);

    /**
     * 复制评论
     *
     */
    public void copyComments(Commentable oldItem, Commentable newItem);

    /**
     * 根据type和id删除comment
     *
     * @param type
     * @param id
     */
    public void deleteCommentByAttachTypeAndId(String type, int id);

    public void relocateComment(Commentable item, int projectId);

    /***
     * @author Chenlong
     * @param companyId
     * @param since
     * @param until
     * @return
     */
    List<Comment> getCommentsByCompanyIdBetweenDates(int companyId, Date since, Date until);
}


text:
var common = require('../common');
var assert = require('assert');

common.globalCheck = false;
global.gc = 42;  // Not a valid global unless --expose_gc is set.
assert.deepEqual(common.leakedGlobals(), ['gc']);


text:
package general;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ClassSpy {

    private Class<?> c;

    public ClassSpy(Class<?> c) {
        this.c = c;
    }

    public List<Field> getFields() {
        List<Field> fList = new ArrayList<Field>();

        // does not get the private members
        Field[] dummy = c.getFields();
        for (Field f : dummy) {
            fList.add(f);
        }

        // get the private members
        dummy = c.getDeclaredFields();
        for (Field f : dummy) {
            if (fList.contains(f) == false) {
                fList.add(f);
            }
        }

        return fList;
    }

    public List<Method> getMethods() {
        List<Method> mList = new ArrayList<Method>();

        // does not get the private members
        Method[] dummy = c.getMethods();
        for (Method m : dummy) {
            mList.add(m);
        }

        // get the private members
        dummy = c.getDeclaredMethods();
        for (Method m : dummy) {
            if (mList.contains(m) == false) {
                mList.add(m);
            }
        }

        return mList;
    }

    public List<Constructor<?>> getConstructors() {
        List<Constructor<?>> cList = new ArrayList<Constructor<?>>();

        // gets all
        Constructor<?>[] dummy = c.getDeclaredConstructors();
        for (Constructor<?> c : dummy) {
            cList.add(c);
        }

        return cList;
    }

    public Package getPackage() {
        return c.getPackage();
    }

}


text:
package main

func f() {
    return
}

func main() {
    // Non lvalue in assignment
    "literally"--
}


text:
package br.ufpe.cin.cloud.mapeamento.selecao.controlador;

import org.apache.log4j.Logger;
import static org.junit.Assert.*;
import org.junit.Test;

/**
 * Representa a implementação dos testes unitários da classe {@link ControladorEngenhariaDeSoftwareEmpirica}.
 *
 * @author emanoel.barreiros
 * @created 24/07/2014 - 18:29:30
 */
public class ControladorEngenhariaDeSoftwareEmpiricaTest {

	/**
	 * Representa o mecanismo de log da classe.
	 */
	private static Logger LOG = Logger
			.getLogger(ControladorEngenhariaDeSoftwareEmpiricaTest.class.getName());

	private ControladorEngenhariaDeSoftwareEmpirica ctrl = new ControladorEngenhariaDeSoftwareEmpirica();

	/**
	 * Representa a implementação de testes unitários do método que realiza o parser do arquivo bibtex das referencias.
	 */
	@Test
	public void testExecutarDiagnosticoBibTexArquivosSelecionados() {
		try {
			ctrl.executarDiagnosticoBibTexArquivosSelecionados();
		} catch (Exception e) {
			LOG.error("Deveria ter executado o teste testExecutarDiagnosticoBibTexArquivosSelecionados sem falhas", e);
			fail("Falhou ao executar o teste testExecutarDiagnosticoBibTexArquivosSelecionados");
		}
	}

	/**
	 * Representa a implementação de testes unitários do método que realiza o parser do arquivo bibtex das referencias.
	 */
	@Test
	public void testTratarBibTexArquivosSelecionados() {
		try {
			ctrl.tratarBibTexArquivosSelecionados();
		} catch (Exception e) {
			LOG.error("Deveria ter executado o teste testTratarBibTexArquivosSelecionados sem falhas", e);
			fail("Falhou ao executar o teste testTratarBibTexArquivosSelecionados");
		}
	}

}


text:
//
//  PlotItem.m
//  CorePlotGallery
//
//  Created by Jeff Buck on 9/4/10.
//  Copyright 2010 Jeff Buck. All rights reserved.
//

#import "PlotGallery.h"

#import <tgmath.h>

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
// For IKImageBrowser
#import <Quartz/Quartz.h>
#endif

NSString *const kDemoPlots      = @"Demos";
NSString *const kPieCharts      = @"Pie Charts";
NSString *const kLinePlots      = @"Line Plots";
NSString *const kBarPlots       = @"Bar Plots";
NSString *const kFinancialPlots = @"Financial Plots";

@implementation PlotItem

@synthesize defaultLayerHostingView;
@synthesize graphs;
@synthesize section;
@synthesize title;

+(void)registerPlotItem:(id)item
{
    NSLog(@"registerPlotItem for class %@", [item class]);

    Class itemClass = [item class];

    if ( itemClass ) {
        // There's no autorelease pool here yet...
        PlotItem *plotItem = [[itemClass alloc] init];
        if ( plotItem ) {
            [[PlotGallery sharedPlotGallery] addPlotItem:plotItem];
            [plotItem release];
        }
    }
}

-(id)init
{
    if ( (self = [super init]) ) {
        defaultLayerHostingView = nil;
        graphs                  = [[NSMutableArray alloc] init];
        section                 = nil;
        title                   = nil;
    }

    return self;
}

-(void)addGraph:(CPTGraph *)graph toHostingView:(CPTGraphHostingView *)layerHostingView
{
    [graphs addObject:graph];

    if ( layerHostingView ) {
        layerHostingView.hostedGraph = graph;
    }
}

-(void)addGraph:(CPTGraph *)graph
{
    [self addGraph:graph toHostingView:nil];
}

-(void)killGraph
{
    // Remove the CPTLayerHostingView
    if ( defaultLayerHostingView ) {
        [defaultLayerHostingView removeFromSuperview];

        defaultLayerHostingView.hostedGraph = nil;
        [defaultLayerHostingView release];
        defaultLayerHostingView = nil;
    }

    [cachedImage release];
    cachedImage = nil;

    [graphs removeAllObjects];

    [[CPTAnimation sharedInstance] removeAllAnimationOperations];
}

-(void)dealloc
{
    [self killGraph];
    [title release];
    [section release];

    [super dealloc];
}

// override to generate data for the plot if needed
-(void)generateData
{
}

-(NSComparisonResult)titleCompare:(PlotItem *)other
{
    NSComparisonResult comparisonResult = [self.section caseInsensitiveCompare:other.section];

    if ( comparisonResult == NSOrderedSame ) {
        comparisonResult = [self.title caseInsensitiveCompare:other.title];
    }

    return comparisonResult;
}

-(void)setTitleDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
    graph.title = title;
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.color                = [CPTColor grayColor];
    textStyle.fontName             = @"Helvetica-Bold";
    textStyle.fontSize             = round(bounds.size.height / (CGFloat)20.0);
    graph.titleTextStyle           = textStyle;
    graph.titleDisplacement        = CGPointMake( 0.0f, round(bounds.size.height / (CGFloat)18.0) ); // Ensure that title displacement falls on an integral pixel
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
}

-(void)setPaddingDefaultsForGraph:(CPTGraph *)graph withBounds:(CGRect)bounds
{
    CGFloat boundsPadding = round(bounds.size.width / (CGFloat)20.0); // Ensure that padding falls on an integral pixel

    graph.paddingLeft = boundsPadding;

    if ( graph.titleDisplacement.y > 0.0 ) {
        graph.paddingTop = graph.titleDisplacement.y * 2;
    }
    else {
        graph.paddingTop = boundsPadding;
    }

    graph.paddingRight  = boundsPadding;
    graph.paddingBottom = boundsPadding;
}

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE

-(UIImage *)image
{
    if ( cachedImage == nil ) {
        CGRect imageFrame = CGRectMake(0, 0, 400, 300);
        UIView *imageView = [[UIView alloc] initWithFrame:imageFrame];
        [imageView setOpaque:YES];
        [imageView setUserInteractionEnabled:NO];

        [self renderInView:imageView withTheme:nil animated:NO];

        CGSize boundsSize = imageView.bounds.size;

        if ( UIGraphicsBeginImageContextWithOptions ) {
            UIGraphicsBeginImageContextWithOptions(boundsSize, YES, 0.0);
        }
        else {
            UIGraphicsBeginImageContext(boundsSize);
        }

        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextSetAllowsAntialiasing(context, true);

        for ( UIView *subView in imageView.subviews ) {
            if ( [subView isKindOfClass:[CPTGraphHostingView class]] ) {
                CPTGraphHostingView *hostingView = (CPTGraphHostingView *)subView;
                CGRect frame                     = hostingView.frame;

                CGContextSaveGState(context);

                CGContextTranslateCTM(context, frame.origin.x, frame.origin.y + frame.size.height);
                CGContextScaleCTM(context, 1.0, -1.0);
                [hostingView.hostedGraph layoutAndRenderInContext:context];

                CGContextRestoreGState(context);
            }
        }

        CGContextSetAllowsAntialiasing(context, false);

        cachedImage = UIGraphicsGetImageFromCurrentImageContext();
        [cachedImage retain];
        UIGraphicsEndImageContext();

        [imageView release];
    }

    return cachedImage;
}

#else // OSX

-(NSImage *)image
{
    if ( cachedImage == nil ) {
        CGRect imageFrame = CGRectMake(0, 0, 400, 300);

        NSView *imageView = [[NSView alloc] initWithFrame:NSRectFromCGRect(imageFrame)];
        [imageView setWantsLayer:YES];

        [self renderInView:imageView withTheme:nil animated:NO];

        CGSize boundsSize = imageFrame.size;

        NSBitmapImageRep *layerImage = [[NSBitmapImageRep alloc]
                                        initWithBitmapDataPlanes:NULL
                                                      pixelsWide:boundsSize.width
                                                      pixelsHigh:boundsSize.height
                                                   bitsPerSample:8
                                                 samplesPerPixel:4
                                                        hasAlpha:YES
                                                        isPlanar:NO
                                                  colorSpaceName:NSCalibratedRGBColorSpace
                                                     bytesPerRow:(NSInteger)boundsSize.width * 4
                                                    bitsPerPixel:32];

        NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:layerImage];
        CGContextRef context             = (CGContextRef)[bitmapContext graphicsPort];

        CGContextClearRect( context, CGRectMake(0.0, 0.0, boundsSize.width, boundsSize.height) );
        CGContextSetAllowsAntialiasing(context, true);
        CGContextSetShouldSmoothFonts(context, false);
        [imageView.layer renderInContext:context];
        CGContextFlush(context);

        cachedImage = [[NSImage alloc] initWithSize:NSSizeFromCGSize(boundsSize)];
        [cachedImage addRepresentation:layerImage];
        [layerImage release];

        [imageView release];
    }

    return cachedImage;
}

#endif

-(void)applyTheme:(CPTTheme *)theme toGraph:(CPTGraph *)graph withDefault:(CPTTheme *)defaultTheme
{
    if ( theme == nil ) {
        [graph applyTheme:defaultTheme];
    }
    else if ( ![theme isKindOfClass:[NSNull class]] ) {
        [graph applyTheme:theme];
    }
}

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else
-(void)setFrameSize:(NSSize)size
{
}

#endif

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
-(void)renderInView:(UIView *)hostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated
#else
-(void)renderInView:(NSView *)hostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated
#endif
{
    [self killGraph];

    defaultLayerHostingView = [(CPTGraphHostingView *)[CPTGraphHostingView alloc] initWithFrame:hostingView.bounds];

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
    defaultLayerHostingView.collapsesLayers = NO;
    [defaultLayerHostingView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
#else
    [defaultLayerHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
#endif
    [defaultLayerHostingView setAutoresizesSubviews:YES];

    [hostingView addSubview:defaultLayerHostingView];
    [self generateData];
    [self renderInLayer:defaultLayerHostingView withTheme:theme animated:animated];
}

-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated
{
    NSLog(@"PlotItem:renderInLayer: Override me");
}

-(void)reloadData
{
    for ( CPTGraph *g in graphs ) {
        [g reloadData];
    }
}

#pragma mark -
#pragma mark IKImageBrowserItem methods

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
#else

-(NSString *)imageUID
{
    return self.title;
}

-(NSString *)imageRepresentationType
{
    return IKImageBrowserNSImageRepresentationType;
}

-(id)imageRepresentation
{
    return [self image];
}

-(NSString *)imageTitle
{
    return self.title;
}

/*
 * - (NSString*)imageSubtitle
 * {
 *  return graph.title;
 * }
 */

#endif

@end


text:
#include "include/vk_conv.h"
#include "include/vk_device.h"
#include "include/vk_instance.h"
#include "include/vk_memory.h"
#include "include/vk_physical_device.h"
#include "include/vk_pipeline_cache.h"
#include "palAutoBuffer.h"

#include "include/binary_cache_serialization.h"

namespace vk
{

// =====================================================================================================================
PipelineCache::PipelineCache(
    const Device*           pDevice,
    ShaderCache*            pShaderCaches,
    PipelineBinaryCache*    pBinaryCache
    )
    :
    m_pDevice(pDevice),
    m_pBinaryCache(pBinaryCache)
{
    memcpy(m_shaderCaches, pShaderCaches, sizeof(m_shaderCaches[0]) * pDevice->NumPalDevices());
    memset(m_shaderCaches + pDevice->NumPalDevices(),
           0,
           sizeof(m_shaderCaches[0]) * (MaxPalDevices - pDevice->NumPalDevices()));
}

// =====================================================================================================================
PipelineCache::~PipelineCache()
{
    for (uint32_t i = 0; i < m_pDevice->NumPalDevices(); i++)
    {
        m_shaderCaches[i].Destroy(m_pDevice->GetCompiler(i));
    }
}

// =====================================================================================================================
VkResult PipelineCache::Create(
    Device*                          pDevice,
    const VkPipelineCacheCreateInfo* pCreateInfo,
    const VkAllocationCallbacks*     pAllocator,
    VkPipelineCache*                 pPipelineCache)
{
    VkResult                result           = VK_SUCCESS;
    const RuntimeSettings&  settings         = pDevice->GetRuntimeSettings();
    uint32_t                numPalDevices    = pDevice->NumPalDevices();
    bool                    useInitialData   = false;
    size_t                  shaderCacheSize  = 0;
    size_t                  pipelineCacheSize[MaxPalDevices];

    bool                    usePipelineCacheInitialData   = false;

    PipelineCompilerType       cacheType = pDevice->GetCompiler(DefaultDeviceIndex)->GetShaderCacheType();

    for (uint32_t i = 0; i < numPalDevices; i++)
    {
        pipelineCacheSize[i] = pDevice->GetCompiler(DefaultDeviceIndex)->GetShaderCacheSize(cacheType);
        shaderCacheSize += pipelineCacheSize[i];
    }

    if ((pCreateInfo->initialDataSize > 0) && settings.usePipelineCacheInitialData)
    {
        const PipelineCacheHeaderData* pHeader = static_cast<const PipelineCacheHeaderData*>(pCreateInfo->pInitialData);

        if (pHeader->headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE)
        {
            const Pal::DeviceProperties& palProps = pDevice->VkPhysicalDevice(DefaultDeviceIndex)->PalProperties();

            if ((pHeader->vendorID == palProps.vendorId) &&
                (pHeader->deviceID == palProps.deviceId))
            {
                VkPhysicalDeviceProperties physicalDeviceProps;
                pDevice->VkPhysicalDevice(DefaultDeviceIndex)->GetDeviceProperties(&physicalDeviceProps);
                if (memcmp(pHeader->UUID, physicalDeviceProps.pipelineCacheUUID, sizeof(pHeader->UUID)) == 0)
                {
                    const void* pData   = Util::VoidPtrInc(pCreateInfo->pInitialData, sizeof(PipelineCacheHeaderData));
                    size_t dataSize     = pCreateInfo->initialDataSize - sizeof(PipelineCacheHeaderData);
                    vk::PhysicalDevice* pPhysicalDevice = pDevice->VkPhysicalDevice(DefaultDeviceIndex);

                    if (PipelineBinaryCache::IsValidBlob(pPhysicalDevice->VkInstance()->GetAllocCallbacks(),
                                                         pPhysicalDevice->GetPlatformKey(),
                                                         dataSize,
                                                         pData))
                    {
                        usePipelineCacheInitialData = true;
                    }
                    else
                    {
                        auto pPrivateDataHeader = reinterpret_cast<const PipelineCachePrivateHeaderData*>(pData);
                        if (pPrivateDataHeader->cacheType == cacheType)
                        {
                            useInitialData = true;
                        }
                    }
                }
            }
        }
    }

    // Allocate system memory for all objects
    const size_t objSize = sizeof(PipelineCache) + shaderCacheSize;
    void* pMemory = pDevice->AllocApiObject(pAllocator, objSize);

    if (pMemory == nullptr)
    {
        result = VK_ERROR_OUT_OF_HOST_MEMORY;
    }
    else
    {
        const PipelineCachePrivateHeaderData* pPrivateDataHeader = nullptr;
        const void* pBlobs[MaxPalDevices] = {};

        if (useInitialData)
        {
            pPrivateDataHeader = reinterpret_cast<const PipelineCachePrivateHeaderData*>(
                Util::VoidPtrInc(pCreateInfo->pInitialData, sizeof(PipelineCacheHeaderData)));

            pBlobs[0] = Util::VoidPtrInc(pPrivateDataHeader, sizeof(PipelineCachePrivateHeaderData));
            for (uint32_t i = 1; i < numPalDevices; i++)
            {
                pBlobs[i] = Util::VoidPtrInc(pBlobs[i - 1], static_cast<size_t>(pPrivateDataHeader->blobSize[i - 1]));
            }
        }

        ShaderCache shaderCaches[MaxPalDevices];
        size_t shaderCacheOffset = sizeof(PipelineCache);
        uint32_t expectedEntries = pDevice->VkPhysicalDevice(DefaultDeviceIndex)->GetPipelineCacheExpectedEntryCount();

        for (uint32_t i = 0; i < numPalDevices; i++)
        {
            const void* pInitialData = nullptr;
            size_t initialDataSize = 0;

            if (useInitialData)
            {
                pInitialData    = pBlobs[i];
                initialDataSize = static_cast<size_t>(pPrivateDataHeader->blobSize[i]);
            }

            if (result == VK_SUCCESS)
            {
                result = pDevice->GetCompiler(DefaultDeviceIndex)->CreateShaderCache(
                    pInitialData,
                    initialDataSize,
                    expectedEntries,
                    Util::VoidPtrInc(pMemory, shaderCacheOffset),
                    &shaderCaches[i]);
            }
            else
            {
                break;
            }

            // Move to next shader cache object
            shaderCacheOffset += pipelineCacheSize[i];
        }

        // Something went wrong with creating the PAL object. Free memory
        if (result != VK_SUCCESS)
        {
            for (uint32_t i = 0; i < numPalDevices; i++)
            {
                shaderCaches[i].Destroy(pDevice->GetCompiler(i));
            }
        }

        if (result == VK_SUCCESS)
        {
            PipelineBinaryCache* pBinaryCache = nullptr;
            if (settings.allowExternalPipelineCacheObject)
            {
                const void* pInitialData = nullptr;
                size_t initialDataSize = 0;

                if (usePipelineCacheInitialData)
                {
                    pInitialData    = Util::VoidPtrInc(pCreateInfo->pInitialData, sizeof(PipelineCacheHeaderData));
                    initialDataSize = pCreateInfo->initialDataSize - sizeof(PipelineCacheHeaderData);
                }

                vk::PhysicalDevice* pDefaultPhysicalDevice = pDevice->VkPhysicalDevice(DefaultDeviceIndex);
                pBinaryCache = PipelineBinaryCache::Create(
                    pDefaultPhysicalDevice->VkInstance()->GetAllocCallbacks(),
                    pDefaultPhysicalDevice->GetPlatformKey(),
                    pDevice->GetCompiler(DefaultDeviceIndex)->GetGfxIp(),
                    pDefaultPhysicalDevice->GetRuntimeSettings(),
                    pDefaultPhysicalDevice->PalDevice()->GetCacheFilePath(),
#if ICD_GPUOPEN_DEVMODE_BUILD
                    pDefaultPhysicalDevice->VkInstance()->GetDevModeMgr(),
#endif
                    expectedEntries,
                    initialDataSize,
                    pInitialData,
                    false);

                // This isn't a terminal failure, the device can continue without the pipeline cache if need be.
                VK_ALERT(pBinaryCache == nullptr);
            }
            PipelineCache* pCache = VK_PLACEMENT_NEW(pMemory) PipelineCache(pDevice, shaderCaches, pBinaryCache);
            *pPipelineCache = PipelineCache::HandleFromVoidPointer(pMemory);
        }
        else
        {
            pDevice->FreeApiObject(pAllocator, pMemory);
        }
    }

    return result;
}

// =====================================================================================================================
VkResult PipelineCache::Destroy(
    Device*                         pDevice,
    const VkAllocationCallbacks*    pAllocator)
{
    pDevice->VkPhysicalDevice(DefaultDeviceIndex)->DecreasePipelineCacheCount();
    if (m_pBinaryCache != nullptr)
    {
        m_pBinaryCache->Destroy();
        m_pBinaryCache = nullptr;
    }

    this->~PipelineCache();

    pDevice->FreeApiObject(pAllocator, this);

    return VK_SUCCESS;
}

// =====================================================================================================================
VkResult PipelineCache::GetData(
    void*   pData,
    size_t* pSize)
{
    VK_ASSERT(pSize != nullptr);

    VkResult        result = VK_SUCCESS;

    if (m_pBinaryCache != nullptr)
    {
        result = m_pBinaryCache->Serialize(pData, pSize);
    }
    else
    {
        uint32_t numPalDevices = m_pDevice->NumPalDevices();

        size_t allBlobSize = sizeof(PipelineCachePrivateHeaderData);
        PipelineCachePrivateHeaderData headerData = {};

        headerData.cacheType = m_shaderCaches[0].GetCacheType();
        for (uint32_t i = 0; i < numPalDevices; i++)
        {
            size_t blobSize = 0;
            result = m_shaderCaches[i].Serialize(nullptr, &blobSize);
            VK_ASSERT(result == VK_SUCCESS);
            headerData.blobSize[i] = blobSize;
            allBlobSize += blobSize;
        }

        if (*pSize == 0)
        {
            *pSize = allBlobSize;
        }
        else
        {
            VK_ASSERT(*pSize >= allBlobSize);
            memcpy(pData, &headerData, sizeof(headerData));

            void* pBlob = Util::VoidPtrInc(pData, sizeof(headerData));

            for (uint32_t i = 0; i < numPalDevices; i++)
            {
                size_t blobSize = static_cast<size_t>(headerData.blobSize[i]);
                result = m_shaderCaches[i].Serialize(pBlob, &blobSize);
                if (result != VK_SUCCESS)
                {
                    break;
                }
                pBlob = Util::VoidPtrInc(pBlob, blobSize);
            }
        }
    }

    return result;
}

// =====================================================================================================================
VkResult PipelineCache::Merge(
    uint32_t              srcCacheCount,
    const PipelineCache** ppSrcCaches)
{
    VkResult result = VK_SUCCESS;

    if (m_pBinaryCache != nullptr)
    {
        Util::AutoBuffer<const PipelineBinaryCache *, 16, PalAllocator> binaryCaches(
            srcCacheCount,
            m_pDevice->VkInstance()->Allocator());

        for (uint32_t cacheIdx = 0; cacheIdx < srcCacheCount; cacheIdx++)
        {
            binaryCaches[cacheIdx] = ppSrcCaches[cacheIdx]->GetPipelineCache();
        }

        result = m_pBinaryCache->Merge(srcCacheCount, &binaryCaches[0]);
    }
    else
    {
        Util::AutoBuffer<ShaderCache::ShaderCachePtr, 16, PalAllocator> shaderCaches(
            srcCacheCount * m_pDevice->NumPalDevices(),
            m_pDevice->VkInstance()->Allocator());

        for (uint32_t deviceIdx = 0; deviceIdx < m_pDevice->NumPalDevices(); deviceIdx++)
        {
            for (uint32_t cacheIdx = 0; cacheIdx < srcCacheCount; cacheIdx++)
            {
                VK_ASSERT(ppSrcCaches[cacheIdx]->GetShaderCache(deviceIdx).GetCacheType() ==
                    GetShaderCache(deviceIdx).GetCacheType());
                // Store all PAL caches like this d0c0,d0c1,d0c2...,d1c0,d1c2,d1c3...
                shaderCaches[deviceIdx * srcCacheCount + cacheIdx] =
                    ppSrcCaches[cacheIdx]->GetShaderCache(deviceIdx).GetCachePtr();
            }
        }

        for (uint32_t i = 0; i < m_pDevice->NumPalDevices(); i++)
        {
            result = m_shaderCaches[i].Merge(srcCacheCount, &shaderCaches[i * srcCacheCount]);

            if (result != VK_SUCCESS)
            {
                break;
            }
        }
    }

    return result;
}

namespace entry
{
// =====================================================================================================================
VKAPI_ATTR void VKAPI_CALL vkDestroyPipelineCache(
    VkDevice                                    device,
    VkPipelineCache                             pipelineCache,
    const VkAllocationCallbacks*                pAllocator)
{
    if (pipelineCache != VK_NULL_HANDLE)
    {
        Device*                      pDevice = ApiDevice::ObjectFromHandle(device);
        const VkAllocationCallbacks* pAllocCB = pAllocator ? pAllocator : pDevice->VkInstance()->GetAllocCallbacks();

        PipelineCache::ObjectFromHandle(pipelineCache)->Destroy(pDevice, pAllocCB);
    }
}

// =====================================================================================================================
VKAPI_ATTR VkResult VKAPI_CALL vkGetPipelineCacheData(
    VkDevice                                    device,
    VkPipelineCache                             pipelineCache,
    size_t*                                     pDataSize,
    void*                                       pData)
{
    size_t                     nBytesRequested = *pDataSize;
    VkPhysicalDeviceProperties physicalDeviceProps;
    VkResult                   result = VK_SUCCESS;

    Device*        pDevice = ApiDevice::ObjectFromHandle(device);
    PipelineCache* pCache = PipelineCache::ObjectFromHandle(pipelineCache);

    const Pal::DeviceProperties& palProps = pDevice->VkPhysicalDevice(DefaultDeviceIndex)->PalProperties();

    size_t privateDataSize = 0;

    result = pCache->GetData(nullptr, &privateDataSize);
    VK_ASSERT(result == VK_SUCCESS);

    const size_t       fullDataSize = VkPipelineCacheHeaderDataSize + privateDataSize;

    if (pData == nullptr)
    {
        *pDataSize = fullDataSize;

        return VK_SUCCESS;
    }

    if (nBytesRequested < fullDataSize)
    {
        // "If pDataSize is less than what is necessary to store this header, nothing will be written to pData and
        // zero will be written to pDataSize."
        *pDataSize = 0;

        result = VK_INCOMPLETE;
    }

    // The vk spec says the data should be written least significant byte first.
#ifdef BIGENDIAN_CPU
#error we need to byte-swap the data we are about to write to pData
#endif

    if (result == VK_SUCCESS)
    {
        ApiDevice::ObjectFromHandle(device)->VkPhysicalDevice(DefaultDeviceIndex)->GetDeviceProperties(&physicalDeviceProps);

        size_t       headerBytesWritten = 0;
        Util::Result headerWriteRes     =  WriteVkPipelineCacheHeaderData(
                                            pData,
                                            fullDataSize,
                                            palProps.vendorId,
                                            palProps.deviceId,
                                            physicalDeviceProps.pipelineCacheUUID,
                                            sizeof(physicalDeviceProps.pipelineCacheUUID),
                                            &headerBytesWritten);

        if (headerWriteRes != Util::Result::Success)
        {
            *pDataSize = 0;
            result = VK_INCOMPLETE;
        }
        else
        {
            VK_ASSERT(headerBytesWritten == VkPipelineCacheHeaderDataSize);
            if (privateDataSize > 0)
            {
                void* pPrivateData = Util::VoidPtrInc(pData, headerBytesWritten);
                result = pCache->GetData(pPrivateData, &privateDataSize);
            }
            // set pDataSize, privateDataSize can be 0.
            *pDataSize = privateDataSize + headerBytesWritten;
        }
    }

    return result;
}

// =====================================================================================================================
VKAPI_ATTR VkResult VKAPI_CALL vkMergePipelineCaches(
    VkDevice                                    device,
    VkPipelineCache                             dstCache,
    uint32_t                                    srcCacheCount,
    const VkPipelineCache*                      pSrcCaches)
{
    Device*        pDevice = ApiDevice::ObjectFromHandle(device);
    PipelineCache* pDstCache = PipelineCache::ObjectFromHandle(dstCache);

    Util::AutoBuffer<const PipelineCache*, 8, PalAllocator> srcCaches(srcCacheCount, pDevice->VkInstance()->Allocator());

    for (uint32_t i = 0; i < srcCacheCount; i++)
    {
        srcCaches[i] = PipelineCache::ObjectFromHandle(pSrcCaches[i]);
    }

    VkResult result = pDstCache->Merge(srcCacheCount, &srcCaches[0]);

    return result;
}

} // namespace entry

} // namespace vk


text:
package io.github.joseerodrigues.utils.dbutil.mapper;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import io.github.joseerodrigues.utils.dbutil.ResultSetMapper;
import io.github.joseerodrigues.utils.dbutil.annotation.DBColumn;
import io.github.joseerodrigues.utils.dbutil.mapper.Mappers;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class BeanResultSetMapperTest {

    public static class MyEntity {
        @DBColumn
        private int id;

        @DBColumn(value ="shortinfo", trim = true)
        private String description;

        @DBColumn
        private long quantity;
    }

    @Mock
    private ResultSet rs;

    @Mock
    private ResultSetMetaData metadata;

    @Before
    public void setUp() throws Exception {

        assertNotNull(rs);
        assertNotNull(metadata);

        when(rs.getMetaData()).thenReturn(metadata);
        when(metadata.getColumnCount()).thenReturn(3);

        when(metadata.getColumnLabel(1)).thenReturn("id");
        when(metadata.getColumnLabel(2)).thenReturn("shortinfo");
        when(metadata.getColumnLabel(3)).thenReturn("quantity");

        when(rs.getObject("id")).thenReturn(1);
        when(rs.getObject("shortinfo")).thenReturn("super short info   ");
        when(rs.getObject("quantity")).thenReturn(30);
    }

    @Test
    public void testBeanMapper() throws SQLException {

        ResultSetMapper<MyEntity> mapper = Mappers.beanMapper(MyEntity.class);

        mapper.init(rs);
        MyEntity result = mapper.mapObject(rs);
        assertNotNull(result);
        mapper.terminate();

        assertEquals(1, result.id);
        assertEquals("super short info", result.description);
        assertEquals(30, result.quantity);
    }
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Pitch.active'
        db.add_column(u'smart_gigabit_communities_pitch', 'active',
                      self.gf('django.db.models.fields.BooleanField')(default=False),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Pitch.active'
        db.delete_column(u'smart_gigabit_communities_pitch', 'active')

    models = {
        u'smart_gigabit_communities.pitch': {
            'Meta': {'ordering': "('order',)", 'object_name': 'Pitch'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'pitch_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
            'pitch_video': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'subtitle': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        }
    }

    complete_apps = ['smart_gigabit_communities']


text:
//
//  IDCheckerSDK.h
//  IDCheckerSDK
//
//  Created by Michiel Boertjes on 5/8/13.
//  Copyright (c) 2013 IDChecker. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "IDCSettings.h"
#import "IDCDocument.h"

@class IDCSettings, IDCDocument, IDCRequestObject;

@interface IDCheckerSDK : NSObject

@property (nonatomic, strong, readonly) IDCSettings *settings;
@property (nonatomic, copy) IDCDocumentProcessedBlock pollingDoneBlock;

/**
 * Call this method first
 */
- (void)loadWithSettings:(IDCSettings *)settings block:(void(^)(NSError *))block;

/**
 * After calling +shared please load your custom settings before calling methods
 */
+ (IDCheckerSDK *)shared;

//- (void)openRecord;

/**
 * SDK takes care of image taking and upload
 * The camera viewcontroller is dismissed after the picture is taken. Upload starts at this moment
 * The IDCDocument argument has to have at least documentDimensions property set.
 * Please set highRes to YES if an image may contain a 2D barcode.
 */
- (void)startProcessForDocument:(IDCDocument *)document viewControllerToPresent:(UIViewController *)vc quality:(IDCQualityType)quality  pictureTakenBlock:(void(^)(BOOL))pictureTakenBlock uploadDoneBlock:(IDCDocumentProcessedBlock)uploadBlock;

/**
 * IDCCameraViewController is presented modally on the supplied UIViewController
 * Please set highRes to YES if an image may contain a 2D barcode.
 */
- (void)takePicture:(IDCDocument *)document viewControllerToPresent:(UIViewController *)vc quality:(IDCQualityType)quality pictureTakenBlock:(IDCDocumentProcessedBlock)pictureTakenBlock;

/**
 * Send a document taken with the -takePicture method to IDchecker for OCR processing
 */
- (void)uploadDocumentForOcr:(IDCDocument *)document ocrResultBlock:(IDCDocumentProcessedBlock)ocrResultBlock;

/**
 * Fetch more accurate data from server for an uploaded document.
 * Please note that -uploadColorImageForIDCProcessing has to be done first.
 * The polling timer fires every 30 seconds
 * If this method is called again while polling is in progress the previous polling will be canceled and it's block will be called with nil as argument
 */
- (void)startPollingForMoreAccurateData:(IDCDocument *)pollingDoc pollingResultBlock:(IDCDocumentProcessedBlock)block;

/**
 * Calling stopPoling stops the polling timer and calls the provided code block with nil as argument
 */
- (void)stopPolling;

/**
 * If you wish to control the time the guid is requested use this method
 */
- (void)openRecordWithBlock:(void(^)(NSString *, NSError *))block;

/**
 * Upload color image to IDChecker for processing
 * If you have no guid at this moment (you did not call the startProcessForDocument method first) please use openRecordWithBlock to obtain one.
 */
- (void)uploadColorImageForIDCProcessing:(UIImage *)image guid:(NSString *)guid block:(void(^)(NSError *))block;

/**
 * After all desired uploads are done we need to close the record to indicate it's ready for processing
 */
- (void)closeRecordForGuid:(NSString *)guid block:(void(^)(NSError *))block;

/**
 * returns a version number for the sdk
 */
+ (CGFloat)sdkVersion;

/**
 * returns a build number for the sdk
 */
+ (NSInteger)sdkBuild;

@end


text:
module Mixin
  module Activatable
    attr_accessor :active

    def active?
      active
    end

    def activate
      self.active = true
      self
    end

    def deactivate
      self.active = false
      self
    end

    def toggle_active
      self.active = !active
      self
    end
  end
end