text:
/*!
    \file  gd32vf103_i2c.c
    \brief I2C driver

    \version 2019-6-5, V1.0.0, firmware for GD32VF103
*/

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

    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 "gd32vf103_i2c.h"

/* I2C register bit mask */
#define I2CCLK_MAX                    ((uint32_t)0x00000048U)             /*!< i2cclk maximum value */
#define I2CCLK_MIN                    ((uint32_t)0x00000002U)             /*!< i2cclk minimum value */
#define I2C_FLAG_MASK                 ((uint32_t)0x0000FFFFU)             /*!< i2c flag mask */
#define I2C_ADDRESS_MASK              ((uint32_t)0x000003FFU)             /*!< i2c address mask */
#define I2C_ADDRESS2_MASK             ((uint32_t)0x000000FEU)             /*!< the second i2c address mask */

/* I2C register bit offset */
#define STAT1_PECV_OFFSET             ((uint32_t)8U)     /* bit offset of PECV in I2C_STAT1 */

/*!
    \brief      reset I2C
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
 */
void i2c_deinit(uint32_t i2c_periph)
{
    switch (i2c_periph) {
    case I2C0:
        /* reset I2C0 */
        rcu_periph_reset_enable(RCU_I2C0RST);
        rcu_periph_reset_disable(RCU_I2C0RST);
        break;
    case I2C1:
        /* reset I2C1 */
        rcu_periph_reset_enable(RCU_I2C1RST);
        rcu_periph_reset_disable(RCU_I2C1RST);
        break;
    default:
        break;
    }
}

/*!
    \brief      configure I2C clock
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  clkspeed: I2C clock speed, supports standard mode (up to 100 kHz), fast mode (up to 400 kHz)
    \param[in]  dutycyc: duty cycle in fast mode
                only one parameter can be selected which is shown as below:
    \arg        I2C_DTCY_2: T_low/T_high=2
    \arg        I2C_DTCY_16_9: T_low/T_high=16/9
    \param[out] none
    \retval     none
 */
void i2c_clock_config(uint32_t i2c_periph, uint32_t clkspeed, uint32_t dutycyc)
{
    uint32_t pclk1, clkc, freq, risetime;
    uint32_t temp;

    pclk1 = rcu_clock_freq_get(CK_APB1);
    /* I2C peripheral clock frequency */
    freq = (uint32_t) (pclk1 / 1000000U);
    if (freq >= I2CCLK_MAX) {
        freq = I2CCLK_MAX;
    }
    temp = I2C_CTL1(i2c_periph);
    temp &= ~I2C_CTL1_I2CCLK;
    temp |= freq;

    I2C_CTL1(i2c_periph) = temp;

    if (100000U >= clkspeed) {
        /* the maximum SCL rise time is 1000ns in standard mode */
        risetime = (uint32_t) ((pclk1 / 1000000U) + 1U);
        if (risetime >= I2CCLK_MAX) {
            I2C_RT(i2c_periph) = I2CCLK_MAX;
        } else if (risetime <= I2CCLK_MIN) {
            I2C_RT(i2c_periph) = I2CCLK_MIN;
        } else {
            I2C_RT(i2c_periph) = risetime;
        }
        clkc = (uint32_t) (pclk1 / (clkspeed * 2U));
        if (clkc < 0x04U) {
            /* the CLKC in standard mode minmum value is 4 */
            clkc = 0x04U;
        }
        I2C_CKCFG(i2c_periph) |= (I2C_CKCFG_CLKC & clkc);

    } else if (400000U >= clkspeed) {
        /* the maximum SCL rise time is 300ns in fast mode */
        I2C_RT(i2c_periph) = (uint32_t) (((freq * (uint32_t) 300U)
                / (uint32_t) 1000U) + (uint32_t) 1U);
        if (I2C_DTCY_2 == dutycyc) {
            /* I2C duty cycle is 2 */
            clkc = (uint32_t) (pclk1 / (clkspeed * 3U));
            I2C_CKCFG(i2c_periph) &= ~I2C_CKCFG_DTCY;
        } else {
            /* I2C duty cycle is 16/9 */
            clkc = (uint32_t) (pclk1 / (clkspeed * 25U));
            I2C_CKCFG(i2c_periph) |= I2C_CKCFG_DTCY;
        }
        if (0U == (clkc & I2C_CKCFG_CLKC)) {
            /* the CLKC in fast mode minmum value is 1 */
            clkc |= 0x0001U;
        }
        I2C_CKCFG(i2c_periph) |= I2C_CKCFG_FAST;
        I2C_CKCFG(i2c_periph) |= clkc;
    } else {
    }
}

/*!
    \brief      configure I2C address
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  mode:
                only one parameter can be selected which is shown as below:
    \arg        I2C_I2CMODE_ENABLE: I2C mode
    \arg        I2C_SMBUSMODE_ENABLE: SMBus mode
    \param[in]  addformat: 7bits or 10bits
                only one parameter can be selected which is shown as below:
    \arg        I2C_ADDFORMAT_7BITS: 7bits
    \arg        I2C_ADDFORMAT_10BITS: 10bits
    \param[in]  addr: I2C address
    \param[out] none
    \retval     none
 */
void i2c_mode_addr_config(uint32_t i2c_periph, uint32_t mode,uint32_t addformat, uint32_t addr)
{
    /* SMBus/I2C mode selected */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_SMBEN);
    ctl |= mode;
    I2C_CTL0(i2c_periph) = ctl;
    /* configure address */
    addr = addr & I2C_ADDRESS_MASK;
    I2C_SADDR0(i2c_periph) = (addformat | addr);
}

/*!
    \brief      SMBus type selection
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  type:
                only one parameter can be selected which is shown as below:
    \arg        I2C_SMBUS_DEVICE: device
    \arg        I2C_SMBUS_HOST: host
    \param[out] none
    \retval     none
 */
void i2c_smbus_type_config(uint32_t i2c_periph, uint32_t type)
{
    if (I2C_SMBUS_HOST == type) {
        I2C_CTL0(i2c_periph) |= I2C_CTL0_SMBSEL;
    } else {
        I2C_CTL0(i2c_periph) &= ~(I2C_CTL0_SMBSEL);
    }
}

/*!
    \brief      whether or not to send an ACK
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  ack:
                only one parameter can be selected which is shown as below:
    \arg        I2C_ACK_ENABLE: ACK will be sent
    \arg        I2C_ACK_DISABLE: ACK will not be sent
    \param[out] none
    \retval     none
 */
void i2c_ack_config(uint32_t i2c_periph, uint32_t ack)
{
    if (I2C_ACK_ENABLE == ack) {
        I2C_CTL0(i2c_periph) |= I2C_CTL0_ACKEN;
    } else {
        I2C_CTL0(i2c_periph) &= ~(I2C_CTL0_ACKEN);
    }
}

/*!
    \brief      configure I2C POAP position
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  pos:
                only one parameter can be selected which is shown as below:
    \arg        I2C_ACKPOS_CURRENT: whether to send ACK or not for the current
    \arg        I2C_ACKPOS_NEXT: whether to send ACK or not for the next byte
    \param[out] none
    \retval     none
 */
void i2c_ackpos_config(uint32_t i2c_periph, uint32_t pos)
{
    /* configure I2C POAP position */
    if (I2C_ACKPOS_NEXT == pos) {
        I2C_CTL0(i2c_periph) |= I2C_CTL0_POAP;
    } else {
        I2C_CTL0(i2c_periph) &= ~(I2C_CTL0_POAP);
    }
}

/*!
    \brief      master sends slave address
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  addr: slave address
    \param[in]  trandirection: transmitter or receiver
                only one parameter can be selected which is shown as below:
    \arg        I2C_TRANSMITTER: transmitter
    \arg        I2C_RECEIVER:    receiver
    \param[out] none
    \retval     none
 */
void i2c_master_addressing(uint32_t i2c_periph, uint32_t addr,uint32_t trandirection)
{
    /* master is a transmitter or a receiver */
    if (I2C_TRANSMITTER == trandirection) {
        addr = addr & I2C_TRANSMITTER;
    } else {
        addr = addr | I2C_RECEIVER;
    }
    /* send slave address */
    I2C_DATA(i2c_periph) = addr;
}

/*!
    \brief      configure I2C saddress1
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  addr: I2C address
    \param[out] none
    \retval     none
*/
void i2c_saddr1_config(uint32_t i2c_periph,uint32_t addr)
{
    /* configure saddress1 */
    I2C_SADDR1(i2c_periph) = (0xFE & addr);
}

/*!
    \brief      enable dual-address mode
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  addr: the second address in dual-address mode
    \param[out] none
    \retval     none
*/
void i2c_dualaddr_enable(uint32_t i2c_periph, uint32_t addr)
{
    /* configure address */
    addr = addr & I2C_ADDRESS2_MASK;
    I2C_SADDR1(i2c_periph) = (I2C_SADDR1_DUADEN | addr);
}

/*!
    \brief      disable dual-address mode
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
*/
void i2c_dualaddr_disable(uint32_t i2c_periph)
{
    I2C_SADDR1(i2c_periph) &= ~(I2C_SADDR1_DUADEN);
}

/*!
    \brief      enable I2C
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
 */
void i2c_enable(uint32_t i2c_periph)
{
    I2C_CTL0(i2c_periph) |= I2C_CTL0_I2CEN;
}

/*!
    \brief      disable I2C
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
 */
void i2c_disable(uint32_t i2c_periph)
{
    I2C_CTL0(i2c_periph) &= ~(I2C_CTL0_I2CEN);
}

/*!
    \brief      generate a START condition on I2C bus
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
 */
void i2c_start_on_bus(uint32_t i2c_periph)
{
    I2C_CTL0(i2c_periph) |= I2C_CTL0_START;
}

/*!
    \brief      generate a STOP condition on I2C bus
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     none
 */
void i2c_stop_on_bus(uint32_t i2c_periph)
{
    I2C_CTL0(i2c_periph) |= I2C_CTL0_STOP;
}

/*!
    \brief      I2C transmit data function
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  data: data of transmission
    \param[out] none
    \retval     none
 */
void i2c_data_transmit(uint32_t i2c_periph, uint8_t data)
{
    I2C_DATA(i2c_periph) = DATA_TRANS(data);
}

/*!
    \brief      I2C receive data function
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     data of received
 */
uint8_t i2c_data_receive(uint32_t i2c_periph)
{
    return (uint8_t) DATA_RECV(I2C_DATA(i2c_periph));
}

/*!
    \brief      enable I2C DMA mode
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  dmastate:
                only one parameter can be selected which is shown as below:
    \arg        I2C_DMA_ON: DMA mode enable
    \arg        I2C_DMA_OFF: DMA mode disable
    \param[out] none
    \retval     none
 */
void i2c_dma_enable(uint32_t i2c_periph, uint32_t dmastate)
{
    /* configure I2C DMA function */
    uint32_t ctl = 0U;

    ctl = I2C_CTL1(i2c_periph);
    ctl &= ~(I2C_CTL1_DMAON);
    ctl |= dmastate;
    I2C_CTL1(i2c_periph) = ctl;
}

/*!
    \brief      configure whether next DMA EOT is DMA last transfer or not
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  dmalast:
                only one parameter can be selected which is shown as below:
    \arg        I2C_DMALST_ON: next DMA EOT is the last transfer
    \arg        I2C_DMALST_OFF: next DMA EOT is not the last transfer
    \param[out] none
    \retval     none
 */
