text:
package org.apache.rocketmq.client.trace;

import org.apache.rocketmq.common.message.MessageClientIDSetter;

import java.util.List;

/**
 * The context of Trace
 */
public class TraceContext implements Comparable<TraceContext> {

    private TraceType traceType;
    private long timeStamp = System.currentTimeMillis();
    private String regionId = "";
    private String regionName = "";
    private String groupName = "";
    private int costTime = 0;
    private boolean isSuccess = true;
    private String requestId = MessageClientIDSetter.createUniqID();
    private int contextCode = 0;
    private List<TraceBean> traceBeans;

    public int getContextCode() {
        return contextCode;
    }

    public void setContextCode(final int contextCode) {
        this.contextCode = contextCode;
    }

    public List<TraceBean> getTraceBeans() {
        return traceBeans;
    }

    public void setTraceBeans(List<TraceBean> traceBeans) {
        this.traceBeans = traceBeans;
    }

    public String getRegionId() {
        return regionId;
    }

    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    public TraceType getTraceType() {
        return traceType;
    }

    public void setTraceType(TraceType traceType) {
        this.traceType = traceType;
    }

    public long getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public int getCostTime() {
        return costTime;
    }

    public void setCostTime(int costTime) {
        this.costTime = costTime;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public String getRegionName() {
        return regionName;
    }

    public void setRegionName(String regionName) {
        this.regionName = regionName;
    }

    @Override
    public int compareTo(TraceContext o) {
        return (int) (this.timeStamp - o.getTimeStamp());
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(1024);
        sb.append(traceType).append("_").append(groupName)
            .append("_").append(regionId).append("_").append(isSuccess).append("_");
        if (traceBeans != null && traceBeans.size() > 0) {
            for (TraceBean bean : traceBeans) {
                sb.append(bean.getMsgId() + "_" + bean.getTopic() + "_");
            }
        }
        return "TraceContext{" + sb.toString() + '}';
    }
}


text:
Bike Details

Brand: <input ng-model="ctrl.bike.name">

Price: <input type="number" ng-model="ctrl.bike.price">

Year: <input type="number" ng-model="ctrl.bike.year">

Previous Owner:<input ng-model="ctrl.bike.previousOwners">

    <button ng-click="ctrl.bike.addAccessory('', '')">Add Accessory</button>

Item: <input ng-model="accessory.description">

Price: <input type="number" ng-model="accessory.cost">

        <button  style="padding:0px; margin-top: 6px;" ng-click="ctrl.bike.deleteAccessory(accessory)">Remove Accessory</button>

    <button ng-click="ctrl.submitBike();" type="submit">Submit Bike</button>

    <button ng-click="ctrl.cancel();" type="submit">Cancel</button>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		#parse('front/_pagelet/Common.IndexHeader.html')
		<link rel='stylesheet' type='text/css' href='/public/assets/css/manage/1.0.1/index.css' />
		<link rel='stylesheet' type='text/css' href='/public/assets/css/manage/1.0.1/iframe.css' />

 后台管理

项目管理

编辑

							#parse('manage/project/_pagelet/Side.Form.html')

