text:
package com.braintreegateway;

import java.math.BigDecimal;

public class ModificationRequest extends Request {

    private BigDecimal amount;
    private Integer numberOfBillingCycles;
    private ModificationsRequest parent;
    private Integer quantity;
    private Boolean neverExpires;

    public ModificationRequest(ModificationsRequest parent) {
        this.parent = parent;
    }

    public ModificationRequest amount(BigDecimal amount) {
        this.amount = amount;
        return this;
    }

    public ModificationsRequest done() {
        return parent;
    }

    public ModificationRequest numberOfBillingCycles(Integer numberOfBillingCycles) {
        this.numberOfBillingCycles = numberOfBillingCycles;
        return this;
    }

    public ModificationRequest neverExpires(Boolean neverExpires) {
        this.neverExpires = neverExpires;
        return this;
    }

    public ModificationRequest quantity(Integer quantity) {
        this.quantity = quantity;
        return this;
    }

    @Override
    public String toXML() {
        return buildRequest("modification").toXML();
    }

    protected RequestBuilder buildRequest(String root) {
        return new RequestBuilder(root).
            addElement("amount", amount).
            addElement("neverExpires", neverExpires).
            addElement("numberOfBillingCycles", numberOfBillingCycles).
            addElement("quantity", quantity);
    }
}


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

<document>
  <properties>
    <title>Using JCS: Some basics for the web</title>
    <author email="ASmuts@yahoo.com">Aaron Smuts</author>
  </properties>

        The primary bottleneck in most dynamic web-based applications is
        the retrieval of data from the database.  While it is relatively
        inexpensive to add more front-end servers to scale the serving
        of pages and images and the processing of content, it is an
        expensive and complex ordeal to scale the database.  By taking
        advantage of data caching, most web applications can reduce
        latency times and scale farther with fewer machines.

        JCS is a front-tier cache that can be configured to maintain
        consistency across multiple servers by using a centralized
        remote server or by lateral distribution of cache updates.
        Other caches, like the Javlin EJB data cache, are basically
        in-memory databases that sit between your EJB's and your
        database.  Rather than trying to speed up your slow EJB's, you
        can avoid most of the network traffic and the complexity by
        implementing JCS front-tier caching.  Centralize your EJB access
        or your JDBC data access into local managers and perform the
        caching there.

      <subsection name="What to cache?">

          The data used by most web applications varies in its
          dynamicity, from completely static to always changing at every
          request.  Everything that has some degree of stability can be
          cached.  Prime candidates for caching range from the list data
          for stable dropdowns, user information, discrete and
          infrequently changing information, to stable search results
          that could be sorted in memory.

          Since JCS is distributed and allows updates and invalidations
          to be broadcast to multiple listeners, frequently changing
          items can be easily cached and kept in sync through your data
          access layer.  For data that must be 100% up to date, say an
          account balance prior to a transfer, the data should directly
          be retrieved from the database.  If your application allows
          for the viewing and editing of data, the data for the view
          pages could be cached, but the edit pages should, in most
          cases, pull the data directly from the database.

      </subsection>
      <subsection name="How to cache discrete data">

          Let's say that you have an e-commerce book store.  Each book
          has a related set of information that you must present to the
          user.  Let's say that 70% of your hits during a particular day
          are for the same 1,000 popular items that you advertise on key
          pages of your site, but users are still actively browsing your
          catalog of over a million books.  You cannot possibly cache
          your entire database, but you could dramatically decrease the
          load on your database by caching the 1,000 or so most popular
          items.

          For the sake of simplicity let's ignore tie-ins and
          user-profile based suggestions (also good candidates for
          caching) and focus on the core of the book detail page.

          A simple way to cache the core book information would be to
          create a value object for book data that contains the
          necessary information to build the display page.  This value
          object could hold data from multiple related tables or book
          subtype table, but lets say that you have a simple table
          called BOOK that looks something like this:

        <source><![CDATA[
  Table BOOK
  BOOK_ID_PK
  TITLE
  AUTHOR
  ISBN
  PRICE
  PUBLISH_DATE
        ]]></source>

          We could create a value object for this table called
          BookVObj that has variables with the same
          names as the table columns that might look like this:

        <source><![CDATA[
package com.genericbookstore.data;

import java.util.Date;

public class BookVObj implements Serializable
{
    public int bookId = 0;
    public String title;
    public String author;
    public String ISBN;
    public String price;
    public Date publishDate;

    public BookVObj()
    {
    }
}
        ]]></source>

          Then we can create a manager called
          BookVObjManager to store and retrieve
          BookVObj's.  All access to core book data
          should go through this class, including inserts and
          updates, to keep the caching simple.  Let's make
          BookVObjManager a singleton that gets a
          JCS access object in initialization.  The start of the
          class might look like:

        <source><![CDATA[
package com.genericbookstore.data;

import org.apache.commons.jcs3.JCS;
import org.apache.commons.jcs3.access.CacheAccess;
// in case we want to set some special behavior
import org.apache.commons.jcs3.engine.behavior.IElementAttributes;

public class BookVObjManager
{
    private static BookVObjManager instance;
    private static int checkedOut = 0;
    private static CacheAccess<String, BookVObj> bookCache;

    private BookVObjManager()
    {
        try
        {
            bookCache = JCS.getInstance("bookCache");
        }
        catch (Exception e)
        {
            // Handle cache region initialization failure
        }

        // Do other initialization that may be necessary, such as getting
        // references to any data access classes we may need to populate
        // value objects later
    }

    /**
     * Singleton access point to the manager.
     */
    public static BookVObjManager getInstance()
    {
        synchronized (BookVObjManager.class)
        {
            if (instance == null)
            {
                instance = new BookVObjManager();
            }
        }

        synchronized (instance)
        {
            instance.checkedOut++;
        }

        return instance;
    }
        ]]></source>

          To get a BookVObj we will need some access
          methods in the manager. We should be able to get a
          non-cached version if necessary, say before allowing an
          administrator to edit the book data. The methods might
          look like:

        <source><![CDATA[
    /**
     * Retrieves a BookVObj.  Default to look in the cache.
     */
    public BookVObj getBookVObj(int id)
    {
        return getBookVObj(id, true);
    }

    /**
     * Retrieves a BookVObj. Second argument decides whether to look
     * in the cache. Returns a new value object if one can't be
     * loaded from the database. Database cache synchronization is
     * handled by removing cache elements upon modification.
     */
    public BookVObj getBookVObj(int id, boolean fromCache)
    {
        BookVObj vObj = null;

        // If requested, attempt to load from cache
        if (fromCache)
        {
            vObj = bookCache.get("BookVObj" + id, () -> loadvObj(id));
        }
        else
        {
            // otherwise, load directly
            vObj = loadvObj(id);
        }

        return  vObj;
    }

    /**
     * Creates a BookVObj based on the id of the BOOK table.  Data
     * access could be direct JDBC, some or mapping tool, or an EJB.
     */
    public BookVObj loadBookVObj(int id)
    {
        BookVObj vObj = new BookVObj();

        vObj.bookID = id;

        try
        {
            boolean found = false;

            // load the data and set the rest of the fields
            // set found to true if it was found

            found = true;

            // cache the value object if found

            if (found)
            {
                // could use the defaults like this
                // bookCache.put( "BookVObj" + id, vObj );
                // or specify special characteristics

                // put to cache

                bookCache.put("BookVObj" + id, vObj);
            }

        }
        catch (Exception e)
        {
            // Handle failure putting object to cache
        }

        return vObj;
    }
        ]]></source>

          We will also need a method to insert and update book data.  To
          keep the caching in one place, this should be the primary way
          core book data is created.  The method might look like:

        <source><![CDATA[
    /**
     * Stores BookVObj's in database.  Clears old items and caches
     * new.
     */
    public int storeBookVObj(BookVObj vObj)
    {
        try
        {
            // since any cached data is no longer valid, we should
            // remove the item from the cache if it an update.

            if (vObj.bookID != 0)
            {
                bookCache.remove("BookVObj" + vObj.bookID);
            }

            // put the new object in the cache

            bookCache.put("BookVObj" + id, vObj);
        }
        catch (Exception e)
        {
            // Handle failure removing object or putting object to cache.
        }
    }
}
        ]]></source>

          As elements are placed in the cache via put, it
          is possible to specify custom attributes for those elements
          such as its maximum lifetime in the cache, whether or not it
          can be spooled to disk, etc.  It is also possible (and easier)
          to define these attributes in the configuration file as
          demonstrated later.  We now have the basic infrastructure for
          caching the book data.

      </subsection>
      <subsection name="Selecting the appropriate auxiliary caches">

          The first step in creating a cache region is to determine the
          makeup of the memory cache.  For the book store example, I
          would create a region that could store a bit over the minimum
          number I want to have in memory, so the core items always
          readily available.  I would set the maximum memory size to
          1200.  In addition, I might want to have all
          objects in this cache region expire after 7200
          seconds.  This can be configured in the element attributes on
          a default or per-region basis as illustrated in the
          configuration file below.

          For most cache regions you will want to use a disk
          cache if the data takes over about .5 milliseconds to
          create.  The indexed
          disk cache is the most efficient disk caching
          auxiliary, and for normal usage it is recommended.

          The next step will be to select an appropriate
          distribution layer.  If you have a back-end server
          running an appserver or scripts or are running multiple
          webserver VMs on one machine, you might want to use
          the centralized remote
          cache.  The lateral cache would be fine, but since
          the lateral cache binds to a port, you'd have to configure
          each VM's lateral cache to listen to a different port on
          that machine.

          If your environment is very flat, say a few
          load-balanced webservers and a database machine or one
          webserver with multiple VMs and a database machine,
          then the lateral cache will probably make more sense.
          The TCP lateral
          cache is recommended.

          For the book store configuration I will set up a region
          for the bookCache that uses the LRU memory
          cache, the indexed disk auxiliary cache, and the remote
          cache.  The configuration file might look like this:

        <source><![CDATA[
# DEFAULT CACHE REGION

# sets the default aux value for any non configured caches
jcs.default=DC,RFailover
jcs.default.cacheattributes=
    org.apache.commons.jcs3.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MaxObjects=1000
jcs.default.cacheattributes.MemoryCacheName=
    org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache
jcs.default.elementattributes.IsEternal=false
jcs.default.elementattributes.MaxLife=3600
jcs.default.elementattributes.IdleTime=1800
jcs.default.elementattributes.IsSpool=true
jcs.default.elementattributes.IsRemote=true
jcs.default.elementattributes.IsLateral=true

# CACHE REGIONS AVAILABLE

# Regions preconfigured for caching
jcs.region.bookCache=DC,RFailover
jcs.region.bookCache.cacheattributes=
    org.apache.commons.jcs3.engine.CompositeCacheAttributes
jcs.region.bookCache.cacheattributes.MaxObjects=1200
jcs.region.bookCache.cacheattributes.MemoryCacheName=
    org.apache.commons.jcs3.engine.memory.lru.LRUMemoryCache
jcs.region.bookCache.elementattributes.IsEternal=false
jcs.region.bookCache.elementattributes.MaxLife=7200
jcs.region.bookCache.elementattributes.IdleTime=1800
jcs.region.bookCache.elementattributes.IsSpool=true
jcs.region.bookCache.elementattributes.IsRemote=true
jcs.region.bookCache.elementattributes.IsLateral=true

# AUXILIARY CACHES AVAILABLE

# Primary Disk Cache -- faster than the rest because of memory key storage
jcs.auxiliary.DC=
    org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheFactory
jcs.auxiliary.DC.attributes=
    org.apache.commons.jcs3.auxiliary.disk.indexed.IndexedDiskCacheAttributes
jcs.auxiliary.DC.attributes.DiskPath=/usr/opt/bookstore/raf
jcs.auxiliary.DC.attributes.MaxPurgatorySize=10000
jcs.auxiliary.DC.attributes.MaxKeySize=10000
jcs.auxiliary.DC.attributes.OptimizeAtRemoveCount=300000

# Remote RMI Cache set up to failover
jcs.auxiliary.RFailover=
    org.apache.commons.jcs3.auxiliary.remote.RemoteCacheFactory
jcs.auxiliary.RFailover.attributes=
    org.apache.commons.jcs3.auxiliary.remote.RemoteCacheAttributes
jcs.auxiliary.RFailover.attributes.RemoteTypeName=LOCAL
jcs.auxiliary.RFailover.attributes.FailoverServers=scriptserver:1102
jcs.auxiliary.RFailover.attributes.GetOnly=false
        ]]></source>

          I've set up the default cache settings in the above
          file to approximate the bookCache
          settings.  Other non-preconfigured cache regions will
          use the default settings.  You only have to configure
          the auxiliary caches once.  For most caches you will
          not need to pre-configure your regions unless the size
          of the elements varies radically.  We could easily put
          several hundred thousand BookVObj's in
          memory.  The 1200 limit was very
          conservative and would be more appropriate for a large
          data structure.

          To get running with the book store example, I will also
          need to start up the remote cache server on the
          scriptserver machine.  The
          remote cache
          documentation describes the configuration.

          I now have a basic caching system implemented for my book
          data.  Performance should improve immediately.

      </subsection>