void i2c_dma_last_transfer_config(uint32_t i2c_periph, uint32_t dmalast)
{
    /* configure DMA last transfer */
    uint32_t ctl = 0U;

    ctl = I2C_CTL1(i2c_periph);
    ctl &= ~(I2C_CTL1_DMALST);
    ctl |= dmalast;
    I2C_CTL1(i2c_periph) = ctl;
}

/*!
    \brief      whether to stretch SCL low when data is not ready in slave mode
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  stretchpara:
                only one parameter can be selected which is shown as below:
    \arg        I2C_SCLSTRETCH_ENABLE: SCL stretching is enabled
    \arg        I2C_SCLSTRETCH_DISABLE: SCL stretching is disabled
    \param[out] none
    \retval     none
 */
void i2c_stretch_scl_low_config(uint32_t i2c_periph, uint32_t stretchpara)
{
    /* configure I2C SCL strerching enable or disable */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_SS);
    ctl |= stretchpara;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      whether or not to response to a general call
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  gcallpara:
                only one parameter can be selected which is shown as below:
    \arg        I2C_GCEN_ENABLE: slave will response to a general call
    \arg        I2C_GCEN_DISABLE: slave will not response to a general call
    \param[out] none
    \retval     none
 */
void i2c_slave_response_to_gcall_config(uint32_t i2c_periph, uint32_t gcallpara)
{
    /* configure slave response to a general call enable or disable */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_GCEN);
    ctl |= gcallpara;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      software reset I2C
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  sreset:
                only one parameter can be selected which is shown as below:
    \arg        I2C_SRESET_SET: I2C is under reset
    \arg        I2C_SRESET_RESET: I2C is not under reset
    \param[out] none
    \retval     none
 */
void i2c_software_reset_config(uint32_t i2c_periph, uint32_t sreset)
{
    /* modify CTL0 and configure software reset I2C state */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_SRESET);
    ctl |= sreset;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      I2C PEC calculation on or off
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  pecpara:
                only one parameter can be selected which is shown as below:
    \arg        I2C_PEC_ENABLE: PEC calculation on
    \arg        I2C_PEC_DISABLE: PEC calculation off
    \param[out] none
    \retval     none
 */
void i2c_pec_enable(uint32_t i2c_periph, uint32_t pecstate)
{
    /* on/off PEC calculation */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_PECEN);
    ctl |= pecstate;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      I2C whether to transfer PEC value
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  pecpara:
                only one parameter can be selected which is shown as below:
    \arg        I2C_PECTRANS_ENABLE: transfer PEC
    \arg        I2C_PECTRANS_DISABLE: not transfer PEC
    \param[out] none
    \retval     none
 */
void i2c_pec_transfer_enable(uint32_t i2c_periph, uint32_t pecpara)
{
    /* whether to transfer PEC */
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_PECTRANS);
    ctl |= pecpara;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      get packet error checking value
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[out] none
    \retval     PEC value
 */
uint8_t i2c_pec_value_get(uint32_t i2c_periph)
{
    return (uint8_t) ((I2C_STAT1(i2c_periph) & I2C_STAT1_PECV)>> STAT1_PECV_OFFSET);
}

/*!
    \brief      I2C issue alert through SMBA pin
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  smbuspara:
                only one parameter can be selected which is shown as below:
    \arg        I2C_SALTSEND_ENABLE: issue alert through SMBA pin
    \arg        I2C_SALTSEND_DISABLE: not issue alert through SMBA pin
    \param[out] none
    \retval     none
 */
void i2c_smbus_issue_alert(uint32_t i2c_periph, uint32_t smbuspara)
{
    /* issue alert through SMBA pin configure*/
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_SALT);
    ctl |= smbuspara;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      enable or disable I2C ARP protocol in SMBus switch
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  arpstate:
                only one parameter can be selected which is shown as below:
    \arg        I2C_ARP_ENABLE: enable ARP
    \arg        I2C_ARP_DISABLE: disable ARP
    \param[out] none
    \retval     none
 */
void i2c_smbus_arp_enable(uint32_t i2c_periph, uint32_t arpstate)
{
    /* enable or disable I2C ARP protocol*/
    uint32_t ctl = 0U;

    ctl = I2C_CTL0(i2c_periph);
    ctl &= ~(I2C_CTL0_ARPEN);
    ctl |= arpstate;
    I2C_CTL0(i2c_periph) = ctl;
}

/*!
    \brief      check I2C flag is set or not
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  flag: I2C flags, refer to i2c_flag_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_FLAG_SBSEND: start condition send out
    \arg        I2C_FLAG_ADDSEND: address is sent in master mode or received and matches in slave mode
    \arg        I2C_FLAG_BTC: byte transmission finishes
    \arg        I2C_FLAG_ADD10SEND: header of 10-bit address is sent in master mode
    \arg        I2C_FLAG_STPDET: stop condition detected in slave mode
    \arg        I2C_FLAG_RBNE: I2C_DATA is not Empty during receiving
    \arg        I2C_FLAG_TBE: I2C_DATA is empty during transmitting
    \arg        I2C_FLAG_BERR: a bus error occurs indication a unexpected start or stop condition on I2C bus
    \arg        I2C_FLAG_LOSTARB: arbitration lost in master mode
    \arg        I2C_FLAG_AERR: acknowledge error
    \arg        I2C_FLAG_OUERR: overrun or underrun situation occurs in slave mode
    \arg        I2C_FLAG_PECERR: PEC error when receiving data
    \arg        I2C_FLAG_SMBTO: timeout signal in SMBus mode
    \arg        I2C_FLAG_SMBALT: SMBus alert status
    \arg        I2C_FLAG_MASTER: a flag indicating whether I2C block is in master or slave mode
    \arg        I2C_FLAG_I2CBSY: busy flag
    \arg        I2C_FLAG_TR: whether the I2C is a transmitter or a receiver
    \arg        I2C_FLAG_RXGC: general call address (00h) received
    \arg        I2C_FLAG_DEFSMB: default address of SMBus device
    \arg        I2C_FLAG_HSTSMB: SMBus host header detected in slave mode
    \arg        I2C_FLAG_DUMODF: dual flag in slave mode indicating which address is matched in dual-address mode
    \param[out] none
    \retval     FlagStatus: SET or RESET
 */
FlagStatus i2c_flag_get(uint32_t i2c_periph, i2c_flag_enum flag)
{
    if (RESET != (I2C_REG_VAL(i2c_periph, flag) & BIT(I2C_BIT_POS(flag)))) {
        return SET;
    } else {
        return RESET;
    }
}

/*!
    \brief      clear I2C flag
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  flag: I2C flags, refer to i2c_flag_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_FLAG_SMBALT: SMBus Alert status
    \arg        I2C_FLAG_SMBTO: timeout signal in SMBus mode
    \arg        I2C_FLAG_PECERR: PEC error when receiving data
    \arg        I2C_FLAG_OUERR: over-run or under-run situation occurs in slave mode
    \arg        I2C_FLAG_AERR: acknowledge error
    \arg        I2C_FLAG_LOSTARB: arbitration lost in master mode
    \arg        I2C_FLAG_BERR: a bus error
    \arg        I2C_FLAG_ADDSEND: cleared by reading I2C_STAT0 and reading I2C_STAT1
    \param[out] none
    \retval     none
 */
void i2c_flag_clear(uint32_t i2c_periph, i2c_flag_enum flag)
{
    uint32_t temp;
    if (I2C_FLAG_ADDSEND == flag) {
        /* read I2C_STAT0 and then read I2C_STAT1 to clear ADDSEND */
        temp = I2C_STAT0(i2c_periph);
        temp = I2C_STAT1(i2c_periph);
    } else {
        I2C_REG_VAL(i2c_periph, flag) &= ~BIT(I2C_BIT_POS(flag));
    }
}

/*!
    \brief      enable I2C interrupt
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  interrupt: I2C interrupts, refer to i2c_interrupt_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_INT_ERR: error interrupt enable
    \arg        I2C_INT_EV: event interrupt enable
    \arg        I2C_INT_BUF: buffer interrupt enable
    \param[out] none
    \retval     none
 */
void i2c_interrupt_enable(uint32_t i2c_periph, i2c_interrupt_enum interrupt)
{
    I2C_REG_VAL(i2c_periph, interrupt) |= BIT(I2C_BIT_POS(interrupt));
}

/*!
    \brief      disable I2C interrupt
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  interrupt: I2C interrupts, refer to i2c_flag_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_INT_ERR: error interrupt enable
    \arg        I2C_INT_EV: event interrupt enable
    \arg        I2C_INT_BUF: buffer interrupt enable
    \param[out] none
    \retval     none
 */
void i2c_interrupt_disable(uint32_t i2c_periph, i2c_interrupt_enum interrupt)
{
    I2C_REG_VAL(i2c_periph, interrupt) &= ~BIT(I2C_BIT_POS(interrupt));
}

/*!
    \brief      check I2C interrupt flag
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  int_flag: I2C interrupt flags, refer to i2c_interrupt_flag_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_INT_FLAG_SBSEND: start condition sent out in master mode interrupt flag
    \arg        I2C_INT_FLAG_ADDSEND: address is sent in master mode or received and matches in slave mode interrupt flag
    \arg        I2C_INT_FLAG_BTC: byte transmission finishes
    \arg        I2C_INT_FLAG_ADD10SEND: header of 10-bit address is sent in master mode interrupt flag
    \arg        I2C_INT_FLAG_STPDET: etop condition detected in slave mode interrupt flag
    \arg        I2C_INT_FLAG_RBNE: I2C_DATA is not Empty during receiving interrupt flag
    \arg        I2C_INT_FLAG_TBE: I2C_DATA is empty during transmitting interrupt flag
    \arg        I2C_INT_FLAG_BERR: a bus error occurs indication a unexpected start or stop condition on I2C bus interrupt flag
    \arg        I2C_INT_FLAG_LOSTARB: arbitration lost in master mode interrupt flag
    \arg        I2C_INT_FLAG_AERR: acknowledge error interrupt flag
    \arg        I2C_INT_FLAG_OUERR: over-run or under-run situation occurs in slave mode interrupt flag
    \arg        I2C_INT_FLAG_PECERR: PEC error when receiving data interrupt flag
    \arg        I2C_INT_FLAG_SMBTO: timeout signal in SMBus mode interrupt flag
    \arg        I2C_INT_FLAG_SMBALT: SMBus Alert status interrupt flag
    \param[out] none
    \retval     FlagStatus: SET or RESET
 */
FlagStatus i2c_interrupt_flag_get(uint32_t i2c_periph,i2c_interrupt_flag_enum int_flag)
{
    uint32_t intenable = 0U, flagstatus = 0U, bufie;

    /* check BUFIE */
    bufie = I2C_CTL1(i2c_periph) & I2C_CTL1_BUFIE;

    /* get the interrupt enable bit status */
    intenable = (I2C_REG_VAL(i2c_periph, int_flag) & BIT(I2C_BIT_POS(int_flag)));
    /* get the corresponding flag bit status */
    flagstatus = (I2C_REG_VAL2(i2c_periph, int_flag)& BIT(I2C_BIT_POS2(int_flag)));

    if ((I2C_INT_FLAG_RBNE == int_flag) || (I2C_INT_FLAG_TBE == int_flag)) {
        if (intenable && bufie) {
            intenable = 1U;
        } else {
            intenable = 0U;
        }
    }
    if ((0U != flagstatus) && (0U != intenable)) {
        return SET;
    } else {
        return RESET;
    }
}

