text:
<?php

namespace Fantur\FanturBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Fantur\FanturBundle\Entity\Eventos;
use Fantur\FanturBundle\Form\EventosType;
use Fantur\FanturBundle\Form\EventosFilterType;

/**
 * Eventos controller.
 * @author Nombre Apellido <name@gmail.com>
 *
 * @Route("/eventos")
 */
class EventosController extends Controller
{

    /**
     * Lists all Eventos entities.
     *
     * @Route("/", name="eventos")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        list($filterForm, $queryBuilder) = $this->filter();

        $paginator  = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $queryBuilder,
            $this->get('request')->query->get('page', 1),
            (isset($this->container->parameters['knp_paginator.page_range'])) ? $this->container->parameters['knp_paginator.page_range'] : 10
        );

        return array(
            'entities'   => $pagination,
            'filterForm' => $filterForm->createView(),
        );
    }

    /**
    * Process filter request.
    *
    * @return array
    */
    protected function filter()
    {
        $request = $this->getRequest();
        $session = $request->getSession();
        $filterForm = $this->createFilterForm();
        $em = $this->getDoctrine()->getManager();
        $queryBuilder = $em->getRepository('FanturFanturBundle:Eventos')
            ->createQueryBuilder('a')
            ->orderBy('a.id', 'DESC')
        ;
        // Bind values from the request
        $filterForm->handleRequest($request);
        // Reset filter
        if ($filterForm->get('reset')->isClicked()) {
            $session->remove('EventosControllerFilter');
            $filterForm = $this->createFilterForm();
        }

        // Filter action
        if ($filterForm->get('filter')->isClicked()) {
            if ($filterForm->isValid()) {
                // Build the query from the given form object
                $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
                // Save filter to session
                $filterData = $filterForm->getData();
                $session->set('EventosControllerFilter', $filterData);
            }
        } else {
            // Get filter from session
            if ($session->has('EventosControllerFilter')) {
                $filterData = $session->get('EventosControllerFilter');
                $filterForm = $this->createFilterForm($filterData);
                $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
            }
        }

        return array($filterForm, $queryBuilder);
    }
    /**
    * Create filter form.
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createFilterForm($filterData = null)
    {
        $form = $this->createForm(new EventosFilterType(), $filterData, array(
            'action' => $this->generateUrl('eventos'),
            'method' => 'GET',
        ));

        $form
            ->add('filter', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.index.filter',
                'attr'               => array('class' => 'btn btn-success col-lg-1'),
            ))
            ->add('reset', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.index.reset',
                'attr'               => array('class' => 'btn btn-danger col-lg-1 col-lg-offset-1'),
            ))
        ;

        return $form;
    }
    /**
     * Creates a new Eventos entity.
     *
     * @Route("/", name="eventos_create")
     * @Method("POST")
     * @Template("FanturFanturBundle:Eventos:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Eventos();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', 'flash.create.success');

            $nextAction = $form->get('saveAndAdd')->isClicked()
                    ? $this->generateUrl('eventos_new')
                    : $this->generateUrl('eventos_show', array('id' => $entity->getId()));
            return $this->redirect($nextAction);

        }
        $this->get('session')->getFlashBag()->add('danger', 'flash.create.error');

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a Eventos entity.
    *
    * @param Eventos $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Eventos $entity)
    {
        $form = $this->createForm(new EventosType(), $entity, array(
            'action' => $this->generateUrl('eventos_create'),
            'method' => 'POST',
        ));

        $form
            ->add(
                'save', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.new.save',
                'attr'               => array('class' => 'btn btn-success col-lg-2')
                )
            )
            ->add(
                'saveAndAdd', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.new.saveAndAdd',
                'attr'               => array('class' => 'btn btn-primary col-lg-2 col-lg-offset-1')
                )
            )
        ;

        return $form;
    }

    /**
     * Displays a form to create a new Eventos entity.
     *
     * @Route("/new", name="eventos_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Eventos();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Eventos entity.
     *
     * @Route("/{id}", name="eventos_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FanturFanturBundle:Eventos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Eventos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Eventos entity.
     *
     * @Route("/{id}/edit", name="eventos_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FanturFanturBundle:Eventos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Eventos entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Eventos entity.
    *
    * @param Eventos $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Eventos $entity)
    {
        $form = $this->createForm(new EventosType(), $entity, array(
            'action' => $this->generateUrl('eventos_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form
            ->add(
                'save', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.new.save',
                'attr'               => array('class' => 'btn btn-success col-lg-2')
                )
            )
            ->add(
                'saveAndAdd', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.new.saveAndAdd',
                'attr'               => array('class' => 'btn btn-primary col-lg-2 col-lg-offset-1')
                )
            )
        ;

        return $form;
    }
    /**
     * Edits an existing Eventos entity.
     *
     * @Route("/{id}", name="eventos_update")
     * @Method("PUT")
     * @Template("FanturFanturBundle:Eventos:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FanturFanturBundle:Eventos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Eventos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', 'flash.update.success');

            $nextAction = $editForm->get('saveAndAdd')->isClicked()
                        ? $this->generateUrl('eventos_new')
                        : $this->generateUrl('eventos_show', array('id' => $id));
            return $this->redirect($nextAction);
        }

        $this->get('session')->getFlashBag()->add('danger', 'flash.update.error');

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Eventos entity.
     *
     * @Route("/{id}", name="eventos_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('FanturFanturBundle:Eventos')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Eventos entity.');
            }

            $em->remove($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add('success', 'flash.delete.success');
        }

        return $this->redirect($this->generateUrl('eventos'));
    }

    /**
     * Creates a form to delete a Eventos entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        $mensaje = $this->get('translator')->trans('views.recordactions.confirm', array(), 'MWSimpleCrudGeneratorBundle');
        $onclick = 'return confirm("'.$mensaje.'");';
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('eventos_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array(
                'translation_domain' => 'MWSimpleCrudGeneratorBundle',
                'label'              => 'views.recordactions.delete',
                'attr'               => array(
                    'class'   => 'btn btn-danger col-lg-11',
                    'onclick' => $onclick,
                )
            ))
            ->getForm()
        ;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;

namespace AU
{

    [Serializable]
    public class TemporaryObjectCache
    {
        public GameObject prefabObject;

        public List<GameObject> activeObjects;
        public Stack<GameObject> freeObjects;
    }

    public class TemporaryObjectManager : MonoBehaviour
    {
        static TemporaryObjectManager instance;

        public static TemporaryObjectManager GetInstance()
        {
            if (!instance)
            {
                instance = FindObjectOfType<TemporaryObjectManager>();
                if (instance == null)
                {
                    GameObject go = new GameObject();
                    go.name = "TemporayObjectManager";
                    instance = go.AddComponent<TemporaryObjectManager>();
                }
            }
            return instance;
        }

        public GameObject objectRoot;
        public GameObject[] cachePrefabs;

        Dictionary<GameObject, TemporaryObjectCache> cacheObjDict = new Dictionary<GameObject, TemporaryObjectCache>();
        Dictionary<Object, TemporaryObjectCache> activeObjDict = new Dictionary<Object, TemporaryObjectCache>();
        NameGenerator _nameGenerator = new NameGenerator("TEMP_OBJECT_", "");

        public TemporaryObjectCache[] objectCaches
        {
            get { return cacheObjDict.Values.ToArray(); }
        }

        public void Awake()
        {
            instance = this;
        }

        public void Start()
        {
            instance = this;

            foreach (GameObject prefab in cachePrefabs)
            {
                if(prefab != null && !cacheObjDict.Keys.Contains(prefab))
                {
                    TemporaryObjectCache cache = new TemporaryObjectCache();
                    cache.prefabObject = prefab;
                    cache.freeObjects = new Stack<GameObject>();
                    cache.activeObjects = new List<GameObject>();

                    cacheObjDict.Add(cache.prefabObject, cache);
                }
            }
            activeObjDict = new Dictionary<Object, TemporaryObjectCache>();
        }

        GameObject InstPrefabViaCache(GameObject prefab)
        {
            GameObject newObj = null;
            if (prefab == null)
            {
                newObj = new GameObject();
            }
            else
            {
                TemporaryObjectCache cache;
                if (cacheObjDict.TryGetValue(prefab, out cache))
                {
                    if (cache.freeObjects.Count > 0)
                    {
                        newObj = cache.freeObjects.Pop();
                        cache.activeObjects.Add(newObj);

                        newObj.SetActive(true);
                        newObj.SendMessage("Reset", SendMessageOptions.DontRequireReceiver);
                    }
                    else
                    {
                        newObj = Instantiate(prefab) as GameObject;
                        cache.activeObjects.Add(newObj);
                        activeObjDict.Add(newObj, cache);
                    }
                }
                else
                {
                    newObj = Instantiate(prefab) as GameObject;
                }
            }

            return newObj;
        }

        public GameObject InstGameObject(GameObject prefab, Vector3 pos, Quaternion rot = new Quaternion())
        {
            GameObject newObj = InstPrefabViaCache(prefab);
            newObj.transform.position = pos;
            if(rot != Quaternion.identity)
                newObj.transform.rotation = rot;

            if (objectRoot != null)
                newObj.transform.parent = objectRoot.transform;
            else
                newObj.transform.parent = this.transform;

            return newObj;
        }

        public GameObject InstParticleSystem(GameObject prefab, Vector3 pos, Quaternion rot = new Quaternion())
        {
            GameObject newObj = InstGameObject(prefab, pos, rot);
            ParticleSystem ps = newObj.GetComponent<ParticleSystem>();
            if (ps != null)
                ps.Play();

            return newObj;
        }

        public GameObject InstGameObjectAsChild(GameObject prefab, GameObject transformParent)
        {
            GameObject newObj = InstPrefabViaCache(prefab);
            newObj.transform.SetParent(transformParent.transform);
            newObj.transform.localPosition = Vector3.zero;

            return newObj;
        }

        public GameObject InstParticleSystemAsChild(GameObject prefab, GameObject transformParent)
        {
            GameObject newObj = InstGameObjectAsChild(prefab, transformParent);
            ParticleSystem ps = newObj.GetComponent<ParticleSystem>();
            if (ps != null)
                ps.Play();

            return newObj;
        }

        public GameObject InstGameObject(Vector3 pos, Quaternion rot = new Quaternion())
        {
            GameObject newObj = new GameObject();
            newObj.name = _nameGenerator.next();

            if (objectRoot != null)
                newObj.transform.parent = objectRoot.transform;
            else
                newObj.transform.parent = this.transform;
            newObj.transform.localPosition = pos;

            if (rot != Quaternion.identity)
                newObj.transform.localRotation = rot;

            return newObj;
        }

        IEnumerator _DelayDestroy(Object o, float t)
        {
            yield return new WaitForSeconds(t);
            DestroyViaCache(o);
        }

        void DestroyViaCache(Object o)
        {
            TemporaryObjectCache cache;
            if(activeObjDict.TryGetValue(o, out cache))
            {
                cache.activeObjects.Remove((GameObject)o);
                cache.freeObjects.Push((GameObject)o);

                ((GameObject)o).SetActive(false);
            }
            else
            {
                Destroy(o);
            }
        }

        public void DelayDestroyObject(Object o, float t)
        {
            if (t == 0)
                DestroyObjectNow(o);
            else
                StartCoroutine(_DelayDestroy(o, t));
        }

        public void DestroyObjectNow(Object o)
        {
            DestroyViaCache(o);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/* SonataPageBundle:Page:redirect.html.twig */
class __TwigTemplate_2e8de97b1ddad0a2245776174949efd4990710b87e62b83cb82434f44483d303 extends Sonata\CacheBundle\Twig\TwigTemplate14
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        // line 11
        return $this->env->resolveTemplate($this->getAttribute((isset($context["sonata_page"]) ? $context["sonata_page"] : $this->getContext($context, "sonata_page")), "defaultTemplate", array()));
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 13
    public function block_title($context, array $blocks = array())
    {
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("title_page_redirected", array(), "SonataPageBundle"), "html", null, true);
    }

    // line 15
    public function block_content($context, array $blocks = array())
    {
        // line 16
        echo "

";
        // line 17
        echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("title_page_redirected", array(), "SonataPageBundle"), "html", null, true);
        echo "

            ";
        // line 20
        echo $this->env->getExtension('translator')->trans("message_page_redirected", array("%url%" => $this->getAttribute($this->getAttribute((isset($context["response"]) ? $context["response"] : $this->getContext($context, "response")), "headers", array()), "get", array(0 => "Location"), "method")), "SonataPageBundle");
        echo "

