text:
<?php

namespace Ff\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ff\DemoBundle\Form\TareaType;
use Ff\DemoBundle\Form\Tarea2Type;
use Ff\DemoBundle\Entity\Tarea;
use Ff\DemoBundle\Entity\Tarea2;
use Ff\DemoBundle\Entity\Alumnos\Alumno;
use Ff\DemoBundle\Entity\AlumnoPago;
use Ff\DemoBundle\Entity\Muaythai;
use Ff\DemoBundle\Entity\Jjb;
use Ff\DemoBundle\Entity\Judo;
use Ff\DemoBundle\Entity\Mma;
use Ff\DemoBundle\Entity\Box;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Ff\DemoBundle\Entity\Boxandfitness;

class DetalleAlumnoController extends Controller
{

	    public function mostrar_alumnoAction(Request $request , $id){

                $alumno = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\Alumnos\Alumno')
                    ->find($id);

                $alumnop = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\AlumnoPago')
                    ->findBy(
                        array('idalumno'  => $id),
                        array('id' => 'DESC')
                    );

                $tarea2 = new Tarea2();
                $tarea2->setFechaInicio(new \DateTime('now'));
                $tarea2->setFechaFinal(new \DateTime('now'));
                $form = $this->createForm(new Tarea2Type(), $tarea2);
                $form->handleRequest($request);

                if ($form->isValid())
                {
                    // **** actualizo la fecha final en alumnos

                    $em= $this->getDoctrine()->getManager();
                    $alumnoaux = $em->getRepository('Ff\DemoBundle\Entity\Alumnos\Alumno')->find($id);
                    $alumnoaux->setFechaFinal($tarea2->getFechafinal());
                    $em->flush();

                    // **** ingreso en AlumnosPagos ***********

                    $vecestotales=0;

                    while($tarea2->getFechaFinal()>$tarea2->getFechaInicio()){
                        date_add($tarea2->getFechaInicio(), date_interval_create_from_date_string('1 days'));
                        $vecestotales= $vecestotales+1;
                    }
                    $diasaumentados=$vecestotales;
                    $vecestotales=$vecestotales/7;
                    $vecestotales=$vecestotales*$tarea2->getVeces();
                    $vecestotales= (int)$vecestotales;

                    while($diasaumentados>0){
                        date_add($tarea2->getFechaInicio(), date_interval_create_from_date_string('-1 days'));
                        $diasaumentados=$diasaumentados-1;
                    }

                    $pagos= new AlumnoPago();
                    $pagos->setIdalumno($id);
                    $pagos->setPrecio($tarea2->getPrecio());
                    $pagos->setFechaFinal($tarea2->getFechaFinal());
                    $pagos->setFechaInicio($tarea2->getFechaInicio());
                    $pagos->setDisciplina($tarea2->getDisciplina());
                    $pagos->setDisciplina2($tarea2->getDisciplina2());
                    $pagos->SetTipodepago($tarea2->getTipodepago());
                    $pagos->SetVeces($tarea2->getVeces());
                    $pagos->setVecesasistencia(0);
                    $pagos->setVecestotales($vecestotales);

                    $em_pago = $this->getDoctrine()->getManager();
                    $em_pago->persist($pagos);
                    $em_pago->flush();

                     //***** Ingreso en las tablas de disciplina

                    if($tarea2->getDisciplina()== 'Box'){ $d = new Box();}

                    if($tarea2->getDisciplina()== 'Thai'){ $d = new Muaythai();}

                    if($tarea2->getDisciplina()== 'Mma'){ $d = new Mma(); }

                    if($tarea2->getDisciplina()== 'Box-fit'){ $d = new Boxandfitness(); }

                    if($tarea2->getDisciplina()== 'Judo'){ $d = new Judo();}

                    $d->setFechaInicio($tarea2->getFechaInicio());
                    $d->setPrecio($tarea2->getPrecio());
                    $d->setSexo('3');
                    $d->SetVeces($tarea2->getVeces());
                    $d->SetIdpago($pagos->getId());

                    $em_d = $this->getDoctrine()->getManager();
                    $em_d->persist($d);
                    $em_d->flush();

                    //*** termino de ingresar los datos *****

                    $alumno = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\Alumnos\Alumno')
                    ->find($id);

                    $alumnop = $this-> getDoctrine()
                        ->getRepository('Ff\DemoBundle\Entity\AlumnoPago')
                        ->findBy(
                            array('idalumno'  => $id),
                            array('id' => 'DESC')
                        );

                    return $this->render('FfDemoBundle:Default:alumno.html.twig', array(
                    'form' => $form->createView(),'alumno' => $alumno,'alumnop' => $alumnop, 'id' => $id));

                }

                return $this->render('FfDemoBundle:Default:alumno.html.twig', array(
                    'form' => $form->createView(),'alumno' => $alumno,'alumnop' => $alumnop, 'id' => $id));
        }

        public function mostrar_alumno_asistenciaAction($id){

                $alumno = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\Alumnos\Alumno')
                    ->find($id);

                $alumnop = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\AlumnoPago')
                    ->findBy(
                        array('idalumno'  => $id),
                        array('id' => 'DESC')
                    );

                /////*****************************************************************

                $em = $this->getDoctrine()->getManager();
                    $query = $em->createQuery(
                    'SELECT  MAX(a.id) FROM FfDemoBundle:AlumnoPago a WHERE a.idalumno='.$id.'');

                $consulta = $query->getResult();
                $idUltPago=  $consulta[0][1];

                $em2 = $this->getDoctrine()->getManager();
                $alumnop1 = $em2->getRepository('Ff\DemoBundle\Entity\AlumnoPago')->find($idUltPago);

                $asistencia = $alumnop1->getVecesasistencia();

                $asistencia = $asistencia + 1;

                $alumnop1->setVecesasistencia($asistencia);

                $em2->flush();

                return $this->redirect($this->generateUrl('alumno',array('id' => $id)));
        }

        /* aqui empieza el controlador que edita los datos del alumno

        *************************
        ************************
        *************************

        */

        public function editarAction(Request $request, $id){

            $em = $this->getDoctrine()->getManager();
            $alumno = $em->getRepository('Ff\DemoBundle\Entity\Alumnos\Alumno')->find($id);

            $apellidop=$alumno->getApellidop();
            $apellidom=$alumno->getApellidom();
            $nombre=$alumno->getNombre();

            $alumnop = $this-> getDoctrine()
                    ->getRepository('Ff\DemoBundle\Entity\AlumnoPago')
                    ->findBy(
                        array('idalumno'  => $id),
                        array('id' => 'DESC')
                    );

            //************************************************************************

            $em1 = $this->getDoctrine()->getManager();
                    $query = $em1->createQuery(
                    'SELECT  MAX(a.id) FROM FfDemoBundle:AlumnoPago a WHERE a.idalumno='.$id.'');

                $consulta = $query->getResult();
                $idUltPago=  $consulta[0][1];

            $em2 = $this->getDoctrine()->getManager();
            $alumnop1 = $em2->getRepository('Ff\DemoBundle\Entity\AlumnoPago')->find($idUltPago);

            //***********************************************************************

            $tarea = new Tarea();
            $tarea->setNombre($alumno->getNombre());
            $tarea->setApellidop($alumno->getApellidop());
            $tarea->setApellidom($alumno->getApellidom());
            $tarea->setDni($alumno->getDni());
            $tarea->setTelefonoc($alumno->getTelefonoc());
            $tarea->setTelefonof($alumno->getTelefonof());
            $tarea->setEmail($alumno->getEmail());
            $tarea->setCumple($alumno->getCumple());
            $tarea->setSexo($alumno->getSexo());
            $tarea->setDisciplina($alumnop1->getDisciplina());
            $tarea->setDisciplina2($alumnop1->getDisciplina2());
            $var = $alumnop1->getDisciplina();
            $tarea->setFechaFinal($alumnop1->getFechafinal());
            $tarea->setFechaInicio($alumnop1->getFechainicio());
            $tarea->setPrecio($alumnop1->getPrecio());
            $tarea->SetTipodepago($alumnop1->getTipodepago());
            $tarea->SetVeces($alumnop1->getVeces());

            $form = $this->createForm(new TareaType(), $tarea);
            $form->handleRequest($request);

            if ($form->isValid())
            {
                $alumno->setNombre($tarea->getNombre());
                $alumno->setApellidop($tarea->getApellidop());
                $alumno->setApellidom($tarea->getApellidom());
                $alumno->setDni($tarea->getDni());
                $alumno->setTelefonoc($tarea->getTelefonoc());
                $alumno->setEmail($tarea->getEmail());
                $alumno->setCumple($tarea->getCumple());
                $alumno->setTelefonof($tarea->getTelefonof());
                $alumno->setFechafinal($tarea->getFechaFinal());
                $alumno->setFile($tarea->getFile());
                $alumnop1->setDisciplina($tarea->getDisciplina());
                $alumnop1->setDisciplina2($tarea->getDisciplina2());
                $alumnop1->SetVeces($tarea->getVeces());

                $em->flush();
                $em2->flush();

                //***********************************************************************

                    $em4 = $this->getDoctrine()->getManager();

                    if( ($var== 1)||($var=='Thai') ){
                         $query = $em4->createQuery(
                         'SELECT  MAX(a.id) FROM FfDemoBundle:Muaythai a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\Muaythai')->find($auxid);
                    }

                    if ($var== 2) {
                         $query = $em4->createQuery(
                        'SELECT  MAX(a.id) FROM FfDemoBundle:Jjb a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\Jjb')->find($auxid);
                    }

                    if( ($var== 3) || ($var=='Judo') ){
                         $query = $em4->createQuery(
                        'SELECT  MAX(a.id) FROM FfDemoBundle:Judo a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\Judo')->find($auxid);
                    }

                    if( ($var == 4)||($var=='Mma') ){
                         $query = $em4->createQuery(
                        'SELECT  MAX(a.id) FROM FfDemoBundle:Mma a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\Mma')->find($auxid);
                    }

                    if( ($var== 5)||($var=='Box') ){
                         $query = $em4->createQuery(
                        'SELECT  MAX(a.id) FROM FfDemoBundle:Box a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\box')->find($auxid);

                    }

                    if($var=='Box-fit'){
                         $query = $em4->createQuery(
                        'SELECT  MAX(a.id) FROM FfDemoBundle:Boxandfitness a WHERE a.idpago='.$idUltPago.'');
                         $consulta= $query->getResult();
                         $auxid=$consulta[0][1];

                         $em5 = $this->getDoctrine()->getManager();
                         $disciplina = $em5->getRepository('Ff\DemoBundle\Entity\Boxandfitness')->find($auxid);

                    }

                    if($var== $tarea->getDisciplina() ){

                        $disciplina->SetPrecio($tarea->getPrecio());
                        $disciplina->SetFechainicio($tarea->getFechaInicio());
                        $disciplina->SetSexo($tarea->getSexo());
                        $em5->flush();
                    }
                    else{

                        $disciplina->SetPrecio(0);
                        $disciplina->setSexo(4);
                        $em5->flush();

                        if($tarea->getDisciplina()== 'Thai'){
                            $var= new Muaythai();
                        }
                        if($tarea->getDisciplina()== 'Box-fit'){
                            $var = new Boxandfitness();
                        }
                        if($tarea->getDisciplina()== 'Judo'){
                            $var = new Judo();
                        }
                        if($tarea->getDisciplina()== 'Mma'){
                            $var = new Mma();
                        }
                        if($tarea->getDisciplina()== 'Box'){
                            $var = new Box();
                        }
                            $var->setFechaInicio($tarea->getFechaInicio());
                            $var->setPrecio($tarea->getPrecio());
                            $var->setSexo($tarea->getSexo());
                            $var->SetVeces($tarea->getVeces());
                            $var->SetIdpago($idUltPago);

                            $em6 = $this->getDoctrine()->getManager();
                            $em6->persist($var);
                            $em6->flush();

                    }

                    //******************************************************

                    $vecestotales=0;
                        while($tarea->getFechaFinal()>$tarea->getFechaInicio()){
                            date_add($tarea->getFechaInicio(), date_interval_create_from_date_string('1 days'));
                            $vecestotales= $vecestotales+1;
                        }
                        $vecestotales=$vecestotales/7;
                        $vecestotales=$vecestotales*$tarea->getVeces();
                        $vecestotales= (int)$vecestotales;

                $em3= $this->getDoctrine()->getManager();
                $alumnoaux = $em3->getRepository('Ff\DemoBundle\Entity\AlumnoPago')->find($idUltPago);

                $alumnoaux->setVecestotales($vecestotales);

                $em3->flush();

                return $this->redirect($this->generateUrl('alumno',array('id' => $id)));

            }
        return $this->render('FfDemoBundle:Default:editar.html.twig', array(
            'form' => $form->createView(),'apellidop' => $apellidop, 'apellidom' => $apellidom, 'nombre' => $nombre,));

        }

}