/*!
    \brief      clear I2C interrupt flag
    \param[in]  i2c_periph: I2Cx(x=0,1)
    \param[in]  int_flag: I2C interrupt flags, refer to i2c_interrupt_flag_enum
                only one parameter can be selected which is shown as below:
    \arg        I2C_INT_FLAG_ADDSEND: address is sent in master mode or received and matches in slave mode interrupt flag
    \arg        I2C_INT_FLAG_BERR: a bus error occurs indication a unexpected start or stop condition on I2C bus interrupt flag
    \arg        I2C_INT_FLAG_LOSTARB: arbitration lost in master mode interrupt flag
    \arg        I2C_INT_FLAG_AERR: acknowledge error interrupt flag
    \arg        I2C_INT_FLAG_OUERR: over-run or under-run situation occurs in slave mode interrupt flag
    \arg        I2C_INT_FLAG_PECERR: PEC error when receiving data interrupt flag
    \arg        I2C_INT_FLAG_SMBTO: timeout signal in SMBus mode interrupt flag
    \arg        I2C_INT_FLAG_SMBALT: SMBus Alert status interrupt flag
    \param[out] none
    \retval     none
 */
void i2c_interrupt_flag_clear(uint32_t i2c_periph,i2c_interrupt_flag_enum int_flag)
{
    uint32_t temp;
    if (I2C_INT_FLAG_ADDSEND == int_flag) {
        /* read I2C_STAT0 and then read I2C_STAT1 to clear ADDSEND */
        temp = I2C_STAT0(i2c_periph);
        temp = I2C_STAT1(i2c_periph);
    } else {
        I2C_REG_VAL2(i2c_periph, int_flag) &= ~BIT(I2C_BIT_POS2(int_flag));
    }
}


text:
package cn.edu.chd.yitu;

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

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import cn.edu.chd.adapter.YiImageAdapter;
import cn.edu.chd.utils.YiUtils;
import cn.edu.chd.values.ApplicationValues;

/**
 * @author Rowand jj
 * 	 "ÎÒµÄ×÷Æ·"Ñ¡Ï ÉúÃüÖÜÆÚ£ºonCreate->onCreateView
 */
public class TabMyWorks extends Fragment
{
	/**
	 * ÊÇ·ñÓÐ×÷Æ·
	 */
	public boolean has_works;
	private GridView mGridView = null;
	private static final int DEFAULT_WIDTH = 140;//ĬÈÏ¿í¶È
	private static final int DEFAULT_HEIGHT = 170;//ĬÈϸ߶È
	private static final String TAG = "TabMyWorks";
	public static final String POSITION = "position";
	/**
	 * ×÷Æ·Îļþ¼ÐϵÄͼƬÃû
	 */
	private List<String> imageNames;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		has_works = getImageNames().size()==0 ? false : true;//ÅжÏÖ¸¶¨Îļþ¼ÐÖÐÊÇ·ñÓÐÎļþ´æÔÚ
		if (has_works)
		{
			imageNames = getImageNames();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		View view = null;
		if (has_works)
		{
			view = inflater.inflate(R.layout.layout_tab_mine, null);
			mGridView = (GridView) view.findViewById(R.id.grid_view_tab_mine_works);
		} else
		{
			view = inflater.inflate(R.layout.layout_tab_mine_noworks, null);
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		if (has_works)
		{
			loadImage();
			mGridView.setOnItemClickListener(new OnItemClickListener()
			{
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id)
				{
					//TODO ä¯ÀÀ
					Intent intent = new Intent(TabMyWorks.this.getActivity(),BrowseWorks.class);
					intent.putExtra(POSITION,position+"");
					TabMyWorks.this.startActivity(intent);

				}
			});
			registerForContextMenu(mGridView);//×¢²áÉÏÏÂÎIJ˵¥
		}
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo)
	{
		//´´½¨ÉÏÏÂÎIJ˵¥
		super.onCreateContextMenu(menu, v, menuInfo);
		getActivity().getMenuInflater().inflate(R.menu.menu_works_item_selected, menu);
	}
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();//ÐèÒªÏòÏÂתÐÍ
		switch (item.getItemId())
		{
		case R.id.id_menu_works_delete:
			delete(info.position);
			return true;
		case R.id.id_menu_works_edit:
			edit(info.position);
			return true;
		default:
			return super.onContextItemSelected(item);
		}

	}

	/**
	 * ɾ³ý×÷Æ·
	 */
	private void delete(int position)
	{
		String fileName = imageNames.get(position);
		new File(fileName).delete();

		ChooseModel activity = (ChooseModel) getActivity();
		activity.getAdapter().reLoad();
	}

	/**
	 * ±à¼×÷Æ·
	 * @param position
	 */
	private void edit(int position)
	{
		Intent intent = new Intent(getActivity(),CanvasPreview.class);
		intent.putExtra(ApplicationValues.Base.PREVIEW_TYPE, ApplicationValues.Base.TYPE_MY_WORKS);
		intent.putExtra(TabDIY.IMAGE_DATA,imageNames.get(position));
		startActivity(intent);
	}
	/**
	 * »ñÈ¡Ö¸¶¨Îļþ¼ÐϵÄ×÷ƷͼƬÃû³Æ¼¯ºÏ
	 *
	 * @return
	 */
	private List<String> getImageNames()
	{
		String dir = null;
		List<String> imageNames = new ArrayList<String>();//·ÀÖ¹nullÖ¸Õë
		if (YiUtils.isSDCardAvailable())
		{
			dir = Environment.getExternalStorageDirectory().getAbsolutePath()+ ApplicationValues.Base.SAVE_PATH;
			String[] temp1 = YiUtils.traverseImages(dir);
			if (temp1 != null)
				imageNames = new ArrayList<String>(Arrays.asList(temp1));
		}
		dir = Environment.getDataDirectory().getAbsolutePath()+ ApplicationValues.Base.SAVE_PATH;
		String[] temp2 = YiUtils.traverseImages(dir);
		if (temp2 != null)
		{
			for (String str : temp2)
			{
				imageNames.add(str);
			}
		}
		Log.i(TAG,"---------->GET_IMAGE_NAMES RUN,NUM = "+imageNames.size());
		return imageNames;
	}

	/**
	 * ¼ÓÔØͼƬ²¢ÏÔʾµ½GridViewÉÏ
	 */
	private void loadImage()
	{
		Point point = new Point(DEFAULT_WIDTH,DEFAULT_HEIGHT);
		mGridView.setAdapter(new YiImageAdapter(getActivity(), imageNames, mGridView, point));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package btcec

import (
	"crypto/ecdsa"
	"errors"
	"fmt"
	"math/big"
)

// These constants define the lengths of serialized public keys.
const (
	PubKeyBytesLenCompressed   = 33
	PubKeyBytesLenUncompressed = 65
	PubKeyBytesLenHybrid       = 65
)

func isOdd(a *big.Int) bool {
	return a.Bit(0) == 1
}

// decompressPoint decompresses a point on the secp256k1 curve given the X point and
// the solution to use.
func decompressPoint(curve *KoblitzCurve, bigX *big.Int, ybit bool) (*big.Int, error) {
	var x fieldVal
	x.SetByteSlice(bigX.Bytes())

	// Compute x^3 + B mod p.
	var x3 fieldVal
	x3.SquareVal(&x).Mul(&x)
	x3.Add(curve.fieldB).Normalize()

	// Now calculate sqrt mod p of x^3 + B
	// This code used to do a full sqrt based on tonelli/shanks,
	// but this was replaced by the algorithms referenced in
	// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294
	var y fieldVal
	y.SqrtVal(&x3).Normalize()
	if ybit != y.IsOdd() {
		y.Negate(1).Normalize()
	}

	// Check that y is a square root of x^3 + B.
	var y2 fieldVal
	y2.SquareVal(&y).Normalize()
	if !y2.Equals(&x3) {
		return nil, fmt.Errorf("invalid square root")
	}

	// Verify that y-coord has expected parity.
	if ybit != y.IsOdd() {
		return nil, fmt.Errorf("ybit doesn't match oddness")
	}

	return new(big.Int).SetBytes(y.Bytes()[:]), nil
}

const (
	pubkeyCompressed   byte = 0x2 // y_bit + x coord
	pubkeyUncompressed byte = 0x4 // x coord + y coord
	pubkeyHybrid       byte = 0x6 // y_bit + x coord + y coord
)

// IsCompressedPubKey returns true the the passed serialized public key has
// been encoded in compressed format, and false otherwise.
func IsCompressedPubKey(pubKey []byte) bool {
	// The public key is only compressed if it is the correct length and
	// the format (first byte) is one of the compressed pubkey values.
	return len(pubKey) == PubKeyBytesLenCompressed &&
		(pubKey[0]&^byte(0x1) == pubkeyCompressed)
}

// ParsePubKey parses a public key for a koblitz curve from a bytestring into a
// ecdsa.Publickey, verifying that it is valid. It supports compressed,
// uncompressed and hybrid signature formats.
func ParsePubKey(pubKeyStr []byte, curve *KoblitzCurve) (key *PublicKey, err error) {
	pubkey := PublicKey{}
	pubkey.Curve = curve

	if len(pubKeyStr) == 0 {
		return nil, errors.New("pubkey string is empty")
	}

	format := pubKeyStr[0]
	ybit := (format & 0x1) == 0x1
	format &= ^byte(0x1)

	switch len(pubKeyStr) {
	case PubKeyBytesLenUncompressed:
		if format != pubkeyUncompressed && format != pubkeyHybrid {
			return nil, fmt.Errorf("invalid magic in pubkey str: "+
				"%d", pubKeyStr[0])
		}

		pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])
		pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:])
		// hybrid keys have extra information, make use of it.
		if format == pubkeyHybrid && ybit != isOdd(pubkey.Y) {
			return nil, fmt.Errorf("ybit doesn't match oddness")
		}

		if pubkey.X.Cmp(pubkey.Curve.Params().P) >= 0 {
			return nil, fmt.Errorf("pubkey X parameter is >= to P")
		}
		if pubkey.Y.Cmp(pubkey.Curve.Params().P) >= 0 {
			return nil, fmt.Errorf("pubkey Y parameter is >= to P")
		}
		if !pubkey.Curve.IsOnCurve(pubkey.X, pubkey.Y) {
			return nil, fmt.Errorf("pubkey isn't on secp256k1 curve")
		}

	case PubKeyBytesLenCompressed:
		// format is 0x2 | solution, <X coordinate>
		// solution determines which solution of the curve we use.
		/// y^2 = x^3 + Curve.B
		if format != pubkeyCompressed {
			return nil, fmt.Errorf("invalid magic in compressed "+
				"pubkey string: %d", pubKeyStr[0])
		}
		pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33])
		pubkey.Y, err = decompressPoint(curve, pubkey.X, ybit)
		if err != nil {
			return nil, err
		}

	default: // wrong!
		return nil, fmt.Errorf("invalid pub key length %d",
			len(pubKeyStr))
	}

	return &pubkey, nil
}

// PublicKey is an ecdsa.PublicKey with additional functions to
// serialize in uncompressed, compressed, and hybrid formats.
type PublicKey ecdsa.PublicKey

// ToECDSA returns the public key as a *ecdsa.PublicKey.
func (p *PublicKey) ToECDSA() *ecdsa.PublicKey {
	return (*ecdsa.PublicKey)(p)
}

