text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<process-definition xmlns="urn:jbpm.org:jpdl-3.2" name="(SG) Expedição de outros documentos">
    <description><![CDATA[Código do fluxo: SG_EXP_OUTROSDOC..

Descrição: Fluxo destinado a expedição de outros documentos (certidão, ato ordinatório da secretaria, etc).

Raia        Localização              Papel
Secretaria  Secretaria Segundo Grau  Chefe de Secretaria
Secretaria  Secretaria Segundo Grau  Servidor Geral
Magistrado  Gabinete Segundo Grau    Magistrado
Magistrado  Assessoria Segundo Grau  Assessor para Votação Antecipada
Magistrado  Assessoria Segundo Grau  Assessor
Magistrado  Assessoria Segundo Grau  Assessor Chefe
Magistrado  Assessoria Segundo Grau  Assessor Geral..]]></description>
    <!-- SWIMLANES -->
    <swimlane name="Nó de Desvio - (SG) Expedição de outros documentos">
        <assignment actor-id="#{actor.id}"/>
    </swimlane>
    <swimlane name="Magistrado">
        <assignment pooled-actors="#{localizacaoAssignment.getPooledActors('599:1469,600:5899,600:5898,600:5197,600:5907,6:1469,5:5899,5:5898,5:5197,5:5907')}"/>
    </swimlane>
    <swimlane name="Secretaria">
        <assignment pooled-actors="#{localizacaoAssignment.getPooledActors('602:1338,602:5483,602:5906,8:1338,8:5483,8:5906')}"/>
    </swimlane>
    <!-- START-STATE -->
    <start-state name="Início">
        <task name="Tarefa inicial" priority="3"/>
        <transition to="(SG) É documento criminal?" name="(SG) É documento criminal?"/>
    </start-state>
    <!-- NODES -->
    <decision expression="#{tramitacaoProcessualService.recuperaVariavel('sg:deccolrel:outros_documentos_criminais') == true ? '(SG) Outros documentos criminais- EXPEDIR' : '(SG) Outros documentos - EXPEDIR'}" name="(SG) É documento criminal?">
        <transition to="(SG) Outros documentos - EXPEDIR" name="(SG) Outros documentos - EXPEDIR"/>
        <transition to="(SG) Outros documentos criminais- EXPEDIR" name="(SG) Outros documentos criminais- EXPEDIR"/>
    </decision>
    <task-node end-tasks="true" name="(SG) Outros documentos - EXPEDIR">
        <task name="(SG) Outros documentos - EXPEDIR" swimlane="Secretaria" priority="3">
            <controller>
                <variable name="minuta_outros_documentos" mapped-name="textEditCombo:minuta_outros_documentos" access="read,write,required"/>
                <variable name="minutarLote" mapped-name="minutarLote:minutarLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: minuta_outros_documentos
   Label: Minuta em elaboração de outros documentos
   Escrita: Sim
   Obrig.: Sim
   Tipo: Editor

2. Variável: minutarLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Minutar em Lote]]></description>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Apagar minuta não assinada de outros documentos" name="Cancelar e sair da tarefa"/>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR" name="Encaminhar para assinatura do(a) secretário(a)"/>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.gravaVariavel('minutaEmElaboracao', tramitacaoProcessualService.recuperaVariavelTarefa('textEditCombo:minuta_outros_documentos'))}"/>
            <action expression="#{not empty processoHome.idProcessoDocumento ? org.jboss.seam.bpm.processInstance.contextInstance.setVariable('minutaEmElaboracao', processoHome.idProcessoDocumento) : ''}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('TipoDocumentoTipoProcessoDocumento')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos')}"/>
        </event>
        <event type="task-create">
            <action name="upd" expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos','Cancelar e sair da tarefa')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(SG) Outros documentos criminais- EXPEDIR">
        <task name="(SG) Outros documentos criminais- EXPEDIR" swimlane="Secretaria" priority="3">
            <controller>
                <variable name="minuta_outros_documentos" mapped-name="textEditCombo:minuta_outros_documentos" access="read,write,required"/>
                <variable name="minutarLote" mapped-name="minutarLote:minutarLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: minuta_outros_documentos
   Label: Minuta em elaboração de outros documentos
   Escrita: Sim
   Obrig.: Sim
   Tipo: Editor

2. Variável: minutarLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Minutar em Lote]]></description>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Apagar minuta não assinada de outros documentos" name="Cancelar e sair da tarefa"/>
        <transition to="(SG) Outros documentos criminais - ASSINAR" name="Outros documentos criminais - ASSINAR"/>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.gravaVariavel('minutaEmElaboracao', tramitacaoProcessualService.recuperaVariavelTarefa('textEditCombo:minuta_outros_documentos'))}"/>
            <action expression="#{not empty processoHome.idProcessoDocumento ? org.jboss.seam.bpm.processInstance.contextInstance.setVariable('minutaEmElaboracao', processoHome.idProcessoDocumento) : ''}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('TipoDocumentoTipoProcessoDocumento')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos','Cancelar e sair da tarefa')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR">
        <task name="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR" swimlane="Secretaria" priority="3">
            <controller>
                <variable name="Processo_Fluxo_revisarMinuta" mapped-name="frame:Processo_Fluxo_revisarMinuta" access="read,write"/>
                <variable name="movimentacaoLote" mapped-name="movimentarLote:movimentacaoLote" access="read,write"/>
                <variable name="assinaturaLote" mapped-name="assinarLote:assinaturaLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: Processo_Fluxo_revisarMinuta
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Frame

2. Variável: movimentacaoLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Movimentação em Lote

3. Variável: assinaturaLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Assinatura em Lote]]></description>
        <transition to="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR" name="Encaminhar para assinatura do gabinete"/>
        <transition to="(SG) Lançar movimento de expedição de outros documentos" name="(SG) Lançar movimento de expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Outros documentos - EXPEDIR" name="Retornar para elaboração do documento pela secretaria"/>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{taskInstanceUtil.deleteVariableLocally('frameDefaultLeavingTransition')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavel('condicaoLancamentoMovimentosTemporario')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('frameDefaultLeavingTransition', '(SG) Lançar movimento de expedição de outros documentos')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavel('condicaoLancamentoMovimentosTemporario', '${true}')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(SG) Outros documentos - ASSINAR">
        <task name="(SG) Outros documentos - ASSINAR" swimlane="Secretaria" priority="3">
            <controller>
                <variable name="Processo_Fluxo_revisarMinuta" mapped-name="frame:Processo_Fluxo_revisarMinuta" access="read,write"/>
                <variable name="movimentacaoLote" mapped-name="movimentarLote:movimentacaoLote" access="read,write"/>
                <variable name="assinaturaLote" mapped-name="assinarLote:assinaturaLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: Processo_Fluxo_revisarMinuta
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Frame

2. Variável: movimentacaoLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Movimentação em Lote

3. Variável: assinaturaLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Assinatura em Lote]]></description>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Outros documentos - EXPEDIR" name="Retornar para expedição de outros documentos"/>
        <transition to="(SG) Lançar movimento de expedição de outros documentos" name="(SG) Lançar movimento de expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR" name="Encaminhar para assinatura do gabinete"/>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('frameDefaultLeavingTransition')"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavel('condicaoLancamentoMovimentosTemporario')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('frameDefaultLeavingTransition', '(SG) Lançar movimento de expedição de outros documentos')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavel('condicaoLancamentoMovimentosTemporario', '${true}')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(SG) Outros documentos criminais - ASSINAR">
        <task name="(SG) Outros documentos criminais - ASSINAR" swimlane="Magistrado" priority="3">
            <controller>
                <variable name="Processo_Fluxo_revisarMinuta" mapped-name="frame:Processo_Fluxo_revisarMinuta" access="read,write"/>
                <variable name="movimentacaoLote" mapped-name="movimentarLote:movimentacaoLote" access="read,write"/>
                <variable name="assinaturaLote" mapped-name="assinarLote:assinaturaLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: Processo_Fluxo_revisarMinuta
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Frame

2. Variável: movimentacaoLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Movimentação em Lote

3. Variável: assinaturaLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Assinatura em Lote]]></description>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Outros documentos criminais- EXPEDIR" name="Retornar para expedição de outros documentos criminais"/>
        <transition to="(SG) Lançar movimento de expedição de outros documentos" name="(SG) Lançar movimento de expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action/>
            <action expression="#{tramitacaoProcessualService.apagaVariavel('condicaoLancamentoMovimentosTemporario')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('frameDefaultLeavingTransition', '(SG) Lançar movimento de expedição de outros documentos')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavel('condicaoLancamentoMovimentosTemporario', '${true}')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR">
        <task name="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR" swimlane="Magistrado" priority="3">
            <controller>
                <variable name="Processo_Fluxo_revisarMinuta" mapped-name="frame:Processo_Fluxo_revisarMinuta" access="read,write"/>
                <variable name="movimentacaoLote" mapped-name="movimentarLote:movimentacaoLote" access="read,write"/>
                <variable name="assinaturaLote" mapped-name="assinarLote:assinaturaLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: Processo_Fluxo_revisarMinuta
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Frame

2. Variável: movimentacaoLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Movimentação em Lote

