text:
; vim:noet:sw=8:ts=8:ai:syn=pic
;
; USB 512-Word CDC Bootloader for PIC16(L)F1454/5/9
; Copyright (c) 2015, Matt Sarnoff (msarnoff.org)
; v1.0, February 12, 2015
; Released under a 3-clause BSD license: see the accompanying LICENSE file.
;
; Bootloader is entered if the MCLR/RA3 pin is grounded at power-up or reset,
; or if there is no application programmed. (The internal pull-up is used,
; no external resistor is necessary.)
;
; To be detected as a valid application, the lower 8 bytes of the first
; instruction word must NOT be 0xFF.
;
; At application start, the device is configured with a 48MHz CPU clock,
; using the internal oscillator and 3x PLL. If a different oscillator
; configuration is required, it must be set by the application.
;
; A serial number between 0 and 65535 should be specified during the build
; by using the gpasm -D argument to set the SERIAL_NUMBER symbol, e.g.
;   gpasm -D SERIAL_NUMBER=12345
; If not specified, it will default to zero.
; A host may not behave correctly if multiple PICs with the same serial number
; are connected simultaneously.
;
; Code notes:
; - Labels that do not begin with an underscore can be called as functions.
;   Labels that begin with an underscore are not safe to call, they should only
;   be reached via goto.
;
; - FSR0L, FSR0H, FSR1L, and FSR1H are used as temporary registers in several
;   places, e.g. as loop counters. They're accessible regardless of the current
;   bank, and automatically saved/restored on interrupt. Neato!
;
; - As much stuff as possible is packed into bank 0 of RAM. This includes the
;   buffer descriptors, bootloader state, endpoint 0 OUT and IN buffers,
;   the endpoint 1 IN buffer (only a single byte is used), and the beginning of
;   the 64-byte endpoint 1 OUT buffer.
;
; - Notification endpoint 2 is enabled, but never used. The endpoint 2 IN
;   buffer descriptor is left uninitialized. The endpoint 2 OUT buffer
;   descriptor is used as 4 bytes of RAM.
;
; - The programming protocol is described in the 'usb16f1prog' script. It is
;   very minimal, but does provide checksum verification. Writing the ID words
;   (0x8000-8003) is not supported at this time, and writing the configuration
;   words is not possible via self-programming.

; With logging enabled, the bootloader will not fit in 512 words.
; Use this only for debugging!
; For more info, see log_macros.inc and log.asm.
LOGGING_ENABLED		equ	0

	radix dec
	list n=0,st=off
	include "p16f1454.inc"
	nolist
	include "macros.inc"
	include "bdt.inc"
	include "usb.inc"
	include "protocol_constants.inc"
	include "log_macros.inc"
	list
	errorlevel -302

;;; Configuration
	if LOGGING_ENABLED
WRT_CONFIG		equ	_WRT_HALF
	else
WRT_CONFIG		equ	_WRT_BOOT
	endif

	__config _CONFIG1, _FOSC_INTOSC & _WDTE_SWDTEN & _PWRTE_ON & _MCLRE_OFF & _CP_OFF & _BOREN_ON & _IESO_OFF & _FCMEN_OFF
	__config _CONFIG2, WRT_CONFIG & _CPUDIV_NOCLKDIV & _USBLSCLK_48MHz & _PLLMULT_3x & _PLLEN_ENABLED & _STVREN_ON & _BORV_LO & _LVP_OFF

;;; Constants and varaiable addresses
SERIAL_NUMBER_DIGIT_CNT	equ	4
	ifndef SERIAL_NUMBER
	variable SERIAL_NUMBER=0	; Why doesnt 'equ' work here? Go figure
	endif

; I plan to apply for an Openmoko Product ID: the current product ID is temporary.
; If your organization has its own vendor ID/product ID, substitute it here.
; The Openmoko vendor/product ID cannot be used in closed-source/non-open-hardware
; projects: see http://wiki.openmoko.org/wiki/USB_Product_IDs
USB_VENDOR_ID		equ	0x1D50
USB_PRODUCT_ID		equ	0xEEEE	; to be filled in once I obtain a product ID

DEVICE_DESC_LEN		equ	18	; device descriptor length
CONFIG_DESC_TOTAL_LEN	equ	67	; total length of configuration descriptor and sub-descriptors
SERIAL_NUM_DESC_LEN	equ	2+(SERIAL_NUMBER_DIGIT_CNT*2)
ALL_DESCS_TOTAL_LEN	equ	DEVICE_DESC_LEN+CONFIG_DESC_TOTAL_LEN+SERIAL_NUM_DESC_LEN

EP0_BUF_SIZE 		equ	8	; endpoint 0 buffer size
EP1_OUT_BUF_SIZE	equ	64	; endpoint 1 OUT (CDC data) buffer size
EP1_IN_BUF_SIZE		equ	1	; endpoint 1 IN (CDC data) buffer size (only need 1 byte to return status codes)

; Since we're only using 5 endpoints, use the BDT area for buffers,
; and use the 4 bytes normally occupied by the EP2 OUT buffer descriptor for variables.
USB_STATE		equ	BANKED_EP2OUT+0
EP0_DATA_IN_PTR		equ	BANKED_EP2OUT+1	; pointer to descriptor to be sent (low byte only)
EP0_DATA_IN_COUNT	equ	BANKED_EP2OUT+2	; remaining bytes to be sent
APP_POWER_CONFIG	equ	BANKED_EP2OUT+3	; application power config byte
EP0OUT_BUF		equ	EP3OUT
BANKED_EP0OUT_BUF	equ	BANKED_EP3OUT	; buffers go immediately after EP2 IN's buffer descriptor
EP0IN_BUF		equ	EP0OUT_BUF+EP0_BUF_SIZE
BANKED_EP0IN_BUF	equ	BANKED_EP0OUT_BUF+EP0_BUF_SIZE

; Use another byte to store the checksum we use to verify writes
EXTRA_VARS_LEN		equ	1
EXPECTED_CHECKSUM	equ	BANKED_EP0IN_BUF+EP0_BUF_SIZE	; for saving expected checksum

EP1IN_BUF		equ	EP0IN_BUF+EP0_BUF_SIZE+EXTRA_VARS_LEN
BANKED_EP1IN_BUF	equ	BANKED_EP0IN_BUF+EP0_BUF_SIZE+EXTRA_VARS_LEN

EP1OUT_BUF		equ	EP1IN_BUF+EP1_IN_BUF_SIZE	; only use 1 byte for EP1 IN
BANKED_EP1OUT_BUF	equ	BANKED_EP1IN_BUF+EP1_IN_BUF_SIZE

; High byte of all endpoint buffers.
EPBUF_ADRH		equ	(EP0OUT_BUF>>8)
	if ((EP0IN_BUF>>8) != (EP0OUT_BUF>>8)) || ((EP1OUT_BUF>>8) != (EP0OUT_BUF>>8)) || ((EP1IN_BUF>>8) != (EP0OUT_BUF>>8))
	error "Endpoint buffers must be in the same 256-word region"
	endif

; Total length of all RAM (variables, buffers, BDT entries) used by the bootloader,
USED_RAM_LEN		equ	EP1OUT_BUF+EP1_OUT_BUF_SIZE-BDT_START

	if LOGGING_ENABLED
BOOTLOADER_SIZE		equ	0x1000
	else
BOOTLOADER_SIZE		equ	0x200
	endif

; Application code locations
APP_ENTRY_POINT		equ	BOOTLOADER_SIZE
APP_CONFIG		equ	BOOTLOADER_SIZE+2
APP_INTERRUPT		equ	BOOTLOADER_SIZE+4

; USB_STATE bit flags
IS_CONTROL_WRITE	equ	0	; current endpoint 0 transaction is a control write
ADDRESS_PENDING		equ	1	; need to set address in next IN transaction
DEVICE_CONFIGURED	equ	2	; the device is configured

;;; Vectors
	org	0x0000
RESET_VECT
; Enable weak pull-ups
	banksel	OPTION_REG
	bcf	OPTION_REG,NOT_WPUEN
	banksel	OSCCON
	goto	bootloader_start	; to be continued further down in the file

	org	0x0004
INTERRUPT_VECT
; check the high byte of the return address (at the top of the stack)
	banksel	TOSH
	if LOGGING_ENABLED
; for 4k-word mode: if TOSH < 0x10, we're in the bootloader
; if TOSH >= 0x10, jump to the application interrupt handler
	movlw	high BOOTLOADER_SIZE
	subwf	TOSH,w
	bnc	_bootloader_interrupt
	else
; for 512-word mode: if TOSH == 0, we're in the bootloader
; if TOSH != 0, jump to the application interrupt handler
	tstf	TOSH
	bz	_bootloader_interrupt
	endif
	pagesel	APP_INTERRUPT
	goto	APP_INTERRUPT

; executing from the bootloader? it's a USB interrupt
_bootloader_interrupt
	banksel	UIR
; reset?
	btfss	UIR,URSTIF
	goto	_utrans		; not a reset? just start servicing transactions
	call	usb_init	; if so, reset the USB interface (clears interrupts)
	banksel	PIE2
	bsf	PIE2,USBIE	; reenable USB interrupts
	banksel	UIR
	bcf	UIR,URSTIF	; clear the flag
; service transactions
_utrans	banksel	UIR
	btfss	UIR,TRNIF
	goto	_usdone
	movfw	USTAT		; stash the status in a temp register
	movwf	FSR1H
	bcf	UIR,TRNIF	; clear flag and advance USTAT fifo
	banksel	BANKED_EP0OUT_STAT
	andlw	b'01111000'	; check endpoint number
	bnz	_ucdc		; if not endpoint 0, it's a CDC message
	call	usb_service_ep0	; handle the control message
	goto	_utrans
; clear USB interrupt
_usdone	banksel	PIR2
	bcf	PIR2,USBIF
	retfie
_ucdc	call	usb_service_cdc	; USTAT value is still in FSR1H
	goto	_utrans

;;; Idle loop. In bootloader mode, the MCU just spins here, and all USB
;;; communication is interrupt-driven.
;;; This snippet is deliberately located within the first 256 words of program
;;; memory, so we can easily check in the interrupt handler if the interrupt
;;; occurred while executing application code or bootloader code.
;;; (TOSH will be 0x00 when executing bootloader code, i.e. this snippet)
bootloader_main_loop
	bsf	INTCON,GIE	; enable interrupts
_loop
	if LOGGING_ENABLED
; Print any pending characters in the log
	call	log_service
	endif
	goto	_loop

;;; Handles a control transfer on endpoint 0.
;;; arguments:	expects USTAT value in FSR1H
;;;		BSR=0
;;; returns:	none
;;; clobbers:	W, FSR1H
usb_service_ep0
	btfsc	FSR1H,DIR	; is it an IN transfer or an OUT/SETUP?
	goto	_usb_ctrl_in
; it's an OUT or SETUP transfer
	movfw	BANKED_EP0OUT_STAT
	andlw	b'00111100'	; isolate PID bits
	sublw	PID_SETUP	; is it a SETUP packet?
	bnz	arm_ep0_out	; if not, it's a regular OUT, just rearm the buffer
	; it's a SETUP packet--fall through

; Handles a SETUP control transfer on endpoint 0.
; BSR=0
_usb_ctrl_setup
	bcf	USB_STATE,IS_CONTROL_WRITE
; get bmRequestType, but don't bother checking whether it's standard/class/vendor...
; the CDC and standard requests we'll receive have distinct bRequest numbers
	movfw	BANKED_EP0OUT_BUF+bmRequestType
	btfss	BANKED_EP0OUT_BUF+bmRequestType,7	; is this host->device?
	bsf	USB_STATE,IS_CONTROL_WRITE		; if so, this is a control write
; check request number: is it Get Descriptor?
	movlw	GET_DESCRIPTOR
	subwf	BANKED_EP0OUT_BUF+bRequest,w
	bz	_usb_get_descriptor
; is it Set Address?
	movlw	SET_ADDRESS
	subwf	BANKED_EP0OUT_BUF+bRequest,w
	bz	_usb_set_address
; is it Set_Configuration?
	movlw	SET_CONFIG
	subwf	BANKED_EP0OUT_BUF+bRequest,w
	bz	_usb_set_configuration
; is it Get Configuration?
	movlw	GET_CONFIG
	subwf	BANKED_EP0OUT_BUF+bRequest,w
	bz	_usb_get_configuration