// SerializeUncompressed serializes a public key in a 65-byte uncompressed
// format.
func (p *PublicKey) SerializeUncompressed() []byte {
	b := make([]byte, 0, PubKeyBytesLenUncompressed)
	b = append(b, pubkeyUncompressed)
	b = paddedAppend(32, b, p.X.Bytes())
	return paddedAppend(32, b, p.Y.Bytes())
}

// SerializeCompressed serializes a public key in a 33-byte compressed format.
func (p *PublicKey) SerializeCompressed() []byte {
	b := make([]byte, 0, PubKeyBytesLenCompressed)
	format := pubkeyCompressed
	if isOdd(p.Y) {
		format |= 0x1
	}
	b = append(b, format)
	return paddedAppend(32, b, p.X.Bytes())
}

// SerializeHybrid serializes a public key in a 65-byte hybrid format.
func (p *PublicKey) SerializeHybrid() []byte {
	b := make([]byte, 0, PubKeyBytesLenHybrid)
	format := pubkeyHybrid
	if isOdd(p.Y) {
		format |= 0x1
	}
	b = append(b, format)
	b = paddedAppend(32, b, p.X.Bytes())
	return paddedAppend(32, b, p.Y.Bytes())
}

// IsEqual compares this PublicKey instance to the one passed, returning true if
// both PublicKeys are equivalent. A PublicKey is equivalent to another, if they
// both have the same X and Y coordinate.
func (p *PublicKey) IsEqual(otherPubKey *PublicKey) bool {
	return p.X.Cmp(otherPubKey.X) == 0 &&
		p.Y.Cmp(otherPubKey.Y) == 0
}

// paddedAppend appends the src byte slice to dst, returning the new slice.
// If the length of the source is smaller than the passed size, leading zero
// bytes are appended to the dst slice before appending src.
func paddedAppend(size uint, dst, src []byte) []byte {
	for i := 0; i < int(size)-len(src); i++ {
		dst = append(dst, 0)
	}
	return append(dst, src...)
}


text:
from evelink import api

class EVE(object):
    """Wrapper around /eve/ of the EVE API."""

    @api.auto_api
    def __init__(self, api=None):
        self.api = api

    @api.auto_call('eve/CharacterName', map_params={'id_list': 'IDs'})
    def character_names_from_ids(self, id_list, api_result=None):
        """Retrieve a dict mapping character IDs to names.

        id_list:
            A list of ids to retrieve names.

        NOTE: *ALL* character IDs passed to this function
        must be valid - an invalid character ID will cause
        the entire call to fail.
        """

        if api_result is None:
            # The API doesn't actually tell us which character IDs are invalid
            msg = "One or more of these character IDs are invalid: %r"
            raise ValueError(msg % id_list)

        rowset = api_result.result.find('rowset')
        rows = rowset.findall('row')

        results = {}
        for row in rows:
            name = row.attrib['name']
            char_id = int(row.attrib['characterID'])
            results[char_id] = name

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    def character_name_from_id(self, char_id):
        """Retrieve the character's name based on ID.

        Convenience wrapper around character_names_from_ids().
        """
        api_result = self.character_names_from_ids([char_id])
        return api.APIResult(api_result.result.get(char_id), api_result.timestamp, api_result.expires)

    @api.auto_call('eve/CharacterID', map_params={'name_list': 'names'})
    def character_ids_from_names(self, name_list, api_result=None):
        """Retrieve a dict mapping character names to IDs.

        name_list:
            A list of names to retrieve character IDs.

        Names of unknown characters will map to None.
        """

        rowset = api_result.result.find('rowset')
        rows = rowset.findall('row')

        results = {}
        for row in rows:
            name = row.attrib['name']
            char_id = int(row.attrib['characterID']) or None
            results[name] = char_id

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    def character_id_from_name(self, name):
        """Retrieve the named character's ID.

        Convenience wrapper around character_ids_from_names().
        """
        api_result = self.character_ids_from_names([name])
        return api.APIResult(list(api_result.result.values())[0], api_result.timestamp, api_result.expires)

    @api.auto_call('eve/CharacterAffiliation', map_params={'id_list': 'ids'})
    def affiliations_for_characters(self, id_list, api_result=None):
        """Retrieve the affiliations for a set of character IDs, returned as a dictionary.

        name_list:
            A list of names to retrieve IDs for.

        IDs for anything not a character will be returned with a name, but nothing else.
        """

        rowset = api_result.result.find('rowset')
        rows = rowset.findall('row')

        results = {}
        for row in rows:
            char_id = int(row.attrib['characterID'])
            char_name = row.attrib['characterName']
            corp_id = int(row.attrib['corporationID']) or None
            corp_name = row.attrib['corporationName'] or None
            faction_id = int(row.attrib['factionID']) or None
            faction_name = row.attrib['factionName'] or None
            alliance_id = int(row.attrib['allianceID']) or None
            alliance_name = row.attrib['allianceName'] or None
            results[char_id] = {
                'id': char_id,
                'name': char_name,
                'corp': {
                    'id': corp_id,
                    'name': corp_name
                }
            }

            if faction_id is not None:
                results[char_id]['faction'] = {
                    'id': faction_id,
                    'name': faction_name
                }

            if alliance_id is not None:
                results[char_id]['alliance'] = {
                    'id': alliance_id,
                    'name': alliance_name
                }

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    def affiliations_for_character(self, char_id):
        """Retrieve the affiliations of a single character

        Convenience wrapper around owner_ids_from_names().
        """

        api_result = self.affiliations_for_characters([char_id])
        return api.APIResult(api_result.result[char_id], api_result.timestamp, api_result.expires)

    @api.auto_call('eve/CharacterInfo', map_params={'char_id': 'characterID'})
    def character_info_from_id(self, char_id, api_result=None):
        """Retrieve a dict of info about the designated character."""
        if api_result is None:
            raise ValueError("Unable to fetch info for character %r" % char_id)

        _str, _int, _float, _bool, _ts = api.elem_getters(api_result.result)

        results = {
            'id': _int('characterID'),
            'name': _str('characterName'),
            'race': _str('race'),
            'bloodline': _str('bloodline'),
            'sec_status': _float('securityStatus'),
            'skillpoints': _int('skillPoints'),
            'location': _str('lastKnownLocation'),
            'isk': _float('accountBalance'),

            'corp': {
                'id': _int('corporationID'),
                'name': _str('corporation'),
                'timestamp': _ts('corporationDate'),
            },

            'alliance': {
                'id': _int('allianceID'),
                'name': _str('alliance'),
                'timestamp': _ts('allianceDate'),
            },

            'ship': {
                'name': _str('shipName'),
                'type_id': _int('shipTypeID'),
                'type_name': _str('shipTypeName'),
            },

            'history': [],
        }

        # Add in corp history
        history = api_result.result.find('rowset')
        for row in history.findall('row'):
            corp_id = int(row.attrib['corporationID'])
            corp_name = row.attrib['corporationName']
            start_date = api.parse_ts(row.attrib['startDate'])
            results['history'].append({
                    'corp_id': corp_id,
                    'corp_name': corp_name,
                    'start_ts': start_date,
                })

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/AllianceList')
    def alliances(self, api_result=None):
        """Return a dict of all alliances in EVE."""
        results = {}
        rowset = api_result.result.find('rowset')
        for row in rowset.findall('row'):
            alliance = {
                'name': row.attrib['name'],
                'ticker': row.attrib['shortName'],
                'id': int(row.attrib['allianceID']),
                'executor_id': int(row.attrib['executorCorpID']),
                'member_count': int(row.attrib['memberCount']),
                'timestamp': api.parse_ts(row.attrib['startDate']),
                'member_corps': {},
            }

            corp_rowset = row.find('rowset')
            for corp_row in corp_rowset.findall('row'):
                corp_id = int(corp_row.attrib['corporationID'])
                corp_ts = api.parse_ts(corp_row.attrib['startDate'])
                alliance['member_corps'][corp_id] = {
                    'id': corp_id,
                    'timestamp': corp_ts,
                }

            results[alliance['id']] = alliance

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/ErrorList')
    def errors(self, api_result=None):
        """Return a mapping of error codes to messages."""
        rowset = api_result.result.find('rowset')
        results = {}
        for row in rowset.findall('row'):
            code = int(row.attrib['errorCode'])
            message = row.attrib['errorText']
            results[code] = message

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/FacWarStats')
    def faction_warfare_stats(self, api_result=None):
        """Return various statistics from Faction Warfare."""
        totals = api_result.result.find('totals')
        rowsets = dict((r.attrib['name'], r) for r in api_result.result.findall('rowset'))

        _str, _int, _float, _bool, _ts = api.elem_getters(totals)
        results = {
            'kills': {
                'yesterday': _int('killsYesterday'),
                'week': _int('killsLastWeek'),
                'total': _int('killsTotal'),
            },
            'points': {
                'yesterday': _int('victoryPointsYesterday'),
                'week': _int('victoryPointsLastWeek'),
                'total': _int('victoryPointsTotal'),
            },
            'factions': {},
            'wars': [],
        }

        for row in rowsets['factions'].findall('row'):
            a = row.attrib
            faction = {
                'id': int(a['factionID']),
                'name': a['factionName'],
                'pilots': int(a['pilots']),
                'systems': int(a['systemsControlled']),
                'kills': {
                    'yesterday': int(a['killsYesterday']),
                    'week': int(a['killsLastWeek']),
                    'total': int(a['killsTotal']),
                },
                'points': {
                    'yesterday': int(a['victoryPointsYesterday']),
                    'week': int(a['victoryPointsLastWeek']),
                    'total': int(a['victoryPointsTotal']),
                },
            }
            results['factions'][faction['id']] = faction

        for row in rowsets['factionWars'].findall('row'):
            a = row.attrib
            war = {
                'faction': {
                    'id': int(a['factionID']),
                    'name': a['factionName'],
                },
                'against': {
                    'id': int(a['againstID']),
                    'name': a['againstName'],
                },
            }
            results['wars'].append(war)

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/SkillTree')
    def skill_tree(self, api_result=None):
        """Return a dict of all available skill groups."""
        rowset = api_result.result.find('rowset') # skillGroups

        results = {}
        name_cache = {}
        for row in rowset.findall('row'):

            # the skill group data
            g = row.attrib
            group = {
                'id': int(g['groupID']),
                'name': g['groupName'],
                'skills': {}
                }
            # Because :ccp: groups can sometimes be listed
            # multiple times with different skills, and the
            # correct result is to add the contents together
            group = results.get(group['id'], group)

            # now get the actual skill data
            skills_rs = row.find('rowset') # skills
            for skill_row in skills_rs.findall('row'):
                a = skill_row.attrib
                _str, _int, _float, _bool, _ts = api.elem_getters(skill_row)

                req_attrib = skill_row.find('requiredAttributes')

                skill = {
                    'id': int(a['typeID']),
                    'group_id': int(a['groupID']),
                    'name': a['typeName'],
                    'published': (a['published'] == '1'),
                    'description': _str('description'),
                    'rank': _int('rank'),
                    'required_skills': {},
                    'bonuses': {},
                    'attributes': {
                        'primary': api.get_named_value(req_attrib, 'primaryAttribute'),
                        'secondary': api.get_named_value(req_attrib, 'secondaryAttribute'),
                        }
                    }

                name_cache[skill['id']] = skill['name']

                # Check each rowset inside the skill, and branch based on the name attribute
                for sub_rs in skill_row.findall('rowset'):

                    if sub_rs.attrib['name'] == 'requiredSkills':
                        for sub_row in sub_rs.findall('row'):
                            b = sub_row.attrib
                            req = {
                                'level': int(b['skillLevel']),
                                'id': int(b['typeID']),
                                }
                            skill['required_skills'][req['id']] = req

                    elif sub_rs.attrib['name'] == 'skillBonusCollection':
                        for sub_row in sub_rs.findall('row'):
                            b = sub_row.attrib
                            bonus = {
                                'type': b['bonusType'],
                                'value': float(b['bonusValue']),
                                }
                            skill['bonuses'][bonus['type']] = bonus

                group['skills'][skill['id']] = skill

            results[group['id']] = group

        # Second pass to fill in required skill names
        for group in results.values():
            for skill in group['skills'].values():
                for skill_id, skill_info in skill['required_skills'].items():
                    skill_info['name'] = name_cache.get(skill_id)

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/RefTypes')
    def reference_types(self, api_result=None):
        """Return a dict containing id -> name reference type mappings."""
        rowset = api_result.result.find('rowset')

        results = {}
        for row in rowset.findall('row'):
            a = row.attrib
            results[int(a['refTypeID'])] = a['refTypeName']

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/FacWarTopStats')
    def faction_warfare_leaderboard(self, api_result=None):
        """Return top-100 lists from Faction Warfare."""

        def parse_top_100(rowset, prefix, attr, attr_name):
            top100 = []
            id_field = '%sID' % prefix
            name_field = '%sName' % prefix
            for row in rowset.findall('row'):
                a = row.attrib
                top100.append({
                    'id': int(a[id_field]),
                    'name': a[name_field],
                    attr_name: int(a[attr]),
                })
            return top100

        def parse_section(section, prefix):
            section_result = {}
            rowsets = dict((r.attrib['name'], r) for r in section.findall('rowset'))

            section_result['kills'] = {
                'yesterday': parse_top_100(rowsets['KillsYesterday'], prefix, 'kills', 'kills'),
                'week': parse_top_100(rowsets['KillsLastWeek'], prefix, 'kills', 'kills'),
                'total': parse_top_100(rowsets['KillsTotal'], prefix, 'kills', 'kills'),
            }

            section_result['points'] = {
                'yesterday': parse_top_100(rowsets['VictoryPointsYesterday'],
                    prefix, 'victoryPoints', 'points'),
                'week': parse_top_100(rowsets['VictoryPointsLastWeek'],
                    prefix, 'victoryPoints', 'points'),
                'total': parse_top_100(rowsets['VictoryPointsTotal'],
                    prefix, 'victoryPoints', 'points'),
            }

            return section_result

        results = {
            'char': parse_section(api_result.result.find('characters'), 'character'),
            'corp': parse_section(api_result.result.find('corporations'), 'corporation'),
            'faction': parse_section(api_result.result.find('factions'), 'faction'),
        }

        return api.APIResult(results, api_result.timestamp, api_result.expires)

    @api.auto_call('eve/ConquerableStationlist')
    def conquerable_stations(self, api_result=None):
        results = {}
        rowset = api_result.result.find('rowset')
        for row in rowset.findall('row'):
            station = {
                'id': int(row.attrib['stationID']),
                'name': row.attrib['stationName'],
                'type_id': int(row.attrib['stationTypeID']),
                'system_id': int(row.attrib['solarSystemID']),
                'corp': {
                    'id': int(row.attrib['corporationID']),
                    'name': row.attrib['corporationName'] }
                }
            results[station['id']] = station

        return api.APIResult(results, api_result.timestamp, api_result.expires)

