text:
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _SOC_UART_STRUCT_H_
#define _SOC_UART_STRUCT_H_

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef volatile struct uart_dev_s {
    union {
        struct {
            uint8_t rw_byte;                 /*This register stores one byte data  read by rx fifo.*/
            uint8_t reserved[3];
        };
        uint32_t val;
    } fifo;
    union {
        struct {
            uint32_t rxfifo_full:      1;           /*This interrupt raw bit turns to high level when receiver receives more data than (rx_flow_thrhd_h3 rx_flow_thrhd).*/
            uint32_t txfifo_empty:     1;           /*This interrupt raw bit turns to high level when the amount of data in transmitter's fifo is less than ((tx_mem_cnttxfifo_cnt) .*/
            uint32_t parity_err:       1;           /*This interrupt raw bit turns to high level when receiver detects the parity error of data.*/
            uint32_t frm_err:          1;           /*This interrupt raw bit turns to high level when receiver detects data's frame error .*/
            uint32_t rxfifo_ovf:       1;           /*This interrupt raw bit turns to high level when receiver receives more data than the fifo can store.*/
            uint32_t dsr_chg:          1;           /*This interrupt raw bit turns to high level when receiver detects the edge change of dsrn signal.*/
            uint32_t cts_chg:          1;           /*This interrupt raw bit turns to high level when receiver detects the edge change of ctsn signal.*/
            uint32_t brk_det:          1;           /*This interrupt raw bit turns to high level when receiver detects the 0 after the stop bit.*/
            uint32_t rxfifo_tout:      1;           /*This interrupt raw bit turns to high level when receiver takes more time than rx_tout_thrhd to receive a byte.*/
            uint32_t sw_xon:           1;           /*This interrupt raw bit turns to high level when receiver receives xoff char with uart_sw_flow_con_en is set to 1.*/
            uint32_t sw_xoff:          1;           /*This interrupt raw bit turns to high level when receiver receives xon char with uart_sw_flow_con_en is set to 1.*/
            uint32_t glitch_det:       1;           /*This interrupt raw bit turns to high level when receiver detects the start bit.*/
            uint32_t tx_brk_done:      1;           /*This interrupt raw bit turns to high level when transmitter completes  sending  0 after all the data in transmitter's fifo are send.*/
            uint32_t tx_brk_idle_done: 1;           /*This interrupt raw bit turns to high level when transmitter has kept the shortest duration after the  last data has been send.*/
            uint32_t tx_done:          1;           /*This interrupt raw bit turns to high level when transmitter has send all the data in fifo.*/
            uint32_t rs485_parity_err: 1;           /*This interrupt raw bit turns to high level when rs485 detects the parity error.*/
            uint32_t rs485_frm_err:    1;           /*This interrupt raw bit turns to high level when rs485 detects the data frame error.*/
            uint32_t rs485_clash:      1;           /*This interrupt raw bit turns to high level when rs485 detects the clash between transmitter and receiver.*/
            uint32_t at_cmd_char_det:  1;           /*This interrupt raw bit turns to high level when receiver detects the configured at_cmd chars.*/
            uint32_t reserved19:      13;
        };
        uint32_t val;
    } int_raw;
    union {
        struct {
            uint32_t rxfifo_full:      1;            /*This is the status bit for rxfifo_full_int_raw when rxfifo_full_int_ena is set to 1.*/
            uint32_t txfifo_empty:     1;            /*This is the status bit for  txfifo_empty_int_raw  when txfifo_empty_int_ena is set to 1.*/
            uint32_t parity_err:       1;            /*This is the status bit for parity_err_int_raw when parity_err_int_ena is set to 1.*/
            uint32_t frm_err:          1;            /*This is the status bit for frm_err_int_raw when fm_err_int_ena is set to 1.*/
            uint32_t rxfifo_ovf:       1;            /*This is the status bit for rxfifo_ovf_int_raw when rxfifo_ovf_int_ena is set to 1.*/
            uint32_t dsr_chg:          1;            /*This is the status bit for dsr_chg_int_raw when dsr_chg_int_ena is set to 1.*/
            uint32_t cts_chg:          1;            /*This is the status bit for cts_chg_int_raw when cts_chg_int_ena is set to 1.*/
            uint32_t brk_det:          1;            /*This is the status bit for brk_det_int_raw when brk_det_int_ena is set to 1.*/
            uint32_t rxfifo_tout:      1;            /*This is the status bit for rxfifo_tout_int_raw when rxfifo_tout_int_ena is set to 1.*/
            uint32_t sw_xon:           1;            /*This is the status bit for sw_xon_int_raw when sw_xon_int_ena is set to 1.*/
            uint32_t sw_xoff:          1;            /*This is the status bit for sw_xoff_int_raw when sw_xoff_int_ena is set to 1.*/
            uint32_t glitch_det:       1;            /*This is the status bit for glitch_det_int_raw when glitch_det_int_ena is set to 1.*/
            uint32_t tx_brk_done:      1;            /*This is the status bit for tx_brk_done_int_raw when tx_brk_done_int_ena is set to 1.*/
            uint32_t tx_brk_idle_done: 1;            /*This is the status bit for tx_brk_idle_done_int_raw when tx_brk_idle_done_int_ena is set to 1.*/
            uint32_t tx_done:          1;            /*This is the status bit for tx_done_int_raw when tx_done_int_ena is set to 1.*/
            uint32_t rs485_parity_err: 1;            /*This is the status bit for rs485_parity_err_int_raw when rs485_parity_int_ena is set to 1.*/
            uint32_t rs485_frm_err:    1;            /*This is the status bit for rs485_fm_err_int_raw when rs485_fm_err_int_ena is set to 1.*/
            uint32_t rs485_clash:      1;            /*This is the status bit for rs485_clash_int_raw when rs485_clash_int_ena is set to 1.*/
            uint32_t at_cmd_char_det:  1;            /*This is the status bit for at_cmd_det_int_raw when at_cmd_char_det_int_ena is set to 1.*/
            uint32_t reserved19:      13;
        };
        uint32_t val;
    } int_st;
    union {
        struct {
            uint32_t rxfifo_full:      1;           /*This is the enable bit for rxfifo_full_int_st register.*/
            uint32_t txfifo_empty:     1;           /*This is the enable bit for rxfifo_full_int_st register.*/
            uint32_t parity_err:       1;           /*This is the enable bit for parity_err_int_st register.*/
            uint32_t frm_err:          1;           /*This is the enable bit for frm_err_int_st register.*/
            uint32_t rxfifo_ovf:       1;           /*This is the enable bit for rxfifo_ovf_int_st register.*/
            uint32_t dsr_chg:          1;           /*This is the enable bit for dsr_chg_int_st register.*/
            uint32_t cts_chg:          1;           /*This is the enable bit for cts_chg_int_st register.*/
            uint32_t brk_det:          1;           /*This is the enable bit for brk_det_int_st register.*/
            uint32_t rxfifo_tout:      1;           /*This is the enable bit for rxfifo_tout_int_st register.*/
            uint32_t sw_xon:           1;           /*This is the enable bit for sw_xon_int_st register.*/
            uint32_t sw_xoff:          1;           /*This is the enable bit for sw_xoff_int_st register.*/
            uint32_t glitch_det:       1;           /*This is the enable bit for glitch_det_int_st register.*/
            uint32_t tx_brk_done:      1;           /*This is the enable bit for tx_brk_done_int_st register.*/
            uint32_t tx_brk_idle_done: 1;           /*This is the enable bit for tx_brk_idle_done_int_st register.*/
            uint32_t tx_done:          1;           /*This is the enable bit for tx_done_int_st register.*/
            uint32_t rs485_parity_err: 1;           /*This is the enable bit for rs485_parity_err_int_st register.*/
            uint32_t rs485_frm_err:    1;           /*This is the enable bit for rs485_parity_err_int_st register.*/
            uint32_t rs485_clash:      1;           /*This is the enable bit for rs485_clash_int_st register.*/
            uint32_t at_cmd_char_det:  1;           /*This is the enable bit for at_cmd_char_det_int_st register.*/
            uint32_t reserved19:      13;
        };
        uint32_t val;
    } int_ena;
    union {
        struct {
            uint32_t rxfifo_full:      1;           /*Set this bit to clear the rxfifo_full_int_raw interrupt.*/
            uint32_t txfifo_empty:     1;           /*Set this bit to clear txfifo_empty_int_raw interrupt.*/
            uint32_t parity_err:       1;           /*Set this bit to clear parity_err_int_raw interrupt.*/
            uint32_t frm_err:          1;           /*Set this bit to clear frm_err_int_raw interrupt.*/
            uint32_t rxfifo_ovf:       1;           /*Set this bit to clear rxfifo_ovf_int_raw interrupt.*/
            uint32_t dsr_chg:          1;           /*Set this bit to clear the dsr_chg_int_raw interrupt.*/
            uint32_t cts_chg:          1;           /*Set this bit to clear the cts_chg_int_raw interrupt.*/
            uint32_t brk_det:          1;           /*Set this bit to clear the brk_det_int_raw interrupt.*/
            uint32_t rxfifo_tout:      1;           /*Set this bit to clear the rxfifo_tout_int_raw interrupt.*/
            uint32_t sw_xon:           1;           /*Set this bit to clear the sw_xon_int_raw interrupt.*/
            uint32_t sw_xoff:          1;           /*Set this bit to clear the sw_xon_int_raw interrupt.*/
            uint32_t glitch_det:       1;           /*Set this bit to clear the glitch_det_int_raw interrupt.*/
            uint32_t tx_brk_done:      1;           /*Set this bit to clear the tx_brk_done_int_raw interrupt..*/
            uint32_t tx_brk_idle_done: 1;           /*Set this bit to clear the tx_brk_idle_done_int_raw interrupt.*/
            uint32_t tx_done:          1;           /*Set this bit to clear the tx_done_int_raw interrupt.*/
            uint32_t rs485_parity_err: 1;           /*Set this bit to clear the rs485_parity_err_int_raw interrupt.*/
            uint32_t rs485_frm_err:    1;           /*Set this bit to clear the rs485_frm_err_int_raw interrupt.*/
            uint32_t rs485_clash:      1;           /*Set this bit to clear the rs485_clash_int_raw interrupt.*/
            uint32_t at_cmd_char_det:  1;           /*Set this bit to clear the at_cmd_char_det_int_raw interrupt.*/
            uint32_t reserved19:      13;
        };
        uint32_t val;
    } int_clr;
    union {
        struct {
            uint32_t div_int:    20;                /*The register value is  the  integer part of the frequency divider's factor.*/
            uint32_t div_frag:    4;                /*The register  value is the decimal part of the frequency divider's factor.*/
            uint32_t reserved24:  8;
        };
        uint32_t val;
    } clk_div;
    union {
        struct {
            uint32_t en: 1;                         /*This is the enable bit for detecting baudrate.*/
            uint32_t reserved1:   7;
            uint32_t glitch_filt: 8;                /*when input pulse width is lower then this value ignore this pulse.this register is used in auto-baud detect process.*/
            uint32_t reserved16: 16;
        };
        uint32_t val;
    } auto_baud;
    union {
        struct {
            uint32_t rxfifo_cnt: 8;                 /*(rx_mem_cnt rxfifo_cnt) stores the byte number of valid data in receiver's fifo. rx_mem_cnt register stores the 3 most significant bits  rxfifo_cnt stores the 8 least significant bits.*/
            uint32_t st_urx_out: 4;                 /*This register stores the value of receiver's finite state machine. 0:RX_IDLE  1:RX_STRT  2:RX_DAT0  3:RX_DAT1  4:RX_DAT2  5:RX_DAT3  6:RX_DAT4  7:RX_DAT5  8:RX_DAT6  9:RX_DAT7   10:RX_PRTY   11:RX_STP1  12:RX_STP2 13:RX_DL1*/
            uint32_t reserved12: 1;
            uint32_t dsrn:       1;                 /*This register stores the level value of the internal uart dsr signal.*/
            uint32_t ctsn:       1;                 /*This register stores the level value of the internal uart cts signal.*/
            uint32_t rxd:        1;                 /*This register stores the level value of the internal uart rxd signal.*/
            uint32_t txfifo_cnt: 8;                 /*(tx_mem_cnt txfifo_cnt) stores the byte number of valid data in transmitter's fifo.tx_mem_cnt stores the 3 most significant bits  txfifo_cnt stores the 8 least significant bits.*/
            uint32_t st_utx_out: 4;                 /*This register stores the value of transmitter's finite state machine. 0:TX_IDLE  1:TX_STRT  2:TX_DAT0  3:TX_DAT1  4:TX_DAT2   5:TX_DAT3 6:TX_DAT4  7:TX_DAT5  8:TX_DAT6 9:TX_DAT7  10:TX_PRTY   11:TX_STP1  12:TX_STP2  13:TX_DL0   14:TX_DL1*/
            uint32_t reserved28: 1;
            uint32_t dtrn:       1;                 /*The register represent the level value of the internal uart dsr signal.*/
            uint32_t rtsn:       1;                 /*This register represent the level value of the internal uart cts signal.*/
            uint32_t txd:        1;                 /*This register represent the  level value of the internal uart rxd signal.*/
        };
        uint32_t val;
    } status;
    union {
        struct {
            uint32_t parity:             1;         /*This register is used to configure the parity check mode.  0:even 1:odd*/
            uint32_t parity_en:          1;         /*Set this bit to enable uart parity check.*/
            uint32_t bit_num:            2;         /*This register is used to set the length of data:  0:5bits 1:6bits 2:7bits 3:8bits*/
            uint32_t stop_bit_num:       2;         /*This register is used to set the length of  stop bit. 1:1bit  2:1.5bits  3:2bits*/
            uint32_t sw_rts:             1;         /*This register is used to configure the software rts signal which is used in software flow control.*/
            uint32_t sw_dtr:             1;         /*This register is used to configure the software dtr signal which is used in software flow control..*/
            uint32_t txd_brk:            1;         /*Set this bit to enable transmitter to  send 0 when the process of sending data is done.*/
            uint32_t irda_dplx:          1;         /*Set this bit to enable irda loop-back mode.*/
            uint32_t irda_tx_en:         1;         /*This is the start enable bit for irda transmitter.*/
            uint32_t irda_wctl:          1;         /*1:the irda transmitter's 11th bit is the same to the 10th bit. 0:set irda transmitter's 11th bit to 0.*/
            uint32_t irda_tx_inv:        1;         /*Set this bit to inverse the level value of  irda transmitter's level.*/
            uint32_t irda_rx_inv:        1;         /*Set this bit to inverse the level value of irda receiver's level.*/
            uint32_t loopback:           1;         /*Set this bit to enable uart loop-back test mode.*/
            uint32_t tx_flow_en:         1;         /*Set this bit to enable transmitter's flow control function.*/
            uint32_t irda_en:            1;         /*Set this bit to enable irda protocol.*/
            uint32_t rxfifo_rst:         1;         /*Set this bit to reset uart receiver's fifo.*/
            uint32_t txfifo_rst:         1;         /*Set this bit to reset uart transmitter's fifo.*/
            uint32_t rxd_inv:            1;         /*Set this bit to inverse the level value of uart rxd signal.*/
            uint32_t cts_inv:            1;         /*Set this bit to inverse the level value of uart cts signal.*/
            uint32_t dsr_inv:            1;         /*Set this bit to inverse the level value of uart dsr signal.*/
            uint32_t txd_inv:            1;         /*Set this bit to inverse the level value of uart txd signal.*/
            uint32_t rts_inv:            1;         /*Set this bit to inverse the level value of uart rts signal.*/
            uint32_t dtr_inv:            1;         /*Set this bit to inverse the level value of uart dtr signal.*/
            uint32_t clk_en:             1;         /*1:force clock on for registers:support clock only when write registers*/
            uint32_t err_wr_mask:        1;         /*1:receiver stops storing data int fifo when data is wrong. 0:receiver stores the data even if the  received data is wrong.*/
            uint32_t tick_ref_always_on: 1;         /*This register is used to select the clock.1:apb clock:ref_tick*/
            uint32_t reserved28:         4;
        };
        uint32_t val;
    } conf0;
    union {
        struct {
            uint32_t rxfifo_full_thrhd:  7;         /*When receiver receives more data than its threshold value,receiver will produce rxfifo_full_int_raw interrupt.the threshold value is (rx_flow_thrhd_h3 rxfifo_full_thrhd).*/
            uint32_t reserved7:          1;
            uint32_t txfifo_empty_thrhd: 7;         /*when the data amount in transmitter fifo is less than its threshold value, it will produce txfifo_empty_int_raw interrupt. the threshold value is (tx_mem_empty_thrhd txfifo_empty_thrhd)*/
            uint32_t reserved15:         1;
            uint32_t rx_flow_thrhd:      7;         /*when receiver receives more data than its threshold value, receiver produce signal to tell the transmitter stop transferring data. the threshold value is (rx_flow_thrhd_h3 rx_flow_thrhd).*/
            uint32_t rx_flow_en:         1;         /*This is the flow enable bit for uart receiver. 1:choose software flow control with configuring sw_rts signal*/
            uint32_t rx_tout_thrhd:      7;         /*This register is used to configure the timeout value for uart receiver receiving a byte.*/
            uint32_t rx_tout_en:         1;         /*This is the enable bit for uart receiver's timeout function.*/
        };
        uint32_t val;
    } conf1;
    union {
        struct {
            uint32_t min_cnt:     20;               /*This register stores the value of the minimum duration time for the low level pulse, it is used in baudrate-detect process.*/
            uint32_t reserved20:  12;
        };
        uint32_t val;
    } lowpulse;
    union {
        struct {
            uint32_t min_cnt:     20;               /*This register stores  the value of the maximum duration time for the high level pulse, it is used in baudrate-detect process.*/
            uint32_t reserved20:  12;
        };
        uint32_t val;
    } highpulse;
    union {
        struct {
            uint32_t edge_cnt:    10;               /*This register stores the count of rxd edge change, it is used in baudrate-detect process.*/
            uint32_t reserved10:  22;
        };
        uint32_t val;
    } rxd_cnt;
    union {
        struct {
            uint32_t sw_flow_con_en: 1;             /*Set this bit to enable software  flow control. it is used with register sw_xon or sw_xoff .*/
            uint32_t xonoff_del:     1;             /*Set this bit to remove flow control char from the received data.*/
            uint32_t force_xon:      1;             /*Set this bit to clear ctsn to stop the  transmitter from sending data.*/
            uint32_t force_xoff:     1;             /*Set this bit to set ctsn to enable the transmitter to go on sending data.*/
            uint32_t send_xon:       1;             /*Set this bit to send xon char, it is cleared by hardware automatically.*/
            uint32_t send_xoff:      1;             /*Set this bit to send xoff char, it is cleared by hardware automatically.*/
            uint32_t reserved6:     26;
        };
        uint32_t val;
    } flow_conf;
    union {
        struct {
            uint32_t active_threshold:10;           /*When the input rxd edge changes more than this register value, the uart is active from light sleeping mode.*/
            uint32_t reserved10:      22;
        };
        uint32_t val;
    } sleep_conf;
    union {
        struct {
            uint32_t xon_threshold:  8;             /*when the data amount in receiver's fifo is more than this register value, it will send a xoff char with uart_sw_flow_con_en set to 1.*/
            uint32_t xoff_threshold: 8;             /*When the data amount in receiver's fifo is less than this register value, it will send a xon char with uart_sw_flow_con_en set to 1.*/
            uint32_t xon_char:       8;             /*This register stores the xon flow control char.*/
            uint32_t xoff_char:      8;             /*This register stores the xoff flow control char.*/
        };
        uint32_t val;
    } swfc_conf;
    union {
        struct {
            uint32_t rx_idle_thrhd:10;              /*when receiver takes more time than this register value to receive a byte data, it will produce frame end signal for uhci to stop receiving data.*/
            uint32_t tx_idle_num:  10;              /*This register is used to configure the duration time between transfers.*/
            uint32_t tx_brk_num:    8;              /*This register is used to configure the number of 0 send after the process of sending data is done. it is active when txd_brk is set to 1.*/
            uint32_t reserved28:    4;
        };
        uint32_t val;
    } idle_conf;
    union {
        struct {
            uint32_t en:               1;           /*Set this bit to choose rs485 mode.*/
            uint32_t dl0_en:           1;           /*Set this bit to delay the stop bit by 1 bit.*/
            uint32_t dl1_en:           1;           /*Set this bit to delay the stop bit by 1 bit.*/
            uint32_t tx_rx_en:         1;           /*Set this bit to enable loop-back transmitter's output data signal to receiver's input data signal.*/
            uint32_t rx_busy_tx_en:    1;           /*1: enable rs485's transmitter to send data when rs485's receiver is busy. 0:rs485's transmitter should not send data when its receiver is busy.*/
            uint32_t rx_dly_num:       1;           /*This register is used to delay the receiver's internal data signal.*/
            uint32_t tx_dly_num:       4;           /*This register is used to delay the transmitter's internal data signal.*/
            uint32_t reserved10:      22;
        };
        uint32_t val;
    } rs485_conf;
    union {
        struct {
            uint32_t pre_idle_num:24;               /*This register is used to configure the idle duration time before the first at_cmd is received by receiver, when the the duration is less than this register value it will not take the next data received as at_cmd char.*/
            uint32_t reserved24:   8;
        };
        uint32_t val;
    } at_cmd_precnt;
    union {
        struct {
            uint32_t post_idle_num:24;              /*This register is used to configure the duration time between the last at_cmd and the next data, when the duration is less than this register value  it will not take the previous data as at_cmd char.*/
            uint32_t reserved24:    8;
        };
        uint32_t val;
    } at_cmd_postcnt;
    union {
        struct {
            uint32_t rx_gap_tout:24;                /*This register is used to configure the duration time between the at_cmd chars, when the duration time is less than this register value it will not take the data as continous at_cmd chars.*/
            uint32_t reserved24:  8;
        };
        uint32_t val;
    } at_cmd_gaptout;
    union {
        struct {
            uint32_t data:        8;                /*This register is used to configure the content of at_cmd char.*/
            uint32_t char_num:    8;                /*This register is used to configure the number of continuous at_cmd chars received by receiver.*/
            uint32_t reserved16: 16;
        };
        uint32_t val;
    } at_cmd_char;
    union {
        struct {
            uint32_t mem_pd:             1;         /*Set this bit to power down memory,when reg_mem_pd registers in the 3 uarts are all set to 1  memory will enter low power mode.*/
            uint32_t reserved1:          1;
            uint32_t reserved2:          1;
            uint32_t rx_size:            4;         /*This register is used to configure the amount of mem allocated to receiver's fifo. the default byte num is 128.*/
            uint32_t tx_size:            4;         /*This register is used to configure the amount of mem allocated to transmitter's fifo.the default byte num is 128.*/
            uint32_t reserved11:         4;
            uint32_t rx_flow_thrhd_h3:   3;         /*refer to the rx_flow_thrhd's description.*/
            uint32_t rx_tout_thrhd_h3:   3;         /*refer to the rx_tout_thrhd's description.*/
            uint32_t xon_threshold_h2:   2;         /*refer to the uart_xon_threshold's description.*/
            uint32_t xoff_threshold_h2:  2;         /*refer to the uart_xoff_threshold's description.*/
            uint32_t rx_mem_full_thrhd:  3;         /*refer to the rxfifo_full_thrhd's description.*/
            uint32_t tx_mem_empty_thrhd: 3;         /*refer to txfifo_empty_thrhd 's description.*/
            uint32_t reserved31:         1;
        };
        uint32_t val;
    } mem_conf;
    union {
        struct {
            uint32_t status:24;
            uint32_t reserved24:    8;
        };
        uint32_t val;
    } mem_tx_status;
    union {
        struct {
            uint32_t status:      24;
            uint32_t reserved24:   8;
        };
        struct {
            uint32_t reserved0:     2;
            uint32_t rd_addr:      11;              /*This register stores the rx mem read address.*/
            uint32_t wr_addr:      11;              /*This register stores the rx mem write address.*/
            uint32_t reserved:      8;
        };
        uint32_t val;
    } mem_rx_status;
    union {
        struct {
            uint32_t rx_cnt: 3;                      /*refer to the rxfifo_cnt's description.*/
            uint32_t tx_cnt: 3;                      /*refer to the txfifo_cnt's description.*/
            uint32_t reserved6: 26;
        };
        uint32_t val;
    } mem_cnt_status;
    union {
        struct {
            uint32_t min_cnt:     20;                 /*This register stores the count of rxd pos-edge edge, it is used in baudrate-detect process.*/
            uint32_t reserved20:  12;
        };
        uint32_t val;
    } pospulse;
    union {
        struct {
            uint32_t min_cnt:     20;                 /*This register stores the count of rxd neg-edge edge, it is used in baudrate-detect process.*/
            uint32_t reserved20:  12;
        };
        uint32_t val;
    } negpulse;
    uint32_t reserved_70;
    uint32_t reserved_74;
    uint32_t date;                                    /**/
    uint32_t id;                                      /**/
} uart_dev_t;
extern uart_dev_t UART0;
extern uart_dev_t UART1;
extern uart_dev_t UART2;