";
    }

    public function getTemplateName()
    {
        return "SonataPageBundle:Page:redirect.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  46 => 20,  40 => 17,  37 => 16,  34 => 15,  28 => 13,  19 => 11,);
    }
}


text:
package com.mfglabs.stream
package extensions.postgres

import java.sql.{DriverManager, Connection}
import org.postgresql.util.PSQLException
import org.scalatest.{Suite, BeforeAndAfter}
import scala.sys.process._
import scala.util.{Failure, Success, Try}
import com.typesafe.config.ConfigFactory
/**
 * for each test, creates a PostgresSQL docker container and provides a connection to its database
 */
trait DockerTmpDB extends BeforeAndAfter { self: Suite =>

  import Debug._

  val version: PostgresVersion = PostgresVersion(ConfigFactory.load().getString("postgres.version"))

  Class.forName("org.postgresql.Driver")
  implicit var conn : Connection = _

  val dockerInstances = collection.mutable.Buffer.empty[String]

  def newPGDB(): Int = {
    val port: Int = 5432 + (math.random * (10000 - 5432)).toInt
    Try {
      s"docker pull postgres:${version.value}".pp.!!.trim
      val containerId =
        s"""docker run -p $port:5432 -e POSTGRES_PASSWORD=pwd -d postgres:${version.value}""".pp.!!.trim
      dockerInstances += containerId.pp("New docker instance with id")
      port
    } match {
      case Success(p) => p
      case Failure(err) =>
        throw  new IllegalStateException(s"Error while trying to run docker container", err)
    }
  }

  lazy val dockerIp: String =
    Try("docker-machine ip default".!!.trim).toOption
      .orElse {
        val conf = ConfigFactory.load()
        if (conf.hasPath("docker.ip")) Some(conf.getString("docker.ip")) else None
      }
      .getOrElse("127.0.0.1") // platform dependent

  //ugly solution to wait for the connection to be ready
  def waitsForConnection(port : Int) : Connection = {
    try {
      DriverManager.getConnection(s"jdbc:postgresql://$dockerIp:$port/postgres", "postgres", "pwd")
    } catch {
      case _: PSQLException =>
        println("Retrying DB connection...")
        Thread.sleep(1000)
        waitsForConnection(port)
    }
  }

  before {
    val port = newPGDB()
    println(s"New postgres ${version.value} instance at port $port")
    Thread.sleep(5000)
    conn = waitsForConnection(port)
  }

  after {
    conn.close()
    dockerInstances.toSeq.foreach { dockerId =>
      s"docker stop $dockerId".pp.!!
      s"docker rm $dockerId".pp.!!
    }
  }

}

object Debug {

  implicit class RichString(s:String){
    def pp :String = pp(None)
    def pp(p:String) :String = pp(Some(p))

    private def pp(p:Option[String]) = {
      println(p.map(_ + " ").getOrElse("") + s)
      s
    }
  }
}


text:
package io.gatling.recorder.http.ssl

import java.io._
import java.math.BigInteger
import java.nio.file.Path
import java.security._
import java.security.cert.X509Certificate
import java.util.Date
import javax.security.auth.x500.X500Principal

import scala.util.Try
import scala.concurrent.duration._

import io.gatling.commons.util.Io.withCloseable
import io.gatling.commons.util.PathHelper._
import io.gatling.commons.util.ClockSingleton._

import com.typesafe.scalalogging.StrictLogging
import org.bouncycastle.cert.{ X509CertificateHolder, X509v3CertificateBuilder }
import org.bouncycastle.cert.jcajce.{ JcaX509CertificateConverter, JcaX509CertificateHolder, JcaX509v1CertificateBuilder }
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.{ PEMKeyPair, PEMParser }
import org.bouncycastle.openssl.jcajce.{ JcaPEMKeyConverter, JcaPEMWriter }
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
import org.bouncycastle.pkcs.PKCS10CertificationRequest
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder

private[ssl] case class Ca(cert: X509Certificate, privKey: PrivateKey)
private[ssl] case class Csr(cert: PKCS10CertificationRequest, privKey: PrivateKey)

/**
 * Utility class to create SSL server certificate on the fly for the recorder keystore
 */
private[recorder] object SslCertUtil extends StrictLogging {

  Security.addProvider(new BouncyCastleProvider)

  def readPEM(file: InputStream): Any = withCloseable(new PEMParser(new InputStreamReader(file))) { _.readObject }

  def writePEM(obj: Any, os: OutputStream): Unit = withCloseable(new JcaPEMWriter(new OutputStreamWriter(os))) { _.writeObject(obj) }

  def certificateFromHolder(certHolder: X509CertificateHolder) = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certHolder)

  def newRSAKeyPair: KeyPair = {
    val kpGen = KeyPairGenerator.getInstance("RSA")
    kpGen.initialize(1024)
    kpGen.generateKeyPair
  }

  private def newSigner(privKey: PrivateKey) = new JcaContentSignerBuilder("SHA256withRSA").build(privKey)

  def generateGatlingCAPEMFiles(dir: Path, privKeyFileName: String, certFileName: String): Unit = {
    assert(dir.isDirectory, s"$dir isn't a directory")

      def generateCACertificate(pair: KeyPair): X509CertificateHolder = {
        val dn = s"C=FR, ST=Val de marne, O=GatlingCA, CN=Gatling"
        val now = nowMillis

        // has to be v1 for CA
        val certGen = new JcaX509v1CertificateBuilder(
          new X500Principal(dn), // issuer
          BigInteger.valueOf(now), // serial
          new Date(now), // notBefore
          new Date(now + 365.days.toMillis), // notAfter
          new X500Principal(dn), //subject
          pair.getPublic
        ) // publicKey

        val signer = newSigner(pair.getPrivate)
        certGen.build(signer)
      }

    val pair = newRSAKeyPair
    val crtHolder = generateCACertificate(pair)

    writePEM(crtHolder, (dir / certFileName).outputStream)
    writePEM(pair, (dir / privKeyFileName).outputStream)
  }

  def getCA(crtFile: InputStream, keyFile: InputStream): Try[Ca] =
    Try {
      val certHolder = readPEM(crtFile).asInstanceOf[X509CertificateHolder]
      val certificate = certificateFromHolder(certHolder)

      val keyInfo = readPEM(keyFile).asInstanceOf[PEMKeyPair].getPrivateKeyInfo
      val privKey = new JcaPEMKeyConverter().getPrivateKey(keyInfo)

      Ca(certificate, privKey)
    }

  def updateKeystoreWithNewAlias(keyStore: KeyStore, password: Array[Char], alias: String, caT: Try[Ca]): Try[KeyStore] =
    for {
      ca <- caT
      csr <- createCSR(alias)
      serverCrt <- createServerCert(ca.cert, ca.privKey, csr.cert)
      updatedKeyStore <- addNewKeystoreEntry(keyStore, password, serverCrt, csr.privKey, ca.cert, alias)
    } yield updatedKeyStore

  private def createCSR(dnHostName: String): Try[Csr] =
    Try {
      val pair = newRSAKeyPair
      val dn = s"C=FR, ST=Val de marne, O=GatlingCA, OU=Gatling, CN=$dnHostName"
      val builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal(dn), pair.getPublic)
      val signer = newSigner(pair.getPrivate)
      val pkcs10CR = builder.build(signer)
      Csr(pkcs10CR, pair.getPrivate)
    }

  private def createServerCert(caCert: X509Certificate, caKey: PrivateKey, csr: PKCS10CertificationRequest): Try[X509Certificate] =
    Try {
      val now = nowMillis
      val certBuilder = new X509v3CertificateBuilder(
        new JcaX509CertificateHolder(caCert).getSubject, // issuer
        BigInteger.valueOf(now), // serial
        new Date(now), // notBefore
        new Date(now + 1.day.toMillis), // notAfter
        csr.getSubject, //subject
        csr.getSubjectPublicKeyInfo
      ) // publicKey
      val signer = newSigner(caKey)
      certificateFromHolder(certBuilder.build(signer))
    }

  private def addNewKeystoreEntry(keyStore: KeyStore, password: Array[Char], serverCert: X509Certificate, csrPrivKey: PrivateKey, caCert: X509Certificate, alias: String): Try[KeyStore] =
    Try {
      keyStore.setCertificateEntry(alias, serverCert)
      keyStore.setKeyEntry(alias, csrPrivKey, password, Array(serverCert, caCert))
      keyStore
    }
}