text:
* [Getting Started](getting_started)
* [Command-Line Interface](command-line_interface)
* [Vagrantfile](vagrantfile)
* [Provisioning](provisioning)
* [Networking](networking)
* [Multi-Machine](multi-machine)

以上

redpajama_set_name: RedPajamaGithub


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

  CSS parsing utilities.


text:
package com.android.internal.telephony;

import android.telephony.Rlog;

import com.android.internal.telephony.uicc.UiccController;
import com.android.internal.telephony.uicc.IccCardProxy;

import java.io.FileDescriptor;
import java.io.PrintWriter;

/**
 * A debug service that will dump telephony's state
 *
 * Currently this "Service" has a proxy in the phone app
 * com.android.phone.TelephonyDebugService which actually
 * invokes the dump method.
 */
public class DebugService {
    private static String TAG = "DebugService";

    /** Constructor */
    public DebugService() {
        log("DebugService:");
    }

    /**
     * Dump the state of various objects, add calls to other objects as desired.
     */
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        log("dump: +");
        PhoneProxy phoneProxy = null;
        PhoneBase phoneBase = null;

        try {
            phoneProxy = (PhoneProxy) PhoneFactory.getDefaultPhone();
        } catch (Exception e) {
            pw.println("Telephony DebugService: Could not getDefaultPhone e=" + e);
            return;
        }
        try {
            phoneBase = (PhoneBase)phoneProxy.getActivePhone();
        } catch (Exception e) {
            pw.println("Telephony DebugService: Could not PhoneBase e=" + e);
            return;
        }

        /**
         * Surround each of the sub dump's with try/catch so even
         * if one fails we'll be able to dump the next ones.
         */
        pw.println();
        pw.println("++++++++++++++++++++++++++++++++");
        pw.flush();
        try {
            phoneBase.dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            phoneBase.mDcTracker.dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            phoneBase.getServiceStateTracker().dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            phoneBase.getCallTracker().dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            ((RIL)phoneBase.mCi).dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            UiccController.getInstance().dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        try {
            ((IccCardProxy)phoneProxy.getIccCard()).dump(fd, pw, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pw.flush();
        pw.println("++++++++++++++++++++++++++++++++");
        log("dump: -");
    }

    private static void log(String s) {
        Rlog.d(TAG, "DebugService " + s);
    }
}


text:
@implementation _MiscMergeFieldCommand

- (void)dealloc
{
    [expression release];
    [super dealloc];
}

- (BOOL)parseFromScanner:(NSScanner *)aScanner template:(MiscMergeTemplate *)template
{
    [self eatKeyWord:@"field" fromScanner:aScanner isOptional:YES];
    expression = [[self getExpressionFromScanner:aScanner] retain];
    return YES;
}

- (MiscMergeCommandExitType)executeForMerge:(MiscMergeEngine *)aMerger
{
    [aMerger appendToOutput:[expression evaluateWithEngine:aMerger]];
    return MiscMergeCommandExitNormal;
}

@end


text:
package org.ocpsoft.rewrite.config;

import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.event.Rewrite;

/**
 * An {@link OperationBuilder} that does nothing.
 *
 * @author Lincoln Baxter, III
 */
public final class NoOp extends DefaultOperationBuilder
{
   @Override
   public void perform(Rewrite event, EvaluationContext context)
   {}

   @Override
   public String toString()
   {
      return "new NoOp()";
   }
}


text:
@implementation UIImage (LDSDKShare)

// Returns a rescaled copy of the image, taking into account its orientation
// The image will be scaled disproportionately if necessary to fit the bounds specified by the
// parameter
- (UIImage *)LDSDKShare_resizedImage:(CGSize)newSize
                interpolationQuality:(CGInterpolationQuality)quality
{
    BOOL drawTransposed;

    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            drawTransposed = YES;
            break;

        default:
            drawTransposed = NO;
    }

    return [self LDSDKShare_resizedImage:newSize
                               transform:[self LDSDKShare_transformForOrientation:newSize]
                          drawTransposed:drawTransposed
                    interpolationQuality:quality];
}

// Returns a copy of the image that has been transformed using the given affine transform and scaled
// to the new size
// The new image's orientation will be UIImageOrientationUp, regardless of the current image's
// orientation
// If the new size is not integral, it will be rounded up
- (UIImage *)LDSDKShare_resizedImage:(CGSize)newSize
                           transform:(CGAffineTransform)transform
                      drawTransposed:(BOOL)transpose
                interpolationQuality:(CGInterpolationQuality)quality
{
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    CGRect transposedRect = CGRectMake(0, 0, newRect.size.height, newRect.size.width);
    CGImageRef imageRef = self.CGImage;

    // Build a context that's the same dimensions as the new size
    CGContextRef bitmap = CGBitmapContextCreate(
        NULL, newRect.size.width, newRect.size.height, CGImageGetBitsPerComponent(imageRef), 0,
        CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef));

    // Rotate and/or flip the image if required by its orientation
    CGContextConcatCTM(bitmap, transform);

    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(bitmap, quality);

    // Draw into the context; this scales the image
    CGContextDrawImage(bitmap, transpose ? transposedRect : newRect, imageRef);

    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    // Clean up
    CGContextRelease(bitmap);
    CGImageRelease(newImageRef);

    return newImage;
}

