text:
/*!
    \file  gd32f3x0_gpio.h
    \brief definitions for the GPIO

    \version 2017-06-06, V1.0.0, firmware for GD32F3x0
    \version 2019-06-01, V2.0.0, firmware for GD32F3x0
*/

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

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

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

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

#ifndef GD32F3X0_GPIO_H
#define GD32F3X0_GPIO_H

#include "gd32f3x0.h"

/* GPIOx(x=A,B,C,D,F) definitions */
#define GPIOA                      (GPIO_BASE + 0x00000000U)
#define GPIOB                      (GPIO_BASE + 0x00000400U)
#define GPIOC                      (GPIO_BASE + 0x00000800U)
#define GPIOD                      (GPIO_BASE + 0x00000C00U)
#define GPIOF                      (GPIO_BASE + 0x00001400U)

/* registers definitions */
#define GPIO_CTL(gpiox)            REG32((gpiox) + 0x00000000U)    /*!< GPIO port control register */
#define GPIO_OMODE(gpiox)          REG32((gpiox) + 0x00000004U)    /*!< GPIO port output mode register */
#define GPIO_OSPD0(gpiox)          REG32((gpiox) + 0x00000008U)    /*!< GPIO port output speed register 0 */
#define GPIO_PUD(gpiox)            REG32((gpiox) + 0x0000000CU)    /*!< GPIO port pull-up/pull-down register */
#define GPIO_ISTAT(gpiox)          REG32((gpiox) + 0x00000010U)    /*!< GPIO port input status register */
#define GPIO_OCTL(gpiox)           REG32((gpiox) + 0x00000014U)    /*!< GPIO port output control register */
#define GPIO_BOP(gpiox)            REG32((gpiox) + 0x00000018U)    /*!< GPIO port bit operation register */
#define GPIO_LOCK(gpiox)           REG32((gpiox) + 0x0000001CU)    /*!< GPIO port configuration lock register */
#define GPIO_AFSEL0(gpiox)         REG32((gpiox) + 0x00000020U)    /*!< GPIO alternate function selected register 0 */
#define GPIO_AFSEL1(gpiox)         REG32((gpiox) + 0x00000024U)    /*!< GPIO alternate function selected register 1 */
#define GPIO_BC(gpiox)             REG32((gpiox) + 0x00000028U)    /*!< GPIO bit clear register */
#define GPIO_TG(gpiox)             REG32((gpiox) + 0x0000002CU)    /*!< GPIO port bit toggle register */
#define GPIO_OSPD1(gpiox)          REG32((gpiox) + 0x0000003CU)    /*!< GPIO port output speed register 1 */

/* bits definitions */
/* GPIO_CTL */
#define GPIO_CTL_CTL0              BITS(0,1)             /*!< pin 0 configuration bits */
#define GPIO_CTL_CTL1              BITS(2,3)             /*!< pin 1 configuration bits */
#define GPIO_CTL_CTL2              BITS(4,5)             /*!< pin 2 configuration bits */
#define GPIO_CTL_CTL3              BITS(6,7)             /*!< pin 3 configuration bits */
#define GPIO_CTL_CTL4              BITS(8,9)             /*!< pin 4 configuration bits */
#define GPIO_CTL_CTL5              BITS(10,11)           /*!< pin 5 configuration bits */
#define GPIO_CTL_CTL6              BITS(12,13)           /*!< pin 6 configuration bits */
#define GPIO_CTL_CTL7              BITS(14,15)           /*!< pin 7 configuration bits */
#define GPIO_CTL_CTL8              BITS(16,17)           /*!< pin 8 configuration bits */
#define GPIO_CTL_CTL9              BITS(18,19)           /*!< pin 9 configuration bits */
#define GPIO_CTL_CTL10             BITS(20,21)           /*!< pin 10 configuration bits */
#define GPIO_CTL_CTL11             BITS(22,23)           /*!< pin 11 configuration bits */
#define GPIO_CTL_CTL12             BITS(24,25)           /*!< pin 12 configuration bits */
#define GPIO_CTL_CTL13             BITS(26,27)           /*!< pin 13 configuration bits */
#define GPIO_CTL_CTL14             BITS(28,29)           /*!< pin 14 configuration bits */
#define GPIO_CTL_CTL15             BITS(30,31)           /*!< pin 15 configuration bits */

/* GPIO_OMODE */
#define GPIO_OMODE_OM0             BIT(0)                /*!< pin 0 output mode bit */
#define GPIO_OMODE_OM1             BIT(1)                /*!< pin 1 output mode bit */
#define GPIO_OMODE_OM2             BIT(2)                /*!< pin 2 output mode bit */
#define GPIO_OMODE_OM3             BIT(3)                /*!< pin 3 output mode bit */
#define GPIO_OMODE_OM4             BIT(4)                /*!< pin 4 output mode bit */
#define GPIO_OMODE_OM5             BIT(5)                /*!< pin 5 output mode bit */
#define GPIO_OMODE_OM6             BIT(6)                /*!< pin 6 output mode bit */
#define GPIO_OMODE_OM7             BIT(7)                /*!< pin 7 output mode bit */
#define GPIO_OMODE_OM8             BIT(8)                /*!< pin 8 output mode bit */
#define GPIO_OMODE_OM9             BIT(9)                /*!< pin 9 output mode bit */
#define GPIO_OMODE_OM10            BIT(10)               /*!< pin 10 output mode bit */
#define GPIO_OMODE_OM11            BIT(11)               /*!< pin 11 output mode bit */
#define GPIO_OMODE_OM12            BIT(12)               /*!< pin 12 output mode bit */
#define GPIO_OMODE_OM13            BIT(13)               /*!< pin 13 output mode bit */
#define GPIO_OMODE_OM14            BIT(14)               /*!< pin 14 output mode bit */
#define GPIO_OMODE_OM15            BIT(15)               /*!< pin 15 output mode bit */

/* GPIO_OSPD0 */
#define GPIO_OSPD0_OSPD0           BITS(0,1)             /*!< pin 0 output max speed bits */
#define GPIO_OSPD0_OSPD1           BITS(2,3)             /*!< pin 1 output max speed bits */
#define GPIO_OSPD0_OSPD2           BITS(4,5)             /*!< pin 2 output max speed bits */
#define GPIO_OSPD0_OSPD3           BITS(6,7)             /*!< pin 3 output max speed bits */
#define GPIO_OSPD0_OSPD4           BITS(8,9)             /*!< pin 4 output max speed bits */
#define GPIO_OSPD0_OSPD5           BITS(10,11)           /*!< pin 5 output max speed bits */
#define GPIO_OSPD0_OSPD6           BITS(12,13)           /*!< pin 6 output max speed bits */
#define GPIO_OSPD0_OSPD7           BITS(14,15)           /*!< pin 7 output max speed bits */
#define GPIO_OSPD0_OSPD8           BITS(16,17)           /*!< pin 8 output max speed bits */
#define GPIO_OSPD0_OSPD9           BITS(18,19)           /*!< pin 9 output max speed bits */
#define GPIO_OSPD0_OSPD10          BITS(20,21)           /*!< pin 10 output max speed bits */
#define GPIO_OSPD0_OSPD11          BITS(22,23)           /*!< pin 11 output max speed bits */
#define GPIO_OSPD0_OSPD12          BITS(24,25)           /*!< pin 12 output max speed bits */
#define GPIO_OSPD0_OSPD13          BITS(26,27)           /*!< pin 13 output max speed bits */
#define GPIO_OSPD0_OSPD14          BITS(28,29)           /*!< pin 14 output max speed bits */
#define GPIO_OSPD0_OSPD15          BITS(30,31)           /*!< pin 15 output max speed bits */

/* GPIO_PUD */
#define GPIO_PUD_PUD0              BITS(0,1)             /*!< pin 0 pull-up or pull-down bits */
#define GPIO_PUD_PUD1              BITS(2,3)             /*!< pin 1 pull-up or pull-down bits */
#define GPIO_PUD_PUD2              BITS(4,5)             /*!< pin 2 pull-up or pull-down bits */
#define GPIO_PUD_PUD3              BITS(6,7)             /*!< pin 3 pull-up or pull-down bits */
#define GPIO_PUD_PUD4              BITS(8,9)             /*!< pin 4 pull-up or pull-down bits */
#define GPIO_PUD_PUD5              BITS(10,11)           /*!< pin 5 pull-up or pull-down bits */
#define GPIO_PUD_PUD6              BITS(12,13)           /*!< pin 6 pull-up or pull-down bits */
#define GPIO_PUD_PUD7              BITS(14,15)           /*!< pin 7 pull-up or pull-down bits */
#define GPIO_PUD_PUD8              BITS(16,17)           /*!< pin 8 pull-up or pull-down bits */
#define GPIO_PUD_PUD9              BITS(18,19)           /*!< pin 9 pull-up or pull-down bits */
#define GPIO_PUD_PUD10             BITS(20,21)           /*!< pin 10 pull-up or pull-down bits */
#define GPIO_PUD_PUD11             BITS(22,23)           /*!< pin 11 pull-up or pull-down bits */
#define GPIO_PUD_PUD12             BITS(24,25)           /*!< pin 12 pull-up or pull-down bits */
#define GPIO_PUD_PUD13             BITS(26,27)           /*!< pin 13 pull-up or pull-down bits */
#define GPIO_PUD_PUD14             BITS(28,29)           /*!< pin 14 pull-up or pull-down bits */
#define GPIO_PUD_PUD15             BITS(30,31)           /*!< pin 15 pull-up or pull-down bits */

/* GPIO_ISTAT */
#define GPIO_ISTAT_ISTAT0          BIT(0)                /*!< pin 0 input status */
#define GPIO_ISTAT_ISTAT1          BIT(1)                /*!< pin 1 input status */
#define GPIO_ISTAT_ISTAT2          BIT(2)                /*!< pin 2 input status */
#define GPIO_ISTAT_ISTAT3          BIT(3)                /*!< pin 3 input status */
#define GPIO_ISTAT_ISTAT4          BIT(4)                /*!< pin 4 input status */
#define GPIO_ISTAT_ISTAT5          BIT(5)                /*!< pin 5 input status */
#define GPIO_ISTAT_ISTAT6          BIT(6)                /*!< pin 6 input status */
#define GPIO_ISTAT_ISTAT7          BIT(7)                /*!< pin 7 input status */
#define GPIO_ISTAT_ISTAT8          BIT(8)                /*!< pin 8 input status */
#define GPIO_ISTAT_ISTAT9          BIT(9)                /*!< pin 9 input status */
#define GPIO_ISTAT_ISTAT10         BIT(10)               /*!< pin 10 input status */
#define GPIO_ISTAT_ISTAT11         BIT(11)               /*!< pin 11 input status */
#define GPIO_ISTAT_ISTAT12         BIT(12)               /*!< pin 12 input status */
#define GPIO_ISTAT_ISTAT13         BIT(13)               /*!< pin 13 input status */
#define GPIO_ISTAT_ISTAT14         BIT(14)               /*!< pin 14 input status */
#define GPIO_ISTAT_ISTAT15         BIT(15)               /*!< pin 15 input status */

/* GPIO_OCTL */
#define GPIO_OCTL_OCTL0            BIT(0)                /*!< pin 0 output bit */
#define GPIO_OCTL_OCTL1            BIT(1)                /*!< pin 1 output bit */
#define GPIO_OCTL_OCTL2            BIT(2)                /*!< pin 2 output bit */
#define GPIO_OCTL_OCTL3            BIT(3)                /*!< pin 3 output bit */
#define GPIO_OCTL_OCTL4            BIT(4)                /*!< pin 4 output bit */
#define GPIO_OCTL_OCTL5            BIT(5)                /*!< pin 5 output bit */
#define GPIO_OCTL_OCTL6            BIT(6)                /*!< pin 6 output bit */
#define GPIO_OCTL_OCTL7            BIT(7)                /*!< pin 7 output bit */
#define GPIO_OCTL_OCTL8            BIT(8)                /*!< pin 8 output bit */
#define GPIO_OCTL_OCTL9            BIT(9)                /*!< pin 9 output bit */
#define GPIO_OCTL_OCTL10           BIT(10)               /*!< pin 10 output bit */
#define GPIO_OCTL_OCTL11           BIT(11)               /*!< pin 11 output bit */
#define GPIO_OCTL_OCTL12           BIT(12)               /*!< pin 12 output bit */
#define GPIO_OCTL_OCTL13           BIT(13)               /*!< pin 13 output bit */
#define GPIO_OCTL_OCTL14           BIT(14)               /*!< pin 14 output bit */
#define GPIO_OCTL_OCTL15           BIT(15)               /*!< pin 15 output bit */