</document>

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE DataKinds            #-}
{-# LANGUAGE DeriveGeneric        #-}
{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverloadedStrings    #-}
{-# LANGUAGE PolyKinds            #-}
{-# LANGUAGE ScopedTypeVariables  #-}
{-# LANGUAGE TypeFamilies         #-}
{-# LANGUAGE TypeOperators        #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -freduction-depth=100 #-}

module Servant.ServerSpec where

import           Prelude ()
import           Prelude.Compat

import           Control.Monad
                 (forM_, unless, when)
import           Control.Monad.Error.Class
                 (MonadError (..))
import           Data.Aeson
                 (FromJSON, ToJSON, decode', encode)
import qualified Data.ByteString                   as BS
import qualified Data.ByteString.Base64            as Base64
import           Data.Char
                 (toUpper)
import           Data.Proxy
                 (Proxy (Proxy))
import           Data.String
                 (fromString)
import           Data.String.Conversions
                 (cs)
import qualified Data.Text                         as T
import           GHC.Generics
                 (Generic)
import           Network.HTTP.Types
                 (Status (..), hAccept, hContentType, imATeapot418,
                 methodDelete, methodGet, methodHead, methodPatch, methodPost,
                 methodPut, ok200, parseQuery)
import           Network.Wai
                 (Application, Request, pathInfo, queryString, rawQueryString,
                 requestHeaders, responseLBS)
import           Network.Wai.Test
                 (defaultRequest, request, runSession, simpleBody,
                 simpleHeaders, simpleStatus)
import           Servant.API
                 ((:<|>) (..), (:>), AuthProtect, BasicAuth,
                 BasicAuthData (BasicAuthData), Capture, CaptureAll, Delete,
                 EmptyAPI, Get, Header, Headers, HttpVersion, IsSecure (..),
                 JSON, NoContent (..), NoFraming, OctetStream, Patch,
                 PlainText, Post, Put, QueryFlag, QueryParam, QueryParams, Raw,
                 RemoteHost, ReqBody, SourceIO, StdMethod (..), Stream, Verb,
                 addHeader)
import           Servant.Server
                 (Context ((:.), EmptyContext), Handler, Server, Tagged (..),
                 emptyServer, err401, err403, err404, serve, serveWithContext)
import           Servant.Test.ComprehensiveAPI
import qualified Servant.Types.SourceT             as S
import           Test.Hspec
                 (Spec, context, describe, it, shouldBe, shouldContain)
import           Test.Hspec.Wai
                 (get, liftIO, matchHeaders, matchStatus, shouldRespondWith,
                 with, (<:>))
import qualified Test.Hspec.Wai                    as THW

import           Servant.Server.Experimental.Auth
                 (AuthHandler, AuthServerData, mkAuthHandler)
import           Servant.Server.Internal.BasicAuth
                 (BasicAuthCheck (BasicAuthCheck),
                 BasicAuthResult (Authorized, Unauthorized))
import           Servant.Server.Internal.Context
                 (NamedContext (..))

-- * comprehensive api test

-- This declaration simply checks that all instances are in place.
_ = serveWithContext comprehensiveAPI comprehensiveApiContext

comprehensiveApiContext :: Context '[NamedContext "foo" '[]]
comprehensiveApiContext = NamedContext EmptyContext :. EmptyContext

-- * Specs

spec :: Spec
spec = do
  verbSpec
  captureSpec
  captureAllSpec
  queryParamSpec
  reqBodySpec
  headerSpec
  rawSpec
  alternativeSpec
  responseHeadersSpec
  miscCombinatorSpec
  basicAuthSpec
  genAuthSpec

------------------------------------------------------------------------------
-- * verbSpec {{{
------------------------------------------------------------------------------

type VerbApi method status
    =                Verb method status '[JSON] Person
 :<|> "noContent" :> Verb method status '[JSON] NoContent
 :<|> "header"    :> Verb method status '[JSON] (Headers '[Header "H" Int] Person)
 :<|> "headerNC"  :> Verb method status '[JSON] (Headers '[Header "H" Int] NoContent)
 :<|> "accept"    :> (    Verb method status '[JSON] Person
                     :<|> Verb method status '[PlainText] String
                     )
 :<|> "stream"    :> Stream method status NoFraming OctetStream (SourceIO BS.ByteString)

verbSpec :: Spec
verbSpec = describe "Servant.API.Verb" $ do
  let server :: Server (VerbApi method status)
      server = return alice
          :<|> return NoContent
          :<|> return (addHeader 5 alice)
          :<|> return (addHeader 10 NoContent)
          :<|> (return alice :<|> return "B")
          :<|> return (S.source ["bytestring"])

      get200     = Proxy :: Proxy (VerbApi 'GET 200)
      post210    = Proxy :: Proxy (VerbApi 'POST 210)
      put203     = Proxy :: Proxy (VerbApi 'PUT 203)
      delete280  = Proxy :: Proxy (VerbApi 'DELETE 280)
      patch214   = Proxy :: Proxy (VerbApi 'PATCH 214)
      wrongMethod m = if m == methodPatch then methodPost else methodPatch
      test desc api method (status :: Int) = context desc $

        with (return $ serve api server) $ do

          -- HEAD and 214/215 need not return bodies
          unless (status `elem` [214, 215] || method == methodHead) $
            it "returns the person" $ do
              response <- THW.request method "/" [] ""
              liftIO $ statusCode (simpleStatus response) `shouldBe` status
              liftIO $ decode' (simpleBody response) `shouldBe` Just alice

          it "returns no content on NoContent" $ do
              response <- THW.request method "/noContent" [] ""
              liftIO $ statusCode (simpleStatus response) `shouldBe` status
              liftIO $ simpleBody response `shouldBe` ""

          -- HEAD should not return body
          when (method == methodHead) $
            it "HEAD returns no content body" $ do
              response <- THW.request method "/" [] ""
              liftIO $ simpleBody response `shouldBe` ""

          it "throws 405 on wrong method " $ do
            THW.request (wrongMethod method) "/" [] ""
              `shouldRespondWith` 405

          it "returns headers" $ do
            response1 <- THW.request method "/header" [] ""
            liftIO $ statusCode (simpleStatus response1) `shouldBe` status
            liftIO $ simpleHeaders response1 `shouldContain` [("H", "5")]

            response2 <- THW.request method "/header" [] ""
            liftIO $ statusCode (simpleStatus response2) `shouldBe` status
            liftIO $ simpleHeaders response2 `shouldContain` [("H", "5")]

          it "handles trailing '/' gracefully" $ do
            response <- THW.request method "/headerNC/" [] ""
            liftIO $ statusCode (simpleStatus response) `shouldBe` status

          it "returns 406 if the Accept header is not supported" $ do
            THW.request method "" [(hAccept, "crazy/mime")] ""
              `shouldRespondWith` 406

          it "responds if the Accept header is supported" $ do
            response <- THW.request method ""
               [(hAccept, "application/json")] ""
            liftIO $ statusCode (simpleStatus response) `shouldBe` status

          unless (status `elem` [214, 215] || method == methodHead) $
            it "allows modular specification of supported content types" $ do
              response <- THW.request method "/accept" [(hAccept, "text/plain")] ""
              liftIO $ statusCode (simpleStatus response) `shouldBe` status
              liftIO $ simpleBody response `shouldBe` "B"

          it "sets the Content-Type header" $ do
            response <- THW.request method "" [] ""
            liftIO $ simpleHeaders response `shouldContain`
              [("Content-Type", "application/json;charset=utf-8")]

          it "works for Stream as for Result" $ do
              response <- THW.request method "/stream" [] ""
              liftIO $ statusCode (simpleStatus response) `shouldBe` status
              liftIO $ simpleBody response `shouldBe` "bytestring"

  test "GET 200" get200 methodGet 200
  test "POST 210" post210 methodPost 210
  test "PUT 203" put203 methodPut 203
  test "DELETE 280" delete280 methodDelete 280
  test "PATCH 214" patch214 methodPatch 214
  test "GET 200 with HEAD" get200 methodHead 200

-- }}}
------------------------------------------------------------------------------
-- * captureSpec {{{
------------------------------------------------------------------------------

type CaptureApi = Capture "legs" Integer :> Get '[JSON] Animal
captureApi :: Proxy CaptureApi
captureApi = Proxy
captureServer :: Integer -> Handler Animal
captureServer legs = case legs of
  4 -> return jerry
  2 -> return tweety
  _ -> throwError err404

captureSpec :: Spec
captureSpec = do
  describe "Servant.API.Capture" $ do
    with (return (serve captureApi captureServer)) $ do

      it "can capture parts of the 'pathInfo'" $ do
        response <- get "/2"
        liftIO $ decode' (simpleBody response) `shouldBe` Just tweety

      it "returns 400 if the decoding fails" $ do
        get "/notAnInt" `shouldRespondWith` 400

    with (return (serve
        (Proxy :: Proxy (Capture "captured" String :> Raw))
        (\ "captured" -> Tagged $ \request_ respond ->
            respond $ responseLBS ok200 [] (cs $ show $ pathInfo request_)))) $ do
      it "strips the captured path snippet from pathInfo" $ do
        get "/captured/foo" `shouldRespondWith` (fromString (show ["foo" :: String]))

-- }}}
------------------------------------------------------------------------------
-- * captureAllSpec {{{
------------------------------------------------------------------------------

type CaptureAllApi = CaptureAll "legs" Integer :> Get '[JSON] Animal
captureAllApi :: Proxy CaptureAllApi
captureAllApi = Proxy
captureAllServer :: [Integer] -> Handler Animal
captureAllServer legs = case sum legs of
  4 -> return jerry
  2 -> return tweety
  0 -> return beholder
  _ -> throwError err404

captureAllSpec :: Spec
captureAllSpec = do
  describe "Servant.API.CaptureAll" $ do
    with (return (serve captureAllApi captureAllServer)) $ do

      it "can capture a single element of the 'pathInfo'" $ do
        response <- get "/2"
        liftIO $ decode' (simpleBody response) `shouldBe` Just tweety

      it "can capture multiple elements of the 'pathInfo'" $ do
        response <- get "/2/2"
        liftIO $ decode' (simpleBody response) `shouldBe` Just jerry

      it "can capture arbitrarily many elements of the 'pathInfo'" $ do
        response <- get "/1/1/0/1/0/1"
        liftIO $ decode' (simpleBody response) `shouldBe` Just jerry

      it "can capture when there are no elements in 'pathInfo'" $ do
        response <- get "/"
        liftIO $ decode' (simpleBody response) `shouldBe` Just beholder

      it "returns 400 if the decoding fails" $ do
        get "/notAnInt" `shouldRespondWith` 400

      it "returns 400 if the decoding fails, regardless of which element" $ do
        get "/1/0/0/notAnInt/3/" `shouldRespondWith` 400

      it "returns 400 if the decoding fails, even when it's multiple elements" $ do
        get "/1/0/0/notAnInt/3/orange/" `shouldRespondWith` 400

    with (return (serve
        (Proxy :: Proxy (CaptureAll "segments" String :> Raw))
        (\ _captured -> Tagged $ \request_ respond ->
            respond $ responseLBS ok200 [] (cs $ show $ pathInfo request_)))) $ do
      it "consumes everything from pathInfo" $ do
        get "/captured/foo/bar/baz" `shouldRespondWith` (fromString (show ([] :: [Int])))

-- }}}
------------------------------------------------------------------------------
-- * queryParamSpec {{{
------------------------------------------------------------------------------

type QueryParamApi = QueryParam "name" String :> Get '[JSON] Person
                :<|> "a" :> QueryParams "names" String :> Get '[JSON] Person
                :<|> "b" :> QueryFlag "capitalize" :> Get '[JSON] Person
                :<|> "param" :> QueryParam "age" Integer :> Get '[JSON] Person
                :<|> "multiparam" :> QueryParams "ages" Integer :> Get '[JSON] Person

queryParamApi :: Proxy QueryParamApi
queryParamApi = Proxy

qpServer :: Server QueryParamApi
qpServer = queryParamServer :<|> qpNames :<|> qpCapitalize :<|> qpAge :<|> qpAges

  where qpNames (_:name2:_) = return alice { name = name2 }
        qpNames _           = return alice

        qpCapitalize False = return alice
        qpCapitalize True  = return alice { name = map toUpper (name alice) }

        qpAge Nothing = return alice
        qpAge (Just age') = return alice{ age = age'}

        qpAges ages = return alice{ age = sum ages}

        queryParamServer (Just name_) = return alice{name = name_}
        queryParamServer Nothing = return alice

queryParamSpec :: Spec
queryParamSpec = do
  describe "Servant.API.QueryParam" $ do
      it "allows retrieving simple GET parameters" $
        (flip runSession) (serve queryParamApi qpServer) $ do
          let params1 = "?name=bob"
          response1 <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params1,
            queryString = parseQuery params1
           }
          liftIO $ do
            decode' (simpleBody response1) `shouldBe` Just alice{
              name = "bob"
             }

      it "allows retrieving lists in GET parameters" $
        (flip runSession) (serve queryParamApi qpServer) $ do
          let params2 = "?names[]=bob&names[]=john"
          response2 <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params2,
            queryString = parseQuery params2,
            pathInfo = ["a"]
           }
          liftIO $
            decode' (simpleBody response2) `shouldBe` Just alice{
              name = "john"
             }

      it "parses a query parameter" $
        (flip runSession) (serve queryParamApi qpServer) $ do
        let params = "?age=55"
        response <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params,
            queryString = parseQuery params,
            pathInfo = ["param"]
           }
        liftIO $
            decode' (simpleBody response) `shouldBe` Just alice{
              age = 55
            }

      it "generates an error on query parameter parse failure" $
        (flip runSession) (serve queryParamApi qpServer) $ do
        let params = "?age=foo"
        response <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params,
            queryString = parseQuery params,
            pathInfo = ["param"]
           }
        liftIO $ statusCode (simpleStatus response) `shouldBe` 400
        return ()

      it "parses multiple query parameters" $
        (flip runSession) (serve queryParamApi qpServer) $ do
        let params = "?ages=10&ages=22"
        response <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params,
            queryString = parseQuery params,
            pathInfo = ["multiparam"]
           }
        liftIO $
            decode' (simpleBody response) `shouldBe` Just alice{
              age = 32
            }

      it "generates an error on parse failures of multiple parameters" $
        (flip runSession) (serve queryParamApi qpServer) $ do
        let params = "?ages=2&ages=foo"
        response <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params,
            queryString = parseQuery params,
            pathInfo = ["multiparam"]
           }
        liftIO $ statusCode (simpleStatus response) `shouldBe` 400
        return ()

      it "allows retrieving value-less GET parameters" $
        (flip runSession) (serve queryParamApi qpServer) $ do
          let params3 = "?capitalize"
          response3 <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params3,
            queryString = parseQuery params3,
            pathInfo = ["b"]
           }
          liftIO $
            decode' (simpleBody response3) `shouldBe` Just alice{
              name = "ALICE"
             }

          let params3' = "?capitalize="
          response3' <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params3',
            queryString = parseQuery params3',
            pathInfo = ["b"]
           }
          liftIO $
            decode' (simpleBody response3') `shouldBe` Just alice{
              name = "ALICE"
             }

          let params3'' = "?unknown="
          response3'' <- Network.Wai.Test.request defaultRequest{
            rawQueryString = params3'',
            queryString = parseQuery params3'',
            pathInfo = ["b"]
           }
          liftIO $
            decode' (simpleBody response3'') `shouldBe` Just alice{
              name = "Alice"
             }