; unhandled request? fall through to _usb_ctrl_invalid

; Finishes a rejected SETUP transaction: the endpoints are stalled
_usb_ctrl_invalid
	banksel	UCON
	bcf	UCON,PKTDIS	; reenable packet processing
	banksel	BANKED_EP0IN_STAT
	movlw	_DAT0|_DTSEN|_BSTALL
	call	arm_ep0_in_with_flags
arm_ep0_out
	movlw	_DAT0|_DTSEN|_BSTALL
arm_ep0_out_with_flags			; W specifies STAT flags
	movwf	BANKED_EP0OUT_STAT
	movlw	EP0_BUF_SIZE		; reset the buffer count
	movwf	BANKED_EP0OUT_CNT
	bsf	BANKED_EP0OUT_STAT,UOWN	; arm the OUT endpoint
	return

; Finishes a successful SETUP transaction.
_usb_ctrl_complete
	banksel	UCON
	bcf	UCON,PKTDIS		; reenable packet processing
	banksel	USB_STATE
	btfsc	USB_STATE,IS_CONTROL_WRITE
	goto	_cwrite
; this is a control read; prepare the IN endpoint for the data stage
; and the OUT endpoint for the status stage
_cread	call	ep0_read_in		; read data into IN buffer
	movlw	_DAT1|_DTSEN		; OUT buffer will be ready for status stage
; value in W is used to specify the EP0 OUT flags
_armbfs	call	arm_ep0_out_with_flags
	movlw	_DAT1|_DTSEN		; arm IN buffer
arm_ep0_in_with_flags			; W specifies STAT flags
	movwf	BANKED_EP0IN_STAT
	bsf	BANKED_EP0IN_STAT,UOWN
	return
; this is a control write: prepare the IN endpoint for the status stage
; and the OUT endpoint for the next SETUP transaction
_cwrite	bcf	BANKED_EP0IN_STAT,UOWN	; ensure we have ownership of the buffer
	clrf	BANKED_EP0IN_CNT	; we'll be sending a zero-length packet
	movlw	_DAT0|_DTSEN|_BSTALL	; make OUT buffer ready for next SETUP packet
	goto	_armbfs			; arm OUT and IN buffers

; Handles a Get Descriptor request.
; BSR=0
_usb_get_descriptor
; check descriptor type
	movlw	DESC_CONFIG
	subwf	BANKED_EP0OUT_BUF+wValueH,w
	bz	_config_descriptor
	movlw	DESC_STRING
	subwf	BANKED_EP0OUT_BUF+wValueH,w
	bz	_string_descriptor
	movlw	DESC_DEVICE
	subwf	BANKED_EP0OUT_BUF+wValueH,w
	bnz	_usb_ctrl_invalid
_device_descriptor
	movlw	low DEVICE_DESCRIPTOR
	movwf	EP0_DATA_IN_PTR
	movlw	DEVICE_DESC_LEN
	goto	_set_data_in_count_from_w
_config_descriptor
	movlw	low CONFIGURATION_DESCRIPTOR
	movwf	EP0_DATA_IN_PTR
	movlw	CONFIG_DESC_TOTAL_LEN	; length includes all subordinate descriptors
	goto	_set_data_in_count_from_w
_string_descriptor
; only one string descriptor (serial number) is supported,
; so don't bother checking wValueL
	movlw	low SERIAL_NUMBER_STRING_DESCRIPTOR
	movwf	EP0_DATA_IN_PTR
	movlw	SERIAL_NUM_DESC_LEN
_set_data_in_count_from_w
	movwf	EP0_DATA_IN_COUNT
; the count needs to be set to the minimum of the descriptor's length (in W)
; and the requested length
	subwf	BANKED_EP0OUT_BUF+wLengthL,w	; just ignore high byte...
	bc	_usb_ctrl_complete		; if W <= f, no need to adjust
	movfw	BANKED_EP0OUT_BUF+wLengthL
	movwf	EP0_DATA_IN_COUNT
	goto	_usb_ctrl_complete

; Handles a Set Address request.
; The address is actually set in the IN status stage.
_usb_set_address
	bsf	USB_STATE,ADDRESS_PENDING	; address will be assigned in the status stage
	goto	_usb_ctrl_complete

; Handles a Set Configuration request.
; For now just accept any nonzero configuration.
; BSR=0
_usb_set_configuration
	bcf	USB_STATE,DEVICE_CONFIGURED	; temporarily clear flag
	tstf	BANKED_EP0OUT_BUF+wValueL	; anything other than 0 is valid
	skpz
	bsf	USB_STATE,DEVICE_CONFIGURED
	call	cdc_init
	goto	_usb_ctrl_complete

; Handles a Get Configuration request.
; BSR=0
_usb_get_configuration
; load a pointer to either a 0 or a 1 in ROM
; the 0 and 1 have been chosen so that they are adjacent
	movlw	low CONFIGURATION_0_CONSTANT
	btfsc	USB_STATE,DEVICE_CONFIGURED
	incw
	movwf	EP0_DATA_IN_PTR
	movlw	1
	movwf	EP0_DATA_IN_COUNT
	goto	_usb_ctrl_complete

; Handles an IN control transfer on endpoint 0.
; BSR=0
_usb_ctrl_in
	btfsc	USB_STATE,IS_CONTROL_WRITE	; is this a control read or write?
	goto	_check_for_pending_address
; fetch more data and re-arm the IN endpoint
	call	ep0_read_in
	movlw	_DTSEN
	btfss	BANKED_EP0IN_STAT,DTS	; toggle DTS
	bsf	WREG,DTS
	goto	arm_ep0_in_with_flags	; arm the IN buffer

; if this is the status stage of a Set Address request, assign the address here.
; The OUT buffer has already been armed for the next SETUP.
_check_for_pending_address
	btfss	USB_STATE,ADDRESS_PENDING
	return
; read the address out of the setup packed in the OUT buffer
	bcf	USB_STATE,ADDRESS_PENDING
	movfw	BANKED_EP0OUT_BUF+wValueL
	banksel	UADDR
	movwf	UADDR
	return

;;; Reads descriptor data from EP0_DATA_IN_PTR, copies it to the EP0 IN buffer,
;;; and decrements EP0_DATA_IN_COUNT.
;;; arguments:	BSR=0
;;; returns:	EP0_DATA_IN_PTRL advanced
;;;		EP0_DATA_IN_COUNT decremented
;;; clobbers:	W, FSR0, FSR1
ep0_read_in
	bcf	BANKED_EP0IN_STAT,UOWN	; make sure we have ownership of the buffer
	clrf	BANKED_EP0IN_CNT	; initialize buffer size to 0
	tstf	EP0_DATA_IN_COUNT	; do nothing if there are 0 bytes to send
	retz
	movfw	EP0_DATA_IN_PTR		; set up source pointer
	movwf	FSR0L
	movlw	DESCRIPTOR_ADRH|0x80
	movwf	FSR0H
	ldfsr1d	EP0IN_BUF		; set up destination pointer
	clrw
; byte copy loop
_bcopy	sublw	EP0_BUF_SIZE		; have we filled the buffer?
	bz	_bcdone
	moviw	FSR0++
	movwi	FSR1++
	incf	BANKED_EP0IN_CNT,f	; increase number of bytes copied
	movfw	BANKED_EP0IN_CNT	; save to test on the next iteration
	decfsz	EP0_DATA_IN_COUNT,f	; decrement number of bytes remaining
	goto	_bcopy
; write back the updated source pointer
_bcdone	movfw	FSR0L
	movwf	EP0_DATA_IN_PTR
; if we're sending the configuration descriptor, we need to inject the app's
; values for bus power/self power and max current consumption
_check_for_config_bmattributes
	movlw	(low CONFIGURATION_DESCRIPTOR)+EP0_BUF_SIZE
	subwf	FSR0L,w
	bnz	_check_for_config_bmaxpower
; if we're sending the first 8 bytes of the configuration descriptor,
; set bit 6 of bmAttributes if the application is self-powered
	btfsc	APP_POWER_CONFIG,0
	bsf	BANKED_EP0IN_BUF+7,6
	return
_check_for_config_bmaxpower
	movlw	(low CONFIGURATION_DESCRIPTOR)+(EP0_BUF_SIZE*2)
	subwf	FSR0L,w
	retnz
; if we're sending the second 8 bytes of the configuration descriptor,
; replace bMaxPower with the app's value
	movfw	APP_POWER_CONFIG
	bcf	WREG,0			; value is in the upper 7 bits
	movwf	BANKED_EP0IN_BUF+0
	return

;;; Initializes the buffers for the CDC endpoints (1 OUT, 1 IN, and 2 IN).
;;; arguments:	none
;;; returns:	none
;;; clobbers:	W, BSR=0
cdc_init
	banksel	BANKED_EP1OUT_STAT
	call	arm_ep1_out
	; arm EP1 IN buffer, clearing data toggle bit
	clrw

; arms endpoint 1 IN, toggling DTS if W=(1<<DTS)
arm_ep1_in
	clrf	BANKED_EP1IN_CNT	; next packet will have 0 length (unless another OUT is received)
	andwf	BANKED_EP1IN_STAT,f	; clear all bits (except DTS if bit is set in W)
	xorwf	BANKED_EP1IN_STAT,f	; update data toggle (if bit is set in W)
	bsf	BANKED_EP1IN_STAT,UOWN
	return

;;; Services a transaction on one of the CDC endpoints.
;;; arguments:	USTAT value in FSR1H
;;;		BSR=0
;;; returns:	none
;;; clobbers:	W, FSR0, FSR1
usb_service_cdc
	movlw	(1<<DTS)
	retbfs	FSR1H,ENDP1		; ignore endpoint 2
	bbfs	FSR1H,DIR,arm_ep1_in	; if endpoint 1 IN, rearm buffer
	movf	BANKED_EP1OUT_CNT,f	; test for a zero-length packet
	bz	arm_ep1_out		; (just ignore them and rearm the OUT buffer)
	bcf	BANKED_EP1IN_STAT,UOWN
	call	bootloader_exec_cmd	; execute command; status returned in W
	banksel	BANKED_EP1IN_BUF
	movwf	BANKED_EP1IN_BUF	; copy status to IN buffer
	movlw	1
	movwf	BANKED_EP1IN_CNT	; output byte count is 1
	bsf	BANKED_EP1IN_STAT,UOWN
	; fall through to arm_ep1_out

arm_ep1_out
	movlw	EP1_OUT_BUF_SIZE	; set CNT
	movwf	BANKED_EP1OUT_CNT
	clrf	BANKED_EP1OUT_STAT	; ignore data toggle
	bsf	BANKED_EP1OUT_STAT,UOWN	; rearm OUT buffer
	return

;;; Executes a bootloader command.
;;; arguments:	command payload in EP1 OUT buffer
;;; 		BSR=0
;;; returns:	status code in W
;;; clobbers:	W, BSR, FSR0, FSR1
bootloader_exec_cmd
; check length of data packet
	movlw	BCMD_SET_PARAMS_LEN
	subwf	BANKED_EP1OUT_CNT,w
	bz	_bootloader_set_params
	movlw	BCMD_WRITE_LEN
	subwf	BANKED_EP1OUT_CNT,w
	bz	_bootloader_write
	movlw	BCMD_RESET_LEN
	subwf	BANKED_EP1OUT_CNT,w
	bz	_bootloader_reset
	retlw	BSTAT_INVALID_COMMAND

; Resets the device if the received byte matches the reset character.
_bootloader_reset
	movlw	BCMD_RESET_CHAR
	subwf	BANKED_EP1OUT_BUF,w	; check received character
	skpz
	retlw	BSTAT_INVALID_COMMAND
; command is valid, reset the device
	reset

; Sets the write address, expected checksum of the next 32 words,
; and erases the row at that address if the last byte of the command matches
; the "erase" character.
; BSR=0
_bootloader_set_params
	movfw	BANKED_EP1OUT_BUF+BCMD_SET_PARAMS_CKSUM	; expected checksum
	movwf	EXPECTED_CHECKSUM			; save for verification during write command
	movfw	BANKED_EP1OUT_BUF+BCMD_SET_PARAMS_ERASE
	movwf	FSR1L	; temp
	movfw	BANKED_EP1OUT_BUF+BCMD_SET_PARAMS_ADRL	; address lower bits
	movwf	FSR1H	; temp
	movfw	BANKED_EP1OUT_BUF+BCMD_SET_PARAMS_ADRH	; address upper bits
	banksel	PMADRH
	movwf	PMADRH
	movfw	FSR1H	; bring lower bits out of temp
	movwf	PMADRL
