text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace TODT.Test.Fakes
{
    [RouteArea("TestArea")]
    public class TestControllerWithArea : TestController
    {
    }
}


text:
<<'EOF_LICENSE'
Copyright 2013 Ben Gimpert (ben@somethingmodern.com)

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.
EOF_LICENSE

require 'test/unit'

require 'rubygems'
require 'graphviz'

require '_logger'
require '_stanford_sentiment_treebank'

class StanfordSentimentTreebankTests <Test::Unit::TestCase
  include Test::Unit::Assertions

  def test_phrases
    treebank = StanfordSentimentTreebank::StanfordSentimentTreebank.new
    treebank.each_phrase_map do |phrase_map|
      Logger.verbose("Phrase map #{phrase_map.inspect} found.") #if Logger.verbose?
      assert_equal(69, phrase_map.length)
      assert_equal(phrase_map["The Rock is destined to be the 21st Century 's new `` Conan '' and that he 's going to make a splash even greater than Arnold Schwarzenegger , Jean-Claud Van Damme or Steven Segal ."], 0.69444)
      assert_equal(phrase_map["even greater"], 0.54167)
      assert_equal(phrase_map["destined"], 0.58333)
      break
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [("events", "0005_auto_20150503_1741")]

    operations = [migrations.RemoveField(model_name="event", name="for_client")]


text:
package org.ovirt.engine.ui.uicommonweb.models.templates;

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

import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.ExportVmModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;

public abstract class VmBaseListModel<T> extends ListWithDetailsModel {

    protected void Export()
    {
        T selectedEntity = (T) getSelectedItem();
        if (selectedEntity == null)
        {
            return;
        }

        if (getWindow() != null)
        {
            return;
        }

        ExportVmModel model = new ExportVmModel();
        setWindow(model);
        model.StartProgress(null);
        model.setTitle(ConstantsManager.getInstance().getConstants().exportVirtualMachineTitle());
        model.setHashName("export_virtual_machine"); //$NON-NLS-1$
        setupExportModel(model);

        AsyncDataProvider.GetStorageDomainList(new AsyncQuery(this,
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object target, Object returnValue) {
                        VmBaseListModel vmListModel = (VmBaseListModel) target;
                        List<storage_domains> storageDomains =
                                (List<storage_domains>) returnValue;

                        List<storage_domains> filteredStorageDomains =
                                new ArrayList<storage_domains>();
                        for (storage_domains a : storageDomains)
                        {
                            if (a.getstorage_domain_type() == StorageDomainType.ImportExport)
                            {
                                filteredStorageDomains.add(a);
                            }
                        }

                        vmListModel.PostExportGetStorageDomainList(filteredStorageDomains);
                    }
                }), extractStoragePoolIdNullSafe(selectedEntity));
    }

    private void PostExportGetStorageDomainList(List<storage_domains> storageDomains)
    {
        ExportVmModel model = (ExportVmModel) getWindow();
        model.getStorage().setItems(storageDomains);
        model.getStorage().setSelectedItem(Linq.FirstOrDefault(storageDomains));

        boolean noActiveStorage = true;
        for (storage_domains a : storageDomains) {
            if (a.getstatus() == StorageDomainStatus.Active) {
                noActiveStorage = false;
                break;
            }
        }

        if (entitiesSelectedOnDifferentDataCenters()) {
            model.getCollapseSnapshots().setIsChangable(false);
            model.getForceOverride().setIsChangable(false);

            model.setMessage(entityResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg());

            UICommand tempVar = new UICommand("Cancel", this); //$NON-NLS-1$
            tempVar.setTitle(ConstantsManager.getInstance().getConstants().close());
            tempVar.setIsDefault(true);
            tempVar.setIsCancel(true);
            model.getCommands().add(tempVar);
            model.StopProgress();
        }
        else if (storageDomains.isEmpty()) {
            model.getCollapseSnapshots().setIsChangable(false);
            model.getForceOverride().setIsChangable(false);

            model.setMessage(thereIsNoExportDomainBackupEntityAttachExportDomainToVmsDcMsg());

            UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
            tempVar2.setTitle(ConstantsManager.getInstance().getConstants().close());
            tempVar2.setIsDefault(true);
            tempVar2.setIsCancel(true);
            model.getCommands().add(tempVar2);
            model.StopProgress();
        }
        else if (noActiveStorage) {
            model.getCollapseSnapshots().setIsChangable(false);
            model.getForceOverride().setIsChangable(false);

            model.setMessage(ConstantsManager.getInstance()
                    .getConstants()
                    .theRelevantExportDomainIsNotActivePleaseActivateItMsg());

            UICommand tempVar3 = new UICommand("Cancel", this); //$NON-NLS-1$
            tempVar3.setTitle(ConstantsManager.getInstance().getConstants().close());
            tempVar3.setIsDefault(true);
            tempVar3.setIsCancel(true);
            model.getCommands().add(tempVar3);
            model.StopProgress();
        }
        else {
            showWarningOnExistingEntities(model, getEntityExportDomain());

            UICommand tempVar4 = new UICommand("OnExport", this); //$NON-NLS-1$
            tempVar4.setTitle(ConstantsManager.getInstance().getConstants().ok());
            tempVar4.setIsDefault(true);
            model.getCommands().add(tempVar4);
            UICommand tempVar5 = new UICommand("Cancel", this); //$NON-NLS-1$
            tempVar5.setTitle(ConstantsManager.getInstance().getConstants().cancel());
            tempVar5.setIsCancel(true);
            model.getCommands().add(tempVar5);
        }
    }

    protected void showWarningOnExistingEntities(ExportVmModel model, final VdcQueryType getVmOrTemplateQuery) {
        Guid storageDomainId = ((storage_domains) model.getStorage().getSelectedItem()).getId();
        AsyncDataProvider.GetDataCentersByStorageDomain(new AsyncQuery(new Object[] { this, model },
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object target, Object returnValue) {
                        Object[] array = (Object[]) target;
                        VmBaseListModel vmListModel = (VmBaseListModel) array[0];
                        ExportVmModel exportVmModel = (ExportVmModel) array[1];
                        List<storage_pool> storagePools = (List<storage_pool>) returnValue;
                        vmListModel.PostShowWarningOnExistingVms(exportVmModel, storagePools, getVmOrTemplateQuery);
                    }
                }), storageDomainId);
    }

    private void PostShowWarningOnExistingVms(final ExportVmModel exportModel,
            List<storage_pool> storagePools,
            VdcQueryType getVmOrTemplateQuery) {
        storage_pool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null;

        if (storagePool != null) {
            AsyncQuery _asyncQuery = new AsyncQuery();
            _asyncQuery.setModel(this);
            _asyncQuery.asyncCallback = new INewAsyncCallback() {
                @Override
                public void OnSuccess(Object model, Object result) {
                    VmBaseListModel listModel = (VmBaseListModel) model;
                    ExportVmModel exportModel1 = (ExportVmModel) listModel.getWindow();
                    String existingEntitiess = ""; //$NON-NLS-1$

                    if (result != null) {
                        for (Object rawSelectedItem : listModel.getSelectedItems()) {
                            T selectedItem = (T) rawSelectedItem;
                            T foundVm = null;
                            VdcQueryReturnValue returnValue = (VdcQueryReturnValue) result;
                            for (T returnValueItem : asIterableReturnValue(returnValue.getReturnValue())) {
                                if (entititesEqualsNullSafe(returnValueItem, selectedItem)) {
                                    foundVm = selectedItem;
                                    break;
                                }
                            }

                            if (foundVm != null) {
                                existingEntitiess = "\u2022  " + extractNameFromEntity(foundVm) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
                            }
                        }
                    }
                    if (!StringHelper.isNullOrEmpty(existingEntitiess)) {
                        exportModel1.setMessage(composeEntityOnStorage(existingEntitiess));
                    }
                    exportModel.StopProgress();
                }
            };

            Guid storageDomainId = ((storage_domains) exportModel.getStorage().getSelectedItem()).getId();
            GetAllFromExportDomainQueryParameters tempVar =
                    new GetAllFromExportDomainQueryParameters(storagePool.getId(), storageDomainId);
            tempVar.setGetAll(true);
            Frontend.RunQuery(getVmOrTemplateQuery, tempVar, _asyncQuery);
        } else {
            exportModel.StopProgress();
        }
    }

    protected void setupExportModel(ExportVmModel model) {
        // no-op by default. Override if needed.
    }

    protected abstract String composeEntityOnStorage(String entities);

    protected abstract Iterable<T> asIterableReturnValue(Object returnValue);

    protected abstract boolean entititesEqualsNullSafe(T e1, T e2);

    protected abstract String extractNameFromEntity(T entity);

    protected abstract Guid extractStoragePoolIdNullSafe(T entity);

    protected abstract boolean entitiesSelectedOnDifferentDataCenters();

    protected abstract String entityResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg();

    protected abstract String thereIsNoExportDomainBackupEntityAttachExportDomainToVmsDcMsg();

    protected abstract VdcQueryType getEntityExportDomain();

}