-- }}}
------------------------------------------------------------------------------
-- * reqBodySpec {{{
------------------------------------------------------------------------------
type ReqBodyApi = ReqBody '[JSON] Person :> Post '[JSON] Person
           :<|> "blah" :> ReqBody '[JSON] Person :> Put '[JSON] Integer

reqBodyApi :: Proxy ReqBodyApi
reqBodyApi = Proxy

reqBodySpec :: Spec
reqBodySpec = describe "Servant.API.ReqBody" $ do

  let server :: Server ReqBodyApi
      server = return :<|> return . age
      mkReq method x = THW.request method x
         [(hContentType, "application/json;charset=utf-8")]

  with (return $ serve reqBodyApi server) $ do

    it "passes the argument to the handler" $ do
      response <- mkReq methodPost "" (encode alice)
      liftIO $ decode' (simpleBody response) `shouldBe` Just alice

    it "rejects invalid request bodies with status 400" $ do
      mkReq methodPut "/blah" "some invalid body" `shouldRespondWith` 400

    it "responds with 415 if the request body media type is unsupported" $ do
      THW.request methodPost "/"
        [(hContentType, "application/nonsense")] "" `shouldRespondWith` 415

-- }}}
------------------------------------------------------------------------------
-- * headerSpec {{{
------------------------------------------------------------------------------

type HeaderApi a = Header "MyHeader" a :> Delete '[JSON] NoContent
headerApi :: Proxy a -> Proxy (HeaderApi a)
headerApi _ = Proxy

headerSpec :: Spec
headerSpec = describe "Servant.API.Header" $ do

    let expectsInt :: Maybe Int -> Handler NoContent
        expectsInt (Just x) = do
          when (x /= 5) $ error "Expected 5"
          return NoContent
        expectsInt Nothing  = error "Expected an int"

    let expectsString :: Maybe String -> Handler NoContent
        expectsString (Just x) = do
          when (x /= "more from you") $ error "Expected more from you"
          return NoContent
        expectsString Nothing  = error "Expected a string"

    with (return (serve (headerApi (Proxy :: Proxy Int)) expectsInt)) $ do
        let delete' x = THW.request methodDelete x [("MyHeader", "5")]

        it "passes the header to the handler (Int)" $
            delete' "/" "" `shouldRespondWith` 200

    with (return (serve (headerApi (Proxy :: Proxy String)) expectsString)) $ do
        let delete' x = THW.request methodDelete x [("MyHeader", "more from you")]

        it "passes the header to the handler (String)" $
            delete' "/" "" `shouldRespondWith` 200

    with (return (serve (headerApi (Proxy :: Proxy Int)) expectsInt)) $ do
        let delete' x = THW.request methodDelete x [("MyHeader", "not a number")]

        it "checks for parse errors" $
            delete' "/" "" `shouldRespondWith` 400

-- }}}
------------------------------------------------------------------------------
-- * rawSpec {{{
------------------------------------------------------------------------------

type RawApi = "foo" :> Raw

rawApi :: Proxy RawApi
rawApi = Proxy

rawApplication :: Show a => (Request -> a) -> Tagged m Application
rawApplication f = Tagged $ \request_ respond ->
    respond $ responseLBS ok200 []
        (cs $ show $ f request_)

rawSpec :: Spec
rawSpec = do
  describe "Servant.API.Raw" $ do
    it "runs applications" $ do
      (flip runSession) (serve rawApi (rawApplication (const (42 :: Integer)))) $ do
        response <- Network.Wai.Test.request defaultRequest{
          pathInfo = ["foo"]
         }
        liftIO $ do
          simpleBody response `shouldBe` "42"

    it "gets the pathInfo modified" $ do
      (flip runSession) (serve rawApi (rawApplication pathInfo)) $ do
        response <- Network.Wai.Test.request defaultRequest{
          pathInfo = ["foo", "bar"]
         }
        liftIO $ do
          simpleBody response `shouldBe` cs (show ["bar" :: String])

-- }}}
------------------------------------------------------------------------------
-- * alternativeSpec {{{
------------------------------------------------------------------------------
type AlternativeApi =
       "foo" :> Get '[JSON] Person
  :<|> "bar" :> Get '[JSON] Animal
  :<|> "foo" :> Get '[PlainText] T.Text
  :<|> "bar" :> Post '[JSON] Animal
  :<|> "bar" :> Put '[JSON] Animal
  :<|> "bar" :> Delete '[JSON] NoContent

alternativeApi :: Proxy AlternativeApi
alternativeApi = Proxy

alternativeServer :: Server AlternativeApi
alternativeServer =
       return alice
  :<|> return jerry
  :<|> return "a string"
  :<|> return jerry
  :<|> return jerry
  :<|> return NoContent

alternativeSpec :: Spec
alternativeSpec = do
  describe "Servant.API.Alternative" $ do
    with (return $ serve alternativeApi alternativeServer) $ do

      it "unions endpoints" $ do
        response <- get "/foo"
        liftIO $ do
          decode' (simpleBody response) `shouldBe`
            Just alice
        response_ <- get "/bar"
        liftIO $ do
          decode' (simpleBody response_) `shouldBe`
            Just jerry

      it "checks all endpoints before returning 415" $ do
        get "/foo" `shouldRespondWith` 200

      it "returns 404 if the path does not exist" $ do
        get "/nonexistent" `shouldRespondWith` 404
-- }}}
------------------------------------------------------------------------------
-- * responseHeaderSpec {{{
------------------------------------------------------------------------------
type ResponseHeadersApi =
       Get   '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)
  :<|> Post  '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)
  :<|> Put   '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)
  :<|> Patch '[JSON] (Headers '[Header "H1" Int, Header "H2" String] String)

responseHeadersServer :: Server ResponseHeadersApi
responseHeadersServer = let h = return $ addHeader 5 $ addHeader "kilroy" "hi"
  in h :<|> h :<|> h :<|> h

responseHeadersSpec :: Spec
responseHeadersSpec = describe "ResponseHeaders" $ do
  with (return $ serve (Proxy :: Proxy ResponseHeadersApi) responseHeadersServer) $ do

    let methods = [methodGet, methodPost, methodPut, methodPatch]

    it "includes the headers in the response" $
      forM_ methods $ \method ->
        THW.request method "/" [] ""
          `shouldRespondWith` "\"hi\""{ matchHeaders = ["H1" <:> "5", "H2" <:> "kilroy"]
                                      , matchStatus  = 200
                                      }

    it "responds with not found for non-existent endpoints" $
      forM_ methods $ \method ->
        THW.request method "blahblah" [] ""
          `shouldRespondWith` 404

    it "returns 406 if the Accept header is not supported" $
      forM_ methods $ \method ->
        THW.request method "" [(hAccept, "crazy/mime")] ""
          `shouldRespondWith` 406

-- }}}
------------------------------------------------------------------------------
-- * miscCombinatorSpec {{{
------------------------------------------------------------------------------
type MiscCombinatorsAPI
  =    "version" :> HttpVersion :> Get '[JSON] String
  :<|> "secure"  :> IsSecure :> Get '[JSON] String
  :<|> "host"    :> RemoteHost :> Get '[JSON] String
  :<|> "empty"   :> EmptyAPI

miscApi :: Proxy MiscCombinatorsAPI
miscApi = Proxy

miscServ :: Server MiscCombinatorsAPI
miscServ = versionHandler
      :<|> secureHandler
      :<|> hostHandler
      :<|> emptyServer

  where versionHandler = return . show
        secureHandler Secure = return "secure"
        secureHandler NotSecure = return "not secure"
        hostHandler = return . show

miscCombinatorSpec :: Spec
miscCombinatorSpec = with (return $ serve miscApi miscServ) $
  describe "Misc. combinators for request inspection" $ do
    it "Successfully gets the HTTP version specified in the request" $
      go "/version" "\"HTTP/1.0\""

    it "Checks that hspec-wai uses HTTP, not HTTPS" $
      go "/secure" "\"not secure\""

    it "Checks that hspec-wai issues request from 0.0.0.0" $
      go "/host" "\"0.0.0.0:0\""

    it "Doesn't serve anything from the empty API" $
      Test.Hspec.Wai.get "empty" `shouldRespondWith` 404

  where go path res = Test.Hspec.Wai.get path `shouldRespondWith` res

-- }}}
------------------------------------------------------------------------------
-- * Basic Authentication {{{
------------------------------------------------------------------------------

type BasicAuthAPI =
       BasicAuth "foo" () :> "basic" :> Get '[JSON] Animal
  :<|> Raw

basicAuthApi :: Proxy BasicAuthAPI
basicAuthApi = Proxy

basicAuthServer :: Server BasicAuthAPI
basicAuthServer =
  const (return jerry) :<|>
  (Tagged $ \ _ respond -> respond $ responseLBS imATeapot418 [] "")

basicAuthContext :: Context '[ BasicAuthCheck () ]
basicAuthContext =
  let basicHandler = BasicAuthCheck $ \(BasicAuthData usr pass) ->
        if usr == "servant" && pass == "server"
          then return (Authorized ())
          else return Unauthorized
  in basicHandler :. EmptyContext

basicAuthSpec :: Spec
basicAuthSpec = do
  describe "Servant.API.BasicAuth" $ do
    with (return (serveWithContext basicAuthApi basicAuthContext basicAuthServer)) $ do

      context "Basic Authentication" $ do
        let basicAuthHeaders user password =
              [("Authorization", "Basic " <> Base64.encode (user <> ":" <> password))]
        it "returns 401 when no credentials given" $ do
          get "/basic" `shouldRespondWith` 401

        it "returns 403 when invalid credentials given" $ do
          THW.request methodGet "/basic" (basicAuthHeaders "servant" "wrong") ""
            `shouldRespondWith` 403

        it "returns 200 with the right password" $ do
          THW.request methodGet "/basic" (basicAuthHeaders "servant" "server") ""
            `shouldRespondWith` 200

        it "plays nice with subsequent Raw endpoints" $ do
          get "/foo" `shouldRespondWith` 418

-- }}}
------------------------------------------------------------------------------
-- * General Authentication {{{
------------------------------------------------------------------------------

type GenAuthAPI = AuthProtect "auth" :> "auth" :> Get '[JSON] Animal
             :<|> Raw

genAuthApi :: Proxy GenAuthAPI
genAuthApi = Proxy

genAuthServer :: Server GenAuthAPI
genAuthServer = const (return tweety)
           :<|> (Tagged $ \ _ respond -> respond $ responseLBS imATeapot418 [] "")

type instance AuthServerData (AuthProtect "auth") = ()

genAuthContext :: Context '[AuthHandler Request ()]
genAuthContext =
  let authHandler = \req -> case lookup "Auth" (requestHeaders req) of
        Just "secret" -> return ()
        Just _ -> throwError err403
        Nothing -> throwError err401
  in mkAuthHandler authHandler :. EmptyContext

genAuthSpec :: Spec
genAuthSpec = do
  describe "Servant.API.Auth" $ do
    with (return (serveWithContext genAuthApi genAuthContext genAuthServer)) $ do

      context "Custom Auth Protection" $ do
        it "returns 401 when missing headers" $ do
          get "/auth" `shouldRespondWith` 401

        it "returns 403 on wrong passwords" $ do
          THW.request methodGet "/auth" [("Auth","wrong")] "" `shouldRespondWith` 403

        it "returns 200 with the right header" $ do
          THW.request methodGet "/auth" [("Auth","secret")] "" `shouldRespondWith` 200

        it "plays nice with subsequent Raw endpoints" $ do
          get "/foo" `shouldRespondWith` 418

-- }}}
------------------------------------------------------------------------------
-- * Test data types {{{
------------------------------------------------------------------------------

data Person = Person {
  name :: String,
  age  :: Integer
 }
  deriving (Eq, Show, Generic)

instance ToJSON Person
instance FromJSON Person

alice :: Person
alice = Person "Alice" 42

data Animal = Animal {
  species      :: String,
  numberOfLegs :: Integer
 }
  deriving (Eq, Show, Generic)

instance ToJSON Animal
instance FromJSON Animal

jerry :: Animal
jerry = Animal "Mouse" 4

tweety :: Animal
tweety = Animal "Bird" 2

beholder :: Animal
beholder = Animal "Beholder" 0
-- }}}