; do we need to erase?
	movlw	BCMD_ERASE_CHAR
	subwf	FSR1L,w
	skpz
	retlw	BSTAT_OK	; if no reset command is given, return OK

; Erases the row of flash in PMADRH:PMADRL.
; BSR=3
_bootloader_erase
	movlw	(1<<FREE)|(1<<WREN)	; enable write and erase to program memory
	movwf	PMCON1
	call	flash_unlock		; stalls until erase finishes
_wdone	bcf	PMCON1,WREN		; clear write enable flag
	retlw	BSTAT_OK

; Verifies that the checksum of the 32 words (64 bytes) in the EP1 OUT buffer
; matches the previously sent value. If so, the 32 bytes are then written to
; flash memory at the address in PMADRH:PMADRL. (set by a prior command)
; BSR=0
_bootloader_write
; The expected checksum is the two's complement of the sum of the bytes.
; If the data is valid, we can add the checksum to the sum of the bytes and
; the result will be 0. We initialize a temporary register with the expected
; checksum, and then add each byte to it as it's processed.
; If the value in the temp register is 0 after all 64 bytes have been copied
; to the write latches, proceed with the write.
	movfw	EXPECTED_CHECKSUM
	movwf	FSR1L			; use a temp for the running checksum
	ldfsr0d	EP1OUT_BUF		; set up read pointer
	movlw	(1<<LWLO)|(1<<WREN)	; write to latches only
	banksel	PMCON1
	movwf	PMCON1
; simultaneously compute the checksum of the 32 words and copy them to the
; write latches
	movlw	32			; number of words to write minus 1
	movwf	FSR1H			; used for loop count
_wloop	moviw	FSR0++			; load lower byte
	addwf	FSR1L,f			; add lower byte to checksum
	movwf	PMDATL			; copy to write latch
	moviw	FSR0++			; load upper byte
	addwf	FSR1L,f			; add upper byte to checksum
	movwf	PMDATH			; copy to write latch
; after writing the 32nd word to PMDATH:PMDATL, don't execute the unlock sequence
; or advance the address pointer!
	decf	FSR1H,f			; decrement loop count
	bz	_wcksum			; if 0, we're done writing to the latches
; still have more words to go
	call	flash_unlock		; execute unlock sequence
	incf	PMADRL,f		; increment write address
	goto	_wloop
; verify the checksum
_wcksum	clrf	PMCON1
	tstf	FSR1L
	skpz
	retlw	BSTAT_INVALID_CHECKSUM	; if there's a mismatch, abort the write
; checksum is valid, write the data
	bsf	PMCON1,WREN
	call	flash_unlock		; stalls until write finishes
; verify the write: compare each byte in the buffer to its counterpart that
; was just written to flash.
; we do this backwards so we don't waste instructions resetting the pointers.
; (note: PMADRH:PMADRL is already pointing at the last written word, but FSR0
; is pointing to one byte past the end of the buffer)
	clrf	PMCON1			; clear write enable
	bsf	FSR1H,5			; set loop count to 32 (just need to set one bit because it's already 0)
_vloop	bsf	PMCON1,RD		; read word from flash
	nop				; 2 required nops
	nop
	moviw	--FSR0			; get high byte of expected word
	subwf	PMDATH,w		; compare with high byte written to flash
	skpz
	retlw	BSTAT_VERIFY_FAILED
	moviw	--FSR0			; get low byte of expected word
	subwf	PMDATL,w		; compare with low byte written to flash
	skpz
	retlw	BSTAT_VERIFY_FAILED
	decf	PMADRL,f		; decrement read address
	decfsz	FSR1H,f			; decrement loop count
	goto	_vloop
	retlw	BSTAT_OK

;;; Executes the flash unlock sequence, performing an erase or write.
;;; arguments:	PMCON1 bits CFGS, LWLO, FREE and WREN set appropriately
;;;		BSR=3
;;; returns:	none
;;; clobbers:	W
flash_unlock
	movlw	0x55
	movwf	PMCON2
	movlw	0xAA
	movwf	PMCON2
	bsf	PMCON1,WR
	nop
	nop
ret	return

;;; Main function
;;; BSR=1 (OSCCON bank)
bootloader_start
; Configure the oscillator (48MHz from INTOSC using 3x PLL)
	movlw	(1<<SPLLEN)|(1<<SPLLMULT)|(1<<IRCF3)|(1<<IRCF2)|(1<<IRCF1)|(1<<IRCF0)
	movwf	OSCCON

; Wait for the oscillator and PLL to stabilize
_wosc	movlw	(1<<PLLRDY)|(1<<HFIOFR)|(1<<HFIOFS)
	andwf	OSCSTAT,w
	sublw	(1<<PLLRDY)|(1<<HFIOFR)|(1<<HFIOFS)
	bnz	_wosc

; Check for valid application code: the lower 8 bits of the first word cannot be 0xFF
	call	app_is_present
	bz	_bootloader_main	; if we have no application, enter bootloader mode

; We have a valid application? Check if the entry pin is grounded
	banksel	PORTA
	btfss	PORTA,RA3
	goto	_bootloader_main	; enter bootloader mode if input is low

; We have a valid application and the entry pin is high. Start the application.
	banksel	OPTION_REG
	bsf	OPTION_REG,NOT_WPUEN	; but first, disable weak pullups
	if APP_ENTRY_POINT>=2048
	pagesel	APP_ENTRY_POINT
	endif
	goto	APP_ENTRY_POINT

; Not entering application code: initialize the USB interface and wait for commands.
_bootloader_main
; Enable active clock tuning
	banksel	ACTCON
	movlw	(1<<ACTSRC)|(1<<ACTEN)
	movwf	ACTCON		; source = USB

	if LOGGING_ENABLED
	call	uart_init
; Print a power-on character
	call	log_init
	logch	'^',LOG_NEWLINE
	endif

; Initialize USB
	call	usb_init

; Attach to the bus (could be a subroutine, but inlining it saves 2 instructions)
_usb_attach
	logch	'A',0
	banksel	UCON		; reset UCON
	clrf	UCON
	banksel	PIE2
	bsf	PIE2,USBIE	; enable USB interrupts
	bsf	INTCON,PEIE
	banksel	UCON
_usben	bsf	UCON,USBEN	; enable USB module and wait until ready
	btfss	UCON,USBEN
	goto	_usben
	logch	'!',LOG_NEWLINE

; Enable interrupts and enter an idle loop
; (Loop code is located at the top of the file, in the first 256 words of
; program memory)
	goto	bootloader_main_loop

;;; Determines if application code is present in flash memory.
;;; arguments:	none
;;; returns:	Z flag cleared if application code is present
;;; clobbers:	W, FSR0
app_is_present
	clrf	FSR0L
	movlw	(high APP_ENTRY_POINT)|0x80	; need to set high bit to indicate program memory
	movwf	FSR0H
	moviw	FSR0
	incw				; if W was 0xFF, it'll be 0 now
	return				; Z flag will be unset if app code is present

;;; Gets the application's power config byte and stores it in APP_POWER_CONFIG.
;;; arguments:	none
;;; returns:	none
;;; clobbers:	W, BSR, FSR0
get_app_power_config
	banksel	APP_POWER_CONFIG
	movlw	0x33			; default value: bus-powered, max current 100 mA
	movwf	APP_POWER_CONFIG
	call	app_is_present
	retz				; if Z flag is set, we have no application, just return
	if LOGGING_ENABLED
	pagesel	APP_CONFIG
	endif
	call	APP_CONFIG		; config value returned in W
	pagesel	get_app_power_config
	banksel	APP_POWER_CONFIG
	movwf	APP_POWER_CONFIG
	return

;;; Initializes the USB system and resets all associated registers.
;;; arguments:	none
;;; returns:	none
;;; clobbers:	W, BSR, FSR0, FSR1H
usb_init
	logch	'R',LOG_NEWLINE
; disable USB interrupts
	banksel	PIE2
	bcf	PIE2,USBIE
; clear USB registers
	banksel	UEIR
	clrf	UEIR
	clrf	UIR
; disable endpoints we won't use
	clrf	UEP3
	clrf	UEP4
	clrf	UEP5
	clrf	UEP6
	clrf	UEP7
; set configuration
	clrf	UEIE		; don't need any error interrupts
	movlw	(1<<UPUEN)|(1<<FSEN)
	movwf	UCFG		; enable pullups, full speed, no ping-pong buffering
	movlw	(1<<TRNIE)|(1<<URSTIE)
	movwf	UIE		; only need interrupts for transaction complete and reset
; clear all BDT entries, variables, and buffers
	clrf	FSR0L
	movlw	high BDT_START	; BDT starts at 0x2000
	movwf	FSR0H
	movlw	USED_RAM_LEN
	movwf	FSR1H		; loop count
	movlw	0
_ramclr	movwi	FSR0++
	decfsz	FSR1H,f
	goto	_ramclr
; get the app's power configuration (if it's present)
	call	get_app_power_config
; reset ping-pong buffers and address
	banksel	UCON
	bsf	UCON,PPBRST
	clrf	UADDR
	bcf	UCON,PKTDIS	; enable packet processing
	bcf	UCON,PPBRST	; clear ping-pong buffer reset flag
; flush pending transactions
_tflush	btfss	UIR,TRNIF
	goto	_initep
	bcf	UIR,TRNIF
	call	ret		; need at least 6 cycles before checking TRNIF again
	goto	_tflush
; initialize endpoints:
; 0 for control
; 1 for CDC bulk data
; 2 for CDC notifications (though it's never actually used)
; my intuition was that I should wait until a SET_CONFIGURATION is received
; before setting up endpoints 1 and 2... but there seemed to be a timing issue
; when doing so, so I moved them here
_initep	movlw	(1<<EPHSHK)|(1<<EPOUTEN)|(1<<EPINEN)
	movwf	UEP0
	movlw	(1<<EPHSHK)|(1<<EPCONDIS)|(1<<EPOUTEN)|(1<<EPINEN)
	movwf	UEP1
	movlw	(1<<EPHSHK)|(1<<EPCONDIS)|(1<<EPINEN)
	movwf	UEP2
; initialize endpoint buffers and counts
	banksel	BANKED_EP0OUT_ADRL
	movlw	low EP0OUT_BUF	; set endpoint 0 OUT address low
	movwf	BANKED_EP0OUT_ADRL
	movlw	low EP0IN_BUF	; set endpoint 0 IN address low
	movwf	BANKED_EP0IN_ADRL
	movlw	low EP1OUT_BUF	; set endpoint 1 OUT address low
	movwf	BANKED_EP1OUT_ADRL
	movlw	low EP1IN_BUF	; set endpoint 1 IN address low
	movwf	BANKED_EP1IN_ADRL
	movlw	EPBUF_ADRH	; set all ADRH values
	movwf	BANKED_EP0OUT_ADRH
	movwf	BANKED_EP0IN_ADRH
	movwf	BANKED_EP1OUT_ADRH
	movwf	BANKED_EP1IN_ADRH
	goto	arm_ep0_out

;;; Includes
	if LOGGING_ENABLED
	include "log.asm"
	endif

;;; Descriptors

; Place all the descriptors at the end of the bootloader region.
; This serves 2 purposes: 1) as long as the total length of all descriptors is
; less than 256, we can address them with an 8-bit pointer,
; and 2) the assembler will raise an error if space is exhausted.
	org	BOOTLOADER_SIZE-ALL_DESCS_TOTAL_LEN
DESCRIPTOR_ADRH	equ	high $
DEVICE_DESCRIPTOR
	dt	DEVICE_DESC_LEN	; bLength
	dt	0x01		; bDescriptorType
	dt	0x00, 0x02	; bcdUSB (USB 2.0)
	dt	0x02		; bDeviceClass (communication device)
	dt	0x00		; bDeviceSubclass
	dt	0x00		; bDeviceProtocol
	dt	0x08		; bMaxPacketSize0 (8 bytes)
	dt	low USB_VENDOR_ID, high USB_VENDOR_ID	; idVendor
	dt	low USB_PRODUCT_ID, high USB_PRODUCT_ID	; idProduct
	dt	0x01, 0x00	; bcdDevice (1)
	dt	0x00		; iManufacturer
	dt	0x00		; iProduct
	dt	0x01		; iSerialNumber
	dt	0x01		; bNumConfigurations