// Returns an affine transform that takes into account the image orientation when drawing a scaled
// image
- (CGAffineTransform)LDSDKShare_transformForOrientation:(CGSize)newSize
{
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (self.imageOrientation) {
        case UIImageOrientationDown:          // EXIF = 3
        case UIImageOrientationDownMirrored:  // EXIF = 4
            transform = CGAffineTransformTranslate(transform, newSize.width, newSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:          // EXIF = 6
        case UIImageOrientationLeftMirrored:  // EXIF = 5
            transform = CGAffineTransformTranslate(transform, newSize.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:          // EXIF = 8
        case UIImageOrientationRightMirrored:  // EXIF = 7
            transform = CGAffineTransformTranslate(transform, 0, newSize.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:    // EXIF = 2
        case UIImageOrientationDownMirrored:  // EXIF = 4
            transform = CGAffineTransformTranslate(transform, newSize.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:   // EXIF = 5
        case UIImageOrientationRightMirrored:  // EXIF = 7
            transform = CGAffineTransformTranslate(transform, newSize.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }

    return transform;
}

@end


text:
module Azure::Network::Mgmt::V2020_03_01
  module Models
    #
    # Response for ServiceAssociationLinks_List operation.
    #
    class ServiceAssociationLinksListResult

      include MsRestAzure

      # @return [Array<ServiceAssociationLink>] The service association links
      # in a subnet.
      attr_accessor :value

      # @return [String] The URL to get the next set of results.
      attr_accessor :next_link

      #
      # Mapper for ServiceAssociationLinksListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ServiceAssociationLinksListResult',
          type: {
            name: 'Composite',
            class_name: 'ServiceAssociationLinksListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ServiceAssociationLinkElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ServiceAssociationLink'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import java.util.*;
import java.io.*;

public class Util
{
    public static final Vector<String> readLines (String inputFile)
    {
        /*
         * Open the data file and read it in.
         */

        BufferedReader reader = null;
        Vector<String> values = new Vector<String>();

        try
        {
            reader = new BufferedReader(new FileReader(inputFile));
            String line = null;

            while ((line = reader.readLine()) != null)
            {
                values.add(line);
            }
        }
        catch (Throwable ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                reader.close();
            }
            catch (Throwable ex)
            {
            }
        }

        return values;
    }
}


text:
{% extends "base.html" %}
{% block content %}

Login to Publications Router

		<form method="post" action="" class="form">
			<fieldset class="form__fieldset">
				<legend>
					Enter your login details to continue
				</legend>

							Email address
							<input type="text" name="username" class="input--large">

							Password
							<input type="password" name="password" class="input--large">

					<button class="btn btn--3d btn--primary" id="login" type="submit">
						Log	in
					</button>

			</fieldset>
		</form>

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright 2015 "Henry Tao <hi@henrytao.me>"
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="me.henrytao.mddemo">

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
      android:configChanges="orientation|screenSize"
      android:label="@string/app_name"
      android:name=".activity.MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity
      android:label="@string/title_activity_simple"
      android:name=".activity.SimpleActivity" />
    <activity
      android:label="@string/title_activity_theme"
      android:name=".activity.ThemeActivity"
      android:theme="@style/AppTheme.Purple" />
    <activity
      android:label="@string/title_activity_typo"
      android:name=".activity.TypoActivity"></activity>
  </application>

</manifest>


text:
package com.github.rshindo.playchat.json

import java.util.Date

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Writes}

/**
  * Created by shindo on 2016/12/18.
  */
case class Channel(channelId: Long, title: String, insertDate: Date)

object Channel {

  implicit val f = Writes.dateWrites("yyyy-MM-dd HH:mm:ss")

  implicit val channelWrites: Writes[Channel] = (
    (JsPath \ "channelId").write[Long] and
      (JsPath \ "title").write[String] and
      (JsPath \ "insertDate").format(f)
    ) (unlift(Channel.unapply))
}


text:
package com.yunhuwifi.vcard;

public interface Spanned
extends CharSequence
{
    public static final int SPAN_POINT_MARK_MASK = 0x33;

    public static final int SPAN_MARK_MARK =   0x11;

    public static final int SPAN_MARK_POINT =  0x12;

    public static final int SPAN_POINT_MARK =  0x21;

    public static final int SPAN_POINT_POINT = 0x22;

    public static final int SPAN_PARAGRAPH =   0x33;

    public static final int SPAN_INCLUSIVE_EXCLUSIVE = SPAN_MARK_MARK;

    public static final int SPAN_INCLUSIVE_INCLUSIVE = SPAN_MARK_POINT;

    public static final int SPAN_EXCLUSIVE_EXCLUSIVE = SPAN_POINT_MARK;

    public static final int SPAN_EXCLUSIVE_INCLUSIVE = SPAN_POINT_POINT;

    public static final int SPAN_COMPOSING = 0x100;

    public static final int SPAN_INTERMEDIATE = 0x200;

    public static final int SPAN_USER_SHIFT = 24;

    public static final int SPAN_USER = 0xFFFFFFFF << SPAN_USER_SHIFT;

    public static final int SPAN_PRIORITY_SHIFT = 16;

    public static final int SPAN_PRIORITY = 0xFF << SPAN_PRIORITY_SHIFT;

    public <T> T[] getSpans(int start, int end, Class<T> type);

    public int getSpanStart(Object tag);

    public int getSpanEnd(Object tag);

    public int getSpanFlags(Object tag);

    public int nextSpanTransition(int start, int limit, Class type);
}


text:
module AdminUserAuthenticable
  extend ActiveSupport::Concern

  included do
    before_action :authenticate_admin_user_from_token!
  end

  def authenticate_admin_user_from_token!
    user_token = params[:auth_token].presence
    user       = user_token && User.find_by_current_token(user_token.to_s)

    unless user && user.admin?
      raise InvalidTokenError, "Authentication token does not have admin privileges"
    end
  end
end


text:
"""Calculate isoelectric points of polypeptides using methods of Bjellqvist.

pK values and the methos are taken from::

    * Bjellqvist, B.,Hughes, G.J., Pasquali, Ch., Paquet, N., Ravier, F., Sanchez,
    J.-Ch., Frutiger, S. & Hochstrasser, D.F.
    The focusing positions of polypeptides in immobilized pH gradients can be predicted
    from their amino acid sequences. Electrophoresis 1993, 14, 1023-1031.

    * Bjellqvist, B., Basse, B., Olsen, E. and Celis, J.E.
    Reference points for comparisons of two-dimensional maps of proteins from
    different human cell types defined in a pH scale where isoelectric points correlate
    with polypeptide compositions. Electrophoresis 1994, 15, 529-539.

I designed the algorithm according to a note by David L. Tabb, available at:
http://fields.scripps.edu/DTASelect/20010710-pI-Algorithm.pdf

"""

__docformat__ = "restructuredtext en"

positive_pKs = {'Nterm': 7.5, 'K': 10.0, 'R': 12.0, 'H': 5.98}
negative_pKs = {'Cterm': 3.55, 'D': 4.05, 'E': 4.45, 'C': 9.0, 'Y': 10.0}
pKcterminal = {'D': 4.55, 'E': 4.75}
pKnterminal = {'A': 7.59, 'M': 7.0, 'S': 6.93, 'P': 8.36, 'T': 6.82, 'V': 7.44, 'E': 7.7}
charged_aas = ('K', 'R', 'H', 'D', 'E', 'C', 'Y')

# access this module through ProtParam.ProteinAnalysis class.
# first make a ProteinAnalysis object and then call its isoelectric_point method.
class IsoelectricPoint(object):
    def __init__(self, ProteinSequence, AminoAcidsContent):
        self.sequence = ProteinSequence
        self.charged_aas_content = self._select_charged(AminoAcidsContent)

    # This function creates a dictionary with the contents of each charged aa,
    # plus Cterm and Nterm.
    def _select_charged(self, AminoAcidsContent):
        charged = {}
        for aa in charged_aas:
            charged[aa] = float(AminoAcidsContent[aa])
        charged['Nterm'] = 1.0
        charged['Cterm'] = 1.0
        return charged

    # This function calculates the total charge of the protein at a given pH.
    def _chargeR(self, pH, pos_pKs, neg_pKs):
        PositiveCharge = 0.0
        for aa, pK in pos_pKs.items():
            CR = 10 ** (pK - pH)
            partial_charge = CR / (CR + 1.0)
            PositiveCharge += self.charged_aas_content[aa] * partial_charge

        NegativeCharge = 0.0
        for aa, pK in neg_pKs.items():
            CR = 10 ** (pH - pK)
            partial_charge = CR / (CR + 1.0)
            NegativeCharge += self.charged_aas_content[aa] * partial_charge

        return PositiveCharge - NegativeCharge

    # This is the action function, it tries different pH until the charge of the protein is 0 (or close).
    def pi(self):
        pos_pKs = dict(positive_pKs)
        neg_pKs = dict(negative_pKs)
        nterm = self.sequence[0]
        cterm = self.sequence[-1]
        if nterm in pKnterminal:
            pos_pKs['Nterm'] = pKnterminal[nterm]
        if cterm in pKcterminal:
            neg_pKs['Cterm'] = pKcterminal[cterm]

        # Bracket between pH1 and pH2
        pH = 7.0
        Charge = self._chargeR(pH, pos_pKs, neg_pKs)
        if Charge > 0.0:
            pH1 = pH
            Charge1 = Charge
            while Charge1 > 0.0:
                pH = pH1 + 1.0
                Charge = self._chargeR(pH, pos_pKs, neg_pKs)
                if Charge > 0.0:
                    pH1 = pH
                    Charge1 = Charge
                else:
                    pH2 = pH
                    Charge2 = Charge
                    break
        else:
            pH2 = pH
            Charge2 = Charge
            while Charge2 < 0.0:
                pH = pH2 - 1.0
                Charge = self._chargeR(pH, pos_pKs, neg_pKs)
                if Charge < 0.0:
                    pH2 = pH
                    Charge2 = Charge
                else:
                    pH1 = pH
                    Charge1 = Charge
                    break

        # Bisection
        while pH2 - pH1 > 0.0001 and Charge != 0.0:
            pH = (pH1 + pH2) / 2.0
            Charge = self._chargeR(pH, pos_pKs, neg_pKs)
            if Charge > 0.0:
                pH1 = pH
                Charge1 = Charge
            else:
                pH2 = pH
                Charge2 = Charge

        return pH


text:
const chalk = require('chalk');
const Table = require('easy-table');
const moment = require('./moment');

//  Functions
const currency = amount =>
  (amount >= 0 ? chalk.green.bold(`$${amount.toFixed(2)}`) : chalk.red.bold(`$${amount.toFixed(2)}`));
const account = a =>
  `${chalk.bold(a.name)} \t(${chalk.red(a.bsb)} ${chalk.red(a.account)})` +
  `\t Balance: ${currency(a.balance)} ` +
  `\t Available Funds: ${currency(a.available)}`;
const accounts = accs =>
  Table.print(accs.map(a => ({
    Name: chalk.bold(a.name),
    Number: `${chalk.red(a.bsb)} ${chalk.red(a.account)}`,
    Balance: `${currency(a.balance)}`,
    Available: `${currency(a.available)}`,
  })));
const transactions = ts =>
  Table.print(ts.map(t => ({
    Time: chalk.italic.cyan(moment(t.timestamp).format('YYYY-MM-DD HH:mm')),
    Description: t.pending ? chalk.gray(t.description) : chalk.white(t.description),
    Amount: currency(t.amount),
    Balance: t.pending ? '' : currency(t.balance),
  })));

module.exports = {
  currency,
  account,
  accounts,
  transactions,
};


text:
package org.apache.taverna.activities.xpath.ui.contextualview;

import java.util.Arrays;
import java.util.List;

import org.apache.taverna.activities.xpath.ui.servicedescription.XPathTemplateService;
import org.apache.taverna.servicedescriptions.ServiceDescriptionRegistry;
import org.apache.taverna.workbench.activityicons.ActivityIconManager;
import org.apache.taverna.workbench.edits.EditManager;
import org.apache.taverna.workbench.file.FileManager;
import org.apache.taverna.workbench.ui.views.contextualviews.ContextualView;
import org.apache.taverna.workbench.ui.views.contextualviews.activity.ContextualViewFactory;
import org.apache.taverna.services.ServiceRegistry;
import org.apache.taverna.scufl2.api.activity.Activity;

/**
 * @author Sergejs Aleksejevs
 */
public class XPathActivityMainContextViewFactory implements ContextualViewFactory<Activity> {

	private EditManager editManager;
	private FileManager fileManager;
	private ActivityIconManager activityIconManager;
	private ServiceDescriptionRegistry serviceDescriptionRegistry;
	private ServiceRegistry serviceRegistry;

	public boolean canHandle(Object selection) {
		return selection instanceof Activity
				&& ((Activity) selection).getType()
						.equals(XPathTemplateService.ACTIVITY_TYPE);
	}

	public List<ContextualView> getViews(Activity selection) {
		return Arrays.<ContextualView> asList(new XPathActivityMainContextualView(selection,
				editManager, fileManager, activityIconManager, serviceDescriptionRegistry,
				serviceRegistry));
	}

	public void setEditManager(EditManager editManager) {
		this.editManager = editManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	public void setActivityIconManager(ActivityIconManager activityIconManager) {
		this.activityIconManager = activityIconManager;
	}

	public void setServiceDescriptionRegistry(ServiceDescriptionRegistry serviceDescriptionRegistry) {
		this.serviceDescriptionRegistry = serviceDescriptionRegistry;
	}

	public void setServiceRegistry(ServiceRegistry serviceRegistry) {
		this.serviceRegistry = serviceRegistry;
	}

}


text:
<?php

declare(strict_types=1);

namespace Emonkak\Orm\Tests\Pagination;

use Emonkak\Orm\Pagination\AbstractPage;
use Emonkak\Orm\Pagination\PageInterface;
use PHPUnit\Framework\TestCase;

/**
 * @covers \Emonkak\Orm\Pagination\AbstractPage
 */
class AbstractPageTest extends TestCase
{
    /**
     * @dataProvider prividerGetOffset
     */
    public function testGetOffset($index, $perPage, $expectedOffset): void
    {
        $page = $this->getMockForAbstractClass(AbstractPage::class);
        $page
            ->expects($this->once())
            ->method('getIndex')
            ->willReturn($index);
        $page
            ->expects($this->once())
            ->method('getPerPage')
            ->willReturn($perPage);

        $this->assertSame($expectedOffset, $page->getOffset());
    }

    public function prividerGetOffset(): array
    {
        return [
            [0, 10, 0],
            [1, 10, 10],
            [2, 10, 20],
        ];
    }

    public function testForward(): void
    {
        $firstPage = $this->getMockForAbstractClass(AbstractPage::class);
        $secondPage = $this->createMock(PageInterface::class);
        $thirdPage = $this->createMock(PageInterface::class);

        $firstPage
            ->expects($this->once())
            ->method('hasNext')
            ->willReturn(true);
        $firstPage
            ->expects($this->once())
            ->method('next')
            ->willReturn($secondPage);

        $secondPage
            ->expects($this->once())
            ->method('hasNext')
            ->willReturn(true);
        $secondPage
            ->expects($this->once())
            ->method('next')
            ->willReturn($thirdPage);

        $thirdPage
            ->expects($this->once())
            ->method('hasNext')
            ->willReturn(false);
        $thirdPage
            ->expects($this->never())
            ->method('next');

        $this->assertSame([$firstPage, $secondPage, $thirdPage], iterator_to_array($firstPage->forward()));
    }

    public function testBackward(): void
    {
        $firstPage = $this->getMockForAbstractClass(AbstractPage::class);
        $secondPage = $this->createMock(PageInterface::class);
        $thirdPage = $this->createMock(PageInterface::class);

        $firstPage
            ->expects($this->once())
            ->method('hasPrevious')
            ->willReturn(true);
        $firstPage
            ->expects($this->once())
            ->method('previous')
            ->willReturn($secondPage);

        $secondPage
            ->expects($this->once())
            ->method('hasPrevious')
            ->willReturn(true);
        $secondPage
            ->expects($this->once())
            ->method('previous')
            ->willReturn($thirdPage);

        $thirdPage
            ->expects($this->once())
            ->method('hasPrevious')
            ->willReturn(false);
        $thirdPage
            ->expects($this->never())
            ->method('previous');

        $this->assertSame([$firstPage, $secondPage, $thirdPage], iterator_to_array($firstPage->backward()));
    }

    public function testIsFirst(): void
    {
        $page = $this->getMockForAbstractClass(AbstractPage::class);
        $page
            ->expects($this->exactly(2))
            ->method('hasPrevious')
            ->willReturnOnConsecutiveCalls(false, true);

        $this->assertTrue($page->isFirst());
        $this->assertFalse($page->isFirst());
    }

    public function testIsLast(): void
    {
        $page = $this->getMockForAbstractClass(AbstractPage::class);
        $page
            ->expects($this->exactly(2))
            ->method('hasNext')
            ->willReturnOnConsecutiveCalls(false, true);

        $this->assertTrue($page->isLast());
        $this->assertFalse($page->isLast());
    }
}


text:
package org.mybatis.generator.api.dom.java;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.core.Is.*;

public class InterfaceTest {

    @Test
    public void testConstructor() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        assertNotNull(interfaze);
    }

    @Test
    public void testAddImportedType() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        FullyQualifiedJavaType arrayList = FullyQualifiedJavaType.getNewArrayListInstance();
        interfaze.addImportedType(arrayList);

        assertNotNull(interfaze.getImportedTypes());
        assertEquals(interfaze.getImportedTypes().size(), 1);
        assertTrue(interfaze.getImportedTypes().contains(arrayList));
    }

    @Test
    public void testAddImportedTypes() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        Set<FullyQualifiedJavaType> importedTypes = new HashSet<FullyQualifiedJavaType>();

        FullyQualifiedJavaType arrayList = FullyQualifiedJavaType.getNewArrayListInstance();
        FullyQualifiedJavaType hashMap = FullyQualifiedJavaType.getNewHashMapInstance();

        importedTypes.add(arrayList);
        importedTypes.add(hashMap);
        interfaze.addImportedTypes(importedTypes);

        assertNotNull(interfaze.getImportedTypes());
        assertEquals(interfaze.getImportedTypes().size(), 2);
        assertTrue(interfaze.getImportedTypes().contains(arrayList));
        assertTrue(interfaze.getImportedTypes().contains(hashMap));
    }

    @Test
    public void testAddFileCommentLine() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        interfaze.addFileCommentLine("test");

        assertNotNull(interfaze.getFileCommentLines());
        assertEquals(interfaze.getFileCommentLines().size(), 1);
        assertEquals(interfaze.getFileCommentLines().get(0), "test");
    }

    @Test
    public void testAddStaticImport() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        interfaze.addStaticImport("com.foo.StaticUtil");

        assertNotNull(interfaze.getStaticImports());
        assertEquals(interfaze.getStaticImports().size(), 1);
        assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil"));
    }

    @Test
    public void testAddStaticImports() {

        Interface interfaze = new Interface("com.foo.UserInterface");
        Set<String> staticImports = new HashSet<String>();
        staticImports.add("com.foo.StaticUtil1");
        staticImports.add("com.foo.StaticUtil2");
        interfaze.addStaticImports(staticImports);

        assertNotNull(interfaze.getStaticImports());
        assertEquals(interfaze.getStaticImports().size(), 2);
        assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil1"));
        assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil2"));
    }

    @Test
    public void testInterfaceFields() {
        Interface interfaze = new Interface("foo.Bar");
        interfaze.setVisibility(JavaVisibility.PUBLIC);

        Field field = new Field("EMPTY_STRING", FullyQualifiedJavaType.getStringInstance());
        field.setInitializationString("\"\"");
        interfaze.addField(field);

        field = new Field("ONE", FullyQualifiedJavaType.getStringInstance());
        field.setInitializationString("\"one\"");
        interfaze.addField(field);

        String expected = "package foo;" + System.lineSeparator()
            + System.lineSeparator()
            + "public interface Bar {" + System.lineSeparator()
            + "    String EMPTY_STRING = \"\";" + System.lineSeparator()
            + "    String ONE = \"one\";" + System.lineSeparator()
            + "}";

        assertThat(interfaze.getFormattedContent(), is(expected));
    }
}


