text:
/**
\brief Definitions for the Atmel AT86RF231 radio chip.
*/

#ifndef __ATMEL_H
#define __ATMEL_H

//=========================== define ==========================================

/**
\brief Possible values for the status of the radio.

After you get an interrupt from the radio, read the status register
(<tt>RG_IRQ_STATUS</tt>) to know what type it is, amoung the following.
*/
enum radio_irqstatus_enum {
   AT_IRQ_BAT_LOW                 = 0x80,   //< Supply voltage below the programmed threshold.
   AT_IRQ_TRX_UR                  = 0x40,   ///< Frame buffer access violation.
   AT_IRQ_AMI                     = 0x20,   ///< Address matching.
   AT_IRQ_CCA_ED_DONE             = 0x10,   ///< End of a CCA or ED measurement.
   AT_IRQ_TRX_END                 = 0x08,   ///< Completion of a frame transmission/reception.
   AT_IRQ_RX_START                = 0x04,   ///< Start of a PSDU reception.
   AT_IRQ_PLL_UNLOCK              = 0x02,   ///< PLL unlock.
   AT_IRQ_PLL_LOCK                = 0x01,   ///< PLL lock.
};

#define HAVE_REGISTER_MAP (1)
/** Offset for register TRX_STATUS
 * @ingroup apiHalPHY230Reg
 */
#define RG_TRX_STATUS                    (0x01)
  /** Access parameters for sub-register CCA_DONE in register @ref RG_TRX_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_DONE                  0x01, 0x80, 7
  /** Access parameters for sub-register CCA_STATUS in register @ref RG_TRX_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_STATUS                0x01, 0x40, 6
# define SR_reserved_01_3             0x01, 0x20, 5
  /** Access parameters for sub-register TRX_STATUS in register @ref RG_TRX_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_TRX_STATUS                0x01, 0x1f, 0
   /** Constant P_ON for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define P_ON                     (0)
   /** Constant BUSY_RX for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define BUSY_RX                  (1)
   /** Constant BUSY_TX for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define BUSY_TX                  (2)
   /** Constant RX_ON for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define RX_ON                    (6)
   /** Constant TRX_OFF for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define TRX_OFF                  (8)
   /** Constant PLL_ON for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define PLL_ON                   (9)
   /** Constant SLEEP for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define SLEEP                    (15)
   /** Constant BUSY_RX_AACK for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define BUSY_RX_AACK             (17)
   /** Constant BUSY_TX_ARET for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define BUSY_TX_ARET             (18)
   /** Constant RX_AACK_ON for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define RX_AACK_ON               (22)
   /** Constant TX_ARET_ON for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define TX_ARET_ON               (25)
   /** Constant RX_ON_NOCLK for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define RX_ON_NOCLK              (28)
   /** Constant RX_AACK_ON_NOCLK for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define RX_AACK_ON_NOCLK         (29)
   /** Constant BUSY_RX_AACK_NOCLK for sub-register @ref SR_TRX_STATUS
    * @ingroup apiHalPHY230Const
    */
#  define BUSY_RX_AACK_NOCLK       (30)

/** Offset for register TRX_STATE
 * @ingroup apiHalPHY230Reg
 */
#define RG_TRX_STATE                     (0x02)
  /** Access parameters for sub-register TRAC_STATUS in register @ref RG_TRX_STATE
   * @ingroup apiHalPHY230Sreg
   */
# define SR_TRAC_STATUS               0x02, 0xe0, 5
  /** Access parameters for sub-register TRX_CMD in register @ref RG_TRX_STATE
   * @ingroup apiHalPHY230Sreg
   */
# define SR_TRX_CMD                   0x02, 0x1f, 0
   /** Constant CMD_NOP for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_NOP                  (0)
   /** Constant CMD_TX_START for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_TX_START             (2)
   /** Constant CMD_FORCE_TRX_OFF for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_FORCE_TRX_OFF        (3)
   /** Constant CMD_RX_ON for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_RX_ON                (6)
   /** Constant CMD_TRX_OFF for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_TRX_OFF              (8)
   /** Constant CMD_PLL_ON for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_PLL_ON               (9)
   /** Constant CMD_RX_AACK_ON for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_RX_AACK_ON           (22)
   /** Constant CMD_TX_ARET_ON for sub-register @ref SR_TRX_CMD
    * @ingroup apiHalPHY230Const
    */
#  define CMD_TX_ARET_ON           (25)

/** Offset for register TRX_CTRL_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_TRX_CTRL_0                    (0x03)
  /** Access parameters for sub-register PAD_IO in register @ref RG_TRX_CTRL_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PAD_IO                    0x03, 0xc0, 6
  /** Access parameters for sub-register PAD_IO_CLKM in register @ref RG_TRX_CTRL_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PAD_IO_CLKM               0x03, 0x30, 4
   /** Constant CLKM_2mA for sub-register @ref SR_PAD_IO_CLKM
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_2mA                 (0)
   /** Constant CLKM_4mA for sub-register @ref SR_PAD_IO_CLKM
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_4mA                 (1)
   /** Constant CLKM_6mA for sub-register @ref SR_PAD_IO_CLKM
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_6mA                 (2)
   /** Constant CLKM_8mA for sub-register @ref SR_PAD_IO_CLKM
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_8mA                 (3)
  /** Access parameters for sub-register CLKM_SHA_SEL in register @ref RG_TRX_CTRL_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CLKM_SHA_SEL              0x03, 0x08, 3
  /** Access parameters for sub-register CLKM_CTRL in register @ref RG_TRX_CTRL_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CLKM_CTRL                 0x03, 0x07, 0
   /** Constant CLKM_no_clock for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_no_clock            (0)
   /** Constant CLKM_1MHz for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_1MHz                (1)
   /** Constant CLKM_2MHz for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_2MHz                (2)
   /** Constant CLKM_4MHz for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_4MHz                (3)
   /** Constant CLKM_8MHz for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_8MHz                (4)
   /** Constant CLKM_16MHz for sub-register @ref SR_CLKM_CTRL
    * @ingroup apiHalPHY230Const
    */
#  define CLKM_16MHz               (5)

/** Offset for register PHY_TX_PWR
 * @ingroup apiHalPHY230Reg
 */
#define RG_PHY_TX_PWR                    (0x05)
  /** Access parameters for sub-register TX_AUTO_CRC_ON in register @ref RG_PHY_TX_PWR
   * @ingroup apiHalPHY230Sreg
   */
# define SR_TX_AUTO_CRC_ON            0x05, 0x80, 7
# define SR_reserved_05_2             0x05, 0x70, 4
  /** Access parameters for sub-register TX_PWR in register @ref RG_PHY_TX_PWR
   * @ingroup apiHalPHY230Sreg
   */
# define SR_TX_PWR                    0x05, 0x0f, 0

/** Offset for register PHY_RSSI
 * @ingroup apiHalPHY230Reg
 */
#define RG_PHY_RSSI                      (0x06)
# define SR_reserved_06_1             0x06, 0xe0, 5
  /** Access parameters for sub-register RSSI in register @ref RG_PHY_RSSI
   * @ingroup apiHalPHY230Sreg
   */
# define SR_RSSI                      0x06, 0x1f, 0

/** Offset for register PHY_ED_LEVEL
 * @ingroup apiHalPHY230Reg
 */
#define RG_PHY_ED_LEVEL                  (0x07)
  /** Access parameters for sub-register ED_LEVEL in register @ref RG_PHY_ED_LEVEL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_ED_LEVEL                  0x07, 0xff, 0

/** Offset for register PHY_CC_CCA
 * @ingroup apiHalPHY230Reg
 */
#define RG_PHY_CC_CCA                    (0x08)
  /** Access parameters for sub-register CCA_REQUEST in register @ref RG_PHY_CC_CCA
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_REQUEST               0x08, 0x80, 7
  /** Access parameters for sub-register CCA_MODE in register @ref RG_PHY_CC_CCA
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_MODE                  0x08, 0x60, 5
  /** Access parameters for sub-register CHANNEL in register @ref RG_PHY_CC_CCA
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CHANNEL                   0x08, 0x1f, 0

/** Offset for register CCA_THRES
 * @ingroup apiHalPHY230Reg
 */
#define RG_CCA_THRES                     (0x09)
  /** Access parameters for sub-register CCA_CS_THRES in register @ref RG_CCA_THRES
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_CS_THRES              0x09, 0xf0, 4
  /** Access parameters for sub-register CCA_ED_THRES in register @ref RG_CCA_THRES
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CCA_ED_THRES              0x09, 0x0f, 0

/** Offset for register IRQ_MASK
 * @ingroup apiHalPHY230Reg
 */
#define RG_IRQ_MASK                      (0x0e)
  /** Access parameters for sub-register IRQ_MASK in register @ref RG_IRQ_MASK
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_MASK                  0x0e, 0xff, 0

/** Offset for register IRQ_STATUS
 * @ingroup apiHalPHY230Reg
 */
#define RG_IRQ_STATUS                    (0x0f)
  /** Access parameters for sub-register IRQ_7_BAT_LOW in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_7_BAT_LOW             0x0f, 0x80, 7
  /** Access parameters for sub-register IRQ_6_TRX_UR in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_6_TRX_UR              0x0f, 0x40, 6
  /** Access parameters for sub-register IRQ_5 in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_5                     0x0f, 0x20, 5
  /** Access parameters for sub-register IRQ_4 in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_4                     0x0f, 0x10, 4
  /** Access parameters for sub-register IRQ_3_TRX_END in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_3_TRX_END             0x0f, 0x08, 3
  /** Access parameters for sub-register IRQ_2_RX_START in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_2_RX_START            0x0f, 0x04, 2
  /** Access parameters for sub-register IRQ_1_PLL_UNLOCK in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_1_PLL_UNLOCK          0x0f, 0x02, 1
  /** Access parameters for sub-register IRQ_0_PLL_LOCK in register @ref RG_IRQ_STATUS
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IRQ_0_PLL_LOCK            0x0f, 0x01, 0

/** Offset for register VREG_CTRL
 * @ingroup apiHalPHY230Reg
 */