		#parse('front/_pagelet/Common.IndexJs.html')
		#parse('manage/_pagelet/Common.Iframe.html')


text:
;==============================================================================
;   HAPCAN - Home Automation Project Firmware (http://hapcan.com)
;   Copyright (C) 2013 hapcan.com
;
;   This program is free software: you can redistribute it and/or modify
;   it under the terms of the GNU General Public License as published by
;   the Free Software Foundation, either version 3 of the License, or
;   (at your option) any later version.
;
;   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
;   GNU General Public License for more details.
;
;   You should have received a copy of the GNU General Public License
;   along with this program.  If not, see <http://www.gnu.org/licenses/>.
;==============================================================================
;   Filename:              univ_3-1-0-0.asm
;   Associated diagram:    univ_3-1-0-x.sch
;   Author:                Jacek Siwilo
;   Note:                  8 channel button
;==============================================================================
;   Revision History
;   Rev:  Date:     Details:
;   0     08.2013   Original version
;==============================================================================
;===  FIRMWARE DEFINITIONS  ===================================================
;==============================================================================
    #define    ATYPE    .1                            ;application type [0-255]
    #define    AVERS    .0                         ;application version [0-255]
    #define    FVERS    .0                            ;firmware version [0-255]

    #define    FREV     .0                         ;firmware revision [0-65536]
;==============================================================================
;===  NEEDED FILES  ===========================================================
;==============================================================================
    LIST P=18F26K80                              ;directive to define processor
    #include <P18F26K80.INC>           ;processor specific variable definitions
    #include "univ_3-1-0-0-rev0.inc"                         ;project variables
INCLUDEDFILES   code
    #include "univ3-routines-rev2.inc"                     ;UNIV 3 CPU routines
    #include "univ3-fake_bootloader-rev2.inc"    ;fake bootloader for debugging

;==============================================================================
;===  FIRMWARE CHECKSUM  ======================================================
;==============================================================================
FIRMCHKSM   code    0x001000
    DB      0x67, 0x85, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
;==============================================================================
;===  FIRMWARE ID  ============================================================
;==============================================================================
FIRMID      code    0x001010
    DB      0x30, 0x00, 0x03,ATYPE,AVERS,FVERS,FREV>>8,FREV
;            |     |     |     |     |     |     |_____|_____ firmware revision
;            |     |     |     |     |     |__________________ firmware version
;            |     |     |     |     |_____________________ application version
;            |     |     |     |______________________________ application type
;            |     |     |________________________________ hardware version '3'
;            |_____|______________________________________ hardware type 'UNIV'
;==============================================================================
;===  MOVED VECTORS  ==========================================================
;==============================================================================
;PROGRAM RESET VECTOR
FIRMRESET   code    0x1020
        goto    Main
;PROGRAM HIGH PRIORITY INTERRUPT VECTOR
FIRMHIGHINT code    0x1030
        call    HighInterrupt
        retfie
;PROGRAM LOW PRIORITY INTERRUPT VECTOR
FIRMLOWINT  code    0x1040
        call    LowInterrupt
        retfie

;==============================================================================
;===  FIRMWARE STARTS  ========================================================
;==============================================================================
FIRMSTART   code    0x001050
;------------------------------------------------------------------------------
;---  LOW PRIORITY INTERRUPT  -------------------------------------------------
;------------------------------------------------------------------------------
LowInterrupt
        movff   STATUS,STATUS_LOW           ;save STATUS register
        movff   WREG,WREG_LOW               ;save working register
        movff   BSR,BSR_LOW                 ;save BSR register
        movff   FSR0L,FSR0L_LOW             ;save other registers used in high int
        movff   FSR0H,FSR0H_LOW
        movff   FSR1L,FSR1L_LOW
        movff   FSR1H,FSR1H_LOW

    ;main firmware ready flag
        movlb   0x1
        btfss   FIRMREADY,0
        bra     ExitLowInterrupt            ;main firmware is not ready yet
    ;CAN buffer
        movlb   0x1
        btfsc   CANFULL,0                   ;check if CAN received anything
        call    CANInterrupt                ;proceed with CAN interrupt

ExitLowInterrupt
        movff   BSR_LOW,BSR                 ;restore BSR register
        movff   WREG_LOW,WREG               ;restore working register
        movff   STATUS_LOW,STATUS           ;restore STATUS register
        movff   FSR0L_LOW,FSR0L             ;restore other registers used in high int
        movff   FSR0H_LOW,FSR0H
        movff   FSR1L_LOW,FSR1L
        movff   FSR1H_LOW,FSR1H
    return

;------------------------------------------------------------------------------
;---  HIGH PRIORITY INTERRUPT  ------------------------------------------------
;------------------------------------------------------------------------------
HighInterrupt
        movff   STATUS,STATUS_HIGH          ;save STATUS register
        movff   WREG,WREG_HIGH              ;save working register
        movff   BSR,BSR_HIGH                ;save BSR register
        movff   FSR0L,FSR0L_HIGH            ;save other registers used in high int
        movff   FSR0H,FSR0H_HIGH
        movff   FSR1L,FSR1L_HIGH
        movff   FSR1H,FSR1H_HIGH

    ;main firmware ready flag
        movlb   0x1
        btfss   FIRMREADY,0
        bra     ExitHighInterrupt           ;main firmware is not ready yet
    ;Timer0
		btfsc	INTCON,TMR0IF			    ;Timer0 interrupt? (1000ms)
		rcall	Timer0Interrupt
	;Timer2
        btfsc	PIR1,TMR2IF		    	    ;Timer2 interrupt? (20ms)
		rcall	Timer2Interrupt

ExitHighInterrupt
        movff   BSR_HIGH,BSR                ;restore BSR register
        movff   WREG_HIGH,WREG              ;restore working register
        movff   STATUS_HIGH,STATUS          ;restore STATUS register
        movff   FSR0L_HIGH,FSR0L            ;restore other registers used in high int
        movff   FSR0H_HIGH,FSR0H
        movff   FSR1L_HIGH,FSR1L
        movff   FSR1H_HIGH,FSR1H
    return

;------------------------------------------------------------------------------
; Routine:			CAN INTERRUPT
;------------------------------------------------------------------------------
; Overview:			Checks CAN message for response and RTR and saves to FIFO
;------------------------------------------------------------------------------
CANInterrupt
		banksel CANFRAME2
		btfsc	CANFRAME2,0				    ;response message?
	return                                  ;yes, so ignore it and exit
		btfsc	CANFRAME2,1                 ;RTR (Remote Transmit Request)?
	return                                  ;yes, so ignore it and exit
        call    Copy_RXB_RXFIFOIN           ;copies received message to CAN RX FIFO input buffer
        call    WriteToCanRxFIFO		    ;saves message to FIFO
    return

;------------------------------------------------------------------------------
; Routine:			TIMER 0 INTERRUPT
;------------------------------------------------------------------------------
; Overview:			1000ms periodical interrupt
;------------------------------------------------------------------------------
Timer0Interrupt:
        call    Timer0Initialization8MHz    ;restart 1000ms Timer
        call    UpdateUpTime                ;counts time from restart
        call    UpdateTransmitTimer         ;increment transmit timer (seconds after last transmission)
        setf    Timer0_1000ms               ;timer 0 interrupt occurred flag
    return

;------------------------------------------------------------------------------
; Routine:			TIMER 2 INTERRUPT
;------------------------------------------------------------------------------
; Overview:			20ms periodical interrupt
;------------------------------------------------------------------------------
Timer2Interrupt
        rcall   Timer2Initialization        ;restart timer
        rcall   ReadInputs                  ;read port
        setf    Timer2_20ms                 ;timer 2 interrupt occurred flag
    return
;-------------------------------
Timer2Initialization
        movlb   0xF
        bcf     PMD1,TMR2MD                 ;enable timer 2
        movlw   0x3F
		movwf	TMR2                        ;set 20ms (19.999500)
		movlw	b'01001111'				    ;start timer, prescaler=16, postscaler=10
		movwf	T2CON
        bsf     IPR1,TMR2IP                 ;high priority for interrupt
		bcf		PIR1,TMR2IF			        ;clear timer's flag
		bsf		PIE1,TMR2IE			        ;interrupt on
    return
;-------------------------------
ReadInputs
        movff   PORTC,Buttons               ;move current states to Buttons
    return

;==============================================================================
;===  MAIN PROGRAM  ===========================================================
;==============================================================================
Main:
    ;disable global interrupts for startup
        call    DisAllInt                   ;disable all interrupts
    ;initiate ports                         ;default all pins set as analog (portA,B) and digital (portB,C) inputs
        rcall   PortInitialization          ;prepare processor ports
    ;firmware initialization
        call    GeneralInitialization       ;read eeprom config, clear other registers
        call    FIFOInitialization          ;prepare FIFO buffers
		call	Timer0Initialization32MHz   ;Timer 0 initialization for 1s periodical interrupt
        call    Timer2Initialization        ;Timer 2 initialization for 20ms periodical interrupt
		call	ButtonPowerUpValues         ;button on power up values
    ;firmware ready
        movlb   0x1
        bsf     FIRMREADY,0                 ;set flag "firmware started and ready for interrupts"
    ;enable global interrupts
        call    EnAllInt                    ;enable all interrupts

;-------------------------------
Loop:                                       ;main loop
        clrwdt                              ;clear Watchdog timer
        call    ReceiveProcedure            ;check if any msg in RX FIFO and if so - process the msg
        call    TransmitProcedure           ;check if any msg in TX FIFO and if so - transmit it
        rcall   OnceA20ms                   ;do routines only after 20ms interrupt
        rcall   OnceA1000ms                 ;do routines only after 1000ms interrupt
    bra     Loop

;-------------------------------
OnceA20ms                                   ;procedures executed once per 1000ms (flag set in interrupt)
        tstfsz  Timer2_20ms                 ;flag set?
        bra     $ + 4
    return                                  ;no, so exit
        call    RecognizeButtons            ;recognize what button is pressed
        clrf    Timer2_20ms
    return
;-------------------------------
OnceA1000ms                                 ;procedures executed once per 1000ms (flag set in interrupt)
        tstfsz  Timer0_1000ms               ;flag set?
        bra     $ + 4
    return                                  ;no, so exit
        call    UpdateHealthRegs            ;saves health maximums to eeprom
        clrf    Timer0_1000ms
    return

;==============================================================================
;===  FIRMWARE ROUTINES  ======================================================
;==============================================================================
;------------------------------------------------------------------------------
; Routine:			PORT INITIALIZATION
;------------------------------------------------------------------------------
; Overview:			It sets processor pins. All unused pins should be set as
;                   outputs and driven low
;------------------------------------------------------------------------------
PortInitialization
    ;PORT A
        banksel ANCON0                      ;select memory bank
        ;0-digital, 1-analog input
        movlw   b'00000011'                 ;(x,x,x,AN4,AN3,AN2,AN1-boot_mode,AN0-volt)
        movwf   ANCON0
        ;output level
        clrf    LATA                        ;all low
        ;0-output, 1-input
        movlw   b'00000011'                 ;all outputs except, bit<1>-boot_mode, bit<0>-volt
        movwf   TRISA
    ;PORT B
        ;0-digital, 1-analog input
        movlw   b'00000000'                 ;(x,x,x,x,x,AN10,AN9,AN8)
        movwf   ANCON1
        ;output level
        clrf    LATB                        ;all low
        ;0-output, 1-input
        movlw   b'00001000'                 ;all output except CANRX
        movwf   TRISB
    ;PORT C
        ;output level
        clrf    LATC                        ;all low
        ;0-output, 1-input
        movlw   b'11111111'                 ;all intput
        movwf   TRISC
    return

;------------------------------------------------------------------------------
; Routine:			NODE STATUS
;------------------------------------------------------------------------------
; Overview:			It prepares status messages when status request was
;                   received
;------------------------------------------------------------------------------
NodeStatusRequest

;------buttons---------------
ButtonStatus: MACRO ButNr                  ;macro sends status for chosen button
		movlw	ButNr                       ;button x
		movwf	TXFIFOIN6
		setf	WREG                        ;0xFF - pressed
		btfsc	Buttons,ButNr-1
		clrf	WREG                        ;0x00 - released
		movwf	TXFIFOIN7
		setf	TXFIFOIN8
		rcall	SendButtonStatus
    ENDM
;------------
        banksel TXFIFOIN0
        ButtonStatus   .1                   ;button 1, call macro, /macro_arg: Button_No, Button_REGISTER/
        ButtonStatus   .2                   ;button 2
        ButtonStatus   .3                   ;button 3
        ButtonStatus   .4                   ;button 4
        ButtonStatus   .5                   ;button 5
        ButtonStatus   .6                   ;button 6
        ButtonStatus   .7                   ;button 7
        ButtonStatus   .8                   ;button 8
    return
;------------
SendButtonStatus
        movlw   0x30			            ;set relay frame
		movwf   TXFIFOIN0
        movlw   0x10
		movwf   TXFIFOIN1
		bsf		TXFIFOIN1,0					;response bit
		movff	NODENR,TXFIFOIN2            ;node id
		movff	GROUPNR,TXFIFOIN3
		setf	TXFIFOIN4				    ;unused
		setf	TXFIFOIN5				    ;unused
		setf	TXFIFOIN9				    ;unused
		setf	TXFIFOIN10				    ;unused
		setf	TXFIFOIN11				    ;unused
		call	WriteToCanTxFIFO
	return

;------------------------------------------------------------------------------
; Routine:			DO INSTRUCTION
;------------------------------------------------------------------------------
; Overview:			Executes instruction immediately or sets timer for later
;                   execution
;------------------------------------------------------------------------------
DoInstructionRequest
        banksel INSTR1

;Check if timer is needed
   ;    movff   INSTR3,TIMER                ;/timer is not used/
   ;    tstfsz	TIMER				        ;is timer = 0?
   ;    bra		$ + 8				        ;no
		call	DoInstructionNow	        ;yes
	return
   ;    call	DoInstructionLater          ;save instruction for later execution
   ;    return

;-------------------------------
;Recognize instruction
DoInstructionNow
	return                                  ;no instructions

;------------------------------------------------------------------------------
; Routine:			DO INSTRUCTION LATER
;------------------------------------------------------------------------------
; Overview:			It saves instruction for particular channel for later
;                   execution
;------------------------------------------------------------------------------
DoInstructionLater
	return                                  ;no instructions

;==============================================================================
;                   BUTTON PROCEDURES
;==============================================================================
;------------------------------------------------------------------------------
; Routine:			BUTTON POWER UP VALUES
;------------------------------------------------------------------------------
; Overview:			Sets registers at power up
;------------------------------------------------------------------------------
ButtonPowerUpValues
		setf	Buttons          		    ;buttons status as released
        movlw   .8                          ;clear counters
        lfsr    FSR0,BUT1Cnt
        clrf    POSTINC0
        decfsz  WREG
        bra     $ - 4
    return

;------------------------------------------------------------------------------
; Routine:			RECOGNIZE BUTTONS
;------------------------------------------------------------------------------
; Overview:			Recognizes which button is pressed and for how long.
;                   Routine also sends button message to the CAN bus.
;------------------------------------------------------------------------------
RecognizeButtons
		call	Button1_ON
		call	Button1_OFF
		call	Button2_ON
		call	Button2_OFF
		call	Button3_ON
		call	Button3_OFF
		call	Button4_ON
		call	Button4_OFF
		call	Button5_ON
		call	Button5_OFF
		call	Button6_ON
		call	Button6_OFF
		call	Button7_ON
		call	Button7_OFF
		call	Button8_ON
		call	Button8_OFF
    return

;----------------------------
Button_IncCnt:MACRO ButCnt                  ;increment but don't overflow button counter
		incfsz	ButCnt
		bra		$ + 4
		decf	ButCnt
    ENDM
;------------
Button_Pressed:MACRO ButNr,ButCnt           ;counter equal 2 (40ms-button pressed)
        banksel BUTCnfg                     ;turn on in config?
		btfss	BUTCnfg+ButNr-1,0
	bra $ + .22                             ;no - go to macro end
        movlw   .2                          ;counter = 2?
        cpfseq  ButCnt
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFF
        movwf   TXFIFOIN7                   ;button code 0xFF - pressed
        call    TransmitButton
    ENDM
;------------
Button_400ms:MACRO ButNr,ButCnt             ;counter equal 20 (400ms-button pressed)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,1
	bra $ + .22                             ;no - go to macro end
		movlw   .20                         ;counter =20?
		cpfseq  ButCnt                      ;skip if so
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFE
        movwf   TXFIFOIN7                   ;button code 0xFE - pressed for 400ms
		call    TransmitButton
	ENDM
;------------
Button_4s:MACRO ButNr,ButCnt                ;counter equal 200 (4s-button pressed)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,2
	bra $ + .22                             ;no - go to macro end
		movlw   .200                        ;counter =200?
		cpfseq  ButCnt                      ;skip if so
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFD
        movwf   TXFIFOIN7                   ;button code 0xFD - pressed for 4s
		call    TransmitButton
	ENDM
;------------
Button_Released:MACRO ButNr,ButCnt          ;counter >2 (released after 20ms)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,3
	bra $ + .24                             ;no - go to macro end
        movlw   .2                          ;counter >=2?
        cpfslt  ButCnt                      ;to send msg counter must be at least 2 to make sure "pressed msg" was send
        bra     $ + 4                       ;if counter <2 means button was in the same state, so do not send msg
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0x00
        movwf   TXFIFOIN7                   ;button code 0x00 - released
        call    TransmitButton
	ENDM
;------------
Button_60_400ms:MACRO ButNr,ButCnt          ;2 < counter < 20 (release before 400ms)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,4
	bra $ + .30                             ;no - go to macro end
        movlw   .2                          ;counter >=2?
        cpfslt  ButCnt                      ;to send msg counter must be at least 2 to make sure "pressed msg" was send
        bra     $ + 4                       ;if counter <2 means button was in the same state, so do not send msg
	bra $ + .22                             ;no - go to macro end
        movlw   .20                         ;counter <20?
        cpfslt  ButCnt                      ;skip if so
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFC
        movwf   TXFIFOIN7                   ;button code 0xFC - released within 400ms
		call    TransmitButton
	ENDM
;------------
Button_400_4s:MACRO ButNr,ButCnt            ;20 < counter < 200 (released between 400ms and 4s)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,5
	bra $ + .30                             ;no - go to macro end
        movlw   .20                         ;counter >=20?
        cpfslt  ButCnt                      ;to send msg counter must be at least 20
        bra     $ + 4                       ;if not do not send msg
	bra $ + .22                             ;no - go to macro end
        movlw   .200                        ;counter <200?
        cpfslt  ButCnt                      ;skip if so
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFB
        movwf   TXFIFOIN7                   ;button code 0xFB - released within 4s
		call    TransmitButton
	ENDM
;------------
Button_4s_infin:MACRO ButNr,ButCnt          ;200 < counter < infinity (released after 4s)
        banksel BUTCnfg                     ;turn on in config?
        btfss   BUTCnfg+ButNr-1,6
	bra $ + .24                             ;no - go to macro end
        movlw   .200                        ;counter >=200?
        cpfslt  ButCnt                      ;to send msg counter must be at least 200
        bra     $ + 4                       ;if not do not send msg
	bra $ + .16                             ;no - go to macro end
        banksel TXFIFOIN0
        movlw   ButNr                       ;set button number in msg to be sent
        movwf   TXFIFOIN6
		movlw   0xFA
        movwf   TXFIFOIN7                   ;button code 0xFA - released after 4s
		call    TransmitButton
	ENDM
;------------
TransmitButton
        banksel TXFIFOIN0
		movlw	0x30				    	;set frame type
		movwf	TXFIFOIN0
		movlw	0x10
		movwf	TXFIFOIN1
		movff	NODENR,TXFIFOIN2            ;node id
		movff	GROUPNR,TXFIFOIN3
		setf	TXFIFOIN4				    ;unused
		setf	TXFIFOIN5			    	;unused
		;(TXFIFOIN6 -TXFIFOIN7) are already changed in macro
        setf    TXFIFOIN8
		setf	TXFIFOIN9				    ;unused
		setf	TXFIFOIN10			    	;unused
		setf	TXFIFOIN11				    ;unused
		call	WriteToCanTxFIFO
    ;node can respond to its own message
        bcf     INTCON,GIEL                 ;disable low priority intr to make sure RXFIFO buffer is not overwritten
        call    Copy_TXFIFOIN_RXFIFOIN
        call    WriteToCanRxFIFO
        bsf     INTCON,GIEL                 ;enable back interrupt
    return

;------------
ButtonON:MACRO ButNr,ButCnt                 ;do all needed routines when button is pressed
        Button_IncCnt   ButCnt              ;increment button counter      /macro_arg: Button_COUNTER/
        Button_Pressed  ButNr,ButCnt        ;button pressed?               /macro_arg: Button_No, Button_COUNTER/
        Button_400ms    ButNr,ButCnt        ;button held for 400ms?        /macro_arg: Button_No, Button_COUNTER/
        Button_4s       ButNr,ButCnt        ;button held for 4s?           /macro_arg: Button_No, Button_COUNTER/
	ENDM
;------------
ButtonOFF:MACRO ButNr,ButCnt                ;do all needed routines when button is released
        Button_Released ButNr,ButCnt        ;button released?              /macro_arg: Button_No, Button_COUNTER/
        Button_60_400ms ButNr,ButCnt        ;button released within 400ms? /macro_arg: Button_No, Button_COUNTER/
        Button_400_4s   ButNr,ButCnt        ;button released within 4s?    /macro_arg: Button_No, Button_COUNTER/
		Button_4s_infin ButNr,ButCnt        ;button released after 4s?     /macro_arg: Button_No, Button_COUNTER/
        clrf	ButCnt                      ;reset counter
	ENDM

;----------button 1----------
Button1_ON:
        btfsc   Buttons,0                   ;button on?
    return                                  ;no
        ButtonON   .1,BUT1Cnt               ;all routines for button ON /macro_arg: Button_No, Button_COUNTER/
    return
;------------
Button1_OFF:
        btfss   Buttons,0                   ;button off?
    return                                  ;no
        ButtonOFF  .1,BUT1Cnt               ;all routines for button OFF /macro_arg: Button_No, Button_COUNTER/
    return
;----------button 2----------
Button2_ON:
        btfsc   Buttons,1
    return
        ButtonON   .2,BUT2Cnt
    return
;------------
Button2_OFF:
        btfss   Buttons,1
    return
        ButtonOFF  .2,BUT2Cnt
    return
;----------button 3----------
Button3_ON:
        btfsc   Buttons,2
    return
        ButtonON   .3,BUT3Cnt
    return
;------------
Button3_OFF:
        btfss   Buttons,2
    return
        ButtonOFF  .3,BUT3Cnt
    return
;----------button 4----------
Button4_ON:
        btfsc   Buttons,3
    return
        ButtonON   .4,BUT4Cnt
    return
;------------
Button4_OFF:
        btfss   Buttons,3
    return
        ButtonOFF  .4,BUT4Cnt
    return
;----------button 5----------
Button5_ON:
        btfsc   Buttons,4
    return
        ButtonON   .5,BUT5Cnt
    return
;------------
Button5_OFF:
        btfss   Buttons,4
    return
        ButtonOFF  .5,BUT5Cnt
    return
;----------button 6----------
Button6_ON:
        btfsc   Buttons,5
    return
        ButtonON   .6,BUT6Cnt
    return
;------------
Button6_OFF:
        btfss   Buttons,5
    return
        ButtonOFF  .6,BUT6Cnt
    return
;----------button 7----------
Button7_ON:
        btfsc   Buttons,6
    return
        ButtonON   .7,BUT7Cnt
    return
;------------
Button7_OFF:
        btfss   Buttons,6
    return
        ButtonOFF  .7,BUT7Cnt
    return
;----------button 8----------
Button8_ON:
        btfsc   Buttons,7
    return
        ButtonON   .8,BUT8Cnt
    return
;------------
Button8_OFF:
        btfss   Buttons,7
    return
        ButtonOFF  .8,BUT8Cnt
    return

;==============================================================================
;===  END  OF  PROGRAM  =======================================================
;==============================================================================
    END


text:
/**
 * Created by IntelliJ IDEA.
 * User: dsl
 * Date: Nov 15, 2002
 * Time: 5:21:33 PM
 * To change this template use Options | File Templates.
 */
package com.intellij.refactoring.introduceVariable;

import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.LanguageRefactoringSupport;
import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.*;
import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.*;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer;
import com.intellij.refactoring.ui.TypeSelectorManagerImpl;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.FieldConflictsResolver;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.occurences.ExpressionOccurenceManager;
import com.intellij.refactoring.util.occurences.NotInSuperCallOccurenceFilter;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

public abstract class IntroduceVariableBase extends IntroduceHandlerBase implements RefactoringActionHandler {
  private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceVariable.IntroduceVariableBase");
  @NonNls private static final String PREFER_STATEMENTS_OPTION = "introduce.variable.prefer.statements";

  protected static String REFACTORING_NAME = RefactoringBundle.message("introduce.variable.title");

  public static SuggestedNameInfo getSuggestedName(PsiType type, final PsiExpression expression) {
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject());
    final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expression, type);
    final String[] strings = JavaCompletionUtil
      .completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo);
    final SuggestedNameInfo.Delegate delegate = new SuggestedNameInfo.Delegate(strings, nameInfo);
    return codeStyleManager.suggestUniqueVariableName(delegate, expression, true);
  }

  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, DataContext dataContext) {
    final SelectionModel selectionModel = editor.getSelectionModel();
    if (!selectionModel.hasSelection()) {
      final int offset = editor.getCaretModel().getOffset();
      final PsiElement[] statementsInRange = findStatementsAtOffset(editor, file, offset);

      //try line selection
      if (statementsInRange.length == 1 && (PsiUtil.hasErrorElementChild(statementsInRange[0]) || !PsiUtil.isStatement(statementsInRange[0]) || isPreferStatements())) {
        selectionModel.selectLineAtCaret();
        if (findExpressionInRange(project, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) == null) {
          selectionModel.removeSelection();
        }
      }

      if (!selectionModel.hasSelection()) {
        final List<PsiExpression> expressions = collectExpressions(file, editor, offset, statementsInRange);
        if (expressions.isEmpty()) {
          selectionModel.selectLineAtCaret();
        } else if (expressions.size() == 1) {
          final TextRange textRange = expressions.get(0).getTextRange();
          selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
        }
        else {
          IntroduceTargetChooser.showChooser(editor, expressions,
            new Pass<PsiExpression>(){
              public void pass(final PsiExpression selectedValue) {
                invoke(project, editor, file, selectedValue.getTextRange().getStartOffset(), selectedValue.getTextRange().getEndOffset());
              }
            },
            new PsiExpressionTrimRenderer.RenderFunction());
          return;
        }
      }
    }
    if (invoke(project, editor, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) &&
        LookupManager.getActiveLookup(editor) == null) {
      selectionModel.removeSelection();
    }
  }

  public static boolean isPreferStatements() {
    return Boolean.valueOf(PropertiesComponent.getInstance().getOrInit(PREFER_STATEMENTS_OPTION, "false")).booleanValue();
  }

  public static List<PsiExpression> collectExpressions(final PsiFile file, final Editor editor, final int offset, final PsiElement... statementsInRange) {
    Document document = editor.getDocument();
    CharSequence text = document.getCharsSequence();
    int correctedOffset = offset;
    int textLength = document.getTextLength();
    if (offset >= textLength) {
      correctedOffset = textLength - 1;
    }
    else if (!Character.isJavaIdentifierPart(text.charAt(offset))) {
      correctedOffset--;
    }
    if (correctedOffset < 0) {
      correctedOffset = offset;
    }
    else if (!Character.isJavaIdentifierPart(text.charAt(correctedOffset))) {
      if (text.charAt(correctedOffset) == ';') {//initially caret on the end of line
        correctedOffset--;
      }
      if (text.charAt(correctedOffset) != ')') {
        correctedOffset = offset;
      }
    }
    final PsiElement elementAtCaret = file.findElementAt(correctedOffset);
    final List<PsiExpression> expressions = new ArrayList<PsiExpression>();
    /*for (PsiElement element : statementsInRange) {
      if (element instanceof PsiExpressionStatement) {
        final PsiExpression expression = ((PsiExpressionStatement)element).getExpression();
        if (expression.getType() != PsiType.VOID) {
          expressions.add(expression);
        }
      }
    }*/
    PsiExpression expression = PsiTreeUtil.getParentOfType(elementAtCaret, PsiExpression.class);
    while (expression != null) {
      if (!expressions.contains(expression) && !(expression instanceof PsiParenthesizedExpression) && !(expression instanceof PsiSuperExpression) && expression.getType() != PsiType.VOID) {
        if (!(expression instanceof PsiReferenceExpression && (expression.getParent() instanceof PsiMethodCallExpression ||
                                                               ((PsiReferenceExpression)expression).resolve() instanceof PsiClass))
            && !(expression instanceof PsiAssignmentExpression)) {
          expressions.add(expression);
        }
      }
      expression = PsiTreeUtil.getParentOfType(expression, PsiExpression.class);
    }
    return expressions;
  }

  public static PsiElement[] findStatementsAtOffset(final Editor editor, final PsiFile file, final int offset) {
    final Document document = editor.getDocument();
    final int lineNumber = document.getLineNumber(offset);
    final int lineStart = document.getLineStartOffset(lineNumber);
    final int lineEnd = document.getLineEndOffset(lineNumber);

    return CodeInsightUtil.findStatementsInRange(file, lineStart, lineEnd);
  }

  private boolean invoke(final Project project, final Editor editor, PsiFile file, int startOffset, int endOffset) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.introduceVariable");
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    return invokeImpl(project, findExpressionInRange(project, file, startOffset, endOffset), editor);
  }

  private static PsiExpression findExpressionInRange(Project project, PsiFile file, int startOffset, int endOffset) {
    PsiExpression tempExpr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
    if (tempExpr == null) {
      PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
      if (statements.length == 1) {
        if (statements[0] instanceof PsiExpressionStatement) {
          tempExpr = ((PsiExpressionStatement) statements[0]).getExpression();
        } else if (statements[0] instanceof PsiReturnStatement) {
          tempExpr = ((PsiReturnStatement)statements[0]).getReturnValue();
        }
      }
    }

    if (tempExpr == null) {
      tempExpr = getSelectedExpression(project, file, startOffset, endOffset);
    }
    return tempExpr;
  }

  public static PsiExpression getSelectedExpression(final Project project, final PsiFile file, int startOffset, int endOffset) {

    PsiElement elementAtStart = file.findElementAt(startOffset);
    if (elementAtStart == null || elementAtStart instanceof PsiWhiteSpace || elementAtStart instanceof PsiComment) {
      elementAtStart = PsiTreeUtil.skipSiblingsForward(elementAtStart, PsiWhiteSpace.class, PsiComment.class);
      if (elementAtStart == null) return null;
      startOffset = elementAtStart.getTextOffset();
    }
    PsiElement elementAtEnd = file.findElementAt(endOffset - 1);
    if (elementAtEnd == null || elementAtEnd instanceof PsiWhiteSpace || elementAtEnd instanceof PsiComment) {
      elementAtEnd = PsiTreeUtil.skipSiblingsBackward(elementAtEnd, PsiWhiteSpace.class, PsiComment.class);
      if (elementAtEnd == null) return null;
      endOffset = elementAtEnd.getTextRange().getEndOffset();
    }

    if (endOffset <= startOffset) return null;

    PsiExpression tempExpr;
    PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd);
    if (PsiTreeUtil.getParentOfType(elementAt, PsiExpression.class, false) == null) {
      elementAt = null;
    }
    final PsiLiteralExpression literalExpression = PsiTreeUtil.getParentOfType(elementAt, PsiLiteralExpression.class);

    final PsiLiteralExpression startLiteralExpression = PsiTreeUtil.getParentOfType(elementAtStart, PsiLiteralExpression.class);
    final PsiLiteralExpression endLiteralExpression = PsiTreeUtil.getParentOfType(file.findElementAt(endOffset), PsiLiteralExpression.class);

    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    try {
      String text = file.getText().subSequence(startOffset, endOffset).toString();
      String prefix = null;
      String suffix = null;
      String stripped = text;
      if (startLiteralExpression != null) {
        final int startExpressionOffset = startLiteralExpression.getTextOffset();
        if (startOffset == startExpressionOffset) {
          if (StringUtil.startsWithChar(text, '\"') || StringUtil.startsWithChar(text, '\'')) {
            stripped = text.substring(1);
          }
        } else if (startOffset == startExpressionOffset + 1) {
          text = "\"" + text;
        } else if (startOffset > startExpressionOffset + 1){
          prefix = "\" + ";
          text = "\"" + text;
        }
      }

      if (endLiteralExpression != null) {
        final int endExpressionOffset = endLiteralExpression.getTextOffset() + endLiteralExpression.getTextLength();
        if (endOffset == endExpressionOffset ) {
          if (StringUtil.endsWithChar(stripped, '\"') || StringUtil.endsWithChar(stripped, '\'')) {
            stripped = stripped.substring(0, stripped.length() - 1);
          }
        } else if (endOffset == endExpressionOffset - 1) {
          text += "\"";
        } else if (endOffset < endExpressionOffset - 1) {
          suffix = " + \"";
          text += "\"";
        }
      }

      boolean primitive = false;
      if (stripped.equals("true") || stripped.equals("false")) {
        primitive = true;
      }
      else {
        try {
          Integer.parseInt(stripped);
          primitive = true;
        }
        catch (NumberFormatException e1) {
          //then not primitive
        }
      }

      if (primitive) {
        text = stripped;
      }

      final PsiElement parent = literalExpression != null ? literalExpression : elementAt;
      tempExpr = elementFactory.createExpressionFromText(text, parent);

      final boolean [] hasErrors = new boolean[1];
      final JavaRecursiveElementWalkingVisitor errorsVisitor = new JavaRecursiveElementWalkingVisitor() {
        @Override
        public void visitElement(final PsiElement element) {
          if (hasErrors[0]) {
            return;
          }
          super.visitElement(element);
        }

        @Override
        public void visitErrorElement(final PsiErrorElement element) {
          hasErrors[0] = true;
        }
      };
      tempExpr.accept(errorsVisitor);
      if (hasErrors[0]) return null;

      tempExpr.putUserData(ElementToWorkOn.PREFIX, prefix);
      tempExpr.putUserData(ElementToWorkOn.SUFFIX, suffix);

      final RangeMarker rangeMarker =
        FileDocumentManager.getInstance().getDocument(file.getVirtualFile()).createRangeMarker(startOffset, endOffset);
      tempExpr.putUserData(ElementToWorkOn.TEXT_RANGE, rangeMarker);

      if (parent != null) {
        tempExpr.putUserData(ElementToWorkOn.PARENT, parent);
      }
      else {
        PsiErrorElement errorElement = elementAtStart instanceof PsiErrorElement
                                       ? (PsiErrorElement)elementAtStart
                                       : PsiTreeUtil.getNextSiblingOfType(elementAtStart, PsiErrorElement.class);
        if (errorElement == null) {
          errorElement = PsiTreeUtil.getParentOfType(elementAtStart, PsiErrorElement.class);
        }
        if (errorElement == null) return null;
        if (!(errorElement.getParent() instanceof PsiClass)) return null;
        tempExpr.putUserData(ElementToWorkOn.PARENT, errorElement);
        tempExpr.putUserData(ElementToWorkOn.OUT_OF_CODE_BLOCK, Boolean.TRUE);
      }

      final String fakeInitializer = "intellijidearulezzz";
      final int[] refIdx = new int[1];
      final PsiExpression toBeExpression = createReplacement(fakeInitializer, project, prefix, suffix, parent, rangeMarker, refIdx);
      toBeExpression.accept(errorsVisitor);
      if (hasErrors[0]) return null;

      final PsiReferenceExpression refExpr = PsiTreeUtil.getParentOfType(toBeExpression.findElementAt(refIdx[0]), PsiReferenceExpression.class);
      assert refExpr != null;
      if (ReplaceExpressionUtil.isNeedParenthesis(refExpr.getNode(), tempExpr.getNode())) {
        return null;
      }
    }
    catch (IncorrectOperationException e) {
      return null;
    }

    return tempExpr;
  }

  protected boolean invokeImpl(final Project project, final PsiExpression expr,
                               final Editor editor) {
    if (expr != null && expr.getParent() instanceof PsiExpressionStatement) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.introduceVariable.incompleteStatement");
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("expression:" + expr);
    }

    if (expr == null) {
      if (ReassignVariableUtil.reassign(editor)) return false;
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("selected.block.should.represent.an.expression"));
      showErrorMessage(project, editor, message);
      return false;
    }

    final PsiType originalType = RefactoringUtil.getTypeByExpressionWithExpectedType(expr);
    if (originalType == null) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("unknown.expression.type"));
      showErrorMessage(project, editor, message);
      return false;
    }

    if (PsiType.VOID.equals(originalType)) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("selected.expression.has.void.type"));
      showErrorMessage(project, editor, message);
      return false;
    }

    final PsiElement physicalElement = expr.getUserData(ElementToWorkOn.PARENT);

    final PsiElement anchorStatement = RefactoringUtil.getParentStatement(physicalElement != null ? physicalElement : expr, false);

    if (anchorStatement == null) {
      return parentStatementNotFound(project, editor);
    }
    if (checkAnchorBeforeThisOrSuper(project, editor, anchorStatement, REFACTORING_NAME, HelpID.INTRODUCE_VARIABLE)) return false;

    final PsiElement tempContainer = anchorStatement.getParent();

    if (!(tempContainer instanceof PsiCodeBlock) && !isLoopOrIf(tempContainer)) {
      String message = RefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", REFACTORING_NAME);
      showErrorMessage(project, editor, message);
      return false;
    }

    if(!NotInSuperCallOccurenceFilter.INSTANCE.isOK(expr)) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("cannot.introduce.variable.in.super.constructor.call"));
      showErrorMessage(project, editor, message);
      return false;
    }

    final PsiFile file = anchorStatement.getContainingFile();
    LOG.assertTrue(file != null, "expr.getContainingFile() == null");

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return false;

    PsiElement containerParent = tempContainer;
    PsiElement lastScope = tempContainer;
    while (true) {
      if (containerParent instanceof PsiFile) break;
      if (containerParent instanceof PsiMethod) break;
      containerParent = containerParent.getParent();
      if (containerParent instanceof PsiCodeBlock) {
        lastScope = containerParent;
      }
    }

    final ExpressionOccurenceManager occurenceManager = new ExpressionOccurenceManager(expr, lastScope,
                                                                                NotInSuperCallOccurenceFilter.INSTANCE);
    final PsiExpression[] occurrences = occurenceManager.getOccurences();
    final PsiElement anchorStatementIfAll = occurenceManager.getAnchorStatementForAll();

    final LinkedHashMap<OccurrencesChooser.ReplaceChoice, PsiExpression[]> occurrencesMap =
      new LinkedHashMap<OccurrencesChooser.ReplaceChoice, PsiExpression[]>();

    final boolean hasWriteAccess = OccurrencesChooser.fillChoices(expr, occurrences, occurrencesMap);

    final PsiElement nameSuggestionContext = editor != null ? file.findElementAt(editor.getCaretModel().getOffset()) : null;
    final RefactoringSupportProvider supportProvider = LanguageRefactoringSupport.INSTANCE.forLanguage(expr.getLanguage());
    final boolean isInplaceAvailableOnDataContext =
      supportProvider != null &&
      editor.getSettings().isVariableInplaceRenameEnabled() &&
      supportProvider.isInplaceIntroduceAvailable(expr, nameSuggestionContext) &&
      !ApplicationManager.getApplication().isUnitTestMode();
    final boolean inFinalContext = occurenceManager.isInFinalContext();
    final InputValidator validator = new InputValidator(this, project, anchorStatementIfAll, anchorStatement, occurenceManager);
    final TypeSelectorManagerImpl typeSelectorManager = new TypeSelectorManagerImpl(project, originalType, expr, occurrences);

    final Pass<OccurrencesChooser.ReplaceChoice> callback = new Pass<OccurrencesChooser.ReplaceChoice>() {
      @Override
      public void pass(final OccurrencesChooser.ReplaceChoice choice) {
        final Ref<SmartPsiElementPointer<PsiVariable>> variable = new Ref<SmartPsiElementPointer<PsiVariable>>();
        final IntroduceVariableSettings settings =
          getSettings(project, editor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, choice);
        if (!settings.isOK()) return;
        typeSelectorManager.setAllOccurences(choice != OccurrencesChooser.ReplaceChoice.NO);
        final TypeExpression expression = new TypeExpression(project, typeSelectorManager.getTypesForAll());
        final RangeMarker exprMarker = editor.getDocument().createRangeMarker(expr.getTextRange());
        final SuggestedNameInfo suggestedName = getSuggestedName(settings.getSelectedType(), expr);
        final List<RangeMarker> occurrenceMarkers = new ArrayList<RangeMarker>();
        for (PsiExpression occurrence : occurrences) {
          occurrenceMarkers.add(editor.getDocument().createRangeMarker(occurrence.getTextRange()));
        }
        final Runnable runnable =
          introduce(project, expr, editor, anchorStatement, tempContainer, occurrences, anchorStatementIfAll, settings, variable);
        CommandProcessor.getInstance().executeCommand(
          project,
          new Runnable() {
            public void run() {
              ApplicationManager.getApplication().runWriteAction(runnable);
              if (isInplaceAvailableOnDataContext) {
                final PsiVariable elementToRename = variable.get().getElement();
                if (elementToRename != null) {
                  editor.getCaretModel().moveToOffset(elementToRename.getTextOffset());
                  final boolean cantChangeFinalModifier = hasWriteAccess || (inFinalContext && choice == OccurrencesChooser.ReplaceChoice.ALL);
                  final VariableInplaceRenamer renamer =
                    new VariableInplaceIntroducer(project, expression, editor, elementToRename, cantChangeFinalModifier,
                                                  typeSelectorManager.getTypesForAll().length > 1, exprMarker, occurrenceMarkers);
                  renamer.performInplaceRename(false, new LinkedHashSet<String>(Arrays.asList(suggestedName.names)));
                }
              }
            }
          }, REFACTORING_NAME, null);
      }
    };

    if (!isInplaceAvailableOnDataContext) {
      callback.pass(null);
    }
    else {
      new OccurrencesChooser(editor).showChooser(callback, occurrencesMap);
    }
    return true;
  }

  private static Runnable introduce(final Project project,
                                    final PsiExpression expr,
                                    final Editor editor,
                                    PsiElement anchorStatement,
                                    PsiElement tempContainer,
                                    final PsiExpression[] occurrences,
                                    PsiElement anchorStatementIfAll,
                                    final IntroduceVariableSettings settings,
                                    final Ref<SmartPsiElementPointer<PsiVariable>> variable) {
    if (settings.isReplaceAllOccurrences()) {
      anchorStatement = anchorStatementIfAll;
      tempContainer = anchorStatement.getParent();
    }

    final PsiElement container = tempContainer;

    PsiElement child = anchorStatement;
    if (!isLoopOrIf(container)) {
      child = locateAnchor(child);
    }
    final PsiElement anchor = child == null ? anchorStatement : child;

    boolean tempDeleteSelf = false;
    final boolean replaceSelf = settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(expr);
    if (!isLoopOrIf(container)) {
      if (expr.getParent() instanceof PsiExpressionStatement && anchor.equals(anchorStatement)) {
        PsiStatement statement = (PsiStatement) expr.getParent();
        PsiElement parent = statement.getParent();
        if (parent instanceof PsiCodeBlock ||
            //fabrique
            parent instanceof PsiCodeFragment) {
          tempDeleteSelf = true;
        }
      }
      tempDeleteSelf &= replaceSelf;
    }
    final boolean deleteSelf = tempDeleteSelf;

    final int col = editor != null ? editor.getCaretModel().getLogicalPosition().column : 0;
    final int line = editor != null ? editor.getCaretModel().getLogicalPosition().line : 0;
    if (deleteSelf) {
      if (editor != null) {
        LogicalPosition pos = new LogicalPosition(line, col);
        editor.getCaretModel().moveToLogicalPosition(pos);
      }
    }

    final PsiCodeBlock newDeclarationScope = PsiTreeUtil.getParentOfType(container, PsiCodeBlock.class, false);
    final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(settings.getEnteredName(), newDeclarationScope);
    final PsiElement finalAnchorStatement = anchorStatement;
    return new Runnable() {
      public void run() {
        try {
          PsiStatement statement = null;
          final boolean isInsideLoop = isLoopOrIf(container);
          if (!isInsideLoop && deleteSelf) {
            statement = (PsiStatement) expr.getParent();
          }

          final PsiExpression expr1 = fieldConflictsResolver.fixInitializer(expr);
          PsiExpression initializer = RefactoringUtil.unparenthesizeExpression(expr1);
          if (expr1 instanceof PsiNewExpression) {
            final PsiNewExpression newExpression = (PsiNewExpression)expr1;
            if (newExpression.getArrayInitializer() != null) {
              initializer = newExpression.getArrayInitializer();
            }
          }
          PsiDeclarationStatement declaration = JavaPsiFacade.getInstance(project).getElementFactory()
            .createVariableDeclarationStatement(settings.getEnteredName(), settings.getSelectedType(), initializer);
          if (!isInsideLoop) {
            declaration = (PsiDeclarationStatement) container.addBefore(declaration, anchor);
            LOG.assertTrue(expr1.isValid());
            if (deleteSelf) { // never true
              final PsiElement lastChild = statement.getLastChild();
              if (lastChild instanceof PsiComment) { // keep trailing comment
                declaration.addBefore(lastChild, null);
              }
              statement.delete();
              if (editor != null) {
                LogicalPosition pos = new LogicalPosition(line, col);
                editor.getCaretModel().moveToLogicalPosition(pos);
                editor.getCaretModel().moveToOffset(declaration.getTextRange().getEndOffset());
                editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                editor.getSelectionModel().removeSelection();
              }
            }
          }

          PsiExpression ref = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(settings.getEnteredName(), null);
          if (settings.isReplaceAllOccurrences()) {
            ArrayList<PsiElement> array = new ArrayList<PsiElement>();
            for (PsiExpression occurrence : occurrences) {
              if (deleteSelf && occurrence.equals(expr)) continue;
              if (occurrence.equals(expr)) {
                occurrence = expr1;
              }
              if (occurrence != null) {
                occurrence = RefactoringUtil.outermostParenthesizedExpression(occurrence);
              }
              if (settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(occurrence)) {
                array.add(replace(occurrence, ref, project));
              }
            }

            if (editor != null) {
              final PsiElement[] replacedOccurences = array.toArray(new PsiElement[array.size()]);
              highlightReplacedOccurences(project, editor, replacedOccurences);
            }
          } else {
            if (!deleteSelf && replaceSelf) {
              replace(expr1, ref, project);
            }
          }

          declaration = (PsiDeclarationStatement) putStatementInLoopBody(declaration, container, finalAnchorStatement);
          declaration = (PsiDeclarationStatement)JavaCodeStyleManager.getInstance(project).shortenClassReferences(declaration);
          PsiVariable var = (PsiVariable) declaration.getDeclaredElements()[0];
          PsiUtil.setModifierProperty(var, PsiModifier.FINAL, settings.isDeclareFinal());
          variable.set(SmartPointerManager.getInstance(project).createLazyPointer(var));
          fieldConflictsResolver.fix();
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    };
  }

  public static PsiElement replace(final PsiExpression expr1, final PsiExpression ref, final Project project)
    throws IncorrectOperationException {
    final PsiExpression expr2 = RefactoringUtil.outermostParenthesizedExpression(expr1);
    if (expr2.isPhysical()) {
      return expr2.replace(ref);
    }
    else {
      final String prefix  = expr1.getUserData(ElementToWorkOn.PREFIX);
      final String suffix  = expr1.getUserData(ElementToWorkOn.SUFFIX);
      final PsiElement parent = expr1.getUserData(ElementToWorkOn.PARENT);
      final RangeMarker rangeMarker = expr1.getUserData(ElementToWorkOn.TEXT_RANGE);

      return parent.replace(createReplacement(ref.getText(), project, prefix, suffix, parent, rangeMarker, new int[1]));
    }
  }

  private static PsiExpression createReplacement(final String refText, final Project project,
                                                 final String prefix,
                                                 final String suffix,
                                                 final PsiElement parent, final RangeMarker rangeMarker, int[] refIdx) {
    String text = refText;
    if (parent != null) {
      final String allText = parent.getContainingFile().getText();
      final TextRange parentRange = parent.getTextRange();

      String beg = allText.substring(parentRange.getStartOffset(), rangeMarker.getStartOffset());
      if (StringUtil.stripQuotesAroundValue(beg).trim().length() == 0 && prefix == null) beg = "";

      String end = allText.substring(rangeMarker.getEndOffset(), parentRange.getEndOffset());
      if (StringUtil.stripQuotesAroundValue(end).trim().length() == 0 && suffix == null) end = "";

      final String start = beg + (prefix != null ? prefix : "");
      refIdx[0] = start.length();
      text = start + refText + (suffix != null ? suffix : "") + end;
    }
    return JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(text, parent);
  }

  public static PsiStatement putStatementInLoopBody(PsiStatement declaration, PsiElement container, PsiElement finalAnchorStatement)
    throws IncorrectOperationException {
    if(isLoopOrIf(container)) {
      PsiStatement loopBody = getLoopBody(container, finalAnchorStatement);
      PsiStatement loopBodyCopy = loopBody != null ? (PsiStatement) loopBody.copy() : null;
      PsiBlockStatement blockStatement = (PsiBlockStatement)JavaPsiFacade.getInstance(container.getProject()).getElementFactory()
        .createStatementFromText("{}", null);
      blockStatement = (PsiBlockStatement) CodeStyleManager.getInstance(container.getProject()).reformat(blockStatement);
      final PsiElement prevSibling = loopBody.getPrevSibling();
      if(prevSibling instanceof PsiWhiteSpace) {
        final PsiElement pprev = prevSibling.getPrevSibling();
        if (!(pprev instanceof PsiComment) || !((PsiComment)pprev).getTokenType().equals(JavaTokenType.END_OF_LINE_COMMENT)) {
          prevSibling.delete();
        }
      }
      blockStatement = (PsiBlockStatement) loopBody.replace(blockStatement);
      final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
      declaration = (PsiStatement) codeBlock.add(declaration);
      JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);
      if (loopBodyCopy != null) codeBlock.add(loopBodyCopy);
    }
    return declaration;
  }

  private boolean parentStatementNotFound(final Project project, Editor editor) {
    String message = RefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", REFACTORING_NAME);
    showErrorMessage(project, editor, message);
    return false;
  }

  protected boolean invokeImpl(Project project, PsiLocalVariable localVariable, Editor editor) {
    throw new UnsupportedOperationException();
  }

  private static PsiElement locateAnchor(PsiElement child) {
    while (child != null) {
      PsiElement prev = child.getPrevSibling();
      if (prev instanceof PsiStatement) break;
      if (prev instanceof PsiJavaToken && ((PsiJavaToken)prev).getTokenType() == JavaTokenType.LBRACE) break;
      child = prev;
    }

    while (child instanceof PsiWhiteSpace || child instanceof PsiComment) {
      child = child.getNextSibling();
    }
    return child;
  }

  protected static void highlightReplacedOccurences(Project project, Editor editor, PsiElement[] replacedOccurences){
    if (editor == null) return;
    if (ApplicationManager.getApplication().isUnitTestMode()) return;
    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager colorsManager = EditorColorsManager.getInstance();
    TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    highlightManager.addOccurrenceHighlights(editor, replacedOccurences, attributes, true, null);
    WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
  }

  protected abstract void showErrorMessage(Project project, Editor editor, String message);

  @Nullable
  private static PsiStatement getLoopBody(PsiElement container, PsiElement anchorStatement) {
    if(container instanceof PsiLoopStatement) {
      return ((PsiLoopStatement) container).getBody();
    }
    else if (container instanceof PsiIfStatement) {
      final PsiStatement thenBranch = ((PsiIfStatement)container).getThenBranch();
      if (thenBranch != null && PsiTreeUtil.isAncestor(thenBranch, anchorStatement, false)) {
        return thenBranch;
      }
      final PsiStatement elseBranch = ((PsiIfStatement)container).getElseBranch();
      if (elseBranch != null && PsiTreeUtil.isAncestor(elseBranch, anchorStatement, false)) {
        return elseBranch;
      }
      LOG.assertTrue(false);
    }
    LOG.assertTrue(false);
    return null;
  }

  public static boolean isLoopOrIf(PsiElement element) {
    return element instanceof PsiLoopStatement || element instanceof PsiIfStatement;
  }

  protected boolean reportConflicts(MultiMap<PsiElement,String> conflicts, Project project, IntroduceVariableSettings settings){
    return false;
  }

  public IntroduceVariableSettings getSettings(Project project, Editor editor,
                                               PsiExpression expr, PsiExpression[] occurrences,
                                               final TypeSelectorManagerImpl typeSelectorManager,
                                               boolean declareFinalIfAll,
                                               boolean anyAssignmentLHS,
                                               final InputValidator validator,
                                               final OccurrencesChooser.ReplaceChoice replaceChoice) {
    final SuggestedNameInfo suggestedName = getSuggestedName(typeSelectorManager.getDefaultType(), expr);
    final String variableName = suggestedName.names[0];
    final boolean replaceAll =
      replaceChoice == OccurrencesChooser.ReplaceChoice.ALL || replaceChoice == OccurrencesChooser.ReplaceChoice.NO_WRITE;
    final boolean declareFinal =
      !anyAssignmentLHS && (replaceAll &&
                            declareFinalIfAll || createFinals(project));
    final boolean replaceWrite = anyAssignmentLHS && replaceChoice == OccurrencesChooser.ReplaceChoice.ALL;
    return new IntroduceVariableSettings() {
      @Override
      public String getEnteredName() {
        return variableName;
      }

      @Override
      public boolean isReplaceAllOccurrences() {
        return replaceAll;
      }

      @Override
      public boolean isDeclareFinal() {
        return declareFinal;
      }

      @Override
      public boolean isReplaceLValues() {
        return replaceWrite;
      }

      @Override
      public PsiType getSelectedType() {
        final PsiType selectedType = typeSelectorManager.getTypeSelector().getSelectedType();
        return selectedType != null ? selectedType : typeSelectorManager.getDefaultType();
      }

      @Override
      public boolean isOK() {
        return true;
      }
    };
  }

  public static boolean createFinals(Project project) {
    final Boolean createFinals = JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS;
    return createFinals == null ? CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS : createFinals.booleanValue();
  }

  public static boolean checkAnchorBeforeThisOrSuper(final Project project,
                                                     final Editor editor,
                                                     final PsiElement tempAnchorElement,
                                                     final String refactoringName,
                                                     final String helpID) {
    if (tempAnchorElement instanceof PsiExpressionStatement) {
      PsiExpression enclosingExpr = ((PsiExpressionStatement)tempAnchorElement).getExpression();
      if (enclosingExpr instanceof PsiMethodCallExpression) {
        PsiMethod method = ((PsiMethodCallExpression)enclosingExpr).resolveMethod();
        if (method != null && method.isConstructor()) {
          //This is either 'this' or 'super', both must be the first in the respective contructor
          String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invalid.expression.context"));
          CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpID);
          return true;
        }
      }
    }
    return false;
  }

  public interface Validator {
    boolean isOK(IntroduceVariableSettings dialog);
  }

  public static void checkInLoopCondition(PsiExpression occurence, MultiMap<PsiElement, String> conflicts) {
    final PsiElement loopForLoopCondition = RefactoringUtil.getLoopForLoopCondition(occurence);
    if (loopForLoopCondition == null) return;
    final List<PsiVariable> referencedVariables = RefactoringUtil.collectReferencedVariables(occurence);
    final List<PsiVariable> modifiedInBody = new ArrayList<PsiVariable>();
    for (PsiVariable psiVariable : referencedVariables) {
      if (RefactoringUtil.isModifiedInScope(psiVariable, loopForLoopCondition)) {
        modifiedInBody.add(psiVariable);
      }
    }

    if (!modifiedInBody.isEmpty()) {
      for (PsiVariable variable : modifiedInBody) {
        final String message = RefactoringBundle.message("is.modified.in.loop.body", RefactoringUIUtil.getDescription(variable, false));
        conflicts.putValue(variable, CommonRefactoringUtil.capitalize(message));
      }
      conflicts.putValue(occurence, RefactoringBundle.message("introducing.variable.may.break.code.logic"));
    }
  }

}