text:
<?php

namespace Jmbermudo\SGR3Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Jmbermudo\SGR3Bundle\Entity\Voto;

class VotoController extends Controller
{

    public function showAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        //Vamos a llamar a un método que comprobará si el usuario puede o no puede
        //votar para esta reunión
        $reunion = $this->usuarioPuedeVotar($id, $em);

        $usuario = $this->getUser();

        $votos = $em->getRepository('JmbermudoSGR3Bundle:Voto')->getVotosUsuario($usuario, $reunion);

        $formulario = $this->generaFormulario($request, $reunion, $votos);

        return $this->render('JmbermudoSGR3Bundle:Voto:votacion.html.twig', array(
            'reunion'=> $reunion,
            'votos' => $votos,
            'form'   => $formulario->createView(),
        ));
    }

    /**
     * Registra la votación de un usuario invitado a la reunión
     * @param type $id Id de la Reunión para la que se vota
     */
    public function votacionAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        //Lo primero será ver para qué reunión está votando. El parámetro viene oculto
        $params = $request->request->all();
        $reunion_id = $params['form']['reunion'];

        //Vamos a llamar a un método que comprobará si el usuario puede o no puede
        //votar para esta reunión
        $reunion = $this->usuarioPuedeVotar($reunion_id, $em);

        $usuario = $this->getUser();

        $votos = $em->getRepository('JmbermudoSGR3Bundle:Voto')->getVotosUsuario($usuario, $reunion);

        $formulario = $this->generaFormulario($request, $reunion, $votos);

        $formulario->handleRequest($request);

        if ($formulario->isValid()) {

            //Primero anulamos los votos anteriores
            $res = $em->getRepository('JmbermudoSGR3Bundle:Voto')->anulaVotoUsuarioReunion($usuario, $reunion);

            //Si la anulación de los votos falla, terminamos
            if(!$res){
                //error 500
                throw new \Exception($this->get('translator')->trans('global.errorBD'));
            }

            //Y ahora guardamos los nuevos
            foreach($reunion->getPrereservas() as $preReserva){
                //Si el voto viene, es que el usuario lo ha votado, si no no
                $voto = new Voto();
                $voto->setFecha(new \DateTime());
                $voto->setPrereserva($preReserva);
                $voto->setUsuario($usuario);
                $voto->setValido(true);

                $id_voto = 'voto_' . $preReserva->getId() . '_' . $this->getUser()->getId();
                if (array_key_exists($id_voto, $params['form'])){
                    $voto->setAcepta(true);
                }
                else{
                    $voto->setAcepta(false);
                }

                //Por último, guardamos el voto
                $em->persist($voto);
            }
            //Y guardamos en la base de datos
            $em->flush();

            // add flash messages
            $request->getSession()->getFlashBag()->add(
                    'success', $this->get('translator')->trans('voto.votacionOK')
            );
        }

        //El formulario no es válido
        return $this->redirect($this->generateUrl('jmbermudo_sgr3_homepage'));
    }

    private function generaFormulario(Request $request, $reunion, $votos)
    {
        $form = $this->createFormBuilder()
        ->add('reunion', 'hidden', array(
            'data' => $reunion->getId()
        ));

        foreach ($reunion->getPrereservas() as $preReserva) {
            //obtenemos el voto del usuario para esta prereserva
            $voto = $this->getVotoDePrereserva($preReserva, $votos);
            $form->add('voto_' . $preReserva->getId() . '_' . $this->getUser()->getId(), 'checkbox', array(
                'data' => $voto->getAcepta(),
                'label' => $this->formatFecha($preReserva->getFecha(), $request) . ' => ' . $this->formatHora($preReserva->getHoraInicio(), $request) . ' - ' . $this->formatHora($preReserva->getHoraFin(), $request),
                'required' => false
            ));
        }

        $form->add('submit', 'submit', array('label' => $this->get('translator')->trans('voto.votar')));

        //Cambiamos el action
        $form->setAction($this->generateUrl('voto_votar'));

        return $form->getForm();
    }

    /**
     * Devuelve el voto correspondiente a la prereserva, o un voto vacío en caso de que
     * no exista
     * @param type $prereserva
     * @param type $votos
     * @return null
     */
    private function getVotoDePrereserva($prereserva, $votos)
    {
        foreach ($votos as $voto) {
            if($voto->getPrereserva() === $prereserva){
                return $voto;
            }
        }

        return new Voto();
    }

    private function formatFecha(\Datetime $fecha, Request $request)
    {
        $formatterFecha = \IntlDateFormatter::create(
                        $request->getLocale(),
                        \IntlDateFormatter::MEDIUM,
                        \IntlDateFormatter::NONE,
                        $fecha->getTimezone()->getName(),
                        \IntlDateFormatter::GREGORIAN,
                        null
                    );

        return $formatterFecha->format($fecha);
    }

    private function formatHora(\Datetime $fecha, Request $request)
    {
        $formatterFecha = \IntlDateFormatter::create(
                        $request->getLocale(),
                        \IntlDateFormatter::NONE,
                        \IntlDateFormatter::MEDIUM,
                        $fecha->getTimezone()->getName(),
                        \IntlDateFormatter::GREGORIAN,
                        null
                    );

        return $formatterFecha->format($fecha);
    }

    /**
     * Determina si un usuario puede votar en una reunión. tiene en cuenta los
     * siguientes factores:
     *      - Está invitado
     *      - La reunión es válida
     *      - La fecha de votación todavía está activa
     * @param type $request
     * @param type $reunion
     *
     * @return Reunion El objeto reunión si no se ha producido ningún problema
     * para que el usuario pueda votar
     */
    private function usuarioPuedeVotar($reunion_id, $em)
    {
        $reunion = $em->getRepository('JmbermudoSGR3Bundle:Reunion')->find($reunion_id);

        if(!$reunion){
            $this->createNotFoundException($this->get('translator')->trans('reunion.notFound'));
        }

        //Vamos a ver si la reunión se ha cancelado
        if ($reunion->getAnulada())
        {
            throw new \Exception($this->get('translator')->trans('reunion.anulada'));
        }

        $invitados = $reunion->getInvitados();

        $usuario = $this->getUser();

        //Si el usuario no está invitado, no puede participar
        if(!$invitados->contains($usuario)){
            throw new AccessDeniedException($this->get('translator')->trans('voto.no_invitado'));
        }

        //Vamos a calcular cuándo era la fecha máxima para votar de la reunión
        $fecha_actual = new \DateTime('', new \DateTimeZone($this->container->getParameter('timezone')));

        $fecha_max_reunion = $reunion->getFechaCreacion();
        //Añadimos el número de días que el usuario tenía para votar
        $fecha_max_reunion->add(new \DateInterval('P' . $this->container->getParameter('duracion_reunion') . 'D'));

        //Si la reunión ya ha pasado su fecha máxima de voto, no puede votar
        //Sólo tendremos en cuenta el día, no la hora
        $fecha_actual_dia = $fecha_actual->format('Y-m-d');
        $fecha_max_reunion_dia = $fecha_max_reunion->format('Y-m-d');

        if($fecha_actual_dia > $fecha_max_reunion_dia){
            throw new \Exception($this->get('translator')->trans('reunion.fechaExpirada'));
        }

        //Si todo lo anterior pasa sin lanzar excepciones, el usuario puede votar
        return $reunion;
    }

}


text:
<Type Name="ShadowMarginStyle" FullName="Hyena.Gui.Canvas.ShadowMarginStyle">
  <TypeSignature Language="C#" Value="public class ShadowMarginStyle : Hyena.Gui.Canvas.MarginStyle" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit ShadowMarginStyle extends Hyena.Gui.Canvas.MarginStyle" />
  <AssemblyInfo>
    <AssemblyName>Hyena.Gui</AssemblyName>
    <AssemblyVersion>2.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Hyena.Gui.Canvas.MarginStyle</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public ShadowMarginStyle ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Apply">
      <MemberSignature Language="C#" Value="public override void Apply (Hyena.Gui.Canvas.CanvasItem item, Cairo.Context cr);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance void Apply(class Hyena.Gui.Canvas.CanvasItem item, class Cairo.Context cr) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="item" Type="Hyena.Gui.Canvas.CanvasItem" />
        <Parameter Name="cr" Type="Cairo.Context" />
      </Parameters>
      <Docs>
        <param name="item">To be added.</param>
        <param name="cr">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Fill">
      <MemberSignature Language="C#" Value="public Hyena.Gui.Canvas.Brush Fill { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class Hyena.Gui.Canvas.Brush Fill" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>Hyena.Gui.Canvas.Brush</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ShadowOpacity">
      <MemberSignature Language="C#" Value="public double ShadowOpacity { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance float64 ShadowOpacity" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Double</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ShadowSize">
      <MemberSignature Language="C#" Value="public int ShadowSize { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance int32 ShadowSize" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.4.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Int32</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