#ifdef __cplusplus
}
#endif

#endif  /* _SOC_UART_STRUCT_H_ */


text:
import { IteratorClass } from '../iterator'
import { IterableClass, isIterable } from '../iterable'
import { RecursiveOrElement, Recursive } from './recursiveType'
import { $$iterator } from '../symbol'

export class ConcatMapIterator<T, I, R> extends IteratorClass<R> {
  protected i = 0
  protected iterators: Iterator<RecursiveOrElement<I>>[] = []
  protected outerValue: T | undefined
  protected it: Iterator<T>
  protected resFn?: (outerValue: T, innerValue: I) => R
  protected recursive: boolean

  constructor(it: { [Symbol.iterator](): Iterator<T> }, fn: (value: T, index?: number) => Recursive<R>, recursive?: boolean)
  constructor(it: { [Symbol.iterator](): Iterator<T> }, fn: (value: T, index?: number) => Recursive<I>, resFn: (outerValue: T, innerValue: I) => R, recursive?: boolean)

  constructor(it: { [Symbol.iterator](): Iterator<T> }, protected fn: (value: T, index?: number) => Recursive<I>, resFn?: ((outerValue: T, innerValue: I) => R) | boolean, recursive?: boolean) {
    super()
    this.it = it[$$iterator]()
    if (resFn !== undefined) {
      if (typeof resFn === 'boolean') {
        this.recursive = resFn
      } else {
        this.resFn = resFn
      }
    }
    if (recursive !== undefined) {
      this.recursive = recursive
    }
    if (this.recursive === undefined) {
      this.recursive = true
    }
  }