text:
 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.carlosgb.poi.excel.elements;

/**
 *
 * @author carlos
 */
public class Header {

    private String nombreColumna;
    private boolean required;
    private int cell;
    private HeaderStyle style;
    private BodyStyle bodyStyle;

    public Header(){
        this.nombreColumna=new String();
        this.required=true;
        this.cell=-1;
        this.style=new HeaderStyle();
        this.bodyStyle=new BodyStyle();
    }
    public Header(String nombreColumna){
        this.nombreColumna=nombreColumna;
        this.required=true;
        this.cell=-1;
        this.style=new HeaderStyle();
        this.bodyStyle=new BodyStyle();
    }

    public Header(String nombreColumna,boolean required){
        this.nombreColumna=nombreColumna;
        this.required=required;
        this.cell=-1;
        this.style=new HeaderStyle();
        this.bodyStyle=new BodyStyle();
    }

    /**
     * @return the nombreColumna
     */
    public String getNombreColumna() {
        return nombreColumna;
    }

    /**
     * @param nombreColumna the nombreColumna to set
     */
    public void setNombreColumna(String nombreColumna) {
        this.nombreColumna = nombreColumna;
    }

    /**
     * @return the required
     */
    public boolean isRequired() {
        return required;
    }

    /**
     * @param required the required to set
     */
    public void setRequired(boolean required) {
        this.required = required;
    }