Adafruit's Raspberry-Pi Python Code Library
============
  Here is a growing collection of libraries and example python scripts
  for controlling a variety of Adafruit electronics with a Raspberry Pi

  In progress!

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries.
  BSD license, all text above and below must be included in any redistribution

  To download, we suggest logging into your Pi with Internet accessibility and typing:

```bash
git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
```

============
Copyright (c) 2012-2013 Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
module.exports = {
  tabWidth: 2,
  semi: true,
  singleQuote: true,
};


text:
// msort.c
// LMNO LALR(1) parser generator
//
// Copyright ©2010 Brigham Toskin
// (Based on LEMON v1 parser generator, public domain)
//////////////////////////////////////////////////////

#include "global.h"

/*
 ** A generic merge-sort program.
 **
 ** USAGE:
 ** Let "ptr" be a pointer to some structure which is at the head of
 ** a null-terminated list.  Then to sort the list call:
 **
 **	 ptr = msort(ptr,&(ptr->next),cmpfnc);
 **
 ** In the above, "cmpfnc" is a pointer to a function which compares
 ** two instances of the structure and returns an integer, as in
 ** strcmp.  The second argument is a pointer to the pointer to the
 ** second element of the linked list.  This address is used to compute
 ** the offset to the "next" field within the structure.  The offset to
 ** the "next" field must be constant for all structures in the list.
 **
 ** The function returns a new pointer which is the head of the list
 ** after sorting.
 **
 ** ALGORITHM:
 ** Merge-sort.
 */

/*
 ** Return a pointer to the next structure in the linked list.
 */
#define NEXT(A) (*(char**)(((unsigned long)A)+offset))

/*
 ** Inputs:
 **   a:	   A sorted, null-terminated linked list.  (May be null).
 **   b:	   A sorted, null-terminated linked list.  (May be null).
 **   cmp:	 A pointer to the comparison function.
 **   offset:  Offset in the structure to the "next" field.
 **
 ** Return Value:
 **   A pointer to the head of a sorted list containing the elements
 **   of both a and b.
 **
 ** Side effects:
 **   The "next" pointers for elements in the lists a and b are
 **   changed.
 */
static char *merge(char *a, char *b, int (*cmp)(), int offset)
{
	char *ptr, *head;

	if( a==0 )
	{
		head = b;
	}
	else if( b==0 )
	{
		head = a;
	}
	else
	{
		if( (*cmp)(a,b)<0 )
		{
			ptr = a;
			a = NEXT(a);
		}
		else
		{
			ptr = b;
			b = NEXT(b);
		}
		head = ptr;
		while( a && b )
		{
			if( (*cmp)(a,b)<0 )
			{
				NEXT(ptr) = a;
				ptr = a;
				a = NEXT(a);
			}
			else
			{
				NEXT(ptr) = b;
				ptr = b;
				b = NEXT(b);
			}
		}
		if( a )
			NEXT(ptr) = a;
		else
			NEXT(ptr) = b;
	}
	return head;
}

/*
 ** Inputs:
 **   list:	  Pointer to a singly-linked list of structures.
 **   next:	  Pointer to pointer to the second element of the list.
 **   cmp:	   A comparison function.
 **
 ** Return Value:
 **   A pointer to the head of a sorted list containing the elements
 **   orginally in list.
 **
 ** Side effects:
 **   The "next" pointers for elements in list are changed.
 */
#define LISTSIZE 30
char *msort(char *list, char **next, int (*cmp)())
{
	unsigned long offset;
	char *ep;
	char *set[LISTSIZE];
	int i;
	offset = (unsigned long)next - (unsigned long)list;
	for(i=0; i<LISTSIZE; i++)
		set[i] = 0;
	while( list )
	{
		ep = list;
		list = NEXT(list);
		NEXT(ep) = 0;
		for(i=0; i<LISTSIZE-1 && set[i]!=0; i++)
		{
			ep = merge(ep,set[i],cmp,offset);
			set[i] = 0;
		}
		set[i] = ep;
	}
	ep = 0;
	for(i=0; i<LISTSIZE; i++)
		if( set[i] )
			ep = merge(ep,set[i],cmp,offset);
	return ep;
}


text: simple swiper


text:
package org.scalawiki.dto.cmd.query.prop

import org.scalawiki.dto.cmd.query.prop.rvprop._

object RvPropArgs {
  val args = Seq(Ids, Flags, Timestamp, User, UserId, Size, Sha1, ContentModel, Comment, ParsedComment, Content, Tags)
  val argsByName: Map[String, RvPropArg] = args.groupBy(_.name).mapValues(_.head).toMap

  def byNames(names: Seq[String]): Seq[RvPropArg] = {
    names.flatMap(argsByName.get)
  }
}


text:
package org.apache.hadoop.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authorize.AuthorizationException;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Extend the function of {@link AuthenticationFilter} to
 * support authorizing proxy user. If the query string
 * contains doAs parameter, then check the proxy user,
 * otherwise do the next filter.
 */
public class AuthenticationWithProxyUserFilter extends AuthenticationFilter {

  public static final Log LOG =
      LogFactory.getLog(AuthenticationWithProxyUserFilter.class);

  /**
   * Constant used in URL's query string to perform a proxy user request, the
   * value of the DO_AS parameter is the user the request will be
   * done on behalf of.
   */
  private static final String DO_AS = "doAs";

  private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

  /**
   * This method provide the ability to do pre/post tasks
   * in filter chain. Override this method to authorize
   * proxy user between AuthenticationFilter and next filter.
   * @param filterChain the filter chain object.
   * @param request the request object.
   * @param response the response object.
   *
   * @throws IOException
   * @throws ServletException
   */
  @Override
  protected void doFilter(FilterChain filterChain, HttpServletRequest request,
      HttpServletResponse response) throws IOException, ServletException {

    final String proxyUser = getDoAs(request);
    if (proxyUser != null) {

      // Change the remote user after proxy user is authorized.
      final HttpServletRequest finalReq = request;
      request = new HttpServletRequestWrapper(finalReq) {

        private String getRemoteOrProxyUser() throws AuthorizationException {
          UserGroupInformation realUser =
              UserGroupInformation.createRemoteUser(finalReq.getRemoteUser());
          UserGroupInformation proxyUserInfo =
              UserGroupInformation.createProxyUser(proxyUser, realUser);
          ProxyUsers.authorize(proxyUserInfo, finalReq.getRemoteAddr());
          return proxyUserInfo.getUserName();
        }

        @Override
        public String getRemoteUser() {
          try {
            return getRemoteOrProxyUser();
          } catch (AuthorizationException ex) {
            LOG.error("Unable to verify proxy user: " + ex.getMessage(), ex);
          }
          return null;
        }
      };

    }
    filterChain.doFilter(request, response);
  }

  /**
   * Get proxy user from query string.
   * @param request the request object
   * @return proxy user
   */
  public static String getDoAs(HttpServletRequest request) {
    String queryString = request.getQueryString();
    if (queryString == null) {
      return null;
    }
    List<NameValuePair> list = URLEncodedUtils.parse(queryString, UTF8_CHARSET);
    if (list != null) {
      for (NameValuePair nv : list) {
        if (DO_AS.equalsIgnoreCase(nv.getName())) {
          return nv.getValue();
        }
      }
    }
    return null;
  }
}


text:
namespace cloud_devices {

namespace json {

const char kVersion[] = "version";
const char kVersion10[] = "1.0";

const char kKeyDefault[] = "default";
const char kKeyIsDefault[] = "is_default";
const char kKeyOption[] = "option";

}  // namespace json

}  // namespace cloud_devices


text:
'use strict'

const jsonApi = require('../..')

module.exports = new jsonApi.MemoryHandler()


text:
<#
.EXAMPLE
    This example makes sure the service application exists and has a specific configuration
#>

    Configuration Example
    {
        param(
            [Parameter(Mandatory = $true)]
            [PSCredential]
            $SetupAccount
        )
        Import-DscResource -ModuleName SharePointDsc

        node localhost {
            SPWordAutomationServiceApp WordAutomation
            {
                Name = "Word Automation Service Application"
                Ensure = "Present"
                ApplicationPool = "SharePoint Web Services"
                DatabaseName = "WordAutomation_DB"
                DatabaseServer = "SQLServer"
                SupportedFileFormats = "docx", "doc", "mht", "rtf", "xml"
                DisableEmbeddedFonts = $false
                MaximumMemoryUsage = 100
                RecycleThreshold = 100
                DisableBinaryFileScan = $false
                ConversionProcesses = 8
                JobConversionFrequency = 15
                NumberOfConversionsPerProcess = 12
                TimeBeforeConversionIsMonitored = 5
                MaximumConversionAttempts = 2
                MaximumSyncConversionRequests = 25
                KeepAliveTimeout = 30
                MaximumConversionTime = 300
                PsDscRunAsCredential = $SetupAccount
            }
        }
    }