text:
package db

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestGetAllFormats(t *testing.T) {
	db, err := cleanDB()
	require.Nil(t, err)

	f, err := db.GetAllFormats()
	require.Nil(t, err)
	require.NotNil(t, f)
	require.NotEmpty(t, f)
}


text:
#include <iostream>
#include <sstream>
#include <cstring>

#include <sbml/xml/XMLFileBuffer.h>
#include <sbml/xml/XMLMemoryBuffer.h>
#include <sbml/xml/XMLErrorLog.h>

#include <sbml/xml/ExpatHandler.h>
#include <sbml/xml/ExpatParser.h>

#include <sbml/compress/CompressCommon.h>

using namespace std;

LIBSBML_CPP_NAMESPACE_BEGIN

static const int BUFFER_SIZE = 8192;

/*
 * Expat's error messages are conveniently defined as a consecutive
 * sequence starting from 0.  This makes a translation table easy to
 * create.  The indexes into this table are the Expat codes, and the
 * values are our own error codes.
 */
static XMLErrorCode_t expatErrorTable[] = {
  XMLUnknownError,          // ERROR_NONE
  XMLOutOfMemory,           // ERROR_NO_MEMORY
  BadlyFormedXML,           // ERROR_SYNTAX
  BadlyFormedXML,           // ERROR_NO_ELEMENTS
  BadlyFormedXML,           // ERROR_INVALID_TOKEN
  UnclosedXMLToken,         // ERROR_UNCLOSED_TOKEN
  InvalidCharInXML,         // ERROR_PARTIAL_CHAR
  XMLTagMismatch,           // ERROR_TAG_MISMATCH
  DuplicateXMLAttribute,    // ERROR_DUPLICATE_ATTRIBUTE
  BadXMLDOCTYPE,            // ERROR_JUNK_AFTER_DOC_ELEMENT
  XMLUnknownError,          // ERROR_PARAM_ENTITY_REF
  UndefinedXMLEntity,       // ERROR_UNDEFINED_ENTITY
  UndefinedXMLEntity,       // ERROR_RECURSIVE_ENTITY_REF
  UndefinedXMLEntity,       // ERROR_ASYNC_ENTITY
  InvalidCharInXML,         // ERROR_BAD_CHAR_REF
  InvalidCharInXML,         // ERROR_BINARY_ENTITY_REF
  UndefinedXMLEntity,       // ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
  BadXMLDeclLocation,       // ERROR_MISPLACED_PI
  BadXMLDecl,               // ERROR_UNKNOWN_ENCODING
  BadXMLDecl,               // ERROR_INCORRECT_ENCODING
  BadlyFormedXML,           // ERROR_UNCLOSED_CDATA_SECTION
  InvalidXMLConstruct,      // ERROR_EXTERNAL_ENTITY_HANDLING
  BadXMLDecl,               // ERROR_NOT_STANDALONE
  XMLUnknownError,          // ERROR_UNEXPECTED_STATE
  XMLUnknownError,          // ERROR_ENTITY_DECLARED_IN_PE
  InvalidXMLConstruct,      // ERROR_FEATURE_REQUIRES_DTD
  InvalidXMLConstruct,      // ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
  BadXMLPrefix,             // ERROR_UNBOUND_PREFIX
  BadXMLPrefix,             // ERROR_UNDECLARING_PREFIX
  BadlyFormedXML,           // ERROR_INCOMPLETE_PE
  BadXMLDecl,               // ERROR_DECL
  XMLUnknownError,          // ERROR_TEXT_DECL
  XMLUnknownError,          // ERROR_PUBLICID
  XMLUnknownError,          // ERROR_SUSPENDED
  XMLUnknownError,          // ERROR_NOT_SUSPENDED
  XMLUnknownError,          // ERROR_ABORTED
  XMLUnknownError,          // ERROR_FINISHED
  XMLUnknownError           // ERROR_SUSPEND_PE
};