# vim: set ts=4 sts=4 sw=4 et:


text:
package com.gs.fw.common.mithra.test.domain.dated;

public class NotDatedTable extends NotDatedTableAbstract
{
}


text:
import pytest

from django.core.urlresolvers import reverse

from .utils import render_for_test_user

@pytest.mark.django_db
def test_with_user(simple_content, user, user_noauth):
    t = ("{% tinycontent 'foobar' %}"
         "Text if empty."
         "{% endtinycontent %}")

    assert "This is a test." == render_for_test_user(t, user_noauth)

    root_edit_url = reverse('admin:tinycontent_tinycontent_change',
                            args=[simple_content.pk, ])

    rendered = render_for_test_user(t, user)
    assert root_edit_url in rendered
    assert 'Edit' in rendered
    assert "This is a test." in rendered

    t = "{% tinycontent_simple 'foobar' %}"
    rendered = render_for_test_user(t, user)
    assert root_edit_url in rendered
    assert 'Edit' in rendered
    assert "This is a test." in rendered

@pytest.mark.django_db
def test_with_user_for_nonexistent_tag(simple_content, user, user_noauth):
    t = ("{% tinycontent 'notthere' %}"
         "Text if empty."
         "{% endtinycontent %}")

    assert "Text if empty." == render_for_test_user(t, user_noauth)

    root_add_url = reverse('admin:tinycontent_tinycontent_add')

    rendered = render_for_test_user(t, user)
    assert '%s?name=notthere' % root_add_url in rendered
    assert 'Add' in rendered
    assert "Text if empty." in rendered

    t = "{% tinycontent_simple 'notthere' %}"
    rendered = render_for_test_user(t, user)
    assert '%s?name=notthere' % root_add_url in rendered
    assert 'Add' in rendered


text:
/*	$NetBSD: arcsisabr.c,v 1.1 2001/06/13 15:03:25 soda Exp $	*/
/*	$OpenBSD: isabus.c,v 1.15 1998/03/16 09:38:46 pefo Exp $	*/
/*	NetBSD: isa.c,v 1.33 1995/06/28 04:30:51 cgd Exp 	*/

/*-
 * Copyright (c) 1995 Per Fogelstrom
 * Copyright (c) 1993, 1994 Charles M. Hannum.
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * William Jolitz and Don Ahn.
 *
 * 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. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
 *
 *	@(#)isa.c	7.2 (Berkeley) 5/12/91
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>

#include <machine/autoconf.h>
#include <machine/bus.h>
#include <machine/platform.h>

#include <dev/isa/isavar.h>

#include <arc/isa/isabrvar.h>

/* Definition of the driver for autoconfig. */
int	arcsisabrmatch(struct device *, struct cfdata *, void *);
void	arcsisabrattach(struct device *, struct device *, void *);
int	arcsisabr_iointr(unsigned mask, struct clockframe *cf);

struct cfattach arcsisabr_ca = {
	sizeof(struct isabr_softc), arcsisabrmatch, arcsisabrattach
};
extern struct cfdriver arcsisabr_cd;

int
arcsisabrmatch(parent, match, aux)
	struct device *parent;
	struct cfdata *match;
	void *aux;
{
	struct confargs *ca = aux;

        /* Make sure that we're looking for a ARCSISABR. */
        if (strcmp(ca->ca_name, arcsisabr_cd.cd_name) != 0)
                return (0);

	return (1);
}

void
arcsisabrattach(parent, self, aux)
	struct device *parent;
	struct device *self;
	void *aux;
{
	struct isabr_softc *sc = (struct isabr_softc *)self;

	isadma_bounce_tag_init(&sc->sc_dmat);
	(*platform->set_intr)(MIPS_INT_MASK_2, isabr_iointr, 2);

	isabrattach(sc);
}


text:
package com.comze.sanman00.lang;

@FunctionalInterface
public interface ISyntax {
    public void parseSyntax0(String code) throws SyntaxError;
}


text:
<?php

declare(strict_types=1);

namespace Linio\Component\Input\Exception;

class RequiredFieldException extends \RuntimeException
{
    /**
     * @var string
     */
    protected $field;

    public function __construct(string $field)
    {
        $this->field = $field;
    }

    public function getField(): string
    {
        return $this->field;
    }
}


text: return require('3scale_referrer')


text:
package org.apache.pulsar.client.api;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.pulsar.client.api.PulsarClientException.UnsupportedAuthenticationException;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;

/**
 * Class used to specify client side configuration like authentication, etc..
 *
 * @deprecated Use {@link PulsarClient#builder()} to construct and configure a new {@link PulsarClient} instance
 */
@Deprecated
public class ClientConfiguration implements Serializable {

    private static final long serialVersionUID = 1L;

    private final ClientConfigurationData confData = new ClientConfigurationData();

    /**
     * @return the authentication provider to be used
     */
    public Authentication getAuthentication() {
        return confData.getAuthentication();
    }

    /**
     * Set the authentication provider to use in the Pulsar client instance.
     *

     * Example:
     *

     *
     *

     *
     * ClientConfiguration confData = new ClientConfiguration();
     * String authPluginClassName = "org.apache.pulsar.client.impl.auth.MyAuthentication";
     * String authParamsString = "key1:val1,key2:val2";
     * Authentication auth = AuthenticationFactory.create(authPluginClassName, authParamsString);
     * confData.setAuthentication(auth);
     * PulsarClient client = PulsarClient.create(serviceUrl, confData);
     * ....
     *
     *

     *
     * @param authentication
     */
    public void setAuthentication(Authentication authentication) {
        confData.setAuthentication(authentication);
    }

    /**
     * Set the authentication provider to use in the Pulsar client instance.
     *

     * Example:
     *

     *
     *

     *
     * ClientConfiguration confData = new ClientConfiguration();
     * String authPluginClassName = "org.apache.pulsar.client.impl.auth.MyAuthentication";
     * String authParamsString = "key1:val1,key2:val2";
     * confData.setAuthentication(authPluginClassName, authParamsString);
     * PulsarClient client = PulsarClient.create(serviceUrl, confData);
     * ....
     *
     *

     *
     * @param authPluginClassName
     *            name of the Authentication-Plugin you want to use
     * @param authParamsString
     *            string which represents parameters for the Authentication-Plugin, e.g., "key1:val1,key2:val2"
     * @throws UnsupportedAuthenticationException
     *             failed to instantiate specified Authentication-Plugin
     */
    public void setAuthentication(String authPluginClassName, String authParamsString)
            throws UnsupportedAuthenticationException {
        confData.setAuthentication(AuthenticationFactory.create(authPluginClassName, authParamsString));
    }

    /**
     * Set the authentication provider to use in the Pulsar client instance.
     *

     * Example:
     *

     *
     *

     *
     * ClientConfiguration confData = new ClientConfiguration();
     * String authPluginClassName = "org.apache.pulsar.client.impl.auth.MyAuthentication";
     * Map<String, String> authParams = new HashMap<String, String>();
     * authParams.put("key1", "val1");
     * confData.setAuthentication(authPluginClassName, authParams);
     * PulsarClient client = PulsarClient.create(serviceUrl, confData);
     * ....
     *
     *

     *
     * @param authPluginClassName
     *            name of the Authentication-Plugin you want to use
     * @param authParams
     *            map which represents parameters for the Authentication-Plugin
     * @throws UnsupportedAuthenticationException
     *             failed to instantiate specified Authentication-Plugin
     */
    public void setAuthentication(String authPluginClassName, Map<String, String> authParams)
            throws UnsupportedAuthenticationException {
        confData.setAuthentication(AuthenticationFactory.create(authPluginClassName, authParams));
    }

    /**
     * @return the operation timeout in ms
     */
    public long getOperationTimeoutMs() {
        return confData.getOperationTimeoutMs();
    }