text:
package it.polimi.tower4clouds.rules.actions;

import it.polimi.modaclouds.qos_models.EnumErrorType;
import it.polimi.modaclouds.qos_models.Problem;
import it.polimi.tower4clouds.rules.AbstractAction;
import it.polimi.tower4clouds.rules.Action;
import it.polimi.tower4clouds.rules.MonitoringRule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class OutputMetric extends AbstractAction {

	public static final String metric = "metric";
	public static final String resourceId = "resourceId";
	public static final String value = "value";

	private final Set<String> requiredParameters = new HashSet<String>();
	private final Map<String, String> defaultParameterValues = new HashMap<String, String>();

	public OutputMetric() {
		requiredParameters.add(metric);
		defaultParameterValues.put(resourceId, "ID");
		defaultParameterValues.put(value, "METRIC");
	}

	@Override
	protected Set<String> getMyRequiredPars() {
		return requiredParameters;
	}

	@Override
	protected Map<String, String> getMyDefaultParameterValues() {
		return defaultParameterValues;
	}

	@Override
	protected Set<Problem> validate(MonitoringRule rule,
			List<MonitoringRule> otherRules) {
		Set<Problem> problems = new HashSet<Problem>();
		List<String> metrics = getOutputMetrics(rule);
		if (!findDuplicates(metrics).isEmpty()) {
			problems.add(new Problem(rule.getId(),
					EnumErrorType.INVALID_ACTION, getName(),
					"Metrics name can only be used once"));
		}
		if (otherRules != null) {
			for (MonitoringRule otherRule : otherRules) {
				for (String metric : metrics) {
					if (getOutputMetrics(otherRule).contains(metric)) {
						problems.add(new Problem(rule.getId(),
								EnumErrorType.INVALID_ACTION, getName(),
								"Metric " + metric
										+ " is already generated by rule "
										+ otherRule.getId()));
					}
				}
			}
		}
		return problems;
	}

	private List<String> getOutputMetrics(MonitoringRule rule) {
		List<String> metrics = new ArrayList<String>();
		Set<Action> actions = getMyActions(rule);
		for (Action action : actions) {
			metrics.add(extractParameters(action).get(metric));
		}
		return metrics;
	}

	private static Set<String> findDuplicates(List<String> list) {

		final Set<String> duplicates = new HashSet<String>();
		final Set<String> set1 = new HashSet<String>();

		for (String yourInt : list) {
			if (!set1.add(yourInt)) {
				duplicates.add(yourInt);
			}
		}
		return duplicates;
	}

	@Override
	public void execute(String resourceId, String value, String timestamp) {
		// Nothing to do. This is a special action, nothing is sent to the
		// manager, the metric is just made available at the data analyzer
		// endpoint. When attaching observers to metrics, metrics are sent
		// directly to the observer by the data analyzer.
	}

}


text:
<?php

namespace SSE\ICSSBundle\DependencyInjection;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class DynamicContentMarker
{
    /** @var Request */
    protected $request;

    public function setRequest(RequestStack $request_stack)
    {
        $this->request = $request_stack->getCurrentRequest();
    }

    public function isAjax()
    {
        return $this->request->isXmlHttpRequest();
    }
}


text:
<!doctype html><title>Minimal tQuery Page</title>
<script src="../../../build/tquery-bundle-require.js"></script>
<body><script>
require([ 'tquery.tween'
	, 'tquery.blueskybackground'
	, 'tquery.skymap'
], function(){
	var world	= tQuery.createWorld().boilerplate().start();
	var object	= tQuery.createTorus().addTo(world)

	// put the camera a little further
	world.camera().positionZ( 4 );
	// limit camera range
	world.getCameraControls().rangeX	*= 0.05;
	world.getCameraControls().rangeY	*= 0.05;

	// put a blue sky in the background
	world.tRenderer().setClearColor(0x000000, 0)
	tQuery.addBlueSkyBackground();
	// add a skymap
	tQuery.createSkymap('skybox').addTo(world);

	///////////////////////////////////////////////////////////////////////
	// here start the particles
	var texture	= THREE.ImageUtils.loadTexture('../images/cloud10.png')
	var center	= tQuery.createVector3(0, -1.5, -6)
	var range	= tQuery.createVector3(20,0.2, 16)
	var rangeCluster= tQuery.createVector3(4, 0.1, 2)
	var material	= tQuery.createSpriteMaterial()
				.map(texture)
				.color('lightgrey')
	var nClusters	= 30
	for(var i = 0; i < nClusters; i++){
		var container	= tQuery.createObject3D().addTo(world)
			.positionX(center.x + (Math.random()-0.5)*range.x )
			.positionY(center.y + (Math.random()-0.5)*range.y )
			.positionZ(center.z + (Math.random()-0.5)*range.z )
		var nClouds	= 2 + Math.floor( 3*Math.random() )
		for(var j = 0; j < nClouds; j++){
			var sprite	= tQuery.createSprite(material).addTo(container)
				.positionX( (Math.random()-0.5)*rangeCluster.x )
				.positionY( (Math.random()-0.5)*rangeCluster.y )
				.positionZ( (Math.random()-0.5)*rangeCluster.z )
				.rotation(Math.random() * Math.PI*2)
				.scale(4 + (Math.random()-0.5)*1 )
		}
	}
});
</script></body>


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    LLDS01 - MembersList
    <protected>true</protected>
    <values>
        <field>Apex_Class_Name__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>CompanyNameText__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>ContinueButtonText__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>CustomView__c</field>
        <value xsi:type="xsd:boolean">false</value>
    </values>
    <values>
        <field>Display_Text_1__c</field>
        <value xsi:type="xsd:string">

The directors listed on the public register for COMPANYNAME is:

</value>
    </values>
    <values>
        <field>Display_Text_2__c</field>
        <value xsi:type="xsd:string">