#define RG_VREG_CTRL                     (0x10)
  /** Access parameters for sub-register AVREG_EXT in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_AVREG_EXT                 0x10, 0x80, 7
  /** Access parameters for sub-register AVDD_OK in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_AVDD_OK                   0x10, 0x40, 6
  /** Access parameters for sub-register AVREG_TRIM in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_AVREG_TRIM                0x10, 0x30, 4
   /** Constant AVREG_1_80V for sub-register @ref SR_AVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define AVREG_1_80V              (0)
   /** Constant AVREG_1_75V for sub-register @ref SR_AVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define AVREG_1_75V              (1)
   /** Constant AVREG_1_84V for sub-register @ref SR_AVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define AVREG_1_84V              (2)
   /** Constant AVREG_1_88V for sub-register @ref SR_AVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define AVREG_1_88V              (3)
  /** Access parameters for sub-register DVREG_EXT in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_DVREG_EXT                 0x10, 0x08, 3
  /** Access parameters for sub-register DVDD_OK in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_DVDD_OK                   0x10, 0x04, 2
  /** Access parameters for sub-register DVREG_TRIM in register @ref RG_VREG_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_DVREG_TRIM                0x10, 0x03, 0
   /** Constant DVREG_1_80V for sub-register @ref SR_DVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define DVREG_1_80V              (0)
   /** Constant DVREG_1_75V for sub-register @ref SR_DVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define DVREG_1_75V              (1)
   /** Constant DVREG_1_84V for sub-register @ref SR_DVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define DVREG_1_84V              (2)
   /** Constant DVREG_1_88V for sub-register @ref SR_DVREG_TRIM
    * @ingroup apiHalPHY230Const
    */
#  define DVREG_1_88V              (3)

/** Offset for register BATMON
 * @ingroup apiHalPHY230Reg
 */
#define RG_BATMON                        (0x11)
# define SR_reserved_11_1             0x11, 0xc0, 6
  /** Access parameters for sub-register BATMON_OK in register @ref RG_BATMON
   * @ingroup apiHalPHY230Sreg
   */
# define SR_BATMON_OK                 0x11, 0x20, 5
  /** Access parameters for sub-register BATMON_HR in register @ref RG_BATMON
   * @ingroup apiHalPHY230Sreg
   */
# define SR_BATMON_HR                 0x11, 0x10, 4
  /** Access parameters for sub-register BATMON_VTH in register @ref RG_BATMON
   * @ingroup apiHalPHY230Sreg
   */
# define SR_BATMON_VTH                0x11, 0x0f, 0

/** Offset for register XOSC_CTRL
 * @ingroup apiHalPHY230Reg
 */
#define RG_XOSC_CTRL                     (0x12)
  /** Access parameters for sub-register XTAL_MODE in register @ref RG_XOSC_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_XTAL_MODE                 0x12, 0xf0, 4
  /** Access parameters for sub-register XTAL_TRIM in register @ref RG_XOSC_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_XTAL_TRIM                 0x12, 0x0f, 0

/** Offset for register FTN_CTRL
 * @ingroup apiHalPHY230Reg
 */
#define RG_FTN_CTRL                      (0x18)
  /** Access parameters for sub-register FTN_START in register @ref RG_FTN_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_FTN_START                 0x18, 0x80, 7
# define SR_reserved_18_2             0x18, 0x40, 6
  /** Access parameters for sub-register FTNV in register @ref RG_FTN_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_FTNV                      0x18, 0x3f, 0

/** Offset for register PLL_CF
 * @ingroup apiHalPHY230Reg
 */
#define RG_PLL_CF                        (0x1a)
  /** Access parameters for sub-register PLL_CF_START in register @ref RG_PLL_CF
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PLL_CF_START              0x1a, 0x80, 7
# define SR_reserved_1a_2             0x1a, 0x70, 4
  /** Access parameters for sub-register PLL_CF in register @ref RG_PLL_CF
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PLL_CF                    0x1a, 0x0f, 0

/** Offset for register PLL_DCU
 * @ingroup apiHalPHY230Reg
 */
#define RG_PLL_DCU                       (0x1b)
  /** Access parameters for sub-register PLL_DCU_START in register @ref RG_PLL_DCU
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PLL_DCU_START             0x1b, 0x80, 7
# define SR_reserved_1b_2             0x1b, 0x40, 6
  /** Access parameters for sub-register PLL_DCUW in register @ref RG_PLL_DCU
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PLL_DCUW                  0x1b, 0x3f, 0

/** Offset for register PART_NUM
 * @ingroup apiHalPHY230Reg
 */
#define RG_PART_NUM                      (0x1c)
  /** Access parameters for sub-register PART_NUM in register @ref RG_PART_NUM
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PART_NUM                  0x1c, 0xff, 0
   /** Constant RF230 for sub-register @ref SR_PART_NUM
    * @ingroup apiHalPHY230Const
    */
#  define RF230                    (2)

/** Offset for register VERSION_NUM
 * @ingroup apiHalPHY230Reg
 */
#define RG_VERSION_NUM                   (0x1d)
  /** Access parameters for sub-register VERSION_NUM in register @ref RG_VERSION_NUM
   * @ingroup apiHalPHY230Sreg
   */
# define SR_VERSION_NUM               0x1d, 0xff, 0

/** Offset for register MAN_ID_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_MAN_ID_0                      (0x1e)
  /** Access parameters for sub-register MAN_ID_0 in register @ref RG_MAN_ID_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_MAN_ID_0                  0x1e, 0xff, 0

/** Offset for register MAN_ID_1
 * @ingroup apiHalPHY230Reg
 */
#define RG_MAN_ID_1                      (0x1f)
  /** Access parameters for sub-register MAN_ID_1 in register @ref RG_MAN_ID_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_MAN_ID_1                  0x1f, 0xff, 0

/** Offset for register SHORT_ADDR_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_SHORT_ADDR_0                  (0x20)
  /** Access parameters for sub-register SHORT_ADDR_0 in register @ref RG_SHORT_ADDR_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_SHORT_ADDR_0              0x20, 0xff, 0

/** Offset for register SHORT_ADDR_1
 * @ingroup apiHalPHY230Reg
 */
#define RG_SHORT_ADDR_1                  (0x21)
  /** Access parameters for sub-register SHORT_ADDR_1 in register @ref RG_SHORT_ADDR_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_SHORT_ADDR_1              0x21, 0xff, 0

/** Offset for register PAN_ID_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_PAN_ID_0                      (0x22)
  /** Access parameters for sub-register PAN_ID_0 in register @ref RG_PAN_ID_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PAN_ID_0                  0x22, 0xff, 0

/** Offset for register PAN_ID_1
 * @ingroup apiHalPHY230Reg
 */
#define RG_PAN_ID_1                      (0x23)
  /** Access parameters for sub-register PAN_ID_1 in register @ref RG_PAN_ID_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_PAN_ID_1                  0x23, 0xff, 0

/** Offset for register IEEE_ADDR_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_0                   (0x24)
  /** Access parameters for sub-register IEEE_ADDR_0 in register @ref RG_IEEE_ADDR_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_0               0x24, 0xff, 0

/** Offset for register IEEE_ADDR_1
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_1                   (0x25)
  /** Access parameters for sub-register IEEE_ADDR_1 in register @ref RG_IEEE_ADDR_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_1               0x25, 0xff, 0

/** Offset for register IEEE_ADDR_2
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_2                   (0x26)
  /** Access parameters for sub-register IEEE_ADDR_2 in register @ref RG_IEEE_ADDR_2
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_2               0x26, 0xff, 0

/** Offset for register IEEE_ADDR_3
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_3                   (0x27)
  /** Access parameters for sub-register IEEE_ADDR_3 in register @ref RG_IEEE_ADDR_3
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_3               0x27, 0xff, 0

/** Offset for register IEEE_ADDR_4
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_4                   (0x28)
  /** Access parameters for sub-register IEEE_ADDR_4 in register @ref RG_IEEE_ADDR_4
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_4               0x28, 0xff, 0

/** Offset for register IEEE_ADDR_5
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_5                   (0x29)
  /** Access parameters for sub-register IEEE_ADDR_5 in register @ref RG_IEEE_ADDR_5
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_5               0x29, 0xff, 0

/** Offset for register IEEE_ADDR_6
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_6                   (0x2a)
  /** Access parameters for sub-register IEEE_ADDR_6 in register @ref RG_IEEE_ADDR_6
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_6               0x2a, 0xff, 0

/** Offset for register IEEE_ADDR_7
 * @ingroup apiHalPHY230Reg
 */
#define RG_IEEE_ADDR_7                   (0x2b)
  /** Access parameters for sub-register IEEE_ADDR_7 in register @ref RG_IEEE_ADDR_7
   * @ingroup apiHalPHY230Sreg
   */
# define SR_IEEE_ADDR_7               0x2b, 0xff, 0

/** Offset for register XAH_CTRL
 * @ingroup apiHalPHY230Reg
 */
#define RG_XAH_CTRL                      (0x2c)
  /** Access parameters for sub-register MAX_FRAME_RETRIES in register @ref RG_XAH_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_MAX_FRAME_RETRIES         0x2c, 0xf0, 4
  /** Access parameters for sub-register MAX_CSMA_RETRIES in register @ref RG_XAH_CTRL
   * @ingroup apiHalPHY230Sreg
   */
# define SR_MAX_CSMA_RETRIES          0x2c, 0x0e, 1
# define SR_reserved_2c_3             0x2c, 0x01, 0

/** Offset for register CSMA_SEED_0
 * @ingroup apiHalPHY230Reg
 */
#define RG_CSMA_SEED_0                   (0x2d)
  /** Access parameters for sub-register CSMA_SEED_0 in register @ref RG_CSMA_SEED_0
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CSMA_SEED_0               0x2d, 0xff, 0

/** Offset for register CSMA_SEED_1
 * @ingroup apiHalPHY230Reg
 */
#define RG_CSMA_SEED_1                   (0x2e)
  /** Access parameters for sub-register MIN_BE in register @ref RG_CSMA_SEED_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_MIN_BE                    0x2e, 0xc0, 6
# define SR_reserved_2e_2             0x2e, 0x30, 4
  /** Access parameters for sub-register I_AM_COORD in register @ref RG_CSMA_SEED_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_I_AM_COORD                0x2e, 0x08, 3
  /** Access parameters for sub-register CSMA_SEED_1 in register @ref RG_CSMA_SEED_1
   * @ingroup apiHalPHY230Sreg
   */
# define SR_CSMA_SEED_1               0x2e, 0x07, 0

# define RG_ANT_DIV                      (0x0d)
//controls antenna diversity

# define RG_RX_CTRL                      (0x0a)
//controls the sensitivity of the antenna diversity mode

//=========================== typedef =========================================

//=========================== variables =======================================

//=========================== prototypes ======================================

#endif


text:
# Cumulative Distribution Function

> [Poisson][poisson-distribution] distribution [cumulative distribution function][cdf].

The [cumulative distribution function][cdf] for a [Poisson][poisson-distribution] random variable is

where `lambda` is the mean parameter. Internally, the module evaluates the CDF by evaluating the upper regularized gamma function at input values `lambda` and `floor( x ) + 1`.

## Usage

```javascript
var cdf = require( '@stdlib/stats/base/dists/poisson/cdf' );
```

#### cdf( x, lambda )

Evaluates the [cumulative distribution function][cdf] for a [Poisson][poisson-distribution] distribution with mean parameter `lambda`.

```javascript
var y = cdf( 2.0, 0.5 );
// returns ~0.986

y = cdf( 2.0, 10.0 );
// returns ~0.003

y = cdf( -1.0, 4.0 );
// returns 0.0
```