text:
This repository contains examples for the [Google Genomics Pipelines API]
(https://cloud.google.com/genomics/reference/rest/v1alpha2/pipelines).

| Alpha |
|-------|
| This is an Alpha release of Google Genomics API. This feature might be changed in backward-incompatible ways and is not recommended for production use. It is not subject to any SLA or deprecation policy. |

The API provides an easy way to create, run, and monitor command-line tools
on Google Compute Engine running in a Docker container. You can use it like
you would a job scheduler.

The most common use case is to run an off-the-shelf tool or custom script
that reads and writes files. You may want to run such a tool over files in
Google Cloud Storage. You may want to run this independently over hundreds
or thousands of files.

The typical flow for a pipeline is:

  1. Create a Compute Engine virtual machine
  1. Copy one or more files from Cloud Storage to a disk
  1. Run the tool on the file(s)
  1. Copy the output to Cloud Storage
  1. Destroy the Compute Engine virtual machine

You can submit batch operations from your laptop, and have them run in the cloud.
You can do the packaging to Docker yourself, or use existing Docker images.

## Prerequisites

1. Clone or fork this repository.
1. If you plan to create your own Docker images, then install docker: https://docs.docker.com/engine/installation/#installation
1. Follow the Google Genomics [getting started instructions](https://cloud.google.com/genomics/install-genomics-tools#create-project-and-authenticate) to set up your Google Cloud Project. The Pipelines API requires that the following are enabled in your project:
    1. [Genomics API](https://console.cloud.google.com/project/_/apis/api/genomics)
    2. [Cloud Storage API](https://console.cloud.google.com/project/_/apis/api/storage_api)
    3. [Compute Engine API](https://console.cloud.google.com/project/_/apis/api/compute_component)
1. Follow the Google Genomics [getting started instructions](https://cloud.google.com/genomics/install-genomics-tools#install-genomics-tools) to install and authorize the Google Cloud SDK.
1. Install or update the python client via `pip install --upgrade google-api-python-client`.  For more detail see https://cloud.google.com/genomics/v1/libraries.

## Examples

* [Compress or Decompress files](./compress)
* [Run FastQC over a list of BAM or FASTQ files](./fastqc)
* [Use samtools to create a BAM index file](./samtools)
* [Use a custom script in Cloud Storage to update a VCF header](./set_vcf_sample_id)
* [Use Bioconductor to count overlaps in a BAM file](./bioconductor)
* [Use Cromwell and WDL to orchestrate a multi-stage workflow](./wdl_runner)

## See Also

* [Pipelines API docs](https://cloud.google.com/genomics/reference/rest/v1alpha2/pipelines)
* [PyDocs](https://developers.google.com/resources/api-libraries/documentation/genomics/v1alpha2/python/latest/)


text:
"""
file        :   views.py
date        :   2016-0330
module      :   common.views
classes     :
description :   views used by entire site, eg, error pages
"""

from django.shortcuts import render_to_response
from django.template import RequestContext

def custom_bad_request(request):

    response = render_to_response('error/400.html', context_instance=RequestContext(request))

    response.status_code = 400

    return response

def custom_permission_denied(request):

    response = render_to_response('error/403.html', context_instance=RequestContext(request))

    response.status_code = 403

    return response

def custom_page_not_found(request):

    response = render_to_response('error/404.html', context_instance=RequestContext(request))

    response.status_code = 404

    return response

def custom_server_error(request):

    response = render_to_response('error/500.html', context_instance=RequestContext(request))

    response.status_code = 500

    return response

def custom_bad_gateway(request):

    response = render_to_response('error/502.html', context_instance=RequestContext(request))

    response.status_code = 502

    return response


text:
using System;
using System.Linq;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.WindowsAzure.Management.SiteRecovery.Models
{
    /// <summary>
    /// The response model for the Site object
    /// </summary>
    public partial class SiteResponse : AzureOperationResponse
    {
        private Site _site;

        /// <summary>
        /// Optional. The Site object
        /// </summary>
        public Site Site
        {
            get { return this._site; }
            set { this._site = value; }
        }

        /// <summary>
        /// Initializes a new instance of the SiteResponse class.
        /// </summary>
        public SiteResponse()
        {
        }
    }
}


text:
namespace sync_sessions {

namespace {

SyncedTabDelegate* GetSyncedTabDelegateFromWebContents(
    content::WebContents* web_contents) {
#if BUILDFLAG(IS_ANDROID)
  TabAndroid* tab = TabAndroid::FromWebContents(web_contents);
  return tab ? tab->GetSyncedTabDelegate() : nullptr;
#else
  SyncedTabDelegate* delegate =
      BrowserSyncedTabDelegate::FromWebContents(web_contents);
  return delegate;
#endif
}

}  // namespace

SyncSessionsWebContentsRouter::SyncSessionsWebContentsRouter(Profile* profile) {
#if !BUILDFLAG(IS_ANDROID)
  browser_list_helper_ =
      std::make_unique<BrowserListRouterHelper>(this, profile);
#endif  // !BUILDFLAG(IS_ANDROID)
}

SyncSessionsWebContentsRouter::~SyncSessionsWebContentsRouter() = default;

void SyncSessionsWebContentsRouter::NotifyTabModified(
    content::WebContents* web_contents,
    bool page_load_completed) {
  SyncedTabDelegate* delegate = nullptr;
  if (web_contents) {
    delegate = GetSyncedTabDelegateFromWebContents(web_contents);
  }

  if (handler_ && delegate) {
    handler_->OnLocalTabModified(delegate);
  }

  if (!flare_.is_null() && delegate && page_load_completed) {
    flare_.Run(syncer::SESSIONS);
    flare_.Reset();
  }
}

void SyncSessionsWebContentsRouter::NotifySessionRestoreComplete() {
  if (handler_) {
    handler_->OnSessionRestoreComplete();
  }
}

void SyncSessionsWebContentsRouter::InjectStartSyncFlare(
    syncer::SyncableService::StartSyncFlare flare) {
  flare_ = flare;
}

void SyncSessionsWebContentsRouter::StartRoutingTo(
    LocalSessionEventHandler* handler) {
  handler_ = handler;
}

void SyncSessionsWebContentsRouter::Stop() {
  handler_ = nullptr;
}

void SyncSessionsWebContentsRouter::Shutdown() {
#if !BUILDFLAG(IS_ANDROID)
  browser_list_helper_.reset();
#endif  // !BUILDFLAG(IS_ANDROID)
}

}  // namespace sync_sessions


text:
namespace
{
auto const kFoodPlacementId = "1";
auto const kShopsPlacementId = "2";
auto const kCityTransportPlacementId = "13";
auto const kGlobalTransportPlacementId = "12";
auto const kSightsPlacementId = "5";
auto const kLargeToponymsPlacementId = "6";
auto const kHealthPlacementId = "7";
auto const kFinancialPlacementId = "8";
auto const kEntertainmentPlacementId = "9";
auto const kBuildingPlacementId = "11";
auto const kBannerIdForOtherTypes = "14";

std::initializer_list<storage::TCountryId> const kSupportedCountries =
{
  "Azerbaijan Region",
  "Armenia",
  "Belarus",
  "Kazakhstan",
  "Kyrgyzstan",
  "Moldova",
  "Russian Federation",
  "Tajikistan",
  "Turkmenistan",
  "Uzbekistan",
  "Ukraine"
};

std::initializer_list<std::string> const kSupportedLanguages = {"be", "hy", "kk", "ru", "uk"};
}  // namespace

namespace ads
{
Rb::Rb()
{
  AppendEntry({{"amenity", "cafe"},
               {"amenity", "fast_food"},
               {"amenity", "restaurant"},
               {"amenity", "bar"},
               {"amenity", "pub"}},
              kFoodPlacementId);

  AppendEntry({{"shop"},
               {"amenity", "marketplace"}},
              kShopsPlacementId);

  AppendEntry({{"aerialway"},
               {"highway", "bus_stop"},
               {"highway", "speed_camera"},
               {"public_transport"}},
              kCityTransportPlacementId);

  AppendEntry({{"aeroway"},
               {"railway"},
               {"man_made", "pier"}},
              kGlobalTransportPlacementId);

  AppendEntry({{"tourism", "zoo"},
               {"tourism", "artwork"},
               {"tourism", "information"},
               {"tourism", "attraction"},
               {"tourism", "viewpoint"},
               {"tourism", "museum"},
               {"amenity", "fountain"},
               {"amenity", "townhall"},
               {"historic"}},
              kSightsPlacementId);

  AppendEntry({{"place"}}, kLargeToponymsPlacementId);

  AppendEntry({{"amenity", "dentist"},
               {"amenity", "doctors"},
               {"amenity", "clinic"},
               {"amenity", "hospital"},
               {"amenity", "pharmacy"},
               {"amenity", "veterinary"}},
              kHealthPlacementId);

  AppendEntry({{"amenity", "bank"},
               {"amenity", "atm"},
               {"amenity", "bureau_de_change"}},
              kFinancialPlacementId);

  AppendEntry({{"amenity", "cinema"},
               {"amenity", "brothel"},
               {"amenity", "casino"},
               {"amenity", "nightclub"},
               {"amenity", "theatre"},
               {"boundary", "national_park"},
               {"leisure"}},
              kEntertainmentPlacementId);

  AppendEntry({{"building"}}, kBuildingPlacementId);

  AppendExcludedTypes({{"sponsored", "banner"}});

  AppendSupportedCountries(kSupportedCountries);
  AppendSupportedUserLanguages(kSupportedLanguages);
}

std::string Rb::GetBannerIdForOtherTypes() const
{
  return kBannerIdForOtherTypes;
}
}  // namespace ads


text:
package com.google.android.exoplayer2.source.hls.playlist;

import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.util.MimeTypes;

import java.util.Collections;
import java.util.List;

/**
 * Represents an HLS master playlist.
 */
public final class HlsMasterPlaylist extends HlsPlaylist {

  /**
   * Represents a url in an HLS master playlist.
   */
  public static final class HlsUrl {

    /**
     * The http url from which the media playlist can be obtained.
     */
    public final String url;
    /**
     * Format information associated with the HLS url.
     */
    public final Format format;

    /**
     * Creates an HLS url from a given http url.
     *
     * @param url The url.
     * @return An HLS url.
     */
    public static HlsUrl createMediaPlaylistHlsUrl(String url) {
      Format format = Format.createContainerFormat("0", MimeTypes.APPLICATION_M3U8, null, null,
          Format.NO_VALUE, 0, null);
      return new HlsUrl(url, format);
    }

    /**
     * @param url See {@link #url}.
     * @param format See {@link #format}.
     */
    public HlsUrl(String url, Format format) {
      this.url = url;
      this.format = format;
    }

  }

  /**
   * The list of variants declared by the playlist.
   */
  public final List<HlsUrl> variants;
  /**
   * The list of demuxed audios declared by the playlist.
   */
  public final List<HlsUrl> audios;
  /**
   * The list of subtitles declared by the playlist.
   */
  public final List<HlsUrl> subtitles;

  /**
   * The format of the audio muxed in the variants. May be null if the playlist does not declare any
   * muxed audio.
   */
  public final Format muxedAudioFormat;
  /**
   * The format of the closed captions declared by the playlist. May be empty if the playlist
   * explicitly declares no captions are available, or null if the playlist does not declare any
   * captions information.
   */
  public final List<Format> muxedCaptionFormats;

  /**
   * @param baseUri The base uri. Used to resolve relative paths.
   * @param variants See {@link #variants}.
   * @param audios See {@link #audios}.
   * @param subtitles See {@link #subtitles}.
   * @param muxedAudioFormat See {@link #muxedAudioFormat}.
   * @param muxedCaptionFormats See {@link #muxedCaptionFormats}.
   */
  public HlsMasterPlaylist(String baseUri, List<HlsUrl> variants, List<HlsUrl> audios,
      List<HlsUrl> subtitles, Format muxedAudioFormat, List<Format> muxedCaptionFormats) {
    super(baseUri);
    this.variants = Collections.unmodifiableList(variants);
    this.audios = Collections.unmodifiableList(audios);
    this.subtitles = Collections.unmodifiableList(subtitles);
    this.muxedAudioFormat = muxedAudioFormat;
    this.muxedCaptionFormats = muxedCaptionFormats != null
        ? Collections.unmodifiableList(muxedCaptionFormats) : null;
  }

  /**
   * Creates a playlist with a single variant.
   *
   * @param variantUrl The url of the single variant.
   * @return A master playlist with a single variant for the provided url.
   */
  public static HlsMasterPlaylist createSingleVariantMasterPlaylist(String variantUrl) {
    List<HlsUrl> variant = Collections.singletonList(HlsUrl.createMediaPlaylistHlsUrl(variantUrl));
    List<HlsUrl> emptyList = Collections.emptyList();
    return new HlsMasterPlaylist(null, variant, emptyList, emptyList, null, null);
  }

}


text:
from django.shortcuts import get_object_or_404, render, redirect

from address.models import ipv6_address, ipv4_address
from netdevice.models import router, interface, logical_interface

from address.forms import IPv6AddressForm, IPv4AddressForm

def ipv6_address_create(request, logical_interface_id):
    logical_interface_obj = get_object_or_404(logical_interface, pk=logical_interface_id)
    if request.method == "POST":
        form = IPv6AddressForm(request.POST)
        if form.is_valid():
            ipv6_address_obj = form.save()
            return redirect('netdevice:router_detail', router_id=ipv6_address_obj.interface.interface.router.pk)
    else:
        form = IPv6AddressForm(initial={'interface': logical_interface_obj})
    return render(request, 'op_webgui/generic_edit.html', {'form': form})

def ipv6_address_edit(request, ipv6_address_id):
    ipv6_address_obj = get_object_or_404(ipv6_address, pk=ipv6_address_id)
    if request.method == "POST":
        form = IPv6AddressForm(request.POST, instance=ipv6_address_obj)
        if form.is_valid():
            ipv6_address_obj = form.save()
            return redirect('netdevice:router_detail', router_id=ipv6_address_obj.interface.interface.router.pk)
    else:
        form = IPv6AddressForm(instance=ipv6_address_obj)
    return render(request, 'op_webgui/generic_edit.html', {'form': form})

def ipv4_address_create(request, logical_interface_id):
    logical_interface_obj = get_object_or_404(logical_interface, pk=logical_interface_id)
    if request.method == "POST":
        form = IPv4AddressForm(request.POST)
        if form.is_valid():
            ipv4_address_obj = form.save()
            return redirect('netdevice:router_detail', router_id=ipv4_address_obj.interface.interface.router.pk)
    else:
        form = IPv4AddressForm(initial={'interface': logical_interface_obj})
    return render(request, 'op_webgui/generic_edit.html', {'form': form})

def ipv4_address_edit(request, ipv4_address_id):
    ipv4_address_obj = get_object_or_404(ipv4_address, pk=ipv4_address_id)
    if request.method == "POST":
        form = IPv4AddressForm(request.POST, instance=ipv4_address_obj)
        if form.is_valid():
            ipv4_address_obj = form.save()
            return redirect('netdevice:router_detail', router_id=ipv4_address_obj.interface.interface.router.pk)
    else:
        form = IPv4AddressForm(instance=ipv4_address_obj)
    return render(request, 'op_webgui/generic_edit.html', {'form': form})


text:
layout: links
permalink: /:title
forward_to: https://cshopper.herokuapp.com/
author: team@tufts.io
hidden: false
project: true
description: "[replace email] COMP20 Web Programming final project by Leah Holden, Emma Plankey, Kathryn Tweel, and Fabio Vera"
---


text:
package com.getperka.flatpack.visitors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

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

import javax.inject.Inject;

import org.junit.Test;

import com.getperka.flatpack.FlatPackTest;
import com.getperka.flatpack.FlatPackVisitor;
import com.getperka.flatpack.Visitors;
import com.getperka.flatpack.codexes.ValueCodex;
import com.getperka.flatpack.ext.Codex;
import com.getperka.flatpack.ext.DeserializationContext;
import com.getperka.flatpack.ext.SerializationContext;
import com.getperka.flatpack.ext.Type;
import com.getperka.flatpack.ext.VisitorContext;
import com.google.gson.JsonElement;

/**
 * Verify behaviors of standard {@link VisitorContext} implementations.
 */
public class VisitorContextTest extends FlatPackTest {
  /**
   * Just used as a trivial codex to pump {@link FlatPackVisitor#visitValue}.
   */
  static class PassthroughCodex extends ValueCodex<Object> {
    @Override
    public Type describe() {
      return null;
    }

    @Override
    public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception {
      return null;
    }

    @Override
    public void writeNotNull(Object object, SerializationContext context) throws Exception {}
  }

  static class ValueRecorder extends FlatPackVisitor {
    final List<Object> values = new ArrayList<Object>();

    @Override
    public <T> void endVisitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
      values.add(value);
    }

    @Override
    public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
      values.add(value);
      return false;
    }
  }

  @Inject
  PassthroughCodex passthrough;

  @Inject
  Visitors visitors;

  @Test
  public void testArrayContext() {
    final Object replacement = "c";
    ValueRecorder recorder = new ValueRecorder() {
      @Override
      public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
        assertTrue(ctx.canReplace());
        ctx.replace(codex.cast(replacement));
        return super.visitValue(value, codex, ctx);
      }

    };
    Object[] array = new Object[] { "a", "b" };
    visitors.getWalkers().walkArray(passthrough).accept(recorder, array);
    assertEquals(Arrays.asList("a", "a", "b", "b"), recorder.values);
    assertEquals(Arrays.asList("c", "c"), Arrays.asList(array));
  }

  /**
   * Test the default behaviors of the VisitorContext base type so other tests can concentrate on
   * subclass-specific behaviors.
   */
  @Test
  public void testImmutableContext() {
    VisitorContext<?> ctx = (VisitorContext<?>) visitors.getWalkers().walkImmutable(passthrough);
    assertFalse(ctx.canInsert());
    assertFalse(ctx.canRemove());
    assertFalse(ctx.canReplace());
    assertFalse(ctx.didInsert());
    assertFalse(ctx.didRemove());
    assertFalse(ctx.didReplace());
    try {
      ctx.insertAfter(null);
      fail();
    } catch (UnsupportedOperationException expected) {}
    try {
      ctx.insertBefore(null);
      fail();
    } catch (UnsupportedOperationException expected) {}
    try {
      ctx.remove();
      fail();
    } catch (UnsupportedOperationException expected) {}
    try {
      ctx.replace(null);
      fail();
    } catch (UnsupportedOperationException expected) {}

    ValueRecorder recorder = new ValueRecorder();
    Object value = new Object();
    ctx.walkImmutable(passthrough).accept(recorder, value);
    assertEquals(Arrays.asList(value, value), recorder.values);
  }

  @Test
  public void testIterableContext() {
    VisitorContext<?> ctx = (VisitorContext<?>) visitors.getWalkers().walkIterable(passthrough);
    assertTrue(ctx.canRemove());

    ValueRecorder recorder = new ValueRecorder() {
      @Override
      public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
        ctx.remove();
        return super.visitValue(value, codex, ctx);
      }

    };
    List<Object> iterable = new ArrayList<Object>(Arrays.asList("a", "b"));
    ctx.walkIterable(passthrough).accept(recorder, iterable);
    assertEquals(Arrays.asList("a", "a", "b", "b"), recorder.values);
    assertTrue(iterable.isEmpty());
  }

  @Test
  public void testListContext() {
    VisitorContext<?> ctx = (VisitorContext<?>) visitors.getWalkers().walkList(passthrough);
    assertTrue(ctx.canInsert());
    assertTrue(ctx.canReplace());
    assertTrue(ctx.canRemove());

    ValueRecorder recorder = new ValueRecorder() {
      int count = 0;

      @Override
      public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
        switch (count) {
          case 0:
            assertEquals("a", value);
            ctx.insertBefore(codex.cast(String.valueOf(count)));
            break;
          case 1:
            assertEquals("b", value);
            ctx.insertAfter(codex.cast(String.valueOf(count)));
            break;
          case 2:
            assertEquals("c", value);
            ctx.remove();
            break;
          case 3:
            assertEquals("d", value);
            ctx.replace(codex.cast(String.valueOf(count)));
            break;
          case 4:
            assertEquals("e", value);
            ctx.insertBefore(codex.cast(String.valueOf(count)));
            break;
          default:
            throw new RuntimeException(String.valueOf(count));
        }
        count++;
        return super.visitValue(value, codex, ctx);
      }

    };
    List<Object> list = new ArrayList<Object>(Arrays.asList("a", "b", "c", "d", "e"));
    ctx.walkList(passthrough).accept(recorder, list);
    assertEquals(Arrays.asList("0", "a", "b", "1", "3", "4", "e"), list);
    assertEquals(Arrays.asList("a", "a", "b", "b", "c", "c", "d", "d", "e", "e"), recorder.values);
  }

  @Test
  public void testListContextEmpty() {
    ValueRecorder recorder = new ValueRecorder() {
      @Override
      public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
        fail("Should not see this with an empty list");
        return super.visitValue(value, codex, ctx);
      }
    };

    visitors.getWalkers().walkList(passthrough).accept(recorder, Collections.emptyList());
    assertTrue(recorder.values.isEmpty());
  }

  @Test
  public void testListContextRemoveBefore() {
    ValueRecorder recorder = new ValueRecorder() {
      @Override
      public <T> boolean visitValue(T value, Codex<T> codex, VisitorContext<T> ctx) {
        assertEquals("Hello", value);
        ctx.remove();
        ctx.insertBefore(codex.cast("World!"));
        return super.visitValue(value, codex, ctx);
      }
    };
    List<Object> list = new ArrayList<Object>(Arrays.asList("Hello"));
    visitors.getWalkers().walkList(passthrough).accept(recorder, list);
    assertEquals(Collections.singletonList("World!"), list);
    assertEquals(Arrays.asList("Hello", "Hello"), recorder.values);
  }

  @Test
  public void testNullableContext() {
    NullableContext<Object> ctx = (NullableContext<Object>) visitors.getWalkers()
        .walkNullable(passthrough);
    assertTrue(ctx.canRemove());
    assertTrue(ctx.canReplace());
    assertNull(ctx.getValue(null));

    Object value = new Object();
    ctx.replace(value);
    assertTrue(ctx.didReplace());
    assertSame(value, ctx.getValue(new Object()));

    ctx.remove();
    assertNull(ctx.getValue(new Object()));

    // Verify that re-replacing the value will restore
    ctx.replace(value);
    assertSame(value, ctx.getValue(new Object()));

    ValueRecorder recorder = new ValueRecorder();
    ctx.walkSingleton(passthrough).accept(recorder, value);
    assertEquals(Arrays.asList(value, value), recorder.values);
  }

  @Test
  public void testSingletonContext() {
    SingletonContext<Object> ctx = (SingletonContext<Object>) visitors.getWalkers()
        .walkSingleton(passthrough);
    assertTrue(ctx.canReplace());
    assertNull(ctx.getValue(null));
    Object value = new Object();
    ctx.replace(value);
    assertTrue(ctx.didReplace());
    assertSame(value, ctx.getValue(new Object()));

    ValueRecorder recorder = new ValueRecorder();
    ctx.walkSingleton(passthrough).accept(recorder, value);
    assertEquals(Arrays.asList(value, value), recorder.values);
  }
}


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:/home/christopher/workspace/thiefaine/composer.json</file>
            <file>file:/home/christopher/workspace/thiefaine/src/Thiefaine/ReferentielBundle/Controller/DefaultController.php</file>
        </group>
    </open-files>
</project-private>


text:
require "spec_helper"

describe "Asset" do
  include AssetCloud

  before do
    @cloud = double("Cloud", asset_extension_classes_for_bucket: [])
  end

  describe "when first created (without a value)" do
    before do
      @asset = AssetCloud::Asset.new(@cloud, "products/key.txt")
    end

    it "should be return new_asset? => true" do
      expect(@asset.new_asset?).to(eq(true))
    end

    it "should have a key" do
      expect(@asset.key).to(eq("products/key.txt"))
    end

    it "should have a value of nil" do
      expect(@asset.value).to(eq(nil))
    end

    it "should have a basename" do
      expect(@asset.basename).to(eq("key.txt"))
    end

    it "should have a basename without ext (if required)" do
      expect(@asset.basename_without_ext).to(eq("key"))
    end

    it "should have an ext" do
      expect(@asset.extname).to(eq(".txt"))
    end

    it "should have a relative_key_without_ext" do
      expect(@asset.relative_key_without_ext).to(eq("key"))
    end

    it "should have a bucket_name" do
      expect(@asset.bucket_name).to(eq("products"))
    end

    it "should have a bucket" do
      expect(@cloud).to(receive(:buckets).and_return(products: :products_bucket))
      expect(@asset.bucket).to(eq(:products_bucket))
    end

    it "should store data to the bucket" do
      expect(@cloud).to(receive(:write).with("products/key.txt", "value"))

      @asset.value = "value"
      @asset.store
    end

    it "should not try to store data when it's value is nil" do
      expect(@cloud).to(receive(:write).never)

      @asset.store
    end

    it "should not try to read data from bucket if its a new_asset" do
      expect(@cloud).to(receive(:read).never)

      expect(@asset.value).to(eq(nil))
    end

    it "should simply ignore calls to delete" do
      expect(@cloud).to(receive(:delete).never)

      @asset.delete
    end
  end

  describe "when first created (without a value) with subdirectory" do
    before do
      @asset = AssetCloud::Asset.new(@cloud, "products/retail/key.txt")
    end

    it "should have a relative_key_without_ext" do
      expect(@asset.relative_key_without_ext).to(eq("retail/key"))
    end

    it "should have a relative_key" do
      expect(@asset.relative_key).to(eq("retail/key.txt"))
    end
  end

  describe "when first created with value" do
    before do
      @asset = AssetCloud::Asset.new(@cloud, "products/key.txt", "value")
    end

    it "should be return new_asset? => true" do
      expect(@asset.new_asset?).to(eq(true))
    end

    it "should have a value of 'value'" do
      expect(@asset.value).to(eq("value"))
    end

    it "should return false when asked if it exists because its still a new_asset" do
      expect(@asset.exist?).to(eq(false))
    end

    it "should not try to read data from bucket if its a new_asset" do
      expect(@cloud).to(receive(:read).never)

      expect(@asset.value).to(eq("value"))
    end

    it "should write data to the bucket" do
      expect(@cloud).to(receive(:write).with("products/key.txt", "value"))
      @asset.store
    end
  end

  describe "when fetched from the bucket" do
    before do
      @asset = AssetCloud::Asset.at(@cloud, "products/key.txt", "value",
        AssetCloud::Metadata.new(true, "value".size, Time.now, Time.now))
    end

    it "should be return new_asset? => false" do
      expect(@asset.new_asset?).to(eq(false))
    end

    it "should indicate that it exists" do
      expect(@asset.exist?).to(eq(true))
    end

    it "should read the value from the bucket" do
      expect(@asset.value).to(eq("value"))
    end

    it "should simply ignore calls to delete" do
      expect(@cloud).to(receive(:delete).and_return(true))

      @asset.delete
    end

    it "should ask the bucket to create a full url" do
      expect(@cloud).to(receive(:url_for).with("products/key.txt", {}).and_return("http://assets/products/key.txt"))

      expect(@asset.url).to(eq("http://assets/products/key.txt"))
    end

    it "should ask the bucket whether or not it is versioned" do
      bucket = double("Bucket")
      expect(@cloud).to(receive(:buckets).and_return(products: bucket))
      expect(bucket).to(receive(:versioned?).and_return(true))

      expect(@asset.versioned?).to(eq(true))
    end

    it "should validate its key" do
      asset = AssetCloud::Asset.new(@cloud, "products/foo, bar.txt", "data")
      expect(asset.store).to(eq(false))
      expect(asset.errors.size).to(eq(1))
      expect(asset.errors.first).to(match(/illegal characters/))
    end
  end

  describe "comparable" do
    before do
      @key = "products/key.txt"
      @asset = AssetCloud::Asset.new(@cloud, @key)
    end

    context "comparing to instance of Asset class" do
      it "is equal if cloud and key of both assets are equal" do
        other_asset = AssetCloud::Asset.new(@cloud, @key)

        expect(@asset == other_asset).to(eq(true))
      end

      it "is not equal if key of both assets are not equal" do
        other_key = "products/other_key.txt"
        other_asset = AssetCloud::Asset.new(@cloud, other_key)

        expect(@asset == other_asset).to(eq(false))
      end
    end

    context "comparing to instance of non-Asset class" do
      it "is not equal to a non-Asset object" do
        AssetCloud::Asset.new(@cloud, "products/foo, bar.txt", "data")

        expect(@asset == "some_string").to(eq(false))
        expect(@asset == :some_symbol).to(eq(false))
        expect(@asset == []).to(eq(false))
        expect(@asset.nil?).to(eq(false))

        expect(@asset <=> "some_string").to(eq(nil))
        expect(@asset <=> :some_symbol).to(eq(nil))
        expect(@asset <=> []).to(eq(nil))
        expect(@asset <=> nil).to(eq(nil))
      end
    end
  end
end


text:
@implementation WLCoreDataHelper {
    NSString *databaseName;
}

+ (WLCoreDataHelper *)sharedHelper {
    static dispatch_once_t onceToken;
    static WLCoreDataHelper *sharedHelper = nil;

    dispatch_once(&onceToken, ^{
        sharedHelper = [[WLCoreDataHelper alloc] init];
        // Register helper for application termination notification
        [[NSNotificationCenter defaultCenter] addObserver:sharedHelper
                                                 selector:@selector(applicationWillTerminate)
                                                     name:UIApplicationWillTerminateNotification
                                                   object:nil];
    });
    return sharedHelper;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setDatabaseName:(NSString *)userDatabaseName {
    // This is preferebbly done in application delegate - this sets name of the database we will be looking for
    databaseName = userDatabaseName;
}

- (void)applicationWillTerminate {
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:databaseName withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // Create the coordinator and store

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSString *sqliteDatabaseName = [NSString stringWithFormat:@"%@.sqlite",databaseName];
    NSURL *storeURL = [[WLUtilityHelper applicationDocumentsDirectoryURL] URLByAppendingPathComponent:sqliteDatabaseName];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"WLCOREDATA_ERROR_DOMAIN" code:9999 userInfo:dict];

        // Error while saving data does not generate crash
        WLErrLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }

    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

- (void)deleteAllEntitiesOf:(NSString *)entityDescription  {
    if (entityDescription.length) {
        // Drop a specific table

        // Gather all entities of a type
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:[[WLCoreDataHelper sharedHelper] managedObjectContext]];
        [fetchRequest setEntity:entity];

        NSError *error;
        NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];

        // Remove all entities
        for (NSManagedObject *managedObject in items) {
            [_managedObjectContext deleteObject:managedObject];
        }

        // Save changes
        [self saveContext];
    }
}