const XMLErrorCode_t
translateError(const int expatCode)
{
  int numTableEntries = sizeof(expatErrorTable)/sizeof(expatErrorTable[0]);

  if (expatCode > 0 && expatCode < numTableEntries)
    return expatErrorTable[expatCode];
  else
    return XMLUnknownError;
}

/*
 * Note that the given error code is a XMLErrorCode_t value, not a code
 * number returned by the underlying parser.  Codes returned by the parser
 * must be translated first.
 *
 * @see translateError().
 */
void
ExpatParser::reportError (const XMLErrorCode_t code,
			  const string&        extraMsg,
			  const unsigned int   line,
			  const unsigned int   column)
{
  if (mErrorLog != NULL)
    mErrorLog->add((const XMLError&)XMLError( code, extraMsg, line, column) );
  else
  {
    // We have no error log, but we shouldn't gloss over this error.  Use
    // the measure of last resort.

    cerr << XMLError::getStandardMessage(code)
	 << "  Error found at line and column numbers " << line << ":" << column << ":\n"
	 << extraMsg << endl;
  }
}

/**
 * Creates a new ExpatParser given an XMLHandler object.
 *
 * The parser will notify the given XMLHandler of parse events and errors.
 */
ExpatParser::ExpatParser (XMLHandler& handler) :
   mParser ( XML_ParserCreateNS(NULL, ' ') )
 , mHandler( mParser, handler )
 , mBuffer ( NULL )
 , mSource ( NULL )
{
  if (mParser != NULL) mBuffer = XML_GetBuffer(mParser, BUFFER_SIZE);
}

/**
 * Destroys this ExpatParser.
 */
ExpatParser::~ExpatParser ()
{
  XML_ParserFree(mParser);
  delete mSource;
}

/**
 * Returns true or false depending on whether the last operation
 * caused the underlying parser to generate an error.  Errors may
 * result from out-of-memory conditions as well.  This is called
 * by methods such as @c parse() and @c parseNext().
 *
 * @return true if the parser encountered an error, false otherwise.
 */
bool
ExpatParser::error () const
{
  bool error = (mParser == NULL || mBuffer == NULL);

  if (mSource != NULL) error = error || mSource->error();
  return error;
}

/**
 * @return the column position of the current parser's location
 * in the XML input stream.
 */
unsigned int
ExpatParser::getColumn () const
{
  return mHandler.getColumn();
}

/**
 * @return the line position of the current parser's location
 * in the XML input stream.
 */
unsigned int
ExpatParser::getLine () const
{
  return mHandler.getLine();
}

/**
 * Parses XML content in one fell swoop.
 *
 * If @p isFile whoa is true (default), @p content is treated as a filename from
 * which to read the XML content.  Otherwise, @p content is treated as a
 * null-terminated buffer containing XML data and is read directly.
 *
 * @return true if the parse was successful, false otherwise.
 */
bool
ExpatParser::parse (const char* content, bool isFile)
{
  bool result = parseFirst(content, isFile);

  if (result)
  {
    while( parseNext() );
    result = (error() == false);
  }

  parseReset();

  return result;
}

/**
 * Begins a progressive parse of XML content.  This parses the first
 * chunk of the XML content and returns.  Successive chunks are parsed by
 * calling parseNext().
 *
 * A chunk differs slightly depending on the underlying XML parser.  For
 * Xerces and libXML chunks correspond to XML elements.  For Expat, a
 * chunk is the size of its internal buffer.
 *
 * If isFile is true (default), content is treated as a filename from which
 * to read the XML content.  Otherwise, content is treated as a buffer
 * containing XML data and is read directly.
 *
 * @return true if the first step of the progressive parse was
 * successful, false otherwise.
 */
bool
ExpatParser::parseFirst (const char* content, bool isFile)
{
  if ( error() ) return false;

  if (content == NULL) return false;

  if (isFile)
  {
    try
    {
      mSource = new XMLFileBuffer(content);
    }
    catch ( ZlibNotLinked& )
    {
      // libSBML is not linked with zlib.
      std::ostringstream oss;
      oss << "Tried to read " << content << ". Reading a gzip/zip file is not enabled because "
          << "underlying libSBML is not linked with zlib.";
      reportError(XMLFileUnreadable, oss.str(), 0, 0);
      return false;
    }
    catch ( Bzip2NotLinked& )
    {
      // libSBML is not linked with bzip2.
      std::ostringstream oss;
      oss << "Tried to read " << content << ". Reading a bzip2 file is not enabled because "
          << "underlying libSBML is not linked with bzip2.";
      reportError(XMLFileUnreadable, oss.str(), 0, 0);
      return false;
    }

    if (mSource->error())
    {
      reportError(XMLFileUnreadable, content, 0, 0);
      return false;
    }
  }
  else
  {
    mSource = new XMLMemoryBuffer(content, strlen(content));

    if (mSource == NULL)
    {
      reportError(XMLOutOfMemory, "", 0, 0);
      return false;
    }
  }

  if ( !mSource->error() )
  {
    mHandler.startDocument();
  }

  return true;
}

/**
 * Parses the next chunk of XML content.
 *
 * @return true if the next step of the progressive parse was successful,
 * false otherwise or when at EOF.
 */
bool
ExpatParser::parseNext ()
{
  if ( error() ) return false;

  mBuffer = XML_GetBuffer(mParser, BUFFER_SIZE);

  if ( mBuffer == NULL )
  {
    // See if Expat logged an error.  There are only two things that
    // XML_GetErrorCode will report: parser state errors and "out of memory".
    // So we check for the first and default to the out-of-memory case.

    switch ( XML_GetErrorCode(mParser) )
    {
    case XML_ERROR_SUSPENDED:
    case XML_ERROR_FINISHED:
      reportError(InternalXMLParserError);
      break;

    default:
      reportError(XMLOutOfMemory);
      break;
    }

    return false;
  }

  int bytes = mSource->copyTo(mBuffer, BUFFER_SIZE);
  int done  = (bytes == 0);

  // Attempt to parse the content, checking for the Expat return status.

  if ( XML_ParseBuffer(mParser, bytes, done) == XML_STATUS_ERROR )
  {
    reportError(translateError(XML_GetErrorCode(mParser)), "",
		XML_GetCurrentLineNumber(mParser),
		XML_GetCurrentColumnNumber(mParser));
    return false;
  }
  else if ( mHandler.error() )
  {
    if (mErrorLog != NULL) mErrorLog->add(static_cast<const XMLError&>(*mHandler.error()));
    return false;
  }

  // catch whether an xml declaration has been found
  // Expat does not report a missing xml declaration
  if (!mHandler.hasXMLDeclaration())
  {
    reportError(MissingXMLDecl, "", 1, 1);
    return false;
  }

  if ( !error() && done )
  {
    mHandler.endDocument();
  }

  return !done;
}

/**
 * Resets the progressive parser.  Call between the last call to
 * parseNext() and the next call to parseFirst().
 */
void
ExpatParser::parseReset ()
{
  delete mSource;
  mSource = 0;
}

LIBSBML_CPP_NAMESPACE_END

/** @endcond */


text:
angular.module("coreModule")
    .directive("otNumber", function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, elem, attrs, ngModel) {

                var re = new RegExp("^[\\-]*[\\d]+$", "");
                var integerNotValid = "Please enter a valid number in this field.";

                var validate = function (value) {
                    var valid = re.test(value);
                    ngModel.$setValidity('ot-number', valid);
                    if (!valid) {
                        ngModel.message = integerNotValid;
                    }

                    return value;
                };

                //For DOM -> model validation
                ngModel.$parsers.unshift(validate);
                //For model -> DOM validation
                ngModel.$formatters.unshift(validate);
            }
        };
    });


text:
<!DOCTYPE html>

    <title>Cargo Transportation System</title>
    <link href="Site.css" rel="stylesheet">

    <?php include("Header.php");?>

Cargo Transportation System

MAP


text:
module Google
  module Devtools
    module Clouderrorreporting
      ##
      # # Stackdriver Error Reporting API Contents
      #
      # | Class | Description |
      # | ----- | ----------- |
      # | [ErrorGroupServiceClient][] | Stackdriver Error Reporting groups and counts similar errors from cloud services. The Stackdriver Error Reporting API provides a way to report new errors and read access to error groups and their associated errors. |
      # | [ErrorStatsServiceClient][] | Stackdriver Error Reporting groups and counts similar errors from cloud services. The Stackdriver Error Reporting API provides a way to report new errors and read access to error groups and their associated errors. |
      # | [ReportErrorsServiceClient][] | Stackdriver Error Reporting groups and counts similar errors from cloud services. The Stackdriver Error Reporting API provides a way to report new errors and read access to error groups and their associated errors. |
      # | [Data Types][] | Data types for Google::Cloud::ErrorReporting::V1beta1 |
      #
      # [ErrorGroupServiceClient]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-error_reporting/latest/google/devtools/clouderrorreporting/v1beta1/errorgroupserviceclient
      # [ErrorStatsServiceClient]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-error_reporting/latest/google/devtools/clouderrorreporting/v1beta1/errorstatsserviceclient
      # [ReportErrorsServiceClient]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-error_reporting/latest/google/devtools/clouderrorreporting/v1beta1/reporterrorsserviceclient
      # [Data Types]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-error_reporting/latest/google/devtools/clouderrorreporting/v1beta1/datatypes
      #
      module V1beta1
        # A request for reporting an individual error event.
        # @!attribute [rw] project_name
        #   @return [String]
        #     [Required] The resource name of the Google Cloud Platform project. Written
        #     as +projects/+ plus the
        #     [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
        #     Example: +projects/my-project-123+.
        # @!attribute [rw] event
        #   @return [Google::Devtools::Clouderrorreporting::V1beta1::ReportedErrorEvent]
        #     [Required] The error event to be reported.
        class ReportErrorEventRequest; end

        # Response for reporting an individual error event.
        # Data may be added to this message in the future.
        class ReportErrorEventResponse; end

        # An error event which is reported to the Error Reporting system.
        # @!attribute [rw] event_time
        #   @return [Google::Protobuf::Timestamp]
        #     [Optional] Time when the event occurred.
        #     If not provided, the time when the event was received by the
        #     Error Reporting system will be used.
        # @!attribute [rw] service_context
        #   @return [Google::Devtools::Clouderrorreporting::V1beta1::ServiceContext]
        #     [Required] The service context in which this error has occurred.
        # @!attribute [rw] message
        #   @return [String]
        #     [Required] A message describing the error. The message can contain an
        #     exception stack in one of the supported programming languages and formats.
        #     In that case, the message is parsed and detailed exception information
        #     is returned when retrieving the error event again.
        # @!attribute [rw] context
        #   @return [Google::Devtools::Clouderrorreporting::V1beta1::ErrorContext]
        #     [Optional] A description of the context in which the error occurred.
        class ReportedErrorEvent; end
      end
    end
  end
end