text:
cask 'lexiloader' do
  version '30'
  sha256 '68c0d9482fe8f3b8c7251b452929ba4b58bbfdf478f5dc68740edc09fd87d860'

  # dl.dropboxusercontent.com/u/6682148 was verified as official when first introduced to the cask
  url "https://dl.dropboxusercontent.com/u/6682148/LexiLoader_v#{version}.zip"
  name 'LexiLoader'
  homepage 'http://www.pocketsoap.com/osx/lexiloader/'

  app 'LexiLoader.app'
end


text:
<?php

/**
 * PHPUnit Autoloader for GDImage Library
 * @author José Luis Quintana <quintana.io>
 */

date_default_timezone_set('America/Lima');

function loader($class) {
  $file = "src/GDImage/$class.php";

  if (file_exists($file)) {
    require $file;
  }
}

spl_autoload_register('loader');


text:
Gesso Changelog
===============

Version 0.13.0 (2016-03-18)
---------------------------

- Enhancement: Expose URL parameters with `Gesso.param('<name>')`
- Enhancement: Add viewport to server's client for mobile testing
- Enhancement: Add `max-width: 100%` to canvas for resize testing
- Enhancement: Add `pointerdown`, `pointermove`, and `pointerup` for unifying mouse and touch events (use hand.js polyfill for cross-browser support)
- Enhancement: Add `keydown` and `keyup` for basic keyboard input
- Enhancement: Send CLI errors to `stderr` instead of `stdout`
- Bugfix: Move `Gesso.asset` method to protocol
- Bugfix: Prevent keyboard default only when no other DOM element is focused
- Bugfix: Explicitly check for `window` global in RAF
- Bugfix: Remove unused `bower` dependency from `package.json`
- Cleanup: Move remaining vendor file, `raf.js`, to vendor subdirectory
- Cleanup: Use JavaScript convention of only one newline between top-level functions
- License: Update license to 2016

Version 0.12.0 (2015-09-12)
---------------------------

- Enhancement: Have `Gesso` handle `preventDefault` for the click event
- Enhancement: Remove Bootstrap, FontAwesome, and jQuery dependencies
- Enhancement: Remove Bower dependency from the built-in server's frontend
  (removed Bootstrap, FontAwesome, and jQuery; added custom Bootstrap-based CSS reset;
  inlined source-map-support, and stacktrace.js)
- Enhancement: Build and serve `<project-name>.js` instead of `gesso-bundle.js`
- Enhancement: Allow passing in custom `argv` to `globalMain` for running the CLI from a script
- Enhancement: Build and serve client assets from `/assets` and add `Gesso.asset('<filename>')`
  helper for constructing proper asset URLs (e.g. serving from a CDN)
- Bugfix: Handle malformed logging message errors on the server
- Bugfix: Don't syntax-check .json files that are loaded with `require` in client code
- Bugfix: Serve title and script name dynamically so you don't need to re-run the server manually
- Docs: Update and clean up the examples

Version 0.11.0 (2015-05-08)
---------------------------

- API: Expose Controller.canvas.
- Enhancement: Add ability to listen to Delegate subscribes and unsubscribes.
- Enhancement: Add cross-platform Gesso.click() handler for mousedown and touchstart.
- Enhancement: Add ability to use <img id="gesso-target"> as a placeholder until script loads.
- Bugfix: Reflect default host in CLI usage help.
- Bugfix: Fix endless wait after building from the CLI.

Version 0.10.1 (2015-05-04)
---------------------------

- Bugfix: Fix Gesso.height

Version 0.10.0 (2015-02-24)
---------------------------

- Enhancement: Allow inspection of Delegate's handlers and clean up
- Enhancement: Always show the version when running Gesso, and show the locally installed version on `-v`
- Enhancement: Switch to Browserify to allow requiring of built-in Node.js modules
- Enhancement: Show Node.js-like errors in the browser, including the original stack trace and the source line
- Bugfix: Use `gesso build` like the usage shows, instead of accepting the old `gesso bundle`
- Bugfix: Add missing `bower` dependency to `package.json`
- Readme: Separate out `npm install -S gesso` step
- Readme: Update example code and `hello` project

Version 0.9.0 (2015-02-18)
--------------------------

- Breaking Change: Rename `gesso bundle` to `gesso build`
- Breaking Change: API changes
- Enhancement: Hide auxiliary HTTP requests and add --log-all for showing them again
- Enhancement: Add -o alias to bundle command
- Enhancement: Bundle an index.html to play without programming and add --no-index to bundle without it
- Enhancement: Add project name to the page title
- Enhancement: Show build errors in magenta
- Enhancement: Show errors from the client (in red)
- Enhancement: Add Gesso class with update and render delegates, hooks for plugins, and logging to the server
- License: Update license to 2015 and switch to MIT

Version 0.8.5 (2014-10-21)
--------------------------

Testing: Test the build system.

Version 0.8.4 (2014-10-21)
--------------------------

Bugfix: Fix jQuery link.

Version 0.8.1 (2014-10-21)
--------------------------

Bugfix: Add `bower install` to build.

Version 0.8.0 (2014-10-20)
--------------------------

First public preview release.


text:
{{authCtrl.signup ? "Create Account":"Login"}}

  <form data-ng-submit="authCtrl.authenticate(authCtrl.user)">
    Username:
    <input name="username" type="text" required data-ng-model="authCtrl.user.username">

    Password:
    <input name="password" type="password" required data-ng-model="authCtrl.user.password">

    Confirm Password:
    <input data-ng-if="authCtrl.signup" name="confirmation" required type="password" data-ng-keyup="authCtrl.confirm(authCtrl.user.confirmation)" data-ng-model="authCtrl.user.confirmation">

    <button type="submit" name="button" data-ng-model="button" data-ng-disabled="authCtrl.invalid">{{authCtrl.buttonText}}</button>

{{authCtrl.signup ? "Already have an account, ":"Don't have an account, "}}
      {{authCtrl.signup ? "Login":"Create Account"}}

  </form>


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.WiresExt;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssetModels;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfTypeAsset;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;

namespace TTC2017.SmartGrids.CIM.IEC61968.AssetModels
{

    /// <summary>
    /// The public interface for CableInfo
    /// </summary>
    [DefaultImplementationTypeAttribute(typeof(CableInfo))]
    [XmlDefaultImplementationTypeAttribute(typeof(CableInfo))]
    public interface ICableInfo : IModelElement, IConductorInfo
    {

        /// <summary>
        /// The sheathAsNeutral property
        /// </summary>
        bool SheathAsNeutral
        {
            get;
            set;
        }

        /// <summary>
        /// The isStrandFill property
        /// </summary>
        bool IsStrandFill
        {
            get;
            set;
        }

        /// <summary>
        /// The outerJacketKind property
        /// </summary>
        Nullable<CableOuterJacketKind> OuterJacketKind
        {
            get;
            set;
        }

        /// <summary>
        /// The constructionKind property
        /// </summary>
        Nullable<CableConstructionKind> ConstructionKind
        {
            get;
            set;
        }

        /// <summary>
        /// The diameterOverScreen property
        /// </summary>
        float DiameterOverScreen
        {
            get;
            set;
        }

        /// <summary>
        /// The nominalTemperature property
        /// </summary>
        float NominalTemperature
        {
            get;
            set;
        }

        /// <summary>
        /// The diameterOverJacket property
        /// </summary>
        float DiameterOverJacket
        {
            get;
            set;
        }

        /// <summary>
        /// The diameterOverCore property
        /// </summary>
        float DiameterOverCore
        {
            get;
            set;
        }

        /// <summary>
        /// The diameterOverInsulation property
        /// </summary>
        float DiameterOverInsulation
        {
            get;
            set;
        }

        /// <summary>
        /// The shieldMaterial property
        /// </summary>
        Nullable<CableShieldMaterialKind> ShieldMaterial
        {
            get;
            set;
        }

        /// <summary>
        /// The DuctBankInfo property
        /// </summary>
        IDuctInfo DuctBankInfo
        {
            get;
            set;
        }

        /// <summary>
        /// Gets fired before the SheathAsNeutral property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> SheathAsNeutralChanging;

        /// <summary>
        /// Gets fired when the SheathAsNeutral property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> SheathAsNeutralChanged;

        /// <summary>
        /// Gets fired before the IsStrandFill property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> IsStrandFillChanging;

        /// <summary>
        /// Gets fired when the IsStrandFill property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> IsStrandFillChanged;

        /// <summary>
        /// Gets fired before the OuterJacketKind property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> OuterJacketKindChanging;

        /// <summary>
        /// Gets fired when the OuterJacketKind property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> OuterJacketKindChanged;

        /// <summary>
        /// Gets fired before the ConstructionKind property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ConstructionKindChanging;