If provided `NaN` as any argument, the function returns `NaN`.

```javascript
var y = cdf( NaN, 1.0 );
// returns NaN

y = cdf( 0.0, NaN );
// returns NaN
```

If provided `lambda < 0`, the function returns `NaN`.

```javascript
var y = cdf( 2.0, -1.0 );
// returns NaN
```

If provided `lambda = 0`, the function evaluates the [CDF][cdf] of a [degenerate distribution][degenerate-distribution] centered at `0`.

```javascript
var y = cdf( -2.0, 0.0 );
// returns 0.0

y = cdf( 0.0, 0.0 );
// returns 1.0

y = cdf( 10.0, 0.0 );
// returns 1.0
```

#### cdf.factory( lambda )

Returns a function for evaluating the [cumulative distribution function][cdf] of a [Poisson][poisson-distribution] distribution with mean parameter `lambda`.

```javascript
var mycdf = cdf.factory( 5.0 );
var y = mycdf( 3.0 );
// returns ~0.265

y = mycdf( 8.0 );
// returns ~0.932
```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var cdf = require( '@stdlib/stats/base/dists/poisson/cdf' );

var lambda;
var x;
var y;
var i;

for ( i = 0; i < 10; i++ ) {
    x = randu() * 10.0;
    lambda = randu() * 10.0;
    y = cdf( x, lambda );
    console.log( 'x: %d, λ: %d, F(x;λ): %d', x.toFixed( 4 ), lambda.toFixed( 4 ), y.toFixed( 4 ) );
}
```

[cdf]: https://en.wikipedia.org/wiki/Cumulative_distribution_function

[degenerate-distribution]: https://en.wikipedia.org/wiki/Degenerate_distribution

[poisson-distribution]: https://en.wikipedia.org/wiki/Poisson_distribution

redpajama_set_name: RedPajamaGithub


text:
package com.github.dreamhead.moco.util;

import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;

import java.nio.charset.Charset;

import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Optional.of;

public final class FileContentType {
    public static final String DEFAULT_CONTENT_TYPE_WITH_CHARSET = "text/plain; charset=UTF-8";
    private static final String DEFAULT_CONTENT_TYPE = "text/plain";

    private static final ImmutableMap<String, String> contentTypeMap = ImmutableMap.<String, String>builder()
            .put("png", "image/png")
            .put("gif", "image/gif")
            .put("jpg", "image/jpeg")
            .put("jpeg", "image/jpeg")
            .put("tiff", "image/tiff")
            .put("css", "text/css")
            .put("html", "text/html")
            .put("txt", "text/plain")
            .put("js", "application/x-javascript")
            .put("json", "application/json")
            .put("pdf", "application/pdf")
            .put("zip", "application/zip")
            .put("xml", "text/xml")
            .build();

    private final String filename;
    private final Optional<Charset> charset;

    public FileContentType(final String filename, final Optional<Charset> charset) {
        this.filename = filename;
        this.charset = charset;
    }

    public String getContentType() {
        Optional<String> optionalType = toContentType(Files.getFileExtension(filename));
        Optional<Charset> charset = toCharset(optionalType);

        String type = optionalType.or(DEFAULT_CONTENT_TYPE);
        if (charset.isPresent()) {
            return type + "; charset=" + charset.get().displayName();
        }

        return type;
    }

    private Optional<Charset> toCharset(final Optional<String> type) {
        if (charset.isPresent()) {
            return charset;
        }

        if (!type.isPresent()) {
            return of(Charsets.UTF_8);
        }

        return absent();
    }

    private Optional<String> toContentType(final String extension) {
        return fromNullable(contentTypeMap.get(extension.toLowerCase()));
    }
}


text:
#pragma once
#include <aws/apigateway/APIGateway_EXPORTS.h>
#include <aws/apigateway/APIGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace APIGateway
{
namespace Model
{

  /**
   *
A request to delete the DomainName resource.

   */
  class AWS_APIGATEWAY_API DeleteDomainNameRequest : public APIGatewayRequest
  {
  public:
    DeleteDomainNameRequest();
    Aws::String SerializePayload() const override;

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline DeleteDomainNameRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline DeleteDomainNameRequest& WithDomainName(Aws::String&& value) { SetDomainName(value); return *this;}

    /**
     *
The name of the DomainName resource to be deleted.

     */
    inline DeleteDomainNameRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}

  private:
    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;
  };

} // namespace Model
} // namespace APIGateway
} // namespace Aws


text:
package cn.bmob.zuqiu.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Calendar;
import java.util.Date;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.zuqiu.MyApplication;
import cn.bmob.zuqiu.R;
import cn.bmob.zuqiu.ui.base.BaseActivity;
import cn.bmob.zuqiu.utils.TimeUtils;
import cn.bmob.zuqiu.view.views.CityPicker;
import cn.bmob.zuqiu.view.views.DatePicker;
import cn.bmob.zuqiu.view.views.TimePicker;
import cn.bmob.zuqiuj.bean.User;

/**
 * 创建比赛
 */
public class CreateCompetitionActivity extends BaseActivity{

	EditText cpDate;
	EditText cpPeriod;
	EditText cpSite;
    EditText cpCity;
	Button cpNext;

	private BmobDate date;
	private BmobDate begin;
	private BmobDate end;
	private String site;
    private String cityCode;
	private Date comDate;

	private User user;

	@Override
	protected void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		setViewContent(R.layout.activity_create_competition);
		setUpAction(mActionBarTitle, "添加比赛记录", 0, View.VISIBLE);
		setUpAction(mActionBarLeftMenu, "", R.drawable.back_actionbar, View.VISIBLE);
		user = BmobUser.getCurrentUser(mContext, User.class);
	}

	@Override
	protected void findViews(View contentView) {
		// TODO Auto-generated method stub
		cpDate = (EditText)contentView.findViewById(R.id.cp_date_content);
		cpPeriod = (EditText)contentView.findViewById(R.id.cp_period_content);
		cpSite = (EditText)contentView.findViewById(R.id.cp_site_content);
        cpCity = (EditText) contentView.findViewById(R.id.cp_city_content);
		cpNext = (Button)contentView.findViewById(R.id.cp_create_next);

		cpDate.setInputType(InputType.TYPE_NULL);
		cpPeriod.setInputType(InputType.TYPE_NULL);
		cpCity.setInputType(InputType.TYPE_NULL);

		cpDate.setOnClickListener(this);
		cpPeriod.setOnClickListener(this);
		cpSite.setOnClickListener(this);
        cpCity.setOnClickListener(this);
		cpNext.setOnClickListener(this);
	}

	@Override
	protected void onLeftMenuClick() {
		// TODO Auto-generated method stub
		super.onLeftMenuClick();
		finish();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.cp_date_content:
			showTimeDialog(mContext,getDateView());

			break;
		case R.id.cp_period_content:
			if(date==null){
				showToast("请先设置比赛日期");
				return;
			}
			showTimeDialog(mContext, getBeginView());
			break;
		case R.id.cp_site_content:

			break;
        case R.id.cp_city_content:
            showSelectCityDialog();
            break;
		case R.id.cp_create_next:
			if(null==date){
				showToast("请选择比赛日期");
				return;
			}

			if(null==begin){
				showToast("请选择比赛开始时间");
				return;
			}

//			if(null==end){
//				showToast("请选择比赛结束日期。");
//				return;
//			}

			site = cpSite.getText().toString().trim();
			if(TextUtils.isEmpty(site)){
				showToast("请输入地点");
				return;
			}

            if(TextUtils.isEmpty(cityCode)){
                showToast("请输选择城市");
                return;
            }

			MyApplication.getInstance().getmTournament().setEvent_date(date);//比赛日期
			MyApplication.getInstance().getmTournament().setStart_time(begin);//比赛时间
			MyApplication.getInstance().getmTournament().setCity(cityCode);//比赛城市
			MyApplication.getInstance().getmTournament().setSite(site);//比赛地点
			MyApplication.getInstance().getmTournament().setState(false);

			redictTo(mContext, ChooseHomeTeamActivity.class, null);
			break;
		default:
			break;
		}
	}

    /**
     * 打开城市选择对话框
     */
    private void showSelectCityDialog(){
        final Dialog timeDialog = new AlertDialog.Builder(this).create();
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_city_picker, null);

        timeDialog.setCanceledOnTouchOutside(true);
        timeDialog.show();
        timeDialog.setContentView(view);
        final CityPicker cityPicker = (CityPicker) view.findViewById(R.id.cityPicker);
        view.findViewById(R.id.date_commit).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//                showToast("您选择的城市是:"+cityPicker.getCity_string()+cityPicker.getcity_name()+"----"+cityPicker.getCounty_code()+"  市代码:"+cityPicker.getCity_code());
                cpCity.setText(cityPicker.getCity_string());
                cityCode = cityPicker.getCity_code();
                timeDialog.cancel();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                timeDialog.cancel();
            }
        });
    }

	Dialog timeDialog = null;
	private void showTimeDialog(Context context,View view){
		if(timeDialog == null){
			timeDialog = new AlertDialog.Builder(context).create();
		}
		timeDialog.show();
		timeDialog.setCanceledOnTouchOutside(false);
		timeDialog.setContentView(view);
		timeDialog.getWindow().setGravity(Gravity.CENTER);
		timeDialog.getWindow().setLayout(
				getWindowManager().getDefaultDisplay().getWidth()-30,
				android.view.WindowManager.LayoutParams.WRAP_CONTENT);
	}

	/**
	 * 处理日期选择
	 * @return
	 */
	private View getDateView() {
		View view = LayoutInflater.from(CreateCompetitionActivity.this).inflate(
				R.layout.dialog_date_picker, null);
		TextView title = (TextView)view.findViewById(R.id.picker_title);
		title.setText("选择日期");
		final DatePicker datePicker = (DatePicker)view.findViewById(R.id.datePicker);
		datePicker.setYearMin(Integer.parseInt(TimeUtils.getCurrentYear()));
		Button commit = (Button)view.findViewById(R.id.date_commit);
		commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar mCalendar = Calendar.getInstance();
				mCalendar.set(Calendar.YEAR, datePicker.getYear());
				mCalendar.set(Calendar.MONTH, datePicker.getMonth());
				mCalendar.set(Calendar.DAY_OF_MONTH, datePicker.getDay());
				mCalendar.set(Calendar.HOUR_OF_DAY, 0);
				mCalendar.set(Calendar.MINUTE,0);
				mCalendar.set(Calendar.SECOND, 0);
				comDate = mCalendar.getTime();
				date = new BmobDate(mCalendar.getTime());
				cpDate.setText(getStringByDate(date));
//				birthContent.setText(new BmobDate(mCalendar.getTime()).getDate().substring(0, 10));
				if(timeDialog!=null&&timeDialog.isShowing()){
					timeDialog.dismiss();
				}
			}
		});
		return view;
	}

	private boolean isSecond = false;
	/**
	 * 处理日期选择
	 * @return
	 */
	private View getBeginView() {
		View view = LayoutInflater.from(CreateCompetitionActivity.this).inflate(
				R.layout.dialog_time_picker, null);
		final TextView title = (TextView)view.findViewById(R.id.picker_title);
		title.setText("选择开始时间");
		final TimePicker timePicker = (TimePicker)view.findViewById(R.id.timePicker);
		timePicker.setIs24Hour(true);
		Button commit = (Button)view.findViewById(R.id.time_commit);
		commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar mCalendar = Calendar.getInstance();
				mCalendar.setTime(comDate);
//				mCalendar.set(Calendar.YEAR, getCalendarByDate(comDate).get(Calendar.YEAR));
//				mCalendar.set(Calendar.MONTH, getCalendarByDate(comDate).get(Calendar.MONTH));
//				mCalendar.set(Calendar.DAY_OF_MONTH, getCalendarByDate(comDate).get(Calendar.DAY_OF_YEAR));
				mCalendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
				mCalendar.set(Calendar.MINUTE,timePicker.getMinute());
				mCalendar.set(Calendar.SECOND, 0);
//				if(isSecond){
//					end = new BmobDate(mCalendar.getTime());
//					cpPeriod.setText(cpPeriod.getText()+getTimeByDate(end));
//					isSecond = false;
//					if(timeDialog!=null&&timeDialog.isShowing()){
//						timeDialog.dismiss();
//					}
//				}else{

//					Calendar mCalendar2 = Calendar.getInstance();
//					mCalendar2.setTime(new Date());
//					if(mCalendar2.getTimeInMillis()-mCalendar.getTimeInMillis()>0){
//						showToast("您不能选择以前的时间。请重新选择");
//						return;
//					}else{
						begin = new BmobDate(mCalendar.getTime());
						cpPeriod.setText(getTimeByDate(begin));//+" 至 ");
						if(timeDialog!=null&&timeDialog.isShowing()){
							timeDialog.dismiss();
						}
//					}

//					isSecond = true;
//					if(isSecond){
//						title.setText("选择结束时间");
//						showToast("选择结束时间");
//					}
//
//				}
//				birthContent.setText(new BmobDate(mCalendar.getTime()).getDate().substring(0, 10));
//				if(timeDialog!=null&&timeDialog.isShowing()){
//					timeDialog.dismiss();
//				}

//				showTimeDialog(mContext, getEndView());
			}
		});
		return view;
	}

	/**
	 * 处理日期选择
	 * @return
	 */
	private View getEndView() {
		View view = LayoutInflater.from(CreateCompetitionActivity.this).inflate(
				R.layout.dialog_time_picker, null);
		TextView title = (TextView)view.findViewById(R.id.picker_title);
		title.setText("选择结束时间");
		final TimePicker timePicker = (TimePicker)view.findViewById(R.id.timePicker);
		timePicker.setIs24Hour(true);
		Button commit = (Button)view.findViewById(R.id.time_commit);
		commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar mCalendar = Calendar.getInstance();
				mCalendar.setTime(comDate);
//				mCalendar.set(Calendar.YEAR, getCalendarByDate(comDate).get(Calendar.YEAR));
//				mCalendar.set(Calendar.MONTH, getCalendarByDate(comDate).get(Calendar.MONTH));
//				mCalendar.set(Calendar.DAY_OF_MONTH, getCalendarByDate(comDate).get(Calendar.DAY_OF_YEAR));
				mCalendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
				mCalendar.set(Calendar.MINUTE,timePicker.getMinute());
				mCalendar.set(Calendar.SECOND, 0);
				end = new BmobDate(mCalendar.getTime());
				cpPeriod.setText(cpPeriod.getText()+getTimeByDate(end));
//				birthContent.setText(new BmobDate(mCalendar.getTime()).getDate().substring(0, 10));
				if(timeDialog!=null&&timeDialog.isShowing()){
					timeDialog.dismiss();
				}
			}
		});
		return view;
	}

	/*
	 * 根据用户选择的日期生成相应的文字
	 */
	private String getStringByDate(BmobDate date){
		String time = date.getDate();
		return time.substring(0, 4)+"年"+time.substring(5,7)+"月"+time.substring(8,10)+"日";
	}

	private String getTimeByDate(BmobDate date){
		String time = date.getDate();
		return time.substring(11, 16);
	}

	private Calendar getCalendarByDate(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}
}


text:
asyncTest( "Popcorn 1.0 TTML Parser Plugin", function () {
  var count = 0,
      numSubs = 0,
      sub,
      poppercorn = Popcorn( "#video" ),
      subs = [
        {
          id: "subtitle1",
          text: "It seems a paradox, does it not,",
          target: "subtitleArea",
          start: 0.76,
          end: 3.45
        },
        {
          id: "subtitle2",
          text: "that the image formed on
the Retina should be inverted?",
          target: "subtitleArea",
          start: 5,
          end: 10
        },
        {
          id: "subtitle3",
          text: "It is puzzling, why is it
we do not see things upside-down?",
          target: "subtitleArea",
          start: 10,
          end: 16
        },
        {
          id: "subtitle4",
          text: "You have never heard the Theory,
then, that the Brain also is inverted?",
          target: "customRegion",
          start: 17.2,
          end: 23
        },
        {
          id: "subtitle5",
          text: "No indeed! What a beautiful fact!",
          target: "subtitleArea",
          start: 23,
          end: 27
        },
        {
          id: "subtitle6",
          text: "It seems a paradox, does it not,",
          target: "subtitle-container",
          start: 27.76,
          end: 30.45
        },
        {
          id: "subtitle7",
          text: "that the image formed on
the Retina should be inverted?",
          target: "subtitle-container",
          start: 33,
          end: 37
        },
        {
          id: "subtitle8",
          text: "It is puzzling, why is it
we do not see things upside-down?",
          target: "subtitle-container",
          start: 37,
          end: 43
        },
        {
          id: "subtitle9",
          text: "You have never heard the Theory,
then, that the Brain also is inverted?",
          target: "subtitle-container",
          start: 44.2,
          end: 50
        },
        {
          id: "subtitle10",
          text: "No indeed! What a beautiful fact!",
          target: "subtitle-container",
          start: 50,
          end: 54
        }
      ],
      expects = subs.length * 5 + 1;

  function plus() {
    if ( ++count === expects ) {
      start();
    }
  }

  poppercorn.parseTTML( "data/unit.ttml", function(){
    Popcorn.forEach( poppercorn.getTrackEvents(), function( evt ) {
      if( evt._natives.type === "subtitle" ) {
        sub = subs[ numSubs++ ];

        strictEqual( evt.id, sub.id, "Correctly parsed id of " + evt.id );
        plus();
        strictEqual( evt.start, sub.start, "Correctly parsed start of " + evt.id + " at " + evt.start );
        plus();
        strictEqual( evt.text, sub.text, "Correctly parsed text of " + evt.id + " at " + evt.start );
        plus();
        strictEqual( evt.target, sub.target, "Correctly parsed target of " + evt.id + " at " + evt.start );
        plus();
        strictEqual( evt.end, sub.end, "Correctly parsed end of " + evt.id + " at " + evt.start );
        plus();
      }
    });

    strictEqual( subs.length, numSubs, "Parsed all subtitles" );
    plus();
  });

  expect( expects );
});


text:
import re
import logging
from twisted.conch.telnet import TelnetTransport, TelnetProtocol
from twisted.internet import reactor, endpoints, task
from twisted.internet.protocol import ServerFactory
import game_loop

logger = logging.getLogger(__name__)

reset = "\x1B[0m"
bold = "\x1B[1m"
dim = "\x1B[2m"
under = "\x1B[4m"
reverse = "\x1B[7m"
hide = "\x1B[8m"

clearscreen = "\x1B[2J"
clearline = "\x1B[2K"

black = "\x1B[30m"
red = "\x1B[31m"
green = "\x1B[32m"
yellow = "\x1B[33m"
blue = "\x1B[34m"
magenta = "\x1B[35m"
cyan = "\x1B[36m"
white = "\x1B[37m"

bblack = "\x1B[40m"
bred = "\x1B[41m"
bgreen = "\x1B[42m"
byellow = "\x1B[43m"
bblue = "\x1B[44m"
bmagenta = "\x1B[45m"
bcyan = "\x1B[46m"
bwhite = "\x1B[47m"
concealed = "\x1B[8m"

newline = "\r\n"
carriage_return = "\r"

TELNET_REPLACEMENTS = dict(reset=reset,
                           bold=bold,
                           dim=dim,
                           under=under,
                           reverse=reverse,
                           hide=hide,
                           clearscreen=clearscreen,
                           clearline=clearline,
                           black=black,
                           red=red,
                           green=green,
                           yellow=yellow,
                           blue=blue,
                           magenta=magenta,
                           cyan=cyan,
                           white=white,
                           bblack=bblack,
                           bred=bred,
                           bgreen=bgreen,
                           byellow=byellow,
                           bblue=bblue,
                           bmagenta=bmagenta,
                           bcyan=bcyan,
                           bwhite=bwhite,
                           concealed=concealed,
                           newline=newline,
                           carriage_return=carriage_return)

########################################################################
def tf(text):
    """
    Replace the telnet tags with the telnet escape values.
    """
    text = str(text)
    for key, value in TELNET_REPLACEMENTS.items():
        text = text.replace("<" + key + ">", value)
    return text

########################################################################
class MudTelnetHandler(object):
    ####################################################################
    def __init__(self, protocol):
        self.protocol = protocol
        self.data_handlers = []

    ####################################################################
    def send(self, data):
        self.protocol.send(data)

    ####################################################################
    def get_remote_address(self):
        if self.protocol:
            return self.protocol.get_remote_address()
        else:
            return "<unknown address>"

    ####################################################################
    def leave(self):
        logger.info("%s - leave called in %s", self.get_remote_address(), self.__class__.__name__)

    ####################################################################
    def enter(self):
        logger.info("%s - enter called in %s", self.get_remote_address(), self.__class__.__name__)

    ####################################################################
    def hung_up(self):
        logger.warn("%s - hung up in %s", self.get_remote_address(), self.__class__.__name__)

    ####################################################################
    def flooded(self):
        logger.warn("%s - flooded in %s", self.get_remote_address(), self.__class__.__name__)

    ####################################################################
    def handle(self, data):
        raise NotImplementedError

########################################################################
class BaseStateDispatchHandler(MudTelnetHandler):
    initial_state = None
    state = None

    ####################################################################
    def handle(self, data):
        method_name = ("handle_%s" % self.state.name).lower()
        logger.info("Received '%s', passing it to handler %s", data, method_name)
        getattr(self, method_name)(data)

########################################################################
class BaseCommandDispatchHandler(MudTelnetHandler):
    last_command = None

    ####################################################################
    def _register_data_handler(self, predicate, handler):
        self.data_handlers.append((predicate, handler))

    ####################################################################
    def handle(self, data):
        if data:
            split = data.split(None, 1)
            first_word = data.split(None, 1)[0]
            if len(split) > 1:
                rest = split[1]
            else:
                rest = ""

            for predicate, handler in self.data_handlers:
                if self.check_predicate(predicate, first_word):
                    handler(data, first_word, rest)
                    if predicate != "/":
                        self.last_command = data
                    return

    ####################################################################
    def check_predicate(self, predicate, data):
        if isinstance(predicate, basestring):
            return predicate == data
        elif isinstance(predicate, list) or isinstance(predicate, tuple):
            return data in predicate
        elif isinstance(predicate, bool):
            return predicate
        elif isinstance(predicate, re._pattern_type):
            if predicate.match(data):
                return True
            else:
                return False
        else:
            raise ValueError("I don't know how to use the predicate '%s' of type '%s'" % predicate, type(predicate))

########################################################################
class MudTelnetProtocol(TelnetProtocol):
    handler_class = None
    closed = False

    ####################################################################
    def __init__(self):
        self.handlers = []
        self.handlers.append(self.handler_class(self))

    ####################################################################
    @classmethod
    def set_handler_class(cls, handler_class):
        cls.handler_class = handler_class

    ####################################################################
    @property
    def handler(self):
        if self.handlers:
            return self.handlers[-1]

    ####################################################################
    def get_remote_address(self):
        if self.transport:
            return self.transport.getPeer()
        else:
            return "<unknown address>"

    ####################################################################
    def add_handler(self, handler):
        if self.handler:
            self.handler.leave()
        self.handlers.append(handler)
        self.handler.enter()

    ####################################################################
    def drop_connection(self):
        self.transport.loseConnection()

    ####################################################################
    def remove_handler(self):
        if self.handler:
            self.handler.leave()
            self.handlers.pop(-1)
            if self.handler:
                self.handler.enter()

    ####################################################################
    def clear_handlers(self):
        if self.handler:
            self.handler.leave()
        self.handlers = []

    ####################################################################
    def enableRemote(self, option):
        return False

    ####################################################################
    def disableRemote(self, option):
        pass

    ####################################################################
    def enableLocal(self, option):
        return False

    ####################################################################
    def disableLocal(self, option):
        pass

    ####################################################################
    def send(self, data):
        if not data.endswith("<concealed>"):
            data += "<reset>"
        data = tf(data)
        self.transport.write(data)

    ####################################################################
    def dataReceived(self, data):
        data = data.strip()
        self.handler.handle(data)

    ####################################################################
    def connectionMade(self):
        self.handler.enter()

    ####################################################################
    def connectionLost(self, reason=None):
        self.closed = True

########################################################################
def initialize_logger(logging_level=logging.INFO):
    logging.basicConfig(level=logging_level, format="[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", datefmt="%d/%b/%Y %H:%M:%S")

########################################################################
def stop():
    logger.info("Shutting down the reactor...")
    reactor.stop()

########################################################################
def run():
    initialize_logger(logging.INFO)
    factory = ServerFactory()
    factory.protocol = lambda: TelnetTransport(MudTelnetProtocol)
    endpoints.serverFromString(reactor, "tcp:8023").listen(factory)

    round_timer = task.LoopingCall(game_loop.perform_round)
    round_timer.start(game_loop.ROUND_TIME)

    db_timer = task.LoopingCall(game_loop.save_databases)
    db_timer.start(game_loop.DB_SAVE_TIME)

    heal_timer = task.LoopingCall(game_loop.perform_heal)
    heal_timer.start(game_loop.HEAL_TIME)

    regen_timer = task.LoopingCall(game_loop.perform_regen)
    regen_timer.start(game_loop.REGEN_TIME)

    print "running on port 8023..."
    reactor.run()


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="CpH1C13adamSET" author="Agilent" investigator=""
        time_created="20111219T120000" tabname="BioSolidsPack" menu1="Commands" menu2="Set Values" apptype="solidsseq1d"
        application="BioSolids" scans="CpH1C13adamSET" seqfil="ahX">
  <protocol title="CpH1C13adamSET" type="protocol">
    <action  type="CMD" status="Ready" lock="off" title="CpH1C13adamSET" exp="CpH1C13adamSET"
        time="1:45" macro="CpH1C13adamSET" data="" />
  </protocol>
</template>


text:
<?php

header('Content-Type: text/plain; charset=utf-8');

try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    /*
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'json' => 'application/json',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }
    */

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./gamestats.json',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}

?>


text:
require 'thread'
require 'bluepill/system'
require 'bluepill/process_journal'

module Bluepill
  class Application
    PROCESS_COMMANDS = [:start, :stop, :restart, :unmonitor, :status].freeze

    attr_accessor :name, :logger, :base_dir, :socket, :pid_file, :kill_timeout
    attr_accessor :groups, :work_queue
    attr_accessor :pids_dir, :log_file

    def initialize(name, options = {})
      self.name = name

      @foreground   = options[:foreground]
      self.log_file = options[:log_file]
      self.base_dir = ProcessJournal.base_dir = options[:base_dir] ||
        ENV['BLUEPILL_BASE_DIR'] ||
        (::Process.euid != 0 ? File.join(ENV['HOME'], '.bluepill') : '/var/run/bluepill')
      self.pid_file = File.join(base_dir, 'pids', self.name + '.pid')
      self.pids_dir = File.join(base_dir, 'pids', self.name)
      self.kill_timeout = options[:kill_timeout] || 10

      self.groups = {}

      self.logger = ProcessJournal.logger = Bluepill::Logger.new(log_file: log_file, stdout: foreground?).prefix_with(self.name)

      setup_signal_traps
      setup_pids_dir

      @mutex = Mutex.new
    end

    def foreground?
      !!@foreground
    end

    def mutex(&b)
      @mutex.synchronize(&b)
    end

    def load
      start_server
    rescue StandardError => e
      $stderr.puts('Failed to start bluepill:')
      $stderr.puts(format('%s `%s`', e.class.name, e.message))
      $stderr.puts(e.backtrace)
      exit(5)
    end

    PROCESS_COMMANDS.each do |command|
      class_eval <<-END
        def #{command}(group_name = nil, process_name = nil)
          self.send_to_process_or_group(:#{command}, group_name, process_name)
        end
      END
    end

    def add_process(process, group_name = nil)
      group_name = group_name.to_s if group_name

      groups[group_name] ||= Group.new(group_name, logger: logger.prefix_with(group_name))
      groups[group_name].add_process(process)
    end

    def version
      Bluepill::Version
    end

  protected

    def send_to_process_or_group(method, group_name, process_name)
      if group_name.nil? && process_name.nil?
        groups.values.collect do |group|
          group.send(method)
        end.flatten
      elsif groups.key?(group_name)
        groups[group_name].send(method, process_name)
      elsif process_name.nil?
        # they must be targeting just by process name
        process_name = group_name
        groups.values.collect do |group|
          group.send(method, process_name)
        end.flatten
      else
        []
      end
    end

    def start_listener
      @listener_thread.kill if @listener_thread
      @listener_thread = Thread.new do
        loop do
          begin
            client = socket.accept
            client.close_on_exec = true  if client.respond_to?(:close_on_exec=)
            command, *args = client.readline.strip.split(':')
            response = begin
              mutex { send(command, *args) }
            rescue => e
              e
            end
            client.write(Marshal.dump(response))
          rescue StandardError => e
            logger.err(format('Got exception in cmd listener: %s `%s`', e.class.name, e.message))
            e.backtrace.each { |l| logger.err(l) }
          ensure
            begin
              client.close
            rescue IOError
              # closed stream
            end
          end
        end
      end
    end

    def start_server
      kill_previous_bluepill
      ProcessJournal.kill_all_from_all_journals
      ProcessJournal.clear_all_atomic_fs_locks

      begin
        ::Process.setpgid(0, 0)
      rescue Errno::EPERM
      end

      Daemonize.daemonize unless foreground?

      logger.reopen

      $0 = "bluepilld: #{name}"

      groups.each { |_, group| group.determine_initial_state }

      write_pid_file
      self.socket = Bluepill::Socket.server(base_dir, name)
      start_listener

      run
    end

    def run
      @running = true # set to false by signal trap
      while @running
        mutex do
          System.reset_data
          groups.each { |_, group| group.tick }
        end
        sleep 1
      end
    end

    def cleanup
      ProcessJournal.kill_all_from_all_journals
      ProcessJournal.clear_all_atomic_fs_locks
      begin
        System.delete_if_exists(socket.path) if socket
      rescue IOError
      end
      System.delete_if_exists(pid_file)
    end

    def setup_signal_traps
      terminator = proc do
        puts 'Terminating...'
        cleanup
        @running = false
      end

      Signal.trap('TERM', &terminator)
      Signal.trap('INT', &terminator)

      Signal.trap('HUP') do
        logger.reopen if logger
      end
    end

    def setup_pids_dir
      FileUtils.mkdir_p(pids_dir) unless File.exist?(pids_dir)
      # we need everybody to be able to write to the pids_dir as processes managed by
      # bluepill will be writing to this dir after they've dropped privileges
      FileUtils.chmod(0777, pids_dir)
    end

    def kill_previous_bluepill
      return unless File.exist?(pid_file)
      previous_pid = File.read(pid_file).to_i
      return unless System.pid_alive?(previous_pid)
      ::Process.kill(0, previous_pid)
      puts "Killing previous bluepilld[#{previous_pid}]"
      ::Process.kill(2, previous_pid)
    rescue => e
      $stderr.puts 'Encountered error trying to kill previous bluepill:'
      $stderr.puts "#{e.class}: #{e.message}"
      exit(4) unless e.is_a?(Errno::ESRCH)
    else
      kill_timeout.times do |_i|
        sleep 0.5
        break unless System.pid_alive?(previous_pid)
      end

      if System.pid_alive?(previous_pid)
        $stderr.puts "Previous bluepilld[#{previous_pid}] didn't die"
        exit(4)
      end
    end

    def write_pid_file
      File.open(pid_file, 'w') { |x| x.write(::Process.pid) }
    end
  end
end


text:
<script>
    $(function(){

        $("#add").click(function(){
            window.location.href = '${rc.contextPath}/sys/role/addVM';
        });

        $(".am-pagination a").click(function(){
            var page = $(this).text();
            var username = $('#name').val();
            window.location.href = '${rc.contextPath}/sys/role/list?page=' + page + '&username=' + username;
        });

        $("#search").click(function(){
            var name = $('#name').val();
            window.location.href = '${rc.contextPath}/sys/role/list?name=' + name;
        });

    });

    function edit(id){
        window.location.href = '${rc.contextPath}/sys/role/editVM?id=' + id;
    }

    function remove(id){
        if(confirm("确认要删除吗?")){
            var url = '${rc.contextPath}/sys/role/remove';
            $.post(url, { id : id }, function(){
                window.location.reload();
            });

        }
    }

</script>


text:
const m = require('../modules/utils.js');
const fs = require('fs');
const path = require('path');

const randStr = new Date().getTime();

function readHTMLInDirectory(_path) {
  return new Promise((resolve, reject) => {
    let htmls = [];
    m.traverse(
      _path,
      function(pathname) {
        if (path.extname(pathname) == '.html') {
          htmls.push(pathname);
        }
      },
      () => {
        resolve(htmls);
      },
      false
    );
  }).catch((err) => {
    throw err;
  });
}

function editNameFromHTML(htmlpath, randStr) {
  return new Promise((resolve, reject) => {
    fs.readFile(htmlpath, 'utf8', function(err, data) {
      if (err) reject(err);

      var css_reg = /css\/[^<]{1,}\.css/g;
      var js_reg = /\/pricing[^<]*\.js/g;
      var css = data.match(css_reg);
      var js = data.match(js_reg);

      css.forEach(async (value) => {
        value = value.replace('css/', '');
        var newValue = value.split('.')[0] + '.' + randStr + '.css';
        data = data.replace(value, newValue);
        await fs.writeFile(htmlpath, data, () => {
          // css修改后开始修改js
          js.forEach(async (value) => {
            value = value.replace('/', '');
            var newValue = value.split('.')[0] + '.' + randStr + '.js';
            data = data.replace(value, newValue);
            await fs.writeFile(htmlpath, data, () => {
              resolve();
            });
          });
        });
      });
    });
  }).catch((err) => {
    throw err;
  });
}

function editHtmls(htmls) {
  htmls.map(async (value) => {
    await editNameFromHTML(value, randStr);
  });

  console.log('html修改完成');
}

function renameJS(jspath, filternames = [], randStr) {
  return new Promise((resolve, reject) => {
    fs.readdir(jspath, function(err, data) {
      if (err) reject(err);
      data.forEach(async (value) => {
        if (new RegExp(filternames.join('|')).test(value)) {
          let oldpath = value;
          value = value.replace('/', '');
          var newValue = value.split('.')[0] + '.' + randStr + '.js';
          let newpath = newValue;
          await fs.rename(
            path.join(jspath, oldpath),
            path.join(jspath, newpath),
            (err) => {
              resolve();
            }
          );
        }
      });
    });
  }).catch((err) => {
    throw err;
  });
}

function renameCSS(jspath, filternames = [], randStr) {
  return new Promise((resolve, reject) => {
    fs.readdir(jspath, function(err, data) {
      if (err) reject(err);
      data.forEach(async (value) => {
        if (new RegExp(filternames.join('|')).test(value)) {
          let oldpath = value;
          value = value.replace('/', '');
          var newValue = value.split('.')[0] + '.' + randStr + '.css';
          let newpath = newValue;
          await fs.rename(
            path.join(jspath, oldpath),
            path.join(jspath, newpath),
            (err) => {
              resolve();
            }
          );
        }
      });
    });
  }).catch((err) => {
    throw err;
  });
}

readHTMLInDirectory('../asset').then((res) => {
  editHtmls(res);
});

// renameJS('../../../detail-page/js', ['pricing'], randStr);
// renameCSS('../../../detail-page/css', ['common'], randStr);


text:
This module is aimed at enabling easy communication from a game to an
implementation of the `pge-ws-server` example Node.js server.

## About AppMessage Keys

Due to limitations in PebbleKit JS, AppMessage keys must be declared in
`appinfo.json`. To accomodate for this, 16 intial keys have been declared, named
`PGE_WS_KEY_X`, where `X` is `0` to `15`. You should repurpose these for app-
specific data, as shown in the example of `onClientConnected()` shown below. If
you need more, add them to your own implementation. If you do, don't forget to
update the value of `PGE_WS_NUM_KEYS` in `pge/modules/pge_ws.h`!

You should repurpose your keys in the following manner:

```
#define TOTAL_PLAYERS PGE_WS_KEY_0
```

## Preparing the Server

Edit `pge-ws-server/app.js` to implement the `onClientConnected()` and
`onClientMessage()` functions to turn client communication into Pebble
AppMessages. For example:

```
function onClientConnected(socket) {
  // Send text to server
  socket.send(JSON.stringify({ 'PGE_WS_KEY_0': 42 }));
}