  next() {
    const self = this
    function recurse(): IteratorResult<R> {
      if (self.iterators.length === 0) {
        const next = self.it.next()

        if (next.done) {
          return self.settleReturn()
        } else {
          self.iterators.push(self.fn(next.value, self.i++)[$$iterator]())
          return recurse()
        }
      } else {
        const lastR = self.iterators[self.iterators.length - 1]
        const next = lastR.next()

        if (next.done) {
          self.iterators.pop()
          return recurse()
        } else {
          const _value = next.value
          if (self.recursive && isIterable(_value)) {
            self.iterators.push(_value[$$iterator]())
            return recurse()
          } else {
            const value = self.resFn ? self.resFn(<T>self.outerValue, <I>_value) : <R><any>_value
            return self.settleNext(value)
          }
        }
      }
    }
    return recurse()
  }
}

export class ConcatMapIterable<T, I, R> extends IterableClass<R> {
  constructor(source: { [Symbol.iterator](): Iterator<T> }, fn: (value: T, index?: number) => Recursive<I>, resFn: (outerValue: T, innerValue: I) => R)
  constructor(source: { [Symbol.iterator](): Iterator<T> }, fn: (value: T, index?: number) => Recursive<R>)

  constructor(source: { [Symbol.iterator](): Iterator<T> }, fn: (value: T, index?: number) => Recursive<I>, resFn?: (outerValue: T, innerValue: I) => R) {
    super(new ConcatMapIterator(source, fn, <(outerValue: T, innerValue: I) => R>resFn))
  }
}

export function concatMap<T, R>(fn: (value: T, index?: number) => Recursive<R>): ConcatMapIterable<T, R, R>
export function concatMap<T, I, R>(fn: (value: T, index?: number) => Recursive<I>, resFn: (outerValue: T, innerValue: I) => R): ConcatMapIterable<T, I, R>

export function concatMap<T, I, R>(fn: (value: T, index?: number) => Recursive<I>, resFn?: (outerValue: T, innerValue: I) => R) {
  return new ConcatMapIterable<T, I, R>(this, fn, <(outerValue: T, innerValue: I) => R>resFn)
}

redpajama_set_name: RedPajamaGithub


text:
@interface ALLib : NSObject

@end


text:
from setuptools import setup, find_packages
from subprocess import check_output

def get_version():
	tag = check_output(["git", "tag"])
	hash = check_output(["git", "log", "-1", "--format=%H"])[:10]
	return "%s-p%s" % (tag, hash)

setup(
		name = "bugger",
		version = get_version(),
		packages = find_packages(),
		author = "Anton Löfgren",
		author_email = "anton.lofgren@gmail.com",
		license = "BSD (2-clause)",
		keywords = "mantis mechanize bugger bugs bug tracker issue issues",
		url = "https://github.com/catharsis/bugger",
		install_requires = open('requirements.txt').read().split('\n'),
		entry_points = {
			'console_scripts': [
				'bugger = bugger:main_func',
				],
			}
		)


text:
<?php

namespace ZendTest\Http\Header;

use Zend\Http\Header\ContentType;

class ContentTypeTest extends \PHPUnit_Framework_TestCase
{
    public function testContentTypeFromStringCreatesValidContentTypeHeader()
    {
        $contentTypeHeader = ContentType::fromString('Content-Type: xxx');
        $this->assertInstanceOf('Zend\Http\Header\HeaderInterface', $contentTypeHeader);
        $this->assertInstanceOf('Zend\Http\Header\ContentType', $contentTypeHeader);
    }

    public function testContentTypeGetFieldNameReturnsHeaderName()
    {
        $contentTypeHeader = new ContentType();
        $this->assertEquals('Content-Type', $contentTypeHeader->getFieldName());
    }

    public function testContentTypeGetFieldValueReturnsProperValue()
    {
        $header = ContentType::fromString('Content-Type: application/json');
        $this->assertEquals('application/json', $header->getFieldValue());
    }

    public function testContentTypeToStringReturnsHeaderFormattedString()
    {
        $header = new ContentType();
        $header->setMediaType('application/atom+xml')
               ->setCharset('ISO-8859-1');

        $this->assertEquals('Content-Type: application/atom+xml; charset=ISO-8859-1', $header->toString());
    }

    /** Implementation specific tests here */

    public function wildcardMatches()
    {
        return array(
            'wildcard' => array('*/*'),
            'wildcard-format' => array('*/*+*'),
            'wildcard-type-subtype-fixed-format' => array('*/*+json'),
            'wildcard-type-partial-wildcard-subtype-fixed-format' => array('*/vnd.*+json'),
            'wildcard-type-format-subtype' => array('*/json'),
            'fixed-type-wildcard-subtype' => array('application/*'),
            'fixed-type-wildcard-subtype-fixed-format' => array('application/*+json'),
            'fixed-type-format-subtype' => array('application/json'),
            'fixed-type-fixed-subtype-wildcard-format' => array('application/vnd.foobar+*'),
            'fixed-type-partial-wildcard-subtype-fixed-format' => array('application/vnd.*+json'),
            'fixed' => array('application/vnd.foobar+json'),
            'fixed-mixed-case' => array('APPLICATION/vnd.FooBar+json'),
        );
    }