    /**
     * @return the cell
     */
    public int getCell() {
        return cell;
    }

    /**
     * @param cell the cell to set
     */
    public void setCell(int cell) {
        this.cell = cell;
    }

    /**
     * @return the style
     */
    public HeaderStyle getStyle() {
        return style;
    }

    /**
     * @param style the style to set
     */
    public void setStyle(HeaderStyle style) {
        this.style = style;
    }

    /**
     * @return the bodyStyle
     */
    public BodyStyle getBodyStyle() {
        return bodyStyle;
    }

    /**
     * @param bodyStyle the bodyStyle to set
     */
    public void setBodyStyle(BodyStyle bodyStyle) {
        this.bodyStyle = bodyStyle;
    }
    public String toString(){
        return "{nombre_columna:"+this.nombreColumna+", requerido:"+required+"}";
    }

}


text:
import lasagne
import lasagne.nonlinearities as NL
import numpy as np
import itertools

from rllab.core.lasagne_layers import ParamLayer
from rllab.core.lasagne_powered import LasagnePowered
from rllab.spaces import Box

from rllab.core.serializable import Serializable
from rllab.policies.base import StochasticPolicy
from rllab.misc.overrides import overrides
from rllab.misc import logger
from rllab.misc import ext
from sandbox.rocky.snn.core.network import StochasticMLP
from rllab.core.lasagne_helpers import get_full_output
from rllab.distributions.diagonal_gaussian import DiagonalGaussian
import theano.tensor as TT