/* GPIO_BOP */
#define GPIO_BOP_BOP0              BIT(0)                /*!< pin 0 set bit */
#define GPIO_BOP_BOP1              BIT(1)                /*!< pin 1 set bit */
#define GPIO_BOP_BOP2              BIT(2)                /*!< pin 2 set bit */
#define GPIO_BOP_BOP3              BIT(3)                /*!< pin 3 set bit */
#define GPIO_BOP_BOP4              BIT(4)                /*!< pin 4 set bit */
#define GPIO_BOP_BOP5              BIT(5)                /*!< pin 5 set bit */
#define GPIO_BOP_BOP6              BIT(6)                /*!< pin 6 set bit */
#define GPIO_BOP_BOP7              BIT(7)                /*!< pin 7 set bit */
#define GPIO_BOP_BOP8              BIT(8)                /*!< pin 8 set bit */
#define GPIO_BOP_BOP9              BIT(9)                /*!< pin 9 set bit */
#define GPIO_BOP_BOP10             BIT(10)               /*!< pin 10 set bit */
#define GPIO_BOP_BOP11             BIT(11)               /*!< pin 11 set bit */
#define GPIO_BOP_BOP12             BIT(12)               /*!< pin 12 set bit */
#define GPIO_BOP_BOP13             BIT(13)               /*!< pin 13 set bit */
#define GPIO_BOP_BOP14             BIT(14)               /*!< pin 14 set bit */
#define GPIO_BOP_BOP15             BIT(15)               /*!< pin 15 set bit */
#define GPIO_BOP_CR0               BIT(16)               /*!< pin 0 clear bit */
#define GPIO_BOP_CR1               BIT(17)               /*!< pin 1 clear bit */
#define GPIO_BOP_CR2               BIT(18)               /*!< pin 2 clear bit */
#define GPIO_BOP_CR3               BIT(19)               /*!< pin 3 clear bit */
#define GPIO_BOP_CR4               BIT(20)               /*!< pin 4 clear bit */
#define GPIO_BOP_CR5               BIT(21)               /*!< pin 5 clear bit */
#define GPIO_BOP_CR6               BIT(22)               /*!< pin 6 clear bit */
#define GPIO_BOP_CR7               BIT(23)               /*!< pin 7 clear bit */
#define GPIO_BOP_CR8               BIT(24)               /*!< pin 8 clear bit */
#define GPIO_BOP_CR9               BIT(25)               /*!< pin 9 clear bit */
#define GPIO_BOP_CR10              BIT(26)               /*!< pin 10 clear bit */
#define GPIO_BOP_CR11              BIT(27)               /*!< pin 11 clear bit */
#define GPIO_BOP_CR12              BIT(28)               /*!< pin 12 clear bit */
#define GPIO_BOP_CR13              BIT(29)               /*!< pin 13 clear bit */
#define GPIO_BOP_CR14              BIT(30)               /*!< pin 14 clear bit */
#define GPIO_BOP_CR15              BIT(31)               /*!< pin 15 clear bit */

/* GPIO_LOCK */
#define GPIO_LOCK_LK0              BIT(0)                /*!< pin 0 lock bit */
#define GPIO_LOCK_LK1              BIT(1)                /*!< pin 1 lock bit */
#define GPIO_LOCK_LK2              BIT(2)                /*!< pin 2 lock bit */
#define GPIO_LOCK_LK3              BIT(3)                /*!< pin 3 lock bit */
#define GPIO_LOCK_LK4              BIT(4)                /*!< pin 4 lock bit */
#define GPIO_LOCK_LK5              BIT(5)                /*!< pin 5 lock bit */
#define GPIO_LOCK_LK6              BIT(6)                /*!< pin 6 lock bit */
#define GPIO_LOCK_LK7              BIT(7)                /*!< pin 7 lock bit */
#define GPIO_LOCK_LK8              BIT(8)                /*!< pin 8 lock bit */
#define GPIO_LOCK_LK9              BIT(9)                /*!< pin 9 lock bit */
#define GPIO_LOCK_LK10             BIT(10)               /*!< pin 10 lock bit */
#define GPIO_LOCK_LK11             BIT(11)               /*!< pin 11 lock bit */
#define GPIO_LOCK_LK12             BIT(12)               /*!< pin 12 lock bit */
#define GPIO_LOCK_LK13             BIT(13)               /*!< pin 13 lock bit */
#define GPIO_LOCK_LK14             BIT(14)               /*!< pin 14 lock bit */
#define GPIO_LOCK_LK15             BIT(15)               /*!< pin 15 lock bit */
#define GPIO_LOCK_LKK              BIT(16)               /*!< pin sequence lock key */

/* GPIO_AFSEL0 */
#define GPIO_AFSEL0_SEL0           BITS(0,3)             /*!< pin 0 alternate function selected */
#define GPIO_AFSEL0_SEL1           BITS(4,7)             /*!< pin 1 alternate function selected */
#define GPIO_AFSEL0_SEL2           BITS(8,11)            /*!< pin 2 alternate function selected */
#define GPIO_AFSEL0_SEL3           BITS(12,15)           /*!< pin 3 alternate function selected */
#define GPIO_AFSEL0_SEL4           BITS(16,19)           /*!< pin 4 alternate function selected */
#define GPIO_AFSEL0_SEL5           BITS(20,23)           /*!< pin 5 alternate function selected */
#define GPIO_AFSEL0_SEL6           BITS(24,27)           /*!< pin 6 alternate function selected */
#define GPIO_AFSEL0_SEL7           BITS(28,31)           /*!< pin 7 alternate function selected */

/* GPIO_AFSEL1 */
#define GPIO_AFSEL1_SEL8           BITS(0,3)             /*!< pin 8 alternate function selected */
#define GPIO_AFSEL1_SEL9           BITS(4,7)             /*!< pin 9 alternate function selected */
#define GPIO_AFSEL1_SEL10          BITS(8,11)            /*!< pin 10 alternate function selected */
#define GPIO_AFSEL1_SEL11          BITS(12,15)           /*!< pin 11 alternate function selected */
#define GPIO_AFSEL1_SEL12          BITS(16,19)           /*!< pin 12 alternate function selected */
#define GPIO_AFSEL1_SEL13          BITS(20,23)           /*!< pin 13 alternate function selected */
#define GPIO_AFSEL1_SEL14          BITS(24,27)           /*!< pin 14 alternate function selected */
#define GPIO_AFSEL1_SEL15          BITS(28,31)           /*!< pin 15 alternate function selected */

/* GPIO_BC */
#define GPIO_BC_CR0                BIT(0)                /*!< pin 0 clear bit */
#define GPIO_BC_CR1                BIT(1)                /*!< pin 1 clear bit */
#define GPIO_BC_CR2                BIT(2)                /*!< pin 2 clear bit */
#define GPIO_BC_CR3                BIT(3)                /*!< pin 3 clear bit */
#define GPIO_BC_CR4                BIT(4)                /*!< pin 4 clear bit */
#define GPIO_BC_CR5                BIT(5)                /*!< pin 5 clear bit */
#define GPIO_BC_CR6                BIT(6)                /*!< pin 6 clear bit */
#define GPIO_BC_CR7                BIT(7)                /*!< pin 7 clear bit */
#define GPIO_BC_CR8                BIT(8)                /*!< pin 8 clear bit */
#define GPIO_BC_CR9                BIT(9)                /*!< pin 9 clear bit */
#define GPIO_BC_CR10               BIT(10)               /*!< pin 10 clear bit */
#define GPIO_BC_CR11               BIT(11)               /*!< pin 11 clear bit */
#define GPIO_BC_CR12               BIT(12)               /*!< pin 12 clear bit */
#define GPIO_BC_CR13               BIT(13)               /*!< pin 13 clear bit */
#define GPIO_BC_CR14               BIT(14)               /*!< pin 14 clear bit */
#define GPIO_BC_CR15               BIT(15)               /*!< pin 15 clear bit */

/* GPIO_TG */
#define GPIO_TG_TG0                BIT(0)                /*!< pin 0 toggle bit */
#define GPIO_TG_TG1                BIT(1)                /*!< pin 1 toggle bit */
#define GPIO_TG_TG2                BIT(2)                /*!< pin 2 toggle bit */
#define GPIO_TG_TG3                BIT(3)                /*!< pin 3 toggle bit */
#define GPIO_TG_TG4                BIT(4)                /*!< pin 4 toggle bit */
#define GPIO_TG_TG5                BIT(5)                /*!< pin 5 toggle bit */
#define GPIO_TG_TG6                BIT(6)                /*!< pin 6 toggle bit */
#define GPIO_TG_TG7                BIT(7)                /*!< pin 7 toggle bit */
#define GPIO_TG_TG8                BIT(8)                /*!< pin 8 toggle bit */
#define GPIO_TG_TG9                BIT(9)                /*!< pin 9 toggle bit */
#define GPIO_TG_TG10               BIT(10)               /*!< pin 10 toggle bit */
#define GPIO_TG_TG11               BIT(11)               /*!< pin 11 toggle bit */
#define GPIO_TG_TG12               BIT(12)               /*!< pin 12 toggle bit */
#define GPIO_TG_TG13               BIT(13)               /*!< pin 13 toggle bit */
#define GPIO_TG_TG14               BIT(14)               /*!< pin 14 toggle bit */
#define GPIO_TG_TG15               BIT(15)               /*!< pin 15 toggle bit */

/* GPIO_OSPD1 */
#define GPIO_OSPD1_SPD0            BIT(0)                /*!< set pin 0 very high output speed when OSPD0 is "11" */
#define GPIO_OSPD1_SPD1            BIT(1)                /*!< set pin 1 very high output speed when OSPD1 is "11" */
#define GPIO_OSPD1_SPD2            BIT(2)                /*!< set pin 2 very high output speed when OSPD2 is "11" */
#define GPIO_OSPD1_SPD3            BIT(3)                /*!< set pin 3 very high output speed when OSPD3 is "11" */
#define GPIO_OSPD1_SPD4            BIT(4)                /*!< set pin 4 very high output speed when OSPD4 is "11" */
#define GPIO_OSPD1_SPD5            BIT(5)                /*!< set pin 5 very high output speed when OSPD5 is "11" */
#define GPIO_OSPD1_SPD6            BIT(6)                /*!< set pin 6 very high output speed when OSPD6 is "11" */
#define GPIO_OSPD1_SPD7            BIT(7)                /*!< set pin 7 very high output speed when OSPD7 is "11" */
#define GPIO_OSPD1_SPD8            BIT(8)                /*!< set pin 8 very high output speed when OSPD8 is "11" */
#define GPIO_OSPD1_SPD9            BIT(9)                /*!< set pin 9 very high output speed when OSPD9 is "11" */
#define GPIO_OSPD1_SPD10           BIT(10)               /*!< set pin 10 very high output speed when OSPD10 is "11" */
#define GPIO_OSPD1_SPD11           BIT(11)               /*!< set pin 11 very high output speed when OSPD11 is "11" */
#define GPIO_OSPD1_SPD12           BIT(12)               /*!< set pin 12 very high output speed when OSPD12 is "11" */
#define GPIO_OSPD1_SPD13           BIT(13)               /*!< set pin 13 very high output speed when OSPD13 is "11" */
#define GPIO_OSPD1_SPD14           BIT(14)               /*!< set pin 14 very high output speed when OSPD14 is "11" */
#define GPIO_OSPD1_SPD15           BIT(15)               /*!< set pin 15 very high output speed when OSPD15 is "11" */