    /**
     * Set the operation timeout (default: 30 seconds)
     *

     * Producer-create, subscribe and unsubscribe operations will be retried until this interval, after which the
     * operation will be marked as failed
     *
     * @param operationTimeout
     *            operation timeout
     * @param unit
     *            time unit for {@code operationTimeout}
     */
    public void setOperationTimeout(int operationTimeout, TimeUnit unit) {
        checkArgument(operationTimeout >= 0);
        confData.setOperationTimeoutMs(unit.toMillis(operationTimeout));
    }

    /**
     * @return the number of threads to use for handling connections
     */
    public int getIoThreads() {
        return confData.getNumIoThreads();
    }

    /**
     * Set the number of threads to be used for handling connections to brokers (default: 1 thread)
     *
     * @param numIoThreads
     */
    public void setIoThreads(int numIoThreads) {
        checkArgument(numIoThreads > 0);
        confData.setNumIoThreads(numIoThreads);
    }

    /**
     * @return the number of threads to use for message listeners
     */
    public int getListenerThreads() {
        return confData.getNumListenerThreads();
    }

    /**
     * Set the number of threads to be used for message listeners (default: 1 thread)
     *
     * @param numListenerThreads
     */
    public void setListenerThreads(int numListenerThreads) {
        checkArgument(numListenerThreads > 0);
        confData.setNumListenerThreads(numListenerThreads);
    }

    /**
     * @return the max number of connections per single broker
     */
    public int getConnectionsPerBroker() {
        return confData.getConnectionsPerBroker();
    }

    /**
     * Sets the max number of connection that the client library will open to a single broker.
     *

     * By default, the connection pool will use a single connection for all the producers and consumers. Increasing this
     * parameter may improve throughput when using many producers over a high latency connection.
     *

     *
     * @param connectionsPerBroker
     *            max number of connections per broker (needs to be greater than 0)
     */
    public void setConnectionsPerBroker(int connectionsPerBroker) {
        checkArgument(connectionsPerBroker > 0, "Connections per broker need to be greater than 0");
        confData.setConnectionsPerBroker(connectionsPerBroker);
    }

    /**
     * @return whether TCP no-delay should be set on the connections
     */
    public boolean isUseTcpNoDelay() {
        return confData.isUseTcpNoDelay();
    }

    /**
     * Configure whether to use TCP no-delay flag on the connection, to disable Nagle algorithm.
     *

     * No-delay features make sure packets are sent out on the network as soon as possible, and it's critical to achieve
     * low latency publishes. On the other hand, sending out a huge number of small packets might limit the overall
     * throughput, so if latency is not a concern, it's advisable to set the useTcpNoDelay flag to false.
     *

     * Default value is true
     *
     * @param useTcpNoDelay
     */
    public void setUseTcpNoDelay(boolean useTcpNoDelay) {
        confData.setUseTcpNoDelay(useTcpNoDelay);
    }

    /**
     * @return whether TLS encryption is used on the connection
     */
    public boolean isUseTls() {
        return confData.isUseTls();
    }

    /**
     * Configure whether to use TLS encryption on the connection (default: false)
     *
     * @param useTls
     */
    public void setUseTls(boolean useTls) {
        confData.setUseTls(useTls);
    }

    /**
     * @return path to the trusted TLS certificate file
     */
    public String getTlsTrustCertsFilePath() {
        return confData.getTlsTrustCertsFilePath();
    }

    /**
     * Set the path to the trusted TLS certificate file
     *
     * @param tlsTrustCertsFilePath
     */
    public void setTlsTrustCertsFilePath(String tlsTrustCertsFilePath) {
        confData.setTlsTrustCertsFilePath(tlsTrustCertsFilePath);
    }

    /**
     * @return whether the Pulsar client accept untrusted TLS certificate from broker
     */
    public boolean isTlsAllowInsecureConnection() {
        return confData.isTlsAllowInsecureConnection();
    }

    /**
     * Configure whether the Pulsar client accept untrusted TLS certificate from broker (default: false)
     *
     * @param tlsAllowInsecureConnection
     */
    public void setTlsAllowInsecureConnection(boolean tlsAllowInsecureConnection) {
        confData.setTlsAllowInsecureConnection(tlsAllowInsecureConnection);
    }

    /**
     * Stats will be activated with positive statsIntervalSeconds
     *
     * @return the interval between each stat info (default: 60 seconds)
     */
    public long getStatsIntervalSeconds() {
        return confData.getStatsIntervalSeconds();
    }

    /**
     * Set the interval between each stat info (default: 60 seconds) Stats will be activated with positive
     * statsIntervalSeconds It should be set to at least 1 second
     *
     * @param statsIntervalSeconds
     *            the interval between each stat info
     * @param unit
     *            time unit for {@code statsInterval}
     */
    public void setStatsInterval(long statsInterval, TimeUnit unit) {
        confData.setStatsIntervalSeconds(unit.toSeconds(statsInterval));
    }

    /**
     * Get configured total allowed concurrent lookup-request.
     *
     * @return
     */
    public int getConcurrentLookupRequest() {
        return confData.getConcurrentLookupRequest();
    }

    /**
     * Number of concurrent lookup-requests allowed on each broker-connection to prevent overload on broker.
     * (default: 50000) It should be configured with higher value only in case of it requires to
     * produce/subscribe on thousands of topic using created {@link PulsarClient}
     *
     * @param concurrentLookupRequest
     */
    public void setConcurrentLookupRequest(int concurrentLookupRequest) {
        confData.setConcurrentLookupRequest(concurrentLookupRequest);
    }

    /**
     * Get configured max number of reject-request in a time-frame (30 seconds) after which connection will be closed
     *
     * @return
     */
    public int getMaxNumberOfRejectedRequestPerConnection() {
        return confData.getMaxNumberOfRejectedRequestPerConnection();
    }

    /**
     * Set max number of broker-rejected requests in a certain time-frame (30 seconds) after which current connection
     * will be closed and client creates a new connection that give chance to connect a different broker (default:
     * 50)
     *
     * @param maxNumberOfRejectedRequestPerConnection
     */
    public void setMaxNumberOfRejectedRequestPerConnection(int maxNumberOfRejectedRequestPerConnection) {
        confData.setMaxNumberOfRejectedRequestPerConnection(maxNumberOfRejectedRequestPerConnection);
    }

    public boolean isTlsHostnameVerificationEnable() {
        return confData.isTlsHostnameVerificationEnable();
    }

    /**
     * It allows to validate hostname verification when client connects to broker over tls. It validates incoming x509
     * certificate and matches provided hostname(CN/SAN) with expected broker's host name. It follows RFC 2818, 3.1.
     * Server Identity hostname verification.
     *
     * @see rfc2818
     *
     * @param tlsHostnameVerificationEnable
     */
    public void setTlsHostnameVerificationEnable(boolean tlsHostnameVerificationEnable) {
        confData.setTlsHostnameVerificationEnable(tlsHostnameVerificationEnable);
    }

    public ClientConfiguration setServiceUrl(String serviceUrl) {
        confData.setServiceUrl(serviceUrl);
        return this;
    }

    /**
     * Set the duration of time to wait for a connection to a broker to be established. If the duration
     * passes without a response from the broker, the connection attempt is dropped.
     *
     * @param duration the duration to wait
     * @param unit the time unit in which the duration is defined
     */
    public void setConnectionTimeout(int duration, TimeUnit unit) {
        confData.setConnectionTimeoutMs((int)unit.toMillis(duration));
    }

    /**
     * Get the duration of time for which the client will wait for a connection to a broker to be
     * established before giving up.
     *
     * @return the duration, in milliseconds
     */
    public long getConnectionTimeoutMs() {
        return confData.getConnectionTimeoutMs();
    }

    public ClientConfigurationData getConfigurationData() {
        return confData;
    }

}


text:
  Montcornet est
       un village
       situé dans le département des Ardennes en Champagne-Ardenne. Elle comptait 231 habitants en 2008.

La commune propose quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport et deux boucles de randonnée.

À coté de Montcornet sont positionnées géographiquement les villes de
Sécheval située à 3 km, 479 habitants,
Arreux localisée à 1 km, 358 habitants,
Cliron localisée à 2 km, 290 habitants,
Renwez à 2 km, 1 631 habitants,
Harcy localisée à 4 km, 486 habitants,
Houldizy localisée à 3 km, 349 habitants,
 entre autres. De plus, Montcornet est située à seulement neuf km de Charleville-Mézières.

Le nombre d'habitations, à Montcornet, était réparti en 2011 en quatre appartements et 111 maisons soit
 un marché relativement équilibré.

Si vous envisagez de emmenager à Montcornet, vous pourrez aisément trouver une maison à acheter.


text:
'use strict';