CONFIGURATION_DESCRIPTOR
	dt	0x09		; bLength
	dt	0x02		; bDescriptorType
	dt	CONFIG_DESC_TOTAL_LEN, 0x00	; wTotalLength
	dt	0x02		; bNumInterfaces
	dt	0x01		; bConfigurationValue
	dt	0x00		; iConfiguration
	dt	0x80		; bmAttributes
	dt	0x11		; bMaxPower

INTERFACE_DESCRIPTOR_0
	dt	0x09		; bLength
	dt	0x04		; bDescriptorType (INTERFACE)
	dt	0x00		; bInterfaceNumber
CONFIGURATION_0_CONSTANT
	dt	0x00		; bAlternateSetting
CONFIGURATION_1_CONSTANT
	dt	0x01		; bNumEndpoints
	dt	0x02		; bInterfaceClass (communication)
	dt	0x02		; bInterfaceSubclass (abstract control model)
	dt	0x01		; bInterfaceProtocol (V.25ter, common AT commands)
	dt	0x00		; iInterface

	if (CONFIGURATION_0_CONSTANT>>8) != (CONFIGURATION_1_CONSTANT>>8)
	error "CONSTANT_0 and CONSTANT_1 must be in the same 256-word region"
	endif

HEADER_FUNCTIONAL_DESCRIPTOR
	dt	0x05		; bFunctionLength
	dt	0x24		; bDescriptorType (CS_INTERFACE)
	dt	0x00		; bDescriptorSubtype (header functional descriptor)
	dt	0x10,0x01	; bcdCDC (specification version, 1.1)

ABSTRACT_CONTROL_MANAGEMENT_FUNCTIONAL_DESCRIPTOR
	dt	0x04		; bFunctionLength
	dt	0x24		; bDescriptorType (CS_INTERFACE)
	dt	0x02		; bDescriptorSubtype (abstract control management functional descriptor)
	dt	0x02		; bmCapabilities

UNION_FUNCTIONAL_DESCRIPTOR
	dt	0x05		; bFunctionLength
	dt	0x24		; bDescriptorType (CS_INTERFACE)
	dt	0x06		; bDescriptorSubtype (union functional descriptor)
	dt	0x00		; bMasterInterface
	dt	0x01		; bSlaveInterface0

CALL_MANAGEMENT_FUNCTIONAL_DESCRIPTOR
	dt	0x05		; bFunctionLength
	dt	0x24		; bDescriptorType (CS_INTERFACE)
	dt	0x01		; bDescriptorSubtype (call management functional descriptor)
	dt	0x00		; bmCapabilities (doesn't handle call management)
	dt	0x01		; dDataInterface

ENDPOINT_DESCRIPTOR_2_IN
	dt	0x07		; bLength
	dt	0x05		; bDescriptorType (ENDPOINT)
	dt	0x82		; bEndpointAddress (2 IN)
	dt	0x03		; bmAttributes (transfer type: interrupt)
	dt	0x08, 0x00	; wMaxPacketSize (8)
	dt	0x7f		; bInterval

INTERFACE_DESCRIPTOR_1
	dt	0x09		; bLength
	dt	0x04		; bDescriptorType (INTERFACE)
	dt	0x01		; bInterfaceNumber
	dt	0x00		; bAlternateSetting
	dt	0x02		; bNumEndpoints
	dt	0x0a		; bInterfaceClass (data)
	dt	0x00		; bInterfaceSubclass
	dt	0x00		; bInterfaceProtocol
	dt	0x00		; iInterface

ENDPOINT_DESCRIPTOR_1_IN
	dt	0x07		; bLength
	dt	0x05		; bDescriptorType (ENDPOINT)
	dt	0x81		; bEndpointAddress (1 IN)
	dt	0x02		; bmAttributes (transfer type: bulk)
	dt	0x40, 0x00	; wMaxPacketSize (64)
	dt	0x00		; bInterval

ENDPOINT_DESCRIPTOR_1_OUT
	dt	0x07		; bLength
	dt	0x05		; bDescriptorType (ENDPOINT)
	dt	0x01		; bEndpointAddress (1 OUT)
	dt	0x02		; bmAttributes (transfer type: bulk)
	dt	0x40, 0x00	; wMaxPacketSize (64)
	dt	0x00		; bInterval

; extract nibbles from serial number
SN1	equ	(SERIAL_NUMBER>>12) & 0xF
SN2	equ	(SERIAL_NUMBER>>8) & 0xF
SN3	equ	(SERIAL_NUMBER>>4) & 0xF
SN4	equ	SERIAL_NUMBER & 0xF

SERIAL_NUMBER_STRING_DESCRIPTOR
	dt	SERIAL_NUM_DESC_LEN	; bLength
	dt	0x03		; bDescriptorType (STRING)
	dt	'0'+SN1+((SN1>9)*7), 0x00	; convert hex digits to ASCII
	dt	'0'+SN2+((SN2>9)*7), 0x00
	dt	'0'+SN3+((SN3>9)*7), 0x00
	dt	'0'+SN4+((SN4>9)*7), 0x00

; Raise an error if the descriptors aren't properly aligned. (This means you
; changed the descriptors withouth updating the definition of ALL_DESCS_TOTAL_LEN.)
	if $!=BOOTLOADER_SIZE
	error "Descriptors must be aligned with the end of the bootloader region"
	endif

	end