    /**
     * @dataProvider wildcardMatches
     */
    public function testMatchWildCard($matchAgainst)
    {
        $header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
        $result = $header->match($matchAgainst);
        $this->assertEquals(strtolower($matchAgainst), $result);
    }

    public function invalidMatches()
    {
        return array(
            'format' => array('application/vnd.foobar+xml'),
            'wildcard-subtype' => array('application/vendor.*+json'),
            'subtype' => array('application/vendor.foobar+json'),
            'type' => array('text/vnd.foobar+json'),
            'wildcard-type-format' => array('*/vnd.foobar+xml'),
            'wildcard-type-wildcard-subtype' => array('*/vendor.*+json'),
            'wildcard-type-subtype' => array('*/vendor.foobar+json'),
        );
    }

    /**
     * @dataProvider invalidMatches
     */
    public function testFailedMatches($matchAgainst)
    {
        $header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
        $result = $header->match($matchAgainst);
        $this->assertFalse($result);
    }

    public function multipleCriteria()
    {
        $criteria = array(
            'application/vnd.foobar+xml',
            'application/vnd.*+json',
            'application/vendor.foobar+xml',
            '*/vnd.foobar+json',
        );
        return array(
            'array' => array($criteria),
            'string' => array(implode(',', $criteria)),
        );
    }

    /**
     * @dataProvider multipleCriteria
     */
    public function testReturnsMatchingMediaTypeOfFirstCriteriaToValidate($criteria)
    {
        $header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
        $result = $header->match($criteria);
        $this->assertEquals('application/vnd.*+json', $result);
    }

    public function contentTypeParameterExamples()
    {
        return array(
            'no-quotes' => array('Content-Type: foo/bar; param=baz', 'baz'),
            'with-quotes' => array('Content-Type: foo/bar; param="baz"', 'baz'),
            'with-equals' => array('Content-Type: foo/bar; param=baz=bat', 'baz=bat'),
            'with-equals-and-quotes' => array('Content-Type: foo/bar; param="baz=bat"', 'baz=bat'),
        );
    }

    /**
     * @dataProvider contentTypeParameterExamples
     */
    public function testContentTypeParsesParametersCorrectly($headerString, $expectedParameterValue)
    {
        $contentTypeHeader = ContentType::fromString($headerString);

        $parameters = $contentTypeHeader->getParameters();

        $this->assertArrayHasKey('param', $parameters);
        $this->assertSame($expectedParameterValue, $parameters['param']);
    }
}


text:
.class public interface abstract Lcom/google/android/gms/ads/mediation/MediationAdRequest;
.super Ljava/lang/Object;

# static fields
.field public static final TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE:I = 0x0

.field public static final TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE:I = 0x1

.field public static final TAG_FOR_CHILD_DIRECTED_TREATMENT_UNSPECIFIED:I = -0x1

# virtual methods
.method public abstract getBirthday()Ljava/util/Date;
.end method

.method public abstract getGender()I
.end method

.method public abstract getKeywords()Ljava/util/Set;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Set",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end method

.method public abstract getLocation()Landroid/location/Location;
.end method

.method public abstract isTesting()Z
.end method

.method public abstract taggedForChildDirectedTreatment()I
.end method


text:
run "rm public/index.html"
inside 'vendor/plugins' do
  run "git clone ../../../../ friendly_id"
end
gem "haml"
gem "will_paginate"
run "haml --rails ."
generate "friendly_id"
generate :haml_scaffold, "post title:string"
route "map.root :controller => 'posts', :action => 'index'"
rake "db:migrate"
rake "db:fixtures:load"
file 'app/models/post.rb',
%q{class Post < ActiveRecord::Base
  has_friendly_id :title, :use_slug => true
end}
file 'test/fixtures/slugs.yml',
%q{
one:
  name: mystring
  sequence: 1
  sluggable: one (Post)

two:
  name: mystring
  sequence: 2
  sluggable: two (Post)
}


text:
/*!
    \file  gd32e10x_crc.c
    \brief CRC driver

    \version 2017-12-26, V1.0.0, firmware for GD32E10x
    \version 2018-12-20, V1.1.0, firmware for GD32E10x(The version is for mbed)
*/

/*
    Copyright (c) 2018, GigaDevice Semiconductor Inc.

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

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

#include "gd32e10x_crc.h"

#define CRC_DATA_RESET_VALUE      ((uint32_t)0xFFFFFFFFU)
#define CRC_FDATA_RESET_VALUE     ((uint32_t)0x00000000U)

/*!
    \brief      deinit CRC calculation unit
    \param[in]  none
    \param[out] none
    \retval     none
*/
void crc_deinit(void)
{
    CRC_DATA  = CRC_DATA_RESET_VALUE;
    CRC_FDATA = CRC_FDATA_RESET_VALUE;
    CRC_CTL   = (uint32_t)CRC_CTL_RST;
}

/*!
    \brief      reset data register(CRC_DATA) to the value of 0xFFFFFFFF
    \param[in]  none
    \param[out] none
    \retval     none
*/
void crc_data_register_reset(void)
{
    CRC_CTL |= (uint32_t)CRC_CTL_RST;
}

/*!
    \brief      read the value of the data register
    \param[in]  none
    \param[out] none
    \retval     32-bit value of the data register
*/
uint32_t crc_data_register_read(void)
{
    uint32_t data;
    data = CRC_DATA;
    return (data);
}

/*!
    \brief      read the value of the free data register
    \param[in]  none
    \param[out] none
    \retval     8-bit value of the free data register
*/
uint8_t crc_free_data_register_read(void)
{
    uint8_t fdata;
    fdata = (uint8_t)CRC_FDATA;
    return (fdata);
}

/*!
    \brief      write data to the free data register
    \param[in]  free_data: specify 8-bit data
    \param[out] none
    \retval     none
*/
void crc_free_data_register_write(uint8_t free_data)
{
    CRC_FDATA = (uint32_t)free_data;
}

/*!
    \brief      calculate the CRC value of a 32-bit data
    \param[in]  sdata: specified 32-bit data
    \param[out] none
    \retval     32-bit value calculated by CRC
*/
uint32_t crc_single_data_calculate(uint32_t sdata)
{
    CRC_DATA = sdata;
    return (CRC_DATA);
}

/*!
    \brief      calculate the CRC value of an array of 32-bit values
    \param[in]  array: pointer to an array of 32-bit values
    \param[in]  size: size of the array
    \param[out] none
    \retval     32-bit value calculated by CRC
*/
uint32_t crc_block_data_calculate(uint32_t array[], uint32_t size)
{
    uint32_t index;
    for (index = 0U; index < size; index++) {
        CRC_DATA = array[index];
    }
    return (CRC_DATA);
}


text:
require File.dirname(__FILE__) + '/test_helper'

class FeriadoParserTest < Test::Unit::TestCase

  FERIADO_YML_PATH = File.expand_path(File.dirname(__FILE__) + '/../lib/brdata/config')
  p FERIADO_YML_PATH
  NATAL = Feriado.new("natal", 25, 12)

  def test_feriados
    feriados, metodos = FeriadoParser.parser(FERIADO_YML_PATH)
    feriados.each {|feriado| assert_kind_of Feriado, feriado}
    assert_equal NATAL, feriados.find {|f| f.nome == "natal"}
    assert metodos.include?( "pascoa")
    assert metodos.include?( "corpus_christi")
  end

  def test_feriados_quando_path_nao_eh_diretorio
    assert_raise  FeriadoParserDiretorioInvalidoError do
      FeriadoParser.parser(File.dirname(__FILE__) + 'dinheiro_test.rb')
    end
  end

  def test_feriados_quando_path_nao_contem_arquivos
    assert_raise  FeriadoParserDiretorioVazioError do
      FeriadoParser.parser(File.dirname(__FILE__))
    end
  end

end


text:
"""
This is a newer version of the module found in oldapp.py, used in the
upgrading tests.  It upgrades from oldapp in one step, rather than requiring an
intermediary step as morenewapp.py does.
"""

from axiom.item import Item
from axiom.attributes import text, integer, reference, inmemory

from axiom.upgrade import registerUpgrader

class ActivateHelper:
    activated = 0
    def activate(self):
        self.activated += 1

class Adventurer(ActivateHelper, Item):
    typeName = 'test_app_player'
    schemaVersion = 2

    name = text()
    activated = inmemory()

class InventoryEntry(ActivateHelper, Item):
    typeName = 'test_app_inv'
    schemaVersion = 1

    owner = reference()
    owned = reference()

    activated = inmemory()

class Sword(ActivateHelper, Item):
    typeName = 'test_app_sword'
    schemaVersion = 3

    name = text()
    damagePerHit = integer()
    activated = inmemory()

    def owner():
        def get(self):
            return self.store.findUnique(InventoryEntry,
                                         InventoryEntry.owned == self).owner
        return get,

    owner = property(*owner())

def sword2to3(oldsword):
    raise RuntimeError("The database does not contain any swords of version 2,"
                       " so you should be able to skip this version.")

registerUpgrader(sword2to3, 'test_app_sword', 2, 3)

####### DOUBLE-LEGACY UPGRADE SPECTACULAR !! ###########

# declare legacy class.

from axiom.item import declareLegacyItem

declareLegacyItem(typeName = 'test_app_sword',
                  schemaVersion = 2,
                  attributes = dict(name=text(),
                                    damagePerHit=integer(),
                                    owner=reference(),
                                    activated=inmemory()))

def upgradePlayerAndSword(oldplayer):
    newplayer = oldplayer.upgradeVersion('test_app_player', 1, 2)
    newplayer.name = oldplayer.name

    oldsword = oldplayer.sword

    newsword = oldsword.upgradeVersion('test_app_sword', 1, 3,
                                       name=oldsword.name,
                                       damagePerHit=oldsword.hurtfulness * 2)
    invent = InventoryEntry(store=newsword.store,
                            owner=newplayer,
                            owned=newsword)
    return newplayer, newsword

def player1to2(oldplayer):
    newplayer, newsword = upgradePlayerAndSword(oldplayer)
    return newplayer

def sword1to3(oldsword):
    oldPlayerType = oldsword.store.getOldVersionOf('test_app_player', 1)
    oldplayer = list(oldsword.store.query(oldPlayerType,
                                          oldPlayerType.sword == oldsword))[0]
    newplayer, newsword = upgradePlayerAndSword(oldplayer)
    return newsword