var fs         = require('fs');
var path       = require('path');
var util       = require('util');
var gulp       = require('gulp');
var browserify = require('browserify');
var babelify   = require('babelify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var uglify     = require('gulp-uglify');
var nodemon    = require('gulp-nodemon');
var babel      = require('gulp-babel');

var CONFIG = {
  sample: {
    files: {
      data: path.join(__dirname, 'sample', 'data.json'),
      assets: [
        'sample/**/*.html',
        'sample/**/*.css',
        'sample/**/*.jsx'
      ]
    }
  }
};

gulp.task('generate:data', function(cb) {

  var comments = [];

  for (var i = 0; i < 200; i++) {
    comments.push({
      username : util.format('user-%s', i),
      comment  : util.format('This is the comment #%d', i)
    });
  }

  fs.writeFileSync(CONFIG.sample.files.data, JSON.stringify(comments, null, 2));

  return cb();

});

gulp.task('watch', function() {
  gulp.watch('./react_components/*.js', ['dist', 'sample']);
  gulp.watch('./sample/sample.jsx', ['sample']);
});

gulp.task('sample', function() {
  return browserify('./sample/sample.jsx')
    .transform(babelify)
    .bundle()
    .pipe(source('sample.js'))
    .pipe(gulp.dest('./sample'));
});

gulp.task('dist', function() {
  return gulp.src('./react_components/*.js')
    .pipe(babel())
    .pipe(gulp.dest('./dist/'));
});

gulp.task('server:watch', function () {
  nodemon({script: 'server.js'})
    .on('restart', 'server:reload');
});

gulp.task('server:reload', function() {
  gulp.watch('./react_components/*.js', ['dist', 'sample']);
  gulp.watch('./sample/sample.jsx', ['sample']);
});

gulp.task('serve', ['dist', 'sample', 'generate:data', 'server:watch']);
gulp.task('default', ['dist', 'sample']);


text:
typedef void (^RequestHandler)(NSArray *dataList);

@implementation Faculty (Mappings)

+ (NSDictionary *)mappings {
	return @{
			 @"Id": @"facultyId",
			 };
}

+ (NSString *)primaryKey {

	return @"facultyId";
}

+ (void)request:(NSNumber *)parameter withHandler:(RequestHandler)handler errorBlock:(void (^)())errorHandler {

	NSDictionary *parameters = @{ @"get_lists": @"0"};
	NSString *url = @"facult_req.php";

	[RequestManager.manager request:url parameters:parameters withBlock:^(NSArray *entries){
		NSArray *objects = [Faculty createArray:entries];
		[objects each:^(Faculty *object) {
			NSString *name = object.name;
			NSRange range = [name rangeOfString:@"(" options:NSBackwardsSearch range:NSMakeRange(0, name.length)];
			NSString *substring = [name substringFromIndex:range.location];
			name = [name stringByReplacingOccurrencesOfString:substring withString:@""];
			object.name = [name stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
		}];
		[CoreDataManager.sharedManager saveContext];
		if (handler) {
			handler(entries);
		}
	} errorBlock:errorHandler];
}

@end


text:
IoT Kafka Producer is a Maven application for generating IoT Data events using Apache Kafka. This project requires following tools and technologies.

- JDK - 1.8
- Maven - 3.3.9
- ZooKeeper - 3.4.8
- Kafka - 2.10-0.10.0.0

You can build and run this application using below commands. Please check resources/iot-kafka.properties for configuration details.

```sh
mvn package
mvn exec:java -Dexec.mainClass="com.iot.app.kafka.producer.IoTDataProducer"

```

Alternate way to run this application is using the "iot-kafka-producer-1.0.0.jar" file created by maven. Open command prompt, go to target folder and execute below command.

```sh
java -jar iot-kafka-producer-1.0.0.jar
```


text:
// ----------------------------------------------------------------------------------
// <copyright file="ModularKeyInfoFactory" company="NMemory Team">
//     Copyright (C) NMemory Team
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy
//     of this software and associated documentation files (the "Software"), to deal
//     in the Software without restriction, including without limitation the rights
//     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//     copies of the Software, and to permit persons to whom the Software is
//     furnished to do so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in
//     all copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//     THE SOFTWARE.
// </copyright>
// ----------------------------------------------------------------------------------

namespace NMemory.Indexes
{
    using System;
    using System.Linq.Expressions;
    using NMemory.Exceptions;
    using NMemory.Modularity;
    using NMemory.Services;
    using NMemory.Services.Contracts;

    public class ModularKeyInfoFactory : IKeyInfoFactory
    {
        private readonly IKeyInfoService service;

        protected ModularKeyInfoFactory(IKeyInfoService service)
        {
            this.service = service;
        }

        public ModularKeyInfoFactory(IDatabase database)
        {
            this.service = database
                .DatabaseEngine
                .ServiceProvider
                .GetService<IKeyInfoService>();

            if (this.service == null)
            {
                // Fallback
                this.service = DefaultServiceConfigurations.CreateDefaultKeyInfoService();
            }
        }

        public IKeyInfo<TEntity, TKey> Create<TEntity, TKey>(
            Expression<Func<TEntity, TKey>> keySelector) where TEntity : class
        {
            IKeyInfo<TEntity, TKey> result;

            if (!this.service.TryCreateKeyInfo<TEntity, TKey>(keySelector, out result))
            {
                throw new NMemoryException(
                    ErrorCode.GenericError,
                    ExceptionMessages.CannotCreateKeyInfo);
            }

            return result;
        }
    }
}


text:
package com.sample;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

@SuppressWarnings("rawtypes")
public class CustomerRowMapper implements RowMapper	{
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Customer customer = new Customer();
        customer.setSurname(rs.getString("SURNAME"));
        customer.setName(rs.getString("NAME"));
        customer.setAge(rs.getInt("AGE"));
        return customer;
    }
}


text:
'use strict'

const assert = require('assert')
const dgram = require('dgram')
const proxyquire = require('proxyquire')
const WebSocket = require('ws')

describe('bridge', function () {
  let testServer
  let testServerPort
  let ws

  let server // express server
  let app // express app

  beforeEach('setup UDP server', function (done) {
    testServer = dgram.createSocket('udp4')

    testServer.on('message', (msg, rinfo) => {
      testServer.send(msg, 0, msg.length, rinfo.port, rinfo.address)
    })

    testServer.on('listening', () => {
      const address = testServer.address()
      testServerPort = address.port
      done()
    })

    testServer.bind()
  })

  beforeEach('load server', function () {
    const backend = proxyquire('../server/index', {})
    app = backend.app
    server = backend.server
  })

  afterEach('close ws', function () {
    if (ws && (ws.readyState !== WebSocket.CLOSING || ws.readyState !== WebSocket.CLOSED)) {
      ws.close(1000)
    }
  })

  afterEach('close server', function (done) {
    server.close(done)
  })

  afterEach('close UDP server', function (done) {
    testServer.close(done)
  })

  function getBridgeURL () {
    return `ws://127.0.0.1:${server.address().port}/api/bridge`
  }

  it('should require a valid grid session', function (done) {
    ws = new WebSocket(getBridgeURL())
    const sendData = []

    ws.on('open', () => {
      ws.send('oisdfg')
    })

    ws.on('close', (code, reason) => {
      try {
        assert.strictEqual(code, 1008, 'Closing code')
        assert.strictEqual(reason, 'wrong session id', 'Closing reason')
        assert.deepStrictEqual(sendData, [], 'no data was send')
        done()
      } catch (err) {
        done(err)
      }
    })

    ws.on('message', data => {
      sendData.push(data)
    })
  })

  it('should send ok when the connection got validated', function (done) {
    const sessionId = app.get('generateSession')()
    const checkSession = app.get('checkSession')
    ws = new WebSocket(getBridgeURL())

    try {
      assert.strictEqual(checkSession(sessionId), 'inactive')
    } catch (err) {
      done(err)
      return
    }

    ws.on('open', () => {
      ws.send(sessionId)
    })

    ws.on('message', data => {
      try {
        assert.strictEqual(data, 'ok')
        const sessionState = checkSession(sessionId)
        assert.strictEqual(sessionState, 'active')

        done()
      } catch (err) {
        done(err)
      }
    })
  })

  it('should proxy messages to a UDP-server', function (done) {
    const sessionId = app.get('generateSession')()
    ws = new WebSocket(getBridgeURL())

    ws.on('open', () => {
      ws.send(sessionId)
    })

    ws.on('message', data => {
      if (typeof data === 'string') {
        const msg = Buffer.concat([
          Buffer.from([127, 0, 0, 1, 0, 0]),
          Buffer.from('test message')
        ])
        msg.writeUInt16LE(testServerPort, 4)
        ws.send(msg)
      } else {
        try {
          assert.strictEqual(data.length, 6 + 12, 'message length')

          // Server address was send along
          assert.deepStrictEqual(
            [
              data.readUInt8(0),
              data.readUInt8(1),
              data.readUInt8(2),
              data.readUInt8(3)
            ],
            [127, 0, 0, 1],
            'IP part was send'
          )
          assert.strictEqual(data.readUInt16LE(4), testServerPort, 'PORT part was send')
          const msg = data.slice(6)
          assert.strictEqual(msg.toString(), 'test message', 'Message body')

          done()
        } catch (err) {
          done(err)
        }
      }
    })
  })

  it('should end the session if the socket was closed', function (done) {
    const sessionId = app.get('generateSession')()
    const checkSession = app.get('checkSession')
    ws = new WebSocket(getBridgeURL())

    ws.on('open', () => {
      ws.send(sessionId)
    })

    ws.on('message', () => {
      ws.close(1000)
    })

    ws.on('close', () => {
      setTimeout(() => {
        try {
          checkSession(sessionId)

          done(new Error('checkSession did not throw!'))
        } catch (err) {
          if (err.message === 'Name or password is incorrect.') {
            done()
          } else {
            done(err)
          }
        }
      }, 15)
    })
  })

  it('should not end the session if the socket was unexpectedly closed', function (done) {
    const sessionId = app.get('generateSession')()
    const checkSession = app.get('checkSession')
    ws = new WebSocket(getBridgeURL())

    ws.on('open', () => {
      ws.send(sessionId)
    })

    ws.on('message', () => {
      ws.terminate()

      setTimeout(() => {
        try {
          const state = checkSession(sessionId)
          assert.strictEqual(state, 'inactive')

          done()
        } catch (err) {
          done(err)
        }
      }, 15)
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff000000">

    <com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </com.github.nuptboyzhb.lib.SuperSwipeRefreshLayout>

</RelativeLayout>


text:
package org.omarket.trading.verticles;

import joinery.DataFrame;
import org.omarket.trading.Security;
import org.omarket.quotes.Quote;

import java.util.Deque;
import java.util.Map;

/**
 * Interface for processing quotes.
 */
public interface QuoteProcessor {
    /**
     * Called back every time a new tick is sent.
     *
     * @param contracts     mapping each contract code to the relevant contract properties
     * @param quotes        tick data, in increasing order of timestamp (last is most recent)
     * @param sampledQuotes sampled data
     */
    void processQuotes(Map<String, Security> contracts, Map<String, Deque<Quote>> quotes, Map<String, DataFrame> sampledQuotes);
}


text:
module.exports = {
    defaultState: {
        result: [],
        loading: true,
        searchString: '',
        likesCount: 0,
        reviewsCount: 0,
        searchCity: '',
        searchByField: '',
        imagesCountFrom: 5,
        imagesCountTo: 15,
        currentPage: 1,
        pageCount: 1
    }
};


text:
package net.sf.antcontrib.cpptasks.compiler;

import net.sf.antcontrib.cpptasks.OutputTypeEnum;
import net.sf.antcontrib.cpptasks.SubsystemEnum;

/**
 * This class represents the target platform for the compile and link step. The
 * name is an anachronism and should be changed.
 *
 * @author Curt Arnold
 */
public class LinkType {
    private OutputTypeEnum outputType = new OutputTypeEnum();
    private boolean staticRuntime = false;
    private SubsystemEnum subsystem = new SubsystemEnum();

    /**
     *

     * Constructor
     *

     *

     * By default, an gui executable with a dynamically linked runtime
     *

     */
    public LinkType() {
    }

    /**
     * Gets whether the link should produce an executable
     *
     * @return boolean
     */
    public boolean isExecutable() {
        return "executable".equals(outputType.getValue());
    }

    /**
     * Gets whether the link should produce a plugin module.
     *
     * @return boolean
     */
    public boolean isPluginModule() {
        return "plugin".equals(outputType.getValue());
    }

    /**
     * Gets whether the link should produce a shared library.
     *
     * @return boolean
     */
    public boolean isSharedLibrary() {
        String value = outputType.getValue();
        return value.equals("shared") || value.equals("plugin");
    }

    /**
     * Gets whether the link should produce a static library.
     *
     * @return boolean
     */
    public boolean isStaticLibrary() {
        return "static".equals(outputType.getValue());
    }

    /**
     * Gets whether the module should use a statically linked runtime library.
     *
     * @return boolean
     */
    public boolean isStaticRuntime() {
        return staticRuntime;
    }

    /**
     * Gets whether the link should produce a module for a console subsystem.
     *
     * @return boolean
     */
    public boolean isSubsystemConsole() {
        return "console".equals(subsystem.getValue());
    }

    /**
     * Gets whether the link should produce a module for a graphical user
     * interface subsystem.
     *
     * @return boolean
     */
    public boolean isSubsystemGUI() {
        return "gui".equals(subsystem.getValue());
    }

    /**
     * Sets the output type (executable, shared, etc).
     *
     * @param outputType may not be null
     */
    public void setOutputType(OutputTypeEnum outputType) {
        if (outputType == null) {
            throw new IllegalArgumentException("outputType");
        }
        this.outputType = outputType;
    }

    /**
     * Gets the output type.
     *
     * @return output type
     */
    public String getOutputType() {
        return outputType.getValue();
    }

    /**
     * Requests use of a static runtime library.
     *
     * @param staticRuntime if true, use static runtime library if possible.
     */
    public void setStaticRuntime(boolean staticRuntime) {
        this.staticRuntime = staticRuntime;
    }

    /**
     * Sets the subsystem (gui, console, etc).
     *
     * @param subsystem subsystem, may not be null
     */
    public void setSubsystem(SubsystemEnum subsystem) {
        if (subsystem == null) {
            throw new IllegalArgumentException("subsystem");
        }
        this.subsystem = subsystem;
    }

    /**
     * Get subsystem name.
     *
     * @return subsystem name
     */
    public String getSubsystem() {
        return subsystem.getValue();
    }
}


text:
<#
.SYNOPSIS
Nishang script which can check for credentials on remote computers and can open PSSessions if the credentials work.

.DESCRIPTION
The payload uses WMI to check a credential against given list of computers. Use the -Creds parameter to specify username and password. If the script is run
from a powershell session with local or global admin credentials (or from a powershell session started with hashes of such account using WCE), it should be used
without the -Creds parameter. Use the -CreateSessions parameter to create PSSessions.

.PARAMETER filename
Path to the file which stores list of servers.

.PARAMETER Creds
Use this parameter to specify username (in form of domain\username) and password.

.PARAMETER CreateSessions
Use this parameter to make the script create PSSessions to targets on which the credentials worked.

.PARAMETER VerboseErrors
Use this parameter to get verbose error messages.

.EXAMPLE
PS > Create-MultipleSessions -filename .\servers.txt
Above command uses the credentials available with current powershell session and checks it against multiple computers specified in servers.txt

.EXAMPLE
PS > Create-MultipleSessions -filename .\servers.txt -Creds
Above command asks the user to provide username and passowrd to check on remote computers.

.EXAMPLE
PS > Create-MultipleSessions -filename .\servers.txt -CreateSessions
Above command uses the credentials available with current powershell session, checks it against multiple computers specified in servers.txt and creates PSSession for those.

.LINK
http://labofapenetrationtester.blogspot.com/2013/04/poshing-the-hashes.html
https://github.com/samratashok/nishang
#>

function Create-MultipleSessions
{
    [CmdletBinding()] Param (
        [Parameter(Position = 0, Mandatory = $True)]
        [String]
        $filename,

        [Parameter(Mandatory = $False)]
        [Switch]
        $Creds,

        [Parameter(Mandatory = $False)]
        [Switch]
        $CreateSessions,

        [Parameter(Mandatory = $False)]
        [Switch]
        $VerboseErrors
    )

    $ErrorActionPreference = "SilentlyContinue"
    if ($VerboseErrors)
    {
        $ErrorActionPreference = "Continue"
    }
    $servers = Get-Content $filename

    if ($Creds)
    {
        $Credentials = Get-Credential
        $CheckCommand = 'gwmi -query "Select IPAddress From Win32_NetworkAdapterConfiguration Where IPEnabled = True" -ComputerName $server -Credential $Credentials'
        $SessionCommand = 'New-PSSession -ComputerName $server -Credential $Credentials'
    }

    else
    {
        $CheckCommand = 'gwmi -query "Select IPAddress From Win32_NetworkAdapterConfiguration Where IPEnabled = True" -ComputerName $server'
        $SessionCommand = 'New-PSSession -ComputerName $server'
    }

    foreach ($server in $servers)
    {
       $check = Invoke-Expression $CheckCommand
       if($check -ne $null)
       {
           Write-Host "Credentials worked on $server !!" -ForegroundColor Green
           if ($CreateSessions -eq $True)
           {
                "`nCreating Session for $server"
                Invoke-Expression $SessionCommand
           }
        }
        else
        {
           "Could not connect or credentials didn't work on $server"
        }
    }

    if ($CreateSessions -eq $True)
    {
        Write-Host "`nFollowing Sessions have been created: " -ForegroundColor Green
        Get-PSSession
    }
}


text:
#include <xpcc/architecture/platform.hpp>

/**
 * This is some testing of Timers 1 to 14 on a STM32 F4 Discovery Board.
 *
 * The blue LED is blinked in the main loop with busy waiting.
 *
 * Red and green LEDs are blinked by interrupts from timers.
 * The red LED should blink three times, driven by Timer 1,
 * then the green one blinks three times driven by Timer 2,
 * and then the red one again by Timer 3, et cetera.
 *
 * After 14 * 3 blinks each timer TIM1 to TIM14 blinked an LED
 * from an interrupt.
 *
 * When the blue LED stops blinking, probably the processor was
 * caught in the default handler for unassigned interrupts.
 * This should not happen.
 */

// Advanced Timers
template< typename TIMER >
static void
testTimerAdvancedStart()
{
    TIMER::enable();
    TIMER::setMode(TIMER::Mode::UpCounter);

	TIMER::template setPeriod<Board::systemClock>(250000);
    TIMER::enableInterruptVector(TIMER::Interrupt::Update, true, 10);
    TIMER::enableInterrupt(TIMER::Interrupt::Update);

    TIMER::applyAndReset();
    TIMER::start();
}

template< typename TIMER >
static void
testTimerStart()
{
    TIMER::enable();
    TIMER::setMode(TIMER::Mode::UpCounter);

	TIMER::template setPeriod<Board::systemClock>(250000);
    TIMER::enableInterruptVector(true, 10);
    TIMER::enableInterrupt(TIMER::Interrupt::Update);

    TIMER::applyAndReset();
    TIMER::start();
}

template< typename TIMER >
static void
testTimerAdvancedStop()
{
    TIMER::pause();
    TIMER::disableInterrupt(TIMER::Interrupt::Update);
    TIMER::enableInterruptVector(TIMER::Interrupt::Update, false, 10);
    TIMER::disable();
}

template< typename TIMER >
static void
testTimerStop()
{
    TIMER::pause();
    TIMER::disableInterrupt(TIMER::Interrupt::Update);
    TIMER::enableInterruptVector(false, 10);
    TIMER::disable();
}

using namespace Board;

// ----------------------------------------------------------------------------
int
main()
{
    Board::initialize();

    uint16_t state = 0;
	bool restart = false;

    while (1)
    {
        LedBlue::set();
        xpcc::delayMilliseconds(20);
        LedBlue::reset();
        xpcc::delayMilliseconds(150);

		if (restart) {
			restart = false;
			state = 0;
		}

        switch (state)
        {
        case 0:
            testTimerAdvancedStart<Timer1>();
            break;

        case 10:
            testTimerAdvancedStop<Timer1>();
            break;

        case 12:
            testTimerStart<Timer2>();
            break;

        case 22:
            testTimerStop<Timer2>();
            break;

        case 24:
            testTimerStart<Timer3>();
            break;

        case 34:
            testTimerStop<Timer3>();
            break;

        case 36:
            testTimerStart<Timer4>();
            break;

        case 46:
            testTimerStop<Timer4>();
            break;

        case 48:
            testTimerStart<Timer5>();
            break;

        case 58:
            testTimerStop<Timer5>();
            break;

        case 60:
            testTimerStart<Timer6>();
            break;

        case 70:
            testTimerStop<Timer6>();
            break;

        case 72:
            testTimerStart<Timer7>();
            break;

        case 82:
            testTimerStop<Timer7>();
            break;

        case 84:
            testTimerAdvancedStart<Timer8>();
            break;

        case 94:
            testTimerAdvancedStop<Timer8>();
            break;

        case 96:
            testTimerStart<Timer9>();
            break;

        case 106:
            testTimerStop<Timer9>();
            break;

        case 108:
            testTimerStart<Timer10>();
            break;

        case 118:
            testTimerStop<Timer10>();
            break;

        case 120:
            testTimerStart<Timer11>();
            break;

        case 130:
            testTimerStop<Timer11>();
            break;

        case 132:
            testTimerStart<Timer12>();
            break;

        case 142:
            testTimerStop<Timer12>();
            break;

        case 144:
            testTimerStart<Timer13>();
            break;

        case 154:
            testTimerStop<Timer13>();
            break;

        case 156:
            testTimerStart<Timer14>();
            break;

        case 166:
            testTimerStop<Timer14>();
            break;

		case 180:
			restart = true;
			break;

        default:
            break;
        }

        // Next state
        ++state;
    }

    return 0;
}

extern "C"
void
TIM2_IRQHandler(void)
{
    xpcc::stm32::Timer2::acknowledgeInterruptFlags(xpcc::stm32::Timer2::InterruptFlag::Update);
    LedGreen::toggle();
}

extern "C"
void
TIM3_IRQHandler(void)
{
    xpcc::stm32::Timer3::acknowledgeInterruptFlags(xpcc::stm32::Timer3::InterruptFlag::Update);
    LedRed::toggle();
}

extern "C"
void
TIM4_IRQHandler(void)
{
    xpcc::stm32::Timer4::acknowledgeInterruptFlags(xpcc::stm32::Timer4::InterruptFlag::Update);
    LedGreen::toggle();
}

extern "C"
void
TIM5_IRQHandler(void)
{
    xpcc::stm32::Timer5::acknowledgeInterruptFlags(xpcc::stm32::Timer5::InterruptFlag::Update);
    LedRed::toggle();
}

extern "C"
void
TIM6_DAC_IRQHandler(void)
{
    xpcc::stm32::Timer6::acknowledgeInterruptFlags(xpcc::stm32::Timer6::InterruptFlag::Update);
    LedGreen::toggle();
}

extern "C"
void
TIM7_IRQHandler(void)
{
    xpcc::stm32::Timer7::acknowledgeInterruptFlags(xpcc::stm32::Timer7::InterruptFlag::Update);
    LedRed::toggle();
}

// For TIM8 See TIM13

extern "C"
void
TIM1_BRK_TIM9_IRQHandler(void)
{
    xpcc::stm32::Timer9::acknowledgeInterruptFlags(xpcc::stm32::Timer9::InterruptFlag::Update);
    LedGreen::toggle();
}

// Timer 1 and 10
extern "C"
void
TIM1_UP_TIM10_IRQHandler(void)
{
    xpcc::stm32::Timer1::acknowledgeInterruptFlags(xpcc::stm32::Timer1::InterruptFlag::Update);
    xpcc::stm32::Timer10::acknowledgeInterruptFlags(xpcc::stm32::Timer10::InterruptFlag::Update);
    LedRed::toggle();
}

extern "C"
void
TIM1_TRG_COM_TIM11_IRQHandler(void)
{
    xpcc::stm32::Timer11::acknowledgeInterruptFlags(xpcc::stm32::Timer11::InterruptFlag::Update);
    LedGreen::toggle();
}

extern "C"
void
TIM8_BRK_TIM12_IRQHandler(void)
{
    xpcc::stm32::Timer12::acknowledgeInterruptFlags(xpcc::stm32::Timer12::InterruptFlag::Update);
    LedRed::toggle();
}

extern "C"
void
TIM8_UP_TIM13_IRQHandler(void)
{
    xpcc::stm32::Timer8::acknowledgeInterruptFlags(xpcc::stm32::Timer8::InterruptFlag::Update);
    xpcc::stm32::Timer13::acknowledgeInterruptFlags(xpcc::stm32::Timer13::InterruptFlag::Update);
    LedGreen::toggle();
}

extern "C"
void
TIM8_TRG_COM_TIM14_IRQHandler(void)
{
    xpcc::stm32::Timer14::acknowledgeInterruptFlags(xpcc::stm32::Timer14::InterruptFlag::Update);
    LedRed::toggle();
}


text:
<?php

// tutoWelcomeBundle:Article:index.html.twig
return array (
);