The directors listed on the public register for COMPANYNAME are:

</value>
    </values>
    <values>
        <field>Display_Text_3__c</field>
        <value xsi:type="xsd:string">
There are no current members for this LLP according to our records. You must register the appointments before requesting to close the LLP.
</value>
    </values>
    <values>
        <field>Display_Text_4__c</field>
        <value xsi:type="xsd:string">
The number of members exceeds the maximum that this private beta permits. Please contact Companies House for advice.
</value>
    </values>
    <values>
        <field>Display_Text_5__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Display_Text_6__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Document_Template_Name__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Header_Text_1__c</field>
        <value xsi:type="xsd:string">

Confirm the LLP directors
</value>
    </values>
    <values>
        <field>Header_Text_2__c</field>
        <value xsi:type="xsd:string">

Appoint company members
</value>
    </values>
    <values>
        <field>Header_Text_3__c</field>
        <value xsi:type="xsd:string">

Limit exceeded
</value>
    </values>
    <values>
        <field>Header_Text_4__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Is_Active__c</field>
        <value xsi:type="xsd:boolean">false</value>
    </values>
    <values>
        <field>Persist_FieldSet_1_Name__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Query_FieldSet_1_Name__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>SObject_Type__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>StandardView__c</field>
        <value xsi:type="xsd:boolean">false</value>
    </values>
    <values>
        <field>Step_Number__c</field>
        <value xsi:nil="true"/>
    </values>
    <values>
        <field>Step_Type__c</field>
        <value xsi:type="xsd:string">VF Page</value>
    </values>
    <values>
        <field>Transaction_Type__c</field>
        <value xsi:type="xsd:string">LLDS01</value>
    </values>
    <values>
        <field>Visualforce_Page_Name__c</field>
        <value xsi:type="xsd:string">DirectorsList</value>
    </values>
    <values>
        <field>previousButtonText__c</field>
        <value xsi:type="xsd:string">Back</value>
    </values>
</CustomMetadata>


text:
package pl.touk.nussknacker.engine.canonize

import cats.Applicative
import cats.data.{NonEmptyList, ValidatedNel}
import pl.touk.nussknacker.engine.graph.node
import pl.touk.nussknacker.engine.graph.sink.SinkRef
import pl.touk.nussknacker.engine.graph.source.SourceRef

// todo: this is basically a Writer; we should approach it differently?
private[engine] class MaybeArtificial[A](private val value: A, private val errors: List[ProcessUncanonizationError]) {
  def map[B](f: A => B): MaybeArtificial[B] = new MaybeArtificial(f(value), errors)

  def flatMap[B](f: A => MaybeArtificial[B]): MaybeArtificial[B] = {
    val result = f(value)
    new MaybeArtificial[B](result.value, errors ++ result.errors)
  }

  def toValidNel(implicit extractor: MaybeArtificialExtractor[A]): ValidatedNel[ProcessUncanonizationError, A] = {
    import cats.syntax.validated._
    errors match {
      case h :: hs => NonEmptyList.of(h, hs: _*).invalid[A]
      case _ => extract.validNel
    }
  }

  def extract(implicit extractor: MaybeArtificialExtractor[A]): A = extractor.get(errors, value)
}

private[engine] object MaybeArtificial {
  val DummyObjectName = "dummy"

  implicit val applicative: Applicative[MaybeArtificial] = new Applicative[MaybeArtificial] {
    override def pure[A](x: A): MaybeArtificial[A] = new MaybeArtificial(x, Nil)

    override def ap[A, B](ff: MaybeArtificial[A => B])(fa: MaybeArtificial[A]): MaybeArtificial[B] = {
      new MaybeArtificial(ff.value(fa.value), fa.errors ++ ff.errors)
    }
  }

  def artificialSink(errors: ProcessUncanonizationError*): MaybeArtificial[node.SubsequentNode] =
    new MaybeArtificial(node.EndingNode(node.Sink(DummyObjectName, SinkRef(DummyObjectName, Nil), None)), errors.toList)

  def artificialSource(errors: ProcessUncanonizationError*): MaybeArtificial[node.SourceNode] =
    artificialSink(errors: _*).map(node.SourceNode(node.Source(DummyObjectName, SourceRef(DummyObjectName, Nil)), _))
}


text:
% Source: https://blogs.wsj.com/puzzle/2010/10/29/marching-bands-saturday-puzzle-2/
% Original by Mike Shenk.

\puzzle{WSJ Puzzle~2 (2010-10-30)}{%
  \item
    \begin{itemize}
      \item
        Halloween mischief-maker
      \item
        Honey
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Does a poltergeist's work
      \item
        Lock of Medusa's hair
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Legend in his own mind
      \item
        City at the foot of the Sierra Nevada
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Thankless bunch
      \item
        Witches, usually
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Seeks, politically (2~wds.)
      \item
        Mathematician who helped crack the Enigma machine codes
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Like arcade games (Hyph.)
      \item
        Celeb's manager
    \end{itemize}
  \item
    \begin{itemize}
      \item
        First family of~1842
      \item
        Maker of Butterfingers and Baby Ruths
    \end{itemize}
  \item
    \begin{itemize}
      \item
        It'll help you walk tall
      \item
        Droid producer
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Ready for action (2~wds.)
      \item
        ``You can count on me!'' (3~wds.)
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Triangular part of a skeleton
      \item
        Bit of haunted house decor
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Prowler during the full moon
      \item
        Spitting mammal
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Cruel monsters
      \item
        Hard cider and the like
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Malory's ``\blank\ d'Arthur'' (2~wds.)
      \item
        Pressed sandwich
    \end{itemize}
}{%
  \item
    \begin{itemize}
      \item
        React like Peeping Tom in the Godiva legend (2~wds.)
      \item
        County with a famous cemetery
      \item
        Desert region west of the Rockies (2~wds.)
      \item
        Sulky (3~wds.)
      \item
        Spanish Steps setting
      \item
        Area below the opponent's basket (2~wds.)
      \item
        Screams
    \end{itemize}
  \item
    \begin{itemize}
      \item
        One offering loving touches
      \item
        Tubular pasta
      \item
        Famed Covent Garden star (2~wds.)
      \item
        Military officer slangily called a ``first shirt'' (2~wds.)
      \item
        Like Brooks's Frankenstein
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Man from Muscat
      \item
        Pumpkin patch measure
      \item
        Chocolate pioneer Hershey
      \item
        One sidelined by shyness
      \item
        Shadow's activity
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Bank quote
      \item
        Dragon-slaying tools
      \item
        Telemarketing annoyance
      \item
        Page and Burstyn
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Crystal gazer's offering
      \item
        Do away with
      \item
        Fashionably nostalgic
    \end{itemize}
  \item
    \begin{itemize}
      \item
        Apparitions
    \end{itemize}
}{%
  \puzzlerow GOBLINDARLING;
  \puzzlerow SCARESSERPENT;
  \puzzlerow EGOMANIACRENO;
  \puzzlerow INGRATESWOMEN;
  \puzzlerow RUNSFORTURING;
  \puzzlerow COINOPHANDLER;
  \puzzlerow TYLERS.NESTLE;
  \puzzlerow STILTMOTOROLA;
  \puzzlerow ONALERTIMONIT;
  \puzzlerow PATELLACOBWEB;
  \puzzlerow WEREWOLFLLAMA;
  \puzzlerow OGRESPOTABLES;
  \puzzlerow LEMORTEPANINI;
}


text:
namespace XS {

	namespace ClientGame {

		static Renderer::View *sceneView = nullptr;
		static constexpr size_t dimensions[2] = { 32u, 18u };

		// each tile acts as a node in the graph to search
		// a tile has a specific type (e.g. start, goal, wall)
		// the only identifying property of a tile is the position, which is inferred by the tilemap

		// references for A* pathfinding:
		//	https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode
		//	http://www.policyalmanac.org/games/aStarTutorial.htm
		//	http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
		//	http://code.activestate.com/recipes/577457-a-star-shortest-path-algorithm/

		enum class TileType {
			Blank,
			Wall,
			Start,
			Goal
		};

		enum Direction {
			NorthWest,
			North,
			NorthEast,
			East,
			SouthEast,
			South,
			SouthWest,
			West,
			NUM_DIRECTIONS
		};

		struct Tile {
			int32_t		x, y;

			// a cost of -1 means it is an unmoveable direction (i.e. off the map)
			// the lower the cost, the better the move
			int16_t		cost[NUM_DIRECTIONS];
			Tile		*neighbours[NUM_DIRECTIONS];
			TileType	type;

			// the only unique element for a tile is the coordinate, so use this for comparison
			inline bool operator==( const Tile &rhs ) const {
				if ( x == rhs.x && y == rhs.y ) {
					return true;
				}
				return false;
			}
		};
		typedef std::vector<Tile *> nodeList;

		struct Path {
			enum class Algorithm {
				AStar,
				DStar, //TODO
				Dijkstra, //TODO
				BFS, //TODO
			};

			// tiles are added to the open list if it's to be explored
			// when a tile is determined to be unsuitable, it's moved to the closed list and never checked again
			nodeList				openList, closedList;
			nodeList				result;
			std::map<Tile*, Tile*>	cameFrom;
			Algorithm				algorithm;

			// calculate the H cost of moving from t1 to t2
			int16_t HeuristicCost(
				const Tile *t1,
				const Tile *t2
			);

			// we've reached the goal, so backtrack to the start node and return that path
			void Backtrack(
				Tile *tile,
				nodeList &route
			);

			// construct a path from current tile to goal tile
			bool Find(
				Tile *current,
				Tile *goal,
				nodeList &route
			);
		};

		static struct GameState {
			Tile							 tiles[dimensions[0]][dimensions[1]];
			Path							 path;
			nodeList						 route;
			Tile							*start, *goal;
			std::map<const Tile*, int16_t>	 fScore;
			std::map<const Tile*, int16_t>	 gScore;
		} state = {};

		static Tile *GetTile( uint32_t x, uint32_t y ) {
			if ( x < dimensions[0] && y < dimensions[1] ) {
				return &state.tiles[x][y];
			}
			return nullptr;
		}

		static TileType GetTileType( uint32_t x, uint32_t y ) {
			return state.tiles[x][y].type;
		}

		int16_t Path::HeuristicCost( const Tile *t1, const Tile *t2 ) {
			switch( algorithm ) {

				case Algorithm::AStar: {
					Tile delta = {
						.x = std::abs( t2->x - t1->x ),
						.y = std::abs( t2->y - t1->y )
					};

					// euclidean distance
					//	* by 8 to alleviate lack of integer precision
					//return static_cast<int16_t>( sqrt( delta.x*delta.x + delta.y*delta.y ) * 8 );

					// custom
					//	abuse integer truncation to add negative weight to diagonal moves
					return static_cast<int16_t>( delta.x * 1.5f ) + static_cast<int16_t>( delta.y * 1.5f );
				} break;

				default: {
					//TODO: handle other algo's
					return 0;
				} break;

			}

			return 0;
		}