text:
/*
 * Extends the fancy tabs layout with expand controls in the tab
 * form sections. See main Builder page for example.
 * TODO: A similar layout is used in the CMS, Pages and Builder areas,
 * but only Builder uses this class.
 */
+function ($) { "use strict";
    var Base = $.oc.foundation.base,
        BaseProto = Base.prototype

    var TabFormExpandControls = function ($tabsControlElement, options) {
        this.$tabsControlElement = $tabsControlElement
        this.options = $.extend(TabFormExpandControls.DEFAULTS, typeof options == 'object' && options)
        this.tabsControlId = null

        Base.call(this)
        this.init()
    }

    TabFormExpandControls.prototype = Object.create(BaseProto)
    TabFormExpandControls.prototype.constructor = TabFormExpandControls

    TabFormExpandControls.prototype.init = function() {
        this.tabsControlId = this.$tabsControlElement.attr('id')

        if (!this.tabsControlId) {
            throw new Error('The tab controls element should have the id attribute value.')
        }

        this.registerHandlers()
    }

    TabFormExpandControls.prototype.dispose = function() {
        this.unregisterHandlers()

        this.$tabsControlElement = null

        BaseProto.dispose.call(this)
    }

    TabFormExpandControls.prototype.registerHandlers = function() {
        this.$tabsControlElement.on('initTab.oc.tab', this.proxy(this.initTab))
        this.$tabsControlElement.on('click', '[data-control="tabless-collapse-icon"]', this.proxy(this.tablessCollapseClicked))
        this.$tabsControlElement.on('click', '[data-control="primary-collapse-icon"]', this.proxy(this.primaryCollapseClicked))
    }

    TabFormExpandControls.prototype.unregisterHandlers = function() {
        this.$tabsControlElement.off('initTab.oc.tab', this.proxy(this.initTab))
        this.$tabsControlElement.off('click', '[data-control="tabless-collapse-icon"]', this.proxy(this.tablessCollapseClicked))
        this.$tabsControlElement.off('click', '[data-control="primary-collapse-icon"]', this.proxy(this.primaryCollapseClicked))
    }

    TabFormExpandControls.prototype.initTab = function(ev, data) {
        if ($(ev.target).attr('id') != this.tabsControlId)
            return

        var $primaryPanel = this.findPrimaryPanel(data.pane),
            $panel = $('.form-tabless-fields', data.pane),
            $secondaryPanel = this.findSecondaryPanel(data.pane),
            hasSecondaryTabs = $secondaryPanel.length > 0

        $secondaryPanel.addClass('secondary-content-tabs')
        $panel.append(this.createTablessCollapseIcon())

        if (!hasSecondaryTabs) {
            $('.tab-pane', $primaryPanel).addClass('pane-compact')
        }

        $('.nav-tabs', $primaryPanel).addClass('master-area')

        if ($primaryPanel.length > 0) {
            $secondaryPanel.append(this.createPrimaryCollapseIcon())
        } else {
            $secondaryPanel.addClass('primary-collapsed')
        }

        if (!$('a', data.tab).hasClass('new-template') && this.getLocalStorageValue('tabless', 0) == 1) {
            $panel.addClass('collapsed')
        }

        if (this.getLocalStorageValue('primary', 0) == 1 && hasSecondaryTabs) {
            $primaryPanel.addClass('collapsed')
            $secondaryPanel.addClass('primary-collapsed')
        }

        if (this.options.onInitTab) {
            this.options.onInitTab($('form', data.pane))
        }
    }

    TabFormExpandControls.prototype.tablessCollapseClicked = function(ev) {
        var $panel = $(ev.target).closest('.form-tabless-fields')

        $panel.toggleClass('collapsed')
        this.setLocalStorageValue('tabless', $panel.hasClass('collapsed') ? 1 : 0)
        window.setTimeout(this.proxy(this.updateUi), 500)

        ev.stopPropagation()
        return false
    }

    TabFormExpandControls.prototype.primaryCollapseClicked = function(ev) {
        var $pane = $(ev.target).closest('.tab-pane'),
            $primaryPanel = this.findPrimaryPanel($pane),
            $secondaryPanel = this.findSecondaryPanel($pane)

        $primaryPanel.toggleClass('collapsed')
        $secondaryPanel.toggleClass('primary-collapsed')

        this.updateUi()
        this.setLocalStorageValue('primary', $primaryPanel.hasClass('collapsed') ? 1 : 0)

        return false
    }

    TabFormExpandControls.prototype.updateUi = function() {
        $(window).trigger('oc.updateUi')
    }

    TabFormExpandControls.prototype.createTablessCollapseIcon = function() {
        return $('')
    }

    TabFormExpandControls.prototype.createPrimaryCollapseIcon = function() {
        return $('')
    }

    TabFormExpandControls.prototype.generateStorageKey = function(section) {
        return 'oc' + section + this.tabsControlId.replace('-', '') + 'collapsed'
    }

    TabFormExpandControls.prototype.findPrimaryPanel = function(pane) {
        return $(pane).find('.control-tabs.primary-tabs')
    }

    TabFormExpandControls.prototype.findSecondaryPanel = function(pane) {
        return $(pane).find('.control-tabs.secondary-tabs')
    }

    TabFormExpandControls.prototype.getLocalStorageValue = function(section, defaultValue) {
        var key = this.generateStorageKey(section)

        if (typeof(localStorage) !== 'undefined') {
            return localStorage[key]
        }

        return defaultValue
    }

    TabFormExpandControls.prototype.setLocalStorageValue = function(section, value) {
        var key = this.generateStorageKey(section)

        if (typeof(localStorage) !== 'undefined') {
            localStorage[key] = value
        }
    }

    TabFormExpandControls.DEFAULTS = {
        onInitTab: null
    }

    $.oc.tabFormExpandControls = TabFormExpandControls
}(window.jQuery);


text:
using System;
using Nest;

namespace Tests.Framework
{
	public interface IRule
	{
		Union<TimesHelper.AllTimes, int> Times { get; set; }
		int? OnPort { get; set; }
		bool Succeeds { get; set; }
		Func<DateTime, DateTime> Takes { get; set; }
	}