function onClientDisconnected(client) {

}

function onClientMessage(socket, data) {
  var json = JSON.parse(data);

  // Process data from server
  if(json['PGE_WS_KEY_0']) {
    var someValue = json['PGE_WS_KEY_0'];

    // Send data on to Pebble
    Pebble.sendAppMessage({ 'PGE_WS_KEY_0': parseInt(someValue) });
  }
}
```

## Connecting to a Server

The client **MUST** wait for the phone to signal PebbleKit JS is ready with the
'ready' event. To accomodate for this, prepare PGE WS in app initialization,
supplying the URL, and two handlers for when the connection attempt returns, and
when data is received.

When the 'ready' event is received, the connection will be attempted and the
result passed to the `PGEWSConnectedHandler`. At this point, each successfully
connected client is given an ID by the server, and can be read with
`pge_ws_get_client_id()`:

```
static void ws_connection_handler(bool successful) {
  APP_LOG(APP_LOG_LEVEL_INFO, "Got ID: %d", pge_ws_get_client_id());
}

static void ws_received_handler() {

}

void pge_init() {
  // Start engine
  pge_begin(logic, draw, click);

  // Prepare WS for web communication with local server
  pge_ws_begin("ws://192.168.1.4:5000", ws_connection_handler, ws_received_handler);
}
```

## Disconnecting From a Server

Currently, any `AppMessage`s sent during app deinitialization (when the Back
button causes it to exit) are not successfully sent to the server. Therefore,
every client will be abandoned by the server after `EXPIRATION_MS` milliseconds
(default value is 10 minutes). Of course, WebSockets can be manually closed at
any time, and an app exiting on a real watch will trigger the connection to
close automatically (tested only on Android 4.4.5).

## Receiving Data

Read data with `pge_ws_get_value()` inside a `PGEWSReceivedHandler`
implementation, which is called everytime a packet arrives with at least one
`Tuple` in the pre-declared `AppMessage` key range (from `0` to
`PGE_WS_NUM_KEYS`). This mechanism is designed this way so that multiple key
values can be retrieved at once, useful for retrieving points or vectors. For
example:

```
// Attempt to read a value
int key_0_value = pge_ws_get_value(PGE_WS_KEY_0);