class StochasticGaussianMLPPolicy(StochasticPolicy, LasagnePowered, Serializable):
    def __init__(
            self,
            env_spec,
            input_latent_vars=None,
            hidden_sizes=(32, 32),
            hidden_latent_vars=None,
            learn_std=True,
            init_std=1.0,
            hidden_nonlinearity=NL.tanh,
            output_nonlinearity=None,
    ):
        Serializable.quick_init(self, locals())
        assert isinstance(env_spec.action_space, Box)

        obs_dim = env_spec.observation_space.flat_dim
        action_dim = env_spec.action_space.flat_dim

        # create network
        mean_network = StochasticMLP(
            input_shape=(obs_dim,),
            input_latent_vars=input_latent_vars,
            output_dim=action_dim,
            hidden_sizes=hidden_sizes,
            hidden_latent_vars=hidden_latent_vars,
            hidden_nonlinearity=hidden_nonlinearity,
            output_nonlinearity=output_nonlinearity,
        )

        l_mean = mean_network.output_layer
        obs_var = mean_network.input_layer.input_var

        l_log_std = ParamLayer(
            mean_network.input_layer,
            num_units=action_dim,
            param=lasagne.init.Constant(np.log(init_std)),
            name="output_log_std",
            trainable=learn_std,
        )

        self._mean_network = mean_network
        self._n_latent_layers = len(mean_network.latent_layers)
        self._l_mean = l_mean
        self._l_log_std = l_log_std

        LasagnePowered.__init__(self, [l_mean, l_log_std])
        super(StochasticGaussianMLPPolicy, self).__init__(env_spec)

        outputs = self.dist_info_sym(mean_network.input_var)
        latent_keys = sorted(set(outputs.keys()).difference({"mean", "log_std"}))

        extras = get_full_output(
            [self._l_mean, self._l_log_std] + self._mean_network.latent_layers,
        )[1]
        latent_distributions = [extras[layer]["distribution"] for layer in self._mean_network.latent_layers]

        self._latent_keys = latent_keys
        self._latent_distributions = latent_distributions
        self._dist = DiagonalGaussian(action_dim)

        self._f_dist_info = ext.compile_function(
            inputs=[obs_var],
            outputs=outputs,
        )
        self._f_dist_info_givens = None

    @property
    def latent_layers(self):
        return self._mean_network.latent_layers

    @property
    def latent_dims(self):
        return self._mean_network.latent_dims

    def dist_info(self, obs, state_infos=None):
        if state_infos is None or len(state_infos) == 0:
            return self._f_dist_info(obs)
        if self._f_dist_info_givens is None:
            # compile function
            obs_var = self._mean_network.input_var
            latent_keys = ["latent_%d" % idx for idx in range(self._n_latent_layers)]
            latent_vars = [TT.matrix("latent_%d" % idx) for idx in range(self._n_latent_layers)]
            latent_dict = dict(list(zip(latent_keys, latent_vars)))
            self._f_dist_info_givens = ext.compile_function(
                inputs=[obs_var] + latent_vars,
                outputs=self.dist_info_sym(obs_var, latent_dict),
            )
        latent_vals = []
        for idx in range(self._n_latent_layers):
            latent_vals.append(state_infos["latent_%d" % idx])
        return self._f_dist_info_givens(*[obs] + latent_vals)

    def reset(self):  #here I would sample a latents var.
        # sample latents
        # store it in self.something that then goes to all the others
        pass

    def dist_info_sym(self, obs_var, state_info_vars=None):
        if state_info_vars is not None:
            latent_givens = {
                latent_layer: state_info_vars["latent_%d" % idx]
                for idx, latent_layer in enumerate(self._mean_network.latent_layers)
                }
            latent_dist_infos = dict()
            for idx, latent_layer in enumerate(self._mean_network.latent_layers):
                cur_dist_info = dict()
                prefix = "latent_%d_" % idx
                for k, v in state_info_vars.items():
                    if k.startswith(prefix):
                        cur_dist_info[k[len(prefix):]] = v
                latent_dist_infos[latent_layer] = cur_dist_info
        else:
            latent_givens = dict()
            latent_dist_infos = dict()
        all_outputs, extras = get_full_output(
            [self._l_mean, self._l_log_std] + self._mean_network.latent_layers,
            inputs={self._mean_network._l_in: obs_var},
            latent_givens=latent_givens,
            latent_dist_infos=latent_dist_infos,
        )

        mean_var = all_outputs[0]
        log_std_var = all_outputs[1]
        latent_vars = all_outputs[2:]
        latent_dist_infos = []
        for latent_layer in self._mean_network.latent_layers:
            latent_dist_infos.append(extras[latent_layer]["dist_info"])

        output_dict = dict(mean=mean_var, log_std=log_std_var)
        for idx, latent_var, latent_dist_info in zip(itertools.count(), latent_vars, latent_dist_infos):
            output_dict["latent_%d" % idx] = latent_var
            for k, v in latent_dist_info.items():
                output_dict["latent_%d_%s" % (idx, k)] = v

        return output_dict

    def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
        """
        Compute the symbolic KL divergence of distributions of both the actions and the latents variables
        """
        kl = self._dist.kl_sym(old_dist_info_vars, new_dist_info_vars)
        for idx, latent_dist in enumerate(self._latent_distributions):
            # collect dist info for each latents variable
            prefix = "latent_%d_" % idx
            old_latent_dist_info = {k[len(prefix):]: v for k, v in old_dist_info_vars.items() if k.startswith(
                prefix)}
            new_latent_dist_info = {k[len(prefix):]: v for k, v in new_dist_info_vars.items() if k.startswith(
                prefix)}
            kl += latent_dist.kl_sym(old_latent_dist_info, new_latent_dist_info)
        return kl

    def likelihood_ratio_sym(self, action_var, old_dist_info_vars, new_dist_info_vars):
        """
        Compute the symbolic likelihood ratio of both the actions and the latents variables.
        """
        lr = self._dist.likelihood_ratio_sym(action_var, old_dist_info_vars, new_dist_info_vars)
        for idx, latent_dist in enumerate(self._latent_distributions):
            latent_var = old_dist_info_vars["latent_%d" % idx]
            prefix = "latent_%d_" % idx
            old_latent_dist_info = {k[len(prefix):]: v for k, v in old_dist_info_vars.items() if k.startswith(
                prefix)}
            new_latent_dist_info = {k[len(prefix):]: v for k, v in new_dist_info_vars.items() if k.startswith(
                prefix)}
            lr *= latent_dist.likelihood_ratio_sym(latent_var, old_latent_dist_info, new_latent_dist_info)
        return lr

    def log_likelihood(self, actions, dist_info, action_only=False):
        """
        Computes the log likelihood of both the actions and the latents variables, unless action_only is set to True,
        in which case it will only compute the log likelihood of the actions.
        :return:
        """
        logli = self._dist.log_likelihood(actions, dist_info)
        if not action_only:
            for idx, latent_dist in enumerate(self._latent_distributions):
                latent_var = dist_info["latent_%d" % idx]
                prefix = "latent_%d_" % idx
                latent_dist_info = {k[len(prefix):]: v for k, v in dist_info.items() if k.startswith(
                    prefix)}
                logli += latent_dist.log_likelihood(latent_var, latent_dist_info)
        return logli

    def log_likelihood_sym(self, action_var, dist_info_vars):
        logli = self._dist.log_likelihood_sym(action_var, dist_info_vars)
        for idx, latent_dist in enumerate(self._latent_distributions):
            latent_var = dist_info_vars["latent_%d" % idx]
            prefix = "latent_%d_" % idx
            latent_dist_info = {k[len(prefix):]: v for k, v in dist_info_vars.items() if k.startswith(
                prefix)}
            logli += latent_dist.log_likelihood_sym(latent_var, latent_dist_info)
        return logli

    def entropy(self, dist_info):
        ent = self._dist.entropy(dist_info)
        for idx, latent_dist in enumerate(self._latent_distributions):
            prefix = "latent_%d_" % idx
            latent_dist_info = {k[len(prefix):]: v for k, v in dist_info.items() if k.startswith(prefix)}
            ent += latent_dist.entropy(latent_dist_info)
        return ent

    @property
    def dist_info_keys(self):
        return ["mean", "log_std"] + self._latent_keys

    @overrides
    def get_action(self, observation):
        actions, outputs = self.get_actions([observation])
        return actions[0], {k: v[0] for k, v in outputs.items()}

    def get_actions(self, observations):
        outputs = self._f_dist_info(observations)
        mean = outputs["mean"]
        log_std = outputs["log_std"]
        rnd = np.random.normal(size=mean.shape)
        actions = rnd * np.exp(log_std) + mean
        return actions, outputs

    def log_diagnostics(self, paths):
        log_stds = np.vstack([path["agent_infos"]["log_std"] for path in paths])
        logger.record_tabular('AveragePolicyStd', np.mean(np.exp(log_stds)))

    @property
    def distribution(self):
        """
        We set the distribution to the policy itself since we need some behavior different from a usual diagonal
        Gaussian distribution.
        """
        return self

    @property
    def state_info_keys(self):
        return self._latent_keys


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.wenqixian.myfirstapp.activities.RatingActivity"
    tools:showIn="@layout/activity_rating">

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ratingBar"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="20"
        android:minLines="10"
        android:maxLength="250"
        android:gravity="top|left"
        android:inputType="textMultiLine"
        android:textSize="20sp"
        android:textColor="#00000F"
        android:background="#DCDCDC"
        android:id="@+id/comments_editText"
        android:layout_below="@+id/ratingBar"
        android:layout_marginTop="10dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/textView2"
        android:layout_toEndOf="@+id/ratingBar"
        android:layout_marginStart="15dp"
        android:layout_marginTop="15dp" />