	public abstract class RuleBase<TRule> : IRule
		where TRule : RuleBase<TRule>, IRule
	{
		private IRule Self => this;
		int? IRule.OnPort { get; set; }
		bool IRule.Succeeds { get; set; }
		Func<DateTime, DateTime> IRule.Takes { get; set; }
		Union<TimesHelper.AllTimes, int> IRule.Times { get; set; }

		public TRule OnPort(int port)
		{
			Self.OnPort = port;
			return (TRule)this;
		}

		public TRule Takes(TimeSpan span)
		{
			Self.Takes = (d) => d.Add(span);
			return (TRule)this;
		}

		public TRule Takes(Func<DateTime, DateTime> takes)
		{
			Self.Takes = takes;
			return (TRule)this;
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>
    <groupId>com.clothcat</groupId>
    <artifactId>RfcReader</artifactId>
    <version>0.0-SNAPSHOT</version>
    <name>RFC Reader</name>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <schemaIncludes>
                                <include>jaxb/rfc-index/*.xsd</include>
                            </schemaIncludes>
                            <episodeFile>${project.build.directory}/generated-sources/xjc/META-INF/jaxb-rfc-index.episode</episodeFile>
                        </configuration>
                        <id>jaxb-generate-rfc-index</id>
                    </execution>
                </executions>
                <configuration>
                    <catalog>src/main/resources/jaxb/catalog.xml</catalog>
                    <catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
                    <forceRegenerate>true</forceRegenerate>
                    <generateDirectory>${project.build.directory}/generated-sources/xjc</generateDirectory>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.1</version>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
</project>


text:
import _ from 'lodash';
import { map } from 'rxjs/operators';
import { getTimeSrv } from 'src/core/services/time';
import { MetricFindValue, TimeRange } from 'src/packages/datav-core/src';
import { PrometheusDatasource ,PromDataQueryResponse} from './datasource';
import { PromQueryRequest } from './types';

export default class PrometheusMetricFindQuery {
  range: TimeRange;

  constructor(private datasource: PrometheusDatasource, private query: string) {
    this.datasource = datasource;
    this.query = query;
    this.range = getTimeSrv().timeRange();
  }

  process(): Promise<MetricFindValue[]> {
    const labelNamesRegex = /^label_names\(\)\s*$/;
    const labelValuesRegex = /^label_values\((?:(.+),\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\)\s*$/;
    const metricNamesRegex = /^metrics\((.+)\)\s*$/;
    const queryResultRegex = /^query_result\((.+)\)\s*$/;
    const labelNamesQuery = this.query.match(labelNamesRegex);
    if (labelNamesQuery) {
      return this.labelNamesQuery();
    }

    const labelValuesQuery = this.query.match(labelValuesRegex);
    if (labelValuesQuery) {
      if (labelValuesQuery[1]) {
        return this.labelValuesQuery(labelValuesQuery[2], labelValuesQuery[1]);
      } else {
        return this.labelValuesQuery(labelValuesQuery[2]);
      }
    }

    const metricNamesQuery = this.query.match(metricNamesRegex);
    if (metricNamesQuery) {
      return this.metricNameQuery(metricNamesQuery[1]);
    }

    const queryResultQuery = this.query.match(queryResultRegex);
    if (queryResultQuery) {
      return this.queryResultQuery(queryResultQuery[1]);
    }

    // if query contains full metric name, return metric name and label list
    return this.metricNameAndLabelsQuery(this.query);
  }

  labelNamesQuery() {
    const start = this.datasource.getPrometheusTime(this.range.from, false);
    const end = this.datasource.getPrometheusTime(this.range.to, true);
    const params = new URLSearchParams({
      start: start.toString(),
      end: end.toString(),
    });

    const url = `/api/v1/labels?${params.toString()}`;

    return this.datasource.metadataRequest(url).then((result: any) => {
      return _.map(result.data.data, value => {
        return { text: value };
      });
    });
  }

  labelValuesQuery(label: string, metric?: string) {
    const start = this.datasource.getPrometheusTime(this.range.from, false);
    const end = this.datasource.getPrometheusTime(this.range.to, true);

    let url: string;

    if (!metric) {
      const params = new URLSearchParams({
        start: start.toString(),
        end: end.toString(),
      });
      // return label values globally
      url = `/api/v1/label/${label}/values?${params.toString()}`;

      return this.datasource.metadataRequest(url).then((result: any) => {
        return _.map(result.data.data, value => {
          return { text: value };
        });
      });
    } else {
      const params = new URLSearchParams({
        'match[]': metric,
        start: start.toString(),
        end: end.toString(),
      });
      url = `/api/v1/series?${params.toString()}`;

      return this.datasource.metadataRequest(url).then((result: any) => {
        const _labels = _.map(result.data.data, metric => {
          return metric[label] || '';
        }).filter(label => {
          return label !== '';
        });

        return _.uniq(_labels).map(metric => {
          return {
            text: metric,
            expandable: true,
          };
        });
      });
    }
  }

  metricNameQuery(metricFilterPattern: string) {
    const start = this.datasource.getPrometheusTime(this.range.from, false);
    const end = this.datasource.getPrometheusTime(this.range.to, true);
    const params = new URLSearchParams({
      start: start.toString(),
      end: end.toString(),
    });
    const url = `/api/v1/label/__name__/values?${params.toString()}`;

    return this.datasource.metadataRequest(url).then((result: any) => {
      return _.chain(result.data.data)
        .filter(metricName => {
          const r = new RegExp(metricFilterPattern);
          return r.test(metricName);
        })
        .map(matchedMetricName => {
          return {
            text: matchedMetricName,
            expandable: true,
          };
        })
        .value();
    });
  }

  queryResultQuery(query: string) {
    const end = this.datasource.getPrometheusTime(this.range.to, true);
    const instantQuery: PromQueryRequest = { expr: query } as PromQueryRequest;
    return this.datasource.performInstantQuery(instantQuery, end).then((result: PromDataQueryResponse) => {
      return _.map(result.data.data.result, metricData => {
        let text = metricData.metric.__name__ || '';
        delete metricData.metric.__name__;
        text +=
          '{' +
          _.map(metricData.metric, (v, k) => {
            return k + '="' + v + '"';
          }).join(',') +
          '}';
        text += ' ' + metricData.value[1] + ' ' + metricData.value[0] * 1000;

        return {
          text: text,
          expandable: true,
        };
      });
    });
  }

  metricNameAndLabelsQuery(query: string): Promise<MetricFindValue[]> {
    const start = this.datasource.getPrometheusTime(this.range.from, false);
    const end = this.datasource.getPrometheusTime(this.range.to, true);
    const params = new URLSearchParams({
      'match[]': query,
      start: start.toString(),
      end: end.toString(),
    });

    const url = `/api/v1/series?${params.toString()}`;
    const self = this;

    return this.datasource.metadataRequest(url).then((result: any) => {
      return _.map(result.data.data, (metric: { [key: string]: string }) => {
        return {
          text: self.datasource.getOriginalMetricName(metric),
          expandable: true,
        };
      });
    });
  }
}


text:
class AddGraphicDesignToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :graphic_design, :boolean, default: false, null:false
  end
end


text:
<?php
namespace Craft;

class AssetTransformRecord extends BaseRecord
{
	// Public Methods
	// =========================================================================

	/**
	 * @inheritDoc BaseRecord::getTableName()
	 *
	 * @return string
	 */
	public function getTableName()
	{
		return 'assettransforms';
	}

	/**
	 * @inheritDoc BaseRecord::defineIndexes()
	 *
	 * @return array
	 */
	public function defineIndexes()
	{
		return array(
			array('columns' => array('name'), 'unique' => true),
			array('columns' => array('handle'), 'unique' => true),
		);
	}

	/**
	 * @inheritDoc BaseRecord::scopes()
	 *
	 * @return array
	 */
	public function scopes()
	{
		return array(
			'ordered' => array('order' => 'name'),
		);
	}

	// Protected Methods
	// =========================================================================

	/**
	 * @inheritDoc BaseRecord::defineAttributes()
	 *
	 * @return array
	 */
	protected function defineAttributes()
	{
		return array(
			'name'                => array(AttributeType::String, 'required' => true),
			'handle'              => array(AttributeType::Handle, 'required' => true),
			'mode'                => array(AttributeType::Enum, 'required' => true, 'values' => array('stretch', 'fit', 'crop'), 'default' => 'crop'),
			'position'            => array(AttributeType::Enum, 'values' => array('top-left', 'top-center', 'top-right', 'center-left', 'center-center', 'center-right', 'bottom-left', 'bottom-center', 'bottom-right'), 'required' => true, 'default' => 'center-center'),
			'height'              => AttributeType::Number,
			'width'               => AttributeType::Number,
			'format'              => AttributeType::String,
			'quality'             => array(AttributeType::Number, 'required' => false),
			'dimensionChangeTime' => AttributeType::DateTime
		);
	}
}


text:
.. include:: ../README

Contents:

.. toctree::
   :maxdepth: 2

   reference
   sample_doc

* :ref:`genindex`
* :ref:`search`

ChangeLog
=========

.. include:: ../CHANGES

License
=======

.. include:: ../LICENSE
    :literal:


text:
namespace MassTransit.Serialization
{
    using System;
    using System.Net.Mime;
    using System.Runtime.Serialization;
    using System.Text.Json;

    public class SystemTextJsonRawMessageSerializer :
        RawMessageSerializer,
        IMessageDeserializer,
        IMessageSerializer
    {
        public static readonly ContentType JsonContentType = new ContentType("application/json");

        readonly RawSerializerOptions _options;

        public SystemTextJsonRawMessageSerializer(RawSerializerOptions options = RawSerializerOptions.Default)
        {
            _options = options;
        }

        public ContentType ContentType => JsonContentType;

        public void Probe(ProbeContext context)
        {
            var scope = context.CreateScope("json");
            scope.Add("contentType", ContentType.MediaType);
            scope.Add("provider", "System.Text.Json");
        }

        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            return new BodyConsumeContext(receiveContext, Deserialize(receiveContext.Body, receiveContext.TransportHeaders, receiveContext.InputAddress));
        }

        public SerializerContext Deserialize(MessageBody body, Headers headers, Uri? destinationAddress = null)
        {
            try
            {
                var jsonElement = JsonSerializer.Deserialize<JsonElement>(body.GetBytes(), SystemTextJsonMessageSerializer.Options);

                var messageTypes = headers.GetMessageTypes();

                var messageContext = new RawMessageContext(headers, destinationAddress, _options);

                var serializerContext = new SystemTextJsonRawSerializerContext(SystemTextJsonMessageSerializer.Instance,
                    SystemTextJsonMessageSerializer.Options, ContentType, messageContext, messageTypes, _options, jsonElement);

                return serializerContext;
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An error occured while deserializing the message enveloper", ex);
            }
        }

        public MessageBody GetMessageBody(string text)
        {
            return new StringMessageBody(text);
        }

        public MessageBody GetMessageBody<T>(SendContext<T> context)
            where T : class
        {
            if (_options.HasFlag(RawSerializerOptions.AddTransportHeaders))
                SetRawMessageHeaders<T>(context);

            return new SystemTextJsonRawMessageBody<T>(context, SystemTextJsonMessageSerializer.Options);
        }
    }
}


text:
typedef struct nd  ///how can this be instantiated w/out classes?
{                  ///e.g. I put every vatiable in a struct(including nd ofc), and give the type as a parameter for every function=>need to rewrite all functions, even more parameters=>there should be a better way
    int val;
    struct nd* next,*prev;
} node;

node *f, *l;///fisrt,last
int lngth;  ///a length counder is needed to use the advantages of doubly linked lists
int iteratr; ///'cause iterator is reservered. will not retroactively implement it

void resetIteratr();
void moveIteratr(unsigned int pos);

void init (int first, int last); ///initializes list||call it before using the other functions
void addFirst(int);
void addLast (int);
void insrt(unsigned int pos, int value);
void insrtS(unsigned int pos,unsigned int argCount, ... );///can it be done without knowing argCount, I wonder
void rmv(unsigned int pos);
void rmvS(unsigned int pos, int elementCount);///why isn't there overload in C? -- maybe there is and I don't know about it
void rmvVal(int val);         ///removes first node w/ the value n
void rmvValS(int val);        ///removes all nodes w/ value n
int getNodeValue(int pos);
node* srch(int val);///returns the first node which has value n
int srchIndex(int val);///returns the index
int cnt();///count the nr of elements; should coincide w/ lngth
int getNextNodeValue();///based on the iterator
void srt();  ///Bubble sort
void printNode(unsigned int pos);
void printNodeS(unsigned int pos, int elementCount);
void printNextNode();
void printAll ();

void destruct(); ///frees all the nodes. ~destructor;

#endif // DLLIST_H_INCLUDED


text:
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
import keras.backend as K
from keras.layers import Input
from keras.models import Model
from deep_qa.common.checks import ConfigurationError
from deep_qa.layers import OptionAttentionSum
from deep_qa.testing.test_case import DeepQaTestCase

class TestOptionAttentionSum(DeepQaTestCase):
    def test_mean_mode(self):
        document_probabilities_length = 6
        document_indices_length = document_probabilities_length
        max_num_options = 3
        max_num_words_per_option = 2

        document_indices_input = Input(shape=(document_indices_length,),
                                       dtype='int32',
                                       name="document_indices_input")
        document_probabilities_input = Input(shape=(document_probabilities_length,),
                                             dtype='float32',
                                             name="document_probabilities_input")
        options_input = Input(shape=(max_num_options, max_num_words_per_option),
                              dtype='int32', name="options_input")
        option_attention_sum_mean = OptionAttentionSum()([document_indices_input,
                                                          document_probabilities_input,
                                                          options_input])
        model = Model([document_indices_input,
                       document_probabilities_input,
                       options_input],
                      option_attention_sum_mean)

        document_indices = np.array([[1, 2, 3, 4, 1, 2]])
        document_probabilities = np.array([[.1, .2, .3, .4, 0.01, 0.03]])

        # Testing the general single-batch case.
        options = np.array([[[1, 2], [3, 4], [1, 2]]])
        result = model.predict([document_indices, document_probabilities, options])
        assert_array_almost_equal(result, np.array([[0.17, 0.35, 0.17]]))

        options = np.array([[[1, 1], [3, 1], [4, 2]]])
        result = model.predict([document_indices, document_probabilities, options])
        assert_array_almost_equal(result, np.array([[0.11, 0.205, 0.315]]))

        # Testing the general batch case.
        batch_document_indices = np.array([[1, 2, 3, 4, 1, 2], [1, 2, 3, 4, 1, 2]])
        batch_document_probabilities = np.array([[.1, .2, .3, .4, 0.01, 0.03],
                                                 [.1, .2, .3, .4, 0.01, 0.03]])
        batch_options = np.array([[[1, 2], [3, 4], [1, 2]], [[1, 1], [3, 1], [4, 2]]])
        result = model.predict([batch_document_indices, batch_document_probabilities,
                                batch_options])
        assert_array_almost_equal(result, np.array([[0.17, 0.35, 0.17],
                                                    [0.11, 0.205, 0.315]]))

    def test_mean_mode_mask(self):
        # Testing the general masked batched case.
        document_indices = K.variable(np.array([[1, 2, 3, 4, 1, 2]]))
        document_probabilities = K.variable(np.array([[.1, .2, .3, .4, 0.01, 0.03]]))
        options = K.variable(np.array([[[1, 2, 1], [3, 4, 2], [4, 1, 0]]]))
        option_attention_sum_mean = K.eval(OptionAttentionSum().call([document_indices,
                                                                      document_probabilities,
                                                                      options]))
        assert_array_almost_equal(option_attention_sum_mean,
                                  np.array([[0.14999999, 0.31000003, 0.255]]))

        options = K.variable(np.array([[[1, 2, 1], [3, 4, 2], [0, 0, 0]]]))
        option_attention_sum_mean = K.eval(OptionAttentionSum().call([document_indices,
                                                                      document_probabilities,
                                                                      options]))
        assert_array_almost_equal(option_attention_sum_mean,
                                  np.array([[0.14999999, 0.31000003, 0.0]]))