text:
[![Latest Stable Version](https://poser.pugx.org/jadjoubran/laravel5-angular-material-starter/v/stable)](https://packagist.org/packages/jadjoubran/laravel5-angular-material-starter)
[![Latest Unstable Version](https://poser.pugx.org/jadjoubran/laravel5-angular-material-starter/v/unstable)](https://packagist.org/packages/jadjoubran/laravel5-angular-material-starter)
[![Build Status](https://travis-ci.org/jadjoubran/laravel5-angular-material-starter.svg?branch=master)](https://travis-ci.org/jadjoubran/laravel5-angular-material-starter)
[![StyleCI](https://styleci.io/repos/34944760/shield?style=flat)](https://styleci.io/repos/34944760)
[![Code Climate](https://codeclimate.com/github/jadjoubran/laravel5-angular-material-starter/badges/gpa.svg)](https://codeclimate.com/github/jadjoubran/laravel5-angular-material-starter)
[![License](https://poser.pugx.org/jadjoubran/laravel5-angular-material-starter/license)](https://packagist.org/packages/jadjoubran/laravel5-angular-material-starter)
[![Join the chat at https://gitter.im/jadjoubran/laravel5-angular-material-starter](https://badges.gitter.im/jadjoubran/laravel5-angular-material-starter.svg)](https://gitter.im/jadjoubran/laravel5-angular-material-starter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

![Laravel & Angular](http://i.imgur.com/CwQy3Il.png)

## Demo

An online demo is available.

## Angular (2+) update

While this starter used to be an excellent starting point for Laravel 5 & Angular 1.x, using Angular 1.x results in large JavaScript bundles which makes mobile experience slow.
Thus it's recommended to upgrade to Angular (2+).
You can use the shiny new [Laravel & Angular package](https://github.com/jadjoubran/laravel-angular)

## Docs

[View Latest Docs](http://laravel-angular.readme.io/) for installation steps & tutorials.

Running on 3.2? Here are the [3.2 Docs](https://laravel-angular.readme.io/v3.2)

## Screencasts

Screencasts on [Youtube](https://www.youtube.com/c/LaravelAngularMaterialStarter).

## Issues, questions and feature requests
Open a new issue, I'd love to help.

## Do It Yourself (Outdated)

A nice article on sitepoint that explains the first few versions of this repository. Recommended read if you're not familiar with the underlying technologies.

## Community translations

- [v3.4 - Chinese](https://github.com/ArrayZoneYour/Laravel-Angular-Material-Doc-Chinese)

## Contributing

Thank you for contributing to this repository.

Here are the guidelines:

1. If you are adding/modifying backend functionality, make sure to include the appropriate `test`. Let me know if you need help writing the test.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ask_amy — ASK Amy  documentation</title>
    <link rel="stylesheet" href="_static/sphinx13.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,700'
          rel='stylesheet' type='text/css' />

Home

Get it

Docs

Extend/Develop

Navigation

          index

          modules |

ASK Amy home |

Documentation »

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

ask_amy¶

ask_amy package

Submodules

ask_amy.lambda_function module

Module contents

Navigation

          index

          modules |

ASK Amy home |

Documentation »

        © Copyright 2017, Dan Higgins.
      Created using Sphinx 1.7.0.


text:
package com.vk.api.sdk.queries.groups;

import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.Actor;
import com.vk.api.sdk.objects.groups.responses.GetMembersResponse;

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

/**
 * Query for Groups.getMembers method
 */
public class GroupsGetMembersQuery extends AbstractQueryBuilder<GroupsGetMembersQuery, GetMembersResponse> {
    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client VK API client
     * @param actor  actor with access token
     */
    public GroupsGetMembersQuery(VkApiClient client, Actor actor) {
        super(client, "groups.getMembers", GetMembersResponse.class);
        accessToken(actor.getAccessToken());
    }

    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client VK API client
     */
    public GroupsGetMembersQuery(VkApiClient client) {
        super(client, "groups.getMembers", GetMembersResponse.class);
    }

    /**
     * ID or screen name of the community.
     *
     * @param value value of "group id" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsGetMembersQuery groupId(String value) {
        return unsafeParam("group_id", value);
    }

    /**
     * Sort order
     *
     * @param value value of "sort" parameter. By default 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsGetMembersQuery sort(GroupsGetMembersSort value) {
        return unsafeParam("sort", value);
    }

    /**
     * Offset needed to return a specific subset of community members.
     *
     * @param value value of "offset" parameter. Minimum is 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsGetMembersQuery offset(Integer value) {
        return unsafeParam("offset", value);
    }

    /**
     * Number of community members to return.
     *
     * @param value value of "count" parameter. Maximum is 1000. Minimum is 0. By default 1000.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsGetMembersQuery count(Integer value) {
        return unsafeParam("count", value);
    }

    @Override
    protected GroupsGetMembersQuery getThis() {
        return this;
    }

    @Override
    protected List<String> essentialKeys() {
        return Collections.EMPTY_LIST;
    }
}


text:
using Aragas.Network.IO;

using PokeD.Core.Data.SCON;

namespace PokeD.Core.Packets.SCON.Logs
{
    public class LogListResponsePacket : SCONPacket
    {
        public Log[] Logs { get; set; } = new Log[0];

        public override void Deserialize(ProtobufDeserialiser deserialiser)
        {
            Logs = deserialiser.Read(Logs);
        }
        public override void Serialize(ProtobufSerializer serializer)
        {
            serializer.Write(Logs);
        }
    }
}


text:
import { XmlComponent } from "@file/xml-components";
import { DefaultAttributes } from "./default-attributes";

export class Default extends XmlComponent {
    public constructor(contentType: string, extension?: string) {
        super("Default");

        this.root.push(
            new DefaultAttributes({
                contentType: contentType,
                extension: extension,
            }),
        );
    }
}


text:
<!DOCTYPE html>
<html>
<!--
  Copyright 2009 The Closure Library Authors. All Rights Reserved.
  Author: brenneman@google.com (Shawn Brenneman)
-->
<head>
<title>Closure Unit Tests - goog.async.DeferredList</title>
<script src="../../../../../closure/goog/base.js"></script>
<script src="../../deps.js"></script>
<script>

goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.async.DeferredList');
goog.require('goog.testing.jsunit');

</script>
</head>
<body>
<script>

var Deferred = goog.async.Deferred;
var DeferredList = goog.async.DeferredList;

/**
 * A list of unhandled errors.
 * @type {Array.<Error>}
 */
var storedErrors = [];

/**
 * Adds a catch-all error handler to deferred objects. Unhandled errors that
 * reach the catch-all will be rethrown during tearDown.
 *
 * @param {...Deferred} var_args A list of deferred objects.
 */
function addCatchAll(var_args) {
  for (var i = 0, d; d = arguments[i]; i++) {
    d.addErrback(function(res) {
      storedErrors.push(res);
    });
  }
}

/**
 * Checks storedErrors for unhandled errors. If found, the error is rethrown.
 */
function checkCatchAll() {
  var err = storedErrors.shift();
  goog.array.clear(storedErrors);

  if (err) {
    throw err;
  }
}

function tearDown() {
  checkCatchAll();
}

function neverHappen(res) {
  fail('This should not happen');
}

function testNoInputs() {
  var count = 0;
  var d = new DeferredList([]);

  d.addCallback(function(res) {
    assertArrayEquals([], res);
    count++;
  });
  addCatchAll(d);

  assertEquals('An empty DeferredList should fire immediately with an empty ' +
               'list of results.',
               1, count);
}

function testNoInputsAndFireOnOneCallback() {
  var count = 0;
  var d = new DeferredList([], true);

  d.addCallback(function(res) {
    assertArrayEquals([], res);
    count++;
  });
  addCatchAll(d);

  assertEquals('An empty DeferredList with opt_fireOnOneCallback set should ' +
               'not fire unless callback is invoked explicitly.',
               0, count);

  d.callback([]);
  assertEquals('Calling callback explicitly should still fire.', 1, count);
}

function testDeferredList() {
  var count = 0;
  var results;

  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();

  var dl = new DeferredList([a, b, c]);

  dl.addCallback(function(res) {
    assertEquals('Expected 3 Deferred results.', 3, res.length);

    assertTrue('Deferred a should return success.', res[0][0]);
    assertFalse('Deferred b should return failure.', res[1][0]);
    assertTrue('Deferred c should return success.', res[2][0]);

    assertEquals('Unexpected return value for a.', 'A', res[0][1]);
    assertEquals('Unexpected return value for c.', 'C', res[2][1]);

    assertTrue(res[1][1] instanceof Error);
    assertEquals('B', res[1][1].message);

    count++;
  });

  addCatchAll(dl);

  c.callback('C');
  assertEquals(0, count);

  b.errback('B');
  assertEquals(0, count);

  a.callback('A');

  checkCatchAll();
  assertEquals('DeferredList should fire on last call or errback.', 1, count);
}

function testFireOnFirstCallback() {
  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();

  var dl = new DeferredList([a, b, c], true);

  dl.addCallback(function(res) {
    assertEquals('Should be the deferred index in this mode.', 1, res[0]);
    assertEquals('B', res[1]);
  });
  dl.addErrback(neverHappen);

  addCatchAll(dl);

  a.errback('A');
  b.callback('B');

  // Shouldn't cause any more callbacks on the DeferredList.
  c.callback('C');
}

function testFireOnFirstErrback() {
  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();

  var dl = new DeferredList([a, b, c], false, true);

  dl.addCallback(neverHappen);
  dl.addErrback(function(res) {
    assertTrue(res instanceof Error);
    assertEquals('A', res.message);

    // Return a non-error value to break out of the errback path.
    return true;
  });

  addCatchAll(dl);

  b.callback('B');
  a.errback('A');

  // Shouldn't cause any more callbacks on the DeferredList.
  c.callback('C');
}

function testNoConsumeErrors() {
  var count = 0;

  var a = new Deferred();
  var dl = new DeferredList([a]);

  a.addErrback(function(res) {
    count++;
    return true;
  });

  addCatchAll(a, dl);

  a.errback('oh noes');
  assertEquals(1, count);
}

function testConsumeErrors() {
  var count = 0;

  var a = new Deferred();
  var dl = new DeferredList([a], false, false, true);

  a.addErrback(neverHappen);

  addCatchAll(a, dl);

  a.errback('oh noes');
  assertEquals(0, count);
}

function testNesting() {

  function upperCase(res) {
    return res.toUpperCase();
  }

  // Concatenates a list of callback or errback results into a single string.
  function combine(res) {
    return goog.array.map(res, function(result) {
      // Use the Error message if the result was not a success.
      return result[0] ? result[1] : result[1].message;
    }).join('');
  }

  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();
  var d = new Deferred();

  a.addCallback(upperCase);
  b.addCallback(upperCase);
  c.addCallback(upperCase);
  d.addCallback(upperCase);

  var dl1 = new DeferredList([a, b]);
  var dl2 = new DeferredList([c, d]);

  dl1.addCallback(combine);
  dl2.addCallback(combine);

  var dl3 = new DeferredList([dl1, dl2]);
  dl3.addCallback(combine);
  dl3.addCallback(function(res) {
    assertEquals('AbCd', res);
  });

  addCatchAll(dl1, dl2, dl3);

  a.callback('a');
  c.callback('c');
  b.errback('b');
  d.errback('d');
}

function testGatherResults() {
  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();

  var dl = DeferredList.gatherResults([a, b, c]);

  dl.addCallback(function(res) {
    assertArrayEquals(['A', 'B', 'C'], res);
  });

  addCatchAll(dl);

  b.callback('B');
  a.callback('A');
  c.callback('C');
}

function testGatherResultsFailure() {
  var a = new Deferred();
  var b = new Deferred();
  var c = new Deferred();

  var dl = DeferredList.gatherResults([a, b, c]);

  var firedErrback = false;
  var firedCallback = false;
  dl.addCallback(function() {
    firedCallback = true;
  });
  dl.addErrback(function() {
    firedErrback = true;
    return true;
  });

  addCatchAll(dl);

  b.callback('B');
  a.callback('A');
  c.errback();

  assertTrue('Errback should be called', firedErrback);
  assertFalse('Callback should not be called', firedCallback);
}

function testGatherResults_cancelCancelsChildren() {
  var cancelled = [];
  var a = new Deferred(function() {
    cancelled.push('a');
  });
  var b = new Deferred(function() {
    cancelled.push('b');
  });
  var c = new Deferred(function() {
    cancelled.push('c');
  });

  var dl = new DeferredList([a, b, c]);

  var firedErrback = false;
  var firedCallback = false;
  dl.addCallback(function() {
    firedCallback = true;
  });
  dl.addErrback(function() {
    firedErrback = true;
    return true;
  });

  addCatchAll(dl);

  b.callback('b');
  dl.cancel();

  assertTrue('Errback should be called', firedErrback);
  assertFalse('Callback should not be called', firedCallback);
  assertArrayEquals(['a', 'c'], cancelled);
}

function testErrorCancelsPendingChildrenWhenFireOnFirstError() {
  var cancelled = [];
  var a = new Deferred(function() {
    cancelled.push('a');
  });
  var b = new Deferred(function() {
    cancelled.push('b');
  });
  var c = new Deferred(function() {
    cancelled.push('c');
  });

  var dl = new DeferredList([a, b, c], false, true);

  var firedErrback = false;
  var firedCallback = false;
  dl.addCallback(function() {
    firedCallback = true;
  });
  dl.addErrback(function() {
    firedErrback = true;
    return true;
  });

  addCatchAll(dl);

  a.callback('a')
  b.errback();

  assertTrue('Errback should be called', firedErrback);
  assertFalse('Callback should not be called', firedCallback);
  assertArrayEquals('Only C should be cancelled since A and B finished.',
      ['c'], cancelled);
}

function testErrorDoesNotCancelPendingChildrenForVanillaLists() {
  var cancelled = [];
  var a = new Deferred(function() {
    cancelled.push('a');
  });
  var b = new Deferred(function() {
    cancelled.push('b');
  });
  var c = new Deferred(function() {
    cancelled.push('c');
  });

  var dl = new DeferredList([a, b, c]);

  var firedErrback = false;
  var firedCallback = false;
  dl.addCallback(function() {
    firedCallback = true;
  });
  dl.addErrback(function() {
    firedErrback = true;
    return true;
  });

  addCatchAll(dl);

  a.callback('a')
  b.errback();
  c.callback('c')

  assertFalse('Errback should not be called', firedErrback);
  assertTrue('Callback should be called', firedCallback);
  assertArrayEquals('No cancellations', [], cancelled);
}

</script>
</body>
</html>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace Dnn.PersonaBar.Pages.Services.Dto
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Dnn.PersonaBar.Library.DTO.Tabs;
    using Newtonsoft.Json;

    [JsonObject]
    public class DnnPagesDto
    {
        public DnnPagesDto(IList<LocaleInfoDto> locales)
        {
            this.Locales = locales;
            this.Pages = new List<DnnPageDto>(); // one of each language
            this.Modules = new List<DnnModulesDto>(); // one for each module on the page
            foreach (var locale in locales)
            {
                this.Pages.Add(new DnnPageDto { CultureCode = locale.CultureCode });
            }
        }

        public IList<LocaleInfoDto> Locales { get; }

        public IList<DnnPageDto> Pages { get; }

        public IList<DnnModulesDto> Modules { get; }

        public bool HasMissingLanguages { get; set; }

        public bool ErrorExists { get; set; }

        public DnnPageDto Page(string locale)
        {
            return this.Pages.Single(pa => pa.CultureCode == locale);
        }

        public DnnModulesDto Module(Guid uniqueId)
        {
            var m = this.Modules.SingleOrDefault(dm => dm.UniqueId == uniqueId);
            if (m == null)
            {
                m = new DnnModulesDto(this.Locales.Select(l => l.CultureCode)) { UniqueId = uniqueId };
                this.Modules.Add(m);
            }
            return m;

        }

        public bool Error1(int moduleId, Guid uniqueId, string cultureCode)
        {
            return this.Modules.Any(dm => dm.UniqueId != uniqueId &&
                                     dm.Modules.Any(mm => mm.ModuleId == moduleId && mm.CultureCode != cultureCode));
        }

        public void RemoveLocale(string cultureCode)
        {
            var locale = this.Locales.FirstOrDefault(l => l.CultureCode == cultureCode);
            if (locale != null) this.Locales.Remove(locale);
        }
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>serializer::serializer</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.JSON">
<link rel="up" href="../boost__json__serializer.html" title="serializer">
<link rel="prev" href="reset/overload5.html" title="serializer::reset (5 of 5 overloads)">
<link rel="next" href="serializer/overload1.html" title="serializer::serializer (1 of 2 overloads)">

Home
Libraries
People
FAQ
More

serializer::serializer

          Move constructor (deleted)

serializer(
    serializer&&);
  » more...

          Default constructor.

serializer();
  » more...

Copyright © 2019, 2020 Vinnie Falco
Copyright © 2020 Krystian Stasiowski

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
import socket, errno
import sys, getopt, subprocess

class Ports:

  def __init__(self, origHost="localhost"):
    print "-" * 75
    print "Scanning Open Ports, example: $python Ports.py --host localhost -s 79 -e 83"
    print "\tHost Name is: %s" % origHost
    self.origHost = socket.gethostbyname(origHost)

  def find_open_port(self, min_port=1, max_port=65535):
    print "\tScan open ports from: %s to %s for ip: %s" % (min_port, max_port, self.origHost)
    print "-" * 75
    try:
      for port in range(min_port, max_port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((self.origHost, port))
        if result == 0:
          try:
            print "Port: {} \t --> Open \t Service: %s".format(port) % socket.getservbyport(port)
          except:
            print "Port: {} \t --> Open".format(port)
        #else:
        #  print "Port %s is not open" % port
    except KeyboardInterrupt:
      print "You pressed Ctrl+C :-)"
      sys.exit()
    except socket.gaierror:
      print 'Hostname "%s" could not be resolved. Exiting' % self.origHost
      sys.exit()
    except socket.error, e:
      print e[1]
      #raise e
      sys.exit()

def getPorts(argv):
   startport = 1
   endport = 65535
   hostname = "localhost"
   try:
      opts, args = getopt.getopt(argv,"hs:e:host:",["sport=","eport=", "hostname="])
   except getopt.GetoptError:
      print 'Ports.py -s <startport> -e <endport> --host <hostname>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'Ports.py -s <startport> -e <endport> --host <hostname>'
         sys.exit()
      elif opt in ("-s", "--sport"):
         startport = arg
      elif opt in ("-e", "--eport"):
         endport = arg
      elif opt in ("--host", "--hostname"):
         hostname = arg
   return int(startport), int(endport), hostname

if __name__ == '__main__':
  subprocess.call('clear',shell=True)
  startport, endport, hostname = getPorts(sys.argv[1:])
  aPorts = Ports(hostname)
  aPorts.find_open_port(startport, endport)


text:
package org.omg.PortableServer;

//
// IDL:omg.org/PortableServer/ThreadPolicyValue:1.0
//
public class ThreadPolicyValueHelper
{
    public static void
    insert(org.omg.CORBA.Any any, ThreadPolicyValue val)
    {
        org.omg.CORBA.portable.OutputStream out = any.create_output_stream();
        write(out, val);
        any.read_value(out.create_input_stream(), type());
    }

    public static ThreadPolicyValue
    extract(org.omg.CORBA.Any any)
    {
        if(any.type().equivalent(type()))
            return read(any.create_input_stream());
        else
            throw new org.omg.CORBA.BAD_OPERATION();
    }

    private static org.omg.CORBA.TypeCode typeCode_;

    public static org.omg.CORBA.TypeCode
    type()
    {
        if(typeCode_ == null)
        {
            org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
            String[] members = new String[2];
            members[0] = "ORB_CTRL_MODEL";
            members[1] = "SINGLE_THREAD_MODEL";
            typeCode_ = orb.create_enum_tc(id(), "ThreadPolicyValue", members);
        }

        return typeCode_;
    }

    public static String
    id()
    {
        return "IDL:omg.org/PortableServer/ThreadPolicyValue:1.0";
    }

    public static ThreadPolicyValue
    read(org.omg.CORBA.portable.InputStream in)
    {
        ThreadPolicyValue _ob_v;
        _ob_v = ThreadPolicyValue.from_int(in.read_ulong());
        return _ob_v;
    }

    public static void
    write(org.omg.CORBA.portable.OutputStream out, ThreadPolicyValue val)
    {
        out.write_ulong(val.value());
    }
}


text:
import { moduleForModel, test } from 'ember-qunit';
import modelList from '../../helpers/model-list';

moduleForModel('mesh-tree', 'Unit | Model | mesh tree ', {
  needs: modelList
});

test('it exists', function(assert) {
  var model = this.subject();
  // var store = this.store();
  assert.ok(!!model);
});


text:
<html>
	<head>
		<script language="javascript" src="../dom.js"></script>
		<script language="javascript" src="../menu.js"></script>
		<script language="javascript">
			var skin=parent._skin?parent._skin:"skin_standard";
			var lang=parent._lang?parent._lang:"en";

			initDom("../images/"+skin+"/",lang)
			styleSheet()
		</script>

		<script language="javascript">

			_globIDCont=0

			function cb()
			{
				switch (this.id)
				{
					case "addItem":
						this.par.add("gen"+(_globIDCont++),"Test item 1",cb,"imgtabs.gif",0,0)
						break

					case "addCheck":
						this.par.addCheck("gen"+(_globIDCont++),"check 1",cbCheck)
						break

					case "addCheckImg":
						this.par.addCheck("gen"+(_globIDCont++),"check 1",cbCheck,"imgtabs.gif",0,0)
						break

					case "addSep":
						this.par.addSeparator()
						break

					case "removeItem":
						this.par.removeByID("myItem");
						break

					case "removeSep":
						if(this.par.getItem(2).isSeparator)
							this.par.remove(2);
						break

					case "removeAll":
							this.par.remove();
						break

					case "insertItem":
						this.par.insert(3,"myItem"+(_globIDCont++),"insert text");
						break

					case "insertSep":
						this.par.insertSeparator(5);
						break

					default:
						alert(this.id)
						break
				}
			}
			function cbCheck()
			{
				alert(this.id+" checked? "+this.isChecked())
			}

			function showMenu(e)
			{
				menu.show(true,eventGetX(e),eventGetY(e))
			}

			function disableSecond()
			{
				var dis=(this.id=="1b")

				var item=menu.getItem(1)
				item.setDisabled(dis)
			}
			function disableFirst()
			{
				var dis=(this.id=="1c")

				var item=menu.getItem(5)
				item.setDisabled(dis)
			}

			function showFirst()
			{
				var dis=(this.id=="0d")

				var item=menu.getItem(5)
				item.show(dis)
			}

			function cbDisCheck()
			{
				check1.setDisabled(this.id=="0")
			}

			menu=newMenuWidget("test")

			menu.add("id1","Test item 1",cb,"imgtabs.gif",0,0)
			menu.add("id2","Test item 2",cb)
			menu.add("id3","Test item plus int",cb)
			menu.add("id4","court",cb)
			menu.add("id5","Test item 1",cb)
			menu.add("id6","Test item 2",cb,"format.gif",48,0,true,48,16)
			theItem=menu.add("id7","Test des check boxes",cb,"format.gif",64,0)

			menu2=newMenuWidget("test2")
			menu2.add("id8","Test item 2",cb)
			menu2.add("id9","essai",cb)
			check1=menu2.addCheck("check1","check 1",cbCheck)
			check1.check(true)
			check2=menu2.addCheck("check2","check 2",cbCheck)
			check2.check(false)
			check3=menu2.addCheck("check3","check 3",cbCheck,"format.gif",80,0)
			check3.check(true)
			check4=menu2.addCheck("check4","check 4",cbCheck,"format.gif",64,0)
			check4.check(false)
			menu2.addSeparator()
			menu2.add("0","Disable check 1",cbDisCheck)
			menu2.add("1","Enable check 1",cbDisCheck)
			theItem.attachSubMenu(menu2)

			menu.addSeparator()
			menu.add("0b","Enable second item",disableSecond)
			menu.add("1b","Disable second item",disableSecond)

			menu.addSeparator()
			menu.add("0c","Enable 6th item",disableFirst)
			menu.add("1c","Disable 6th item",disableFirst)

			menu.add("0d","Show 6th item",showFirst)
			menu.add("1d","Hide 6th item",showFirst)

			menu.addSeparator()

			theItem=menu.add("id10","Ajout dynamique d'items",cb)

				menu3=newMenuWidget("test3")
				menu3.add("addItem","Add an Item",cb)
				menu3.add("addCheck","Add a Check",cb)
				menu3.add("addCheckImg","Add a Check with image",cb)
				menu3.add("addSep","Add a separator",cb)
				menu3.addSeparator()

			theItem.attachSubMenu(menu3)

			theItem2=menu.add("theItem2","Remove/insert dynamique d'items",cb)
			menu4=newMenuWidget("test4")
				menu4.add("removeItem","remove an Item",cb)
				menu4.add("removeSep","remove a sep",cb)
				menu4.addSeparator()
				menu4.add("removeAll","remove all",cb)
				menu4.addSeparator()
				menu4.add("myItem","item to be removed",cb)
				menu4.addSeparator()
				menu4.add("insertItem","insert an item",cb)
				menu4.add("insertSep","insert an sep",cb)
			theItem2.attachSubMenu(menu4)

			menu.add("id19","Test item plus int",cb)
			menu.add("id20","court",cb)

			function loadCB()
			{
			}

		</script>
	</head>
	<body onload="loadCB()" onclick="showMenu(event)">
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g
			sdfjgfds lkfjglk sfdkg dflskjg lsdfgldfsjlgk sdfkg lsfdj glsdfjg lksfdjklg sdflk g

	</body>

</html>


text:
package org.wildfly.swarm.examples.jdd;

import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

/**
 * Created by rafaelszp on 9/8/16.
 */

@XmlRootElement
@Entity
@Table(name="PERSON")
public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name="PERSON_DOCUMENT_IDENTIFICATION",nullable = false,unique = true,length = 32)
    private String documentId;

    @Column(name="PERSON_NAME",nullable = false,length = 500)
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getDocumentId() {
        return documentId;
    }

    public void setDocumentId(String documentId) {
        this.documentId = documentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
.monaco-workbench > .part.statusbar {
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	z-index: 25;
	width: 100%;
	height: 22px;
	background: #007ACC;
	color: white;
	font-size: 12px;
	padding: 0 10px;
}

.monaco-workbench.no-workspace > .part.statusbar {
	background: #68217A;
}

.monaco-workbench > .part.statusbar > .statusbar-item {
	display: inline-block;
	line-height: 22px;
	height: 100%;
	vertical-align: top;
}

.monaco-workbench > .part.statusbar > .statusbar-item.left {
	margin-right: 5px;
}

.monaco-workbench > .part.statusbar > .statusbar-item.right {
	float: right;
	margin-left: 5px;
}

.monaco-workbench > .part.statusbar > .statusbar-item a:not([disabled]) {
	cursor: pointer;
	display: inline-block;
	height: 100%;
}

.monaco-workbench > .part.statusbar > .statusbar-entry > span {
	cursor: default;
	height: 100%;
}

.monaco-workbench > .part.statusbar > .statusbar-entry > span,
.monaco-workbench > .part.statusbar > .statusbar-entry > a:not([disabled]) {
	padding: 0 5px 0 5px;
	white-space: pre; /* gives some degree of styling */
}

.monaco-workbench > .part.statusbar > .statusbar-entry span.octicon {
	text-align: center;
	font-size: 14px;
}

.monaco-workbench > .part.statusbar > .statusbar-item a:hover:not([disabled]) {
	background-color: rgba(255, 255, 255, 0.12);
	text-decoration: none;
	color: inherit;
}

.monaco-workbench > .part.statusbar > .statusbar-item a:active:not([disabled]) {
	background-color: rgba(255, 255, 255, 0.18);
}

/* High Contrast Black */

.monaco-workbench.hc-black > .part.statusbar {
	border-top: 1px solid #6FC3DF;
	background-color: #000;
}


text:
package org.springframework.social.google.api.plus.moments;

import org.springframework.social.google.api.query.ApiQueryBuilder;
import org.springframework.social.google.api.query.QueryBuilder;

/**
 * {@link QueryBuilder} for {@link Moment}.
 *
 * @author Gabriel Axel
 */
public interface MomentQueryBuilder extends
		ApiQueryBuilder<MomentQueryBuilder, MomentsPage> {

}


text:
using System.Text.RegularExpressions;

namespace SomeSharp.Nmdc
{
    public sealed class NmdcMyInfoCommand : NmdcCommand
    {
        #region Constants

        private const string CommandStart = "$MyINFO";

        private const string TagGroupName = "tag";
        private const string DescriptionGroupName = "desc";
        private static readonly string DescriptionGroup = $@"(?<{DescriptionGroupName}>.*)(\<(?<{TagGroupName}>.+)\>)?";

        private const string ConnectionGroupName = "conn";
        private const string MagicByteGroupName = "magb";
        private static readonly string ConnectionGroup = $@"(?<{ConnectionGroupName}>.+)(?<{MagicByteGroupName}>.)?";

        private const string SharedSizeGroupName = "ss";
        private static readonly string SharedSizeGroup = $@"(?<{SharedSizeGroupName}>\d+)";

        private const string EmailGroupName = "email";
        private static readonly string EmailGroup = $@"(?<{EmailGroupName}>.+)";

        private static readonly Regex ParseRegex = new Regex(
            $@"^{Regex.Escape(CommandStart)} \$ALL {NmdcCommandParser.NickGroup}( {DescriptionGroup}\$)? \${ConnectionGroup}?\${EmailGroup}?\${SharedSizeGroup}?\$",
            RegexOptions.Singleline);

        #endregion

        #region Constructors

        public NmdcMyInfoCommand(string nick, string description, string tag, string connection, byte magicByte, string email, long sharedSize)
        {
            Nick = nick;
            Description = description;
            Tag = tag;
            Connection = connection;
            MagicByte = magicByte;
            Email = email;
            SharedSize = sharedSize;
        }

        #endregion

        #region Properties

        public string Nick { get; private set; }

        public string Description { get; private set; }

        public string Tag { get; private set; }

        public string Connection { get; private set; }

        public byte MagicByte { get; private set; }

        public string Email { get; private set; }

        public long SharedSize { get; private set; }

        #endregion

        #region Overrides

        public override string ToString()
        {
            var tagPart = string.IsNullOrEmpty(Tag)
                ? string.Empty
                : $"<{Tag}>";

            return $"{CommandStart} $ALL {Nick ?? string.Empty} {Description ?? string.Empty}{tagPart}$ ${Connection ?? string.Empty}{(char)MagicByte}${Email ?? string.Empty}${SharedSize}$";
        }

        #endregion

        #region Methods

        public static NmdcMyInfoCommand Parse(string message)
        {
            if (string.IsNullOrWhiteSpace(message))
                return null;

            var match = ParseRegex.Match(message);
            if (match == null || !match.Success)
                return null;

            var groups = match.Groups;
            if (groups == null || groups.Count == 0)
                return null;

            // Nick

            var nick = groups[NmdcCommandParser.NickGroupName].Value;

            // Description

            var descriptionGroup = groups[DescriptionGroupName];
            var description = descriptionGroup.Success
                ? descriptionGroup.Value
                : string.Empty;

            // Tag

            var tagGroup = groups[TagGroupName];
            var tag = tagGroup.Success
                ? tagGroup.Value
                : string.Empty;

            // Connection

            var connectionGroup = groups[ConnectionGroupName];
            var connection = connectionGroup.Success
                ? connectionGroup.Value
                : string.Empty;

            // Magic byte

            var magicByteGroup = groups[MagicByteGroupName];
            var magicByte = magicByteGroup.Success
                ? (byte)magicByteGroup.Value[0]
                : (byte)0;

            // Email

            var emailGroup = groups[EmailGroupName];
            var email = emailGroup.Success
                ? emailGroup.Value
                : string.Empty;

            // Shared size

            long sharedSize = 0;
            var sharedSizeGroup = groups[SharedSizeGroupName];
            if (sharedSizeGroup.Success && !long.TryParse(sharedSizeGroup.Value, out sharedSize))
                sharedSize = 0;

            //

            return new NmdcMyInfoCommand(nick, description, tag, connection, magicByte, email, sharedSize);
        }

        #endregion
    }
}


text:
import { csgeo } from "Setup";
import { nada } from "expose";
import { CSNumber } from "libcs/CSNumber";
import { List } from "libcs/List";
import { General } from "libcs/General";
import { niceprint } from "libcs/Essentials";
import { setupTraceDrawing } from "libgeo/GeoBasics";
import { movepointscr } from "libgeo/Tracing";
import { geoOps } from "libgeo/GeoOps";

//*************************************************************
// and here are the accessors for properties and elements
//*************************************************************

var Accessor = {};

Accessor.generalFields = {
    // fieldname translation
    color: "color",
    colorhsb: "",
    size: "size",
    alpha: "alpha",
    fillcolor: "fillcolor",
    fillalpha: "fillalpha",
    isshowing: "isshowing",
    visible: "visible",
    name: "name",
    caption: "caption",
    trace: "",
    tracelength: "",
    selected: "",
    labeled: "labeled",
    labelled: "labeled",
};

Accessor.getGeoField = function (geoname, field) {
    if (typeof csgeo.csnames[geoname] !== "undefined") {
        return Accessor.getField(csgeo.csnames[geoname], field);
    }
    return nada;
};

Accessor.setGeoField = function (geoname, field, value) {
    if (typeof csgeo.csnames[geoname] !== "undefined") {
        return Accessor.setField(csgeo.csnames[geoname], field, value);
    }
    return nada;
};

Accessor.getField = function (geo, field) {
    var erg;
    if (geo.kind === "P") {
        if (field === "xy") {
            erg = List.dehom(geo.homog);
            return General.withUsage(erg, "Point");
        }

        if (field === "homog") {
            return General.withUsage(geo.homog, "Point");
        }

        if (field === "x") {
            return CSNumber.div(geo.homog.value[0], geo.homog.value[2]);
        }

        if (field === "y") {
            return CSNumber.div(geo.homog.value[1], geo.homog.value[2]);
        }
        if (field === "narrow") {
            return General.wrap(geo.narrow);
        }
    }
    if (geo.kind === "L" || geo.kind === "S") {
        if (field === "homog") {
            return General.withUsage(geo.homog, "Line");
        }
        if (field === "angle") {
            erg = List.eucangle(List.ey, geo.homog);
            return General.withUsage(erg, "Angle");
        }
        if (field === "slope") {
            return CSNumber.neg(CSNumber.div(geo.homog.value[0], geo.homog.value[1]));
        }
    }
    if (geo.kind === "Tr") {
        if (field === "matrix") {
            return geo.matrix;
        }
    }
    if (geo.kind === "C") {
        if (field === "radius") {
            //Assumes that we have a circle
            var s = geo.matrix;
            var ax = s.value[0].value[0];
            var az = s.value[0].value[2];
            var bz = s.value[1].value[2];
            var cz = s.value[2].value[2];

            var n = CSNumber.mult(ax, ax);
            var aa = CSNumber.div(az, ax);
            var bb = CSNumber.div(bz, ax);
            var cc = CSNumber.div(cz, ax);
            erg = CSNumber.sqrt(CSNumber.sub(CSNumber.add(CSNumber.mult(aa, aa), CSNumber.mult(bb, bb)), cc));

            return erg;
        }

        if (field === "size") {
            return geo.size;
        }

        if (field === "matrix") {
            return geo.matrix;
        }

        if (field === "center") {
            var cen = geoOps._helper.CenterOfConic(geo.matrix);
            cen = List.dehom(cen);
            return General.withUsage(cen, "Point");
        }

        if (field === "dualMatrix") {
            return List.normalizeMax(List.adjoint3(geo.matrix));
        }

        if (field === "narrow") {
            return General.wrap(geo.narrow);
        }
    }
    if (geo.kind === "Text") {
        if (field === "pressed") {
            if (geo.checkbox) {
                return General.bool(geo.checkbox.checked);
            } else {
                return General.bool(false);
            }
        }
        if (field === "xy") {
            erg = List.dehom(geo.homog);
            return General.withUsage(erg, "Point");
        }
        if (field === "homog") {
            return General.withUsage(geo.homog, "Point");
        }
        if (field === "x") {
            return CSNumber.div(geo.homog.value[0], geo.homog.value[2]);
        }
        if (field === "y") {
            return CSNumber.div(geo.homog.value[1], geo.homog.value[2]);
        }
    }
    if (field === "trace") {
        return General.bool(!!geo.drawtrace);
    }
    if (field === "pinned") {
        return General.bool(!!geo.pinned);
    }
    if (Accessor.generalFields[field]) {
        //must be defined as an actual string
        erg = geo[Accessor.generalFields[field]];
        if (erg && erg.ctype) {
            return erg;
        } else if (typeof erg !== "object") {
            return General.wrap(erg);
        } else {
            return nada;
        }
    }
    //Accessors for masses
    if (geo.behavior) {
        if (field === "mass" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.mass);
        }
        if (field === "radius" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.radius);
        }
        if (field === "charge" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.charge);
        }
        if (field === "friction" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.friction);
        }
        if (field === "vx" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.vx);
        }
        if (field === "vy" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.vy);
        }
        if (field === "v" && geo.behavior.type === "Mass") {
            return List.realVector([geo.behavior.vx, geo.behavior.vy]);
        }
        if (field === "fx" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.fx);
        }
        if (field === "fy" && geo.behavior.type === "Mass") {
            return CSNumber.real(geo.behavior.fy);
        }
        if (field === "f" && geo.behavior.type === "Mass") {
            return List.realVector([geo.behavior.fx, geo.behavior.fy]);
        }
        if (field === "ldiff" && geo.behavior.type === "Spring") {
            return CSNumber.real(geo.behavior.ldiff);
        }
    }
    var getter = geoOps[geo.type]["get_" + field];
    if (typeof getter === "function") {
        return getter(geo);
    }
    return nada;
};

Accessor.setField = function (geo, field, value) {
    var dir;

    if (field === "color" && List._helper.isNumberVecN(value, 3)) {
        geo.color = value;
    }
    if (field === "size" && value.ctype === "number") {
        geo.size = value;
    }
    if (field === "alpha" && value.ctype === "number") {
        geo.alpha = value;
    }
    if (field === "fillcolor" && List._helper.isNumberVecN(value, 3)) {
        geo.fillcolor = value;
    }
    if (field === "fillalpha" && value.ctype === "number") {
        geo.fillalpha = value;
    }
    if (field === "visible") {
        if (value.ctype === "boolean") {
            geo.visible = value.value;
        }
    }
    if (field === "pinned") {
        if (value.ctype === "boolean") {
            geo.pinned = value.value;
        }
    }
    if (field === "labeled" || field === "labelled") {
        if (value.ctype === "boolean") {
            geo.labeled = value.value;
        }
    }
    if (field === "printlabel") {
        geo.printname = niceprint(value);
    }
    if (field === "trace") {
        if (value.ctype === "boolean") {
            if (value.value && !geo.drawtrace) {
                geo.drawtrace = true;
                setupTraceDrawing(geo);
            } else {
                geo.drawtrace = value.value;
            }
        }
    }

    if (geo.kind === "P" && geo.movable) {
        if (field === "xy" && List._helper.isNumberVecN(value, 2)) {
            movepointscr(geo, List.turnIntoCSList([value.value[0], value.value[1], CSNumber.real(1)]), "homog");
        }

        if (field === "xy" && List._helper.isNumberVecN(value, 3)) {
            movepointscr(geo, value, "homog");
        }

        if (field === "x" && value.ctype === "number") {
            movepointscr(
                geo,
                List.turnIntoCSList([CSNumber.mult(value, geo.homog.value[2]), geo.homog.value[1], geo.homog.value[2]]),
                "homog"
            );
        }

        if (field === "y" && value.ctype === "number") {
            movepointscr(
                geo,
                List.turnIntoCSList([geo.homog.value[0], CSNumber.mult(value, geo.homog.value[2]), geo.homog.value[2]]),
                "homog"
            );
        }

        if (field === "homog" && List._helper.isNumberVecN(value, 3)) {
            movepointscr(geo, value, "homog");
        }
    }

    if (field === "homog" && geo.kind === "L" && geo.movable && List._helper.isNumberVecN(value, 3)) {
        movepointscr(geo, value, "homog");
    }

    if (geo.kind === "Text") {
        if (field === "pressed" && value.ctype === "boolean" && geo.checkbox) {
            geo.checkbox.checked = value.value;
        }
        if (geo.movable) {
            // Texts may move without tracing
            if (field === "xy") {
                if (List._helper.isNumberVecN(value, 2)) {
                    geo.homog = List.turnIntoCSList([value.value[0], value.value[1], CSNumber.real(1)]);
                } else if (List._helper.isNumberVecN(value, 3)) {
                    geo.homog = value;
                }
            } else if (field === "homog" && List._helper.isNumberVecN(value, 3)) {
                geo.homog = value;
            } else if (field === "x" && value.ctype === "number") {
                geo.homog = List.turnIntoCSList([
                    CSNumber.mult(value, geo.homog.value[2]),
                    geo.homog.value[1],
                    geo.homog.value[2],
                ]);
            } else if (field === "y" && value.ctype === "number") {
                geo.homog = List.turnIntoCSList([
                    geo.homog.value[0],
                    CSNumber.mult(value, geo.homog.value[2]),
                    geo.homog.value[2],
                ]);
            }
        }
    }
    if (geo.behavior) {
        if (field === "mass" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.mass = value.value.real;
        }
        if (field === "mass" && geo.behavior.type === "Sun" && value.ctype === "number") {
            geo.behavior.mass = value.value.real;
        }
        if (field === "friction" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.friction = value.value.real;
        }
        if (field === "charge" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.charge = value.value.real;
        }
        if (field === "radius" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.radius = value.value.real;
        }
        if (field === "vx" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.vx = value.value.real;
        }
        if (field === "vy" && geo.behavior.type === "Mass" && value.ctype === "number") {
            geo.behavior.vy = value.value.real;
        }
        if (field === "v" && geo.behavior.type === "Mass" && List._helper.isNumberVecN(value, 2)) {
            geo.behavior.vx = value.value[0].value.real;
            geo.behavior.vy = value.value[1].value.real;
        }
    }

    if (field === "narrow" && ["P", "C"].indexOf(geo.kind) !== -1) {
        if (value.ctype === "boolean") geo.narrow = value.value;
        if (value.ctype === "number" && CSNumber._helper.isAlmostReal(value)) geo.narrow = value.value.real;
    }

    var setter = geoOps[geo.type]["set_" + field];
    if (typeof setter === "function") {
        return setter(geo, value);
    }
};

Accessor.getuserData = function (obj, key) {
    var val;
    if (key.ctype === "string" && obj.userData && obj.userData[key.value]) val = obj.userData[key.value];

    if (val && val.ctype) {
        return val;
    } else if (typeof val !== "object") {
        return General.wrap(val);
    } else {
        return nada;
    }
};

Accessor.setuserData = function (obj, key, value) {
    if (!(key && key.ctype === "string" && obj && value)) {
        return;
    }
    if (!obj.userData) obj.userData = {};
    obj.userData[key.value] = value;
};

export { Accessor };


text:
package org.assertj.core.error;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldBeEqual.shouldBeEqual;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyVararg;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.assertj.core.description.Description;
import org.assertj.core.internal.Failures;
import org.assertj.core.internal.TestDescription;
import org.assertj.core.presentation.StandardRepresentation;
import org.junit.Before;
import org.junit.ComparisonFailure;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.quality.Strictness;
import org.opentest4j.AssertionFailedError;

/**
 * Tests for
 * <code>{@link ShouldBeEqual#newAssertionError(Description, org.assertj.core.presentation.Representation)}</code>.
 *
 * @author Filip Hrisafov
 */
public class ShouldBeEqual_newAssertionError_without_JUnit_and_OTA4J_Test {

  @Rule
  public final MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

  private Description description;
  private ShouldBeEqual factory;
  private ConstructorInvoker constructorInvoker;

  @Before
  public void setUp() {
    Failures.instance().setRemoveAssertJRelatedElementsFromStackTrace(false);
    description = new TestDescription("Jedi");
    factory = (ShouldBeEqual) shouldBeEqual("Luke", "Yoda", new StandardRepresentation());
    constructorInvoker = mock(ConstructorInvoker.class);
    factory.constructorInvoker = constructorInvoker;
  }

  @Test
  public void should_create_AssertionError_if_created_ComparisonFailure_and_AssertionFailedError_is_null()
    throws Exception {
    when(constructorInvoker.newInstance(any(String.class), any(Class[].class), any(Object[].class))).thenReturn(null);
    AssertionError error = factory.newAssertionError(description, new StandardRepresentation());
    check(error);
  }

  @Test
  public void should_create_AssertionError_if_error_is_thrown_when_creating_ComparisonFailure() throws Exception {
    when(constructorInvoker.newInstance(any(String.class), any(Class[].class), any(Object[].class)))
      .thenThrow(new AssertionError("Thrown on purpose"));
    AssertionError error = factory.newAssertionError(description, new StandardRepresentation());
    check(error);
  }

  private void check(AssertionError error) throws Exception {
    verify(constructorInvoker)
      .newInstance(ComparisonFailure.class.getName(), new Class<?>[] { String.class, String.class, String.class },
                   "[Jedi]", "\"Yoda\"", "\"Luke\"");
    verify(constructorInvoker)
      .newInstance(AssertionFailedError.class.getName(), new Class<?>[] { String.class, Object.class, Object.class },
                   String.format("[Jedi] %nExpecting:%n <\"Luke\">%nto be equal to:%n <\"Yoda\">%nbut was not."),
                   "Yoda", "Luke");
    assertThat(error).isNotInstanceOf(ComparisonFailure.class);
    assertThat(error).isNotInstanceOf(AssertionFailedError.class);
    assertThat(error.getMessage())
      .isEqualTo(String.format("[Jedi] %nExpecting:%n <\"Luke\">%nto be equal to:%n <\"Yoda\">%nbut was not."));
  }
}


text:
package mx.openpay.core.client.full;

import java.util.TimeZone;

import org.junit.Before;

import mx.openpay.client.core.OpenpayAPI;

/**
 * @author Eli Lopez, eli.lopez@opencard.mx
 */
public class BaseTest {

    protected OpenpayAPI api;

    @Before
    public void setupAPI() throws Exception {
        String merchantId = "mioppzc1kgz2cj21s8sp";
        String apiKey = "sk_fe7d3759f4514f4b8fe11cf0404812de";
        String endpoint = "https://dev-api.openpay.mx/";
        this.api = new OpenpayAPI(endpoint, apiKey, merchantId);
        TimeZone.setDefault(TimeZone.getTimeZone("Mexico/General"));
    }

}


text:
typedef struct _Termpty       Termpty;
typedef struct _Termcell      Termcell;
typedef struct _Termatt       Termatt;
typedef struct _Termstate     Termstate;
typedef struct _Termsave      Termsave;
typedef struct _Termsavecomp  Termsavecomp;
typedef struct _Termblock     Termblock;
typedef struct _Termexp       Termexp;

#define COL_DEF        0
#define COL_BLACK      1
#define COL_RED        2
#define COL_GREEN      3
#define COL_YELLOW     4
#define COL_BLUE       5
#define COL_MAGENTA    6
#define COL_CYAN       7
#define COL_WHITE      8
#define COL_INVIS      9

#define COL_INVERSE   10
#define COL_INVERSEBG 11

#define MOUSE_OFF              0
#define MOUSE_X10              1 // Press only
#define MOUSE_NORMAL           2 // Press+release only
#define MOUSE_NORMAL_BTN_MOVE  3 // Press+release+motion while pressed
#define MOUSE_NORMAL_ALL_MOVE  4 // Press+release+all motion

#define MOUSE_EXT_NONE         0
#define MOUSE_EXT_UTF8         1
#define MOUSE_EXT_SGR          2
#define MOUSE_EXT_URXVT        3

// choose - italic OR double-width support

//#define SUPPORT_ITALIC   1
#define SUPPORT_DBLWIDTH 1

// Only for testing purpose
//#define SUPPORT_80_132_COLUMNS 1

struct _Termatt
{
   unsigned char fg, bg;
   unsigned short bold : 1;
   unsigned short faint : 1;
#if defined(SUPPORT_ITALIC)
   unsigned short italic : 1;
#elif defined(SUPPORT_DBLWIDTH)
   unsigned short dblwidth : 1;
#else
   unsigned short bit_padding_0 : 1;
#endif
   unsigned short underline : 1;
   unsigned short blink : 1; // don't intend to support this currently
   unsigned short blink2 : 1; // don't intend to support this currently
   unsigned short inverse : 1;
   unsigned short invisible : 1;
   unsigned short strike : 1;
   unsigned short fg256 : 1;
   unsigned short bg256 : 1;
   unsigned short fgintense : 1;
   unsigned short bgintense : 1;
   // below used for working out text from selections
   unsigned short autowrapped : 1;
   unsigned short newline : 1;
   unsigned short tab : 1;
   unsigned short fraktur : 1;
#if defined(SUPPORT_80_132_COLUMNS)
   unsigned short is_80_132_mode_allowed : 1;
   unsigned short bit_padding : 14;
#else
   unsigned short bit_padding : 15;
#endif
};

struct _Termstate
{
   int           cx, cy;
   Termatt       att;
   unsigned char charset;
   unsigned char charsetch;
   unsigned char chset[4];
   int           scroll_y1, scroll_y2;
   int           had_cr_x, had_cr_y;
   int           margin_top; // soon, more to come...
   unsigned int  multibyte : 1;
   unsigned int  alt_kp : 1;
   unsigned int  insert : 1;
   unsigned int  appcursor : 1;
   unsigned int  wrap : 1;
   unsigned int  wrapnext : 1;
   unsigned int  hidecursor : 1;
   unsigned int  crlf : 1;
   unsigned int  had_cr : 1;
   unsigned int  send_bs : 1;
   unsigned int  kbd_lock : 1;
   unsigned int  reverse : 1;
   unsigned int  no_autorepeat : 1;
   unsigned int  cjk_ambiguous_wide : 1;
};

struct _Termpty
{
   Evas_Object *obj;
   Ecore_Event_Handler *hand_exe_exit;
   Ecore_Fd_Handler *hand_fd;
   struct {
      struct {
         void (*func) (void *data);
         void *data;
      } change, set_title, set_icon, cancel_sel, exited, bell, command;
   } cb;
   struct {
      const char *title, *icon;
   } prop;
   const char *cur_cmd;
   Termcell *screen, *screen2;
   Termsave **back;
   unsigned char oldbuf[4];
   int *buf;
   int buflen;
   int w, h;
   int fd, slavefd;
   int circular_offset;
   int circular_offset2;
   int backmax, backpos;
   int backscroll_num;
   struct {
      int curid;
      Eina_Hash *blocks;
      Eina_Hash *chid_map;
      Eina_List *active;
      Eina_List *expecting;
      unsigned char on : 1;
   } block;
   struct {
      struct {
         int x, y;
      } start, end, start_backup, end_backup;
      unsigned char is_active : 1;
      unsigned char is_box    : 1;
      unsigned char makesel   : 1;
   } selection;
   Termstate state, save, swap;
   int exit_code;
   pid_t pid;
   unsigned int altbuf     : 1;
   unsigned int mouse_mode : 3;
   unsigned int mouse_ext  : 2;
   unsigned int bracketed_paste : 1;
};

struct _Termcell
{
   Eina_Unicode   codepoint;
   Termatt        att;
   unsigned char padding[2];
};

struct _Termsave
{
   unsigned int   gen  : 8;
   unsigned int   comp : 1;
   unsigned int   z    : 1;
   unsigned int   w    : 22;
   Termcell       cell[1];
};

struct _Termsavecomp
{
   unsigned int   gen  : 8;
   unsigned int   comp : 1;
   unsigned int   z    : 1;
   unsigned int   w    : 22; // compressed size in bytes
   unsigned int   wout; // output width in Termcells
};

struct _Termblock
{
   Termpty     *pty;
   const char  *path, *link, *chid;
   Evas_Object *obj;
   Eina_List   *cmds;
   int          id;
   int          type;
   int          refs;
   short        w, h;
   short        x, y;
   unsigned char scale_stretch : 1;
   unsigned char scale_center : 1;
   unsigned char scale_fill : 1;
   unsigned char thumb : 1;
   unsigned char edje : 1;

   unsigned char active : 1;
   unsigned char was_active : 1;
   unsigned char was_active_before : 1;

   unsigned char mov_paused : 1;  // movie paused state marker
};

struct _Termexp
{
   int ch, left, id;
   int x, y, w, h;
};

void       termpty_init(void);
void       termpty_shutdown(void);

Termpty   *termpty_new(const char *cmd, Eina_Bool login_shell, const char *cd,
                      int w, int h, int backscroll, Eina_Bool xterm_256color,
                      Eina_Bool erase_is_del, const char *emotion_mod);
void       termpty_free(Termpty *ty);
void       termpty_cellcomp_freeze(Termpty *ty);
void       termpty_cellcomp_thaw(Termpty *ty);
Termcell  *termpty_cellrow_get(Termpty *ty, int y, int *wret);
void       termpty_write(Termpty *ty, const char *input, int len);
void       termpty_resize(Termpty *ty, int w, int h);
void       termpty_backscroll_set(Termpty *ty, int size);

pid_t      termpty_pid_get(const Termpty *ty);
void       termpty_block_free(Termblock *tb);
Termblock *termpty_block_new(Termpty *ty, int w, int h, const char *path, const char *link);
void       termpty_block_insert(Termpty *ty, int ch, Termblock *blk);
int        termpty_block_id_get(Termcell *cell, int *x, int *y);
Termblock *termpty_block_get(Termpty *ty, int id);
void       termpty_block_chid_update(Termpty *ty, Termblock *blk);
Termblock *termpty_block_chid_get(Termpty *ty, const char *chid);

void       termpty_cell_copy(Termpty *ty, Termcell *src, Termcell *dst, int n);
void       termpty_cell_fill(Termpty *ty, Termcell *src, Termcell *dst, int n);
void       termpty_cell_codepoint_att_fill(Termpty *ty, Eina_Unicode codepoint, Termatt att, Termcell *dst, int n);
void       termpty_screen_swap(Termpty *ty);

ssize_t termpty_line_length(const Termcell *cells, ssize_t nb_cells);

Config *termpty_config_get(const Termpty *ty);

extern int _termpty_log_dom;

#define TERMPTY_SCREEN(Tpty, X, Y) \
  Tpty->screen[X + (((Y + Tpty->circular_offset) % Tpty->h) * Tpty->w)]
#define TERMPTY_FMTCLR(Tatt) \
   (Tatt).autowrapped = (Tatt).newline = (Tatt).tab = 0

#endif


text:
package java8professional.chapter08.userinteractions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class OldWayInputtingUserData {

    static final String EXIT_KEYWORD = "exit";

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in), 1024);
        System.out.println("End app writing '" + EXIT_KEYWORD + "'");
        System.out.print("Now, write: ");
        String input;
        while(!(input = in.readLine()).equalsIgnoreCase(EXIT_KEYWORD)) {
            System.out.println(String.format("Your input: '%s'", input));
            System.out.print("And again: ");
        }
    }

}