- (void)flushDatabase{
    // Flush the whole datamodel completely
    [_managedObjectContext performBlockAndWait:^{
        NSArray *stores = [_persistentStoreCoordinator persistentStores];
        for(NSPersistentStore *store in stores) {
            [_persistentStoreCoordinator removePersistentStore:store error:nil];
            [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
        }
    }];
    _managedObjectModel    = nil;
    _managedObjectContext  = nil;
    _persistentStoreCoordinator = nil;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Error while saving data does not generate crash
            WLErrLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    }
}

@end


text:
    <a class="travel__link" href="<?php echo get_permalink($post->ID); ?>">
      <div class="img-fluid travel__image" style="background-image:<?php echo cc_background_image_filter(); ?>, url('<?php echo the_post_thumbnail_url('large-feature'); ?>')">

            <?php echo get_category_type_title(); ?>

            <?php echo get_category_type_subject(); ?>

            <?php echo get_card_title(); ?>

            <?php echo get_card_excerpt(null, '245'); ?>


text:
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

/**
 * The Enum Access Package Subject Type.
*/
public enum AccessPackageSubjectType
{
    /**
    * not Specified
    */
    NOT_SPECIFIED,
    /**
    * user
    */
    USER,
    /**
    * service Principal
    */
    SERVICE_PRINCIPAL,
    /**
    * unknown Future Value
    */
    UNKNOWN_FUTURE_VALUE,
    /**
    * For AccessPackageSubjectType values that were not expected from the service
    */
    UNEXPECTED_VALUE
}