        /// <summary>
        /// Gets fired when the ConstructionKind property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ConstructionKindChanged;

        /// <summary>
        /// Gets fired before the DiameterOverScreen property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverScreenChanging;

        /// <summary>
        /// Gets fired when the DiameterOverScreen property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverScreenChanged;

        /// <summary>
        /// Gets fired before the NominalTemperature property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NominalTemperatureChanging;

        /// <summary>
        /// Gets fired when the NominalTemperature property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> NominalTemperatureChanged;

        /// <summary>
        /// Gets fired before the DiameterOverJacket property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverJacketChanging;

        /// <summary>
        /// Gets fired when the DiameterOverJacket property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverJacketChanged;

        /// <summary>
        /// Gets fired before the DiameterOverCore property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverCoreChanging;

        /// <summary>
        /// Gets fired when the DiameterOverCore property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverCoreChanged;

        /// <summary>
        /// Gets fired before the DiameterOverInsulation property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverInsulationChanging;

        /// <summary>
        /// Gets fired when the DiameterOverInsulation property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DiameterOverInsulationChanged;

        /// <summary>
        /// Gets fired before the ShieldMaterial property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ShieldMaterialChanging;

        /// <summary>
        /// Gets fired when the ShieldMaterial property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> ShieldMaterialChanged;

        /// <summary>
        /// Gets fired before the DuctBankInfo property changes its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DuctBankInfoChanging;

        /// <summary>
        /// Gets fired when the DuctBankInfo property changed its value
        /// </summary>
        event System.EventHandler<ValueChangedEventArgs> DuctBankInfoChanged;
    }
}


text:
layout: event
categories: eventolocale
title:  "Banchetto AISF Torino"
CL: Torino
locandina:
gallery:
report:
facebook:
link:
---


text:
[![NPM](https://nodei.co/npm/esmangle-webpack-plugin.png)](http://github.com/bholloway/esmangle-webpack-plugin)

A minifier for Webpack based on [ESMangle](https://github.com/estools/esmangle).

Almost as effective as the [Uglify plugin](http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin) whilst significantly **faster**.

Use this plugin **all the time** so that you are developing the same code that you will deploy. Avoid surprises in production, particularly with **Angular** based projects.

## Usage

```javascript
var ESMangleWebpackPlugin = require('esmangle-webpack-plugin');
{
  plugins : [
    new ESMangleWebpackPlugin()
  ]
}
```

It is possible to pass `options` to the constructor, but this is normally not required. By default the plugin will produce a compressed output for all `.js` files.

## How it works

Esprima parses the code into an Abstract Syntax Tree (AST). This is passed to **esmangle** which renames variables but does not compress the code. The AST is rendered back to Javascript by applying **escodegen** with `options.format`.

The default constructor is equivalent to the following.

```javascript
new ESMangleWebpackPlugin({
	test  : /\.js($|\?)/i,
	format: {
		renumber   : true,
		hexadecimal: true,
		escapeless : true,
		compact    : true,
		semicolons : false,
		parentheses: false
	}
})
```


text:
#include <burger.h>

/* If TRUE then all NonFatal errors are fatal ones */

Boolean BombFlag = TRUE;


text:
class MissingParameterException(Exception):
  pass

def FillInParameter(parameter, value, template):
  if parameter not in template:
    raise MissingParameterException('Did not find parameter %s in template.' %
                                    parameter)

  return template.replace(parameter, value)


text:
import {Request, Response} from 'express';
import wrapAsync from './../../../framework/server/express/wrapAsync';
import invoke from './../../../framework/server/invoke/invoke';
import IDB from './../../../framework/server/database/IDB';
import PasswordUtils from './../../../framework/server/password/PasswordUtils';
import GetUser from '../api/commands/User/GetUser';
import NewUser from '../api/commands/User/NewUser';
import ClosePopup from './ClosePopup';

var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

interface AuthRoutesSettings {
  config: any;
  webserver: any;
  db: IDB;
  passwordUtils: PasswordUtils;
}

export default class AuthRoutes {

  settings: AuthRoutesSettings;

  constructor(settings: AuthRoutesSettings) {
    this.settings = settings;
  }

  setup() {
    var { webserver, config, db, passwordUtils } = this.settings;

    passport.use(new FacebookStrategy({
        clientID: config.oauth.facebook.facebook_api_key,
        clientSecret: config.oauth.facebook.facebook_api_secret,
        callbackURL: '/auth/facebook/callback',
        profileFields: ['id', 'email', 'displayName', 'name', 'gender', 'link', 'locale', 'timezone', 'photos']
      },

      function(accessToken, refreshToken, profile, done) {

        console.log("fbuser:"+JSON.stringify(profile, null, 2));

        var run = async () => {
          var user = await invoke(new GetUser({query: {provider: 'fb', provider_id: profile.id}, db}));
          console.log("user:"+JSON.stringify(user));
          if (user) {
            return done(null, user);
          } else {
            console.log('Create new user');
            user = await invoke(new NewUser({first_name: profile.name.givenName, last_name: profile.name.familyName, picurl: profile.photos[0].value, provider: 'fb', provider_id: profile.id, db, passwordUtils}));
            console.log('New user:', JSON.stringify(user, null, 2));
            return done(null, user)
          }
        }

        try {
          run().catch(console.error);
        } catch (e) {
          console.log(e);
        }
        // process.nextTick(function () {
        //   //Check whether the User exists or not using profile.id
        //   //Further DB code.
        //   profile.user_id="00000444000555";
        //   return done(null, profile);
        // });

      }
    ));

    passport.serializeUser(function(user, done) {
      console.log('passport.serializeUser', user);
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
      console.log('passport.deserializeUser', id);
        done(null, {id})
      // User.findById(id, function(err, user) {
      //   done(err, user);
      // });
    });

    webserver.use(passport.initialize());
    webserver.use(passport.session());
    webserver.get('/auth/closepopup', (req, res) => res.send(ClosePopup()));
    webserver.get('/auth/facebook', passport.authenticate('facebook', {session: false, scope: []}));
    webserver.get('/auth/facebook/callback',
      passport.authenticate('facebook', { session: false, failureRedirect: '/auth/closepopup' }),
      (req, res) => {
        res.cookie('user', req.user.id, {
          signed: true,
          maxAge: 365 * 24 * 60 * 60 * 1000, //1 year
          httpOnly: true
        });
        res.cookie('authprovider', 'fb', {
          signed: true,
          maxAge: 365 * 24 * 60 * 60 * 1000, //1 year
          httpOnly: true
        });
        res.redirect('/auth/closepopup');
     }
    );
  }

}


text:
using System.Configuration;

namespace Wimt.CachingFramework.Configuration
{
    public class InMemoryCacheElementCollection : ConfigurationElementCollection
    {
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }

        protected override string ElementName
        {
            get
            {
                return "inMemoryCache";
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new InMemoryCacheElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((InMemoryCacheElement)element).Name;
        }
    }
}


text:
sudo pip install -U platformio

# update PlatformIO
platformio update


text:
<?php

/**
 * CacheHelper.
 *
 * @package    symfony
 * @subpackage helper
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */

/* Usage

<?php if (!cache('name')): ?>

... HTML ...

  <?php cache_save() ?>
<?php endif; ?>

*/
function cache($name, $lifeTime = 86400)
{
  $context = sfContext::getInstance();

  if (!sfConfig::get('sf_cache'))
  {
    return null;
  }

  $request = $context->getRequest();
  $cache   = $context->getViewCacheManager();

  if (!is_null($request->getAttribute('started', null, 'symfony/action/sfAction/cache')))
  {
    throw new sfCacheException('Cache already started');
  }

  $data = $cache->start($name, $lifeTime);

  if ($data === null)
  {
    $request->setAttribute('started', 1, 'symfony/action/sfAction/cache');
    $request->setAttribute('current_name', $name, 'symfony/action/sfAction/cache');

    return 0;
  }
  else
  {
    echo $data;

    return 1;
  }
}

function cache_save()
{
  $context = sfContext::getInstance();

  if (!sfConfig::get('sf_cache'))
  {
    return null;
  }

  $request = $context->getRequest();

  if (is_null($request->getAttribute('started', null, 'symfony/action/sfAction/cache')))
  {
    throw new sfCacheException('Cache not started');
  }

  $name = $request->getAttribute('current_name', '', 'symfony/action/sfAction/cache');

  $data = $context->getViewCacheManager()->stop($name);

  $request->setAttribute('started', null, 'symfony/action/sfAction/cache');
  $request->setAttribute('current_name', null, 'symfony/action/sfAction/cache');

  echo $data;
}


text:
from .cameras import XSyncCamera, YSyncCamera
from .picker import Picker, ROI_time_series
from .probe_view import probe_view
from .color_scheme import palette
from .widgets import param_widget
from .line_view import line_view
#  from .raster_view import raster_view
from .spike_view import spike_view
from .scatter_3d_view import scatter_3d_view
from .wave_view import wave_view
from .correlogram_view import correlogram_view
# from .cluster_view import cluster_view
from .scatter_2d_view import scatter_2d_view
from .raster_view import raster_view
from .amplitude_view import amplitude_view
from .firing_rate_view import firing_rate_view
from .trace_view import trace_view
from .ctree_view import ctree_view
from .volume_view import volume_view
from .pf_view import pf_view
from .image_view import image_view
from .cluster_view import cluster_view
from .grid_scatter3d import grid_scatter3d


text:
<?php

namespace vxPHP\Form\FormElement;

/**
 * input element of type "image"
 *
 * @author Gregor Kofler
 */
class ImageElement extends InputElement
{
	/**
	 * inialize a <input type="image"> element instance
	 *
	 * @param string $name
	 * @param string $src
	 */
	public function __construct(string $name, string $src)
    {
		parent::__construct($name, $src);
		$this->setAttribute('alt', pathinfo($src, PATHINFO_FILENAME));
	}

	/**
	 * (non-PHPdoc)
	 * @see \vxPHP\Form\FormElement\InputElement::render()
	 */
	public function render($force = false): string
    {
        if(empty($this->html) || $force) {

            $attr = [
                sprintf('src="%s"', $this->getValue()),
                'type="image"'
            ];

            foreach($this->attributes as $k => $v) {

                if(in_array(strtolower($k), ['src', 'value', 'type'])) {
                    continue;
                }
                $attr[] = sprintf('%s="%s"', $k, $v);

            }

            $this->html = sprintf('<input name="%s" %s>',
                $this->getName(),
                implode(' ', $attr)
            );

        }

        return $this->html;
	}
}


text:
'use strict';

// Dependencies
var knex = require('knex').knex;

// Session Schema
knex.schema.hasTable('place').then(function(exists) {
  if (!exists) {
    return knex.schema.createTable('place', function(table) {

      // Unique key that identifies a place name.
      table.increments('id').primary().unique();

      // A point date or date range describing when this place was in existence.
      table.specificType('existence_date', 'daterange').notNullable();

      // Describes the order of the PLACE-PARTs.
      table.string('ascending_descending_none').notNullable().defaultTo('none');

      table.timestamp('created_at').notNullable();
      table.timestamp('updated_at').notNullable();
    });
  }
});


text:
package com.boonto.order.controller;

import com.boonto.order.config.exception.BusinessException;
import com.boonto.order.entity.OrdIndex_Entity;
import com.boonto.order.service.OrdIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by neil on 16/5/17.
 */
@RestController
@Scope("prototype")
public class aa {
    @Autowired
    OrdIndexService ordIndexService;

    @RequestMapping("/save")
    @ResponseBody
    public void save() throws BusinessException {
        OrdIndex_Entity ordIndexEntity;
        ordIndexEntity = new OrdIndex_Entity();
        ordIndexEntity.setId(97);
        ordIndexEntity.setUserName("eca");
        ordIndexService.save(ordIndexEntity);
    }
}


text:
//
//  Parser.m
//  BlockML
//
//  Created by Lindemann on 27.08.12.
//  Copyright (c) 2012 Lindemann. All rights reserved.
//

#import "Parser.h"
#import "Scanner.h"
#import "Token.h"
#import "HTMLTree.h"

@interface Parser ()

@property (nonatomic, strong) Scanner *scanner;
@property (nonatomic, strong) Token *token;

@end

@implementation Parser

- (id)initWithString:(NSString*)string {
    if(self = [super init]) {
        self.string = string;
        self.scanner = [Scanner scannerWithString:string];
        self.document = [HTMLDocument new];
    }
    return self;
}

+ (id)parserWithString:(NSString*)string {
    return [[Parser alloc] initWithString:string];
}

- (void)scannerOutput {
    while (self.token.type != END) {
        self.token = [self.scanner getToken];
        NSLog(@"%@", self.token);
    }
}

- (void)startParsing {
//    [self scannerOutput];

//    [Token printAllTokenWithDelimiter:@" "];

    while (self.token.type != END) {
        self.token = [self.scanner getToken];
        [self documentWithParent:self.document];
    }
    [self.document generateHTML];
//    NSLog(@"%@", self.token);
}

- (void)nextToken {
//    NSLog(@"%@", self.token);
    self.token = [self.scanner getToken];
}

- (void)errorWithParent:(HTMLElement*)parent andErrorMessage:(NSString*)message {
    Error *error = [Error new];
    Text *text = [Text new];
    text.string = [NSString stringWithFormat:@"Error with %@", message];
    [error addElement:text];
    [parent addElement:error];
}

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

/*                                     PRODUCTION RULES                                         */

/*//////////////////////////////////////////////////////////////////////////////////////////////*/
#pragma mark - Production Rules

- (void)documentWithParent:(HTMLElement*)parent {
    // Everything
    while (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= TITLE_SB)) {
        // STRING & Inline Tags
        if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
            Paragraph *paragraph = [Paragraph new];
            [parent addElement:paragraph];
            [self textBlock:paragraph];
        }
        // Block Tags
        [self blockTag:parent];
    }
}

//- (void)bracketsWithParent:(HTMLElement*)parent {
//    // Keep Parsing to find Erros
//    BOOL error;
//    while (self.token.type == OPEN_SB || self.token.type == CLOSE_SB) {
//        error = YES;
//        [self nextToken];
//    }
//    if (error) {
//        [self errorWithParent:parent andErrorMessage:@"Brackets"];
//        error = NO;
//    }
//}

- (void)inlineTag:(HTMLElement*)parent {
    [self link:parent];
    [self identifier:parent];
    [self inlineMath:parent];
    [self footnote:parent];
    [self styleModifier:parent];
    [self inlineHTML:parent];
}

- (void)blockTag:(HTMLElement*)parent {
    [self tableOfContent:parent];
    [self section:parent];
    [self title:parent];
    [self code:parent];
    [self image:parent];
    [self unorderedList:parent];
    [self orderedList:parent];
    [self caption:parent];
    [self bibliography:parent];
    [self quote:parent];
    [self math:parent];

    [self table:parent];
    // Not really Block Tags but keep parsing
    [self tableData:parent];
    [self tableHeader:parent];
    [self tableRow:parent];

    [self heading:parent];
    [self head:parent];
    [self pageBreak:parent];
    [self html:parent];
}

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

/*                                            TEXT                                              */

/*//////////////////////////////////////////////////////////////////////////////////////////////*/
#pragma mark - Text

- (void)textBlock:(HTMLElement*)parent {
    if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
        [self text:parent];
        if (self.token.type == LF) {
            [self nextToken];

            // Parent for paragraph depends on from which methode
            // - textBlock: was invoked
            if ([parent isKindOfClass:[HTMLDocument class]]) {
                [self paragraph:parent];
            } else {
                // Parent is paragraph
                [self paragraph:parent.parent];
            }

            if (self.token.type != LF) {
                if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
                    LineBreak *lineBreak = [LineBreak new];
                    [parent addElement:lineBreak];
                }
                [self textBlock:parent];
            }
        }
    }
}