</RelativeLayout>


text:
@import "./src/input.css";

.input {
  extend: %input;
}
.input:disabled {
  extend: %input--disabled;
}


text:
<?php

namespace RunOpenCode\AssetsInjection\Exception;

interface ExceptionInterface
{

}


text:
INCLUDE(FindCygwin)

SET(PERL_POSSIBLE_BIN_PATHS
  ${CYGWIN_INSTALL_PATH}/bin
  )

IF(WIN32)
  GET_FILENAME_COMPONENT(
    ActivePerl_CurrentVersion
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ActiveState\\ActivePerl;CurrentVersion]"
    NAME)
  SET(PERL_POSSIBLE_BIN_PATHS ${PERL_POSSIBLE_BIN_PATHS}
    "C:/Perl/bin"
    [HKEY_LOCAL_MACHINE\\SOFTWARE\\ActiveState\\ActivePerl\\${ActivePerl_CurrentVersion}]/bin
    )
ENDIF(WIN32)

FIND_PROGRAM(PERL_EXECUTABLE
  NAMES perl
  PATHS ${PERL_POSSIBLE_BIN_PATHS}
  )

# Deprecated settings for compatibility with CMake1.4
SET(PERL ${PERL_EXECUTABLE})

# handle the QUIETLY and REQUIRED arguments and set PERL_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Perl DEFAULT_MSG PERL_EXECUTABLE)