/* constants definitions */
typedef FlagStatus bit_status;

/* output mode definitions */
#define CTL_CLTR(regval)           (BITS(0,1) & ((uint32_t)(regval) << 0))
#define GPIO_MODE_INPUT            CTL_CLTR(0)           /*!< input mode */
#define GPIO_MODE_OUTPUT           CTL_CLTR(1)           /*!< output mode */
#define GPIO_MODE_AF               CTL_CLTR(2)           /*!< alternate function mode */
#define GPIO_MODE_ANALOG           CTL_CLTR(3)           /*!< analog mode */

/* pull-up/pull-down definitions */
#define PUD_PUPD(regval)           (BITS(0,1) & ((uint32_t)(regval) << 0))
#define GPIO_PUPD_NONE             PUD_PUPD(0)           /*!< floating mode, no pull-up and pull-down resistors */
#define GPIO_PUPD_PULLUP           PUD_PUPD(1)           /*!< with pull-up resistor */
#define GPIO_PUPD_PULLDOWN         PUD_PUPD(2)           /*!< with pull-down resistor */

/* GPIO pin definitions */
#define GPIO_PIN_0                 BIT(0)                /*!< GPIO pin 0 */
#define GPIO_PIN_1                 BIT(1)                /*!< GPIO pin 1 */
#define GPIO_PIN_2                 BIT(2)                /*!< GPIO pin 2 */
#define GPIO_PIN_3                 BIT(3)                /*!< GPIO pin 3 */
#define GPIO_PIN_4                 BIT(4)                /*!< GPIO pin 4 */
#define GPIO_PIN_5                 BIT(5)                /*!< GPIO pin 5 */
#define GPIO_PIN_6                 BIT(6)                /*!< GPIO pin 6 */
#define GPIO_PIN_7                 BIT(7)                /*!< GPIO pin 7 */
#define GPIO_PIN_8                 BIT(8)                /*!< GPIO pin 8 */
#define GPIO_PIN_9                 BIT(9)                /*!< GPIO pin 9 */
#define GPIO_PIN_10                BIT(10)               /*!< GPIO pin 10 */
#define GPIO_PIN_11                BIT(11)               /*!< GPIO pin 11 */
#define GPIO_PIN_12                BIT(12)               /*!< GPIO pin 12 */
#define GPIO_PIN_13                BIT(13)               /*!< GPIO pin 13 */
#define GPIO_PIN_14                BIT(14)               /*!< GPIO pin 14 */
#define GPIO_PIN_15                BIT(15)               /*!< GPIO pin 15 */
#define GPIO_PIN_ALL               BITS(0,15)            /*!< GPIO pin all */

/* GPIO mode configuration values */
#define GPIO_MODE_SET(n, mode)     ((uint32_t)((uint32_t)(mode) << (2U * (n))))
#define GPIO_MODE_MASK(n)          ((uint32_t)((uint32_t)0x00000003U << (2U * (n))))

/* GPIO pull-up/pull-down values */
#define GPIO_PUPD_SET(n, pupd)     ((uint32_t)((uint32_t)(pupd) << (2U * (n))))
#define GPIO_PUPD_MASK(n)          ((uint32_t)((uint32_t)0x00000003U << (2U * (n))))

/* GPIO output speed values */
#define GPIO_OSPEED_SET(n, speed)  ((uint32_t)((uint32_t)(speed) << (2U * (n))))
#define GPIO_OSPEED_MASK(n)        ((uint32_t)((uint32_t)0x00000003U << (2U * (n))))

/* GPIO output type */
#define GPIO_OTYPE_PP              ((uint8_t)(0x00U))    /*!< push pull mode */
#define GPIO_OTYPE_OD              ((uint8_t)(0x01U))    /*!< open drain mode */

/* GPIO output max speed value */
#define OSPD_OSPD0(regval)         (BITS(0,1) & ((uint32_t)(regval) << 0))
#define GPIO_OSPEED_2MHZ           OSPD_OSPD0(0)                     /*!< output max speed 2MHz */
#define GPIO_OSPEED_10MHZ          OSPD_OSPD0(1)                     /*!< output max speed 10MHz */
#define GPIO_OSPEED_50MHZ          OSPD_OSPD0(3)                     /*!< output max speed 50MHz */
#define GPIO_OSPEED_MAX            ((uint32_t)0x0000FFFFU)           /*!< GPIO very high output speed, max speed more than 50MHz */

/* GPIO alternate function values */
#define GPIO_AFR_SET(n, af)        ((uint32_t)((uint32_t)(af) << (4U * (n))))
#define GPIO_AFR_MASK(n)           ((uint32_t)((uint32_t)0x0000000FU << (4U * (n))))

/* GPIO alternate function */
#define AF(regval)                 (BITS(0,3) & ((uint32_t)(regval) << 0))
#define GPIO_AF_0                   AF(0)                /*!< alternate function 0 selected */
#define GPIO_AF_1                   AF(1)                /*!< alternate function 1 selected */
#define GPIO_AF_2                   AF(2)                /*!< alternate function 2 selected */
#define GPIO_AF_3                   AF(3)                /*!< alternate function 3 selected */
#define GPIO_AF_4                   AF(4)                /*!< alternate function 4 selected (port A,B only) */
#define GPIO_AF_5                   AF(5)                /*!< alternate function 5 selected (port A,B only) */
#define GPIO_AF_6                   AF(6)                /*!< alternate function 6 selected (port A,B only) */
#define GPIO_AF_7                   AF(7)                /*!< alternate function 7 selected (port A,B only) */

/* function declarations */
/* reset GPIO port */
void gpio_deinit(uint32_t gpio_periph);
/* set GPIO mode */
void gpio_mode_set(uint32_t gpio_periph, uint32_t mode, uint32_t pull_up_down, uint32_t pin);
/* set GPIO output type and speed */
void gpio_output_options_set(uint32_t gpio_periph, uint8_t otype, uint32_t speed, uint32_t pin);

/* set GPIO pin bit */
void gpio_bit_set(uint32_t gpio_periph, uint32_t pin);
/* reset GPIO pin bit */
void gpio_bit_reset(uint32_t gpio_periph, uint32_t pin);
/* write data to the specified GPIO pin */
void gpio_bit_write(uint32_t gpio_periph, uint32_t pin, bit_status bit_value);
/* write data to the specified GPIO port */
void gpio_port_write(uint32_t gpio_periph, uint16_t data);

/* get GPIO pin input status */
FlagStatus gpio_input_bit_get(uint32_t gpio_periph, uint32_t pin);
/* get GPIO port input status */
uint16_t gpio_input_port_get(uint32_t gpio_periph);
/* get GPIO pin output status */
FlagStatus gpio_output_bit_get(uint32_t gpio_periph, uint32_t pin);
/* get GPIO port output status */
uint16_t gpio_output_port_get(uint32_t gpio_periph);

/* set GPIO alternate function */
void gpio_af_set(uint32_t gpio_periph,uint32_t alt_func_num, uint32_t pin);
/* lock GPIO pin bit */
void gpio_pin_lock(uint32_t gpio_periph, uint32_t pin);

/* toggle GPIO pin status */
void gpio_bit_toggle(uint32_t gpio_periph, uint32_t pin);
/* toggle GPIO port status */
void gpio_port_toggle(uint32_t gpio_periph);

#endif /* GD32F3X0_GPIO_H */


text:
/**
 * Created by sina on 2015/11/11.
 */
jQuery(document).ready(function() {
    //Metronic.init(); // init metronic core components
    Layout.init(); // init current layout
    Login.init();
    Demo.init();
    // init background slide images
    $.backstretch([
            "http://blog.zhengdingzx.com/css/img/bg/1.jpg",
            "http://blog.zhengdingzx.com/css/img/bg/2.jpg",
            "http://blog.zhengdingzx.com/css/img/bg/3.jpg",
            "http://blog.zhengdingzx.com/css/img/bg/4.jpg"
        ], {
            fade: 1000,
            duration: 8000
        }
    );
});

redpajama_set_name: RedPajamaGithub


text:
package io.iohk.ethereum.utils
import org.scalacheck.Gen

object GenOps {
  implicit class GenOps[T](gen: Gen[T]) {
    def pickValue: T =
      Stream
        .continually(gen)
        .map(_.sample)
        .collectFirst { case Some(value) =>
          value
        }
        .get
  }
}


text:
package cloud9iface

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/service/cloud9"
)