registerUpgrader(sword1to3, 'test_app_sword', 1, 3)
registerUpgrader(player1to2, 'test_app_player', 1, 2)


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.Completion
{
    /// <summary>
    /// The action that triggered completion to start.
    /// </summary>
    public struct CompletionTrigger
    {
        /// <summary>
        /// The reason that completion was started.
        /// </summary>
        public CompletionTriggerKind Kind { get; }

        /// <summary>
        /// The character associated with the triggering action.
        /// </summary>
        public char Character { get; }

        internal CompletionTrigger(CompletionTriggerKind kind, char character = (char)0)
            : this()
        {
            this.Kind = kind;
            this.Character = character;
        }

        /// <summary>
        /// The default <see cref="CompletionTrigger"/> when none is specified.
        /// </summary>
        public static readonly CompletionTrigger Default = new CompletionTrigger(CompletionTriggerKind.Other);

        /// <summary>
        /// Creates a new instance of a <see cref="CompletionTrigger"/> association with the insertion of a typed character into the document.
        /// </summary>
        public static CompletionTrigger CreateInsertionTrigger(char insertedCharacter)
        {
            return new CompletionTrigger(CompletionTriggerKind.Insertion, insertedCharacter);
        }

        /// <summary>
        /// Creates a new instance of a <see cref="CompletionTrigger"/> association with the deletion of a character from the document.
        /// </summary>
        public static CompletionTrigger CreateDeletionTrigger(char deletedCharacter)
        {
            return new CompletionTrigger(CompletionTriggerKind.Deletion, deletedCharacter);
        }
    }
}


text:
class TransporterAddress < ApplicationRecord
  belongs_to :transporter, dependent: :destroy
end


text:
package de.waldheinz.fs.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;

import de.waldheinz.fs.BlockDevice;

/**
 * A {@link BlockDevice} that lives entirely in heap memory. This is basically
 * a RAM disk. A {@code RamDisk} is always writable.
 *
 * @author Matthias Treydte <waldheinz at gmail.com>
 */
public final class RamDisk implements BlockDevice {

    /**
     * The default sector size for {@code RamDisk}s.
     */
    public final static int DEFAULT_SECTOR_SIZE = 512;

    private final int sectorSize;
    private final ByteBuffer data;
    private final int size;
    private boolean closed;

    private RamDisk(ByteBuffer buffer, int sectorSize) {
        this.size = buffer.limit();
        this.sectorSize = sectorSize;
        this.data = buffer;
        this.closed = false;
    }

    /**
     * Creates a new instance of {@code RamDisk} of this specified
     * size and using the {@link #DEFAULT_SECTOR_SIZE}.
     *
     * @param size the size of the new block device
     */
    public RamDisk(int size) {
        this(size, DEFAULT_SECTOR_SIZE);
    }

    /**
     * Creates a new instance of {@code RamDisk} of this specified
     * size and sector size
     *
     * @param size       the size of the new block device
     * @param sectorSize the sector size of the new block device
     */
    public RamDisk(int size, int sectorSize) {
        if (sectorSize < 1) throw new IllegalArgumentException(
                "invalid sector size"); //NOI18N

        this.sectorSize = sectorSize;
        this.size = size;
        this.data = ByteBuffer.allocate(size);
    }

    /**
     * Reads a GZIP compressed disk image from the specified input stream and
     * returns a {@code RamDisk} holding the decompressed image.
     *
     * @param in the stream to read the disk image from
     * @return the decompressed {@code RamDisk}
     * @throws IOException on read or decompression error
     */
    public static RamDisk readGzipped(InputStream in) throws IOException {
        final GZIPInputStream zis = new GZIPInputStream(in);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        final byte[] buffer = new byte[4096];

        int read = zis.read(buffer);
        int total = 0;

        while (read >= 0) {
            total += read;
            bos.write(buffer, 0, read);
            read = zis.read(buffer);
        }

        if (total < DEFAULT_SECTOR_SIZE) throw new IOException(
                "read only " + total + " bytes"); //NOI18N

        final ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray(), 0, total);
        return new RamDisk(bb, DEFAULT_SECTOR_SIZE);
    }

    @Override
    public long getSize() {
        checkClosed();
        return this.size;
    }

    @Override
    public void read(long devOffset, ByteBuffer dest) throws IOException {
        checkClosed();

        if (devOffset > getSize()) {
            final StringBuilder sb = new StringBuilder();
            sb.append("read at ").append(devOffset);
            sb.append(" is off size (").append(getSize()).append(")");

            throw new IllegalArgumentException(sb.toString());
        }

        data.limit((int) (devOffset + dest.remaining()));
        data.position((int) devOffset);

        dest.put(data);
    }

    @Override
    public void write(long devOffset, ByteBuffer src) throws IOException {
        checkClosed();

        if (devOffset + src.remaining() > getSize()) throw new
                IllegalArgumentException(
                "offset=" + devOffset +
                        ", length=" + src.remaining() +
                        ", size=" + getSize());

        data.limit((int) (devOffset + src.remaining()));
        data.position((int) devOffset);

        data.put(src);
    }

    /**
     * Returns a slice of the {@code ByteBuffer} that is used by this
     * {@code RamDisk} as it's backing store. The returned buffer will be
     * live (reflecting any changes made through the
     * {@link #write(long, java.nio.ByteBuffer) method}, but read-only.
     *
     * @return a buffer holding the contents of this {@code RamDisk}
     */
    public ByteBuffer getBuffer() {
        return this.data.asReadOnlyBuffer();
    }

    @Override
    public void flush() throws IOException {
        checkClosed();
    }

    @Override
    public int getSectorSize() {
        checkClosed();
        return this.sectorSize;
    }

    @Override
    public void close() throws IOException {
        this.closed = true;
    }

    @Override
    public boolean isClosed() {
        return this.closed;
    }

    private void checkClosed() {
        if (closed) throw new IllegalStateException("device already closed");
    }

    /**
     * Returns always {@code false}, as a {@code RamDisk} is always writable.
     *
     * @return always {@code false}
     */
    @Override
    public boolean isReadOnly() {
        checkClosed();

        return false;
    }

}


text:
#include <aws/clouddirectory/model/CreateTypedLinkFacetResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::CloudDirectory::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

CreateTypedLinkFacetResult::CreateTypedLinkFacetResult()
{
}

CreateTypedLinkFacetResult::CreateTypedLinkFacetResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

CreateTypedLinkFacetResult& CreateTypedLinkFacetResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
package org.spacehq.mc.protocol.data.game.values.world.map;

public class MapPlayer {

    private int centerX;
    private int centerZ;
    private int iconSize;
    private int iconRotation;

    public MapPlayer(int centerX, int centerZ, int iconSize, int iconRotation) {
        this.centerX = centerX;
        this.centerZ = centerZ;
        this.iconSize = iconSize;
        this.iconRotation = iconRotation;
    }

    public int getCenterX() {
        return this.centerX;
    }

    public int getCenterZ() {
        return this.centerZ;
    }

    public int getIconSize() {
        return this.iconSize;
    }

    public int getIconRotation() {
        return this.iconRotation;
    }

    @Override
    public boolean equals(Object o) {
        if(this == o) return true;
        if(o == null || getClass() != o.getClass()) return false;

        MapPlayer mapPlayer = (MapPlayer) o;

        if(centerX != mapPlayer.centerX) return false;
        if(centerZ != mapPlayer.centerZ) return false;
        if(iconRotation != mapPlayer.iconRotation) return false;
        if(iconSize != mapPlayer.iconSize) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = centerX;
        result = 31 * result + centerZ;
        result = 31 * result + iconSize;
        result = 31 * result + iconRotation;
        return result;
    }

}


text:
require 'xml'
require 'test/unit'

class TestTextNode < Test::Unit::TestCase
  def test_content
    node = XML::Node.new_text('testdata')
    assert_instance_of(XML::Node, node)
    assert_equal('testdata', node.content)
  end

  def test_invalid_content
    error = assert_raise(TypeError) do
      node = XML::Node.new_text(nil)
    end
    assert_equal('wrong argument type nil (expected String)', error.to_s)
  end

	# We use the same facility that libXSLT does here to disable output escaping.
	# This lets you specify that the node's content should be rendered unaltered
	# whenever it is being output.  This is useful for things like <script> and
	# <style> nodes in HTML documents if you don't want to be forced to wrap them
	# in CDATA nodes.  Or if you are sanitizing existing HTML documents and want
	# to preserve the content of any of the text nodes.
	#
	def test_output_escaping
		textnoenc = 'if (a < b || c > d) return "e";'
		text = "if (a < b || c > d) return \"e\";"

		node = XML::Node.new_text(textnoenc)
		assert node.output_escaping?
		assert_equal text, node.to_s

		node.output_escaping = false
		assert_equal textnoenc, node.to_s

		node.output_escaping = true
		assert_equal text, node.to_s

		node.output_escaping = nil
		assert_equal textnoenc, node.to_s

		node.output_escaping = true
		assert_equal text, node.to_s
  end

	# Just a sanity check for output escaping.
	def test_output_escaping_sanity
		node = XML::Node.new_text('testdata')
    assert_equal 'text', node.name
		assert node.output_escaping?

		node.output_escaping = false
    assert_equal 'textnoenc', node.name
		assert ! node.output_escaping?

		node.output_escaping = true
    assert_equal 'text', node.name
		assert node.output_escaping?

		node.output_escaping = nil
    assert_equal 'textnoenc', node.name
		assert ! node.output_escaping?

		node.output_escaping = true
    assert_equal 'text', node.name
		assert node.output_escaping?
  end

end


text:
package org.springframework.cloud.task.listener;

import org.springframework.cloud.task.repository.TaskExecution;
import org.springframework.cloud.task.repository.TaskRepository;

/**
 * The listener interface for receiving task execution events.
 *
 * @author Glenn Renfro
 */
public interface TaskExecutionListener {

	/**
	 * Invoked after the {@link TaskExecution} has been stored in the
	 * {@link TaskRepository}.
	 * @param taskExecution instance containing the information about the current task.
	 */
	void onTaskStartup(TaskExecution taskExecution);

	/**
	 * Invoked before the {@link TaskExecution} has been updated in the
	 * {@link TaskRepository} upon task end.
	 * @param taskExecution instance containing the information about the current task.
	 */
	void onTaskEnd(TaskExecution taskExecution);

	/**
	 * Invoked if an uncaught exception occurs during a task execution. This invocation
	 * will occur before the {@link TaskExecution} has been updated in the
	 * {@link TaskRepository} and before the onTaskEnd is called.
	 * @param taskExecution instance containing the information about the current task.
	 * @param throwable the uncaught exception that was thrown during task execution.
	 */
	void onTaskFailed(TaskExecution taskExecution, Throwable throwable);

}


text:
package org.pkcs11.jacknji11.jna;

import org.pkcs11.jacknji11.CK_MECHANISM_INFO;

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

import com.sun.jna.NativeLong;
import com.sun.jna.Structure;

/**
 * JNA wrapper for PKCS#11 CK_MECHANSIM_INFO struct.
 * @author Joel Hockey (joel.hockey@gmail.com)
 */