// Check this packet contains what we want
if(key_0_value != PGE_WS_NOT_FOUND) {
  // Use the value!
  APP_LOG(APP_LOG_LEVEL_INFO, "Got PGE_WS_KEY_0 value: %d", key_0_value);
}
```

The alternative paradigm is passing every received value into a callback. This
does not allow the order of callbacks to be easily determined, and would make
reading multiple values from one packet more difficult.

## Sending Data

To send data from the C side, begin a packet, add values, then send it:

```
// If connected to server
if(pge_ws_is_connected()) {
  // If beginning a packet was successful
  if(pge_ws_packet_begin()) {
    // Add some data
    pge_ws_add_int(PGE_WS_KEY_0, 42);

    // Send the data!
    pge_ws_packet_send();
  }
}
```

These values are then automatically sent to the server in
`PGEWSForwardToServer()`.

## Implementing a JS client

Use the four functions `onSocketOpen()`, `onSocketClose()`, `onSocketMessage()`,
and `onSocketError()` to implement client logic in `pebble-js-app.js`. Any data
received from the C side is automatically forwarded to the server in
`PGEWSForwardToServer()`.

Manual messages can be sent to the server using the global `webSocket` (only
available after `connectToServer()` is called. For example, using the first
three pre-defined keys to send three values, such as an id, x, and y coordinates
to the server:

```
var id = dict['PGE_WS_KEY_0'];
var x = dict['PGE_WS_KEY_1'];
var y = dict['PGE_WS_KEY_2'];