		void Path::Backtrack( Tile *tile, nodeList &route ) {
			//TODO: backtrack from the goal position to the start position based on which order we traversed the
			//	nodes
			while ( tile ) {
				route.insert( route.begin(), tile );
				tile = cameFrom[tile];
			}
			//TODO: smooth the path
		}

		bool Path::Find( Tile *current, Tile *goal, nodeList &route ) {
			bool finished = false;

			switch( algorithm ) {

				case Algorithm::AStar: {
					if ( !openList.empty() ) {
						int16_t lowestF = INT16_MAX;

						// current = node in open list with lowest f score
						// F=G+H
						for ( Tile *tile : openList ) {
							int16_t thisG = 0;
							int16_t thisH = HeuristicCost( tile, goal );
							int16_t thisF = thisG + thisH;
							if ( thisF < lowestF ) {
								lowestF = thisF;
								current = tile;
							}
						}

						// wut?
						if ( current == goal ) {
							//openList.clear();
							Backtrack( current, route );
							finished = true;
							break;
						}

						// drop it from the openList, add it to the closedList
						auto it = std::find( openList.begin(), openList.end(), current );
						if ( it != openList.end() ) {
							openList.erase( it );
							closedList.push_back( current );
						}

						// then look at its neighbours
						for ( Tile *neighbour : current->neighbours ) {
							if ( neighbour == nullptr ) {
								continue;
							}

							// only add tiles we can navigate to.
							if ( neighbour->type == TileType::Wall ) {
								continue;
							}

							// if this neighbour is in the closedList, skip it
							if ( std::find( closedList.begin(), closedList.end(), neighbour ) != closedList.end() ) {
								continue;
							}
							int16_t score = state.gScore[current] + HeuristicCost( current, neighbour );

							// if this neighbour is not in the openList, or if it has a lower score, mark it for
							//	 traversal
							if ( std::find( openList.begin(), openList.end(), neighbour ) == openList.end()
								|| score < state.gScore[neighbour] )
							{
								cameFrom[neighbour] = current;
								state.gScore[neighbour] = score;
								state.fScore[neighbour] = state.gScore[neighbour] + HeuristicCost( neighbour, goal );
								// if neighbour is not in the open set
								if ( std::find( openList.begin(), openList.end(), neighbour ) == openList.end() ) {
									openList.push_back( neighbour );
									openList = std::vector<Tile *>( openList.begin(), openList.end() );
								}
							}
						}
					}
				} break;

				default: {
					//TODO: handle other algo's
				} break;

			}

			return finished;
		}

		static void RenderScene( void ) {
			// the view is already bound
		}

		static void GenerateMaze( void ) {
			// initialise the tiles
			for ( size_t x = 0u; x < dimensions[0]; x++ ) {
				for ( size_t y = 0u; y < dimensions[1]; y++ ) {
					state.tiles[x][y].x = x;
					state.tiles[x][y].y = y;
					state.tiles[x][y].type = TileType::Blank;

					state.tiles[x][y].neighbours[NorthWest]	= GetTile( x - 1, y - 1 );
					state.tiles[x][y].neighbours[North]		= GetTile( x    , y - 1 );
					state.tiles[x][y].neighbours[NorthEast]	= GetTile( x + 1, y - 1 );
					state.tiles[x][y].neighbours[East]			= GetTile( x + 1, y     );
					state.tiles[x][y].neighbours[SouthEast]	= GetTile( x + 1, y + 1 );
					state.tiles[x][y].neighbours[South]		= GetTile( x    , y + 1 );
					state.tiles[x][y].neighbours[SouthWest]	= GetTile( x - 1, y + 1 );
					state.tiles[x][y].neighbours[West]			= GetTile( x - 1, y     );
				}
			}

			// surround the map in a box
			for ( size_t x = 0u; x < dimensions[0]; x++ ) {
				state.tiles[x][0].type = TileType::Wall;
				state.tiles[x][dimensions[1] - 1].type = TileType::Wall;
			}
			for ( size_t y = 0u; y < dimensions[1]; y++ ) {
				state.tiles[0][y].type = TileType::Wall;
				state.tiles[dimensions[0] - 1][y].type = TileType::Wall;
			}

			// randomly place the start position with 2 cell padding
			int32_t startX = 0u;
			int32_t startY = 0u;
			while ( true ) {
				startX = 1 + (rand() % (dimensions[0] - 1));
				startY = 1 + (rand() % (dimensions[1] - 1));
				if ( startX < 3 || startX >= dimensions[0] - 3 ) {
					continue;
				}
				if ( startY < 3 || startY >= dimensions[1] - 3 ) {
					continue;
				}
				if ( GetTileType( startX, startY ) == TileType::Blank ) {
					break;
				}
			}
			state.tiles[startX][startY].type = TileType::Start;
			state.start = GetTile( startX, startY );

			// randomly surround the start tile
			int32_t side = rand() % 4;
			state.start->neighbours[NorthWest]->type	= TileType::Wall;
			state.start->neighbours[North    ]->type	= (side == 0) ? TileType::Blank : TileType::Wall;
			state.start->neighbours[NorthEast]->type	= TileType::Wall;
			state.start->neighbours[East     ]->type	= (side == 1) ? TileType::Blank : TileType::Wall;
			state.start->neighbours[SouthEast]->type	= TileType::Wall;
			state.start->neighbours[South    ]->type	= (side == 2) ? TileType::Blank : TileType::Wall;
			state.start->neighbours[SouthWest]->type	= TileType::Wall;
			state.start->neighbours[West     ]->type	= (side == 3) ? TileType::Blank : TileType::Wall;

			// randomly place the end position with 2 cell padding, at-least 3 cells away from the start
			int32_t goalX = 0u;
			int32_t goalY = 0u;
			while ( true ) {
				goalX = 1 + (rand() % (dimensions[0] - 1));
				goalY = 1 + (rand() % (dimensions[1] - 1));
				if ( goalX < 3 || goalX >= dimensions[0] - 3 ) {
					continue;
				}
				if ( goalY < 3 || goalY >= dimensions[1] - 3 ) {
					continue;
				}
				if ( std::abs( goalX - startX ) + std::abs( goalY - startY ) < 6 ) {
					continue;
				}
				if ( GetTileType( goalX, goalY ) == TileType::Blank ) {
					break;
				}

			}
			state.tiles[goalX][goalY].type = TileType::Goal;
			state.goal = GetTile( goalX, goalY );

			// randomly surround the goal tiles
			side = rand() % 4;
			state.goal->neighbours[NorthWest]->type	= TileType::Wall;
			state.goal->neighbours[North    ]->type	= (side == 0) ? TileType::Blank : TileType::Wall;
			state.goal->neighbours[NorthEast]->type	= TileType::Wall;
			state.goal->neighbours[East     ]->type	= (side == 1) ? TileType::Blank : TileType::Wall;
			state.goal->neighbours[SouthEast]->type	= TileType::Wall;
			state.goal->neighbours[South    ]->type	= (side == 2) ? TileType::Blank : TileType::Wall;
			state.goal->neighbours[SouthWest]->type	= TileType::Wall;
			state.goal->neighbours[West     ]->type	= (side == 3) ? TileType::Blank : TileType::Wall;

			//TODO: continuously branch off randomly from the surrounding walls using a weighted flood-fill?
			//	5 iterations?
		}

		void Init( void ) {
			const uint32_t width = Cvar::Get( "vid_width" )->GetInt();
			const uint32_t height = Cvar::Get( "vid_height" )->GetInt();
			sceneView = new Renderer::View( width, height, RenderScene );

			GenerateMaze();
			state.path.algorithm = Path::Algorithm::AStar;
			state.path.closedList.clear();
			// populate the open list with the start position
			state.path.openList.push_back( state.start );
			state.path.cameFrom.clear();

			state.gScore[state.start] = 0;
			state.fScore[state.start] = state.gScore[state.start]
				+ state.path.HeuristicCost( state.start, state.goal );
		}

		void RunFrame( void ) {
			static double lastTime = 0.0;
			const double currentTime = Client::GetElapsedTime();
			if ( lastTime < currentTime - 150 ) {
				// step every 150ms
				state.path.Find( state.start, state.goal, state.route );
				lastTime = currentTime;
			}
		}

		void DrawFrame( void ) {
			sceneView->Bind();

			const uint32_t screenWidth = Cvar::Get( "vid_width" )->GetInt();
			const uint32_t screenHeight = Cvar::Get( "vid_height" )->GetInt();

			const real32_t tileWidth = screenWidth / dimensions[0];
			const real32_t tileHeight = screenHeight / dimensions[1];

			for ( size_t x = 0u; x < dimensions[0]; x++ ) {
				for ( size_t y = 0u; y < dimensions[1]; y++ ) {
					const Tile *tile = GetTile( x, y );
					const vector4 *colour = nullptr;
					switch( tile->type ) {

					case TileType::Blank: {
						if ( std::find( state.path.openList.begin(), state.path.openList.end(), tile )
							!= state.path.openList.end() )
						{
							colour = &colourTable[ColourIndex( COLOUR_YELLOW )];
						}
						if ( std::find( state.path.closedList.begin(), state.path.closedList.end(), tile )
							!= state.path.closedList.end() )
						{
							colour = &colourTable[ColourIndex( COLOUR_ORANGE )];
						}
						if ( std::find( state.route.begin(), state.route.end(), tile ) != state.route.end() ) {
							colour = &colourTable[ColourIndex( COLOUR_BLUE )];
						}
					} break;

					case TileType::Wall: {
						colour = &colourTable[ColourIndex( COLOUR_GREY )];
					} break;

					case TileType::Start: {
						colour = &colourTable[ColourIndex( COLOUR_GREEN )];
					} break;

					case TileType::Goal: {
						colour = &colourTable[ColourIndex( COLOUR_RED )];
					} break;

					}

					Renderer::DrawQuad(
						(x * tileWidth) + 1.0f,
						(y * tileHeight) + 1.0f,
						tileWidth - 2.0f,
						tileHeight - 2.0f,
						0.0f, 0.0f, 1.0f, 1.0f, colour, nullptr );
				}
			}
		}

	} // namespace ClientGame

} // namespace XS


text: Dies ist ein Test-Projekt für Git


text:
import { EditorialFeaturesProps } from "Components/Publishing/EditorialFeature/EditorialFeature"
import { Vanguard2019Fixture } from "Components/Publishing/EditorialFeature/Fixtures/Vanguard2019"
import { Nav } from "Components/Publishing/Nav/Nav"
import { ArticleData } from "Components/Publishing/Typings"
import { mount } from "enzyme"
import React from "react"
import renderer from "react-test-renderer"
import { VanguardArtistWrapper } from "../Components/ArtistWrapper"
import { VanguardIntroduction } from "../Components/Introduction"
import { VanguardSeriesWrapper } from "../Components/SeriesWrapper"
import {
  SeriesContainer as TocSeriesContainer,
  VanguardTableOfContents,
} from "../Components/TableOfContents"
import { Vanguard2019 } from "../index"

jest.mock(
  "Components/Publishing/Sections/FullscreenViewer/withFullScreen",
  () => ({
    withFullScreen: x => x,
  })
)