public class JNA_CK_MECHANISM_INFO extends Structure {
    public NativeLong ulMinKeySize;
    public NativeLong ulMaxKeySize;
    public NativeLong flags;

    @Override
    protected List<String> getFieldOrder() {
        return Arrays.asList("ulMinKeySize", "ulMaxKeySize", "flags");
    }

    public JNA_CK_MECHANISM_INFO readFrom(CK_MECHANISM_INFO info) {
        ulMinKeySize = new NativeLong(info.ulMinKeySize);
        ulMaxKeySize = new NativeLong(info.ulMaxKeySize);
        flags = new NativeLong(info.flags);
        return this;
    }

    public CK_MECHANISM_INFO writeTo(CK_MECHANISM_INFO info) {
        info.ulMinKeySize = ulMinKeySize.intValue();
        info.ulMaxKeySize = ulMaxKeySize.intValue();
        info.flags = flags.intValue();
        return info;
    }
}


text:
#pragma once

#include <chrono>
#include <memory>

#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/test/util/TestServerFactory.h>

namespace apache {
namespace thrift {

template <typename Interface>
struct TestThriftServerFactory : public TestServerFactory {
 public:
  std::shared_ptr<BaseThriftServer> create() override {
    auto server = std::make_shared<apache::thrift::ThriftServer>();
    server->setNumIOWorkerThreads(1);
    if (useSimpleThreadManager_) {
      auto threadFactory =
          std::make_shared<apache::thrift::concurrency::PosixThreadFactory>();
      server->setThreadManagerType(
          apache::thrift::BaseThriftServer::ThreadManagerType::SIMPLE);
      server->setNumCPUWorkerThreads(1);
      server->setThreadFactory(threadFactory);
    } else if (setupFunction_) {
      setupFunction_(*server);
    }

    server->setPort(0);

    if (idleTimeoutMs_ != 0) {
      server->setIdleTimeout(std::chrono::milliseconds(idleTimeoutMs_));
    }

    if (duplex_) {
      server->setDuplex(true);
    }

    if (serverEventHandler_) {
      server->setServerEventHandler(serverEventHandler_);
    }

    server->setInterface(std::unique_ptr<Interface>(new Interface));
    return server;
  }

  TestThriftServerFactory& useSimpleThreadManager(bool use) override {
    useSimpleThreadManager_ = use;
    return *this;
  }

  TestThriftServerFactory& setServerSetupFunction(
      std::function<void(BaseThriftServer&)> setupFunction) override {
    setupFunction_ = setupFunction;
    return *this;
  }

  TestThriftServerFactory& idleTimeoutMs(uint32_t idle) {
    idleTimeoutMs_ = idle;
    return *this;
  }

  TestThriftServerFactory& duplex(bool duplex) {
    duplex_ = duplex;
    return *this;
  }

 private:
  bool useSimpleThreadManager_{true};
  std::function<void(BaseThriftServer&)> setupFunction_;
  uint32_t idleTimeoutMs_{0};
  bool duplex_{false};
};

} // namespace thrift
} // namespace apache


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Appmessage extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    public function auth()
    {
        $this->messagemanager->setError('page_error_app_auth');
        $this->viewmanager->renderView();
    }
}


text:
/* global test */
'use strict';

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

var _proclaim = require('proclaim');

var _libUtilsUrl = require('../../../lib/utils/Url');

var _libUtilsUrl2 = _interopRequireDefault(_libUtilsUrl);

test('Url constructor processing', function () {
    var url = new _libUtilsUrl2['default']();
    (0, _proclaim.equal)(url.toString(), 'about:blank');

    url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.equal)(url.toString(), 'http://some.link/');
});

test('Url toString', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.equal)(url, 'http://some.link/');
});

test('href member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.href, 'http://some.link/');

    url.href = 'ftp://test:test@other:8080';
    (0, _proclaim.strictEqual)(url.href, 'ftp://test:test@other:8080/');

    url.href = '';
    (0, _proclaim.strictEqual)(url.href, 'about:blank');
});

test('protocol member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.protocol, 'http:');

    url.protocol = 'some:';
    (0, _proclaim.strictEqual)(url.protocol, 'some:');

    url.protocol = 'ftp';
    (0, _proclaim.strictEqual)(url.protocol, 'ftp:');
});

test('host member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.host, 'some.link');

    url.href = 'ftp://test:test@other:8080';
    (0, _proclaim.strictEqual)(url.host, 'other:8080');

    url.host = 'my.url:8080';
    (0, _proclaim.strictEqual)(url.host, 'my.url:8080');

    url.host = 'other.url';
    url.port = '90';
    (0, _proclaim.strictEqual)(url.host, 'other.url:90');
});

test('auth member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.auth, '');

    url.auth = 'my:name';
    (0, _proclaim.strictEqual)(url.auth, 'my:name');

    url.href = 'http://other:name@link.com';
    (0, _proclaim.strictEqual)(url.auth, 'other:name');

    url.href = 'http://username@link.com';
    (0, _proclaim.strictEqual)(url.auth, 'username');
});

test('hostname member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.hostname, 'some.link');

    url.href = 'ftp://test:test@other:8080';
    (0, _proclaim.strictEqual)(url.hostname, 'other');

    url.hostname = 'my.url';
    (0, _proclaim.strictEqual)(url.hostname, 'my.url');

    url.host = 'other.url';
    url.port = '90';
    (0, _proclaim.strictEqual)(url.hostname, 'other.url');
});

test('port member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.port, '80');

    url.href = 'ftp://test:test@other';
    (0, _proclaim.strictEqual)(url.port, '21');

    url.host = 'my.url:8080';
    (0, _proclaim.strictEqual)(url.port, '8080');

    url.host = 'other.url';
    url.port = '90';
    (0, _proclaim.strictEqual)(url.host, 'other.url:90');
    (0, _proclaim.strictEqual)(url.href, 'ftp://test:test@other.url:90/');

    url.port = 'some other value';
    (0, _proclaim.strictEqual)(url.href, 'ftp://test:test@other.url/');

    url = new _libUtilsUrl2['default']('https://secure.link');
    (0, _proclaim.strictEqual)(url.port, '443');

    url = new _libUtilsUrl2['default']('mongo://mongo.link');
    (0, _proclaim.strictEqual)(url.port, '');
});

test('pathname member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.pathname, '/');

    url.pathname = '/some/path/on/site.html';
    (0, _proclaim.strictEqual)(url.pathname, '/some/path/on/site.html');
    (0, _proclaim.strictEqual)(url.href, 'http://some.link/some/path/on/site.html');
});

test('search member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.search, '');

    url.href = 'http://some.link/some/path/on/site.html?search=me';
    (0, _proclaim.strictEqual)(url.search, '?search=me');

    url.search = 'myparams for search';
    (0, _proclaim.strictEqual)(url.href, 'http://some.link/some/path/on/site.html?myparams for search');
});

test('hash member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.hash, '#');

    url.hash = '#hash';
    (0, _proclaim.strictEqual)(url.hash, '#hash');

    url.hash = 'some_hash';
    (0, _proclaim.strictEqual)(url.hash, '#some_hash');
    (0, _proclaim.strictEqual)(url.href, 'http://some.link/#some_hash');
});

test('username member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.username, '');

    url.username = 'user';
    (0, _proclaim.strictEqual)(url.auth, 'user');

    url.auth = 'my:name';
    (0, _proclaim.strictEqual)(url.username, 'my');

    url.href = 'http://other:name@link.com';
    (0, _proclaim.strictEqual)(url.username, 'other');

    url.href = 'http://username@link.com';
    (0, _proclaim.strictEqual)(url.username, 'username');

    url.href = 'http://:username@link.com';
    (0, _proclaim.strictEqual)(url.username, '');

    url.username = 'me';
    (0, _proclaim.strictEqual)(url.auth, 'me:username');
});

test('password member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.strictEqual)(url.password, '');

    url.password = 'pass';
    (0, _proclaim.strictEqual)(url.auth, ':pass');

    url.auth = 'my:name';
    (0, _proclaim.strictEqual)(url.password, 'name');

    url.href = 'http://other:name@link.com';
    (0, _proclaim.strictEqual)(url.password, 'name');

    url.href = 'http://username@link.com';
    (0, _proclaim.strictEqual)(url.password, '');

    url.password = 'password';
    (0, _proclaim.strictEqual)(url.auth, 'username:password');

    url.href = 'http://:username@link.com';
    (0, _proclaim.strictEqual)(url.password, 'username');
});

test('searchParams member', function () {
    var url = new _libUtilsUrl2['default']('http://some.link');
    (0, _proclaim.deepEqual)(url.searchParams, {});

    url.href = 'http://some.link/some/path/on/site.html?search=me';
    (0, _proclaim.strictEqual)(url.searchParams.search, 'me');
});
//# sourceMappingURL=Url.js.map


text:
cask "microsoft-teams" do
  version "1.4.00.22368"
  sha256 "7984457a0e815359e4ea25684cc5dd548df9df61ee3c9cc209104586347a07ea"

  url "https://statics.teams.cdn.office.net/production-osx/#{version}/Teams_osx.pkg",
      verified: "statics.teams.cdn.office.net"
  name "Microsoft Teams"
  desc "Meet, chat, call, and collaborate in just one place"
  homepage "https://teams.microsoft.com/downloads"

  livecheck do
    url "https://aka.ms/teamsmac"
    strategy :header_match
  end

  auto_updates true

  pkg "Teams_osx.pkg"

  uninstall pkgutil:   "com.microsoft.teams",
            launchctl: "com.microsoft.teams.TeamsUpdaterDaemon"

  zap trash: [
    "/Library/Logs/Microsoft/Teams",
    "/Library/Preferences/com.microsoft.teams.plist",
    "~/Library/Application Support/Microsoft/Teams",
    "~/Library/Application Support/com.microsoft.teams",
    "~/Library/Caches/com.microsoft.teams",
    "~/Library/Cookies/com.microsoft.teams.binarycookies",
    "~/Library/Logs/Microsoft Teams",
    "~/Library/Preferences/com.microsoft.teams.plist",
    "~/Library/Saved Application State/com.microsoft.teams.savedState",
  ]
end


text:
package com.palantir.atlasdb.sweep.queue;

import static com.palantir.atlasdb.sweep.queue.AbstractSweepQueueTest.metadataBytes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.protos.generated.TableMetadataPersistence;
import com.palantir.atlasdb.table.description.SweepStrategy.SweeperStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;