// Send position
var dataString = JSON.stringify({
  'PGE_WS_KEY_0': id,
  'PGE_WS_KEY_1': x,
  'PGE_WS_KEY_2': y
});

webSocket.send(dataString);
```

On the server side, this can be decoded in `onClientMessage()`:

```
function onClientMessage(socket, data) {
  var json = JSON.parse(data);

  // Recover values
  var id = json['PGE_WS_KEY_0'];
  var x = json['PGE_WS_KEY_1'];
  var y = json['PGE_WS_KEY_1'];
}
```


text:
package dao

import (
	"context"
	"fmt"
	"go-common/app/interface/bbq/app-bbq/api/http/v1"
	user "go-common/app/service/bbq/user/api"
	"go-common/library/log"
)

// ModifyRelation .
func (d *Dao) ModifyRelation(c context.Context, mid, upMid int64, action int32) (res *user.ModifyRelationReply, err error) {
	res, err = d.userClient.ModifyRelation(c, &user.ModifyRelationReq{Mid: mid, UpMid: upMid, Action: action})
	if err != nil {
		log.Errorv(c, log.KV("log", fmt.Sprintf("modify relation fail: mid=%d, up_mid=%d, action=%d", mid, upMid, action)))
	}
	return
}

// UserRelationList .
func (d *Dao) UserRelationList(c context.Context, userReq *user.ListRelationUserInfoReq, relationType int32) (res *v1.UserRelationListResponse, err error) {
	res = new(v1.UserRelationListResponse)

	var reply *user.ListUserInfoReply
	switch relationType {
	case user.Follow:
		reply, err = d.userClient.ListFollowUserInfo(c, userReq)
	case user.Fan:
		reply, err = d.userClient.ListFanUserInfo(c, userReq)
	case user.Black:
		reply, err = d.userClient.ListBlackUserInfo(c, userReq)
	}
	if err != nil {
		log.Errorv(c, log.KV("log", fmt.Sprintf("user relation list fail: req=%s", userReq.String())))
		return
	}

	res.HasMore = reply.HasMore
	for _, v := range reply.List {
		userInfo := &v1.UserInfo{UserBase: *v.UserBase, FollowState: v.FollowState, CursorValue: v.CursorValue}
		res.List = append(res.List, userInfo)
	}

	return
}

// FetchFollowList 获取mid的所有关注up主
func (d *Dao) FetchFollowList(c context.Context, mid int64) (upMid []int64, err error) {

	res, err := d.userClient.ListFollow(c, &user.ListRelationReq{Mid: mid})
	if err != nil {
		log.Errorv(c, log.KV("log", "fetch follow list fail"))
		return
	}
	upMid = res.List
	return
}


text:
"""Test transaction behaviors under the Dandelion spreading policy

Tests:
1. Resistance to active probing:
   Stem:  0 --> 1 --> 2 --> 0 where each node has argument "-dandelion=1"
   Probe: TestNode --> 0
   Node 0 generates a Dandelion transaction "tx": 1.0 BTC from Node 0 to Node 2
   TestNode immediately sends getdata for tx to Node 0
   Assert that Node 0 does not reply with tx

2. Loop behavior:
   Stem:  0 --> 1 --> 2 --> 0 where each node has argument "-dandelion=1"
   Probe: TestNode --> 0
   Wait ~5 seconds after Test 1, then TestNode sends getdata for tx to Node 0
   Assert that Node 0 does not reply with tx

3. Resistance to black holes:
   Stem:  0 --> 1 --> 2 --> 0 where each node has argument "-dandelion=1"
   Probe: TestNode --> 0
   Wait ~45 seconds after Test 2, then TestNode sends getdata for tx to Node 0
   Assert that Node 0 replies with tx
"""

from collections import defaultdict
from test_framework.mininode import *                          # NodeConnCB
from test_framework.test_framework import BitcoinTestFramework # BitcoinTestFramework
from test_framework.util import *                              # other stuff
import time                                                    # sleep

class TestP2PConn(NodeConnCB):
    def __init__(self):
        NodeConnCB.__init__(self)
        self.connection = None

        # Track number of messages of each type received and the most recent
        # message of each type
        self.message_count = defaultdict(int)
        self.last_message = {}

        self.ping_counter = 1
        self.last_pong = msg_pong()

    def add_connection(self, conn):
        self.connection = conn
        self.peer_disconnected = False

    def on_inv(self, conn, message):
        """Receive message and dispatch message to appropriate callback.

        We keep a count of how many of each message type has been received
        and the most recent message of each type."""
        with mininode_lock:
            try:
                command = message.command.decode('ascii')
                self.message_count[command] += 1
                self.last_message[command] = message
                getattr(self, 'on_' + command)(message)
            except:
                print("ERROR delivering %s (%s)" % (repr(message), sys.exc_info()[0]))
                raise

    # Track the last getdata message we receive (used in the test)
    def on_getdata(self, conn, message):
        self.last_getdata = message

    # Spin until verack message is received from the node.
    # We use this to signal that our test can begin. This
    # is called from the testing thread, so it needs to acquire
    # the global lock.
    def wait_for_verack(self):
        def veracked():
            return self.verack_received
        return wait_until(veracked, timeout=10)

    def wait_for_disconnect(self):
        def disconnected():
            return self.peer_disconnected
        return wait_until(disconnected, timeout=10)

    # Wrapper for the NodeConn's send_message function
    def send_message(self, message):
        self.connection.send_message(message)

    def on_pong(self, conn, message):
        self.last_pong = message

    def on_close(self, conn):
        self.peer_disconnected = True

    # Sync up with the node after delivery of a block
    def sync_with_ping(self, timeout=30):
        def received_pong():
            return (self.last_pong.nonce == self.ping_counter)
        self.connection.send_message(msg_ping(nonce=self.ping_counter))
        success = wait_until(received_pong, timeout=timeout)
        self.ping_counter += 1
        return success

    def send_dandeliontx_getdata(self, dandeliontx_hash):
        msg = msg_getdata([CInv(5,dandeliontx_hash)]) # 5: "DandelionTx"
        print("Dandelion hash is ", dandeliontx_hash )
        self.connection.send_message(msg)

class DandelionTest(BitcoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 8
        self.extra_args = []
        for i in range(self.num_nodes):
            self.extra_args.append(["-dandelion=1"]) # ,"-debug=dandelion","-printtoconsole=1"

    def setup_nodes(self):
        print("setup_nodes");
        return start_nodes(
            self.num_nodes, self.options.tmpdir,
            extra_args=[['-regtest', '-debug', '-whitelist=127.0.0.1']] * self.num_nodes)

    def setup_network(self):
        print("Setting up network for dandelion.")
        self.nodes = self.setup_nodes()
        # Tests 1,2,3: 0 --> 1 --> 2 --> 0
        connect_nodes(self.nodes[0],1)
        connect_nodes(self.nodes[1],2)
        connect_nodes(self.nodes[2],0)
        self.is_network_split = True
        self.sync_all()
        print("Finished setting up network for dandelion.")

    def run_test(self):
        # Convenience variables
        node0 = self.nodes[0]
        node1 = self.nodes[1]
        node2 = self.nodes[2]

        # Setup TestP2PConns
        test_node0 = TestP2PConn()

        connection = NodeConn('127.0.0.1', p2p_port(0), node0, test_node0)
        test_node0.add_connection(connection)

        # Start networking thread
        NetworkThread().start()
        test_node0.wait_for_verack()
        print("Dandelion test: verack " + ("received." if test_node0.verack_received else "failed."))

        # Get out of Initial Block Download (IBD)
        for node in self.nodes:
          node.generate(1)
        # Generate funds for node0
        node0.generate(101)

        # Tests 1,2,3
        # There is a low probability that one of these tests will fail even if
        # the implementation is correct. Thus, these tests are repeated upon
        # failure. A true bug will result in repeated failures.
        print('Starting tests...')
        test_1_passed = False
        test_2_passed = False
        test_3_passed = False
        tries_left = 5
        while(not (test_1_passed and test_2_passed and test_3_passed) and tries_left > 0):
            tries_left -= 1
            # Test 1: Resistance to active probing
            test_node0.message_count['notfound'] = 0
            node0_txid = node0.sendtoaddress(node2.getnewaddress(),1.0)
            node0_tx = FromHex(CTransaction(),node0.gettransaction(node0_txid)['hex'])
            test_node0.send_dandeliontx_getdata(node0_tx.calc_sha256(True))
            time.sleep(1)
            try:
              assert(test_node0.message_count['notfound']==1)
              if not test_1_passed:
                test_1_passed = True
                self.log.info('Success: resistance to active probing')
            except AssertionError:
              if not test_1_passed and tries_left == 0:
                self.log.info('Failed: resistance to active probing')
            # Test 2: Loop behavior
            test_node0.message_count['notfound'] = 0
            time.sleep(3)
            test_node0.send_dandeliontx_getdata(node0_tx.calc_sha256(True))
            time.sleep(1)
            try:
              assert(test_node0.message_count['notfound']==1)
              if not test_2_passed:
                test_2_passed = True
                self.log.info('Success: loop behavior')
            except AssertionError:
              if not test_2_passed and tries_left == 0:
                self.log.info('Failed: loop behavior')
            # Test 3: Resistance to black holes
            test_node0.message_count['tx'] = 0
            time.sleep(44)
            test_node0.send_dandeliontx_getdata(node0_tx.calc_sha256(True))
            time.sleep(1)
            try:
              assert(test_node0.message_count['tx']==1)
              if not test_3_passed:
                test_3_passed = True
                self.log.info('Success: resistance to black holes')
            except AssertionError:
              if not test_3_passed and tries_left == 0:
                self.log.info('Failed: resistance to black holes')

        print("Running dandelion test 7")
        all_tests_passed = test_1_passed and test_2_passed and test_3_passed
        assert(all_tests_passed)

if __name__ == '__main__':
    DandelionTest().main()


text:
<?php

namespace Acme\TaskBundle\Entity;

class Tag
{
    public $name;
}


text:
FROM php:7.2-alpine
RUN apk --update add libbz2 bzip2-dev && \
    apk del build-base && \
    rm -rf /var/cache/apk/*
RUN docker-php-ext-install bz2
VOLUME ["/app"]
WORKDIR /app


text:
'''

Create an unified test_stub to share test operations

@author: Songtao
'''

import os
import subprocess
import time
import threading
import uuid

import zstacklib.utils.ssh as ssh
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.zstack_test.zstack_test_vm as zstack_vm_header
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.vm_operations as vm_ops
import zstackwoodpecker.operations.account_operations as acc_ops
import zstackwoodpecker.operations.monitor_operations as mon_ops
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header
import os, sys, string
import poplib

def create_vm():
    global vm
    vm_creation_option = test_util.VmOption()
    image_name = os.environ.get('imageName_s')
    image_uuid = test_lib.lib_get_image_by_name(image_name).uuid
    l3_name = os.environ.get('l3PublicNetworkName')

    l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid
    conditions = res_ops.gen_query_conditions('type', '=', 'UserVm')
    instance_offering_uuid = res_ops.query_resource(res_ops.INSTANCE_OFFERING, conditions)[0].uuid
    vm_creation_option.set_l3_uuids([l3_net_uuid])
    vm_creation_option.set_image_uuid(image_uuid)
    vm_creation_option.set_instance_offering_uuid(instance_offering_uuid)
    vm_creation_option.set_name('vm_'+ ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(8))))
    vm = test_vm_header.ZstackTestVm()
    vm.set_creation_option(vm_creation_option)
    vm.create()
    return  vm

def get_monitor_item(resourceType):
    monitor_item_name = []
    vm_db = "VmInstanceVO"
    host_db = "HostVO"
    if resourceType == vm_db:
        monitor_item = mon_ops.get_monitor_item(vm_db)
    elif resourceType == host_db:
         monitor_item = mon_ops.get_monitor_item(host_db)
    for item in monitor_item:
        monitor_item_name.append(item.name)
    return monitor_item_name

def query_monitor_trigger(monitor_trigger_uuid):
    cond = res_ops.gen_query_conditions('uuid', '=', monitor_trigger_uuid)
    return res_ops.query_resource(res_ops.MONITOR_TRIGGER, cond)

def query_monitor_trigger_action(monitor_trigger_action_uuid):
    cond = res_ops.gen_query_conditions('uuid', '=', monitor_trigger_action_uuid)
    return res_ops.query_resource(res_ops.MONITOR_TRIGGER_ACTION, cond)

def query_vmnic(ip):
    cond = res_ops.gen_query_conditions('ip','=',ip)
    return res_ops.query_resource(res_ops.VM_NIC, cond)

def query_trigger_in_loop(trigger,retry_times1):
    retry_times=retry_times1
    Problem = 0
    OK = 0
    while retry_times >0 and Problem == 0:
        time.sleep(10)
        retry_times -= 1
        tirgger_Q = query_monitor_trigger(trigger)
        trigger_status = tirgger_Q[0].status
        if trigger_status == "Problem":
            Problem = 1
            retry_times -= 1
            while retry_times > 0 and Problem == 1:
                time.sleep(10)
                retry_times -= 1
                tirgger_Q = query_monitor_trigger(trigger)
                trigger_status = tirgger_Q[0].status
                if trigger_status == "OK":
                    OK = 1
                    break
            break
    return Problem, OK

def query_trigger_is_problem(trigger,monitor_trigger):
    retry_times = 50
    Problem = 0
    while retry_times >0 and Problem == 0:
        time.sleep(10)
        retry_times -= 1
        tirgger_Q = query_monitor_trigger(trigger)
        trigger_status = tirgger_Q[0].status
        if trigger_status == "Problem":
            Problem = 1
            retry_times -= 1
            stateevent = "disable"
            monitor_trigger =mon_ops.change_monitor_trigger_state(trigger,stateevent)
            break
    return Problem

def create_email_media():
    media_name = "email" + ''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(8)))
    port = os.environ.get('media_smtpport')
    server = os.environ.get('media_smtpserver')
    mail_name = os.environ.get('media_username')
    mail_password = os.environ.get('media_password')
    return mon_ops.create_email_media(media_name, port, server, mail_name, mail_password)

def receive_email():
    server = os.environ.get('receive_pop3server')
    email = os.environ.get('receive_email')
    password = os.environ.get('receive_password')
    pop3 = poplib.POP3(server)
    pop3.set_debuglevel(1)
    pop3.user(email)
    pop3.pass_(password)
    ret = pop3.stat()
    test_util.action_logger('Messages: %s. Size: %s' % pop3.stat())
    mail_list = []
    for i in range(ret[0] - 20, ret[0]):
        resp, msg, octets = pop3.retr(i)
        mail_list.append(msg)
    return mail_list

def check_email(list, keywords, trigger, target_uuid):
    mail = os.environ.get('media_username')
    flag = 0
    print mail
    for i in list:
        '''check mail list form the mail sender'''
        if 'MF='+ mail in i[0]:
            test_util.action_logger('Mail sent addr is %s' % mail)
            if (trigger in i[13].lower()) and (target_uuid in i[13]) and keywords in i[8]:
                flag = 1
                test_util.action_logger('Got Target: %s for: %s Trigger Mail' % (target_uuid, trigger))
                test_util.action_logger('Mail detail info is %s' % i)
                break
            #test_util.action_logger('Mail sent date is %s' % i[3].split(',')[1].lstrip())
            #mail_date = i[3].split(',')[1].lstrip()[:-6]
            #mail_time = time.mktime(time.strptime(mail_date, "%d %b %Y %H:%M:%S"))
            #if operate_time > mail_time:
            #    print "Got an old email"
    test_util.action_logger('flag value is %s' % flag)
    return flag

def execute_shell_in_process(cmd, timeout=10, logfd=None):
    if not logfd:
        process = subprocess.Popen(cmd, executable='/bin/sh', shell=True, universal_newlines=True)
    else:
        process = subprocess.Popen(cmd, executable='/bin/sh', shell=True, stdout=logfd, stderr=logfd, universal_newlines=True)

    start_time = time.time()
    while process.poll() is None:
        curr_time = time.time()
        TEST_TIME = curr_time - start_time
        if TEST_TIME > timeout:
            process.kill()
            test_util.test_logger('[shell:] %s timeout ' % cmd)
            return False
        time.sleep(1)

    test_util.test_logger('[shell:] %s is finished.' % cmd)
    return process.returncode

def ssh_cmd_line(ip_addr, username, password, port):
    ssh_cmd = '/usr/bin/sshpass -p %s ssh  %s@%s -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null  -p %s' \
              % (password, username, ip_addr, port)
    return ssh_cmd

def yum_install_stress_tool(ssh_cmd_line):
    test_util.test_logger('test image need to have fio stress iperf trickle installed')
    #timeout = 330
    #cmd = '%s "yum install -y fio stress iperf trickle enablerepo=ali* --nogpgcheck"' % (ssh_cmd_line)
    #if execute_shell_in_process(cmd, timeout) != 0:
    #    test_util.test_fail('fail to install stress')

def run_cpu_load(ssh_cmd_line, cpu_core, threads):
    timeout = 100
    cmd = '%s "taskset -c %s stress --timeout 90 --cpu %s"' % (ssh_cmd_line, cpu_core,threads)
    if execute_shell_in_process(cmd, timeout) != 0:
        test_util.test_fail('cpu load fail to run')

def run_all_cpus_load(ssh_cmd_line):
    timeout= 100
    cmd ='%s "stress --timeout 90 --cpu $(cat /proc/cpuinfo|grep \"processor\"|wc -l)"' %ssh_cmd_line
    if execute_shell_in_process(cmd, timeout) != 0:
        test_util.test_fail('cpu load fail to run')

def run_mem_load(ssh_cmd_line,runtime):
    timeout = 100
    cmd = '%s "stress --vm-bytes $(awk \'/MemFree/{printf \"%%d\\n\", $2 * 0.95;}\' < /proc/meminfo)k --vm-keep -m 1 -t %d"' % (ssh_cmd_line,runtime)
    if execute_shell_in_process(cmd, timeout) != 0:
        test_util.test_fail('mem load fail to run')

def run_disk_load(ssh_cmd_line, rw):
    timeout = 100
    cmd = '%s "fio -filename=/tmp/test -direct=1 -iodepth 1 -thread -rw=%s -ioengine=psync -bs=16k -size=4G -numjobs=10 -runtime=80 -group_reporting -name=mytest"' \
          % (ssh_cmd_line, rw)
    if execute_shell_in_process(cmd, timeout) != 0:
        test_util.test_fail('disk io load fail to run')

def run_iperf_server(ssh_cmd_line):
    timeout = 100
    cmd = '%s "iptables -F;nohup netperf -s  >/root/tmp.log & "' % ssh_cmd_line

def run_iperf_client(ssh_cmd_line, server_ip, runtime):
    timeout = 100
    cmd = '%s "netperf -d -c %s -t %d >/root/test.log &"' % (ssh_cmd_line, server_ip,runtime)
    if execute_shell_in_process(cmd, timeout) != 0:
        test_util.test_fail('network io load fail to run')

def run_disk_load1(ssh_cmd_line,rw):
    if rw == 'write':
        os.system('%s "dd if=/dev/zero of=test.dbf bs=8k oflag=direct,nonblock"'% ssh_cmd_line)
    else:
        os.system('%s "dd if=/dev/vda of=/dev/null bs=8k iflag=direct,nonblock"' % ssh_cmd_line)

def run_network_rx(ssh_cmd_line):
    os.system('%s "trickle -d 1024 wget http://192.168.200.100/mirror/diskimages/win7.qcow2"' % ssh_cmd_line)

def run_network_tx(ssh_cmd_line,ip):
    os.system('%s "wget http://192.168.200.100/mirror/iso/try_iso.iso"' % ssh_cmd_line)
    cmd = ssh_cmd_line + ' "sshpass -p password scp -l 1024 try_iso.iso root@'+ ip +':/root/"'
    os.system(cmd)

def kill(ssh_cmd_line):
    os.system('%s "ps -A|grep -w dd|awk \'{print $1}\'|xargs kill -9"' % ssh_cmd_line)
    os.system('%s "ps -A|grep wget|awk \'{print $1}\'|xargs kill -9"' % ssh_cmd_line)
    os.system('%s "ps -A|grep -w scp|awk \'{print $1}\'|xargs kill -9"' % ssh_cmd_line)
    os.system('%s "rm -rf win7.qcow2"' % ssh_cmd_line)
    os.system('%s "rm -rf try_iso.iso"' % ssh_cmd_line)


text:
package edu.thu.ggxx.hellobrazil.wc2014.diagram.providers;

import org.eclipse.gmf.tooling.runtime.providers.DefaultEditPartProvider;

import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.Wc2014EditPartFactory;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.edit.parts.WorldCupEditPart;
import edu.thu.ggxx.hellobrazil.wc2014.diagram.part.Wc2014VisualIDRegistry;

/**
 * @generated
 */
public class Wc2014EditPartProvider extends DefaultEditPartProvider {

	/**
	 * @generated
	 */
	public Wc2014EditPartProvider() {
		super(new Wc2014EditPartFactory(),
				Wc2014VisualIDRegistry.TYPED_INSTANCE,
				WorldCupEditPart.MODEL_ID);
	}

}


text:
@extends('template_Dashboard')

@section('title')
    Changer Password
@endsection
@section('content')

            @component('flash_alert_message')
            @endcomponent

Change Password

                        <form class="form-horizontal" action="{{ route('user-profile.update') }}" role="form" method="POST">
                            {{ csrf_field() }}
                            {{ method_field('PUT') }}

has('password') ? ' has-error' : '' }}">
                                Current Password

                                    <input id="current_password" type="password" class="form-control" name="current_password">
                                    @if ($errors->has('current_password'))

                                        {{ $errors->first('current_password') }}

                                    @endif

has('password') ? ' has-error' : '' }}">
                                New Password

                                    <input id="password" type="password" class="form-control" name="password">

                                    @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                                    @endif

has('password_confirmation') ? ' has-error' : '' }}">
                                Confirm New Password

                                    <input id="password-confirm" type="password" class="form-control" name="password_confirmation">

                                    @if ($errors->has('password_confirmation'))

                                        {{ $errors->first('password_confirmation') }}

                                    @endif

                                    <button type="submit" class="btn btn-primary">
                                        Submit
                                    </button>

                        </form>

@endsection


text:
<?php

namespace Modules\Admin\Exceptions;

class UserException extends \Exception
{
}


text:
<?php

namespace Anodoc;

use Anodoc\NullDocComment;
use Anodoc\ClassDoc\InvalidMethodDoc;
use Anodoc\ClassDoc\InvalidAttributeDoc;

class ClassDoc {

  private
    $className,
    $classDoc,
    $methodDocs = array(),
    $attributeDocs = array();

  function __construct(
    $className, DocComment $classDoc, array $methodDocs = array(),
    array $attributeDocs = array()
  ) {
    $this->className = $className;
    $this->classDoc = $classDoc;
    foreach ($methodDocs as $methodName => $docComment) {
      $this->setMethodDoc($methodName, $docComment);
    }
    foreach ($attributeDocs as $attribute => $docComment) {
      $this->setAttributeDoc($attribute, $docComment);
    }
  }

  private function setMethodDoc($methodName, $docComment) {
    if ($docComment instanceof DocComment) {
      $this->methodDocs[$methodName] = $docComment;
    } else {
      throw new InvalidMethodDoc("'$methodName' is not a valid method doc.");
    }
  }

  private function setAttributeDoc($attribute, $docComment) {
    if ($docComment instanceof DocComment) {
      $this->attributeDocs[$attribute] = $docComment;
    } else {
      throw new InvalidAttributeDoc(
        "'$attribute' is not a valid attribute doc."
      );
    }
  }

  function getClassName() {
    return $this->className;
  }

  function getMainDoc() {
    return $this->classDoc;
  }

  function getMethodDoc($method) {
    return $this->getItemDoc($this->methodDocs, $method);
  }

  function getAttributeDoc($attribute) {
    return $this->getItemDoc($this->attributeDocs, $attribute);
  }

  private function getItemDoc($collection, $key) {
    if (isset($collection[$key])) {
      return $collection[$key];
    }
    return new NullDocComment;
  }

}


text:
class Marker
  def self.mark(msg, logger = ActiveRecord::Base.logger)
    start = Time.now
    logger.info("#{start} --> starting #{msg} from #{caller[2]}:#{caller[1]}")
    result = yield
    finish = Time.now
    logger.info("#{finish} --< finished #{msg} --- #{"%2.3f sec" % (finish - start)}")
    result
  end
end