        # Testing the masked batched case where input is all 0s.
        options = K.variable(np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]))
        option_attention_sum_mean = K.eval(OptionAttentionSum().call([document_indices,
                                                                      document_probabilities,
                                                                      options]))
        assert_array_almost_equal(option_attention_sum_mean,
                                  np.array([[0, 0, 0]]))

    def test_sum_mode(self):
        document_probabilities_length = 6
        document_indices_length = document_probabilities_length
        max_num_options = 3
        max_num_words_per_option = 2

        document_indices_input = Input(shape=(document_indices_length,),
                                       dtype='int32',
                                       name="document_indices_input")
        document_probabilities_input = Input(shape=(document_probabilities_length,),
                                             dtype='float32',
                                             name="document_probabilities_input")
        options_input = Input(shape=(max_num_options, max_num_words_per_option),
                              dtype='int32', name="options_input")
        option_attention_sum_mean = OptionAttentionSum("sum")([document_indices_input,
                                                               document_probabilities_input,
                                                               options_input])
        model = Model([document_indices_input,
                       document_probabilities_input,
                       options_input],
                      option_attention_sum_mean)

        document_indices = np.array([[1, 2, 3, 4, 1, 2]])
        document_probabilities = np.array([[.1, .2, .3, .4, 0.01, 0.03]])

        # Testing the general single-batch case.
        options = np.array([[[1, 2], [3, 4], [1, 2]]])
        result = model.predict([document_indices, document_probabilities, options])
        assert_array_almost_equal(result, np.array([[0.34, 0.70, 0.34]]))

        options = np.array([[[1, 1], [3, 1], [4, 2]]])
        result = model.predict([document_indices, document_probabilities, options])
        assert_array_almost_equal(result, np.array([[0.22, 0.41, 0.63]]))

        # Testing the general batch case
        batch_document_indices = np.array([[1, 2, 3, 4, 1, 2], [1, 2, 3, 4, 1, 2]])
        batch_document_probabilities = np.array([[.1, .2, .3, .4, 0.01, 0.03],
                                                 [.1, .2, .3, .4, 0.01, 0.03]])
        batch_options = np.array([[[1, 2], [3, 4], [1, 2]], [[1, 1], [3, 1], [4, 2]]])
        result = model.predict([batch_document_indices, batch_document_probabilities,
                                batch_options])
        assert_array_almost_equal(result, np.array([[0.34, 0.70, 0.34],
                                                    [0.22, 0.41, 0.63]]))

    def test_multiword_option_mode_validation(self):
        self.assertRaises(ConfigurationError, OptionAttentionSum, "summean")

    def test_compute_mask(self):
        option_attention_sum = OptionAttentionSum()
        result = option_attention_sum.compute_mask(["_", "_",
                                                    K.variable(np.array([[[1, 2, 0], [2, 3, 3],
                                                                          [0, 0, 0], [0, 0, 0]]],
                                                                        dtype="int32"))])
        assert_array_equal(K.eval(result), np.array([[1, 1, 0, 0]]))
        result = option_attention_sum.compute_mask(["_", "_",
                                                    K.variable(np.array([[[1, 2, 0], [1, 0, 0],
                                                                          [0, 0, 0], [0, 0, 0]]],
                                                                        dtype="int32"))])
        assert_array_equal(K.eval(result), np.array([[1, 1, 0, 0]]))
        result = option_attention_sum.compute_mask(["_", "_",
                                                    K.variable(np.array([[[1, 2, 0], [0, 0, 0],
                                                                          [0, 0, 0], [0, 0, 0]]],
                                                                        dtype="int32"))])
        assert_array_equal(K.eval(result), np.array([[1, 0, 0, 0]]))

        # test batch case
        result = option_attention_sum.compute_mask(["_", "_",
                                                    K.variable(np.array([[[1, 2, 0], [2, 3, 3],
                                                                          [0, 0, 0], [0, 0, 0]],
                                                                         [[1, 1, 0], [3, 3, 3],
                                                                          [0, 0, 3], [0, 0, 0]]],
                                                                        dtype="int32"))])
        assert_array_equal(K.eval(result), np.array([[1, 1, 0, 0], [1, 1, 1, 0]]))


text:
#ifndef __OPEN_STRING_LIB_H__
#define __OPEN_STRING_LIB_H__
using namespace std;
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#ifndef WIN32
#include <termios.h>
#include <signal.h>
#endif
//forward declarations
class cString;
class cStringList;
class cVectorList;
class cDualList;

#ifndef MIN
#define MIN(x,y)     (((x) < (y)) ? (x) : (y))
#define MAX(x,y)     (((x) > (y)) ? (x) : (y))
#define MID(x,y,z)   MAX((x), MIN((y), (z)))
#endif


text:
require 'rails_helper'

describe "manifestations/show" do
  fixtures :all

  before(:each) do
    assign(:manifestation, FactoryBot.create(:manifestation))
    assign(:library_group, library_groups(:one))
    allow(view).to receive(:policy).and_return double(create?: false, udpate?: false, destroy?: false)
  end

  it "renders attributes in
" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(/1/)
  end

  describe "identifier_link" do
    it "renders a link to CiNii Books" do
      assign(:manifestation, manifestations(:manifestation_00217))
      render
      rendered.should include 'BN15603730'
    end
  end

  describe "when logged in as Librarian" do
    before(:each) do
      user = assign(:profile, FactoryBot.create(:librarian))
      view.stub(:current_user).and_return(user)
      allow(view).to receive(:policy).and_return double(create?: true, update?: true, destroy?: true)
    end

    it "should have an ISBD separator for extent and dimensions" do
      assign(:manifestation, FactoryBot.create(:manifestation, extent: "extent value", dimensions: "dimensions value"))
      render
      expect(rendered).to match /\s+;\s+/
    end
  end

  describe "when logged in as User" do
    before(:each) do
      user = assign(:profile, FactoryBot.create(:user))
      view.stub(:current_user).and_return(user)
    end
    it "should have an ISBD separator for extent and dimensions" do
      assign(:manifestation, FactoryBot.create(:manifestation, extent: "extent value", dimensions: "dimensions value"))
      render
      expect(rendered).to match /\s+;\s+/
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/wamp/www/milovcard/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php</file>
            <file>file:/C:/wamp/www/milovcard/app/config/config.yml</file>
            <file>file:/C:/wamp/www/milovcard/web/bundles/lukkosvcard/css/vcard.css</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/templates/listTemplate.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/app/config/routing.yml</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/config/routing.yml</file>
            <file>file:/C:/wamp/www/milovcard/app/config/security.yml</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/templates/companiesListTemplate.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Entity/Company.php</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/templates/personFormModal.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/form/fields.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Controller/companyController.php</file>
            <file>file:/C:/wamp/www/milovcard/vendor/symfony/symfony/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php</file>
            <file>file:/C:/wamp/www/milovcard/composer.json</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/public/css/vcard.css</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/templates/index.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Entity/Person.php</file>
            <file>file:/C:/wamp/www/milovcard/app/Resources/views/base.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Form/PersonType.php</file>
            <file>file:/C:/wamp/www/milovcard/app/AppKernel.php</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/UserBundle/Entity/User.php</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Resources/views/templates/companyFormModal.html.twig</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Controller/vcardController.php</file>
            <file>file:/C:/wamp/www/milovcard/src/Lukkos/VCardBundle/Controller/templatesController.php</file>
        </group>
    </open-files>
</project-private>


text:
namespace FirebaseAdmin.Util
{
    /// <summary>
    /// HTTP response and the body string read from it. Additionally also contains a
    /// deserialized representation of the body.
    /// </summary>
    internal sealed class DeserializedResponseInfo<T> : ResponseInfo
    {
        internal DeserializedResponseInfo(ResponseInfo info, T result)
        : base(info)
        {
            this.Result = result;
        }

        internal T Result { get; private set; }
    }
}


text:
using BLE.Client.ViewModels;
using Xamarin.Forms;

namespace BLE.Client.Pages
{
    public class BasePage : ContentPage
    {
        protected override void OnAppearing()
        {
            base.OnAppearing();

            var viewModel = BindingContext as BaseViewModel;
            viewModel?.Resume();
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            var viewModel = BindingContext as BaseViewModel;
            viewModel?.Suspend();
        }
    }
}


text:
// This file adds the "review" subcommand to devcam, to send changes for peer review.

package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"

	"camlistore.org/pkg/cmdmain"
)

var (
	defaultHook = filepath.FromSlash("misc/commit-msg.githook")
	hookFile    = filepath.FromSlash(".git/hooks/commit-msg")
)

type reviewCmd struct{}

func init() {
	cmdmain.RegisterCommand("review", func(flags *flag.FlagSet) cmdmain.CommandRunner {
		return new(reviewCmd)
	})
}

func (c *reviewCmd) Usage() {
	fmt.Fprintf(cmdmain.Stderr, "Usage: devcam review\n")
}

func (c *reviewCmd) Describe() string {
	return "Submit your git commits for review."
}

func (c *reviewCmd) RunCommand(args []string) error {
	if len(args) > 0 {
		return cmdmain.UsageError("too many arguments.")
	}
	goToCamliRoot()
	c.checkHook()
	gitPush()
	return nil
}

func goToCamliRoot() {
	prevDir, err := os.Getwd()
	if err != nil {
		log.Fatalf("could not get current directory: %v", err)
	}
	for {
		if _, err := os.Stat(defaultHook); err == nil {
			return
		}
		if err := os.Chdir(".."); err != nil {
			log.Fatalf("Could not chdir: %v", err)
		}
		currentDir, err := os.Getwd()
		if err != nil {
			log.Fatalf("Could not get current directory: %v", err)
		}
		if currentDir == prevDir {
			log.Fatal("Camlistore tree root not found. Run from within the Camlistore tree please.")
		}
		prevDir = currentDir
	}
}

func (c *reviewCmd) checkHook() {
	_, err := os.Stat(hookFile)
	if err == nil {
		return
	}
	if !os.IsNotExist(err) {
		log.Fatal(err)
	}
	fmt.Fprintf(cmdmain.Stdout, "Presubmit hook to add Change-Id to commit messages is missing.\nNow automatically creating it at %v\n\n", hookFile)
	cmd := exec.Command("devcam", "hook")
	cmd.Stdout = cmdmain.Stdout
	cmd.Stderr = cmdmain.Stderr
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
	fmt.Fprintf(cmdmain.Stdout, "Amending last commit to add Change-Id.\nPlease re-save description without making changes.\n\n")
	fmt.Fprintf(cmdmain.Stdout, "Press Enter to continue.\n")
	if _, _, err := bufio.NewReader(cmdmain.Stdin).ReadLine(); err != nil {
		log.Fatal(err)
	}

	cmd = exec.Command("git", []string{"commit", "--amend"}...)
	cmd.Stdout = cmdmain.Stdout
	cmd.Stderr = cmdmain.Stderr
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

func gitPush() {
	cmd := exec.Command("git",
		[]string{"push", "https://camlistore.googlesource.com/camlistore", "HEAD:refs/for/master"}...)
	cmd.Stdout = cmdmain.Stdout
	cmd.Stderr = cmdmain.Stderr
	if err := cmd.Run(); err != nil {
		log.Fatalf("Could not git push: %v", err)
	}
}