public class WriteInfoPartitionerTest {
    private static final TableReference NOTHING = getTableRef("nothing");
    private static final TableReference CONSERVATIVE = getTableRef("conservative");
    private static final TableReference CONSERVATIVE2 = getTableRef("conservative2");
    private static final TableReference THOROUGH = getTableRef("thorough");
    private static final Map<TableReference, byte[]> METADATA_MAP = ImmutableMap.of(
            NOTHING, metadataBytes(TableMetadataPersistence.SweepStrategy.NOTHING),
            CONSERVATIVE, metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE),
            CONSERVATIVE2, metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE),
            THOROUGH, metadataBytes(TableMetadataPersistence.SweepStrategy.THOROUGH));

    private KeyValueService mockKvs = mock(KeyValueService.class);
    private WriteInfoPartitioner partitioner;
    private int numShards = 128;

    @Before
    public void setup() {
        partitioner = new WriteInfoPartitioner(mockKvs, () -> numShards);
        when(mockKvs.getMetadataForTable(any(TableReference.class)))
                .thenAnswer(args ->
                        METADATA_MAP.getOrDefault(args.getArguments()[0], AtlasDbConstants.EMPTY_TABLE_METADATA));
    }

    @Test
    public void getStrategyThrowsForIllegalMetadata() {
        when(mockKvs.getMetadataForTable(any())).thenReturn(AtlasDbConstants.EMPTY_TABLE_METADATA);
        assertThatThrownBy(() -> partitioner.getStrategy(getWriteInfoWithFixedCellHash(getTableRef("a"), 0)))
                .isInstanceOf(UncheckedExecutionException.class);
    }

    @Test
    public void getStrategyThrowsOnUncheckedException() {
        RuntimeException cause = new RuntimeException("cause");
        when(mockKvs.getMetadataForTable(any())).thenThrow(cause);
        assertThatThrownBy(() -> partitioner.getStrategy(getWriteInfoWithFixedCellHash(getTableRef("a"), 0)))
                .isInstanceOf(UncheckedExecutionException.class)
                .hasCause(cause);
    }

    @Test
    public void getStrategyReturnsCorrectStrategy() {
        assertThat(partitioner.getStrategy(getWriteInfoWithFixedCellHash(NOTHING, 0)))
                .isEmpty();
        assertThat(partitioner.getStrategy(getWriteInfoWithFixedCellHash(CONSERVATIVE, 10)))
                .contains(SweeperStrategy.CONSERVATIVE);
        assertThat(partitioner.getStrategy(getWriteInfoWithFixedCellHash(THOROUGH, 100)))
                .contains(SweeperStrategy.THOROUGH);
    }

    @Test
    public void getStrategyQueriesKvsOnlyOnceForEachTable() {
        for (int i = 0; i < 5; i++) {
            partitioner.getStrategy(getWriteInfoWithFixedCellHash(NOTHING, i));
            partitioner.getStrategy(getWriteInfoWithFixedCellHash(CONSERVATIVE, i));
        }
        verify(mockKvs, times(1)).getMetadataForTable(NOTHING);
        verify(mockKvs, times(1)).getMetadataForTable(CONSERVATIVE);
        verifyNoMoreInteractions(mockKvs);
    }

    @Test
    public void filterOutUnsweepableRemovesWritesWithStrategyNothing() {
        List<WriteInfo> writes = ImmutableList.of(
                getWriteInfoWithFixedCellHash(CONSERVATIVE, 0),
                getWriteInfoWithFixedCellHash(NOTHING, 1),
                getWriteInfoWithFixedCellHash(CONSERVATIVE, 0),
                getWriteInfoWithFixedCellHash(CONSERVATIVE2, 1),
                getWriteInfoWithFixedCellHash(THOROUGH, 2),
                getWriteInfoWithFixedCellHash(NOTHING, 0));

        assertThat(partitioner.filterOutUnsweepableTables(writes))
                .containsExactly(
                        getWriteInfoWithFixedCellHash(CONSERVATIVE, 0), getWriteInfoWithFixedCellHash(CONSERVATIVE, 0),
                        getWriteInfoWithFixedCellHash(CONSERVATIVE2, 1), getWriteInfoWithFixedCellHash(THOROUGH, 2));
    }

    @Test
    public void partitionWritesByShardStrategyTimestampPartitionsIntoSeparatePartitions() {
        List<WriteInfo> writes = ImmutableList.of(
                getWriteInfo(CONSERVATIVE, 0, 0, 100L),
                getWriteInfo(CONSERVATIVE, 1, 0, 100L),
                getWriteInfo(CONSERVATIVE, 0, 3, 100L),
                getWriteInfo(CONSERVATIVE, 0, 0, 200L),
                getWriteInfo(CONSERVATIVE2, 0, 0, 100L),
                getWriteInfo(THOROUGH, 0, 0, 100L));

        Map<PartitionInfo, List<WriteInfo>> partitions = partitioner.partitionWritesByShardStrategyTimestamp(writes);
        assertThat(partitions.size()).isEqualTo(6);
    }

    @Test
    public void partitionWritesByShardStrategyTimestampGroupsOnShardClash() {
        List<WriteInfo> writes = new ArrayList<>();
        for (int i = 0; i <= numShards; i++) {
            writes.add(getWriteInfoWithFixedCellHash(CONSERVATIVE, i));
        }
        Map<PartitionInfo, List<WriteInfo>> partitions = partitioner.partitionWritesByShardStrategyTimestamp(writes);
        assertThat(partitions.keySet())
                .containsExactly(PartitionInfo.of(writes.get(0).toShard(numShards), true, 1L));
        assertThat(Iterables.getOnlyElement(partitions.values())).isEqualTo(writes);
    }

    @Test
    public void changingNumberOfPartitionsIsReflectedInPartitionInfo() {
        WriteInfo write = getWriteInfo(CONSERVATIVE, 1, 1, 100L);
        PartitionInfo partition1 = Iterables.getOnlyElement(partitioner
                .partitionWritesByShardStrategyTimestamp(ImmutableList.of(write))
                .keySet());
        numShards += 1;
        PartitionInfo partition2 = Iterables.getOnlyElement(partitioner
                .partitionWritesByShardStrategyTimestamp(ImmutableList.of(write))
                .keySet());

        assertThat(partition1.isConservative()).isEqualTo(partition2.isConservative());
        assertThat(partition1.timestamp()).isEqualTo(partition2.timestamp());
        assertThat(partition1.shard()).isNotEqualTo(partition2.shard());
    }

    private static TableReference getTableRef(String tableName) {
        return TableReference.createFromFullyQualifiedName("test." + tableName);
    }

    private WriteInfo getWriteInfoWithFixedCellHash(TableReference tableRef, int cellIndex) {
        // cell hash is rowname ^ colname, so equals 0 when they are equal
        return getWriteInfo(tableRef, cellIndex, cellIndex, 1L);
    }

    private WriteInfo getWriteInfo(TableReference tableRef, int rowIndex, int colIndex, long timestamp) {
        Cell cell = Cell.create(PtBytes.toBytes(rowIndex), PtBytes.toBytes(colIndex));
        return WriteInfo.write(tableRef, cell, timestamp);
    }
}


text:
package compiler

import (
	"github.com/couchbaselabs/tuqtng/plan"
	"github.com/couchbaselabs/tuqtng/query"
)

type Compiler interface {
	Compile(queryString string) (*plan.Plan, query.Error)
}


text:
namespace Serenity.Abstractions
{
    /// <summary>
    /// Interface for authorization services that supports temporary impersonating
    /// </summary>
    public interface IImpersonator
    {
        void Impersonate(string username);
        void UndoImpersonate();
    }
}


text:
package eu.modernmt.processing;

/**
 * Created by davide on 26/01/16.
 */
public class ProcessingException extends Exception {

    public ProcessingException(Object input, TextProcessor<?, ?> processor, RuntimeException cause) {
        super('(' + processor.getClass().getSimpleName() + ") Failed to process input \"" + input + "\"", cause);
    }

}


text:
using System;
using System.Net;

using NUnit.Framework;
using TestStack.FluentMVCTesting;
using Moq;

using CarSystem.Data.Services.Contracts;
using CarSystem.Web.Infrastucture.Contracts;
using CarSystem.Web.Models.Advert;

namespace CarSystem.Web.Controllers.Tests.AdvertControllerTests
{
    [TestFixture]
    public class IndexShould
    {
        [Test]
        public void Index_Should_ReturnHttpStatusCode_BadRequest_IfModelParameterIsNull()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            // Act &Assert
            advertController
                .WithCallTo(x => x.Index(null))
                .ShouldGiveHttpStatus(HttpStatusCode.BadRequest);
        }

        [Test]
        public void Index_Should_SetTempDataNotificationWithCorrectMessage_IfModelStateIsNotValid()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            advertController.ModelState.AddModelError("Yolo", "Yolo");

            // Act
            advertController.Index(new AdvertSearchViewModel());

            // Assert
            Assert.AreEqual(advertController.TempData["Notification"], "Exception.");
        }

        [Test]
        public void Index_Should_RedirectTo_ControllerHome_MethodIndex_IfModelStateIsNotValid()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            advertController.ModelState.AddModelError("Yolo", "Yolo");

            // Act and Assert
            advertController
                .WithCallTo(x => x.Index(new AdvertSearchViewModel()))
                .ShouldRedirectTo<Controllers.HomeController>(h => h.Index());
        }

        [Test]
        public void Index_Should_InvokeAdvertServiceMethod_Search_Once_IfModelStateIsValid()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            advertController.Index(new AdvertSearchViewModel());

            // Act & Assert
            mockedAdvertService.Verify(a => a.Search(
                                                    It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(),
                                                    It.IsAny<int?>(), It.IsAny<decimal?>(), It.IsAny<decimal?>(),
                                                    It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>()), Times.Once);
        }

        [Test]
        public void Index_Should_InvokeAdvertServiceMethod_Search_Never_IfModelStateIsNotValid()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            advertController.ModelState.AddModelError("Yolo", "Yolo");

            advertController.Index(new AdvertSearchViewModel());

            // Act and Assert
            mockedAdvertService.Verify(a => a.Search(
                                                    It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(),
                                                    It.IsAny<int?>(), It.IsAny<decimal?>(), It.IsAny<decimal?>(),
                                                    It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>()), Times.Never);
        }

        [Test]
        public void Index_Should_SetTempDataNotificationWithCorrectMessage_IfThereIsNoError()
        {
            // Arrange
            var mockedMappingService = new Mock<IMappingService>();
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            mockedAdvertService.Setup(a => a.Search(It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(),
                It.IsAny<int?>(), It.IsAny<decimal?>(), It.IsAny<decimal?>(),
                It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>())).Throws(new Exception());

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            // Act
            advertController.Index(new AdvertSearchViewModel());

            // Assert
            Assert.AreEqual(advertController.TempData["Notification"], "Exception.");
        }

        [Test]
        public void Index_Should_RedirectTo_ControllerHome_MethodIndex_IfThereIsNoError()
        {
            // Arrange
            var mockedAdvertService = new Mock<IAdvertService>();
            var mockedMappingService = new Mock<IMappingService>();
            var mockedCityService = new Mock<ICityService>();
            var mockedVehicleModelService = new Mock<IVehicleModelService>();

            mockedAdvertService.Setup(a => a.Search(It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(),
                It.IsAny<int?>(), It.IsAny<decimal?>(), It.IsAny<decimal?>(),
                It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<int?>())).Throws(new Exception());

            var advertController = new AdvertController(
                mockedAdvertService.Object,
                mockedMappingService.Object,
                mockedVehicleModelService.Object,
                mockedCityService.Object);

            // Act & Assert
            advertController
                .WithCallTo(x => x.Index(new AdvertSearchViewModel()))
                .ShouldRedirectTo<Controllers.HomeController>(h => h.Index());
        }
    }
}