3. Variável: assinaturaLote
   Label:
   Escrita: Sim
   Obrig.: Não
   Tipo: Habilitar Assinatura em Lote]]></description>
        <transition to="(SG) Lançar movimento de expedição de outros documentos" name="(SG) Lançar movimento de expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="Nó de Desvio - (SG) Expedição de outros documentos" name="Nó de Desvio - (SG) Expedição de outros documentos">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR" name="Retornar para elaboração do documento pela secretaria"/>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{taskInstanceUtil.deleteVariableLocally('frameDefaultLeavingTransition')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavel('condicaoLancamentoMovimentosTemporario')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds','57,67,174,34,210,95,235,91')}"/>
            <action expression="#{taskInstanceUtil.setFrameDefaultTransition('(SG) Lançar movimento de expedição de outros documentos')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavel('condicaoLancamentoMovimentosTemporario', '${true}')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos','Retornar para elaboração do documento pela secretaria')}"/>
        </event>
    </task-node>
    <node name="(SG) Apagar minuta não assinada de outros documentos">
        <transition to="(SG) Verificar pendência de cumprimentos" name="(SG) Verificar pendência de cumprimentos"/>
        <event type="node-enter">
            <action expression="${documentoJudicialService.removerDocumentoAPartirDeVariavalDeFluxo('minuta_outros_documentos')}"/>
        </event>
    </node>
    <node name="(SG) Lançar movimento de expedição de outros documentos">
        <transition to="(SG) Verificar pendência de cumprimentos" name="(SG) Verificar pendência de cumprimentos"/>
        <event type="node-enter">
            <action expression="#{documentoJudicialService.getDocumento(tramitacaoProcessualService.recuperaVariavel('pje:atoProferido')).getTipoProcessoDocumento().idTipoProcessoDocumento == 67 ?  preencherMovimento.deCodigo(11383).associarAoDocumento(documentoJudicialService.getDocumento(tramitacaoProcessualService.recuperaVariavel('pje:atoProferido'))).lancarMovimento() :  preencherMovimento.deCodigo(60).associarAoDocumento(documentoJudicialService.getDocumento(tramitacaoProcessualService.recuperaVariavel('pje:atoProferido'))).comProximoComplementoVazio().preencherComTexto(documentoJudicialService.getDocumento(tramitacaoProcessualService.recuperaVariavel('pje:atoProferido')).processoDocumento).lancarMovimento()}"/>
        </event>
    </node>
    <process-state name="(SG) Verificar pendência de cumprimentos">
        <sub-process name="(SG) Sinalizar verificação de cumprimentos" binding="late"/>
        <transition to="Término" name="Término"/>
    </process-state>
    <end-state name="Término">
        <event type="node-leave">
            <action expression="#{tramitacaoProcessualService.apagaVariavel('minutaEmElaboracao')}"/>
        </event>
    </end-state>
    <task-node end-tasks="true" name="Nó de Desvio - (SG) Expedição de outros documentos">
        <task name="Nó de Desvio - (SG) Expedição de outros documentos" swimlane="Nó de Desvio - (SG) Expedição de outros documentos" priority="3"/>
        <transition to="(SG) Outros documentos - EXPEDIR" name="(SG) Outros documentos - EXPEDIR"/>
        <transition to="(SG) Outros documentos - ASSINAR" name="(SG) Outros documentos - ASSINAR"/>
        <transition to="Término" name="Término"/>
        <transition to="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR" name="(SG) Outros documentos pendentes de assinatura pelo gabinete - ASSINAR"/>
        <transition to="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR" name="(SG) Secretário(a) [OUTROS DOCUMENTOS] - ASSINAR"/>
        <transition to="(SG) Outros documentos criminais- EXPEDIR" name="(SG) Outros documentos criminais- EXPEDIR"/>
        <transition to="(SG) Outros documentos criminais - ASSINAR" name="(SG) Outros documentos criminais - ASSINAR"/>
    </task-node>
    <!-- PROCESS-EVENTS -->
    <event type="superstate-enter">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="process-start">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="before-signal">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="subprocess-created">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-create">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="transition">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-assign">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="after-signal">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="timer">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-start">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="subprocess-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="node-leave">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="process-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="superstate-leave">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="node-enter">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <!-- ACTIONS -->
</process-definition>


text:
My RestFul api on the example CRUD application
==============================================

**Dump database:**

CREATE TABLE `book` (

  `id` int(4) unsigned NOT NULL AUTO_INCREMENT,

  `book` varchar(255) NOT NULL,

  `author` varchar(255) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

**Book Api include:**

`GET /localhost/advanced/api/v1/books/list:` list all books;

`POST /localhost/advanced/api/v1/books/list:` create a new book;

`PATCH /localhost/advanced/api/v1/books/list/id:` update the book on ID;

`DELETE /localhost/advanced/api/v1/books/list/id:` delete the book on ID;

**CRUD Application is available on the link:**http://localhost/advanced/frontend/web

redpajama_set_name: RedPajamaGithub


text:
module Minimart
  module Commands
    # Mirror is the main entrance point for the mirroring portion of Minimart.
    # Given a directory, and a path to a config file, this class
    # will generate an inventory.
    class Mirror

      attr_reader :inventory_config, :inventory_directory, :load_deps

      # @param [Hash] opts
      # @option opts [String] :inventory_directory The directory to store the inventory.
      # @option opts [String] :inventory_config The path to the inventory configuration file.
      def initialize(opts)
        @inventory_directory = opts[:inventory_directory]
        Minimart::Configuration.load_deps = opts[:load_deps] if opts[:load_deps]
        @inventory_config    = Minimart::Mirror::InventoryConfiguration.new(opts[:inventory_config])
      end

      # Generate the inventory.
      def execute!
        builder = Minimart::Mirror::InventoryBuilder.new(inventory_directory, inventory_config)
        builder.build!
      end
    end
  end
end


text:
<?php

namespace Alice\Source\Sensor;

use Alice\Alice;

use Alice\Source\SensorSource;

use Alice\Systems\Output\Output;

/**
 * ALICE SensorSource: Audio
 *
 * @author Tim Gunter <tim@vanillaforums.com>
 * @package alice-server
 */
class Audio extends SensorSource {

    /**
     * Constructor
     *
     * @param string $type
     * @param array $config
     */
    public function __construct($type, $config) {
        parent::__construct($type, $config);

        $this->satisfies = [
            'audio'
        ];
    }

    /**
     * Build DataWant ID
     *
     * @param string $filter
     * @param array $config
     * @return string
     */
    public function buildWantID($filter, $config) {
        return "{$this->class}:{$this->type}/{$this->id}";
    }

    /**
     * Get namespaced cache key
     *
     * @param string $key
     * @return string
     */
    protected function getCacheKey($key) {
        return sprintf($key, $this->name);
    }

    /**
     * Handle audio event
     *
     * @param array $event
     * @return type
     */
    public function pushEvent($event) {
        $sessionID = val('session', $event);
        $type = val('type', $event);
        switch ($type) {
            // Alert that we're listening for sounds
            case 'cue':
                $this->rec('audio input keyword');
                Output::alert(Output::ALERT_START_LISTEN);
                break;

            // Alert that we've finished listening for sounds
            case 'uncue':
                $this->rec('audio input decoding');
                Output::alert(Output::ALERT_NOTIFY);
                break;

            case 'command':
                $this->rec('audio input phrase');

                $phrase = val('phrase', $event);
                $confidence = val('confidence', $event);
                $this->rec(" phrase: {$phrase}");

                // Get or create session
                $session = null;
                if ($sessionID) {
                    $session = Alice::go()->dispatcher()->getSession($sessionID);
                }

                if (!$session) {
                    $session = Alice::go()->dispatcher()->createSession();
                    $session->attachSource($this);
                }

                // Push phrase to sesssion
                $session->update($phrase, $confidence);
                break;
        }

        // Push raw event out
        parent::pushEvent($event);
    }

    /**
     * Ask client to listen
     *
     * @param string $sessionID
     */
    public function listen($sessionID) {
        $this->rec("asking for input: {$sessionID}");
        $this->getClient()->sendMessage('listen', [
            'session' => $sessionID
        ]);
    }

}


text:
/**
 *
 */
package edu.mit.ll.nics.common.entity.social;

import java.util.Collection;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.json.JSONException;
import org.json.JSONObject;

import edu.mit.ll.nics.common.entity.SADisplayMessageEntity;
import edu.mit.ll.nics.common.entity.SADisplayPersistedEntity;

/**
 * @author ri18384
 *
 */
@Entity
public class TwitterQuery extends SADisplayMessageEntity implements SADisplayPersistedEntity {

	@Id
	@GeneratedValue
	private int id;

	@Column(nullable=false)
	private Date creationTime;

	@Enumerated(EnumType.STRING)
	private SocialMediaSource source;

	@Column(nullable=false)
	private String queryString;

	@Column
	private double latitude;

	@Column
	private double longitude;

	private double radiusKm;

	// Restricts tweets to the given language, given by an ISO 639-1 code. Language detection is best-effort.
	private String lang;

	public static enum ResultType {
		MIXED,
		RECENT,
		POPULAR
	}

	@Column(nullable=false)
	private ResultType resultType = ResultType.RECENT;

	public TwitterQuery()
	{

	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Date getCreationTime() {
		return creationTime;
	}

	public void setCreationTime(Date creationTime) {
		this.creationTime = creationTime;
	}

	public SocialMediaSource getSource() {
		return source;
	}

	public void setSource(SocialMediaSource source) {
		this.source = source;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}

	public double getLatitude() {
		return latitude;
	}

	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public double getLongitude() {
		return longitude;
	}

	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public double getRadiusKm() {
		return radiusKm;
	}

	public void setRadiusKm(double radiusKm) {
		this.radiusKm = radiusKm;
	}

	public String getLang() {
		return lang;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public ResultType getResultType() {
		return resultType;
	}

	public void setResultType(ResultType resultType) {
		this.resultType = resultType;
	}

	@Override
	public JSONObject toJSONObject() throws JSONException
	{
		JSONObject json = new JSONObject();

		try
		{
			json.put("id", this.id);
			if (this.source != null)
				json.put("source", this.source.toString());
			json.put("queryString", this.queryString);
			json.put("latitude", this.latitude);
			json.put("longitude", this.longitude);
			json.put("radiusKm", this.radiusKm);
			json.put("lang", this.lang);
			json.put("creationTime", this.creationTime);
			json.put("resultType", this.resultType.toString());

			return json;
		} catch (JSONException je)
		{
			je.printStackTrace();
			return null;
		}
	}
} // class TwitterQuery


text:
require 'test_helper'

class FeedbcakTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
<!DOCTYPE html>

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

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Laboratório de Aprendizado de Máquina Aplicado a Finanças e Organizações">

    <title>Bootstrap - LAMFO</title>

    <link rel="canonical" href="http://localhost:4000/2017/06/28/Bootstrap-en/">

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

    <link rel="stylesheet" href="/css/clean-blog.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">

    <link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="LAMFO">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            LAMFO

                    Home

                    Sobre

Bootstrap

                    Posted by Mariana Rosa Montenegro on June 28, 2017

				<link href="https://fonts.googleapis.com/css?family=Rock%20Salt" rel="stylesheet">

<link href="https://fonts.googleapis.com/css?family=Sofia" rel="stylesheet">

Bootstrap

In this post, we present a statistic technique called Bootstrap. Nothing better than an example of brigadeiro (a typical and popular desert in Brazil) for a preliminary taste on the subject.

Imagine you own a candy store. A customer expects that, when buying a brigadeiro, it will have, on average, the same weight as the one of another customer. However, it is impossible to weigh all the brigadeiros that will be produced in your store!!

What should we do then??

You, the owner of the establishment, can use sampling techniques to randomly select 150 brigadeiros and calculate the average weight of these brigadeiros. Done this, you can conclude that the population mean is within an margin error relative to the sample mean.

Suppose you want to know, after a few months, what the average weight of the brigadeiro would be on a given production line date, taking into account greater accuracy.

As several variables have emerged, we can no longer use the sample of brigadeiros produced today as a baseline. Among these variables involved, we consider different types of sugar, cocoa and butter, new flavors, type of confectionery, the filling, among others.

Let us assume that the only information we have is the weight of a sample of 150 brigadeiros on the initial testing date. We can consider the initial error margin as our most relevant information.

Fortunately, to solve this problem there is

Bootstrap!!

In this scenario, we create our Bootstrap sample, which arises from the random sampling of the 150 known weights. If weight replacement is allowed, this bootstrap sample will not necessarily be identical to the initial sample. Some data may be omitted and others may be repeated. In this scenarion, numerous bootstrap samples are quickly created.

Technical View

Let's now introduce Bootstrap with more detail.

This statistical technique was initially proposed by Bradley Efron in 1979. It has been gaining strength, especially due to the advances in computer power.

What is the origin of the word Bootstrap??

Bootstrap term has English origin and refers to the lace on the back of a boot which helps to put it on.

Its use comes from the phrase "To lift himself up by his bootstraps", that is, "Get up using your bootstrap". Here, there is an allusion to something impossible, difficult to achieve.

Imagine getting up in the air pulling only pieces of leather from your boot. This is impossible! And the idea that this model wants to bring is to be able to do the impossible.

The story of Baron Munchausen, also mentioned in the origin of the Bootstrap concept, tells that he was able to raise himself and his horse from a swamp by pulling his own hair (specifically, his ponytail). However, in this history there is no use of the word bootstrap as we know it and no other explicit reference to bootstraps has been found elsewhere in the various versions of Munchausen tales.

Theory

Think about the case of a random sample of size n , from a probability distribution function F undefined:
  , .

Let  and  be the random variables and the observations of the independent random variables, with the same distribution function F . We will investigate the variability and the sampling distribution of the local estimation calculation from the sample of size n. We denote this local estimate as . Note that  is a function of the random variables  and, therefore, has a probability distribution, its sample distribution, which is determined by n and F.

Based on Efron and Tibshirani (1993), the basic steps for creating Bootstrap are:

Step 1:

Construct, from the sample, an empirical probability distribution , inserting, in each point  of the sample, a probability .

Characterized as an empirical distribution function of the sample, this is a non-parametric estimate of the maximum probability from the population distribution, F.

Step 2:

Perform the resample: draw a random sample of size n with replacement from the  distribution function.

Step 3:

Calculate for this resampling the statistic of interest , generating .

Step 4:

Repeat steps 2 and 3 B times. To create B resamples, B must be a large value. The size of B depends on tests that will be performed with the data. When an estimate with confidence interval of  is required, it is suggested that B should be at least equal to 1000.

Step 5:

Build, from the value B of , the relative frequency of the histogram, assigning probability of  to each point , ,…, .

The obtained distribution is the Bootstrap estimate of the sampling distribution of . One can make inferences from parameter θ, using this distribution, estimating .

Bootstrap and stocks in financial market using R

In the following example, we will create the Bootstrap sample for the daily returns of Apple shares and the S&P500 index from 06/02/2016 to 05/31/2017. To do so, first download the base bootstrap.txt from the following file. Now, read the database in R using the code below:

dados<-read.table(file.choose())

To work with this file type the following command:

spxret <- dados[, 'SP500index']
applret <- dados[,'APPLE']

names(dados)[names(dados)=="SP500index"] <- "sp500"
dados$sp500 <- as.numeric(as.character(dados$sp500))

dados$sp500<-c(NA,diff(log(dados$sp500)))
dados$APPLE<-c(NA,diff(log(dados$APPLE)))

spxret<-as.numeric(spxret)

The spxret and applret commands extract a column to create a vector. In the following lines of the code above, we work on the database to turn all data into numerics, removing NA's (No Data values) and transforming returns into log returns.

In our analysis we obtained, in one year, 251 daily returns. Randomly a bootstrap sample was obtained from daily returns. In our case, you will notice that some days will appear several times in the bootstrap sample while others will not appear at all. This is due to the fact that we perform sampling with replacement. From our bootstrap sample, we chose to perform the sum of the values. Typically several bootstrap samples are created.

The code below shows how to use Bootstrap to generate 1000 Bootstrap samples. We can see below that we sample with integers from 1 to 251. We created a sample of size 251 and sample it with replacement. With the command this.samp we get a year with daily returns that could have happened. We collect annual returns for each hypothetical year in the following code line.

spx.boot.sum <- numeric(1000) # numeric vector 1000 long

for(i in 1:1000) {
  this.samp <- spxret[ sample(251, 251, replace=TRUE) ]
  spx.boot.sum[i] <- sum(this.samp)
}

You can also plot the annual returns distribution obtained using Bootstrap with the following code:

plot(density(spx.boot.sum), lwd=3, col="orange")
abline(v=sum(spxret), lwd=3, col='blue')

According to the image below, the annual return is quite variable. If you use a different initial database, your chart will change. In this case we find that our annual return is very close to the middle of the distribution. It is noteworthy that this result may be different due to statistical biases or the database.

Let's practice?

References

Efron, B. (1979). Bootstrap methods: another look at the jackknife. The annals of Statistics, 1-26.

Efron, B, and Tibshirani, R.J. (1993). An introduction to the bootstrap. Chapman and Hall, London.

                        ← Previous Post

                        Next Post →

Please enable JavaScript to view the comments powered by Disqus.

Copyright © LAMFO - UNB 2017


text:
# Copyright 2014 Google Inc. All rights reserved.
#
# 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.

#! /bin/bash

set -x
set -e

# Make sure /dev/shm has correct permissions.
ls -l /dev/shm
sudo chmod 1777 /dev/shm
ls -l /dev/shm

uname -a
cat /etc/lsb-release

npm install
npm install -g grunt-cli

sudo apt-get update --fix-missing

# Install python-imaging from the environment rather then build it.
# If the below fails, pip will build it via the requirements.txt
# sudo apt-get install python-imaging
# VIRTUAL_ENV_site_packages=$(echo $VIRTUAL_ENV/lib/*/site-packages)
# VIRTUAL_ENV_python_version=$(echo $VIRTUAL_ENV_site_packages | sed -e's@.*/\(.*\)/site-packages@\1@')
# ln -s /usr/lib/$VIRTUAL_ENV_python_version/dist-packages/PIL.pth $VIRTUAL_ENV_site_packages/PIL.pth
# ln -s /usr/lib/$VIRTUAL_ENV_python_version/dist-packages/PIL $VIRTUAL_ENV_site_packages/PIL

export VERSION=$(echo $BROWSER | sed -e's/[^-]*-//')
export BROWSER=$(echo $BROWSER | sed -e's/-.*//')

echo BROWSER=$BROWSER
echo VERSION=$VERSION

sudo ln -sf $(which true) $(which xdg-desktop-menu)

case $BROWSER in
Android)
  sudo apt-get install -qq --force-yes \
    libc6:i386 libgcc1:i386 gcc-4.6-base:i386 libstdc++5:i386 \
    libstdc++6:i386 lib32z1 libreadline6-dev:i386 \
    libncurses5-dev:i386
  bash tools/android/setup.sh
  ;;

Chrome)
  echo "Getting $VERSION of $BROWSER"
  export CHROME=google-chrome-${VERSION}_current_amd64.deb
  wget https://dl.google.com/linux/direct/$CHROME
  sudo dpkg --install $CHROME || sudo apt-get -f install
  which google-chrome
  ls -l `which google-chrome`

  if [ -f /opt/google/chrome/chrome-sandbox ]; then
    export CHROME_SANDBOX=/opt/google/chrome/chrome-sandbox
  else
    export CHROME_SANDBOX=$(ls /opt/google/chrome*/chrome-sandbox)
  fi

  # Download a custom chrome-sandbox which works inside OpenVC containers (used on travis).
  sudo rm -f $CHROME_SANDBOX
  sudo wget https://googledrive.com/host/0B5VlNZ_Rvdw6NTJoZDBSVy1ZdkE -O $CHROME_SANDBOX
  sudo chown root:root $CHROME_SANDBOX; sudo chmod 4755 $CHROME_SANDBOX
  sudo md5sum $CHROME_SANDBOX

  google-chrome --version
  ;;

Firefox)
  sudo rm -f /usr/local/bin/firefox
  case $VERSION in
  beta)
    yes "\n" | sudo add-apt-repository -y ppa:mozillateam/firefox-next
    ;;
  aurora)
    yes "\n" | sudo add-apt-repository -y ppa:ubuntu-mozilla-daily/firefox-aurora
    ;;
  esac
  sudo apt-get update --fix-missing
  sudo apt-get install firefox
  which firefox
  ls -l `which firefox`
  firefox --version
  ;;