- (void)text:(HTMLElement*)parent {
    if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
        if (self.token.type == STRING) {

            Text *text = [Text new];
            [parent addElement:text];
            text.string = self.token.value;

            [self nextToken];
        }
        [self inlineTag:parent];
        while (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
            if (self.token.type == STRING) {

                Text *text = [Text new];
                [parent addElement:text];
                text.string = self.token.value;

                [self nextToken];
            }
            [self inlineTag:parent];
        }
    }
}

- (void)paragraph:(HTMLElement*)parent {
    if (self.token.type == LF) {
        [self nextToken];
        while (self.token.type == LF) {
            [self nextToken];
        }

        if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {

            Paragraph *paragraph = [Paragraph new];
            [parent addElement:paragraph];
            [self textBlock:paragraph];
        }
    }
}

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

/*                                         INLINE TAGS                                          */

/*//////////////////////////////////////////////////////////////////////////////////////////////*/
#pragma mark - Inline Tags

- (void)link:(HTMLElement*)parent {
    // a[
    if (self.token.type == A_SB) {
        Link *link = [Link new];
        [parent addElement:link];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            link.href = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // ![
            if (self.token.type != OPEN_SB && link.href) {
                Text *text = [Text new];
                [link addElement:text];
                text.string = link.href;
            }
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // STRING
                if (self.token.type == STRING) {
                    Text *text = [Text new];
                    [link addElement:text];
                    text.string = self.token.value;
                    [self nextToken];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Link"];
                }
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Link"];
        }
    }
}

- (void)identifier:(HTMLElement*)parent {
    // id[
    if (self.token.type == ID_SB) {
        Identifier *identifier = [Identifier new];
        [parent addElement:identifier];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            identifier.identfier = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"ID"];
        }
    }
}