describe("Vanguard2019", () => {
  let props: EditorialFeaturesProps
  const getWrapper = (passedProps = props) => {
    return mount(<Vanguard2019 {...passedProps} />)
  }

  beforeEach(() => {
    props = {
      article: Vanguard2019Fixture as ArticleData,
      isTest: true,
    }
  })

  describe("Snapshots", () => {
    it("renders article series snapshot properly", () => {
      const snapshot = renderer.create(<Vanguard2019 {...props} />).toJSON()
      expect(snapshot).toMatchSnapshot()
    })
  })

  describe("Rendering", () => {
    it("Renders nav", () => {
      const component = getWrapper()
      expect(component.find(Nav).length).toBe(1)
    })

    it("Renders Introduction", () => {
      const component = getWrapper()
      expect(component.find(VanguardIntroduction).length).toBe(1)
    })

    it("Renders TableOfContents", () => {
      const component = getWrapper()
      expect(component.find(VanguardTableOfContents).length).toBe(1)
    })

    it("Renders series articles", () => {
      const component = getWrapper()
      expect(component.find(VanguardSeriesWrapper).length).toBe(3)
    })

    it("Renders artist articles", () => {
      const component = getWrapper()
      expect(component.find(VanguardArtistWrapper).length).toBe(50)
    })
  })

  it("#componentDidMount sets valid slugs and adds scroll listener", () => {
    window.addEventListener = jest.fn()
    const instance = getWrapper().instance() as Vanguard2019
    instance.getValidPaths = jest.fn()
    instance.onChangeSection = jest.fn()
    instance.componentDidMount()

    expect(instance.getValidPaths).toBeCalled()
    expect(window.addEventListener).toBeCalled()
    // FIXME: unable to get equality on bound listener value
  })

  it("#componentWillUnmount removes scroll listener", () => {
    window.removeEventListener = jest.fn()
    const instance = getWrapper().instance() as Vanguard2019
    instance.componentWillUnmount()

    expect(window.removeEventListener).toHaveBeenCalledWith(
      "load",
      instance.handleScrollOnLoad
    )
  })

  describe("#handleScrollOnLoad", () => {
    it("Changes sections and replaces location if valid slug", () => {
      window.history.pushState({}, "", "/series/artsy-vanguard-2019/emerging")
      window.history.replaceState = jest.fn()
      const instance = getWrapper().instance() as Vanguard2019
      instance.onChangeSection = jest.fn()
      instance.handleScrollOnLoad()

      expect(instance.onChangeSection).toBeCalledWith("emerging")
      expect(window.history.replaceState).toBeCalledWith(
        {},
        "",
        "/series/artsy-vanguard-2019"
      )
    })

    it("Removes invalid slug if present", () => {
      window.history.pushState({}, "", "/series/artsy-vanguard-2019/foo")
      window.history.replaceState = jest.fn()
      const instance = getWrapper().instance() as Vanguard2019
      instance.onChangeSection = jest.fn()
      instance.handleScrollOnLoad()

      expect(instance.onChangeSection).not.toBeCalled()
      expect(window.history.replaceState).toBeCalledWith(
        {},
        "",
        "/series/artsy-vanguard-2019"
      )
    })
  })

  it("#getValidPaths creates an array of valid slugs", () => {
    const instance = getWrapper().instance() as Vanguard2019
    expect(instance.validSlugs).toEqual([
      "emerging",
      "victoria-sin",
      "monira-al-qadiri",
      "diedrick-brackens",
      "dineo-seshee-bopape",
      "martine-gutierrez",
      "genesis-belanger",
      "tao-hui",
      "jordan-nassar",
      "geng-xue",
      "meriem-bennani",
      "manuel-solano",
      "lauren-halsey",
      "derek-fordjour",
      "alia-farid",
      "gala-porras-kim",
      "jonathan-lyndon-chase",
      "elle-perez",
      "suki-seokyeong-kang",
      "evelyn-taocheng-wang",
      "jill-mulleady",
      "newly-established",
      "michael-armitage",
      "ebony-g-patterson",
      "lawrence-abu-hamdan",
      "korakrit-arunanondchai",
      "barbara-wagner-benjamin-de-burca",
      "charlotte-prodger",
      "jeffrey-gibson",
      "hao-liang",
      "jacolby-satterwhite",
      "melike-kara",
      "cui-jie",
      "firelei-baez",
      "forensic-architecture",
      "tschabalala-self",
      "harold-ancart",
      "getting-their-due",
      "frank-bowling",
      "zilia-sanchez",
      "fred-eversley",
      "tishan-hsu",
      "howardena-pindell",
      "diane-simpson",
      "lorraine-o-grady",
      "teresa-burga",
      "siah-armajani",
      "mcarthur-binion",
      "beatriz-gonzalez",
      "simone-fattal",
      "vivian-suter",
      "henry-taylor",
      "anna-maria-maiolino",
    ])
  })

  it("#onChangeSection scrolls to section", () => {
    const scrollIntoView = jest.fn()
    const getElementById = jest.fn().mockReturnValue({
      scrollIntoView,
    })
    document.getElementById = getElementById
    const component = getWrapper()
    component
      .find(TocSeriesContainer)
      .at(0)
      .simulate("click")
    expect(getElementById).toBeCalledWith("emerging")
    expect(scrollIntoView).toBeCalled()
  })
})


text:
#ifndef TRANSIENT_STATISTICS_3D_HH
#define TRANSIENT_STATISTICS_3D_HH

#include "core/array.h"
#include "core/globalDefs.h"
#include "core/geometry3D.h"
#include "atomicBlock/dataProcessingFunctional3D.h"
#include "dataProcessors/dataAnalysisFunctional3D.h"
#include "dataProcessors/dataAnalysisWrapper3D.h"
#include "multiBlock/multiBlock3D.h"
#include "multiBlock/multiBlockLattice3D.h"
#include "multiBlock/multiDataField3D.h"
#include "multiBlock/multiDataProcessorWrapper3D.h"
#include "io/imageWriter.h"
#include "io/plbFiles.h"
#include "io/vtkDataOutput.h"
#include "io/transientStatistics3D.h"

#include <algorithm>
#include <cstring>
#include <string>
#include <vector>

namespace plb {

/* ***************** Transient Statistics Manager ************************* */

template<typename T, template<typename U> class Descriptor>
TransientStatistics3D<T,Descriptor>::TransientStatistics3D(MultiBlockLattice3D<T,Descriptor>& lattice_, Box3D const& domain_)
    : lattice(lattice_)
{
#ifdef PLB_DEBUG
    bool intersectsWithSimulationDomain =
#endif
        intersect(domain_, lattice.getBoundingBox(), domain);
    PLB_ASSERT(intersectsWithSimulationDomain);
    enlargedDomain = domain;
    n = 0;
    isInitialized = 0;
    (void) memset(fieldIsRegistered, 0, sizeof fieldIsRegistered);
    (void) memset(fieldOperationIsRegistered, 0, sizeof fieldOperationIsRegistered);
    (void) memset(blocks, 0, sizeof blocks);
}

template<typename T, template<typename U> class Descriptor>
TransientStatistics3D<T,Descriptor>::TransientStatistics3D(TransientStatistics3D<T,Descriptor> const& rhs)
    : lattice(rhs.lattice),
      domain(rhs.domain),
      enlargedDomain(rhs.enlargedDomain),
      n(rhs.n),
      isInitialized(rhs.isInitialized)
{
    for (int iField = 0; iField < numFields; iField++) {
        fieldIsRegistered[iField] = rhs.fieldIsRegistered[iField];
    }

    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            fieldOperationIsRegistered[iField][iOperation] = rhs.fieldOperationIsRegistered[iField][iOperation];
        }
    }

    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            blocks[iField][iOperation] = 0;
            if (rhs.blocks[iField][iOperation] != 0) {
                blocks[iField][iOperation] = rhs.blocks[iField][iOperation]->clone();
            }
        }
    }
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::swap(TransientStatistics3D<T,Descriptor>& rhs)
{
    std::swap(lattice, rhs.lattice);
    std::swap(domain, rhs.domain);
    std::swap(enlargedDomain, rhs.enlargedDomain);
    std::swap(n, rhs.n);
    std::swap(isInitialized, rhs.isInitialized);

    for (int iField = 0; iField < numFields; iField++) {
        std::swap(fieldIsRegistered[iField], rhs.fieldIsRegistered[iField]);
    }

    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            std::swap(fieldOperationIsRegistered[iField][iOperation], rhs.fieldOperationIsRegistered[iField][iOperation]);
        }
    }

    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            std::swap(blocks[iField][iOperation], rhs.blocks[iField][iOperation]);
        }
    }
}

template<typename T, template<typename U> class Descriptor>
TransientStatistics3D<T,Descriptor>& TransientStatistics3D<T,Descriptor>::operator=(
        TransientStatistics3D<T,Descriptor> const& rhs)
{
    TransientStatistics3D<T,Descriptor>(rhs).swap(*this);
    return *this;
}

template<typename T, template<typename U> class Descriptor>
TransientStatistics3D<T,Descriptor>* TransientStatistics3D<T,Descriptor>::clone() const
{
    return new TransientStatistics3D<T,Descriptor>(*this);
}

template<typename T, template<typename U> class Descriptor>
TransientStatistics3D<T,Descriptor>::~TransientStatistics3D()
{
    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            delete blocks[iField][iOperation];
        }
    }
}