esac

# R=tools/python/requirements.txt
# pip install -r $R --use-mirrors || pip install -r $R


text:
@interface News : NSObject
//新闻标题
@property (nonatomic, copy) NSString *title;
//新闻摘要
@property (nonatomic, copy) NSString *digest;
//跟帖数量
@property (nonatomic, assign) int replyCount;
///配图地址
@property (nonatomic, copy) NSString *imgsrc;
//多图
@property (nonatomic, strong) NSArray *imgextra;
//大图
@property (nonatomic, assign, getter=isBigImage) BOOL imgType;
@property (nonatomic, copy) NSString *url;
//加载制定URL 的新闻数组
+ (void)loadNewsListWithURLString:(NSString *)urlString finished:(void (^)(NSArray *newsList)) finished;
@end


text:
'''
## License

The MIT License (MIT)

GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015  Dexter Industries

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import time
import grovepi

# Connect first LED in Chainable RGB LED chain to digital port D7
# In: CI,DI,VCC,GND
# Out: CO,DO,VCC,GND
pin = 7

# I have 10 LEDs connected in series with the first connected to the GrovePi and the last not connected
# First LED input socket connected to GrovePi, output socket connected to second LED input and so on
numleds = 4     #If you only plug 1 LED, change 10 to 1

grovepi.pinMode(pin,"OUTPUT")
time.sleep(1)

# Chainable RGB LED methods
# grovepi.storeColor(red, green, blue)
# grovepi.chainableRgbLed_init(pin, numLeds)
# grovepi.chainableRgbLed_test(pin, numLeds, testColor)
# grovepi.chainableRgbLed_pattern(pin, pattern, whichLed)
# grovepi.chainableRgbLed_modulo(pin, offset, divisor)
# grovepi.chainableRgbLed_setLevel(pin, level, reverse)

# test colors used in grovepi.chainableRgbLed_test()
testColorBlack = 0   # 0b000 #000000
testColorBlue = 1    # 0b001 #0000FF
testColorGreen = 2   # 0b010 #00FF00
testColorCyan = 3    # 0b011 #00FFFF
testColorRed = 4     # 0b100 #FF0000
testColorMagenta = 5 # 0b101 #FF00FF
testColorYellow = 6  # 0b110 #FFFF00
testColorWhite = 7   # 0b111 #FFFFFF

# patterns used in grovepi.chainableRgbLed_pattern()
thisLedOnly = 0
allLedsExceptThis = 1
thisLedAndInwards = 2
thisLedAndOutwards = 3

try:

    print("Test 1) Initialise")

    # init chain of leds
    grovepi.chainableRgbLed_init(pin, numleds)
    time.sleep(.5)

    # change color to green
    grovepi.storeColor(0,255,0)
    time.sleep(.5)

    # set led 1 to green
    grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 0)
    time.sleep(.5)

    # change color to red
    grovepi.storeColor(255,0,0)
    time.sleep(.5)

    # set led 10 to red
    grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 9)
    time.sleep(.5)

    # pause so you can see what happened
    time.sleep(2)

    # reset (all off)
    grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
    time.sleep(.5)

    print ("Test 2a) Test Patterns - black")

    # test pattern 0 - black (all off)
    grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
    time.sleep(1)

    print ("Test 2b) Test Patterns - blue")

    # test pattern 1 blue
    grovepi.chainableRgbLed_test(pin, numleds, testColorBlue)
    time.sleep(1)

    print ("Test 2c) Test Patterns - green")

    # test pattern 2 green
    grovepi.chainableRgbLed_test(pin, numleds, testColorGreen)
    time.sleep(1)

    print ("Test 2d) Test Patterns - cyan")

    # test pattern 3 cyan
    grovepi.chainableRgbLed_test(pin, numleds, testColorCyan)
    time.sleep(1)

    print ("Test 2e) Test Patterns - red")

    # test pattern 4 red
    grovepi.chainableRgbLed_test(pin, numleds, testColorRed)
    time.sleep(1)

    print ("Test 2f) Test Patterns - magenta")

    # test pattern 5 magenta
    grovepi.chainableRgbLed_test(pin, numleds, testColorMagenta)
    time.sleep(1)

    print ("Test 2g) Test Patterns - yellow")

    # test pattern 6 yellow
    grovepi.chainableRgbLed_test(pin, numleds, testColorYellow)
    time.sleep(1)

    print ("Test 2h) Test Patterns - white")

    # test pattern 7 white
    grovepi.chainableRgbLed_test(pin, numleds, testColorWhite)
    time.sleep(1)

    # pause so you can see what happened
    time.sleep(2)

    # reset (all off)
    grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
    time.sleep(.5)

except KeyboardInterrupt:
    # reset (all off)
    grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
except IOError:
    print ("Error")


text:
"""
Chat protocols.
"""

from twisted.python import deprecate, versions

deprecate.deprecatedModuleAttribute(
    versions.Version("Twisted", 15, 1, 0), "MSN has shutdown.", __name__,
    "msn")


text:
package dao

import (
	. "github.com/smartystreets/goconvey/convey"
	"testing"

	"go-common/app/service/live/wallet/model"
	mc "go-common/library/cache/memcache"
	"math/rand"
	"time"
)

func TestDao_WalletCache(t *testing.T) {
	once.Do(startService)
	Convey("Get Nil Cache", t, func() {

		r = rand.New(rand.NewSource(time.Now().UnixNano()))

		uid := r.Int63n(1000000)

		_, err := d.WalletCache(ctx, uid)

		So(err, ShouldEqual, mc.ErrNotFound)

	})

	Convey("Set And Get And Del", t, func() {

		r = rand.New(rand.NewSource(time.Now().UnixNano()))

		uid := r.Int63n(1000000)

		detail := &model.Detail{Uid: uid, Gold: 1, IapGold: 1, Silver: 1, GoldPayCnt: 1, GoldRechargeCnt: 1, SilverPayCnt: 1}

		mcDetail := &model.McDetail{Detail: detail, Exist: true, Version: d.CacheVersion(ctx)}
		err := d.SetWalletCache(ctx, mcDetail, d.cacheExpire)
		So(err, ShouldBeNil)

		nd, err := d.WalletCache(ctx, uid)
		So(err, ShouldBeNil)
		So(nd.Exist, ShouldEqual, true)
		So(nd.Detail.Gold, ShouldEqual, 1)
		So(nd.Detail.IapGold, ShouldEqual, 1)
		So(nd.Detail.Silver, ShouldEqual, 1)
		So(nd.Detail.GoldPayCnt, ShouldEqual, 1)
		So(nd.Detail.GoldRechargeCnt, ShouldEqual, 1)
		So(nd.Detail.SilverPayCnt, ShouldEqual, 1)
		So(nd.Version, ShouldEqual, d.CacheVersion(ctx))

		err = d.DelWalletCache(ctx, uid)
		So(err, ShouldBeNil)

		nnd, err := d.WalletCache(ctx, uid)
		So(err, ShouldEqual, mc.ErrNotFound)
		So(nnd, ShouldBeNil)

	})

	Convey("version", t, func() {
		Convey("just set", func() {
			uid := int64(1)
			d.DelWalletCache(ctx, uid)
			d.GetDetailByCache(ctx, uid)
			detail, err := d.WalletCache(ctx, uid)
			So(err, ShouldBeNil)
			So(detail.Version, ShouldEqual, 1)
		})
		Convey("old to new", func() {

			uid := int64(1)
			od, err := d.Detail(ctx, uid)
			So(err, ShouldBeNil)
			d.DelWalletCache(ctx, uid)

			detail := &model.Detail{Uid: uid, Gold: od.Gold + 1, IapGold: 1, Silver: 1, GoldPayCnt: 1, GoldRechargeCnt: 1, SilverPayCnt: 1} // fake data

			mcDetail := &model.McDetail{Detail: detail, Exist: true} // old version
			err = d.SetWalletCache(ctx, mcDetail, d.cacheExpire)
			So(err, ShouldBeNil)
			So(mcDetail.Version, ShouldEqual, 0)
			So(mcDetail.Detail.Gold, ShouldEqual, od.Gold+1)
			So(mcDetail.Detail.IapGold, ShouldEqual, 1)
			So(mcDetail.Detail.Silver, ShouldEqual, 1)
			So(mcDetail.Detail.GoldPayCnt, ShouldEqual, 1)

			mcDetail1, err := d.WalletCache(ctx, uid) //
			So(err, ShouldBeNil)
			So(mcDetail1.Detail.Gold, ShouldEqual, od.Gold+1)

			fd, err := d.GetDetailByCache(ctx, uid) // check version if it is old update cache
			So(err, ShouldBeNil)
			So(fd.Gold, ShouldEqual, od.Gold)
			So(fd.Silver, ShouldEqual, od.Silver)
			So(fd.GoldPayCnt, ShouldEqual, od.GoldPayCnt)

			mcDetail2, err := d.WalletCache(ctx, uid)
			So(err, ShouldBeNil)
			So(mcDetail2.Version, ShouldEqual, d.CacheVersion(ctx))
			So(mcDetail2.Detail.Gold, ShouldEqual, od.Gold)

		})
	})
}


text:
using BlazorServer.Services;
using Orleans.Providers;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseOrleans((ctx, siloBuilder) => {

    siloBuilder.UseLocalhostClustering();
    siloBuilder.AddMemoryGrainStorageAsDefault();
    siloBuilder.AddMemoryStreams<DefaultMemoryMessageBodySerializer>("MemoryStreams");
    siloBuilder.AddMemoryGrainStorage("PubSubStore");
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<TodoService>();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();


text:
package com.jeedsoft.tomcat.session.impl.rdb.builder;

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

import com.jeedsoft.tomcat.session.util.StringUtil;

public class InsertBuilder implements Builder
{
	private String table = null;

	private Map<String, Field> fieldMap = new HashMap<String, Field>();

	public InsertBuilder()
	{
	}

	public InsertBuilder(String table)
	{
		this.table = table;
	}

	public void setField(String name, int sqlType, Object value)
	{
		fieldMap.put(name, new Field(name, sqlType, value));
	}

	public boolean hasField()
	{
		return !fieldMap.isEmpty();
	}

	public boolean hasField(String name)
	{
		return fieldMap.containsKey(name);
	}

	@Override
	public String getSql()
	{
		List<String> fieldNames = new ArrayList<String>(fieldMap.size());
		for (Field field: fieldMap.values()) {
			fieldNames.add(field.name);
		}
		StringBuilder sb = new StringBuilder(1024);
		sb.append("insert into ").append(table);
		sb.append(" (").append(StringUtil.join(fieldNames)).append(")");
		sb.append(" values ");
		sb.append(" (").append(StringUtil.join("?", fieldNames.size())).append(")");
		return sb.toString();
	}

	@Override
	public Field[] getParameters()
	{
		Field[] array = new Field[fieldMap.size()];
		int i = 0;
		for (Field field: fieldMap.values()) {
			array[i++] = field;
		}
		return array;
	}
}


text:
#ifndef BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED
#define BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/aux_/config/has_xxx.hpp>
#include <boost/mpl/aux_/config/msvc.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>

#if !defined(BOOST_MPL_CFG_NO_HAS_APPLY) \
    && (   defined(BOOST_MPL_CFG_NO_HAS_XXX) \
        || BOOST_WORKAROUND(__EDG_VERSION__, < 300) \
        || BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
        || BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3202)) \
        )

#   define BOOST_MPL_CFG_NO_HAS_APPLY

#endif

#endif // BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED


text:
/* eslint-disable default-case */
import {TypedIdentifier} from "../types/_typed_identifier";
import {StatementNode, ExpressionNode} from "../nodes";
import * as Expressions from "../2_statements/expressions";
import * as Statements from "../2_statements/statements";
import * as Types from "../types/basic";
import {CurrentScope} from "./_current_scope";
import {AbstractType} from "../types/basic/_abstract_type";
import {ScopeType} from "./_scope_type";
import {ObjectOriented} from "./_object_oriented";
import {ClassConstant} from "../types/class_constant";
import {Identifier as TokenIdentifier} from "../1_lexer/tokens/identifier";
import {ReferenceType} from "./_reference";
import {CharacterType, StructureType, TableAccessType, TableType, VoidType} from "../types/basic";
import {FieldChain} from "./expressions/field_chain";
import {ClassDefinition} from "../types";
import {FieldSub, TypeTableKey} from "../2_statements/expressions";
import {BuiltIn} from "./_builtin";
import {Position} from "../../position";

export class BasicTypes {
  private readonly filename: string;
  private readonly scope: CurrentScope;

  public constructor(filename: string, scope: CurrentScope) {
    this.filename = filename;
    this.scope = scope;
  }

  public lookupQualifiedName(name: string | undefined): TypedIdentifier | undefined {
// argh, todo, rewrite this entire method, more argh
    if (name === undefined) {
      return undefined;
    }

    const found = this.scope.findType(name);
    if (found) {
      return found;
    }

    if (name.includes("=>")) {
      const split = name.split("=>");
      const ooName = split[0];
      const typeName = split[1];
      const oo = this.scope.findObjectDefinition(ooName);
      if (oo) {
        if (typeName.includes("-")) {
          const split = typeName.split("-");
          const subTypeName = split[0];
          const fieldName = split[1];
          const stru = oo.getTypeDefinitions().getByName(subTypeName);
          const struType = stru?.getType();
          if (stru && struType instanceof StructureType) {
            const f = struType.getComponentByName(fieldName);
            if (f) {
              return new TypedIdentifier(stru.getToken(), stru.getFilename(), f);
            }
          }
        } else {
          const f = oo.getTypeDefinitions().getByName(typeName);
          if (f) {
            return f;
          }
        }
      }
    } else if (name.includes("-")) {
      const split = name.split("-");
      const typeName = split[0];
      const fieldName = split[1];
      const type = this.scope.findType(typeName);
      if (type) {
        const stru = type.getType();
        if (stru instanceof StructureType) {
          const f = stru.getComponentByName(fieldName);
          if (f) {
            return new TypedIdentifier(type.getToken(), type.getFilename(), f);
          }
        }
      }
    }

    const lookup = this.scope.getDDIC().lookupNoVoid(name);
    const id = lookup?.object?.getIdentifier();
    if (id && lookup?.type) {
      return new TypedIdentifier(id.getToken(), id.getFilename(), lookup.type);
    }

    const builtin = this.scope.getDDIC().lookupBuiltinType(name);
    if (builtin) {
      return new TypedIdentifier(new TokenIdentifier(new Position(1, 1), name), BuiltIn.filename, builtin);
    }

    const type = this.scope.findTypePoolType(name);
    if (type) {
      return type;
    }

    return undefined;
  }

  public resolveLikeName(node: ExpressionNode | StatementNode | undefined, headerLogic = true): AbstractType | undefined {
    if (node === undefined) {
      return undefined;
    }

    let chain = node.findFirstExpression(Expressions.FieldChain);
    if (chain === undefined) {
      chain = node.findFirstExpression(Expressions.TypeName);
    }
    if (chain === undefined) {
      chain = node.findFirstExpression(Expressions.FieldSub);
    }
    if (chain === undefined) {
      chain = node.findFirstExpression(Expressions.SimpleFieldChain);
    }
    if (chain === undefined) {
      throw new Error("resolveLikeName, chain undefined");
    }
    const fullName = chain.concatTokens();
    const children = [...chain.getChildren()];

    if (children.length === 0) {
      return new Types.UnknownType("Type error, could not resolve \"" + fullName + "\", resolveLikeName1");
    }

    let type: AbstractType | undefined = undefined;
    if (children[1] && ( children[1].getFirstToken().getStr() === "=>" || children[1].getFirstToken().getStr() === "->")) {
      type = new FieldChain().runSyntax(chain, this.scope, this.filename, ReferenceType.TypeReference);
    } else {
      const name = children.shift()!.getFirstToken().getStr();
      let found = this.scope.findVariable(name);
      type = found?.getType();

      if (found === undefined) {
        found = this.scope.findExtraLikeType(name);
        type = found?.getType();
      }

      if (found) {
        this.scope.addReference(chain?.getFirstToken(), found, ReferenceType.TypeReference, this.filename);
      }

      if (type === undefined) {
        type = this.scope.getDDIC().lookupNoVoid(name)?.type;
      }

      if (type === undefined && this.scope.isOO() === false && this.scope.getDDIC().inErrorNamespace(name) === false) {
        this.scope.addReference(chain.getChildren()[0].getFirstToken(), undefined, ReferenceType.VoidType, this.filename);
        return new Types.VoidType(name);
      }

      while (children.length > 0) {
        const child = children.shift()!;

        if (child.getFirstToken().getStr() === "-") {
          if (type instanceof Types.VoidType) {
            return type;
          }
        } else if (child.concatTokens() === "[]") {
          if (type instanceof Types.TableType) {
            type = new TableType(type.getRowType(), {withHeader: false});
          }
        } else { // field name
          let sub: AbstractType | undefined = undefined;
          if (type instanceof Types.TableType) {
            type = type.getRowType();
          }
          if (type instanceof Types.StructureType) {
            sub = type.getComponentByName(child.getFirstToken().getStr());
          }
          if (sub === undefined) {
            return new Types.UnknownType("Type error, field not part of structure " + fullName);
          }
          type = sub;
        }
      }

      if (type instanceof Types.VoidType) {
        return type;
      } else if (type instanceof TableType
          && type.isWithHeader()
          && headerLogic === true) {
        type = type.getRowType();
      } else if (type instanceof Types.TableType
          && type.isWithHeader() === true
          && type.getRowType() instanceof Types.VoidType) {
        return type.getRowType();
      }
    }

    if (!type) {
      return new Types.UnknownType("Type error, could not resolve \"" + fullName + "\", resolveLikeName2");
    }

    return type;
  }

  public resolveTypeName(typeName: ExpressionNode | undefined,
                         length?: number, decimals?: number, qualifiedName?: string): AbstractType | undefined {

    if (typeName === undefined) {
      return undefined;
    }

    let chain = this.resolveTypeChain(typeName);
    if (chain) {
      if (chain instanceof CharacterType && qualifiedName) {
        chain = chain.cloneType(qualifiedName);
      }
      return chain;
    }

    const chainText = typeName.concatTokens().toUpperCase();
    const f = this.scope.getDDIC().lookupBuiltinType(chainText, length, decimals, qualifiedName);
    if (f !== undefined) {
      return f;
    }

    const typ = this.scope.findType(chainText);
    if (typ) {
      const token = typeName.getFirstToken();

      if (chainText.includes("~")) {
        const name = chainText.split("~")[0];
        const idef = this.scope.findInterfaceDefinition(name);
        if (idef) {
          this.scope.addReference(token, idef, ReferenceType.ObjectOrientedReference, this.filename, {ooType: "INTF", ooName: name});
        }
      }

      this.scope.addReference(token, typ, ReferenceType.TypeReference, this.filename);
      return typ.getType();
    }

    const type = this.scope.findTypePoolType(chainText)?.getType();
    if (type) {
//      this.scope.addReference(typeName.getFirstToken(), type, ReferenceType.TypeReference, this.filename);
      return type;
    }

    const ddic = this.scope.getDDIC().lookup(chainText);
    if (ddic) {
      this.scope.getDDICReferences().addUsing(this.scope.getParentObj(),
                                              {object: ddic.object, token: typeName.getFirstToken(), filename: this.filename});
      if (ddic.type instanceof TypedIdentifier) {
        this.scope.addReference(typeName.getFirstToken(), ddic.type, ReferenceType.TypeReference, this.filename);
      } else if (ddic.type instanceof VoidType) {
        this.scope.addReference(typeName.getFirstToken(), undefined, ReferenceType.VoidType, this.filename);
      }
      return ddic.type;
    }

    return undefined;
  }

  public simpleType(node: StatementNode | ExpressionNode, qualifiedNamePrefix?: string): TypedIdentifier | undefined {
    let nameExpr = node.findFirstExpression(Expressions.NamespaceSimpleName);
    if (nameExpr === undefined) {
      nameExpr = node.findFirstExpression(Expressions.DefinitionName);
    }
    if (nameExpr === undefined) {
      return undefined;
    }
    let name = nameExpr.getFirstToken();
    if (nameExpr.countTokens() > 1) { // workaround for names with dashes
      name = new TokenIdentifier(name.getStart(), nameExpr.concatTokens());
    }

    let qualifiedName: string | undefined = undefined;
    if (node.get() instanceof Statements.Type) {
      if (this.scope.isTypePool() === true) {
        qualifiedName = name.getStr();
      } else {
        qualifiedName = ( qualifiedNamePrefix || "" ) + name.getStr();
        if (this.scope.getType() === ScopeType.ClassDefinition
            || this.scope.getType() === ScopeType.Interface) {
          qualifiedName = this.scope.getName() + "=>" + qualifiedName;
        }
      }
    } else if (qualifiedNamePrefix) {
      qualifiedName = qualifiedNamePrefix + qualifiedName;
    }

    const found = this.parseType(node, qualifiedName);
    if (found) {
      return new TypedIdentifier(name, this.filename, found);
    }

    return undefined;
  }

  public parseTable(node: ExpressionNode | StatementNode, name?: string): AbstractType | undefined {
    const typename = node.findFirstExpression(Expressions.TypeName);
    const text = node.findFirstExpression(Expressions.TypeTable)?.concatTokens().toUpperCase();
    if (text === undefined) {
      return undefined;
    }

    let type: Types.TableAccessType | undefined = undefined;
    if (text.includes(" STANDARD TABLE ")) {
      type = TableAccessType.standard;
    } else if (text.includes(" SORTED TABLE ")) {
      type = TableAccessType.sorted;
    } else if (text.includes(" HASHED TABLE ")) {
      type = TableAccessType.hashed;
    }
    const keyFields: string[] = [];
    if (type) {
      const keys = node.findFirstExpression(TypeTableKey);
      for (const k of keys?.findDirectExpressions(FieldSub) || []) {
        keyFields.push(k.concatTokens().toUpperCase());
      }
    }
    const options: Types.ITableOptions = {
      withHeader: text.includes(" WITH HEADER LINE"),
      type: type,
      isUnique: text.includes(" WITH UNIQUE"),
      keyFields: keyFields,
    };

    let found: AbstractType | undefined = undefined;
    if (text.startsWith("TYPE TABLE OF REF TO ")
        || text.startsWith("TYPE STANDARD TABLE OF REF TO ")
        || text.startsWith("TYPE SORTED TABLE OF REF TO ")
        || text.startsWith("TYPE HASHED TABLE OF REF TO ")) {
      found = this.resolveTypeRef(typename);
      if (found) {
        return new Types.TableType(found, options, name);
      }
    } else if (text.startsWith("TYPE TABLE OF ")
        || text.startsWith("TYPE STANDARD TABLE OF ")
        || text.startsWith("TYPE SORTED TABLE OF ")
        || text.startsWith("TYPE HASHED TABLE OF ")) {
      found = this.resolveTypeName(typename);
      if (found) {
        return new Types.TableType(found, options, name);
      }
    } else if (text.startsWith("LIKE TABLE OF ")
        || text.startsWith("LIKE STANDARD TABLE OF ")
        || text.startsWith("LIKE SORTED TABLE OF ")
        || text.startsWith("LIKE HASHED TABLE OF ")) {
      found = this.resolveLikeName(node);
      if (found) {
        return new Types.TableType(found, options, name);
      }
    } else if (text === "TYPE STANDARD TABLE"
        || text === "TYPE SORTED TABLE"
        || text === "TYPE HASHED TABLE"
        || text === "TYPE INDEX TABLE"
        || text === "TYPE ANY TABLE") {
      return new Types.TableType(new Types.AnyType(), options);
    } else if (text.startsWith("TYPE RANGE OF ")) {
      const sub = node.findFirstExpression(Expressions.TypeName);
      found = this.resolveTypeName(sub);
      if (found === undefined) {
        return new Types.UnknownType("TYPE RANGE OF, could not resolve type");
      }
      const structure = new Types.StructureType([
        {name: "sign", type: new Types.CharacterType(1)},
        {name: "option", type: new Types.CharacterType(2)},
        {name: "low", type: found},
        {name: "high", type: found},
      ]);
      return new Types.TableType(structure, options, name);
    } else if (text.startsWith("LIKE RANGE OF ")) {
      const sub = node.findFirstExpression(Expressions.SimpleFieldChain);
      found = this.resolveLikeName(sub);
      if (found === undefined) {
        return new Types.UnknownType("LIKE RANGE OF, could not resolve type");
      }
      const structure = new Types.StructureType([
        {name: "sign", type: new Types.CharacterType(1)},
        {name: "option", type: new Types.CharacterType(2)},
        {name: "low", type: found},
        {name: "high", type: found},
      ], name);
      return new Types.TableType(structure, options);
    }

    // fallback to old style syntax, OCCURS etc
    return this.parseType(node, name);
  }

  public parseType(node: ExpressionNode | StatementNode, qualifiedName?: string): AbstractType | undefined {
    const typeName = node.findFirstExpression(Expressions.TypeName);

    let text = node.findFirstExpression(Expressions.Type)?.concatTokens().toUpperCase();
    if (text === undefined) {
      text = node.findFirstExpression(Expressions.TypeParam)?.concatTokens().toUpperCase();
    }
    if (text === undefined) {
      text = node.findFirstExpression(Expressions.TypeTable)?.concatTokens().toUpperCase();
      if (text?.startsWith("TYPE") === false && text?.startsWith("LIKE") === false) {
        text = "TYPE";
      }
    }
    if (text === undefined) {
      text = node.findFirstExpression(Expressions.FormParamType)?.concatTokens().toUpperCase();
    }
    if (text === undefined) {
      text = "TYPE";
    }

    let found: AbstractType | undefined = undefined;
    if (text.startsWith("LIKE LINE OF ")) {
      const name = node.findFirstExpression(Expressions.FieldChain)?.concatTokens();
      let e = node.findFirstExpression(Expressions.Type);
      if (e === undefined) {
        e = node.findFirstExpression(Expressions.FormParamType);
      }
      const type = this.resolveLikeName(e, false);

      if (type === undefined) {
        return new Types.UnknownType("Type error, could not resolve \"" + name + "\", parseType");
      } else if (type instanceof Types.TableType) {
        return type.getRowType();
      } else if (type instanceof Types.VoidType) {
        return type;
      } else {
        return new Types.UnknownType("Type error, not a table type " + name);
      }
    } else if (text.startsWith("LIKE REF TO ")) {
      const name = node.findFirstExpression(Expressions.FieldChain)?.concatTokens();
      const type = this.resolveLikeName(node.findFirstExpression(Expressions.Type), false);
      if (type === undefined) {
        return new Types.UnknownType("Type error, could not resolve \"" + name + "\", parseType");
      }
      return new Types.DataReference(type, name);
    } else if (text === "TYPE STANDARD TABLE"
        || text === "TYPE SORTED TABLE"
        || text === "TYPE HASHED TABLE"
        || text === "TYPE INDEX TABLE"
        || text === "TYPE ANY TABLE") {
      return new Types.TableType(new Types.AnyType(), {withHeader: node.concatTokens().toUpperCase().includes("WITH HEADER LINE")});
    } else if (text.startsWith("LIKE ")) {
      let sub = node.findFirstExpression(Expressions.Type);
      if (sub === undefined) {
        sub = node.findFirstExpression(Expressions.FormParamType);
      }
      if (sub === undefined) {
        sub = node.findFirstExpression(Expressions.TypeParam);
      }
      if (sub === undefined) {
        sub = node.findFirstExpression(Expressions.FieldChain);
      }
      found = this.resolveLikeName(sub);

      if (found && this.isOccurs(node)) {
        found = new Types.TableType(found, {withHeader: text.includes("WITH HEADER LINE")}, qualifiedName);
      }
    } else if (text.startsWith("TYPE LINE OF ")) {
      const sub = node.findFirstExpression(Expressions.TypeName);
      found = this.resolveTypeName(sub);
      if (found instanceof TypedIdentifier) {
        found = found.getType();
      }
      if (found instanceof Types.TableType) {
        return found.getRowType();
      } else if (found instanceof Types.VoidType) {
        return found;
      } else if (found instanceof Types.UnknownType) {
        return new Types.UnknownType("TYPE LINE OF, unknown type, " + found.getError());
      } else {
        return new Types.UnknownType("TYPE LINE OF, unexpected type, " + found?.constructor.name);
      }
    } else if (text.startsWith("TYPE REF TO ")) {
      found = this.resolveTypeRef(typeName);
    } else if (text.startsWith("TYPE")) {
      found = this.resolveTypeName(typeName, this.findLength(node), this.findDecimals(node), qualifiedName);

      const concat = node.concatTokens().toUpperCase();
      if (found && this.isOccurs(node)) {
        found = new Types.TableType(found, {withHeader: concat.includes(" WITH HEADER LINE")}, qualifiedName);
      } else if (found && concat.includes(" WITH HEADER LINE")) {
        if (found instanceof Types.VoidType) {
          found = new Types.TableType(found, {withHeader: true});
        } else if (!(found instanceof Types.TableType)) {
          throw new Error("WITH HEADER LINE can only be used with internal table");
        } else {
          found = new Types.TableType(found.getRowType(), {withHeader: true});
        }
      }

      if (found === undefined && typeName === undefined) {
        let length = 1;

        const len = node.findDirectExpression(Expressions.ConstantFieldLength);
        if (len) {
          const int = len.findDirectExpression(Expressions.Integer);
          if (int) {
            length = parseInt(int.concatTokens(), 10);
          }
        }

        found = new Types.CharacterType(length, qualifiedName); // fallback
        if (this.isOccurs(node)) {
          found = new Types.TableType(found, {withHeader: concat.includes(" WITH HEADER LINE")}, qualifiedName);
        }
      }

    }

    return found;
  }

/////////////////////

  private isOccurs(node: ExpressionNode | StatementNode): boolean {
    if (node.findDirectTokenByText("OCCURS")) {
      return true;
    } else if (node.findFirstExpression(Expressions.TypeTable)?.findDirectTokenByText("OCCURS")) {
      return true;
    }
    return false;
  }

  // todo, rewrite this method
  private resolveTypeChain(expr: ExpressionNode): AbstractType | undefined {
    const chainText = expr.concatTokens().toUpperCase();
    if (chainText.includes("=>") === false && chainText.includes("-") === false) {
      return undefined;
    }

    let className: string | undefined;
    let rest = chainText;
    if (chainText.includes("=>")) {
      const split = chainText.split("=>");
      className = split[0];
      rest = split[1];
    }
    const subs = rest.split("-");
    let foundType: AbstractType | undefined = undefined;

    if (className) {
      const split = chainText.split("=>");
      const className = split[0];

    // the prefix might be itself
      if ((this.scope.getType() === ScopeType.Interface
          || this.scope.getType() === ScopeType.ClassDefinition)
          && this.scope.getName().toUpperCase() === className.toUpperCase()) {
        const foundId = this.scope.findType(subs[0]);
        foundType = foundId?.getType();
        if (foundType === undefined) {
          return new Types.UnknownType("Could not resolve type " + chainText);
        }
        this.scope.addReference(expr.getTokens()[2], foundId, ReferenceType.TypeReference, this.filename);

      } else {
    // lookup in local and global scope
        const obj = this.scope.findObjectDefinition(className);
        if (obj === undefined && this.scope.getDDIC().inErrorNamespace(className) === false) {
          this.scope.addReference(expr.getFirstToken(), undefined,
                                  ReferenceType.ObjectOrientedVoidReference, this.filename, {ooName: className.toUpperCase()});
          return new Types.VoidType(className);
        } else if (obj === undefined) {
          return new Types.UnknownType("Could not resolve top " + className + ", resolveTypeChain");
        }
        const type = obj instanceof ClassDefinition ? "CLAS" : "INTF";

        this.scope.addReference(expr.getFirstToken(), obj, ReferenceType.ObjectOrientedReference, this.filename,
                                {ooType: type, ooName: className});

        const byName = new ObjectOriented(this.scope).searchTypeName(obj, subs[0]);
        foundType = byName?.getType();
        if (byName === undefined || foundType === undefined) {
          return new Types.UnknownType(subs[0] + " not found in class or interface");
        }
        this.scope.addReference(expr.getTokens()[2], byName, ReferenceType.TypeReference, this.filename);

      }
    } else {
      const found = this.scope.findType(subs[0]);
      foundType = found?.getType();
      if (foundType === undefined) {
        const typePoolType = this.scope.findTypePoolType(subs[0])?.getType();
        if (typePoolType) {
//          this.scope.addReference(typeName.getFirstToken(), typePoolType, ReferenceType.TypeReference, this.filename);
          foundType = typePoolType;
        }

        if (foundType === undefined) {
          const f = this.scope.getDDIC().lookupTableOrView(subs[0]);
          this.scope.getDDICReferences().addUsing(this.scope.getParentObj(),
                                                  {object: f.object, filename: this.filename, token: expr.getFirstToken()});
          if (f.type instanceof TypedIdentifier) {
            foundType = f.type.getType();
          } else {
            foundType = f.type;
          }
        }

      } else {
        this.scope.addReference(expr.getFirstToken(), found, ReferenceType.TypeReference, this.filename);
      }
      if (foundType === undefined && this.scope.getDDIC().inErrorNamespace(subs[0]) === false) {
        this.scope.addReference(expr.getFirstToken(), undefined, ReferenceType.VoidType, this.filename);
        return new Types.VoidType(subs[0]);
      } else if (foundType instanceof Types.VoidType) {
        this.scope.addReference(expr.getFirstToken(), undefined, ReferenceType.VoidType, this.filename);
        return foundType;
      } else if (foundType === undefined) {
        return new Types.UnknownType("Unknown type " + subs[0]);
      }
    }

    subs.shift();
    while (subs.length > 0) {
      if (foundType instanceof Types.UnknownType
          || foundType instanceof Types.VoidType) {
        return foundType;
      } else if (!(foundType instanceof Types.StructureType)) {
        return new Types.UnknownType("Not a structured type");
      }
      foundType = foundType.getComponentByName(subs[0]);
      subs.shift();
    }

    return foundType;
  }

  private resolveConstantValue(expr: ExpressionNode): string | undefined {
    if (!(expr.get() instanceof Expressions.SimpleFieldChain)) {
      throw new Error("resolveConstantValue");
    }

    const firstNode = expr.getFirstChild()!;
    const firstToken = firstNode.getFirstToken();
    const firstName = firstToken.getStr();
    if (firstNode.get() instanceof Expressions.Field) {
      const found = this.scope.findVariable(firstName);
      const val = found?.getValue();
      if (typeof val === "string") {
        this.scope.addReference(firstToken, found, ReferenceType.DataReadReference, this.filename);
        return val;
      }
      return undefined;
    } else if (firstNode.get() instanceof Expressions.ClassName
        && firstName.toLowerCase() === this.scope.getName().toLowerCase()
        && (this.scope.getType() === ScopeType.Interface
        || this.scope.getType() === ScopeType.ClassDefinition)) {
      const children = expr.getChildren();
      const token = children[2]?.getFirstToken();
      const found = this.scope.findVariable(token.getStr());
      const val = found?.getValue();
      if (typeof val === "string") {
        this.scope.addReference(firstToken, found, ReferenceType.DataReadReference, this.filename);
        return val;
      }
      return undefined;
    } else if (firstNode.get() instanceof Expressions.ClassName) {
      const obj = this.scope.findObjectDefinition(firstName);
      if (obj === undefined) {
        if (this.scope.existsObject(firstName).found === true) {
          return undefined;
        } else if (this.scope.getDDIC().inErrorNamespace(firstName) === true) {
          throw new Error("resolveConstantValue, not found: " + firstName);
        } else {
          this.scope.addReference(firstNode.getFirstToken(), undefined,
                                  ReferenceType.ObjectOrientedVoidReference, this.filename, {ooName: firstName.toUpperCase()});
          return undefined;
        }
      }
      const children = expr.getChildren();
      const token = children[2]?.getFirstToken();
      const attr = token.getStr();
      const c = new ObjectOriented(this.scope).searchConstantName(obj, attr);
      if (c instanceof ClassConstant) {
        this.scope.addReference(token, c, ReferenceType.DataReadReference, this.filename);
        const val = c.getValue();
        if (typeof val === "string") {
          return val;
        } else if (typeof val === "object" && children[4]) {
          const name = children[4].getFirstToken().getStr();
          if (val[name] !== undefined) {
            return val[name];
          }
        }
        return undefined;
      }
      throw new Error("resolveConstantValue, constant not found " + attr);

    } else {
      throw new Error("resolveConstantValue, unexpected structure");
    }
  }

  private resolveTypeRef(chain: ExpressionNode | undefined): AbstractType | undefined {
    if (chain === undefined) {
      return undefined;
    }

    const name = chain.getFirstToken().getStr();
    if (chain.getAllTokens().length === 1) {
      if (name.toUpperCase() === "OBJECT") {
        return new Types.GenericObjectReferenceType();
      }
      const search = this.scope.existsObject(name);
      if (search.found === true && search.id) {
        this.scope.addReference(chain.getFirstToken(), search.id, ReferenceType.ObjectOrientedReference, this.filename,
                                {ooType: search.ooType, ooName: name});
        return new Types.ObjectReferenceType(search.id, name);
      }
    }

    const found = this.resolveTypeName(chain);
    if (found && !(found instanceof Types.UnknownType) && !(found instanceof Types.VoidType)) {
      return new Types.DataReference(found);
    } else if (chain.concatTokens().toUpperCase() === "DATA") {
      return new Types.DataReference(new Types.AnyType());
    }

    if (this.scope.isBadiDef(name) === true) {
      return new Types.VoidType(name);
    }

    if (this.scope.getDDIC()?.inErrorNamespace(name) === false) {
//      this.scope.addReference(chain.getFirstToken(), undefined, ReferenceType.VoidType, this.filename);
      return new Types.VoidType(name);
    }

    return new Types.UnknownType("REF, unable to resolve " + name);
  }

  public findValue(node: StatementNode): string | undefined {
    const val = node.findFirstExpression(Expressions.Value);
    if (val === undefined) {
      throw new Error("VALUE missing in expression");
    }

    if (val.concatTokens().toUpperCase() === "VALUE IS INITIAL") {
      return undefined;
    }

    const constant = val.findFirstExpression(Expressions.Constant);
    if (constant) {
      return constant.concatTokens();
    }

    const chain = val.findFirstExpression(Expressions.SimpleFieldChain);
    if (chain) {
      return this.resolveConstantValue(chain);
    }

    throw new Error("findValue, unexpected");
  }

  private findDecimals(node: StatementNode | ExpressionNode): number | undefined {
    const dec = node.findDirectExpression(Expressions.Decimals)?.findDirectExpression(Expressions.Integer)?.concatTokens();
    if (dec) {
      return parseInt(dec, 10);
    }
    return undefined;
  }

  private findLength(node: StatementNode | ExpressionNode): number | undefined {
    const val = node.findFirstExpression(Expressions.Length);
    const flen = node.findFirstExpression(Expressions.ConstantFieldLength);

    if (val && flen) {
      throw new Error("Only specify length once");
    }

    if (flen) {
      const cintExpr = flen.findFirstExpression(Expressions.Integer);
      if (cintExpr) {
        return this.parseInt(cintExpr.concatTokens());
      }

      const cchain = flen.findFirstExpression(Expressions.SimpleFieldChain);
      if (cchain) {
        const val = this.resolveConstantValue(cchain);
        return this.parseInt(val);
      }
    }

    if (val === undefined) {
      return 1;
    }

    const intExpr = val.findFirstExpression(Expressions.Integer);
    if (intExpr) {
      return this.parseInt(intExpr.concatTokens());
    }

    const strExpr = val.findFirstExpression(Expressions.ConstantString);
    if (strExpr) {
      return this.parseInt(strExpr.concatTokens());
    }

    const chain = val.findFirstExpression(Expressions.SimpleFieldChain);
    if (chain) {
      const val = this.resolveConstantValue(chain);
      return this.parseInt(val);
    }

    throw new Error("Unexpected, findLength");
  }

  private parseInt(text: string | undefined): number | undefined {
    if (text === undefined) {
      return undefined;
    }

    if (text.startsWith("'")) {
      text = text.split("'")[1];
    } else if (text.startsWith("`")) {
      text = text.split("`")[1];
    }

    return parseInt(text, 10);
  }

}


text:
import sys
import itertools

#from ExcelObjects import *
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Protection
from openpyxl.worksheet import SheetProtection
from openpyxl.styles import fills, colors, Color, PatternFill
from openpyxl.comments import Comment
# for tabColor? from openpyxl.worksheet.properties import WorksheetProperties, PageSetupProperties

def defines():
    exceldef = {}
    exceldef['datasheet'] = 'Daten'
    exceldef['instructsheet'] = 'Anleitung'
    exceldef['firstrow'] = 5
    exceldef['cellcolor'] = Color(rgb = 'FFF9E38C')

    return exceldef

def setColor(cell, color):
    cell.fill = PatternFill(fill_type = 'solid', fgColor = color, bgColor = color)
    #print (cell.fill, cell.fill.fill_type)
    pass

def setDatatype(cell, coltype):
    cell.data_type = coltype['basetype']
    if coltype['num_fmt'] != None:
        cell.number_format = coltype['num_fmt']

def writeExcelFile (args, protect_headers = True, protect_ids = True, striped = True, datatypes = True, sortable = False):
    templateFilepath = args[0];
    targetFilepath = args[1];
    firstTubeNo = args[2];
    lastTubeNo = args[3];
    transactionId = args[4];
    try:
        lang = args[5]
    except IndexError:
        lang = "de"

    exceldef = defines()

    #set transactionId
    workbook = load_workbook(templateFilepath)
    workbook.properties.subject = transactionId

    #get references to sheets
    datasheet = workbook.get_sheet_by_name(exceldef['datasheet'])
    instructsheet = workbook.get_sheet_by_name(exceldef['instructsheet'])
    #helpsheet = workbook.get_sheet_by_name(exceldef['helpsheet'])

    #check datasheet size, raise error when endless rows or cols are formated
    #print (datasheet.max_column)
    if datasheet.max_column > 1023:
        raise ValueError ('excel datasheet has too much columns, check that only needed columns have been formated')
    #print (datasheet.max_row)
    if datasheet.max_row > 1023:
        raise ValueError ('excel datasheet has too much rows, check that only needed rows have been formated')

    #enable protection to switch the feature on
    if protect_headers == True or protect_ids == True:
        sheets = workbook.get_sheet_names()
        for sheetname in sheets:
            sheet = workbook.get_sheet_by_name(sheetname)
            sheet.protection.enable()

    #shortnames for rows to insert
    firstrow = exceldef['firstrow']
    lastrow = exceldef['firstrow'] + int(lastTubeNo) - int(firstTubeNo)

    #state of protection depends on last saved state and must be revisited for each cell
    for row in itertools.islice(datasheet.iter_rows(), 0, firstrow -1):
        for cell in row:
            if protect_headers == True and cell.comment == None: #cell protection deletes comments:
                cell.protection = Protection(locked = True, hidden = False)
            else:
                cell.protection = Protection(locked = False, hidden = False)

    #iterate through data cell and set properties
    #first read data type for column from example row
    coltype = {}
    for row in itertools.islice(datasheet.iter_rows(), firstrow -2, firstrow -1):
        for cell in row:
            #enabling arrows for column sorting in example row means to disable protection in tubenumber column and in the example fields
            if sortable == True:
                cell.protection = Protection(locked = False, hidden = False)

            coltype[cell.col_idx] = {}
            coltype[cell.col_idx]['basetype'] = cell.data_type

            if coltype[cell.col_idx]['basetype'] == 'n':
                coltype[cell.col_idx]['num_fmt'] = cell.number_format
            else:
                coltype[cell.col_idx]['num_fmt'] = None

            #print (cell.value, coltype[cell.col_idx]['basetype'], coltype[cell.col_idx]['num_fmt'])

    #release protection for cells to be filled by collectors, apply data constraints
    colcount = datasheet.max_column
    for col in range (1, colcount + 1, 1):
        for row in range (firstrow, lastrow + 1, 1):
            cell = datasheet.cell(column = col, row = row)
            cell.protection = Protection(locked = False, hidden = False)

            if datatypes == True:
                setDatatype(cell, coltype[col])

            if col == 1: #set color to each cell of tubenumber column
                setColor(cell, exceldef['cellcolor'])
            elif striped == True and int(row) % 2 == 0: # set colors for data cells, striped
                setColor(cell, exceldef['cellcolor'])

    #insert tubenumbers to column 1 in datasheet
    # do this after data_type was set
    rownum = firstrow
    for tube in range (int(firstTubeNo), int(lastTubeNo) + 1, 1):
        cell = datasheet.cell(column = 1, row = rownum)
        cell.value = tube
        rownum += 1
        #set protection, but it is only active when sheet protection is set above
        if protect_ids == True:
            cell.protection = Protection(locked = True, hidden = False)

    #reset style and content for rows not used by tubes
    rowcount = datasheet.max_row
    for row in itertools.islice(datasheet.iter_rows(), lastrow, rowcount):
        for cell in row:
            cell.value = None
            cell.fill = PatternFill(fill_type = None)
            cell.protection = Protection(locked = False, hidden = False)

    workbook.save(targetFilepath)
    return targetFilepath

if __name__ == "__main__":

    if len(sys.argv) < 5:
        sys.exit ('''Write GBOL Collection Sheet.
    Usage:        {0} templateFilepath targetFilepath firstTubeNo lastTubeNo transactionId lang
        templateFilepath:   Path and filename of template collection sheet, e.g. documents/download/Sammeltabelle_GBOL_2014-10-14.xls
        targetFilepath:     Path and filename of desired collection sheet, e.g. documents/download/700_2015-02-18_000000.xls
        firstTubeNo:        Number of the first tube, e.g. 3500760
        lastTubeNo:         Number of the last tube, e.g. 3500854
        transactionId:      Transaction id as generated during material order, e.g. 700_2015-02-18_000000
        lang:               Current language (not used)

    Example:
        {0} documents/download/Sammeltabelle_GBOL_2014-10-14.xls documents/download/700_2015-02-18_000000.xls 3500760 3500854 700_2015-02-18_000000
    '''.format(sys.argv[0]))

    else:
        args = sys.argv[1:]
        filepath = writeExcelFile(args)


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
Copyright (C) 2004, 2007, 2009 Ferdinando Ametrano

This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/

QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license.  You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/math/matrixutilities/getcovariance.hpp>

namespace QuantLib {

    CovarianceDecomposition::CovarianceDecomposition(const Matrix& cov,
                                                     Real tolerance)
    : variances_(cov.diagonal()), stdDevs_(Array(cov.rows())),
      correlationMatrix_(Matrix(cov.rows(), cov.rows()))
    {
        Size size = cov.rows();
        QL_REQUIRE(size==cov.columns(),
                   "input covariance matrix must be square, it is [" <<
                   size << "x" << cov.rows() << "]");

        for (Size i=0; i<size; ++i)
        {
            stdDevs_[i] = std::sqrt(variances_[i]);
            correlationMatrix_[i][i] = 1.0;
            for (Size j=0; j<i; ++j)
            {
                QL_REQUIRE(std::fabs(cov[i][j]-cov[j][i]) <= tolerance,
                           "invalid covariance matrix:" <<
                           "\nc[" << i << ", " << j << "] = " <<
                           cov[i][j] << "\nc[" << j << ", " << i <<
                           "] = " << cov[j][i]);
                correlationMatrix_[i][j] = correlationMatrix_[j][i] =
                    cov[i][j]/(stdDevs_[i]*stdDevs_[j]);
            }
        }
    }
}


text:
Do Not Eat The Dead
===================

This is a little tool to generate a ~/.XCompose file which does not
consume dead keys unless they are part of a valid composed characted.

By default, when you configure your keyboard in X11 to use one of the
international variants [1] you can compose characters using dead keys
-- for example, _~n_ becomes _ñ_.  However, _~p_ is meaningless, so
doesn't output anything.  This is jarring if you're used to dead keys
as they are implemented on Microsoft Windows, where _~p_ would just
output _~p_.

X11 can easily be configured to output _~p_ for _~p_, but it would be
a lot of work to manually write a .XCompose file for every possible
invalid combination.  So I've cobbled together a short python script
to do this task, you can use it like this:

         ./do-not-eat-the-dead > ~/.XCompose

Obviously you may want to make a backup of your previous XCompose
file.  The script requires python and has only been tested with python
2.7.

[1] Like this:
    setxkbmap -layout us -variant intl -option ctrl:nocaps
    setxkbmap -layout us -variant dvorak-intl -option ctrl:nocaps

Configuring GTK/KDE
===================

~/.XCompose is used by the X Input Method, so in order for the file to
work you will have to make sure your applications use the correct
input method.  Add the following environment settings to your
~/.xinitrc or ~/.xsessionrc:

    export DISABLE_IMSETTINGS=yes
    export GTK_IM_MODULE=xim
    export QT_IM_MODULE=xim

License
=======

Copyright 2012, Kuno Woudt <kuno@frob.nl>

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.


text:
(function() {
    'use strict';

    angular
        .module('gatewayApp')
        .controller('TransferDeleteController',TransferDeleteController);

    TransferDeleteController.$inject = ['$uibModalInstance', 'entity', 'Transfer'];

    function TransferDeleteController($uibModalInstance, entity, Transfer) {
        var vm = this;

        vm.transfer = entity;
        vm.clear = clear;
        vm.confirmDelete = confirmDelete;

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function confirmDelete (id) {
            Transfer.delete({id: id},
                function () {
                    $uibModalInstance.close(true);
                });
        }
    }
})();