// Cloud9API provides an interface to enable mocking the
// cloud9.Cloud9 service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
//    // myFunc uses an SDK service client to make a request to
//    // AWS Cloud9.
//    func myFunc(svc cloud9iface.Cloud9API) bool {
//        // Make svc.CreateEnvironmentEC2 request
//    }
//
//    func main() {
//        sess := session.New()
//        svc := cloud9.New(sess)
//
//        myFunc(svc)
//    }
//
// In your _test.go file:
//
//    // Define a mock struct to be used in your unit tests of myFunc.
//    type mockCloud9Client struct {
//        cloud9iface.Cloud9API
//    }
//    func (m *mockCloud9Client) CreateEnvironmentEC2(input *cloud9.CreateEnvironmentEC2Input) (*cloud9.CreateEnvironmentEC2Output, error) {
//        // mock response/functionality
//    }
//
//    func TestMyFunc(t *testing.T) {
//        // Setup Test
//        mockSvc := &mockCloud9Client{}
//
//        myfunc(mockSvc)
//
//        // Verify myFunc's functionality
//    }
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type Cloud9API interface {
	CreateEnvironmentEC2(*cloud9.CreateEnvironmentEC2Input) (*cloud9.CreateEnvironmentEC2Output, error)
	CreateEnvironmentEC2WithContext(aws.Context, *cloud9.CreateEnvironmentEC2Input, ...request.Option) (*cloud9.CreateEnvironmentEC2Output, error)
	CreateEnvironmentEC2Request(*cloud9.CreateEnvironmentEC2Input) (*request.Request, *cloud9.CreateEnvironmentEC2Output)

	CreateEnvironmentMembership(*cloud9.CreateEnvironmentMembershipInput) (*cloud9.CreateEnvironmentMembershipOutput, error)
	CreateEnvironmentMembershipWithContext(aws.Context, *cloud9.CreateEnvironmentMembershipInput, ...request.Option) (*cloud9.CreateEnvironmentMembershipOutput, error)
	CreateEnvironmentMembershipRequest(*cloud9.CreateEnvironmentMembershipInput) (*request.Request, *cloud9.CreateEnvironmentMembershipOutput)

	DeleteEnvironment(*cloud9.DeleteEnvironmentInput) (*cloud9.DeleteEnvironmentOutput, error)
	DeleteEnvironmentWithContext(aws.Context, *cloud9.DeleteEnvironmentInput, ...request.Option) (*cloud9.DeleteEnvironmentOutput, error)
	DeleteEnvironmentRequest(*cloud9.DeleteEnvironmentInput) (*request.Request, *cloud9.DeleteEnvironmentOutput)

	DeleteEnvironmentMembership(*cloud9.DeleteEnvironmentMembershipInput) (*cloud9.DeleteEnvironmentMembershipOutput, error)
	DeleteEnvironmentMembershipWithContext(aws.Context, *cloud9.DeleteEnvironmentMembershipInput, ...request.Option) (*cloud9.DeleteEnvironmentMembershipOutput, error)
	DeleteEnvironmentMembershipRequest(*cloud9.DeleteEnvironmentMembershipInput) (*request.Request, *cloud9.DeleteEnvironmentMembershipOutput)

	DescribeEnvironmentMemberships(*cloud9.DescribeEnvironmentMembershipsInput) (*cloud9.DescribeEnvironmentMembershipsOutput, error)
	DescribeEnvironmentMembershipsWithContext(aws.Context, *cloud9.DescribeEnvironmentMembershipsInput, ...request.Option) (*cloud9.DescribeEnvironmentMembershipsOutput, error)
	DescribeEnvironmentMembershipsRequest(*cloud9.DescribeEnvironmentMembershipsInput) (*request.Request, *cloud9.DescribeEnvironmentMembershipsOutput)

	DescribeEnvironmentMembershipsPages(*cloud9.DescribeEnvironmentMembershipsInput, func(*cloud9.DescribeEnvironmentMembershipsOutput, bool) bool) error
	DescribeEnvironmentMembershipsPagesWithContext(aws.Context, *cloud9.DescribeEnvironmentMembershipsInput, func(*cloud9.DescribeEnvironmentMembershipsOutput, bool) bool, ...request.Option) error

	DescribeEnvironmentStatus(*cloud9.DescribeEnvironmentStatusInput) (*cloud9.DescribeEnvironmentStatusOutput, error)
	DescribeEnvironmentStatusWithContext(aws.Context, *cloud9.DescribeEnvironmentStatusInput, ...request.Option) (*cloud9.DescribeEnvironmentStatusOutput, error)
	DescribeEnvironmentStatusRequest(*cloud9.DescribeEnvironmentStatusInput) (*request.Request, *cloud9.DescribeEnvironmentStatusOutput)

	DescribeEnvironments(*cloud9.DescribeEnvironmentsInput) (*cloud9.DescribeEnvironmentsOutput, error)
	DescribeEnvironmentsWithContext(aws.Context, *cloud9.DescribeEnvironmentsInput, ...request.Option) (*cloud9.DescribeEnvironmentsOutput, error)
	DescribeEnvironmentsRequest(*cloud9.DescribeEnvironmentsInput) (*request.Request, *cloud9.DescribeEnvironmentsOutput)

	ListEnvironments(*cloud9.ListEnvironmentsInput) (*cloud9.ListEnvironmentsOutput, error)
	ListEnvironmentsWithContext(aws.Context, *cloud9.ListEnvironmentsInput, ...request.Option) (*cloud9.ListEnvironmentsOutput, error)
	ListEnvironmentsRequest(*cloud9.ListEnvironmentsInput) (*request.Request, *cloud9.ListEnvironmentsOutput)

	ListEnvironmentsPages(*cloud9.ListEnvironmentsInput, func(*cloud9.ListEnvironmentsOutput, bool) bool) error
	ListEnvironmentsPagesWithContext(aws.Context, *cloud9.ListEnvironmentsInput, func(*cloud9.ListEnvironmentsOutput, bool) bool, ...request.Option) error

	UpdateEnvironment(*cloud9.UpdateEnvironmentInput) (*cloud9.UpdateEnvironmentOutput, error)
	UpdateEnvironmentWithContext(aws.Context, *cloud9.UpdateEnvironmentInput, ...request.Option) (*cloud9.UpdateEnvironmentOutput, error)
	UpdateEnvironmentRequest(*cloud9.UpdateEnvironmentInput) (*request.Request, *cloud9.UpdateEnvironmentOutput)

	UpdateEnvironmentMembership(*cloud9.UpdateEnvironmentMembershipInput) (*cloud9.UpdateEnvironmentMembershipOutput, error)
	UpdateEnvironmentMembershipWithContext(aws.Context, *cloud9.UpdateEnvironmentMembershipInput, ...request.Option) (*cloud9.UpdateEnvironmentMembershipOutput, error)
	UpdateEnvironmentMembershipRequest(*cloud9.UpdateEnvironmentMembershipInput) (*request.Request, *cloud9.UpdateEnvironmentMembershipOutput)
}

var _ Cloud9API = (*cloud9.Cloud9)(nil)


text:
gorillaify
==========

browserify v2 plugin for gorillascript