text:
package support;

public class APIType
{
    public static String USER_TIMELINE = "/statuses/user_timeline";
    public static String FOLLOWERS = "/followers/list";
    public static String FRIENDS = "/friends/list";
    public static String USER_PROFILE = "/users/show";
}


text:
Client (in the root of the project)
```xml
<configuration>
  <system.webServer>

    <handlers>
      <remove name="WebDAV" />
    </handlers>

    <rewrite>
      <rules>
        <rule name="ember">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/contracts/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="{C:1}" />
        </rule>
      </rules>
    </rewrite>

    <defaultDocument>
      <files>
        <clear />
        <add value="index.html" />
      </files>
    </defaultDocument>

    <modules>
      <remove name="WebDAVModule"/>
    </modules>

  </system.webServer>
</configuration>
```

Server (in the API folder)
```xml
<configuration>
  <system.webServer>

    <handlers>
      <add name="iisnode" path="iisnode.js" verb="*" modules="iisnode" />
    </handlers>

    <iisnode watchedFiles="*.js;server\server.js;node_modules*;server*;common*" nodeProcessCommandLine="C:\Program Files (x86)\nodejs\node.exe" promoteServerVars="AUTH_USER,AUTH_TYPE" />

    <rewrite>
      <rules>
        <rule name="default">
          <match url="/*" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="iisnode.js" />
        </rule>
      </rules>
    </rewrite>

    <modules>
      <remove name="WebDAVModule"/>
    </modules>

  </system.webServer>
</configuration>
```