- (void)inlineMath:(HTMLElement*)parent {
    // math[
    if (self.token.type == IM_SB) {
        InlineMath *inlineMath = [InlineMath new];
        [parent addElement:inlineMath];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            self.document.mathJax = YES;;
            Text *text = [Text new];
            text.string = self.token.value;
            [inlineMath addElement:text];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Inline Math"];
        }
    }
}

- (void)footnote:(HTMLElement*)parent {
    // fn[
    if (self.token.type == FN_SB) {
        Footnote *footnote = [Footnote new];
        [parent addElement:footnote];
        [self nextToken];
        // text
        if (self.token.type == STRING) {
            Endnote *endnote = [Endnote new];
            footnote.endnote = endnote;
            // Insert a " " infront of the string
            NSString *tmpValueString = [NSString  stringWithFormat:@" %@",self.token.value];
            self.token.value = tmpValueString;
            [self text:endnote];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Footnote"];
        }
    }
}

- (void)styleModifier:(HTMLElement*)parent {
    // $styleModifier[
    if (self.token.type >= SUB_SB && self.token.type <= U_SB) {
        StyleModifier *styleModifier = [StyleModifier new];
        [parent addElement:styleModifier];

        NSString *errorString;

        switch (self.token.type) {
            case M_SB:
                styleModifier.style = MARKED;
                errorString = @"Marked Style";
                break;
            case B_SB:
                styleModifier.style = BOLD;
                errorString = @"Bold Style";
                break;
            case U_SB:
                styleModifier.style = UNDERLINE;
                errorString = @"Underline Style";
                break;
            case C_SB:
                styleModifier.style = CODE;
                errorString = @"Inline Code";
                break;
            case I_SB:
                styleModifier.style = ITALIC;
                errorString = @"Italic Style";
                break;
            case S_SB:
                styleModifier.style = STRIKETHROUGH;
                errorString = @"Strikethrough Style";
                break;
            case SUB_SB:
                styleModifier.style = SUB;
                errorString = @"Sub Style";
                break;
            case SUP_SB:
                styleModifier.style = SUP;
                errorString = @"Sup Style";
                break;
            default:
                break;
        }
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Text *text = [Text new];
            text.string = self.token.value;

            [styleModifier addElement:text];
            [self nextToken];

//            [self text:styleModifier];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:errorString];
        }
    }
}

- (void)inlineHTML:(HTMLElement*)parent {
    // ihtml[
    if (self.token.type == IH_SB) {
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Text *text = [Text new];
            text.string = self.token.value;
            [parent addElement:text];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Inline HTML"];
        }
    }
}

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

/*                                          BLOCK TAGS                                          */

/*//////////////////////////////////////////////////////////////////////////////////////////////*/
#pragma mark - Block Tags

- (void)tableOfContent:(HTMLElement*)parent {
    // toc[
    if (self.token.type == TOC_SB) {
        TableOfContent *tableOfContent = [TableOfContent new];
        self.document.tableOfContent = tableOfContent;
        [parent addElement:tableOfContent];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Heading *heading = [Heading new];
            heading.level = 1;
            Text *text = [Text new];
            text.string = self.token.value;
            [heading addElement:text];
            [tableOfContent addElement:heading];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Table of Content"];
        }
    }
}

- (void)section:(HTMLElement*)parent {
    // sec[
    if (self.token.type == SEC_SB) {
        Section *section = [Section new];
        Heading *heading = [Heading new];
        Text *text = [Text new];
        text.string = @"";
        [section addElement:heading];
        [heading addElement:text];
        [parent addElement:section];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            text.string = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // document
                [self documentWithParent:section];
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                    // [
                    if (self.token.type == OPEN_SB) {
                        [self nextToken];
                        // STRING
                        if (self.token.type == STRING) {
                            section.identfier = self.token.value;
                            [self nextToken];
                        }
                        // ]
                        if (self.token.type == CLOSE_SB) {
                            [self nextToken];
                        } else {
                            [self errorWithParent:parent andErrorMessage:@"Section"];
                        }
                    }
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Section"];
                }
            } else {
                [self errorWithParent:parent andErrorMessage:@"Section"];
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Section"];
        }
    }
}

- (void)title:(HTMLElement*)parent {
    // title[
    if (self.token.type == TITLE_SB) {
        Heading *heading = [Heading new];
        heading.level = 1;
        [heading.attributes setValue:@"title" forKey:ID];
        [parent addElement:heading];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Text *text = [Text new];
            text.string = self.token.value;
            [heading addElement:text];
            self.document.title = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Title"];
        }
    }
}

- (void)code:(HTMLElement*)parent {
    // code[
    if (self.token.type == CODE_SB) {
        Code *code = [Code new];
        [parent addElement:code];
        self.document.highlight = YES;
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            code.language = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // STRING
                if (self.token.type == STRING) {
                    Text *text = [Text new];
                    text.string = self.token.value;
                    [code addElement:text];
                    [self nextToken];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Code"];
                }
            } else {
                [self errorWithParent:parent andErrorMessage:@"Code"];
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Code"];
        }
    }
}

- (void)image:(HTMLElement*)parent {
    // img[
    if (self.token.type == IMG_SB) {
        Image *image = [Image new];
        [parent addElement:image];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            image.source = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // STRING
                if (self.token.type == STRING) {
                    NSRange searchStringRange = [self.token.value rangeOfString:@"," options:NSCaseInsensitiveSearch];
                    if (searchStringRange.location != NSNotFound) {
                        NSString *tmpIntValue = [[self.token.value componentsSeparatedByString:@","] objectAtIndex:0];
                        image.witdh = [tmpIntValue intValue];
                        tmpIntValue = [[self.token.value componentsSeparatedByString:@","] objectAtIndex:1];
                        image.height = [tmpIntValue intValue];
                    } else {
                        [self errorWithParent:parent andErrorMessage:@"Image"];
                    }
                    [self nextToken];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Image"];
                }
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Image"];
        }
    }
}

- (void)unorderedList:(HTMLElement*)parent {
    // ul[
    if (self.token.type == UL_SB) {
        UnorderedList *unorderedList = [UnorderedList new];
        [parent addElement:unorderedList];
        [self nextToken];
        // STRING | List | LF
        while (self.token.type == STRING ||
               (self.token.type >= A_SB && self.token.type <= ID_SB) ||
               self.token.type == UL_SB || self.token.type == OL_SB ||
               self.token.type == LF) {
            [self listItem:unorderedList];
            [self unorderedList:unorderedList];
            [self orderedList:unorderedList];
            if (self.token.type == LF) {
                [self nextToken];
            }
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Unordered List"];
        }
    }
}

- (void)orderedList:(HTMLElement*)parent {
    // ol[
    if (self.token.type == OL_SB) {
        OrderedList *orderedList = [OrderedList new];
        [parent addElement:orderedList];
        [self nextToken];
        // STRING | List | LF
        while (self.token.type == STRING ||
               (self.token.type >= A_SB && self.token.type <= ID_SB) ||
               self.token.type == UL_SB || self.token.type == OL_SB ||
               self.token.type == LF) {
            [self listItem:orderedList];
            [self unorderedList:orderedList];
            [self orderedList:orderedList];
            if (self.token.type == LF) {
                [self nextToken];
            }
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Ordered List"];
        }
    }

}

- (void)listItem:(HTMLElement*)parent {
    if (self.token.type == STRING || (self.token.type >= A_SB && self.token.type <= ID_SB)) {
        ListItem *listItem = [ListItem new];
        [parent addElement:listItem];
        [self text:listItem];
    }
}

- (void)caption:(HTMLElement*)parent {
    // caption[
    if (self.token.type == CAP_SB) {
        Caption *caption = [Caption new];
        [parent addElement:caption];
        Span *span = [Span new];
        [caption addElement:span];
        // If cap[]
        caption.captionDescription = @" ";
        [self nextToken];
        // STRING eg. Figure
        if (self.token.type == STRING) {
            caption.captionDescription = self.token.value;
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // text
                [self text:caption];
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                    // [
                    if (self.token.type == OPEN_SB) {
                        [self nextToken];
                        // STRING eg. FDERT
                        if (self.token.type == STRING) {
                            caption.identfier = self.token.value;
                            [self nextToken];
                        }
                        if (self.token.type == CLOSE_SB) {
                            [self nextToken];
                        } else {
                            [self errorWithParent:parent andErrorMessage:@"Caption"];
                        }
                    }
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Caption"];
                }
            } else {
                [self errorWithParent:parent andErrorMessage:@"Caption"];
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Caption"];
        }
    }
}