MARK_AS_ADVANCED(PERL_EXECUTABLE)


text:
package com.vladsch.flexmark.page.generator.plugin;

import java.io.File;
import java.util.Arrays;

import org.apache.maven.*;
import org.apache.maven.execution.*;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.apache.maven.project.*;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
import org.eclipse.aether.repository.LocalRepository;

/**
 * Borrowed from ahgittin to provide a working Maven project as part of unit testing.
 *
 * @author ahgittin (https://github.com/ahgittin/license-audit-maven-plugin)
 */
public abstract class BetterAbstractMojoTestCase extends AbstractMojoTestCase {

    protected MavenSession newMavenSession() {
        try {
            MavenExecutionRequest request = new DefaultMavenExecutionRequest();
            MavenExecutionResult result = new DefaultMavenExecutionResult();

            // populate sensible defaults, including repository basedir and remote repos
            MavenExecutionRequestPopulator populator;
            populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
            populator.populateDefaults(request);

            // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
            // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
            request.setSystemProperties(System.getProperties());

            // and this is needed so that the repo session in the maven session
            // has a repo manager, and it points at the local repo
            // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
            DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
            DefaultRepositorySystemSession repoSession =
                    (DefaultRepositorySystemSession) maven.newRepositorySession(request);
            repoSession.setLocalRepositoryManager(
                    new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                            new LocalRepository(request.getLocalRepository().getBasedir())));

            @SuppressWarnings("deprecation")
            MavenSession session = new MavenSession(getContainer(),
                    repoSession,
                    request, result);
            return session;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Extends the super to use the new {@link #newMavenSession()} introduced here
     * which sets the defaults one expects from maven; the standard test case leaves a lot of things blank
     */
    @Override
    protected MavenSession newMavenSession(MavenProject project) {
        MavenSession session = newMavenSession();
        session.setCurrentProject(project);
        session.setProjects(Arrays.asList(project));
        return session;
    }

    /**
     * As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom file
     * and creating the {@link MavenProject}.
     */
    protected Mojo lookupConfiguredMojo(File pom, String goal) throws Exception {
        assertNotNull(pom);
        assertTrue(pom.exists());

        ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest();
        ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
        MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();

        return lookupConfiguredMojo(project, goal);
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>

<Data>
	<baseImgUrl>http://thegamesdb.net/banners/</baseImgUrl>
	<Platform>
		<id>15</id>
		<Platform>Microsoft Xbox 360</Platform>
		<console>http://www.youtube.com/watch?v=15.png</console>
		<controller>http://www.youtube.com/watch?v=15.png</controller>
		<overview>The Xbox 360 is the second video game console produced by Microsoft and the successor to the Xbox. The Xbox 360 competes with Sony&#039;s PlayStation 3 and Nintendo&#039;s Wii as part of the seventh generation of video game consoles. As of September 30, 2011, 57.6 million Xbox 360 consoles have been sold worldwide.

Several major features of the Xbox 360 are its integrated Xbox Live service that allows players to compete online, download arcade games, game demos, trailers, TV shows, music and movies and its Windows Media Center multimedia capabilities. The Xbox 360 also offers region specific access to third-party media streaming services such as Netflix and ESPN in the US or Sky Go in the UK.</overview>
		<developer>Microsoft</developer>
		<manufacturer>Microsoft</manufacturer>
		<cpu>3.2 GHz PowerPC Tri-Core Xenon</cpu>
		<memory>512 MB of GDDR3 RAM clocked at 700 MHz</memory>
		<graphics>500 MHz ATI Xenos</graphics>
		<sound>Dolby Digital 5.1 (TOSLINK and HDMI)</sound>
		<display>1920x1080</display>
		<media>Disc</media>
		<maxcontrollers>4</maxcontrollers>
		<Rating>7.4167</Rating>
		<Images>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-1.jpg</original>
				<thumb>platform/fanart/thumb/15-1.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-2.jpg</original>
				<thumb>platform/fanart/thumb/15-2.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-3.jpg</original>
				<thumb>platform/fanart/thumb/15-3.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-4.jpg</original>
				<thumb>platform/fanart/thumb/15-4.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-5.jpg</original>
				<thumb>platform/fanart/thumb/15-5.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-6.jpg</original>
				<thumb>platform/fanart/thumb/15-6.jpg</thumb>
			</fanart>
			<fanart>
				<original width="1920" height="1080">platform/fanart/15-7.jpg</original>
				<thumb>platform/fanart/thumb/15-7.jpg</thumb>
			</fanart>
			<boxart side="back" width="820" height="1080">platform/boxart/15-2.jpg</boxart>
			<banner width="760" height="140">platform/banners/15-1.jpg</banner>
			<consoleart>platform/consoleart/15.png</consoleart>
			<controllerart>platform/controllerart/15.png</controllerart>
		</Images>
	</Platform>
</Data>


text:
/**
 * Internal dependencies
 */
import type {
  GifResourceV37,
  ImageResourceV37,
  VideoResourceV37,
  GifElementV37,
  ImageElementV37,
  PageV37,
  ProductElementV37,
  ShapeElementV37,
  StoryV37,
  TextElementV37,
  UnionElementV37,
  VideoElementV37,
} from './v0037_removeTransientMediaProperties';

export type TextElementV38 = TextElementV37;
export type ProductElementV38 = ProductElementV37;
export type ShapeElementV38 = Omit<ShapeElementV37, 'isDefaultBackground'>;

export interface ImageResourceV38 extends Omit<ImageResourceV37, 'sizes'> {
  sizes: Record<string, CamelCaseSize>;
}
export interface VideoResourceV38 extends Omit<VideoResourceV37, 'sizes'> {
  sizes: Record<string, CamelCaseSize>;
}
export interface GifResourceV38 extends Omit<GifResourceV37, 'sizes'> {
  sizes: Record<string, CamelCaseSize>;
}

export interface ImageElementV38 extends Omit<ImageElementV37, 'resource'> {
  resource: ImageResourceV38;
}
export interface VideoElementV38 extends Omit<VideoElementV37, 'resource'> {
  resource: VideoResourceV38;
}
export interface GifElementV38 extends Omit<GifElementV37, 'resource'> {
  resource: GifResourceV38;
}

export type UnionElementV38 =
  | ShapeElementV38
  | ImageElementV38
  | VideoElementV38
  | GifElementV38
  | TextElementV38
  | ProductElementV38;

interface Size {
  file: string;
  source_url: string;
  mime_type: string;
  width: number;
  height: number;
}

interface CamelCaseSize {
  [index: string]: string | number;
  file: string;
  sourceUrl: string;
  mimeType: string;
  width: number;
  height: number;
}

export interface StoryV38 extends Omit<StoryV37, 'pages'> {
  pages: PageV38[];
}
export interface PageV38 extends Omit<PageV37, 'elements'> {
  elements: UnionElementV38[];
}

function camelCaseResourceSizes({ pages, ...rest }: StoryV37): StoryV38 {
  return {
    pages: pages.map(reducePage),
    ...rest,
  };
}

function reducePage({ elements, ...rest }: PageV37): PageV38 {
  return {
    elements: elements.map(updateElement),
    ...rest,
  };
}

function snakeToCamelCase(string = ''): string {
  if (!string.includes('_') && !string.includes('-')) {
    return string;
  }

  return string
    .toLowerCase()
    .replace(
      /([a-z])([_|-][a-z])/g,
      (_match, group1: string, group2: string) =>
        group1 + group2.toUpperCase().replace('_', '').replace('-', '')
    );
}

type Key = keyof CamelCaseSize;
function snakeToCamelCaseObjectKeys(obj: Size): CamelCaseSize {
  return Object.entries(obj).reduce(
    (_obj: CamelCaseSize, [key, value]: [string, string | number]) => {
      _obj[snakeToCamelCase(key) as Key] = value;
      return _obj;
    },
    {} as CamelCaseSize
  );
}

function updateElement(element: UnionElementV37): UnionElementV38 {
  if (
    'resource' in element &&
    'sizes' in element.resource &&
    element.resource.sizes
  ) {
    const sizes: Record<string, CamelCaseSize> = {};
    for (const [key, value] of Object.entries(element.resource.sizes)) {
      sizes[key] = snakeToCamelCaseObjectKeys(value as Size);
    }
    return {
      ...element,
      resource: {
        ...element.resource,
        sizes,
      },
    };
  }
  return element as UnionElementV38;
}

export default camelCaseResourceSizes;