text:
import { Distribution } from "../types";
import { integer } from "./integer";

/**
 * Returns a Distribution to return a value within [1, sideCount]
 * @param sideCount The number of sides of the die
 */
export function die(sideCount: number): Distribution<number> {
  return integer(1, sideCount);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>The chef_authn application</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Modules

chef_authn

chef_keygen_cache

chef_keygen_worker

chef_keygen_worker_sup

chef_keyring

chef_time_utils


text:
var index = {
  functional: true,
  render: function render(h, _ref) {
    var children = _ref.children,
        slots = _ref.slots,
        _ref$props = _ref.props,
        regex = _ref$props.regex,
        invert = _ref$props.invert;
    var dummyEl = h('div', {}, []);

    if (process.server) {
      return dummyEl;
    }

    var botRegex = regex || /bot|googlebot|crawler|spider|robot|crawling/i;
    var isBot = navigator.userAgent && botRegex.test(navigator.userAgent);
    var shouldShow = invert ? isBot : !isBot;

    if (!shouldShow) {
      return dummyEl;
    }

    return h('div', {}, slots().default);
  }
};

export default index;


text:
package org.hcjf.layers.storage.actions;

import org.hcjf.layers.storage.StorageSession;

/**
 * Insert storage operation.
 * @author javaito
 *
 */
public abstract class Insert<S extends StorageSession> extends StorageAction<S> {

    public Insert(S session) {
        super(session);
    }

    @Override
    protected void onAdd(Object object) {
        setResultType(object.getClass());
        setResourceName(object.getClass().getSimpleName().toLowerCase());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">RubeLoaderTest</string>
</resources>


text:
from __future__ import absolute_import, print_function, division
import os

import zarr
import petl as etl
import pandas
import h5py

title = 'Phase 1 AR3.1 release'

# noinspection PyGlobalUndefined
def init(release_dir):
    """Initialise data resources.

    Parameters
    ----------
    release_dir : string
        Local filesystem path where data from the release are stored.

    """

    # variation
    ###########

    global callset, callset_pass
    variation_dir = os.path.join(release_dir, 'variation')

    # main callset
    callset_zarr_fn = os.path.join(variation_dir, 'main', 'zarr2', 'ag1000g.phase1.ar3')
    if os.path.exists(callset_zarr_fn):
        callset = zarr.open_group(callset_zarr_fn, mode='r')

    # main callset, PASS variants only
    callset_pass_zarr_fn = os.path.join(variation_dir, 'main', 'zarr2', 'ag1000g.phase1.ar3.pass')
    if os.path.exists(callset_pass_zarr_fn):
        callset_pass = zarr.open_group(callset_pass_zarr_fn, mode='r')

    # haplotypes
    ############

    global callset_phased, tbl_haplotypes, lkp_haplotypes, df_haplotypes
    haplotypes_dir = os.path.join(release_dir, 'haplotypes')

    # try HDF5 first
    callset_phased_h5_fn = os.path.join(haplotypes_dir, 'main', 'hdf5',
                                        'ag1000g.phase1.ar3.1.haplotypes.h5')
    if os.path.exists(callset_phased_h5_fn):
        callset_phased = h5py.File(callset_phased_h5_fn, mode='r')

    # prefer Zarr if available
    # N.B., the Zarr data is not consistent with HDF5 or shapeit outputs,
    # it is based on a previous phasing run.
    #
    #callset_phased_zarr_fn = os.path.join(haplotypes_dir, 'main', 'zarr2',
    #                                      'ag1000g.phase1.ar3.1.haplotypes')
    #if os.path.exists(callset_phased_zarr_fn):
    #    callset_phased = zarr.open_group(callset_phased_zarr_fn, mode='r')

    # haplotypes metadata
    haplotypes_fn = os.path.join(haplotypes_dir, 'haplotypes.meta.txt')
    if os.path.exists(haplotypes_fn):
        tbl_haplotypes = (
            etl
            .fromtsv(haplotypes_fn)
            .convert(('index', 'kt_2la', 'kt_2rb'), int)
        )
        lkp_haplotypes = tbl_haplotypes.recordlookupone('label')
        df_haplotypes = pandas.read_csv(haplotypes_fn, sep='\t', index_col='index')


text:
#include "hcoll.h"
#include "hcoll/api/hcoll_dte.h"
#include <assert.h>

static int recv_nb(dte_data_representation_t data,
                   uint32_t count,
                   void *buffer,
                   rte_ec_handle_t, rte_grp_handle_t, uint32_t tag, rte_request_handle_t * req);

static int send_nb(dte_data_representation_t data,
                   uint32_t count,
                   void *buffer,
                   rte_ec_handle_t ec_h,
                   rte_grp_handle_t grp_h, uint32_t tag, rte_request_handle_t * req);

static int test(rte_request_handle_t * request, int *completed);

static int ec_handle_compare(rte_ec_handle_t handle_1,
                             rte_grp_handle_t
                             group_handle_1,
                             rte_ec_handle_t handle_2, rte_grp_handle_t group_handle_2);

static int get_ec_handles(int num_ec,
                          int *ec_indexes, rte_grp_handle_t, rte_ec_handle_t * ec_handles);

static int get_my_ec(rte_grp_handle_t, rte_ec_handle_t * ec_handle);

static int group_size(rte_grp_handle_t group);
static int my_rank(rte_grp_handle_t grp_h);
static int ec_on_local_node(rte_ec_handle_t ec, rte_grp_handle_t group);
static rte_grp_handle_t get_world_group_handle(void);
static uint32_t jobid(void);

static void *get_coll_handle(void);
static int coll_handle_test(void *handle);
static void coll_handle_free(void *handle);
static void coll_handle_complete(void *handle);
static int group_id(rte_grp_handle_t group);

static int world_rank(rte_grp_handle_t grp_h, rte_ec_handle_t ec);

#undef FUNCNAME
#define FUNCNAME progress
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static void progress(void)
{
    int ret;

    if (0 == world_comm_destroying) {
        MPID_Progress_test();
    }
    else {
        /* FIXME: The hcoll library needs to be updated to return
         * error codes.  The progress function pointer right now
         * expects that the function returns void. */
        ret = hcoll_do_progress();
        assert(ret == MPI_SUCCESS);
    }
}

#undef FUNCNAME
#define FUNCNAME init_module_fns
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static void init_module_fns(void)
{
    hcoll_rte_functions.send_fn = send_nb;
    hcoll_rte_functions.recv_fn = recv_nb;
    hcoll_rte_functions.ec_cmp_fn = ec_handle_compare;
    hcoll_rte_functions.get_ec_handles_fn = get_ec_handles;
    hcoll_rte_functions.rte_group_size_fn = group_size;
    hcoll_rte_functions.test_fn = test;
    hcoll_rte_functions.rte_my_rank_fn = my_rank;
    hcoll_rte_functions.rte_ec_on_local_node_fn = ec_on_local_node;
    hcoll_rte_functions.rte_world_group_fn = get_world_group_handle;
    hcoll_rte_functions.rte_jobid_fn = jobid;
    hcoll_rte_functions.rte_progress_fn = progress;
    hcoll_rte_functions.rte_get_coll_handle_fn = get_coll_handle;
    hcoll_rte_functions.rte_coll_handle_test_fn = coll_handle_test;
    hcoll_rte_functions.rte_coll_handle_free_fn = coll_handle_free;
    hcoll_rte_functions.rte_coll_handle_complete_fn = coll_handle_complete;
    hcoll_rte_functions.rte_group_id_fn = group_id;
    hcoll_rte_functions.rte_world_rank_fn = world_rank;
}

#undef FUNCNAME
#define FUNCNAME hcoll_rte_fns_setup
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
void hcoll_rte_fns_setup(void)
{
    init_module_fns();
}

/* This function converts dte_general_representation data into regular iovec array which is
  used in rml
  */
static inline int count_total_dte_repeat_entries(struct dte_data_representation_t *data)
{
    unsigned int i;

    struct dte_generalized_iovec_t *dte_iovec = data->rep.general_rep->data_representation.data;
    int total_entries_number = 0;
    for (i = 0; i < dte_iovec->repeat_count; i++) {
        total_entries_number += dte_iovec->repeat[i].n_elements;
    }
    return total_entries_number;
}

#undef FUNCNAME
#define FUNCNAME recv_nb
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int recv_nb(struct dte_data_representation_t data,
                   uint32_t count,
                   void *buffer,
                   rte_ec_handle_t ec_h,
                   rte_grp_handle_t grp_h, uint32_t tag, rte_request_handle_t * req)
{
    int mpi_errno;
    MPI_Datatype dtype;
    MPID_Request *request;
    MPID_Comm *comm;
    int context_offset;
    size_t size;
    mpi_errno = MPI_SUCCESS;
    context_offset = MPID_CONTEXT_INTRA_COLL;
    comm = (MPID_Comm *) grp_h;
    if (!ec_h.handle) {
        MPIU_ERR_SETANDJUMP2(mpi_errno, MPI_ERR_OTHER, "**hcoll_wrong_arg",
                             "**hcoll_wrong_arg %p %d", ec_h.handle, ec_h.rank);
    }

    if (HCOL_DTE_IS_INLINE(data)) {
        if (!buffer && !HCOL_DTE_IS_ZERO(data)) {
            MPIU_ERR_SETANDJUMP(mpi_errno, MPI_ERR_OTHER, "**null_buff_ptr");
        }
        size = (size_t) data.rep.in_line_rep.data_handle.in_line.packed_size * count / 8;
        dtype = MPI_CHAR;
        mpi_errno = MPID_Irecv(buffer, size, dtype, ec_h.rank, tag, comm, context_offset, &request);
        req->data = (void *) request;
        req->status = HCOLRTE_REQUEST_ACTIVE;
    }
    else {
        int total_entries_number;
        int i;
        unsigned int j;
        void *buf;
        uint64_t len;
        int repeat_count;
        struct dte_struct_t *repeat;
        if (NULL != buffer) {
            /* We have a full data description & buffer pointer simultaneously.
             * It is ambiguous. Throw a warning since the user might have made a
             * mistake with data reps */
            MPIU_DBG_MSG(CH3_OTHER, VERBOSE, "Warning: buffer_pointer != NULL for NON-inline data "
                         "representation: buffer_pointer is ignored");
        }
        total_entries_number = count_total_dte_repeat_entries(&data);
        repeat = data.rep.general_rep->data_representation.data->repeat;
        repeat_count = data.rep.general_rep->data_representation.data->repeat_count;
        for (i = 0; i < repeat_count; i++) {
            for (j = 0; j < repeat[i].n_elements; j++) {
                char *repeat_unit = (char *) &repeat[i];
                buf = (void *) (repeat_unit + repeat[i].elements[j].base_offset);
                len = repeat[i].elements[j].packed_size;
                recv_nb(DTE_BYTE, len, buf, ec_h, grp_h, tag, req);
            }
        }
    }
  fn_exit:
    return mpi_errno;
  fn_fail:
    return HCOLL_ERROR;
}

#undef FUNCNAME
#define FUNCNAME send_nb
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int send_nb(dte_data_representation_t data,
                   uint32_t count,
                   void *buffer,
                   rte_ec_handle_t ec_h,
                   rte_grp_handle_t grp_h, uint32_t tag, rte_request_handle_t * req)
{
    int mpi_errno;
    MPI_Datatype dtype;
    MPID_Request *request;
    MPID_Comm *comm;
    int context_offset;
    size_t size;
    mpi_errno = MPI_SUCCESS;
    context_offset = MPID_CONTEXT_INTRA_COLL;
    comm = (MPID_Comm *) grp_h;
    if (!ec_h.handle) {
        MPIU_ERR_SETANDJUMP2(mpi_errno, MPI_ERR_OTHER, "**hcoll_wrong_arg",
                             "**hcoll_wrong_arg %p %d", ec_h.handle, ec_h.rank);
    }

    if (HCOL_DTE_IS_INLINE(data)) {
        if (!buffer && !HCOL_DTE_IS_ZERO(data)) {
            MPIU_ERR_SETANDJUMP(mpi_errno, MPI_ERR_OTHER, "**null_buff_ptr");
        }
        size = (size_t) data.rep.in_line_rep.data_handle.in_line.packed_size * count / 8;
        dtype = MPI_CHAR;
        mpi_errno = MPID_Isend(buffer, size, dtype, ec_h.rank, tag, comm, context_offset, &request);
        req->data = (void *) request;
        req->status = HCOLRTE_REQUEST_ACTIVE;
    }
    else {
        int total_entries_number;
        int i;
        unsigned int j;
        void *buf;
        uint64_t len;
        int repeat_count;
        struct dte_struct_t *repeat;
        if (NULL != buffer) {
            /* We have a full data description & buffer pointer simultaneously.
             * It is ambiguous. Throw a warning since the user might have made a
             * mistake with data reps */
            MPIU_DBG_MSG(CH3_OTHER, VERBOSE, "Warning: buffer_pointer != NULL for NON-inline data "
                         "representation: buffer_pointer is ignored");
        }
        total_entries_number = count_total_dte_repeat_entries(&data);
        repeat = data.rep.general_rep->data_representation.data->repeat;
        repeat_count = data.rep.general_rep->data_representation.data->repeat_count;
        for (i = 0; i < repeat_count; i++) {
            for (j = 0; j < repeat[i].n_elements; j++) {
                char *repeat_unit = (char *) &repeat[i];
                buf = (void *) (repeat_unit + repeat[i].elements[j].base_offset);
                len = repeat[i].elements[j].packed_size;
                send_nb(DTE_BYTE, len, buf, ec_h, grp_h, tag, req);
            }
        }
    }
  fn_exit:
    return mpi_errno;
  fn_fail:
    return HCOLL_ERROR;
}

#undef FUNCNAME
#define FUNCNAME test
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int test(rte_request_handle_t * request, int *completed)
{
    MPID_Request *req;
    req = (MPID_Request *) request->data;
    if (HCOLRTE_REQUEST_ACTIVE != request->status) {
        *completed = true;
        return HCOLL_SUCCESS;
    }

    *completed = (int) MPID_Request_is_complete(req);
    if (*completed) {
        MPID_Request_release(req);
        request->status = HCOLRTE_REQUEST_DONE;
    }

    return HCOLL_SUCCESS;
}

#undef FUNCNAME
#define FUNCNAME ec_handle_compare
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int ec_handle_compare(rte_ec_handle_t handle_1,
                             rte_grp_handle_t
                             group_handle_1,
                             rte_ec_handle_t handle_2, rte_grp_handle_t group_handle_2)
{
    return handle_1.handle == handle_2.handle;
}

#undef FUNCNAME
#define FUNCNAME get_ec_handles
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int get_ec_handles(int num_ec,
                          int *ec_indexes, rte_grp_handle_t grp_h, rte_ec_handle_t * ec_handles)
{
    int i;
    MPID_Comm *comm;
    comm = (MPID_Comm *) grp_h;
    for (i = 0; i < num_ec; i++) {
        ec_handles[i].rank = ec_indexes[i];
        ec_handles[i].handle = (void *) (comm->vcr[ec_indexes[i]]);
    }
    return HCOLL_SUCCESS;
}

#undef FUNCNAME
#define FUNCNAME get_my_ec
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int get_my_ec(rte_grp_handle_t grp_h, rte_ec_handle_t * ec_handle)
{
    MPID_Comm *comm;
    comm = (MPID_Comm *) grp_h;
    int my_rank = MPIR_Comm_rank(comm);
    ec_handle->handle = (void *) (comm->vcr[my_rank]);
    ec_handle->rank = my_rank;
    return HCOLL_SUCCESS;
}

#undef FUNCNAME
#define FUNCNAME group_size
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int group_size(rte_grp_handle_t grp_h)
{
    return MPIR_Comm_size((MPID_Comm *) grp_h);
}

#undef FUNCNAME
#define FUNCNAME my_rank
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int my_rank(rte_grp_handle_t grp_h)
{
    return MPIR_Comm_rank((MPID_Comm *) grp_h);
}

#undef FUNCNAME
#define FUNCNAME ec_on_local_node
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int ec_on_local_node(rte_ec_handle_t ec, rte_grp_handle_t group)
{
    MPID_Comm *comm;
    MPID_Node_id_t nodeid, my_nodeid;
    int my_rank;
    comm = (MPID_Comm *) group;
    MPID_Get_node_id(comm, ec.rank, &nodeid);
    my_rank = MPIR_Comm_rank(comm);
    MPID_Get_node_id(comm, my_rank, &my_nodeid);
    return (nodeid == my_nodeid);
}

#undef FUNCNAME
#define FUNCNAME get_world_group_handle
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static rte_grp_handle_t get_world_group_handle(void)
{
    return (rte_grp_handle_t) (MPIR_Process.comm_world);
}

#undef FUNCNAME
#define FUNCNAME jobid
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static uint32_t jobid(void)
{
    /* not used currently */
    return 0;
}

#undef FUNCNAME
#define FUNCNAME group_id
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int group_id(rte_grp_handle_t group)
{
    MPID_Comm *comm;
    comm = (MPID_Comm *) group;
    return comm->context_id;
}

#undef FUNCNAME
#define FUNCNAME get_coll_handle
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static void *get_coll_handle(void)
{
    MPID_Request *req;
    req = MPID_Request_create();
    req->kind = MPID_COLL_REQUEST;
    return (void *) req;
}

#undef FUNCNAME
#define FUNCNAME coll_handle_test
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int coll_handle_test(void *handle)
{
    int completed;
    MPID_Request *req;
    req = (MPID_Request *) handle;
    completed = (int) MPID_Request_is_complete(req);
    return completed;
}

#undef FUNCNAME
#define FUNCNAME coll_handle_free
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static void coll_handle_free(void *handle)
{
    MPID_Request *req;
    if (NULL != handle) {
        req = (MPID_Request *) handle;
        MPID_Request_release(req);
    }
}

#undef FUNCNAME
#define FUNCNAME coll_handle_complete
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static void coll_handle_complete(void *handle)
{
    MPID_Request *req;
    if (NULL != handle) {
        req = (MPID_Request *) handle;
        MPID_Request_set_completed(req);
    }
}

#undef FUNCNAME
#define FUNCNAME world_rank
#undef FCNAME
#define FCNAME MPIU_QUOTE(FUNCNAME)
static int world_rank(rte_grp_handle_t grp_h, rte_ec_handle_t ec)
{
    return ((MPID_VCR) ec.handle)->pg_rank;
}


text:
package com.connectsdk.service.command;

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

import org.json.JSONObject;

import com.connectsdk.service.capability.listeners.ResponseListener;

/**
 * Internal implementation of ServiceSubscription for URL-based commands
 */
public class URLServiceSubscription<T extends ResponseListener<?>> extends ServiceCommand<T> implements ServiceSubscription<T> {
    private List<T> listeners = new ArrayList<T>();

    public URLServiceSubscription(ServiceCommandProcessor processor, String uri, JSONObject payload, ResponseListener<Object> listener) {
        super(processor, uri, payload, listener);
    }

    public URLServiceSubscription(ServiceCommandProcessor processor, String uri, JSONObject payload, boolean isWebOS, ResponseListener<Object> listener) {
        super(processor, uri, payload, isWebOS, listener);

        if (isWebOS)
            httpMethod = "subscribe";
    }

    public void send() {
        this.subscribe();
    }

    public void subscribe() {
        if (!(httpMethod.equalsIgnoreCase(TYPE_GET)
                || httpMethod.equalsIgnoreCase(TYPE_POST))) {
            httpMethod = "subscribe";
        }
        processor.sendCommand(this);
    }

    public void unsubscribe() {
        processor.unsubscribe(this);
    }

    public T addListener(T listener) {
        listeners.add(listener);

        return listener;
    }

    public void removeListener(T listener) {
        listeners.remove(listener);
    }

    public void removeListeners() {
        listeners.clear();
    }

    public List<T> getListeners() {
        return listeners;
    }
}