- (void)bibliography:(HTMLElement*)parent {
    // bib[
    if (self.token.type == BIB_SB) {
        Bibliography *bibliography = [Bibliography new];
        [parent addElement:bibliography];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            bibliography.identfier = self.token.value;
            bibliography.linkString = self.token.value;
            Link *link = [Link new];
            [bibliography addElement:link];
            bibliography.href = self.token.value;
            link.href = bibliography.href;
            Text *text = [Text new];
            text.string = bibliography.linkString;
            [link addElement:text];

            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // text
                Paragraph *paragraph = [Paragraph new];
                [bibliography addElement:paragraph];
                [self text:paragraph];
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Bibliography"];
                }
            } else {
                [self errorWithParent:parent andErrorMessage:@"Bibliography"];
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Bibliography"];
        }
    }
}

- (void)quote:(HTMLElement*)parent {
    // q[
    if (self.token.type == Q_SB) {
        Quote *quote = [Quote new];
        [parent addElement:quote];
        [self nextToken];
        // textBlock
        if (self.token.type == STRING) {
            Paragraph *paragraph = [Paragraph new];
            [quote addElement:paragraph];
            [self textBlock:paragraph];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // text
                if (self.token.type == STRING) {
                    Source *source = [Source new];
                    [quote addElement:source];
                    [self text:source];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Quote"];
                }
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Quote"];
        }
    }
}

- (void)math:(HTMLElement*)parent {
    // math[
    if (self.token.type == MATH_SB) {
        Math *math = [Math new];
        [parent addElement:math];
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            self.document.mathJax = YES;
            Text *text = [Text new];
            text.string = self.token.value;
            [math addElement:text];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Math"];
        }
    }
}

- (void)table:(HTMLElement*)parent {
    // table[
    if (self.token.type == TABLE_SB) {
        Table *table = [Table new];
        [parent addElement:table];
        [self nextToken];
        // tableRow
        while (self.token.type == TR_SB) {
            [self tableRow:table];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Table"];
        }
    }
}

- (void)tableRow:(HTMLElement*)parent {
    // tr[
    if (self.token.type == TR_SB) {
        TableRow *tableRow = [TableRow new];
        [parent addElement:tableRow];
        [self nextToken];
        // TableHeader || TableData
        while (self.token.type == TH_SB ||
               self.token.type == TD_SB) {
            [self tableHeader:tableRow];
            [self tableData:tableRow];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Table Row"];
        }
    }
}

- (void)tableHeader:(HTMLElement*)parent {
    // th[
    if (self.token.type == TH_SB) {
        TableHeader *tableHeader = [TableHeader new];
        [parent addElement:tableHeader];
        [self nextToken];
        // Document
        [self documentWithParent:tableHeader];
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // STRING
                if (self.token.type == STRING) {
                    NSRange searchStringRange = [self.token.value rangeOfString:@":" options:NSCaseInsensitiveSearch];
                    if (searchStringRange.location != NSNotFound) {
                        NSString *tmpIntValue = [[self.token.value componentsSeparatedByString:@":"] objectAtIndex:0];
                        if ([tmpIntValue isEqual:@"v"]) {
                            tableHeader.spanDirection = VERTICAL;
                        }
                        if ([tmpIntValue isEqual:@"h"]) {
                            tableHeader.spanDirection = HORIZONTAL;
                        }
                        tmpIntValue = [[self.token.value componentsSeparatedByString:@":"] objectAtIndex:1];
                        tableHeader.spanWidth = [tmpIntValue intValue];
                    } else {
                        [self errorWithParent:parent andErrorMessage:@"Table Header"];
                    }
                    [self nextToken];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Table Header"];
                }
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Table Header"];
        }
    }
}

- (void)tableData:(HTMLElement*)parent {
    // td[
    if (self.token.type == TD_SB) {
        TableData *tableData = [TableData new];
        [parent addElement:tableData];
        [self nextToken];
        // Document
        [self documentWithParent:tableData];
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
            // [
            if (self.token.type == OPEN_SB) {
                [self nextToken];
                // STRING
                if (self.token.type == STRING) {
                    NSRange searchStringRange = [self.token.value rangeOfString:@":" options:NSCaseInsensitiveSearch];
                    if (searchStringRange.location != NSNotFound) {
                        NSString *tmpIntValue = [[self.token.value componentsSeparatedByString:@":"] objectAtIndex:0];
                        if ([tmpIntValue isEqual:@"v"]) {
                            tableData.spanDirection = VERTICAL;
                        }
                        if ([tmpIntValue isEqual:@"h"]) {
                            tableData.spanDirection = HORIZONTAL;
                        }
                        tmpIntValue = [[self.token.value componentsSeparatedByString:@":"] objectAtIndex:1];
                        tableData.spanWidth = [tmpIntValue intValue];
                    } else {
                        [self errorWithParent:parent andErrorMessage:@"Table Data"];
                    }
                    [self nextToken];
                }
                // ]
                if (self.token.type == CLOSE_SB) {
                    [self nextToken];
                } else {
                    [self errorWithParent:parent andErrorMessage:@"Table Data"];
                }
            }
        } else {
            [self errorWithParent:parent andErrorMessage:@"Table Data"];
        }
    }
}

- (void)heading:(HTMLElement*)parent {
    // title[
    if (self.token.type >= H1_SB && self.token.type <= H6_SB) {
        Heading *heading = [Heading new];
        [parent addElement:heading];
        switch (self.token.type) {
            case H1_SB:
                heading.level = 1;
                break;
            case H2_SB:
                heading.level = 2;
                break;
            case H3_SB:
                heading.level = 3;
                break;
            case H4_SB:
                heading.level = 4;
                break;
            case H5_SB:
                heading.level = 5;
                break;
            case H6_SB:
                heading.level = 6;
                break;
            default:
                break;
        }
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Text *text = [Text new];
            text.string = self.token.value;
            [heading addElement:text];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Heading"];
        }
    }
}

- (void)head:(HTMLElement*)parent {
    // fp[
    if (self.token.type == HEAD_SB) {
        DocumentHead *frontPage = [DocumentHead new];
        [parent addElement:frontPage];
        [self nextToken];
        // Heading | Image | Title
        while ((self.token.type >= H1_SB && self.token.type <= H6_SB) ||
               self.token.type == IMG_SB ||
               self.token.type == TITLE_SB) {
            [self heading:frontPage];
            [self image:frontPage];
            [self title:frontPage];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"Front Page"];
        }
    }
}

- (void)pageBreak:(HTMLElement*)parent {
    // pb[
    if (self.token.type == PB_SB) {
        PageBreak *pageBreak = [PageBreak new];
        [parent addElement:pageBreak];
        [self nextToken];
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"TITLE"];
        }
    }
}

- (void)html:(HTMLElement*)parent {
    // html[
    if (self.token.type == HTML_SB) {
        [self nextToken];
        // STRING
        if (self.token.type == STRING) {
            Text *text = [Text new];
            text.string = [HTMLStringBuilder text:self.token.value indentation:0 lineBreak:YES];
            [parent addElement:text];
            [self nextToken];
        }
        // ]
        if (self.token.type == CLOSE_SB) {
            [self nextToken];
        } else {
            [self errorWithParent:parent andErrorMessage:@"HTML"];
        }
    }
}

@end


text:
package iotanalytics

import (
	"github.com/aws/aws-sdk-go/private/protocol"
)

const (

	// ErrCodeInternalFailureException for service response error code
	// "InternalFailureException".
	//
	// There was an internal failure.
	ErrCodeInternalFailureException = "InternalFailureException"

	// ErrCodeInvalidRequestException for service response error code
	// "InvalidRequestException".
	//
	// The request was not valid.
	ErrCodeInvalidRequestException = "InvalidRequestException"

	// ErrCodeLimitExceededException for service response error code
	// "LimitExceededException".
	//
	// The command caused an internal limit to be exceeded.
	ErrCodeLimitExceededException = "LimitExceededException"

	// ErrCodeResourceAlreadyExistsException for service response error code
	// "ResourceAlreadyExistsException".
	//
	// A resource with the same name already exists.
	ErrCodeResourceAlreadyExistsException = "ResourceAlreadyExistsException"

	// ErrCodeResourceNotFoundException for service response error code
	// "ResourceNotFoundException".
	//
	// A resource with the specified name could not be found.
	ErrCodeResourceNotFoundException = "ResourceNotFoundException"

	// ErrCodeServiceUnavailableException for service response error code
	// "ServiceUnavailableException".
	//
	// The service is temporarily unavailable.
	ErrCodeServiceUnavailableException = "ServiceUnavailableException"

	// ErrCodeThrottlingException for service response error code
	// "ThrottlingException".
	//
	// The request was denied due to request throttling.
	ErrCodeThrottlingException = "ThrottlingException"
)

var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
	"InternalFailureException":       newErrorInternalFailureException,
	"InvalidRequestException":        newErrorInvalidRequestException,
	"LimitExceededException":         newErrorLimitExceededException,
	"ResourceAlreadyExistsException": newErrorResourceAlreadyExistsException,
	"ResourceNotFoundException":      newErrorResourceNotFoundException,
	"ServiceUnavailableException":    newErrorServiceUnavailableException,
	"ThrottlingException":            newErrorThrottlingException,
}