template<typename T, template<typename U> class Descriptor>
bool TransientStatistics3D<T,Descriptor>::registerFieldOperation(std::string field, std::string operation)
{
    if (isInitialized) {    // No registering is allowed after initialization.
        return false;
    }

    int iField = fieldToId(field);
    PLB_ASSERT(iField >= 0);
    int iOperation = operationToId(operation);
    PLB_ASSERT(iOperation >= 0);

    fieldIsRegistered[iField] = 1;
    fieldOperationIsRegistered[iField][iOperation] = 1;
    if (iOperation == dev) {
        fieldOperationIsRegistered[iField][ave] = 1;  // When the standard deviation is registered, averaging is registered also.
    }

    return true;
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::initialize()
{
    if (isInitialized) {
        return;
    }

    // We use an enlarged domain to compute the vorticity, whenever it is registered.
    if (fieldIsRegistered[vorticityX] || fieldIsRegistered[vorticityY] || fieldIsRegistered[vorticityZ] ||
            fieldIsRegistered[vorticityNorm]) {
#ifdef PLB_DEBUG
        bool intersectsWithSimulationDomain =
#endif
            intersect(domain.enlarge(1), lattice.getBoundingBox(), enlargedDomain);
        PLB_ASSERT(intersectsWithSimulationDomain);
    }

    for (int iField = 0; iField < numFields; iField++) {
        if (fieldIsRegistered[iField]) {    // There is at least one operation for this field.
            MultiScalarField3D<T>* field = computeField(iField);
            for (int iOperation = 0; iOperation < numOperations; iOperation++) {
                if (fieldOperationIsRegistered[iField][iOperation]) {
                    MultiScalarField3D<T>* fieldToRegister = 0;
                    if (iOperation == rms) {
                        fieldToRegister = computeAbsoluteValue(*field).release();
                    } else if (iOperation == dev) {
                        fieldToRegister = field->clone();
                        setToConstant(*fieldToRegister, fieldToRegister->getBoundingBox(), (T) 0);
                    } else {
                        fieldToRegister = field->clone();
                    }

                    blocks[iField][iOperation] = fieldToRegister;
                }
            }
            delete field;
        }
    }

    n = 1;
    isInitialized = 1;
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::update()
{
    if (!isInitialized) {
        initialize();
        return;
    }

    n++;

    for (int iField = 0; iField < numFields; iField++) {
        if (fieldIsRegistered[iField]) {    // There is at least one operation for this field.
            MultiScalarField3D<T>* field = computeField(iField);
            for (int iOperation = 0; iOperation < numOperations; iOperation++) {
                if (fieldOperationIsRegistered[iField][iOperation]) {
                    std::vector<MultiBlock3D*> args;
                    args.push_back(field);
                    if (iOperation == dev) {
                        args.push_back(blocks[iField][ave]); // ave must be less than dev, so that the average is already updated.
                    }
                    args.push_back(blocks[iField][iOperation]);

                    BoxProcessingFunctional3D* functional = 0;
                    switch (iOperation) {
                    case min:
                        functional = new UpdateMinScalarTransientStatistics3D<T>();
                        break;
                    case max:
                        functional = new UpdateMaxScalarTransientStatistics3D<T>();
                        break;
                    case ave:
                        functional = new UpdateAveScalarTransientStatistics3D<T>(n);
                        break;
                    case rms:
                        functional = new UpdateRmsScalarTransientStatistics3D<T>(n);
                        break;
                    case dev:
                        functional = new UpdateDevScalarTransientStatistics3D<T>(n);
                        break;
                    default:
                        functional = 0;
                        break;
                    }

                    applyProcessingFunctional(functional, field->getBoundingBox(), args);
                }
            }
            delete field;
        }
    }
}

template<typename T, template<typename U> class Descriptor>
MultiScalarField3D<T>& TransientStatistics3D<T,Descriptor>::get(std::string field, std::string operation) const
{
    int iField = fieldToId(field);
    PLB_ASSERT(iField >= 0);
    int iOperation = operationToId(operation);
    PLB_ASSERT(iOperation >= 0);

    return *blocks[iField][iOperation];
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::output(std::string path, std::string domainName, plint iteration,
        plint namePadding, T dx, T dt, Array<T,3> const& physicalLocation, T rho, T pressureOffset, T rhoLB)
{
    if (!isInitialized) {
        initialize();
    }

    for (int iField = 0; iField < numFields; iField++) {
        for (int iOperation = 0; iOperation < numOperations; iOperation++) {
            if (fieldOperationIsRegistered[iField][iOperation]) {
                std::string fileName = getFileName(path, iField, iOperation, domainName, iteration, namePadding);
                VtkImageOutput3D<T> vtkOut(fileName, dx, physicalLocation);
                std::string field = idToField(iField);
                T scalingFactor = getScalingFactor(iField, dx, dt, rho);
                T offset = getOffset(iField, dx, dt, rho, pressureOffset, rhoLB);
                vtkOut.writeData(*blocks[iField][iOperation], field, scalingFactor, offset);
            }
        }
    }
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::saveState(
        plint iteration, FileName xmlFileName, FileName baseFileName, plint fileNamePadding)
{
    if (!isInitialized) {
        initialize();
    }

    std::string fname_base = createFileName(baseFileName.get() + "_", iteration, fileNamePadding);

    bool saveDynamicContent = false;
    for (int iField = 0; iField < numFields; iField++) {
        if (fieldIsRegistered[iField]) {
            std::string field = idToField(iField);
            for (int iOperation = 0; iOperation < numOperations; iOperation++) {
                if (fieldOperationIsRegistered[iField][iOperation]) {
                    std::string operation = idToOperation(iOperation);
                    std::string fname = fname_base + "_" + field + "_" + operation;
                    parallelIO::save(*blocks[iField][iOperation], fname, saveDynamicContent);
                }
            }
        }
    }

    XMLwriter restart;
    XMLwriter& entry = restart["continue"]["transientStatistics"];
    entry["name"].setString(FileName(fname_base).defaultPath(global::directories().getOutputDir()));
    entry["iteration"].set(iteration);
    entry["n"].set(n);
    restart.print(xmlFileName);
}

template<typename T, template<typename U> class Descriptor>
void TransientStatistics3D<T,Descriptor>::loadState(plint& iteration, FileName xmlFileName)
{
    XMLreader restart(xmlFileName.get());
    std::string fname_base;
    restart["continue"]["transientStatistics"]["name"].read(fname_base);
    restart["continue"]["transientStatistics"]["iteration"].read(iteration);
    restart["continue"]["transientStatistics"]["n"].read(n);

    bool saveDynamicContent = false;
    for (int iField = 0; iField < numFields; iField++) {
        if (fieldIsRegistered[iField]) {
            std::string field = idToField(iField);
            for (int iOperation = 0; iOperation < numOperations; iOperation++) {
                if (fieldOperationIsRegistered[iField][iOperation]) {
                    std::string operation = idToOperation(iOperation);
                    std::string fname = fname_base + "_" + field + "_" + operation;
                    parallelIO::load(fname, *blocks[iField][iOperation], saveDynamicContent);
                }
            }
        }
    }
}

template<typename T, template<typename U> class Descriptor>
int TransientStatistics3D<T,Descriptor>::fieldToId(std::string field) const
{
    if (field == "velocityX") {
        return velocityX;
    } else if (field == "velocityY") {
        return velocityY;
    } else if (field == "velocityZ") {
        return velocityZ;
    } else if (field == "velocityNorm") {
        return velocityNorm;
    } else if (field == "density") {
        return density;
    } else if (field == "pressure") {
        return pressure;
    } else if (field == "vorticityX") {
        return vorticityX;
    } else if (field == "vorticityY") {
        return vorticityY;
    } else if (field == "vorticityZ") {
        return vorticityZ;
    } else if (field == "vorticityNorm") {
        return vorticityNorm;
    } else {
        return -1;
    }
}

template<typename T, template<typename U> class Descriptor>
int TransientStatistics3D<T,Descriptor>::operationToId(std::string operation) const
{
    if (operation == "min") {
        return min;
    } else if (operation == "max") {
        return max;
    } else if (operation == "ave") {
        return ave;
    } else if (operation == "rms") {
        return rms;
    } else if (operation == "dev") {
        return dev;
    } else {
        return -1;
    }
}

template<typename T, template<typename U> class Descriptor>
std::string TransientStatistics3D<T,Descriptor>::idToField(int iField) const
{
    PLB_ASSERT(iField >= 0);

    switch (iField) {
    case velocityX:
        return std::string("velocityX");
    case velocityY:
        return std::string("velocityY");
    case velocityZ:
        return std::string("velocityZ");
    case velocityNorm:
        return std::string("velocityNorm");
    case density:
        return std::string("density");
    case pressure:
        return std::string("pressure");
    case vorticityX:
        return std::string("vorticityX");
    case vorticityY:
        return std::string("vorticityY");
    case vorticityZ:
        return std::string("vorticityZ");
    case vorticityNorm:
        return std::string("vorticityNorm");
    default:
        return std::string("error");
    }
}

template<typename T, template<typename U> class Descriptor>
std::string TransientStatistics3D<T,Descriptor>::idToOperation(int iOperation) const
{
    PLB_ASSERT(iOperation >= 0);

    switch (iOperation) {
    case min:
        return std::string("min");
    case max:
        return std::string("max");
    case ave:
        return std::string("ave");
    case rms:
        return std::string("rms");
    case dev:
        return std::string("dev");
    default:
        return std::string("error");
    }
}

template<typename T, template<typename U> class Descriptor>
T TransientStatistics3D<T,Descriptor>::getScalingFactor(int iField, T dx, T dt, T rho) const
{
    PLB_ASSERT(iField >= 0);

    T scalingFactor = 0.0;

    switch (iField) {
    case velocityX: case velocityY: case velocityZ: case velocityNorm:
        scalingFactor = dx / dt;
        break;
    case density:
        scalingFactor = rho;
        break;
    case pressure:
        scalingFactor = rho * dx * dx / (dt * dt) * Descriptor<T>::cs2;
        break;
    case vorticityX: case vorticityY: case vorticityZ: case vorticityNorm:
        scalingFactor = 1.0 / dt;
        break;
    default:
        scalingFactor = 0.0;
        break;
    }

    return scalingFactor;
}

template<typename T, template<typename U> class Descriptor>
T TransientStatistics3D<T,Descriptor>::getOffset(int iField, T dx, T dt, T rho, T pressureOffset, T rhoLB) const
{
    PLB_ASSERT(iField >= 0);

    T offset = 0.0;

    switch (iField) {
    case pressure:
        offset = pressureOffset - rho * dx * dx / (dt * dt) * Descriptor<T>::cs2 * rhoLB;
        break;
    default:
        offset = 0.0;
        break;
    }

    return offset;
}

template<typename T, template<typename U> class Descriptor>
MultiScalarField3D<T>* TransientStatistics3D<T,Descriptor>::computeField(int iField) const
{
    PLB_ASSERT(iField >= 0);

    MultiScalarField3D<T>* field = 0;

    switch (iField) {
    case velocityX:
        field = computeVelocityComponent(lattice, domain, 0).release();
        break;
    case velocityY:
        field = computeVelocityComponent(lattice, domain, 1).release();
        break;
    case velocityZ:
        field = computeVelocityComponent(lattice, domain, 2).release();
        break;
    case velocityNorm:
        field = computeVelocityNorm(lattice, domain).release();
        break;
    case density:
    case pressure:
        field = computeDensity(lattice, domain).release();
        break;
    case vorticityX:
        field = extractComponent(*computeVorticity(*computeVelocity(lattice, enlargedDomain)), domain, 0).release();
        break;
    case vorticityY:
        field = extractComponent(*computeVorticity(*computeVelocity(lattice, enlargedDomain)), domain, 1).release();
        break;
    case vorticityZ:
        field = extractComponent(*computeVorticity(*computeVelocity(lattice, enlargedDomain)), domain, 2).release();
        break;
    case vorticityNorm:
        field = computeNorm(*computeVorticity(*computeVelocity(lattice, enlargedDomain)), domain).release();
        break;
    default:
        field = 0;
        break;
    }

    return field;
}

template<typename T, template<typename U> class Descriptor>
std::string TransientStatistics3D<T,Descriptor>::getFileName(std::string path, int iField, int iOperation,
        std::string domainName, plint iteration, plint namePadding) const
{
    std::string field = idToField(iField);
    std::string operation = idToOperation(iOperation);
    std::string name = createFileName(field + "_" + operation + "_" + domainName + "_", iteration, namePadding);
    FileName fileName;
    fileName.setPath(path);
    fileName.setName(name);
    return fileName.get();
}

}  // namespace plb

#endif  // TRANSIENT_STATISTICS_3D_HH


text:
package org.eclipse.jdt.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE_USE)
public @interface Nullable {}