text:
module Rutyl

  # Add instance variable creation at runtime by defining them
  # as parameters in the constructor
  # ex:
  # Class Car
  #   include Rutyl
  #
  #   def initialize(color, speed)
  #     ivars_from binding
  #   end
  # end
  #
  # Car.new("green", 10) => <Car @color="green", @speed=10>
  #--------------------------------------------------------------------------------
  def ivars_from(binding)
    binding.eval('local_variables').each do |var|
      self.instance_variable_set("@#{var}", binding.eval("#{var}"))
    end
  end
end


text:
package strategy

import (
	"errors"
	"fmt"

	"github.com/golang/glog"
	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/runtime"

	buildapi "github.com/openshift/origin/pkg/build/api"
)

// CustomBuildStrategy creates a build using a custom builder image.
type CustomBuildStrategy struct {
	// Codec is the codec to use for encoding the output pod.
	// IMPORTANT: This may break backwards compatibility when
	// it changes.
	Codec runtime.Codec
}

// CreateBuildPod creates the pod to be used for the Custom build
func (bs *CustomBuildStrategy) CreateBuildPod(build *buildapi.Build) (*kapi.Pod, error) {
	strategy := build.Spec.Strategy.CustomStrategy
	if strategy == nil {
		return nil, errors.New("CustomBuildStrategy cannot be executed without CustomStrategy parameters")
	}

	codec := bs.Codec
	if len(strategy.BuildAPIVersion) != 0 {
		gv, err := unversioned.ParseGroupVersion(strategy.BuildAPIVersion)
		if err != nil {
			return nil, &FatalError{fmt.Sprintf("failed to parse buildAPIVersion specified in custom build strategy (%q): %v", strategy.BuildAPIVersion, err)}
		}
		codec = kapi.Codecs.LegacyCodec(gv)
	}

	data, err := runtime.Encode(codec, build)
	if err != nil {
		return nil, fmt.Errorf("failed to encode the build: %v", err)
	}

	containerEnv := []kapi.EnvVar{{Name: "BUILD", Value: string(data)}}

	if build.Spec.Source.Git != nil {
		addSourceEnvVars(build.Spec.Source, &containerEnv)
	}
	addOriginVersionVar(&containerEnv)

	if build.Spec.Output.To != nil {
		addOutputEnvVars(build.Spec.Output.To, &containerEnv)
		if err != nil {
			return nil, fmt.Errorf("failed to parse the output docker tag %q: %v", build.Spec.Output.To.Name, err)
		}
	}

	if len(strategy.From.Name) == 0 {
		return nil, errors.New("CustomBuildStrategy cannot be executed without image")
	}

	if len(strategy.Env) > 0 {
		containerEnv = append(containerEnv, strategy.Env...)
	}

	if strategy.ExposeDockerSocket {
		glog.V(2).Infof("ExposeDockerSocket is enabled for %s build", build.Name)
		containerEnv = append(containerEnv, kapi.EnvVar{Name: "DOCKER_SOCKET", Value: dockerSocketPath})
	}

	privileged := true
	pod := &kapi.Pod{
		ObjectMeta: kapi.ObjectMeta{
			Name:      buildapi.GetBuildPodName(build),
			Namespace: build.Namespace,
			Labels:    getPodLabels(build),
		},
		Spec: kapi.PodSpec{
			ServiceAccountName: build.Spec.ServiceAccount,
			Containers: []kapi.Container{
				{
					Name:  "custom-build",
					Image: strategy.From.Name,
					Env:   containerEnv,
					// TODO: run unprivileged https://github.com/openshift/origin/issues/662
					SecurityContext: &kapi.SecurityContext{
						Privileged: &privileged,
					},
				},
			},
			RestartPolicy: kapi.RestartPolicyNever,
			NodeSelector:  build.Spec.NodeSelector,
		},
	}
	if build.Spec.CompletionDeadlineSeconds != nil {
		pod.Spec.ActiveDeadlineSeconds = build.Spec.CompletionDeadlineSeconds
	}

	if !strategy.ForcePull {
		pod.Spec.Containers[0].ImagePullPolicy = kapi.PullIfNotPresent
	} else {
		glog.V(2).Infof("ForcePull is enabled for %s build", build.Name)
		pod.Spec.Containers[0].ImagePullPolicy = kapi.PullAlways
	}
	pod.Spec.Containers[0].Resources = build.Spec.Resources
	if build.Spec.Source.Binary != nil {
		pod.Spec.Containers[0].Stdin = true
		pod.Spec.Containers[0].StdinOnce = true
	}

	if strategy.ExposeDockerSocket {
		setupDockerSocket(pod)
		setupDockerSecrets(pod, build.Spec.Output.PushSecret, strategy.PullSecret, build.Spec.Source.Images)
	}
	setupSourceSecrets(pod, build.Spec.Source.SourceSecret)
	setupSecrets(pod, build.Spec.Source.Secrets)
	setupAdditionalSecrets(pod, build.Spec.Strategy.CustomStrategy.Secrets)
	return pod, nil
}


text:
from __future__ import print_function

import os
import pipes

from fabric.api import settings, task, local, hide, env
from fabric.contrib.console import confirm

def is_working_tree_clean():
    with settings(hide('everything'), warn_only=True):
        local('git update-index -q --ignore-submodules --refresh')
        unstaged = local('git diff-files --quiet --ignore-submodules --',
                         capture=True)
        uncommitted = local('git diff-index --cached --quiet HEAD '
                            '--ignore-submodules --', capture=True)
    return unstaged.succeeded and uncommitted.succeeded

@task
def lint():
    """
    Checks the source code using flake8.
    """
    local('flake8 --statistics --exit-zero --max-complexity=10 '
          '--exclude=\'build,dist,docs,dev\' .')

@task
def authors():
    """
    Updates the AUTHORS file with a list of committers from GIT.
    """
    local('git shortlog -s -e -n | cut -f 2- > AUTHORS')

@task
def release():
    """
    Create a new release and upload it to PyPI.
    """

    if not is_working_tree_clean():
        print('Your working tree is not clean. Refusing to create a release.')
        return

    print('Rebuilding the AUTHORS file to check for modifications...')
    authors()

    if not is_working_tree_clean():
        print(
            'Your working tree is not clean after the AUTHORS file was '
            'rebuilt.'
        )
        print('Please commit the changes before continuing.')
        return

    # Get version
    version = 'v{}'.format(local('python setup.py --version', capture=True))
    name = local('python setup.py --name', capture=True)

    # Tag
    tag_message = '{} release version {}.'.format(name, version)

    print('----------------------')
    print('Proceeding will tag the release, push the repository upstream,')
    print('and release a new version on PyPI.')
    print()
    print('Version: {}'.format(version))
    print('Tag message: {}'.format(tag_message))
    print()
    if not confirm('Continue?', default=True):
        print('Aborting.')
        return

    local('git tag -a {} -m {}'.format(pipes.quote(version),
                                       pipes.quote(tag_message)))

    # Push
    local('git push --tags origin master')

    # Package and upload to pypi
    local('python setup.py sdist bdist_wheel upload')

@task
def package():
    """
    Build a Docker container with the application.

    If skipbuild is specified, the Python package is not rebuilt before
    creating the container.
    """
    from wheel import bdist_wheel
    from distutils.core import Distribution

    dist = Distribution(attrs={
        'name': env.project_name,
        'version': env.project_version,
        'packages': env.package_name,
    })

    cmd = bdist_wheel.bdist_wheel(dist)
    cmd.universal = True
    # TODO: This builds the development setup right now!
    # filename = cmd.get_archive_basename() + '.whl'

    local('time docker run -u {}:{} -w /src -v {}:/src python-dev '
          'python3 setup.py bdist_wheel --universal'.format(
              os.getuid(), os.getgid(), os.path.realpath('.')))

@task
def build(flavor):
    local('time docker-build -t {}/{flavor} -f docker/{flavor} .'
          .format(env.package_name, flavor=flavor))


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptothyrium bornmuelleri Magnus

### Remarks
null


text:
require "black_thursday_spec_harness/version"

module BlackThursdaySpecHarness
  # Your code goes here...
end


text:
require 'mindflow'
require 'listen'
require 'pathname'

module Mindflow
  class Cli
    InvalidFileExtension = Class.new(StandardError)

    def initialize(argv)
      @argv = argv
      check_args
    end

    def run
      generate
      listen
    end

    private

    ALLOWED_EXTNAME = '.mindflow'.freeze

    def check_args
      if ::File.extname(mindflow_filename) != ALLOWED_EXTNAME
        raise InvalidFileExtension, 'Invalid file extension for mindflow file'
      end
    end

    def mindflow_filename
      @argv[0]
    end

    def generate
      puts "Generate ruby files.."
      FileUtils.rm_rf output_dir
      Generator.new(path, root_dir: output_dir).generate
    rescue => ex
      puts ex.backtrace
    end

    def listen
      puts "Listen to #{path}"
      listener = Listen.to(dir, only: /\.mindflow$/) do
        generate
      end
      listener.start
      sleep
    end

    def path
      ::File.expand_path "#{dir}/#{mindflow_filename}"
    end

    def dir
      Dir.pwd
    end

    def output_dir
      "tmp/mindflow/#{mindflow_name}"
    end

    def mindflow_name
      ::File.basename(mindflow_filename, ".*")
    end
  end
end


text:
namespace Microsoft.Azure.Management.ServiceBus
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// RegionsOperations operations.
    /// </summary>
    public partial interface IRegionsOperations
    {
        /// <summary>
        /// Gets the available Regions for a given sku
        /// </summary>
        /// <param name='sku'>
        /// The sku type.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<PremiumMessagingRegions>>> ListBySkuWithHttpMessagesAsync(string sku, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets the available Regions for a given sku
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<PremiumMessagingRegions>>> ListBySkuNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}