mix and match `.gs`[gorillascript](http://ckknight.github.io/gorillascript) and `.js` files in the same project

*This is a mod from [coffeeify](https://github.com/jnordberg/coffeeify)*

[![Build Status](https://travis-ci.org/unc0/gorillaify.png?branch=master)](https://travis-ci.org/unc0/gorillaify)

# example

given some files written in a mix of `js` and `gorilla`:

foo.gs

``` gorillascript
console.log require './bar.js'
```

bar.js:

``` js
module.exports = require('./baz.gs')(5)
```

baz.gs:

``` gorillascript
module.exports := #(n)-> n * 111
```

install gorillaify into your app:

```
$ npm install gorillaify --save-dev
```

when you compile your app, just pass `-t gorillaify` to browserify:

```
$ browserify -t gorillaify foo.gs > bundle.js
$ node bundle.js
555
```

you can omit the `.gs` extension from your requires if you add the extension to browserify's module extensions:

``` js
module.exports = require('./baz')(5)
```

```
$ browserify -t gorillaify --extension=".gs" foo.gs > bundle.js
$ node bundle.js
555
```

if you are ready to bundle codes for production:

```
$ browserify -t gorillaify/no-debug foo.gs > bundle.js
```

this will disable generating source map, and using gorillascript's bare mode.

# install

With [npm](https://npmjs.org) do:

```
npm install gorillaify
```

# license

MIT


text: A simple node and angular js todo application :).


text:
import { DataFrame, Field } from '@grafana/data';

import { DimensionSupplier, ScalarDimensionConfig, ScalarDimensionMode } from './types';
import { findField, getLastNotNullFieldValue } from './utils';

//---------------------------------------------------------
// Scalar dimension
//---------------------------------------------------------
export function getScalarDimension(
  frame: DataFrame | undefined,
  config: ScalarDimensionConfig
): DimensionSupplier<number> {
  return getScalarDimensionForField(findField(frame, config?.field), config);
}
export function getScalarDimensionForField(
  field: Field | undefined,
  cfg: ScalarDimensionConfig
): DimensionSupplier<number> {
  if (!field) {
    const v = cfg.fixed ?? 0;
    return {
      isAssumed: Boolean(cfg.field?.length) || !cfg.fixed,
      fixed: v,
      value: () => v,
      get: () => v,
    };
  }

  //mod mode as default
  let validated = (value: number) => {
    return value % cfg.max;
  };

  //capped mode
  if (cfg.mode === ScalarDimensionMode.Clamped) {
    validated = (value: number) => {
      if (value < cfg.min) {
        return cfg.min;
      }
      if (value > cfg.max) {
        return cfg.max;
      }
      return value;
    };
  }

  const get = (i: number) => {
    const v = field.values.get(i);
    if (v === null || typeof v !== 'number') {
      return 0;
    }
    return validated(v);
  };

  return {
    field,
    get,
    value: () => getLastNotNullFieldValue(field),
  };
}


text:
//
// Copyright (c) 2013-2022 The SRS Authors
//
// SPDX-License-Identifier: MIT or MulanPSL-2.0
//

#ifndef SRS_PROTOCOL_FORMAT_HPP
#define SRS_PROTOCOL_FORMAT_HPP

#include <srs_core.hpp>

#include <srs_kernel_codec.hpp>

class SrsOnMetaDataPacket;
class SrsSharedPtrMessage;

/**
 * Create special structure from RTMP stream, for example, the metadata.
 */
class SrsRtmpFormat : public SrsFormat
{
public:
    SrsRtmpFormat();
    virtual ~SrsRtmpFormat();
public:
    // Initialize the format from metadata, optional.
    virtual srs_error_t on_metadata(SrsOnMetaDataPacket* meta);
    // When got a parsed audio packet.
    virtual srs_error_t on_audio(SrsSharedPtrMessage* shared_audio);
    virtual srs_error_t on_audio(int64_t timestamp, char* data, int size);
    // When got a parsed video packet.
    virtual srs_error_t on_video(SrsSharedPtrMessage* shared_video);
    virtual srs_error_t on_video(int64_t timestamp, char* data, int size);
};

#endif


text:
<?php

namespace app\modules\admin\controllers;

use Exception;
use Yii;
use yii\helpers\Url;
use app\models\Property;
use app\models\PropertyTypeMap;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * PropertyController implements the CRUD actions for Property model.
 */
class PropertyController extends Controller
{
    public function behaviors()
    {
        return [
            'access'=>[
                'class'=>AccessControl::className(),
                'rules'=>[
                    ['allow'=>true, 'actions'=>['index','create','update','delete', 'view'], 'roles'=>['@']],
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Property models.
     * @param $typeId integer
     * @return mixed
     */
    public function actionIndex($typeId = null)
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Property::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Property model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Property model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Property();

        if ($model->load(Yii::$app->request->post()) && self::validatePrices($model))
        {
            $model->acres = str_replace(',', '', $model->acres);
            $model->priceAcre = str_replace(',', '', $model->priceAcre);
            $model->priceTotal = str_replace(',', '', $model->priceTotal);
            $this->addTypes($model);
            $this->addPhoto($model);

            if($model->save())
            {
                $this->addTypes($model);
                return $this->redirect(['view', 'id' => $model->propId]);
            }
        }

        return $this->render('create', ['model' => $model]);
    }

    /**
     * Updates an existing Property model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && self::validatePrices($model))
        {
            $model->acres = str_replace(',', '', $model->acres);
            $model->priceAcre = str_replace(',', '', $model->priceAcre);
            $model->priceTotal = str_replace(',', '', $model->priceTotal);

            $this->updateTypes($model);
            $this->updatePhoto($model);
            $this->addPhoto($model);

            if($model->save())
                return $this->redirect(['view', 'id' => $model->propId]);
        }

        return $this->render('update', ['model' => $model]);
    }

    /**
     * Validates price per acre and total price combination: one (or both) of the two prices must be specified.
     * @param $property Property model object.
     * @return true if one of the price is present; false if both inputs are empty.
     */
    private static function validatePrices($property)
    {
        if(($property->priceAcre == null || $property->priceAcre == '') && ($property->priceTotal == null || $property->priceTotal == ''))
        {
            $property->addError('priceAcre', '\'Price Per Acre\' and \'Total Price\' cannot both be empty.');
            return false;
        }
        return true;
    }

    private function addTypes($property)
    {
        $types = $_POST['typelist'];
        foreach($types as $type)
        {
            $m = new PropertyTypeMap();
            $m->propId = $property->propId;
            $m->typeId = $type;
            $m->save();
        }
    }

    private function updateTypes($property)
    {
        if(!isset($_POST['typelist']) || !$_POST['typelist'])
            return;

        $appendList = [];
        $deleteList = [];

        //Construct append list
        foreach($_POST['typelist'] as $typeId) {
            $found = false;
            foreach($property->types as $type) {
                if($typeId == $type->typeId) {
                    $found = true;
                    break;
                }
            }
            if(!$found)
                $appendList[] = $typeId;
        }

        //Construct delete list
        foreach($property->types as $type) {
            $found = false;
            foreach($_POST['typelist'] as $typeId) {
                if($typeId == $type->typeId) {
                    $found = true;
                    break;
                }
            }
            if(!$found)
                $deleteList[] = $type->typeId;
        }

        foreach($deleteList as $typeId) {
            $m = PropertyTypeMap::findOne(['propId'=>$property->propId, 'typeId'=>$typeId]);
            if(!$m)
                continue;
            $m->delete();
        }

        foreach($appendList as $typeId) {
            $m = new PropertyTypeMap();
            $m->propId = $property->propId;
            $m->typeId = $typeId;
            $m->save();
        }
    }

    /**
     * Process file upload. Overwrite if file already exist.
     * @param $property an Property instance.
     */
    private function addPhoto($property)
    {
        if(!$_FILES)
            return;

        $files = $_FILES['uploads'];

        //Create directory for photos
        $uniqid  = uniqid();
        $dirPath = Yii::getAlias('@webroot/photos/' . $uniqid);
        $dirUrl  = Url::to('@web/photos/' . $uniqid);

        mkdir($dirPath);

        foreach($files['name'] as $index => $name)
        {
            if(!$files['error'][$index] && move_uploaded_file($files['tmp_name'][$index], "{$dirPath}/{$name}"))
            {
                if($property->pictures != null && $property->pictures != '')
                    $property->pictures .= "\n";
                $property->pictures .= "{$dirUrl}/{$name}";
            }
        }
    }

    /**
     * Process photo removal and reordering.
     * Modified photo list is passed in with $_POST['photoOrder'].
     * TODO: physically remove photo from disk.
     * @param $property current Property model object.
     */
    private function updatePhoto($property) {
        if(!isset($_POST['photoOrder']) || $_POST['photoOrder'] == null)
            return;

        $fromList = explode("\n", $property->pictures);
        $order    = explode(',', $_POST['photoOrder']);

        if(!$this->photoOrderChanged($fromList, $order))
            return;

        $resList = [];

        for($i = 0; $i < count($order); $i++)
            $resList[] = trim($fromList[$order[$i]]);

        $property->pictures = implode("\n", $resList);
    }

    /**
     * Checks if photo list and ordering has been changed.
     * @param $fromList an array of original photo url list.
     * @param $order an array that represent the ordering sent from the client.
     * @return true if the list has been changed and should be reprocessed; false otherwise.
     */
    private function photoOrderChanged($fromList, $order) {
        if(count($fromList) != count($order))
            return true;
        for($i = 0; $i < count($order); $i++)
            if($order[$i] != $i)
                return true;
        return false;
    }

    /**
     * Deletes an existing Property model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $prop = $this->findModel($id);
        foreach($prop->propertyTypeMaps as $typeMap)
            $typeMap->delete();
        $prop->delete();
        return $this->redirect(['index']);
    }

    /**
     * Finds the Property model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Property the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Property::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
#include "common/agent.c"

/* XXX
 * Gdb wants to use its internal fnmatch that does wide characters overriding
 * the one from libiberty. This is madness, let's use ours!
 */
int
gnu_fnmatch(const char *pattern, const char *string, int flags)
{
	return fnmatch(pattern, string, flags);
}


text:
#ifndef __RUNTIME_UTILITIES_H__
#define __RUNTIME_UTILITIES_H__

#include <iostream>
#include <string>

#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <cstdarg>

#include <map>
#include <vector>
#include <pthread.h>
#include <time.h>

#include <fcntl.h>

#ifndef __GNUC__
#include "atomics.h" // for __sync_fetch_and_add
#endif

#include "realm/logging.h"
#include "realm/timers.h"

//#define DETAILED_TIMING

namespace LegionRuntime {
  // map old Logger::Category to new Realm::Logger
  namespace Logger {
    typedef Realm::Logger Category;
  };

#ifdef DEBUG_REALM
#define PTHREAD_SAFE_CALL(cmd)			\
	{					\
		int ret = (cmd);		\
		if (ret != 0) {			\
			fprintf(stderr,"PTHREAD error: %s = %d (%s)\n", #cmd, ret, strerror(ret));	\
			assert(false);		\
		}				\
	}
#else
#define PTHREAD_SAFE_CALL(cmd)			\
	(cmd);
#endif
  /**
   * A blocking lock that cannot be moved between nodes
   */
  class ImmovableLock {
  public:
    ImmovableLock(bool initialize = false) : mutex(NULL) {
      if (initialize)
       init();
    }
    ImmovableLock(const ImmovableLock &other) : mutex(other.mutex) { }
  public:
    void init(void) {
      mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
      PTHREAD_SAFE_CALL(pthread_mutex_init(mutex,NULL));
    }
    void destroy(void) {
      PTHREAD_SAFE_CALL(pthread_mutex_destroy(mutex));
      free(mutex);
      mutex = NULL;
    }
    void clear(void) {
      mutex = NULL;
    }
  public:
    void lock(void) {
      PTHREAD_SAFE_CALL(pthread_mutex_lock(mutex));
    }
    void unlock(void) {
      PTHREAD_SAFE_CALL(pthread_mutex_unlock(mutex));
    }
  public:
    bool operator<(const ImmovableLock &rhs) const
    { return (mutex < rhs.mutex); }
    bool operator==(const ImmovableLock &rhs) const
    { return (mutex == rhs.mutex); }
    ImmovableLock& operator=(const ImmovableLock &rhs)
    { mutex = rhs.mutex; return *this; }
  private:
    pthread_mutex_t *mutex;
  };

  // For backwards compatibility only
  class AutoLock {
  public:
    AutoLock(ImmovableLock &lock)
      : low_lock(lock)
    {
      low_lock.lock();
    }
  public:
    AutoLock(const AutoLock &rhs)
      : low_lock(rhs.low_lock)
    {
      // should never be called
      assert(false);
    }
    ~AutoLock(void)
    {
      low_lock.unlock();
    }
  public:
    AutoLock& operator=(const AutoLock &rhs)
    {
      // should never be called
      assert(false);
      return *this;
    }
  private:
    ImmovableLock &low_lock;
  };

  /**
   * A timer class for doing detailed timing analysis of applications
   * Implementation is specific to low level runtimes
   */
  namespace LowLevel {

    class UtilityBarrier {
    public:
      explicit UtilityBarrier(unsigned expected_arrivals)
        : remaining_arrivals(expected_arrivals),
          remaining_leaves(expected_arrivals)
      {
        PTHREAD_SAFE_CALL(pthread_mutex_init(&inner_lock, NULL));
        PTHREAD_SAFE_CALL(pthread_cond_init(&inner_cond, NULL));
      }
      ~UtilityBarrier(void)
      {
        PTHREAD_SAFE_CALL(pthread_mutex_destroy(&inner_lock));
        PTHREAD_SAFE_CALL(pthread_cond_destroy(&inner_cond));
      }
    public:
      bool arrive(void)
      {
        PTHREAD_SAFE_CALL(pthread_mutex_lock(&inner_lock));
        assert(remaining_arrivals > 0);
        remaining_arrivals--;
        if (remaining_arrivals == 0)
        {
          PTHREAD_SAFE_CALL(pthread_cond_broadcast(&inner_cond));
        }
        else
        {
          PTHREAD_SAFE_CALL(pthread_cond_wait(&inner_cond, &inner_lock));
        }
        assert(remaining_leaves > 0);
        remaining_leaves--;
        bool last_owner = false;
        if (remaining_leaves == 0)
          last_owner = true;
        PTHREAD_SAFE_CALL(pthread_mutex_unlock(&inner_lock));
        return last_owner;
      }
    private:
      unsigned remaining_arrivals;
      unsigned remaining_leaves;
      pthread_mutex_t inner_lock;
      pthread_cond_t inner_cond;
    };

    template<typename ITEM>
    class Tracer {
    public:
      class TraceBlock {
      public:
        explicit TraceBlock(const TraceBlock &refblk)
	  : max_size(refblk.max_size), cur_size(0),
	    time_mult(refblk.time_mult), next(0)
	{
	  PTHREAD_SAFE_CALL(pthread_mutex_init(&mutex,NULL));
	  start_time = Realm::Clock::current_time();
	  items = new ITEM[max_size];
	}

	TraceBlock(size_t block_size, double exp_arrv_rate)
	  : max_size(block_size), cur_size(0), next(0)
	{
	  PTHREAD_SAFE_CALL(pthread_mutex_init(&mutex,NULL));
	  start_time = Realm::Clock::current_time();
	  items = new ITEM[max_size];

	  // set the time multiplier such that there'll likely be 2^31
	  //  time units by the time we fill the block, i.e.:
	  // (block_size / exp_arrv_rate) * mult = 2^31  -->
	  // mult = 2^31 * exp_arrv_rate / block_size
	  time_mult = 2147483648.0 * exp_arrv_rate / block_size;
	}
        pthread_mutex_t mutex;
	size_t max_size, cur_size;
	double start_time, time_mult;
	ITEM *items;
	TraceBlock *next;
      };

      static TraceBlock*& get_first_block(void)
      {
        static TraceBlock *first_block = NULL;
        return first_block;
      }

      static TraceBlock*& get_last_block(void)
      {
        static TraceBlock *last_block = NULL;
        return last_block;
      }

      static void init_trace(size_t block_size, double exp_arrv_rate)
      {
        get_first_block() = get_last_block() = new TraceBlock(block_size, exp_arrv_rate);
        assert(get_first_block() != NULL);
        assert(get_last_block() != NULL);
      }

      static inline ITEM& trace_item(void)
      {
        TraceBlock *block = get_last_block();
        assert(block != NULL);

	// loop until we can manage to reserve a real entry
	size_t my_index;
	while(1) {
	  my_index = __sync_fetch_and_add(&(block->cur_size), 1);
	  if(my_index < block->max_size) break; // victory!

	  // no space - case 1: another block has already been chained on -
	  //  try that one
	  if(block->next) {
	    block = block->next;
	    continue;
	  }

	  // case 2: try to add a block on ourselves - take the current block's
	  //  mutex and make sure somebody else didn't do it while we waited
	  pthread_mutex_lock(&(block->mutex));
	  if(block->next) {
	    pthread_mutex_unlock(&(block->mutex));
	    block = block->next;
	    continue;
	  }

	  // the next pointer is still null, and we hold the lock, so we
	  //  do the allocation of the next block
	  TraceBlock *newblock = new TraceBlock(*block);

	  // nobody else knows about the block, so we can have index 0
	  my_index = 0;
	  newblock->cur_size++;

	  // now update the "last_block" static value (while we still hold
	  //  the previous block's lock)
	  get_last_block() = newblock;
	  block->next = newblock;
	  pthread_mutex_unlock(&(block->mutex));

	  // new block has been added, and we already grabbed our location,
	  //  so we're done
	  block = newblock;
	  break;
	}

	double time_units = ((Realm::Clock::current_time() - block->start_time) *
			     block->time_mult);
	assert(time_units >= 0);
	assert(time_units < 4294967296.0);

	block->items[my_index].time_units = (unsigned)time_units;
        return block->items[my_index];
      }

      // Implementation specific to low level runtime because of synchronization
      static void dump_trace(const char *filename, bool append);
    };

    // Example Item types in lowlevel_impl.h

  }; // LegionRuntime::LowLevel namespace

}; // LegionRuntime namespace

#undef PTHREAD_SAFE_CALL

#endif // __RUNTIME_UTILITIES_H__


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Igneel.IA.Inference.Compilation
{
    public abstract class Declaration : ASTNode
    {
        public string Name { get; set; }

        public Declaration(string name)
        {
            Name = name;
        }
    }

    public abstract class ExpressionDeclaration : Declaration
    {
        public Expresion Exp { get; set; }

        public ExpressionDeclaration(string name, Expresion expression)
            : this(name)
        {
            Exp = expression;
        }

        public ExpressionDeclaration(string name)
            : base(name)
        {

        }

        public override void CheckSemantic(ICompilationLog log, CompilationScope scope)
        {
            Exp.CheckSemantic(log, scope);
            this.Type = Exp.Type;
        }
    }

    public abstract class FactDeclaration : Declaration
    {
        public FactDeclaration(string name)
            : base(name)
        {

        }

        public Fact Value { get; set; }

        public override void CheckSemantic(ICompilationLog log, CompilationScope scope)
        {
            scope.Add(this);
            scope.Add(Value);

            Type = Value.FactType;
        }
    }
}


text:
param([string] $IsSilentInstallation = 'false', [string] $Log = '.\Setup.log')
#Requires -Version 2.0
# This code is Copyright (c) 2016 Microsoft Corporation.
#
# All rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
#  INCLUDING BUT NOT LIMITED To THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
#  PARTICULAR PURPOSE.'
#
# IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
#  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
#  WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
#  WITH THE USE OR PERFORMANCE OF THIS CODE OR INFORMATION.

[bool] $IsSilentInstallation = [System.Convert]::ToBoolean($IsSilentInstallation)

#////////////////
#// Functions //
#//////////////

Function Write-Log
{
    param($Output)
    #// Writes to the log file.
    $TimeStamp = "$(Get-Date -format yyyyMMdd-HHmmss)"
    if ($Output -eq $null) {Add-content $Log -value ('[' + $TimeStamp + '] NULL') -Encoding Unicode;Return}
    switch ($Output.GetType().FullName)
    {
        'System.String'                {Add-content -Path $Log -value ('[' + $TimeStamp + '] ' + $Output) -Encoding Unicode}
        'System.Collections.ArrayList' {Add-content -Path $Log -value ('[' + $TimeStamp + ']') -Encoding Unicode; $Output >> $Log}
        default                        {Add-content -Path $Log -value ('[' + $TimeStamp + '] ' + $Output) -Encoding Unicode}
    }
}

Function Test-Error
{
    param($Err)
    #// Tests if an error condition exists and writes it to the log.
    if ($Err.Count -gt 0)
    {
        Write-Log ('[Test-Error] Error(s) found: ' + $Err.Count)
        Write-Log ($Err)
        $Err.Clear()
    }
}

Function Invoke-MyCmd
{
    param([string] $Cmd)
    Write-Log ($Cmd)
    $Output = Invoke-Expression -Command $Cmd
    Write-Log ($Output)
    Test-Error -Err $Error
}

#///////////
#// Main //
#/////////

$Error.Clear()
Write-Log ('[Uninstall]: Start')
Invoke-MyCmd -Cmd 'schtasks /Delete /TN \Microsoft\Windows\PLA\PalCollector-OnWindowsStart /F'
Invoke-MyCmd -Cmd 'logman stop PalCollector'
Start-Sleep -Seconds 2
Invoke-MyCmd -Cmd 'logman delete PalCollector'
Write-Log ('[Uninstall]: End')


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <bean class="blackboard.cloud.spring.ApplicationContextProvider" />
</beans>


text:
package influxql

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestEncodingFormatFromMimeType(t *testing.T) {
	tests := []struct {
		s   string
		exp EncodingFormat
	}{
		{s: "application/csv", exp: EncodingFormatAppCSV},
		{s: "text/csv", exp: EncodingFormatTextCSV},
		{s: "application/x-msgpack", exp: EncodingFormatMessagePack},
		{s: "application/json", exp: EncodingFormatJSON},
		{s: "*/*", exp: EncodingFormatJSON},
		{s: "", exp: EncodingFormatJSON},
		{s: "application/other", exp: EncodingFormatJSON},
	}
	for _, tt := range tests {
		t.Run(tt.s, func(t *testing.T) {
			got := EncodingFormatFromMimeType(tt.s)
			assert.Equal(t, tt.exp, got)
		})
	}
}


text:
Seelog-examples
=======

This package contains examples of [Seelog](https://github.com/cihub/seelog) usage.

Examples
---------------

Current list of examples:

* **starter.go** - runs all examples
* **exceptions_main.go** - demonstrates constraints and exceptions
* **outputs_main.go** - demonstrates dispatchers and writers
* **formats_main.go** - demonstrates formats
* **types_main.go** - demonstrates logger types
* **stresstest_main.go** - demonstrates logger replacement on-the-fly stress test
* **lib_with_sl_main.go** - demonstrates Seelog usage with code that imports Seelog
* **lib_without_sl_main.go** - demonstrates Seelog usage with code that doesn't import Seelog
* **library/lib_log.go** - demonstrates library template with Seelog
* **adaptive_main.go** - demonstrates adaptive logger type


text:
[![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](LICENSE)
[![README](https://img.shields.io/badge/README-English-blue.svg)](README-English.md)
[![README](https://img.shields.io/badge/README-中文-blue.svg)](README.md)
[![README](https://img.shields.io/badge/Telegram-WeChatTweak-brightgreen.svg)](https://t.me/wechattweak)

A dynamic library tweak for WeChat macOS.

## Features

- Anti message revoked
  - Message list notification
  - System notification
  - Revoke message you sent
- Multiple WeChat Instance
  - Launch from Dock menu
  - Run command: `open -n /Applications/WeChat.app`
- Messages enhancement
  - Support stickers exporting
  - Support QRCode identifying
  - Support right-click copy link directly
  - Support opened by the system default browser directly
- ~~Auto login without authentication~~ (Already supported by official)
- UI Interface settings panel
- Alfred workflow support
- Launchbar action support

## Usage

Install command line tool [WeChatTweak-CLI](https://github.com/Sunnyyoung/WeChatTweak-CLI):

  ```bash
  $ brew tap sunnyyoung/repo/wechattweak-cli
  ```

Install/Upgrade/Uninstall Tweak:

  ```bash
  $ sudo wechattweak-cli install   # Install/Uninstall
  $ sudo wechattweak-cli uninstall # Uninstall
  ```

## Screenshots

### Overview

![Overview](Screenshot/0x01.png)

### Alfred workflow

![Alfred](Screenshot/0x02.png)

### LaunchBar action

![LaunchBar](Screenshot/0x03.png)

## References

- [微信 macOS 客户端无限多开功能实践](https://blog.sunnyyoung.net/wei-xin-macos-ke-hu-duan-wu-xian-duo-kai-gong-neng-shi-jian/)
- [微信 macOS 客户端拦截撤回功能实践](https://blog.sunnyyoung.net/wei-xin-macos-ke-hu-duan-lan-jie-che-hui-gong-neng-shi-jian/)
- [让微信 macOS 客户端支持 Alfred](https://blog.sunnyyoung.net/rang-wei-xin-macos-ke-hu-duan-zhi-chi-alfred/)

## Contributors

This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].

[![Contributors](https://opencollective.com/WeChatTweak-macOS/contributors.svg?width=890&button=false)](https://github.com/Sunnyyoung/WeChatTweak-macOS/graphs/contributors)

## License

The [Apache License 2.0](LICENSE).


text:
check: config.pb messages.pb storage.pb types.pb

%.pb: %.proto
	protoc -I/usr/include -I. $< -o $@

clean:
	rm -f *.pb


text:
import { get } from 'lodash';
import mapActionToReducer from 'redux-action-reducer-mapper';

import {
    FETCH_OPTIONS_REQUEST,
    FETCH_OPTIONS_RESPONSE,
} from './actions';

const INITIAL_STATE = {
    loaded: false,
};

export default mapActionToReducer({
    default: INITIAL_STATE,

    [FETCH_OPTIONS_REQUEST]: (state) => ({
        ...state,
        loaded: false,
    }),

    [FETCH_OPTIONS_RESPONSE]: (state, action) => ({
        ...state,
        loaded: true,
        url: get(action.payload.permissions, [`${location.protocol}//${location.host}`, 'url'], ''),
        token: get(action.payload.permissions, [`${location.protocol}//${location.host}`, 'token'], ''),
    }),
});


text:
'use strict';

import { ensureEntity } from './base';

export function ensure (space, contentTypes) {
  return ensureEntity(space, contentTypes, schema());
}

export function schema () {
  return {
    name: 'Post',
    fields: [
      { id: 'title', name: 'Title', type: 'Symbol' },
      { id: 'slug', name: 'Slug', type: 'Symbol' },
      { id: 'body', name: 'Body', type: 'Text' },
      { id: 'publishedAt', name: 'Published At', type: 'Date' },
      { id: 'metaTitle', name: 'Meta Title', type: 'Symbol' },
      { id: 'metaDescription', name: 'Meta Description', type: 'Symbol' },
      { id: 'author', name: 'Author', type: 'Link', linkType: 'Entry' },
      { id: 'tags', name: 'Tags', type: 'Array', items: { type: 'Link', linkType: 'Entry' }}
    ]
  };
}


text:
package com.fruit.thememanager;

import java.util.ArrayList;

import com.fruit.thememanager.helper.ThemeInfo;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class ThemeCustomOptActivity extends Activity
	implements View.OnClickListener, AdapterView.OnItemClickListener{

	static final String TAG = "ThemeCustomOptActivity";
	private static final int REQUEST_THEME_ITEM = 60;
	private static final int REQUEST_THEME_MORE = 70;

	private GridView mThemeGrid;

	private int mThemeCategory;
	private BaseAdapter mAdapter;
	private ArrayList<ThemeInfo> mArrayListTheme;
	private String mThemeName;
	private ThemeManager mThemeMgr ;
	private boolean mbForceUpdate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.theme_custom_opt);
		initViews();
	}

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

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

		String theme = mThemeMgr.getCurrentTheme(mThemeCategory);
		Log.d(TAG, "onResume mThemeName="+mThemeName+", theme="+theme);
		if(mbForceUpdate || !theme.equals(mThemeName)){
			mThemeName = new String(theme);
			mArrayListTheme = mThemeMgr.getAllTheme(mThemeCategory);
			mAdapter = getThemeAdapter(mThemeCategory, mArrayListTheme);
			mThemeGrid.setAdapter(mAdapter);

			mbForceUpdate = false;
		}
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode == REQUEST_THEME_ITEM){
    		if(resultCode == ThemeUtils.ACTIVITY_RESULT_DELETE){
    			Log.w(TAG, "onActivityResult theme delete");
    			mbForceUpdate = true;

    			setResult(ThemeUtils.ACTIVITY_RESULT_DELETE);
    			this.finish();
    		}
    	}
    }

	private void initViews() {
        final Intent intent = getIntent();
        String title = null;

		if (intent.hasExtra(Intent.EXTRA_TITLE)) {
            title = intent.getStringExtra(Intent.EXTRA_TITLE);
        }
		if (intent.hasExtra(ThemeUtils.THEME_CATEGORY)) {
			mThemeCategory = intent.getIntExtra(ThemeUtils.THEME_CATEGORY,
					ThemeUtils.CATEGORY_LAUNCHERICON);
        }

		if(title == null || mThemeCategory == 0){
			Log.e(TAG, "initViews get title , themeCategory error! ");
			return;
		}

		//get adpter
		mThemeMgr = ThemeManager.getInstance(this);
		mThemeName = new String(mThemeMgr.getCurrentTheme(mThemeCategory));
		mArrayListTheme = mThemeMgr.getAllTheme(mThemeCategory);

		mAdapter = getThemeAdapter(mThemeCategory, mArrayListTheme);

		if(mAdapter == null){
			Log.e(TAG, "initViews create adpter error! ");
			return;
		}

		//set title
		((TextView)findViewById(R.id.theme_custom_title)).setText(title);

		//hide or show button more
		if(mThemeCategory == ThemeUtils.CATEGORY_WALLPAPER){
			TextView textMore = (TextView) findViewById(R.id.theme_custom_more);
			textMore.setText(R.string.theme_wallpaper_more);
			textMore.setOnClickListener(this);
		}else{
			findViewById(R.id.theme_custom_more_bar).setVisibility(View.GONE);
		}

		mThemeGrid = (GridView) findViewById(R.id.theme_custom_show);
		mThemeGrid.setAdapter(mAdapter);
		mThemeGrid.setOnItemClickListener(this);

		mbForceUpdate = false;
	}

	private BaseAdapter getThemeAdapter(int category, ArrayList<ThemeInfo> listThemeInfo){
		BaseAdapter adpter = null;

		switch (category) {
		case ThemeUtils.CATEGORY_LAUNCHERICON:
			adpter = new ThemeShowAdapter(this, listThemeInfo,
					ThemeUtils.THUMBIMG_LAUNCHERICON);
			break;
		case ThemeUtils.CATEGORY_LOCKSCREEN:
			adpter = new ThemeShowAdapter(this, listThemeInfo,
					ThemeUtils.THUMBIMG_LOCKSCREEN);
			break;
		case ThemeUtils.CATEGORY_WALLPAPER:
			adpter = new ThemeShowImageAdapter(this, listThemeInfo,
					ThemeUtils.THUMBIMG_WALLPAPER);
			break;
		case ThemeUtils.CATEGORY_LOCKWALLPAPER:
			adpter = new ThemeShowImageAdapter(this, listThemeInfo,
					ThemeUtils.THUMBIMG_LOCKWALLPAPER);
			break;
		default:
			break;
		}

		return adpter;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.theme_custom_more){
			if(mThemeCategory == ThemeUtils.CATEGORY_WALLPAPER){
		        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
		        Intent chooser = Intent.createChooser(pickWallpaper,
		                getText(R.string.chooser_wallpaper));
		        startActivitySafely(chooser, REQUEST_THEME_MORE);
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		// TODO Auto-generated method stub
		ThemeInfo info = (ThemeInfo) parent.getItemAtPosition(position);

		if(info.mPkgName != null){
			Intent intent = new Intent();
			intent.setAction(ThemeUtils.ACTION_APPLY_THEME);
			intent.setClass(this, ThemeApplyActivity.class);
			intent.putExtra(ThemeUtils.PACKAGE_NAME, info.mPkgName);
			intent.putExtra(ThemeUtils.THEME_TYPE, ThemeUtils.getThemeType(info.mThemeType));
			intent.putExtra(ThemeUtils.THEME_CATEGORY, mThemeCategory);
			startActivitySafely(intent, REQUEST_THEME_ITEM);
		}
	}

	public void	startActivitySafely(Intent intent, int requestCode){
        try {
            startActivityForResult(intent, requestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        }
	}
}


text:
package org.apache.samza.storage.kv;

import java.io.File;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.SamzaException;
import org.apache.samza.config.Config;
import org.apache.samza.config.MetricsConfig;
import org.apache.samza.config.StorageConfig;
import org.apache.samza.context.ContainerContext;
import org.apache.samza.context.JobContext;
import org.apache.samza.metrics.MetricsRegistry;
import org.apache.samza.serializers.Serde;
import org.apache.samza.storage.StorageEngine;
import org.apache.samza.storage.StorageEngineFactory;
import org.apache.samza.storage.StoreProperties;
import org.apache.samza.system.SystemStreamPartition;
import org.apache.samza.task.MessageCollector;
import org.apache.samza.util.HighResolutionClock;
import org.apache.samza.util.ScalaJavaUtil;

/**
 * This encapsulates all the steps needed to create a key value storage engine.
 * This is meant to be extended by the specific key value store factory implementations which will in turn override the
 * getKVStore method to return a raw key-value store.
 *
 * BaseKeyValueStorageEngineFactory assumes non null keySerde and msgSerde
 */
public abstract class BaseKeyValueStorageEngineFactory<K, V> implements StorageEngineFactory<K, V> {
  private static final String INMEMORY_KV_STORAGE_ENGINE_FACTORY =
      "org.apache.samza.storage.kv.inmemory.InMemoryKeyValueStorageEngineFactory";
  private static final String WRITE_BATCH_SIZE = "write.batch.size";
  private static final int DEFAULT_WRITE_BATCH_SIZE = 500;
  private static final String OBJECT_CACHE_SIZE = "object.cache.size";
  private static final int DEFAULT_OBJECT_CACHE_SIZE = 1000;

  /**
   * Implement this to return a KeyValueStore instance for the given store name, which will be used as the underlying
   * raw store.
   *
   * @param storeName Name of the store
   * @param storeDir The directory of the store
   * @param registry MetricsRegistry to which to publish store specific metrics.
   * @param jobContext Information about the job in which the task is executing.
   * @param containerContext Information about the container in which the task is executing.
   * @return A raw KeyValueStore instance
   */
  protected abstract KeyValueStore<byte[], byte[]> getKVStore(String storeName,
      File storeDir,
      MetricsRegistry registry,
      JobContext jobContext,
      ContainerContext containerContext,
      StoreMode storeMode);

  /**
   * Constructs a key-value StorageEngine and returns it to the caller
   *
   * @param storeName The name of the storage engine.
   * @param storeDir The directory of the storage engine.
   * @param keySerde The serializer to use for serializing keys when reading or writing to the store.
   * @param msgSerde The serializer to use for serializing messages when reading or writing to the store.
   * @param changelogCollector MessageCollector the storage engine uses to persist changes.
   * @param registry MetricsRegistry to which to publish storage-engine specific metrics.
   * @param changelogSSP Samza system stream partition from which to receive the changelog.
   * @param containerContext Information about the container in which the task is executing.
   **/
  public StorageEngine getStorageEngine(String storeName,
      File storeDir,
      Serde<K> keySerde,
      Serde<V> msgSerde,
      MessageCollector changelogCollector,
      MetricsRegistry registry,
      SystemStreamPartition changelogSSP,
      JobContext jobContext,
      ContainerContext containerContext,
      StoreMode storeMode) {
    Config storageConfigSubset = jobContext.getConfig().subset("stores." + storeName + ".", true);
    StorageConfig storageConfig = new StorageConfig(jobContext.getConfig());
    Optional<String> storeFactory = storageConfig.getStorageFactoryClassName(storeName);
    StoreProperties.StorePropertiesBuilder storePropertiesBuilder = new StoreProperties.StorePropertiesBuilder();
    if (!storeFactory.isPresent() || StringUtils.isBlank(storeFactory.get())) {
      throw new SamzaException(
          String.format("Store factory not defined for store %s. Cannot proceed with KV store creation!", storeName));
    }
    if (!storeFactory.get().equals(INMEMORY_KV_STORAGE_ENGINE_FACTORY)) {
      storePropertiesBuilder.setPersistedToDisk(true);
    }
    // The store is durable iff it is backed by the task backup manager
    List<String> storeBackupManagers = storageConfig.getStoreBackupFactories(storeName);
    storePropertiesBuilder.setIsDurable(!storeBackupManagers.isEmpty());

    int batchSize = storageConfigSubset.getInt(WRITE_BATCH_SIZE, DEFAULT_WRITE_BATCH_SIZE);
    int cacheSize = storageConfigSubset.getInt(OBJECT_CACHE_SIZE, Math.max(batchSize, DEFAULT_OBJECT_CACHE_SIZE));
    if (cacheSize > 0 && cacheSize < batchSize) {
      throw new SamzaException(
          String.format("cache.size for store %s cannot be less than batch.size as batched values reside in cache.",
              storeName));
    }
    if (keySerde == null) {
      throw new SamzaException(
          String.format("Must define a key serde when using key value storage for store %s.", storeName));
    }
    if (msgSerde == null) {
      throw new SamzaException(
          String.format("Must define a message serde when using key value storage for store %s.", storeName));
    }

    KeyValueStore<byte[], byte[]> rawStore =
        getKVStore(storeName, storeDir, registry, jobContext, containerContext, storeMode);
    KeyValueStore<byte[], byte[]> maybeLoggedStore = buildMaybeLoggedStore(changelogSSP,
        storeName, registry, storePropertiesBuilder, rawStore, changelogCollector);
    // this also applies serialization and caching layers
    KeyValueStore<K, V> toBeAccessLoggedStore = buildStoreWithLargeMessageHandling(storeName, registry,
        maybeLoggedStore, storageConfig, cacheSize, batchSize, keySerde, msgSerde);
    KeyValueStore<K, V> maybeAccessLoggedStore =
        buildMaybeAccessLoggedStore(storeName, toBeAccessLoggedStore, changelogCollector, changelogSSP, storageConfig,
            keySerde);
    KeyValueStore<K, V> nullSafeStore = new NullSafeKeyValueStore<>(maybeAccessLoggedStore);

    KeyValueStorageEngineMetrics keyValueStorageEngineMetrics = new KeyValueStorageEngineMetrics(storeName, registry);
    HighResolutionClock clock = buildClock(jobContext.getConfig());
    return new KeyValueStorageEngine<>(storeName, storeDir, storePropertiesBuilder.build(), nullSafeStore, rawStore,
        changelogSSP, changelogCollector, keyValueStorageEngineMetrics, batchSize,
        ScalaJavaUtil.toScalaFunction(clock::nanoTime));
  }

  /**
   * Wraps {@code storeToWrap} into a {@link LoggedStore} if {@code changelogSSP} is defined.
   * Otherwise, returns the original {@code storeToWrap}.
   */
  private static KeyValueStore<byte[], byte[]> buildMaybeLoggedStore(SystemStreamPartition changelogSSP,
      String storeName,
      MetricsRegistry registry,
      StoreProperties.StorePropertiesBuilder storePropertiesBuilder,
      KeyValueStore<byte[], byte[]> storeToWrap,
      MessageCollector changelogCollector) {
    if (changelogSSP == null) {
      return storeToWrap;
    } else {
      LoggedStoreMetrics loggedStoreMetrics = new LoggedStoreMetrics(storeName, registry);
      storePropertiesBuilder.setLoggedStore(true);
      return new LoggedStore<>(storeToWrap, changelogSSP, changelogCollector, loggedStoreMetrics);
    }
  }

  /**
   * Wraps {@code storeToWrap} with the proper layers to handle large messages.
   * If "disallow.large.messages" is enabled, then the message will be serialized and the size will be checked before
   * storing in the serialized message in the cache.
   * If "disallow.large.messages" is disabled, then the deserialized message will be stored in the cache. If
   * "drop.large.messages" is enabled, then large messages will not be sent to the logged store.
   */
  private static <T, U> KeyValueStore<T, U> buildStoreWithLargeMessageHandling(String storeName,
      MetricsRegistry registry,
      KeyValueStore<byte[], byte[]> storeToWrap,
      StorageConfig storageConfig,
      int cacheSize,
      int batchSize,
      Serde<T> keySerde,
      Serde<U> msgSerde) {
    int maxMessageSize = storageConfig.getChangelogMaxMsgSizeBytes(storeName);
    if (storageConfig.getDisallowLargeMessages(storeName)) {
      /*
       * The store wrapping ordering is done this way so that a large message cannot end up in the cache. However, it
       * also means that serialized data is in the cache, so performance will be worse since the data needs to be
       * deserialized even when cached.
       */
      KeyValueStore<byte[], byte[]> maybeCachedStore =
          buildMaybeCachedStore(storeName, registry, storeToWrap, cacheSize, batchSize);
      // this will throw a RecordTooLargeException when a large message is encountered
      LargeMessageSafeStore largeMessageSafeKeyValueStore =
          new LargeMessageSafeStore(maybeCachedStore, storeName, false, maxMessageSize);
      return buildSerializedStore(storeName, registry, largeMessageSafeKeyValueStore, keySerde, msgSerde);
    } else {
      KeyValueStore<byte[], byte[]> toBeSerializedStore;
      if (storageConfig.getDropLargeMessages(storeName)) {
        toBeSerializedStore = new LargeMessageSafeStore(storeToWrap, storeName, true, maxMessageSize);
      } else {
        toBeSerializedStore = storeToWrap;
      }
      KeyValueStore<T, U> serializedStore =
          buildSerializedStore(storeName, registry, toBeSerializedStore, keySerde, msgSerde);
      /*
       * Allows deserialized entries to be stored in the cache, but it means that a large message may end up in the
       * cache even though it was not persisted to the logged store.
       */
      return buildMaybeCachedStore(storeName, registry, serializedStore, cacheSize, batchSize);
    }
  }

  /**
   * Wraps {@code storeToWrap} with a {@link CachedStore} if caching is enabled.
   * Otherwise, returns the {@code storeToWrap}.
   */
  private static <T, U> KeyValueStore<T, U> buildMaybeCachedStore(String storeName, MetricsRegistry registry,
      KeyValueStore<T, U> storeToWrap, int cacheSize, int batchSize) {
    if (cacheSize > 0) {
      CachedStoreMetrics cachedStoreMetrics = new CachedStoreMetrics(storeName, registry);
      return new CachedStore<>(storeToWrap, cacheSize, batchSize, cachedStoreMetrics);
    } else {
      return storeToWrap;
    }
  }

  /**
   * Wraps {@code storeToWrap} with a {@link SerializedKeyValueStore}.
   */
  private static <T, U> KeyValueStore<T, U> buildSerializedStore(String storeName,
      MetricsRegistry registry,
      KeyValueStore<byte[], byte[]> storeToWrap,
      Serde<T> keySerde,
      Serde<U> msgSerde) {
    SerializedKeyValueStoreMetrics serializedMetrics = new SerializedKeyValueStoreMetrics(storeName, registry);
    return new SerializedKeyValueStore<>(storeToWrap, keySerde, msgSerde, serializedMetrics);
  }

  /**
   * Wraps {@code storeToWrap} with an {@link AccessLoggedStore} if enabled.
   * Otherwise, returns the {@code storeToWrap}.
   */
  private static <T, U> KeyValueStore<T, U> buildMaybeAccessLoggedStore(String storeName,
      KeyValueStore<T, U> storeToWrap,
      MessageCollector changelogCollector,
      SystemStreamPartition changelogSSP,
      StorageConfig storageConfig,
      Serde<T> keySerde) {
    if (storageConfig.getAccessLogEnabled(storeName)) {
      return new AccessLoggedStore<>(storeToWrap, changelogCollector, changelogSSP, storageConfig, storeName, keySerde);
    } else {
      return storeToWrap;
    }
  }

  /**
   * If "metrics.timer.enabled" is enabled, then returns a {@link HighResolutionClock} that uses
   * {@link System#nanoTime}.
   * Otherwise, returns a clock which always returns 0.
   */
  private static HighResolutionClock buildClock(Config config) {
    MetricsConfig metricsConfig = new MetricsConfig(config);
    if (metricsConfig.getMetricsTimerEnabled()) {
      return System::nanoTime;
    } else {
      return () -> 0;
    }
  }
}


text:
import { MoLogs } from '../../db/entity/moLogs';

export interface LogsAttributesInterface {
    module: string;
    type: string;
    page: number;
}

export interface GetLogsInterface {
    logs: Array<LogInterface>;
    amount: number;
}

interface LogInterface extends MoLogs {
    admin: string;
}


text:
Portfolio

UNIO

A web based mobile network performance analysis tool for MTN.
                    The tool makes troubleshooting the performance of a mobile network very quick and easy.

The tool was developed using PHP and a self developed lightweight framework.

Big Data Visualisation

A group project completed as part of a M.Eng degree at the University of Witwatersrand.
                    A web based dashboard was developed to visualise a publicly available "big data" data source from the World Bank.

                    The dashboard was developed using Node.js technology and makes use of the Express.js framework.

The author was allocated the responsibility of implementing the framework and structure that the web application would use. In addition to this the author was also tasked to develop the indicator dashboard and maintain the project wiki (located here). A comprehensive help page providing the members with an overview of the framework and how to implement their dashboards using the framework was developed (located here).

                    Git Repository

roosdupreez.co.za

A marketing website for a medico-legal occupational therapy
                        private practice

The website was built using PHP and the Laravel framework.

                    Visit website

tien-kilo.co.za

A communication and social web application for the owners of a shared
                        title farm near Swartruggens in the North-West province

The application was built using PHP and the Laravel framework

                    Visit website

instopp.co.za

A knowledge sharing and communication website for the Institute
                        of Occupational Therapists in Private Practice (INSTOPP)

The website was built using PHP and the Laravel framework

Unfortunately this website has in the meantime been replaced and is not publicly available anymore.

Road Network Maintenance

 A group project completed as part of a M.Eng degree at the University of Witwatersrand.
                        This Java application models the domain of a system to aid the transport department of local government in maintaining their assets, which include not only the road network but also supporting infrastructure.

                    The application was developed using Behavior Driven Development (BDD) and Test Driven Development (TDD) approaches. Cucumber and JUnit were used as testing frameworks. The design methodology used was Domain Driven Design (DDD).

                    Git Repository

FORSHO

Contributing to an app aimed at re-inventing and simplifying the way group events are scheduled.

The app is designed with a RESTful web service decoupling the back end and front end. The Swagger framework is used to aid the design and documentation of the RESTful web service. The back end is developed with Spring Boot and the front end is developed in Android.

Bitbucket Repository (Private - Viewing rights can be granted upon request)


text:
function Light(scene, template) {
    this.lastUpdateFrame = 0;
    this.castsShadows = false;

    this.type = template.type;
    this.subtype = template.subtype;
    this.falloff_angle = template.falloff_angle;
    this.falloff_exponent = template.falloff_exponent;
    this.color = template.color;
    this.constant_attenuation = template.constant_attenuation;
    this.linear_attenuation = template.linear_attenuation;
    this.quadratic_attenuation = template.quadratic_attenuation;

//    this.radius = 100; // TODO: Use attenuation values?
    this.radius = this.linear_attenuation * 10;
    if (this.subtype == 'spot') {
        this.projectionMatrix = M4x4().makePerspective(this.falloff_angle, 1.0, 0.1, this.radius);
    } else if (this.subtype == 'point') {
        this.projectionMatrix = I4x4();
    } else {
        // FIXME: the coordinates here is the size in ws units which the shadowmap covers. Should be calculated using som sort of bbox not using the fallof angle
        this.projectionMatrix = M4x4().makeOrtho(-this.falloff_angle, this.falloff_angle, -this.falloff_angle, this.falloff_angle, 0, this.radius);
    }

    this.shadowmapSize = 1024;
    this.shadowTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, this.shadowTexture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    if (this.subtype != 'point') {
        // Create a texture and FBO for shadowmapping
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.shadowmapSize, this.shadowmapSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

        this.shadowDepth = gl.createRenderbuffer();
        gl.bindRenderbuffer(gl.RENDERBUFFER, this.shadowDepth);
        gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.shadowmapSize, this.shadowmapSize);
        this.shadowFBO = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.shadowFBO);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.shadowTexture, 0);
        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.shadowDepth);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    } else {
        // point light does not have shadows. Set the distance to max to achieve that effect
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255,255,255,255]));
    }
}

function LightPrototype() {
    this.beginShadowmapRendering = function() {
            if (this.subtype == 'point') {
                return false;
            }
            // bind the shadowmap FBO
            gl.bindFramebuffer(gl.FRAMEBUFFER, this.shadowFBO);
            gl.viewport(0,0,this.shadowmapSize,this.shadowmapSize);
            gl.clearColor(1,1,1,1);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            gl.clearColor(0.75, 0.75, 0.75, 1.0);

            this.backupProjection = projectionMatrix().copy();
            this.backupView = viewMatrix().copy();

            projectionMatrix().make(this.projectionMatrix);
            viewMatrix().make(this.getAccumulatedTransform()).invertRigidBody();
            return true;
    }

    this.endShadowmapRendering = function() {
            projectionMatrix().make(this.backupProjection);
            viewMatrix().make(this.backupView);
    }

    this.viewProjectionMatrix = function() {
            var view = M4x3().make(this.getAccumulatedTransform()).invertRigidBody();
            return this.projectionMatrix.copy().multiply(view);
    }

    this.getType = function() {
        // 0 = point, 1 = spot, 2 = directional
        if (this.subtype == 'spot') {
            return 1;
        } else if (this.subtype == 'directional') {
            return 2;
        } else {
            return 0;
        }
    }

    this.drawSkeleton = function(dbgDraw, frames) {
        if (this.subtype == 'point') {
          var alen = 0.3
          dbgDraw.drawLine(-alen,0,0, alen,0,0, dbgDraw.RED,frames, 1);
          dbgDraw.drawLine(0,-alen,0, 0,alen,0, dbgDraw.RED,frames, 1);
          dbgDraw.drawLine(0,0,-alen, 0,0,alen, dbgDraw.RED,frames, 1);
        }
    }
}

LightPrototype.prototype = Node.prototype;
Light.prototype = new LightPrototype();


text:
export default {

  getState(resource) {
    var targets = resource[this.props.column.association.name];
    return {
      targets: targets,
      dirty: false,
    };
  },
  getInitialState() {
    return this.getState(this.props.resource);
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.resource && nextProps.resource.id != this.props.resource.id) {
      this.setState(this.getState(nextProps.resource));
    }
  },

  getResourceValue() {
    var keys = Object.keys(this.refs);
    var result = {};
    var targets = [];
    var name = this.props.column.association.name;

    for (var i = 0, len = keys.length; i < len; i++) {
      var key = keys[i];
      var property = this.refs[key];
      var value = property.getResourceValue();
      targets.push(value[name]);
    }

    result[name] = targets;
    return result;
  },

  isDirty() {
    if( this.props.dirty ) return true;

    var keys = Object.keys(this.refs);
    for (var i = 0, len = keys.length; i < len; i++) {
      var key = keys[i];
      var property = this.refs[key];
      if( property.isDirty() ) {
        return true;
      }
    }
    return false;
  },

  add() {
    var targets = this.state.targets;
    targets.push(null);
    this.setState({
      targets: targets,
      dirty: false,
    });
  },

  hasError() {
    return this.props.invalid;
  },

  render() {
    var column      = this.props.column;
    var name        = column.name;
    var label       = this.toProperyName(column);
    var targets     = this.state.targets || [];
    if(targets.length == 0) {
      targets.push(null);  // append blank record if empty
    }
    var associations = targets.map((tgt, i) => {
      var attrs = {
        key: `${name}[${i}]`,
        ref: i,
      };
      return this.createAssociation(tgt, attrs);
    });

    return(

         { label }

         { associations }

           <button type="button" className="btn btn-flat btn-primary btn-xs" onClick={ this.add } >Add</button>

         { this.errorsBlock(label) }

    );
  },
};


text:
require 'spec_helper'

describe 'delete recipe' do
  it 'should call API::recipes_destroy' do
    Debox::API.should_receive(:recipes_destroy).with(app: 'test', env: 'prod')
    run_command 'recipes:delete test prod'
  end
end


text:
===============================================================================================
Benchmarking Multi-objective Optimizers on the ``bbob-biobj`` Suite with Coco: A Short Tutorial
===============================================================================================

The Comparing Continuous Optimizers platform (COCO) offers an almost automated way of benchmarking numerical (black-box)
optimizers. Running experiments is supported in various languages (C, Java, Matlab/Octave, python) during which the
data acquisition is automated and even hidden to the user such that she/he only needs to care about connecting
an optimization algorithm to the Coco framework and providing some cpu time for the actual experiment. The automatically
created data folder can be postprocessed with a generic python script which produces various outputs (plots, html, and
LaTeX/PDF summaries) semi-automatically.

Since its entire rewrite, the Coco platform now especially contains a multi-objective benchmark suite `bbob-biobj` with
the above described 55 functions of two objectives each. In the following, we will present briefly how to run
an experiment with Coco (in the python programming language as an example), postprocess the data, and create a
pdf with the results, preparing for a submission at the GECCO conference (i.e., in ACM style). The comparison of two
and more algorithm data sets is also provided, but not detailed here. For more information, we refer to the
documentation of the C code of Coco which every supported language is build upon: http://numbbo.github.io/coco-doc/C/.

will go here:

a short tutorial on how to use the ``bbob-biobj`` test suite for benchmarking multi-objective optimizers within the Coco
framework


text: <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">


text:
using System;
using AutoMapper;

namespace KickStart.AutoMapper
{
    /// <summary>
    /// A KickStart extension to initialize AutoMapper.
    /// </summary>
    public class AutoMapperStarter : IKickStarter
    {
        /// <summary>The AutoMapper configuration data key name</summary>
        public const string AutoMapperConfiguration = "AutoMapper:Configuration";

        private readonly AutoMapperOptions _options;

        /// <summary>
        /// Initializes a new instance of the <see cref="AutoMapperStarter"/> class.
        /// </summary>
        /// <param name="options">The options to use.</param>
        public AutoMapperStarter(AutoMapperOptions options)
        {
            _options = options;
        }

        /// <summary>
        /// Runs the application KickStart extension with specified <paramref name="context" />.
        /// </summary>
        /// <param name="context">The KickStart <see cref="Context" /> containing assemblies to scan.</param>
        public void Run(Context context)
        {
            var profiles = context.GetInstancesAssignableFrom<Profile>();

            var configuration = new MapperConfiguration(config =>
            {
                foreach (var profile in profiles)
                {
                    context.WriteLog("AutoMapper Profile: {0}", profile);

                    config.AddProfile(profile);
                }

                _options.Initialize?.Invoke(config);
            });

            if (_options.Validate)
                configuration.AssertConfigurationIsValid();

            context.Data[AutoMapperConfiguration] = configuration;
        }
    }
}