text:
// ArduinoCompat/wirish.cpp
//
// Arduino-like API for STM32F4 Discovery and similar
// using STM32F4xx_DSP_StdPeriph_Lib_V1.3.0

#include <wirish.h>

SerialUSBClass SerialUSB;

// Describes all the STM32 things we need to know about a digital IO pin to
// make it input or output or to configure as an interrupt
typedef struct
{
    uint32_t         ahbperiph;
    GPIO_TypeDef*    port;
    uint16_t         pin;
    uint8_t          extiportsource;
    uint8_t          extipinsource;
} GPIOPin;

// These describe the registers and bits for each digital IO pin to allow us to
// provide Arduino-like pin addressing, digitalRead etc.
// Indexed by pin number
GPIOPin pins[] =
{
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_0,  EXTI_PortSourceGPIOA, EXTI_PinSource0  }, // 0 = PA0
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_1,  EXTI_PortSourceGPIOA, EXTI_PinSource1  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_2,  EXTI_PortSourceGPIOA, EXTI_PinSource2  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_3,  EXTI_PortSourceGPIOA, EXTI_PinSource3  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_4,  EXTI_PortSourceGPIOA, EXTI_PinSource4  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_5,  EXTI_PortSourceGPIOA, EXTI_PinSource5  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_6,  EXTI_PortSourceGPIOA, EXTI_PinSource6  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_7,  EXTI_PortSourceGPIOA, EXTI_PinSource7  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_8,  EXTI_PortSourceGPIOA, EXTI_PinSource8  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_9,  EXTI_PortSourceGPIOA, EXTI_PinSource9  },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_10, EXTI_PortSourceGPIOA, EXTI_PinSource10 },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_11, EXTI_PortSourceGPIOA, EXTI_PinSource11 },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_12, EXTI_PortSourceGPIOA, EXTI_PinSource12 },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_13, EXTI_PortSourceGPIOA, EXTI_PinSource13 },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_14, EXTI_PortSourceGPIOA, EXTI_PinSource14 },
    { RCC_AHB1Periph_GPIOA, GPIOA, GPIO_Pin_15, EXTI_PortSourceGPIOA, EXTI_PinSource15 }, // 15 = PA15

    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_0,  EXTI_PortSourceGPIOB, EXTI_PinSource0  }, // 16 = PB0
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_1,  EXTI_PortSourceGPIOB, EXTI_PinSource1  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_2,  EXTI_PortSourceGPIOB, EXTI_PinSource2  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_3,  EXTI_PortSourceGPIOB, EXTI_PinSource3  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_4,  EXTI_PortSourceGPIOB, EXTI_PinSource4  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_5,  EXTI_PortSourceGPIOB, EXTI_PinSource5  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_6,  EXTI_PortSourceGPIOB, EXTI_PinSource6  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_7,  EXTI_PortSourceGPIOB, EXTI_PinSource7  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_8,  EXTI_PortSourceGPIOB, EXTI_PinSource8  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_9,  EXTI_PortSourceGPIOB, EXTI_PinSource9  },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_10, EXTI_PortSourceGPIOB, EXTI_PinSource10 },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_11, EXTI_PortSourceGPIOB, EXTI_PinSource11 },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_12, EXTI_PortSourceGPIOB, EXTI_PinSource12 },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_13, EXTI_PortSourceGPIOB, EXTI_PinSource13 },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_14, EXTI_PortSourceGPIOB, EXTI_PinSource14 },
    { RCC_AHB1Periph_GPIOB, GPIOB, GPIO_Pin_15, EXTI_PortSourceGPIOB, EXTI_PinSource15 }, // 31 = PB15

    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_0,  EXTI_PortSourceGPIOC, EXTI_PinSource0  }, // 32 = PC0
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_1,  EXTI_PortSourceGPIOC, EXTI_PinSource1  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_2,  EXTI_PortSourceGPIOC, EXTI_PinSource2  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_3,  EXTI_PortSourceGPIOC, EXTI_PinSource3  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_4,  EXTI_PortSourceGPIOC, EXTI_PinSource4  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_5,  EXTI_PortSourceGPIOC, EXTI_PinSource5  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_6,  EXTI_PortSourceGPIOC, EXTI_PinSource6  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_7,  EXTI_PortSourceGPIOC, EXTI_PinSource7  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_8,  EXTI_PortSourceGPIOC, EXTI_PinSource8  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_9,  EXTI_PortSourceGPIOC, EXTI_PinSource9  },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_10, EXTI_PortSourceGPIOC, EXTI_PinSource10 },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_11, EXTI_PortSourceGPIOC, EXTI_PinSource11 },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_12, EXTI_PortSourceGPIOC, EXTI_PinSource12 },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_13, EXTI_PortSourceGPIOC, EXTI_PinSource13 },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_14, EXTI_PortSourceGPIOC, EXTI_PinSource14 },
    { RCC_AHB1Periph_GPIOC, GPIOC, GPIO_Pin_15, EXTI_PortSourceGPIOC, EXTI_PinSource15 }, // 47 = PC15

    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_0,  EXTI_PortSourceGPIOD, EXTI_PinSource0  }, // 48 = PD0
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_1,  EXTI_PortSourceGPIOD, EXTI_PinSource1  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_2,  EXTI_PortSourceGPIOD, EXTI_PinSource2  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_3,  EXTI_PortSourceGPIOD, EXTI_PinSource3  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_4,  EXTI_PortSourceGPIOD, EXTI_PinSource4  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_5,  EXTI_PortSourceGPIOD, EXTI_PinSource5  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_6,  EXTI_PortSourceGPIOD, EXTI_PinSource6  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_7,  EXTI_PortSourceGPIOD, EXTI_PinSource7  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_8,  EXTI_PortSourceGPIOD, EXTI_PinSource8  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_9,  EXTI_PortSourceGPIOD, EXTI_PinSource9  },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_10, EXTI_PortSourceGPIOD, EXTI_PinSource10 },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_11, EXTI_PortSourceGPIOD, EXTI_PinSource11 },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_12, EXTI_PortSourceGPIOD, EXTI_PinSource12 },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_13, EXTI_PortSourceGPIOD, EXTI_PinSource13 },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_14, EXTI_PortSourceGPIOD, EXTI_PinSource14 },
    { RCC_AHB1Periph_GPIOD, GPIOD, GPIO_Pin_15, EXTI_PortSourceGPIOD, EXTI_PinSource15 }, // 63 = PD15

    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_0,  EXTI_PortSourceGPIOE, EXTI_PinSource0  }, // 64 = PE0
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_1,  EXTI_PortSourceGPIOE, EXTI_PinSource1  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_2,  EXTI_PortSourceGPIOE, EXTI_PinSource2  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_3,  EXTI_PortSourceGPIOE, EXTI_PinSource3  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_4,  EXTI_PortSourceGPIOE, EXTI_PinSource4  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_5,  EXTI_PortSourceGPIOE, EXTI_PinSource5  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_6,  EXTI_PortSourceGPIOE, EXTI_PinSource6  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_7,  EXTI_PortSourceGPIOE, EXTI_PinSource7  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_8,  EXTI_PortSourceGPIOE, EXTI_PinSource8  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_9,  EXTI_PortSourceGPIOE, EXTI_PinSource9  },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_10, EXTI_PortSourceGPIOE, EXTI_PinSource10 },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_11, EXTI_PortSourceGPIOE, EXTI_PinSource11 },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_12, EXTI_PortSourceGPIOE, EXTI_PinSource12 },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_13, EXTI_PortSourceGPIOE, EXTI_PinSource13 },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_14, EXTI_PortSourceGPIOE, EXTI_PinSource14 },
    { RCC_AHB1Periph_GPIOE, GPIOE, GPIO_Pin_15, EXTI_PortSourceGPIOE, EXTI_PinSource15 }, // 79 = PE15

};
#define NUM_PINS (sizeof(pins) / sizeof(GPIOPin))

typedef struct
{
    uint32_t  extiline;
    uint8_t   extiirqn;
    void      (*handler)(void);
} IRQLine;

// IRQ line data indexed by pin source number with its port
// and the programmable handler that will handle interrupts on that line
IRQLine irqlines[] =
{
    { EXTI_Line0,  EXTI0_IRQn,     0 },
    { EXTI_Line1,  EXTI1_IRQn,     0 },
    { EXTI_Line2,  EXTI2_IRQn,     0 },
    { EXTI_Line3,  EXTI3_IRQn,     0 },
    { EXTI_Line4,  EXTI4_IRQn,     0 },
    { EXTI_Line5,  EXTI9_5_IRQn,   0 },
    { EXTI_Line6,  EXTI9_5_IRQn,   0 },
    { EXTI_Line7,  EXTI9_5_IRQn,   0 },
    { EXTI_Line8,  EXTI9_5_IRQn,   0 },
    { EXTI_Line9,  EXTI9_5_IRQn,   0 },
    { EXTI_Line10, EXTI15_10_IRQn, 0 },
    { EXTI_Line11, EXTI15_10_IRQn, 0 },
    { EXTI_Line12, EXTI15_10_IRQn, 0 },
    { EXTI_Line13, EXTI15_10_IRQn, 0 },
    { EXTI_Line14, EXTI15_10_IRQn, 0 },
    { EXTI_Line15, EXTI15_10_IRQn, 0 },
};

#define NUM_IRQ_LINES (sizeof(irqlines) / sizeof(IRQLine))

// Functions we expect to find in the sketch
extern void setup();
extern void loop();

volatile unsigned long systick_count = 0;

void SysTickConfig()
{
    /* Setup SysTick Timer for 1ms interrupts  */
    if (SysTick_Config(SystemCoreClock / 1000))
    {
	/* Capture error */
	while (1);
    }

    /* Configure the SysTick handler priority */
    NVIC_SetPriority(SysTick_IRQn, 0x0);
    // SysTick_Handler will now be called every 1 ms
}

// These interrupt handlers have to be extern C else they dont get linked in to the interrupt vectors
extern "C"
{
    // Called every 1 ms
    void SysTick_Handler(void)
    {
	systick_count++;
    }

    // Interrupt handlers for optional external GPIO interrupts
    void EXTI0_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line0) != RESET)
	{
	    if (irqlines[0].handler)
		irqlines[0].handler();
	    EXTI_ClearITPendingBit(EXTI_Line0);
	}
    }
    void EXTI1_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line1) != RESET)
	{
	    if (irqlines[1].handler)
		irqlines[1].handler();
	    EXTI_ClearITPendingBit(EXTI_Line1);
	}
    }
    void EXTI2_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line2) != RESET)
	{
	    if (irqlines[2].handler)
		irqlines[2].handler();
	    EXTI_ClearITPendingBit(EXTI_Line2);
	}
    }
    void EXTI3_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line3) != RESET)
	{
	    if (irqlines[3].handler)
		irqlines[3].handler();
	    EXTI_ClearITPendingBit(EXTI_Line3);
	}
    }
    void EXTI4_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line4) != RESET)
	{
	    if (irqlines[4].handler)
		irqlines[4].handler();
	    EXTI_ClearITPendingBit(EXTI_Line4);
	}
    }
    void EXTI9_5_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line5) != RESET)
	{
	    if (irqlines[5].handler)
		irqlines[5].handler();
	    EXTI_ClearITPendingBit(EXTI_Line5);
	}
	if (EXTI_GetITStatus(EXTI_Line6) != RESET)
	{
	    if (irqlines[6].handler)
		irqlines[6].handler();
	    EXTI_ClearITPendingBit(EXTI_Line6);
	}
	if (EXTI_GetITStatus(EXTI_Line7) != RESET)
	{
	    if (irqlines[7].handler)
		irqlines[7].handler();
	    EXTI_ClearITPendingBit(EXTI_Line7);
	}
	if (EXTI_GetITStatus(EXTI_Line8) != RESET)
	{
	    if (irqlines[8].handler)
		irqlines[8].handler();
	    EXTI_ClearITPendingBit(EXTI_Line8);
	}
	if (EXTI_GetITStatus(EXTI_Line9) != RESET)
	{
	    if (irqlines[9].handler)
		irqlines[9].handler();
	    EXTI_ClearITPendingBit(EXTI_Line9);
	}
    }
    void EXTI15_10_IRQHandler(void)
    {
	if (EXTI_GetITStatus(EXTI_Line10) != RESET)
	{
	    if (irqlines[10].handler)
		irqlines[10].handler();
	    EXTI_ClearITPendingBit(EXTI_Line10);
	}
	if (EXTI_GetITStatus(EXTI_Line11) != RESET)
	{
	    if (irqlines[11].handler)
		irqlines[11].handler();
	    EXTI_ClearITPendingBit(EXTI_Line11);
	}
	if (EXTI_GetITStatus(EXTI_Line12) != RESET)
	{
	    if (irqlines[12].handler)
		irqlines[12].handler();
	    EXTI_ClearITPendingBit(EXTI_Line12);
	}
	if (EXTI_GetITStatus(EXTI_Line13) != RESET)
	{
	    if (irqlines[13].handler)
		irqlines[13].handler();
	    EXTI_ClearITPendingBit(EXTI_Line13);
	}
	if (EXTI_GetITStatus(EXTI_Line14) != RESET)
	{
	    if (irqlines[14].handler)
		irqlines[14].handler();
	    EXTI_ClearITPendingBit(EXTI_Line14);
	}
	if (EXTI_GetITStatus(EXTI_Line15) != RESET)
	{
	    if (irqlines[15].handler)
		irqlines[15].handler();
	    EXTI_ClearITPendingBit(EXTI_Line15);
	}
    }
}

// The sketch we want to run
//#include "examples/rf22/rf22_client/rf22_client.pde"

// Run the Arduino standard functions in the main loop
int main(int argc, char** argv)
{
    SysTickConfig();
    // Seed the random number generator
//    srand(getpid() ^ (unsigned) time(NULL)/2);
    setup();
    while (1)
	loop();
}

void pinMode(uint8_t pin, WiringPinMode mode)
{
    if (pin > NUM_PINS)
	return;
    // Enable the GPIO clock
    RCC_AHB1PeriphClockCmd(pins[pin].ahbperiph, ENABLE);
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = pins[pin].pin;
    if (mode == INPUT)
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; // REVISIT
    else if (mode == OUTPUT)
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; // REVISIT
    else
	return; // Unknown so far
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(pins[pin].port, &GPIO_InitStructure);
}

// This takes about 150ns on STM32F4 Discovery
void digitalWrite(uint8_t pin, uint8_t val)
{
    if (pin > NUM_PINS)
	return;
    if (val)
	GPIO_SetBits(pins[pin].port, pins[pin].pin);
    else
	GPIO_ResetBits(pins[pin].port, pins[pin].pin);
}

uint8_t digitalRead(uint8_t pin)
{
    if (pin > NUM_PINS)
	return 0;
    return GPIO_ReadInputDataBit(pins[pin].port, pins[pin].pin);
}

void attachInterrupt(uint8_t pin, void (*handler)(void), int mode)
{
    EXTI_InitTypeDef EXTI_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    // Record the handler to call when the interrupt occurs
    irqlines[pins[pin].extipinsource].handler = handler;

    /* Connect EXTI Line to GPIO Pin */
    SYSCFG_EXTILineConfig(pins[pin].extiportsource, pins[pin].extipinsource);

    /* Configure EXTI line */
    EXTI_InitStructure.EXTI_Line = irqlines[pins[pin].extipinsource].extiline;

    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    if (mode == RISING)
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
    else if (mode == FALLING)
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    else if (mode == CHANGE)
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    /* Enable and set EXTI Interrupt to the lowest priority */
    NVIC_InitStructure.NVIC_IRQChannel = irqlines[pins[pin].extipinsource].extiirqn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

    NVIC_Init(&NVIC_InitStructure);

    // The relevant EXTI?_IRQHandler
    // will now be called when the pin makes the selected transition
}

void delay(unsigned long ms)
{
    unsigned long start = millis();

    while (millis() - start < ms)
	;
}

unsigned long millis()
{
    return systick_count;
}

long random(long from, long to)
{
    return from + (RNG_GetRandomNumber() % (to - from));
}

long random(long to)
{
    return random(0, to);
}

extern "C"
{
    // These need to be in C land for correct linking
    void _init() {}
    void _fini() {}
}


text:
package org.apache.activemq.usecases;

import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualDestination;
import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualTopic;
import org.apache.activemq.leveldb.LevelDBStore;
import org.apache.activemq.store.kahadb.KahaDBStore;
import org.apache.activemq.util.MessageIdList;

import javax.jms.MessageConsumer;
import java.io.File;
import java.io.IOException;
import java.net.URI;

public class SingleBrokerVirtualDestinationsWithWildcardLevelDBTest extends SingleBrokerVirtualDestinationsWithWildcardTest {

   @Override
   protected void configurePersistenceAdapter(BrokerService broker) throws IOException {
      File dataFileDir = new File("target/test-amq-data/leveldb/" + broker.getBrokerName());
      LevelDBStore kaha = new LevelDBStore();
      kaha.setDirectory(dataFileDir);
      broker.setPersistenceAdapter(kaha);
   }

}

redpajama_set_name: RedPajamaGithub


text:
static int64_t chpl_capPrivateObjects = 0;
static chpl_sync_aux_t privatizationSync;

void** chpl_privateObjects;

void chpl_privatization_init(void) {
    chpl_sync_initAux(&privatizationSync);
}

void chpl_newPrivatizedClass(void* v, int64_t pid) {
  // We need to lock around this operation so two calls in rapid succession
  // that pass the chpl_capPrivateObjects limit don't both try to create a new
  // array. If they do, one of the calls will be leaked and an invalid pointer
  // to be placed in the table.
  chpl_sync_lock(&privatizationSync);

  pid += 1;
  if (pid == 1) {
    chpl_capPrivateObjects = 8;
    // "private" means "node-private", so we can use the system allocator.
    chpl_privateObjects = chpl_mem_allocMany(chpl_capPrivateObjects, sizeof(void*), CHPL_RT_MD_COMM_PRIVATE_OBJECTS_ARRAY, 0, "");
  } else {
    if (pid > chpl_capPrivateObjects) {
      void** tmp;
      chpl_capPrivateObjects *= 2;
      tmp = chpl_mem_allocMany(chpl_capPrivateObjects, sizeof(void*), CHPL_RT_MD_COMM_PRIVATE_OBJECTS_ARRAY, 0, "");
      memcpy((void*)tmp, (void*)chpl_privateObjects, (pid-1)*sizeof(void*));
      chpl_privateObjects = tmp;
      // purposely leak old copies of chpl_privateObject to avoid the need to
      // lock chpl_getPrivatizedClass; TODO: fix with lock free data structure
    }
  }
  chpl_privateObjects[pid-1] = v;

  chpl_sync_unlock(&privatizationSync);
}

extern void* chpl_getPrivatizedClass(int64_t i) {
  return chpl_privateObjects[i];
}


text:
package org.jetbrains.plugins.scala.codeInspection.declarationRedundancy.negative

import org.jetbrains.plugins.scala.codeInspection.{ScalaAnnotatorQuickFixTestBase, ScalaInspectionBundle}
import org.jetbrains.plugins.scala.codeInspection.declarationRedundancy.ScalaAccessCanBeTightenedInspection

final class AccessCanBePrivateInspectionTest extends ScalaAnnotatorQuickFixTestBase {
  override protected val description = ScalaInspectionBundle.message("access.can.be.private")

  override def setUp(): Unit = {
    super.setUp()
    myFixture.enableInspections(classOf[ScalaAccessCanBeTightenedInspection])
  }

  def test_val(): Unit =
    checkTextHasNoErrors("private class A { val foo = 42 }; private class B { new A().foo }")

  def test_var(): Unit =
    checkTextHasNoErrors("private class A { var foo = 42 }; private class B { new A().foo }")

  def test_method(): Unit =
    checkTextHasNoErrors("private class A { def foo = {} }; private class B { new A().foo }")

  def test_class_used_by_public_class_in_other_file(): Unit = {
    val file = myFixture.addFileToProject("B.scala", "class B extends A")
    myFixture.openFileInEditor(file.getVirtualFile)
    val code = "class A"
    checkTextHasNoErrors(code)
  }

  def test_trait_used_by_public_class_in_other_file(): Unit = {
    val file = myFixture.addFileToProject("B.scala", "class B extends A")
    myFixture.openFileInEditor(file.getVirtualFile)
    val code = "trait A"
    checkTextHasNoErrors(code)
  }

  def test_object_used_by_public_class_in_other_file(): Unit = {
    val file = myFixture.addFileToProject("B.scala", "class B { A }")
    myFixture.openFileInEditor(file.getVirtualFile)
    val code = "object A"
    checkTextHasNoErrors(code)
  }

  def test_declaration_that_is_used_both_in_local_and_nonlocal_scope(): Unit = {
    val file = myFixture.addFileToProject("B.scala", "class B extends A { foo() }")
    myFixture.openFileInEditor(file.getVirtualFile)
    val code = "class A { def foo() = { foo() } }"
    checkTextHasNoErrors(code)
  }

  def test_local_method_members_are_skipped(): Unit =
    checkTextHasNoErrors("private class A { private def foo() = { def bar() = {} } }")

  def test_local_var_val_members_are_skipped(): Unit =
    checkTextHasNoErrors("private class A { private def foo() = { var x = 42; val y = 42; } }")

  def test_unused_declarations_are_skipped(): Unit =
    checkTextHasNoErrors("private class A { def foo() = {} }")

  def test_prevent_leaking_via_val(): Unit =
    checkTextHasNoErrors("object A { class B; val c: B = ??? }")

  def test_prevent_leaking_via_var(): Unit =
    checkTextHasNoErrors("object A { class B; var c: B = ??? }")

  def test_prevent_leaking_via_def_return_type(): Unit =
    checkTextHasNoErrors("object A { class B; def c: B = ??? }")

  def test_prevent_leaking_via_nested_def_return_type1(): Unit =
    checkTextHasNoErrors("object A { class B; def c: Option[B] = ??? }")

  def test_prevent_leaking_via_nested_def_return_type2(): Unit =
    checkTextHasNoErrors("object A { class B; def c: Option[Seq[B]] = ??? }")

  def test_prevent_leaking_via_nested_def_return_type3(): Unit =
    checkTextHasNoErrors("object A { class B; def c: Either[B, String] = ??? }")

  def test_prevent_leaking_via_package_qualified_private_def_return_type(): Unit =
    checkTextHasNoErrors("package a; object A { class B; private[a] def c: B = ??? }")

  def test_prevent_leaking_via_def_param(): Unit =
    checkTextHasNoErrors("object A { class B; def foo(b: B) = () }")

  def test_prevent_leaking_via_nested_def_param1(): Unit =
    checkTextHasNoErrors("object A { class B; def c(d: Option[B]) = () }")

  def test_prevent_leaking_via_nested_def_param2(): Unit =
    checkTextHasNoErrors("object A { class B; def c(d: Option[Seq[B]]) = () }")

  def test_prevent_leaking_via_nested_def_param3(): Unit =
    checkTextHasNoErrors("object A { class B; def c(d: Either[B, String]) = () }")

  def test_prevent_leaking_via_def_type_param(): Unit =
    checkTextHasNoErrors("object A { class B; def foo[T <: B]() = () }")

  def test_prevent_leaking_via_inheritance(): Unit =
    checkTextHasNoErrors("object A { class B; class C extends B }")

  def test_member_of_local_class(): Unit =
    checkTextHasNoErrors("object A { def foo = { class B { val bar = 42; println(bar) } } }")

  def test_member_of_a_surprisingly_nested_local_class(): Unit =
    checkTextHasNoErrors("class A { def foo = { class B { class C { class D { def bar = {}; bar } } } } }")
}


text:
package cn.teaey.apns4j.network;

import cn.teaey.apns4j.ApnsException;
import cn.teaey.apns4j.keystore.InvalidKeyStoreException;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

//import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * @author teaey
 * @since 1.0.0
 */
public final class SecuritySocketFactory {
    /* The algorithm used by KeyManagerFactory */
    private static final String ALGORITHM = ((Security.getProperty("ssl.KeyManagerFactory.algorithm") == null) ? "sunx509" : Security.getProperty("ssl.KeyManagerFactory.algorithm"));
    /* The protocol used to create the SSLSocket */
    private static final String PROTOCOL = "TLS";
    //    static
    //    {
    //        Security.addProvider(new BouncyCastleProvider());
    //    }
    private final String host;
    private final int port;
    private final KeyStore keyStore;
    private final String keyStorePwd;
    private final SSLSocketFactory sslSocketFactory;
    private final TrustManager[] trustManagers = new TrustManager[]{new ServerTrustingTrustManager()};

    public SecuritySocketFactory(String host, int port, KeyStore keyStore, String keyStorePwd) {
        if (host == null) {
            throw new NullPointerException("host");
        }
        if (keyStore == null) {
            throw new NullPointerException("keystore");
        }
        if (keyStorePwd == null) {
            throw new NullPointerException("keyStorePwd");
        }
        this.host = host;
        this.port = port;
        this.keyStore = keyStore;
        this.keyStorePwd = keyStorePwd;
        this.sslSocketFactory = createSSLSocketFactoryWithTrustManagers(trustManagers);
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public KeyStore getKeyStore() {
        return keyStore;
    }

    public String getKeyStorePwd() {
        return keyStorePwd;
    }

    public SSLSocketFactory getSslSocketFactory() {
        return sslSocketFactory;
    }

    public TrustManager[] getTrustManagers() {
        return trustManagers;
    }

    /**
     *
createSSLSocketFactoryWithTrustManagers.

     *
     * @param trustManagers an array of {@link javax.net.ssl.TrustManager} objects.
     * @return a {@link javax.net.ssl.SSLSocketFactory} object.
     */
    protected SSLSocketFactory createSSLSocketFactoryWithTrustManagers(TrustManager[] trustManagers) {
        // Get a KeyManager and initialize it
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
            kmf.init(keyStore, keyStorePwd.toCharArray());
            // Get the SSLContext to help create SSLSocketFactory
            SSLContext sslc = SSLContext.getInstance(PROTOCOL);
            sslc.init(kmf.getKeyManagers(), trustManagers, null);
            return sslc.getSocketFactory();
        } catch (Exception e) {
            throw new ApnsException(new InvalidKeyStoreException(e));
        }
    }

    /**
     * Create a SSLSocket which will be used to send data to Apple
     *
     * @return the SSLSocket
     */
    public SSLSocket createSocket() throws IOException {
        return (SSLSocket) sslSocketFactory.createSocket(host, port);
    }

    private class ServerTrustingTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new CertificateException("not trusted");
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) {
            // trust all servers
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}


text:
    public String longestCommonPrefix(String[] strs) {
        // Corner case
        if(strs.length < 1){
            return "";
        }

        // Looping through all the elements
        String pre = strs[0];
        StringBuilder out = new StringBuilder();
        int min = Integer.MAX_VALUE;
        for(String str : strs){
            min = Math.min(min,str.length());
        }

        for(int i = 0; i < min; i++){
            char s = pre.charAt(i);
            for(int j = 1; j < strs.length; j++){
                if(strs[j].charAt(i) != s){
                    return out.toString();
                }
            }
            out.append(s);
        }
        return out.toString();
    }


text:
layout: page
title: Kennedy - Little Wedding
date: 2016-05-24
author: Donna Olsen
tags: weekly links, java
status: published
summary: In quis blandit dui. Vivamus.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/03/2017
  endDate: 06/06/2017
  ctyhocn: IJXILHX
  groupCode: KLW
published: true
---
Sed et justo at justo pharetra mollis. Praesent ac vulputate est. Curabitur sollicitudin eleifend fermentum. Aliquam quis tincidunt lorem. Morbi sed consequat metus. Sed quis venenatis lorem. Pellentesque eleifend quis felis venenatis cursus.

* Proin eget massa placerat turpis commodo condimentum
* Phasellus quis magna sit amet justo fringilla condimentum auctor eu nisi.

Maecenas sem lacus, vulputate eu malesuada id, convallis id enim. Proin sed erat risus. Aenean varius suscipit facilisis. Vivamus ut congue quam, quis porta lorem. Aliquam ornare leo aliquet erat tincidunt, id rhoncus arcu ultrices. Cras tristique tortor turpis, consequat elementum mi rutrum ut. Fusce eu leo a urna facilisis pellentesque in sed sapien. Nunc ornare erat quis sagittis pretium. Nulla quis nisl eget diam sodales tristique nec id justo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam rhoncus venenatis euismod. Mauris non leo in nulla dapibus facilisis eget non enim.
Integer ac sapien vitae ex dapibus ullamcorper vitae ut elit. Quisque in tincidunt purus. Aliquam non mauris sit amet lectus gravida tristique. Mauris dignissim ante quis augue tempor, ut laoreet eros lobortis. Sed posuere nulla nec tellus cursus, at tempus turpis gravida. Cras nec finibus dolor. Phasellus a orci porttitor purus lobortis luctus. Morbi sollicitudin lorem felis, sed imperdiet ligula pretium ut. Donec laoreet nunc quis nibh tempor dapibus. Morbi a imperdiet dui. Vivamus volutpat consequat quam vel dignissim. Vestibulum vehicula fermentum massa id gravida. Donec vitae mollis sapien. Proin fermentum vitae nisi sit amet facilisis. Suspendisse commodo elementum diam id tincidunt.


text:
using KaVE.Commons.Model.Naming.CodeElements;
using KaVE.Commons.Model.SSTs.References;
using KaVE.Commons.Utils.Collections;
using KaVE.JetBrains.Annotations;

namespace KaVE.Commons.Model.SSTs.Expressions.Assignable
{
    public interface IInvocationExpression : IAssignableExpression
    {
        [NotNull]
        IVariableReference Reference { get; }

        [NotNull]
        IMethodName MethodName { get; }

        [NotNull]
        IKaVEList<ISimpleExpression> Parameters { get; }
    }
}


text:
/*
 * GIC-600 driver extension for multichip setup
 */

#include <assert.h>

#include <common/debug.h>
#include <drivers/arm/arm_gicv3_common.h>
#include <drivers/arm/gic600_multichip.h>
#include <drivers/arm/gicv3.h>

#include "../common/gic_common_private.h"
#include "gic600_multichip_private.h"

/*******************************************************************************
 * GIC-600 multichip operation related helper functions
 ******************************************************************************/
static void gicd_dchipr_wait_for_power_update_progress(uintptr_t base)
{
	unsigned int retry = GICD_PUP_UPDATE_RETRIES;

	while ((read_gicd_dchipr(base) & GICD_DCHIPR_PUP_BIT) != 0U) {
		if (retry-- == 0) {
			ERROR("GIC-600 connection to Routing Table Owner timed "
					 "out\n");
			panic();
		}
	}
}

/*******************************************************************************
 * Sets up the routing table owner.
 ******************************************************************************/
static void set_gicd_dchipr_rt_owner(uintptr_t base, unsigned int rt_owner)
{
	/*
	 * Ensure that Group enables in GICD_CTLR are disabled and no pending
	 * register writes to GICD_CTLR.
	 */
	if ((gicd_read_ctlr(base) &
			(CTLR_ENABLE_G0_BIT | CTLR_ENABLE_G1S_BIT |
			 CTLR_ENABLE_G1NS_BIT | GICD_CTLR_RWP_BIT)) != 0) {
		ERROR("GICD_CTLR group interrupts are either enabled or have "
				"pending writes. Cannot set RT owner.\n");
		panic();
	}

	/* Poll till PUP is zero before intiating write */
	gicd_dchipr_wait_for_power_update_progress(base);

	write_gicd_dchipr(base, read_gicd_dchipr(base) |
			(rt_owner << GICD_DCHIPR_RT_OWNER_SHIFT));

	/* Poll till PUP is zero to ensure write is complete */
	gicd_dchipr_wait_for_power_update_progress(base);
}

/*******************************************************************************
 * Configures the Chip Register to make connections to GICDs on
 * a multichip platform.
 ******************************************************************************/
static void set_gicd_chipr_n(uintptr_t base,
				unsigned int chip_id,
				uint64_t chip_addr,
				unsigned int spi_id_min,
				unsigned int spi_id_max)
{
	unsigned int spi_block_min, spi_blocks;
	unsigned int gicd_iidr_val = gicd_read_iidr(base);
	uint64_t chipr_n_val;

	/*
	 * Ensure that group enables in GICD_CTLR are disabled and no pending
	 * register writes to GICD_CTLR.
	 */
	if ((gicd_read_ctlr(base) &
			(CTLR_ENABLE_G0_BIT | CTLR_ENABLE_G1S_BIT |
			 CTLR_ENABLE_G1NS_BIT | GICD_CTLR_RWP_BIT)) != 0) {
		ERROR("GICD_CTLR group interrupts are either enabled or have "
				"pending writes. Cannot set CHIPR register.\n");
		panic();
	}

	/*
	 * spi_id_min and spi_id_max of value 0 is used to intidicate that the
	 * chip doesn't own any SPI block. Re-assign min and max values as SPI
	 * id starts from 32.
	 */
	if (spi_id_min == 0 && spi_id_max == 0) {
		spi_id_min = GIC600_SPI_ID_MIN;
		spi_id_max = GIC600_SPI_ID_MIN;
	}

	spi_block_min = SPI_BLOCK_MIN_VALUE(spi_id_min);
	spi_blocks    = SPI_BLOCKS_VALUE(spi_id_min, spi_id_max);

	switch ((gicd_iidr_val & IIDR_MODEL_MASK)) {
	case IIDR_MODEL_ARM_GIC_600:
		chipr_n_val = GICD_CHIPR_VALUE_GIC_600(chip_addr,
						       spi_block_min,
						       spi_blocks);
		break;
	case IIDR_MODEL_ARM_GIC_700:
		chipr_n_val = GICD_CHIPR_VALUE_GIC_700(chip_addr,
						       spi_block_min,
						       spi_blocks);
		break;
	default:
		ERROR("Unsupported GIC model 0x%x for multichip setup.\n",
		      gicd_iidr_val);
		panic();
		break;
	}
	chipr_n_val |= GICD_CHIPRx_SOCKET_STATE;

	/*
	 * Wait for DCHIPR.PUP to be zero before commencing writes to
	 * GICD_CHIPRx.
	 */
	gicd_dchipr_wait_for_power_update_progress(base);

	/*
	 * Assign chip addr, spi min block, number of spi blocks and bring chip
	 * online by setting SocketState.
	 */
	write_gicd_chipr_n(base, chip_id, chipr_n_val);

	/*
	 * Poll until DCHIP.PUP is zero to verify connection to rt_owner chip
	 * is complete.
	 */
	gicd_dchipr_wait_for_power_update_progress(base);

	/*
	 * Ensure that write to GICD_CHIPRx is successful and the chip_n came
	 * online.
	 */
	if (read_gicd_chipr_n(base, chip_id) != chipr_n_val) {
		ERROR("GICD_CHIPR%u write failed\n", chip_id);
		panic();
	}

	/* Ensure that chip is in consistent state */
	if (((read_gicd_chipsr(base) & GICD_CHIPSR_RTS_MASK) >>
				GICD_CHIPSR_RTS_SHIFT) !=
			GICD_CHIPSR_RTS_STATE_CONSISTENT) {
		ERROR("Chip %u routing table is not in consistent state\n",
				chip_id);
		panic();
	}
}

/*******************************************************************************
 * Validates the GIC-600 Multichip data structure passed by the platform.
 ******************************************************************************/
static void gic600_multichip_validate_data(
		struct gic600_multichip_data *multichip_data)
{
	unsigned int i, spi_id_min, spi_id_max, blocks_of_32;
	unsigned int multichip_spi_blocks = 0;

	assert(multichip_data != NULL);

	if (multichip_data->chip_count > GIC600_MAX_MULTICHIP) {
		ERROR("GIC-600 Multichip count should not exceed %d\n",
				GIC600_MAX_MULTICHIP);
		panic();
	}

	for (i = 0; i < multichip_data->chip_count; i++) {
		spi_id_min = multichip_data->spi_ids[i][SPI_MIN_INDEX];
		spi_id_max = multichip_data->spi_ids[i][SPI_MAX_INDEX];

		if ((spi_id_min != 0) || (spi_id_max != 0)) {

			/* SPI IDs range check */
			if (!(spi_id_min >= GIC600_SPI_ID_MIN) ||
			    !(spi_id_max < GIC600_SPI_ID_MAX) ||
			    !(spi_id_min <= spi_id_max) ||
			    !((spi_id_max - spi_id_min + 1) % 32 == 0)) {
				ERROR("Invalid SPI IDs {%u, %u} passed for "
						"Chip %u\n", spi_id_min,
						spi_id_max, i);
				panic();
			}

			/* SPI IDs overlap check */
			blocks_of_32 = BLOCKS_OF_32(spi_id_min, spi_id_max);
			if ((multichip_spi_blocks & blocks_of_32) != 0) {
				ERROR("SPI IDs of Chip %u overlapping\n", i);
				panic();
			}
			multichip_spi_blocks |= blocks_of_32;
		}
	}
}

/*******************************************************************************
 * Intialize GIC-600 Multichip operation.
 ******************************************************************************/
void gic600_multichip_init(struct gic600_multichip_data *multichip_data)
{
	unsigned int i;

	gic600_multichip_validate_data(multichip_data);

	/*
	 * Ensure that G0/G1S/G1NS interrupts are disabled. This also ensures
	 * that GIC-600 Multichip configuration is done first.
	 */
	if ((gicd_read_ctlr(multichip_data->rt_owner_base) &
			(CTLR_ENABLE_G0_BIT | CTLR_ENABLE_G1S_BIT |
			 CTLR_ENABLE_G1NS_BIT | GICD_CTLR_RWP_BIT)) != 0) {
		ERROR("GICD_CTLR group interrupts are either enabled or have "
				"pending writes.\n");
		panic();
	}

	/* Ensure that the routing table owner is in disconnected state */
	if (((read_gicd_chipsr(multichip_data->rt_owner_base) &
		GICD_CHIPSR_RTS_MASK) >> GICD_CHIPSR_RTS_SHIFT) !=
			GICD_CHIPSR_RTS_STATE_DISCONNECTED) {
		ERROR("GIC-600 routing table owner is not in disconnected "
				"state to begin multichip configuration\n");
		panic();
	}

	/* Initialize the GICD which is marked as routing table owner first */
	set_gicd_dchipr_rt_owner(multichip_data->rt_owner_base,
			multichip_data->rt_owner);

	set_gicd_chipr_n(multichip_data->rt_owner_base, multichip_data->rt_owner,
			multichip_data->chip_addrs[multichip_data->rt_owner],
			multichip_data->
			spi_ids[multichip_data->rt_owner][SPI_MIN_INDEX],
			multichip_data->
			spi_ids[multichip_data->rt_owner][SPI_MAX_INDEX]);

	for (i = 0; i < multichip_data->chip_count; i++) {
		if (i == multichip_data->rt_owner)
			continue;

		set_gicd_chipr_n(multichip_data->rt_owner_base, i,
				multichip_data->chip_addrs[i],
				multichip_data->spi_ids[i][SPI_MIN_INDEX],
				multichip_data->spi_ids[i][SPI_MAX_INDEX]);
	}
}


text:
#include "control.h"
#include "controlparse.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>

static int parse_deplist(struct controlparse_field *pf,
        struct control_dependency **pcd);
static int parse_builtfromlist(struct controlparse_field *pf,
        struct control_built_from **bfs);
static int parse_sourcelist(struct controlparse_field *pf,
        struct control_source **pcs);
static int parse_source(struct controlparse_field *pf, char **pn, char **pv);
static int parse_singleline(struct controlparse_field *pf, char **ps);

int control_parse(const char *path, struct control **ctrl)
{
    int fd, ret;

    if ((fd = open(path, O_RDONLY)) < 0) {
        perror("control_parse: open failed");
        return -1;
    }

    ret = control_parsefd(fd, ctrl);
    close(fd);
    return ret;
}

int control_parsefd(int fd, struct control **ctrl)
{
    struct control *c;
    struct controlparse cp;
    struct controlparse_para *pp;
    struct controlparse_field *pf;

    if (controlparse_init(&cp))
        return -1;
    if (controlparse_parsefd(&cp, fd))
        goto out_err;

    if ((c = calloc(1, sizeof(*c))) == NULL) {
        perror("control_parsefd: malloc failed");
        goto out_err;
    }
    *ctrl = c;

    pp = cp.para_first;
    if (pp == NULL || pp->next != NULL) {
        fprintf(stderr, "control_parsefd: file must have exactly one "
                "paragraph\n");
        goto out_malloc;
    }

    for (pf = pp->field_first; pf != NULL; pf = pf->next) {
        if (!strcmp(pf->name, "Depends-Run")) {
            /* parse run-time dependencies */
            if (parse_deplist(pf, &c->run_depend) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Built-From")) {
            /* parse built-from list */
            if (parse_builtfromlist(pf, &c->built_froms) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Package")) {
            if (parse_singleline(pf, &c->package) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Version")) {
            if (parse_singleline(pf, &c->version) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Source")) {
            if (parse_source(pf, &c->src_package, &c->src_version) != 0)
                goto out_malloc;
        } else {
            fprintf(stderr, "control_parsefd: Unexpected field: '%s'\n",
                pf->name);
            goto out_malloc;
        }
    }

    controlparse_destroy(&cp);
    return 0;

out_malloc:
    control_destroy(c);
out_err:
    controlparse_destroy(&cp);
    return -1;
}

void control_destroy(struct control *ctrl)
{
    struct control_dependency *cd, *cdd;
    struct control_built_from *cbf, *cbff;

    for (cd = ctrl->run_depend; cd != NULL; ) {
        cdd = cd;
        cd = cd->next;
        free(cdd->package);
        free(cdd);
    }
    for (cbf = ctrl->built_froms; cbf != NULL; ) {
        cbff = cbf;
        cbf = cbf->next;
        free(cbff->package);
        free(cbff->version);
        free(cbff);
    }

    free(ctrl->package);
    free(ctrl->version);
    free(ctrl->src_package);
    free(ctrl->src_version);
    free(ctrl);
}

int source_control_parsefd(int fd, struct source_control **sc)
{
    struct source_control *c;
    struct source_control_bin *cb, *cbb;
    struct control_dependency *run_deps = NULL, *rd, *cd, *cdd;
    struct controlparse cp;
    struct controlparse_para *pp;
    struct controlparse_field *pf;

    if (controlparse_init(&cp))
        return -1;
    if (controlparse_parsefd(&cp, fd))
        goto out_err;

    if ((c = calloc(1, sizeof(*c))) == NULL) {
        perror("source_control_parsefd: malloc failed");
        goto out_err;
    }
    *sc = c;

    pp = cp.para_first;
    if (pp == NULL) {
        fprintf(stderr, "source_control_parsefd: file must have at least "
                "one paragraph\n");
        goto out_malloc;
    }

    /* parse first paragraph */
    for (pf = pp->field_first; pf != NULL; pf = pf->next) {
        if (!strcmp(pf->name, "Depends-Build")) {
            if (parse_deplist(pf, &c->build_depend) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Depends-Unpack")) {
            if (parse_deplist(pf, &c->unpack_depend) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Depends-Run")) {
            if (parse_deplist(pf, &run_deps) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Sources")) {
            if (parse_sourcelist(pf, &c->sources) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Source")) {
            if (parse_singleline(pf, &c->source) != 0)
                goto out_malloc;
        } else if (!strcmp(pf->name, "Version")) {
            if (parse_singleline(pf, &c->version) != 0)
                goto out_malloc;
        } else {
            fprintf(stderr, "source_control_parsefd: Unexpected field: '%s'\n",
                pf->name);
            goto out_malloc;
        }
    }

    /* parse additional binary packet paragraph */
    for (pp = pp->next; pp != NULL; pp = pp->next) {
        /* add source control bin struct to list */
        if ((cb = calloc(1, sizeof(*cb))) == NULL) {
            perror("source_control_parsefd: malloc failed");
            goto out_malloc;
        }
        if (c->bins == NULL) {
            c->bins = cb;
        } else {
            for (cbb = c->bins; cbb->next != NULL; cbb = cbb->next);
            cbb->next = cb;
        }

        for (pf = pp->field_first; pf != NULL; pf = pf->next) {
            if (!strcmp(pf->name, "Depends-Run")) {
                if (parse_deplist(pf, &cb->run_depend) != 0)
                    goto out_malloc;
            } else if (!strcmp(pf->name, "Package")) {
                if (parse_singleline(pf, &cb->package) != 0)
                    goto out_malloc;
            } else {
                fprintf(stderr, "source_control_parsefd: Unexpected field: "
                    "'%s'\n", pf->name);
                goto out_malloc;
            }
        }

        /* copy global run dependencies */
        for (cdd = cb->run_depend; cdd != NULL && cdd->next != NULL;
            cdd = cdd->next);
        for (rd = run_deps; rd != NULL; rd = rd->next) {
            if ((cd = calloc(1, sizeof(*cd))) == NULL ||
                (cd->package = strdup(rd->package)) == NULL)
            {
                free(cd);
                perror("source_control_parsefd: malloc failed");
                goto out_malloc;
            }

            /* append to list of already existing dependencies */
            if (cdd == NULL) {
                cb->run_depend = cd;
                cdd = cd;
            } else {
                cdd->next = cd;
                cdd = cd;
            }
        }
    }

    controlparse_destroy(&cp);
    return 0;

out_malloc:
    source_control_destroy(c);
out_err:
    controlparse_destroy(&cp);
    return -1;

    return -1;
}

void source_control_destroy(struct source_control *sc)
{
    struct control_dependency *cd, *cdd;
    struct control_source *cs, *css;
    struct source_control_bin *sb, *sbb;

    for (cd = sc->build_depend; cd != NULL; ) {
        cdd = cd;
        cd = cd->next;
        free(cdd->package);
        free(cdd);
    }
    for (cs = sc->sources; cs != NULL; ) {
        css = cs;
        cs = cs->next;
        free(css->source);
        free(css);
    }
    for (sb = sc->bins; sb != NULL; ) {
        sbb = sb;
        sb = sb->next;

        for (cd = sbb->run_depend; cd != NULL; ) {
            cdd = cd;
            cd = cd->next;
            free(cdd->package);
            free(cdd);
        }

        free(sbb->package);
        free(sbb);
    }

    free(sc->source);
    free(sc->version);
    free(sc);
}

static int parse_deplist(struct controlparse_field *pf,
        struct control_dependency **pcd)
{
    struct control_dependency *cd, *cdd;
    struct controlparse_line *pl;

    if (*pcd != NULL) {
        fprintf(stderr, "parse_deplist: %s set repeatedly\n", pf->name);
        return -1;
    }

    /* parse run-time and build-time dependencies */
    for (pl = pf->line_first; pl != NULL; pl = pl->next) {
        if (!*pl->line)
            continue;

        /* allocate dependency struct */
        if ((cd = malloc(sizeof(*cd))) == NULL ||
            (cd->package = strdup(pl->line)) == NULL)
        {
            free(cd);
            perror("parse_deplist: malloc source failed");
            return -1;
        }

        /* add to deps linked list */
        cd->next = NULL;
        if (*pcd == NULL) {
            *pcd = cd;
        } else {
            for (cdd = *pcd; cdd->next != NULL; cdd = cdd->next);
            cdd->next = cd;
        }
    }

    return 0;
}

static int parse_builtfromlist(struct controlparse_field *pf,
        struct control_built_from **pbf)
{
    struct control_built_from *bf, *bff;
    struct controlparse_line *pl;
    char *space;

    if (*pbf != NULL) {
        fprintf(stderr, "parse_builtfromlist: %s set repeatedly\n", pf->name);
        return -1;
    }

    /* parse run-time and build-time dependencies */
    for (pl = pf->line_first; pl != NULL; pl = pl->next) {
        if (!*pl->line)
            continue;

        /* locate space separating name and version */
        if ((space = strchr(pl->line, ' ')) == NULL) {
            perror("parse_builtfromlist: space separating name and version not"
                " found");
            return -1;
        }
        *space = 0;

        /* allocate dependency struct */
        if ((bf = calloc(1, sizeof(*bf))) == NULL) {
            perror("parse_builtfromlist: malloc struct failed");
            return -1;
        }

        /* allocate package name and version */
        if ((bf->package = strdup(pl->line)) == NULL ||
            (bf->version = strdup(space + 1)) == NULL)
        {
            free(bf->package);
            free(bf);
            perror("parse_builtfromlist: strdup fields failed");
            return -1;
        }

        /* add to deps linked list */
        bf->next = NULL;
        if (*pbf == NULL) {
            *pbf = bf;
        } else {
            for (bff = *pbf; bff->next != NULL; bff = bff->next);
            bff->next = bf;
        }
    }

    return 0;
}

static int parse_sourcelist(struct controlparse_field *pf,
        struct control_source **pcs)
{
    struct control_source *cs, *css;
    struct controlparse_line *pl;

    if (*pcs != NULL) {
        fprintf(stderr, "parse_sourcelist: %s set repeatedly\n", pf->name);
        return -1;
    }

    for (pl = pf->line_first; pl != NULL; pl = pl->next) {
        if (!*pl->line)
            continue;

        /* allocate source struct */
        if ((cs = malloc(sizeof(*cs))) == NULL ||
            (cs->source = strdup(pl->line)) == NULL)
        {
            free(cs);
            perror("parse_sourcelist: malloc source failed");
            return -1;
        }

        /* add to sources linked list */
        cs->next = NULL;
        if (*pcs == NULL) {
            *pcs = cs;
        } else {
            for (css = *pcs; css->next != NULL; css = css->next);
            css->next = cs;
        }
    }

    return 0;
}

static int parse_source(struct controlparse_field *pf, char **pn, char **pv)
{
    char *l, *space;

    if (*pn != NULL) {
        fprintf(stderr, "parse_source: %s has already been set\n", pf->name);
        return -1;
    }

    if (pf->line_first == NULL || pf->line_first->next != NULL ||
            !*pf->line_first->line)
    {
        fprintf(stderr, "parse_source: %s needs to be "
                "non-empty single line\n", pf->name);
        return -1;
    }

    l = pf->line_first->line;
    if ((space = strchr(l, ' ')) == NULL) {
        perror("parse_source: expect space separated name and version");
        return -1;
    }
    *space = 0;

    if ((*pn = strdup(l)) == NULL ||
        (*pv = strdup(space + 1)) == NULL)
    {
        free(*pn);
        perror("parse_source: strdup failed");
        return -1;
    }

    return 0;
}

static int parse_singleline(struct controlparse_field *pf, char **ps)
{
    if (*ps != NULL) {
        fprintf(stderr, "parse_singleline: %s has already been set\n",
                pf->name);
        return -1;
    }
    if (pf->line_first == NULL || pf->line_first->next != NULL ||
            !*pf->line_first->line)
    {
        fprintf(stderr, "parse_singleline: %s needs to be "
                "non-empty single line\n", pf->name);
        return -1;
    }
    if ((*ps = strdup(pf->line_first->line)) == NULL) {
        perror("parse_singleline: strdup failed");
        return -1;
    }

    return 0;
}


text:
import {Subscription} from 'rxjs/Subscription';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import {extendObject} from '../../utils/object-extend';

import {MediaChange, MediaQuerySubscriber} from '../../media-query/media-change';
import {BreakPoint} from '../../media-query/breakpoints/break-point';
import {MediaMonitor} from '../../media-query/media-monitor';

export declare type SubscriptionList = Subscription[ ];

export interface BreakPointX extends BreakPoint {
  key: string;
  baseKey: string;
}

export class KeyOptions {
  constructor(public baseKey: string,
              public defaultValue: string|number|boolean,
              public inputKeys: { [key: string]: any }) {
  }
}

/**
 * ResponsiveActivation acts as a proxy between the MonitorMedia service (which emits mediaQuery
 * changes) and the fx API directives. The MQA proxies mediaQuery change events and notifies the
 * directive via the specified callback.
 *
 * - The MQA also determines which directive property should be used to determine the
 *   current change 'value'... BEFORE the original `onMediaQueryChanges()` method is called.
 * - The `ngOnDestroy()` method is also head-hooked to enable auto-unsubscribe from the
 *   MediaQueryServices.
 *
 * NOTE: these interceptions enables the logic in the fx API directives to remain terse and clean.
 */
export class ResponsiveActivation {
  private _subscribers: SubscriptionList = [];
  private _activatedInputKey: string;

  /**
   * Constructor
   */
  constructor(private _options: KeyOptions,
              private _mediaMonitor: MediaMonitor,
              private _onMediaChanges: MediaQuerySubscriber) {
    this._subscribers = this._configureChangeObservers();
  }

  /**
   * Accessor to the DI'ed directive property
   * Each directive instance has a reference to the MediaMonitor which is
   * used HERE to subscribe to mediaQuery change notifications.
   */
  get mediaMonitor(): MediaMonitor {
    return this._mediaMonitor;
  }

  /**
   * Determine which directive @Input() property is currently active (for the viewport size):
   * The key must be defined (in use) or fallback to the 'closest' overlapping property key
   * that is defined; otherwise the default property key will be used.
   * e.g.
   *      if `<div fxHide fxHide.gt-sm="false">` is used but the current activated mediaQuery alias
   *      key is `.md` then `.gt-sm` should be used instead
   */
  get activatedInputKey(): string {
    return this._activatedInputKey || this._options.baseKey;
  }

  /**
   * Get the currently activated @Input value or the fallback default @Input value
   */
  get activatedInput(): any {
    let key = this.activatedInputKey;
    return this.hasKeyValue(key) ? this._lookupKeyValue(key) : this._options.defaultValue;
  }

  /**
   * Fast validator for presence of attribute on the host element
   */
  public hasKeyValue(key) {
    let value = this._options.inputKeys[key];
    return typeof value !== 'undefined';
  }

  /**
   * Remove interceptors, restore original functions, and forward the onDestroy() call
   */
  destroy() {
    this._subscribers.forEach((link: Subscription) => {
      link.unsubscribe();
    });
    this._subscribers = [];
  }

  /**
   * For each *defined* API property, register a callback to `_onMonitorEvents( )`
   * Cache 1..n subscriptions for internal auto-unsubscribes when the the directive destructs
   */
  private _configureChangeObservers(): SubscriptionList {
    let subscriptions = [];

    this._buildRegistryMap().forEach((bp: BreakPointX) => {
      if (this._keyInUse(bp.key)) {
        // Inject directive default property key name: to let onMediaChange() calls
        // know which property is being triggered...
        let buildChanges = (change: MediaChange) => {
          change = change.clone();
          change.property = this._options.baseKey;
          return change;
        };

        subscriptions.push(
            this.mediaMonitor.observe(bp.alias)
                .map(buildChanges)
                .subscribe(change => {
                  this._onMonitorEvents(change);
                })
        );
      }
    });

    return subscriptions;
  }

  /**
   * Build mediaQuery key-hashmap; only for the directive properties that are actually defined/used
   * in the HTML markup
   */
  private _buildRegistryMap() {
    return this.mediaMonitor.breakpoints
        .map(bp => {
          return <BreakPointX> extendObject({}, bp, {
            baseKey: this._options.baseKey,             // e.g. layout, hide, self-align, flex-wrap
            key: this._options.baseKey + bp.suffix  // e.g.  layoutGtSm, layoutMd, layoutGtLg
          });
        })
        .filter(bp => this._keyInUse(bp.key));
  }

  /**
   * Synchronizes change notifications with the current mq-activated @Input and calculates the
   * mq-activated input value or the default value
   */
  protected _onMonitorEvents(change: MediaChange) {
    if (change.property == this._options.baseKey) {
      change.value = this._calculateActivatedValue(change);

      this._onMediaChanges(change);
    }
  }

  /**
   * Has the key been specified in the HTML markup and thus is intended
   * to participate in activation processes.
   */
  private _keyInUse(key): boolean {
    return this._lookupKeyValue(key) !== undefined;
  }

  /**
   *  Map input key associated with mediaQuery activation to closest defined input key
   *  then return the values associated with the targeted input property
   *
   *  !! change events may arrive out-of-order (activate before deactivate)
   *     so make sure the deactivate is used ONLY when the keys match
   *     (since a different activate may be in use)
   */
  private _calculateActivatedValue(current: MediaChange): any {
    const currentKey = this._options.baseKey + current.suffix;  // e.g. suffix == 'GtSm',
    let newKey = this._activatedInputKey;                     // e.g. newKey == hideGtSm

    newKey = current.matches ? currentKey : ((newKey == currentKey) ? null : newKey);

    this._activatedInputKey = this._validateInputKey(newKey);
    return this.activatedInput;
  }

  /**
   * For the specified input property key, validate it is defined (used in the markup)
   * If not see if a overlapping mediaQuery-related input key fallback has been defined
   *
   * NOTE: scans in the order defined by activeOverLaps (largest viewport ranges -> smallest ranges)
   */
  private _validateInputKey(inputKey) {
    let items: BreakPoint[] = this.mediaMonitor.activeOverlaps;
    let isMissingKey = (key) => !this._keyInUse(key);

    if (isMissingKey(inputKey)) {
      items.some(bp => {
        let key = this._options.baseKey + bp.suffix;
        if (!isMissingKey(key)) {
          inputKey = key;
          return true;  // exit .some()
        }
        return false;
      });
    }
    return inputKey;
  }

  /**
   * Get the value (if any) for the directive instances @Input property (aka key)
   */
  private _lookupKeyValue(key) {
    return this._options.inputKeys[key];
  }

}


text:
// -*- C++ -*-
//
//=============================================================================
/**
 *  @file    RW_Process_Mutex.h
 *
 *  $Id: RW_Process_Mutex.h 78476 2007-05-24 07:55:50Z johnnyw $
 *
 *  @author Douglas C. Schmidt <schmidt@cs.wustl.edu>
 */
//=============================================================================

#ifndef ACE_RW_PROCESS_MUTEX_H
#define ACE_RW_PROCESS_MUTEX_H

#include /**/ "ace/pre.h"

#include "ace/File_Lock.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "ace/Default_Constants.h"
#include "ace/OS_NS_fcntl.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class ACE_RW_Process_Mutex
 *
 * @brief Wrapper for readers/writer locks that exist across processes.
 *
 * Note that because this class uses the
 * <ACE_File_Lock> as its implementation it only can be reliably
 * used between separate processes, rather than threads in the
 * same process.  This isn't a limitation of ACE, it's simply
 * the file lock semantics on UNIX and Win32.
 * \todo For systems with pthread_rwlockattr_setpshared one
 * may consider using them to make the mutex faster.
 */
class ACE_Export ACE_RW_Process_Mutex
{
public:
  /// Create a readers/writer <Process_Mutex>, passing in the optional
  /// @a name, <flags> and <mode> \sa ACE_File_Lock.
  ///  If not specified, a name is generated and flags and mode are set
  ///  to default platform values.
#if defined (ACE_WIN32)
  ACE_RW_Process_Mutex (const ACE_TCHAR *name = 0,
                        int flags = O_CREAT|O_RDWR,
                        mode_t mode =  ACE_DEFAULT_OPEN_PERMS);
#else
  ACE_RW_Process_Mutex (const ACE_TCHAR *name = 0,
                        int flags = O_CREAT|O_RDWR,
                            mode_t mode = S_IRUSR | S_IWUSR );
#endif /* ACE_WIN32 */

  ~ACE_RW_Process_Mutex (void);

  /**
   * Explicitly destroy the mutex.  Note that only one thread should
   * call this method since it doesn't protect against race
   * conditions.
   */
  int remove (void);

  /// Acquire lock ownership (wait on queue if necessary).
  int acquire (void);

  /**
   * Conditionally acquire lock (i.e., don't wait on queue).  Returns
   * -1 on failure.  If we "failed" because someone else already had
   * the lock, @c errno is set to @c EBUSY.
   */
  int tryacquire (void);

  /// Release lock and unblock a thread at head of queue.
  int release (void);

  /// Acquire lock ownership (wait on queue if necessary).
  int acquire_read (void);

  /// Acquire lock ownership (wait on queue if necessary).
  int acquire_write (void);

  /**
   * Conditionally acquire a lock (i.e., won't block).  Returns -1 on
   * failure.  If we "failed" because someone else already had the
   * lock, @c errno is set to @c EBUSY.
   */
  int tryacquire_read (void);

  /**
   * Conditionally acquire a lock (i.e., won't block).  Returns -1 on
   * failure.  If we "failed" because someone else already had the
   * lock, @c errno is set to @c EBUSY.
   */
  int tryacquire_write (void);

  /// Attempt to upgrade a read lock to a write lock. Returns 0 on
  /// success, -1 on failure.
  int tryacquire_write_upgrade (void);

  /// Return the underlying lock.
  const ACE_File_Lock &lock (void) const;

  /// Dump the state of an object.
  void dump (void) const;

  /// Declare the dynamic allocation hooks.
  ACE_ALLOC_HOOK_DECLARE;

private:
  /// If the user does not provide a name we generate a unique name in
  /// this buffer.
  ACE_TCHAR name_[ACE_UNIQUE_NAME_LEN];

  /// Create and return the unique name.
  const ACE_TCHAR *unique_name (void);

  /// We need this to get the readers/writer semantics...
  ACE_File_Lock lock_;
};

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "ace/RW_Process_Mutex.inl"
#endif /* __ACE_INLINE__ */

#include /**/ "ace/post.h"
#endif /* ACE_RW_PROCESS_MUTEX_H */


text:
cask :v1 => 'xone' do
  version '1.0.3'
  sha256 '7dc71593122bbe839d5a642d59943825eb5328287a52061ba1ffac4608051f47'

  url "https://github.com/FranticRain/Xone-OSX/releases/download/v#{version}/Xone-Driver-#{version}.dmg"
  appcast 'https://github.com/FranticRain/Xone-OSX/releases.atom'
  name 'xone'
  name 'xbox-one-controller-driver'
  homepage 'https://github.com/FranticRain/Xone-OSX'
  license :gpl

  pkg "Xone-Driver-#{version}.pkg", :allow_untrusted => true

  uninstall :kext => 'com.vestigl.driver.Xone-Driver',
            :delete => [
                        '/Library/PreferencePanes/Xone Driver Pref Pane.prefPane',
                        '/Library/Extensions/Xone Driver.kext'
                       ]
end


text:
/**
 *
 */
package net.sparkbox.pontointeligente.api.modelo.enums;

/**
 * @author Israel
 *
 */
public enum PerfilEnum {
	ROLE_ADMIN, ROLE_USUARIO;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mutuma.collins.jichunge.ui.ImportContacts">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.10"
            android:layout_marginBottom="0dp"
            android:layout_marginTop="10dp"
            android:text="Choose emergency contacts:"
            android:textColor="#002080"
            android:textStyle="bold"
            android:textSize="18sp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000"
            />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.80"
            android:layout_below="@+id/textView1"
            >
        </ListView>
        <Button
            android:id="@+id/contactsavebutton"
            android:text="SAVE"
            android:textColor="#002080"
            android:textSize="16sp"
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="0.10"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:clickable="true"
            android:onClick="savecontacts" />
    </LinearLayout>

</RelativeLayout>


text:
"""tests of twistedpg."""

from psycopg2.extras import DictCursor
from pyiem import twistedpg

def test_connect():
    """Does our logic work?"""
    conn = twistedpg.connect(database="postgis", host="iemdb.local")
    cursor = conn.cursor()
    assert isinstance(cursor, DictCursor)


text:
from voodoo.representable import Representable

class Resource(object):
    __metaclass__ = Representable

    def __init__(self, resource_type, resource_instance):
        self.resource_type     = resource_type
        self.resource_instance = resource_instance

    def to_weblab_str(self):
        return "%s@%s" % (self.resource_instance, self.resource_type)

    def __hash__(self):
        return hash(self.to_weblab_str())

    @staticmethod
    def parse(weblab_str):
        pos = weblab_str.find("@")
        resource_instance = weblab_str[:pos]
        resource_type     = weblab_str[pos + 1 :]
        return Resource(resource_type, resource_instance)


text:
require File.join(File.dirname(__FILE__), 'provider_database_mysql')

class Chef
  class Provider
    class Database
      class MysqlUser < Chef::Provider::Database::Mysql
        use_inline_resources if defined?(use_inline_resources)

        def whyrun_supported?
          true
        end

        action :create do
          # test
          user_present = nil
          begin
            test_sql = "SELECT User,Host from mysql.user WHERE User='#{new_resource.username}' AND Host='#{new_resource.host}';"
            test_sql_results = test_client.query(test_sql)
            test_sql_results.each do |r|
              user_present = true if r['User'] == new_resource.username
            end
          ensure
            close_test_client
          end

          # repair
          unless user_present
            converge_by "Creating user '#{new_resource.username}'@'#{new_resource.host}'" do
              begin
                repair_sql = "CREATE USER '#{new_resource.username}'@'#{new_resource.host}'"
                repair_sql += " IDENTIFIED BY '#{new_resource.password}'" if new_resource.password
                repair_client.query(repair_sql)
              ensure
                close_repair_client
              end
            end
          end
        end

        action :drop do
          # test
          user_present = nil
          begin
            test_sql = 'SELECT User,Host'
            test_sql += ' from mysql.user'
            test_sql += " WHERE User='#{new_resource.username}'"
            test_sql += " AND Host='#{new_resource.host}'"
            test_sql_results = test_client.query test_sql
            test_sql_results.each do |r|
              user_present = true if r['User'] == new_resource.username
            end
          ensure
            close_test_client
          end

          # repair
          if user_present
            converge_by "Dropping user '#{new_resource.username}'@'#{new_resource.host}'" do
              begin
                repair_sql = 'DROP USER'
                repair_sql += " '#{new_resource.username}'@'#{new_resource.host}'"
                repair_client.query repair_sql
              ensure
                close_repair_client
              end
            end
          end
        end

        action :grant do
          # gratuitous function
          def ishash?
            return true if (/(\A\*[0-9A-F]{40}\z)/i).match(new_resource.password)
          end

          db_name = new_resource.database_name ? "`#{new_resource.database_name}`" : '*'
          tbl_name = new_resource.table ? new_resource.table : '*'

          # Test
          incorrect_privs = nil
          begin
            test_sql = 'SELECT * from mysql.db'
            test_sql += " WHERE User='#{new_resource.username}'"
            test_sql += " AND Host='#{new_resource.host}'"
            test_sql += " AND Db='#{db_name}'"
            test_sql_results = test_client.query test_sql

            incorrect_privs = true if test_sql_results.size == 0
            # These should all by 'Y'
            test_sql_results.each do |r|
              new_resource.privileges.each do |p|
                key = "#{p.capitalize}_priv"
                incorrect_privs = true if r[key] != 'Y'
              end
            end
          ensure
            close_test_client
          end

          # Repair
          if incorrect_privs
            converge_by "Granting privs for '#{new_resource.username}'@'#{new_resource.host}'" do
              begin
                repair_sql = "GRANT #{new_resource.privileges.join(',')}"
                repair_sql += " ON #{db_name}.#{tbl_name}"
                repair_sql += " TO '#{new_resource.username}'@'#{new_resource.host}' IDENTIFIED BY"
                repair_sql += " '#{new_resource.password}'"
                repair_sql += ' REQUIRE SSL' if new_resource.require_ssl
                repair_sql += ' WITH GRANT OPTION' if new_resource.grant_option

                Chef::Log.info("#{new_resource}: granting access with statement [#{repair_sql}]")
                repair_client.query(repair_sql)
                repair_client.query('FLUSH PRIVILEGES')
              ensure
                close_repair_client
              end
            end
          end
        end

        def action_revoke
          db_name = new_resource.database_name ? "`#{new_resource.database_name}`" : '*'
          tbl_name = new_resource.table ? new_resource.table : '*'

          revoke_statement = "REVOKE #{@new_resource.privileges.join(', ')}"
          revoke_statement += " ON #{db_name}.#{tbl_name}"
          revoke_statement += " FROM `#{@new_resource.username}`@`#{@new_resource.host}` "
          Chef::Log.info("#{@new_resource}: revoking access with statement [#{revoke_statement}]")
          db.query(revoke_statement)
          @new_resource.updated_by_last_action(true)
        ensure
          close
        end

        private

        def test_client
          require 'mysql2'
          @test_client ||=
            Mysql2::Client.new(
            host: new_resource.connection[:host],
            socket: new_resource.connection[:socket],
            username: new_resource.connection[:username],
            password: new_resource.connection[:password],
            port: new_resource.connection[:port]
            )
        end

        def close_test_client
          @test_client.close if @test_client
        rescue Mysql2::Error
          @test_client = nil
        end

        def repair_client
          require 'mysql2'
          @repair_client ||=
            Mysql2::Client.new(
            host: new_resource.connection[:host],
            socket: new_resource.connection[:socket],
            username: new_resource.connection[:username],
            password: new_resource.connection[:password],
            port: new_resource.connection[:port]
            )
        end

        def close_repair_client
          @repair_client.close if @repair_client
        rescue Mysql2::Error
          @repair_client = nil
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created by libAntimony version v2.4 with libSBML version 5.8.0. -->
<sbml xmlns="http://www.sbml.org/sbml/level3/version1/core" xmlns:comp="http://www.sbml.org/sbml/level3/version1/comp/version1" level="3" version="1" comp:required="true">
  <model id="bar" name="bar">
    <listOfCompartments>
      <compartment sboTerm="SBO:0000410" id="default_compartment" spatialDimensions="3" size="1" constant="true">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="default_compartment" comp:submodelRef="A"/>
        </comp:listOfReplacedElements>
      </compartment>
    </listOfCompartments>
    <listOfSpecies>
      <species id="y" compartment="default_compartment" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false">
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="x" comp:submodelRef="A"/>
        </comp:listOfReplacedElements>
      </species>
    </listOfSpecies>
    <listOfReactions>
      <reaction id="J1" reversible="true" fast="false">
        <listOfProducts>
          <speciesReference id="y_stoich" species="y" stoichiometry="1" constant="true">
            <comp:listOfReplacedElements>
              <comp:replacedElement comp:idRef="x_stoich" comp:submodelRef="A"/>
            </comp:listOfReplacedElements>
          </speciesReference>
        </listOfProducts>
        <comp:listOfReplacedElements>
          <comp:replacedElement comp:idRef="J0" comp:submodelRef="A"/>
        </comp:listOfReplacedElements>
      </reaction>
    </listOfReactions>
    <comp:listOfSubmodels>
      <comp:submodel comp:id="A" comp:modelRef="foo"/>
    </comp:listOfSubmodels>
  </model>
  <comp:listOfModelDefinitions>
    <comp:modelDefinition id="foo" name="foo">
      <listOfCompartments>
        <compartment sboTerm="SBO:0000410" id="default_compartment" spatialDimensions="3" size="1" constant="true"/>
      </listOfCompartments>
      <listOfSpecies>
        <species id="x" compartment="default_compartment" hasOnlySubstanceUnits="false" boundaryCondition="false" constant="false"/>
      </listOfSpecies>
      <listOfReactions>
        <reaction id="J0" reversible="true" fast="false">
          <listOfReactants>
            <speciesReference id="x_stoich" species="x" stoichiometry="1" constant="true"/>
          </listOfReactants>
        </reaction>
      </listOfReactions>
    </comp:modelDefinition>
  </comp:listOfModelDefinitions>
</sbml>


text:
package drum

import (
	"bytes"
	"errors"
	"io"
)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// Write out a string where the total output size is fixed. The output will either
// be truncated or filled with zero/nulls.
func writeFixedNullTermString(spliceFile io.Writer, value string, length int) error {
	var versionBuffer bytes.Buffer
	n, _ := versionBuffer.WriteString(value[:min(length, len(value))])
	if n < length {
		versionBuffer.Write(make([]byte, length-n))
	}
	spliceFile.Write(versionBuffer.Bytes())

	return nil
}

// Read in a fixed length string where a string shorter than given length will be
// inficated by zero/null termination
func readFixedNullTermString(spliceFile io.Reader, length int) (string, error) {
	raw := make([]byte, length)
	n, err := spliceFile.Read(raw)
	if err != nil {
		return "", err
	}
	if n != length {
		return "", errors.New("Could not read string, insufficient data")
	}

	// Find first occurence of null(0) and use it to slice the string
	n = bytes.Index(raw, []byte{0})
	if n < 0 {
		n = length
	}
	return string(raw[:n]), nil
}


text:
#include <memory>
#include <random>
#include <algorithm>

void Player::Heal( uint8_t amt )
{
	m_health = std::min<int8_t>(m_health + amt, GameState::StartingHealth);
}

void Minion::Heal(uint8_t amt)
{
	m_health = std::min<int8_t>(m_health + amt, m_max_health);
}

void Minion::AddAuraEffects(const MinionAura& aura)
{
	switch (aura.m_effect)
	{
	case MinionAuraEffect::BonusAttack:
		m_attack += aura.m_param;
		break;
	}
}

void Minion::RemoveAuraEffects(const MinionAura& aura)
{
	switch (aura.m_effect)
	{
	case MinionAuraEffect::BonusAttack:
		m_attack -= aura.m_param;
		break;
	}
}

void Minion::RemoveEndOfTurnAuras( )
{
	if (m_auras.Num( ) == 0)
		return;

	for (uint8_t i = m_auras.Num( ) - 1; ; --i)
	{
		if (m_auras[i].m_duration == AuraDuration::EndOfTurn)
		{
			RemoveAuraEffects(m_auras[i]);
			m_auras.RemoveSwap(i);
		}

		if (i == 0)
			break;
	}
}

GameState::GameState()
{
	memset(this, 0, sizeof(GameState));
	m_players[0].m_health = StartingHealth;
	m_players[1].m_health = StartingHealth;

	m_winner = Winner::Undetermined;
}

GameState::GameState(const GameState& other)
{
	memcpy(this, &other, sizeof(GameState));
}

void GameState::ProcessMove(const Move& m)
{
	switch (m.m_type)
	{
	case MoveType::EndTurn: EndTurn(); break;
	case MoveType::PlayCard: PlayCard(m.m_card, m.m_target_packed); break;
	case MoveType::AttackHero: AttackHero(m.m_source_index); break;
	case MoveType::AttackMinion: AttackMinion(m.m_source_index, m.m_target_packed.m_minion); break;
	}

	while (m_pending_spell_effects.Num( ))
	{
		HandlePendingSpellEffect(m_pending_spell_effects[0].m_spell_data, m_pending_spell_effects[0].m_owner_index);
		m_pending_spell_effects.RemoveAt(0);
	}

	UpdatePossibleMoves();
}

void GameState::PlayOutRandomly( std::mt19937& r )
{
	while (m_winner == Winner::Undetermined)
	{
		std::uniform_int_distribution<decltype(m_possible_moves.Num())> move_dist(0, m_possible_moves.Num() - 1);
		auto idx = move_dist(r);
		ProcessMove(m_possible_moves[idx]);
	}
}

void GameState::UpdatePossibleMoves( )
{
	FixedVector< FixedVector<PackedTarget, MaxTargets, uint8_t>, (uint8_t)TargetType::MAX, uint8_t> target_map;

	uint8_t opponent_index = OppositePlayer(m_active_player_index);

	target_map[(uint8_t)TargetType::None].Add(Move::TargetNone());
	target_map[(uint8_t)TargetType::Opponent].Add(Move::TargetPlayer(opponent_index));
	target_map[(uint8_t)TargetType::SelfPlayer].Add(Move::TargetPlayer(m_active_player_index));
	for (uint8_t i = 0; i < 2; ++i)
	{
		target_map[(uint8_t)TargetType::AnyPlayer].Add(Move::TargetPlayer(i));
	}
	for (uint8_t player_index = 0; player_index < 2; ++player_index)
	{
		for (uint8_t minion_index = 0; minion_index < m_players[player_index].m_minions.Num( ); ++minion_index)
		{
			if (player_index == m_active_player_index || !m_players[player_index].m_minions[minion_index].HasStealth( ))
			{
				target_map[(uint8_t)TargetType::AnyCharacter].Add(Move::TargetMinion(player_index, minion_index));
				target_map[(uint8_t)TargetType::AnyMinion].Add(Move::TargetMinion(player_index, minion_index));
			}
		}

		target_map[(uint8_t)TargetType::AnyCharacter].Add(Move::TargetPlayer(player_index));
	}

	m_possible_moves.Clear();

	Player& ActivePlayer = m_players[m_active_player_index];
	Player& Opponent = m_players[opponent_index];

	bool opponent_has_taunt = false;
	for (uint8_t i = 0; i < Opponent.m_minions.Num( ); ++i)
	{
		if (Opponent.m_minions[i].HasTaunt( ) && !Opponent.m_minions[i].HasStealth())
		{
			opponent_has_taunt = true;
			break;
		}
	}

	// Attack each target with each minion
	for (uint8_t i = 0; i < ActivePlayer.m_minions.Num(); ++i)
	{
		if (!ActivePlayer.m_minions[i].CanAttack())
			continue;

		for (uint8_t j = 0; j < Opponent.m_minions.Num( ); ++j)
		{
			if( opponent_has_taunt && !Opponent.m_minions[j].HasTaunt() )
				continue;

			if( Opponent.m_minions[j].HasStealth() )
				continue;

			// Attack minion
			m_possible_moves.Add(Move::AttackMinion(i, j));
		}

		if (!opponent_has_taunt)
		{
			// Attack opponent
			m_possible_moves.Add(Move::AttackHero(i));
		}
	}

	// Play each card
	for (uint8_t i = 0; i < ActivePlayer.m_hand.Num(); ++i)
	{
		Card c = ActivePlayer.m_hand[i];
		const CardData* const data = GetCardData(c);
		if (data->m_mana_cost > ActivePlayer.m_mana)
			continue;

		switch (data->m_type)
		{
		case CardType::Minion:
		{
			const auto& targets = target_map[(uint8_t)data->m_minion_battlecry.m_target_type];

			for (uint8_t target_index = 0; target_index < targets.Num( ); ++target_index)
			{
				m_possible_moves.Add(Move::PlayCard(c, targets[target_index]));
			}

			// Can always(?) play minion battlecries with no target
			if (targets.Num( ) == 0)
			{
				m_possible_moves.Add(Move::PlayCard(c));
			}
		}
			break;
		case CardType::Spell:
		{
			const auto& targets = target_map[(uint8_t)data->m_spell_data.m_target_type];

			for (uint8_t target_index = 0; target_index < targets.Num( ); ++target_index)
			{
				m_possible_moves.Add(Move::PlayCard(c, targets[target_index]));
			}
		}
			break;
		}
	}

	// End turn
	m_possible_moves.Add(Move::EndTurn());
}

void GameState::EndTurn()
{
	m_active_player_index = (uint8_t)abs(m_active_player_index - 1);
	Player& ActivePlayer = m_players[m_active_player_index];
	ActivePlayer.DrawOne();
	ActivePlayer.m_max_mana = (uint8_t)std::min(10, ActivePlayer.m_max_mana + 1);
	ActivePlayer.m_mana = ActivePlayer.m_max_mana;

	for (uint8_t player_idx = 0; player_idx < 2; ++player_idx)
	{
		for (uint8_t i = 0; i < m_players[player_idx].m_minions.Num( ); ++i)
		{
			Minion& m = m_players[player_idx].m_minions[i];
			m.ClearAttackFlags( );
			m.RemoveEndOfTurnAuras( );
		}
	}

	// HACK before fatigue goes in
	if (m_players[0].m_deck.Num() == 0 && m_players[1].m_deck.Num() == 0)
	{
		m_winner = Winner::Draw;
	}
}

void GameState::PlayCard(Card c, PackedTarget packed_target)
{
	Player& ToAct = m_players[m_active_player_index];
	const CardData* ToPlay = GetCardData(c);
	decltype(ToAct.m_hand.Num( )) idx;
	if (!ToAct.m_hand.Find(c, idx))
		return;

	ToAct.m_hand.RemoveSwap(idx);

	ToAct.m_mana -= ToPlay->m_mana_cost;

	if (ToPlay->m_type == CardType::Minion)
	{
		PlayMinion(c, packed_target);
	}
	else
	{
		HandleSpell(ToPlay->m_spell_data, packed_target, m_active_player_index, true);
	}
}

void GameState::AttackHero(uint8_t SourceIndex)
{
	Player& Active = m_players[m_active_player_index];
	Player& Opponent = m_players[abs(m_active_player_index - 1)];

	Minion& Attacker = Active.m_minions[SourceIndex];
	Attacker.Attacked( );

	Opponent.m_health -= Attacker.m_attack;

	if (Opponent.m_health <= 0)
	{
		m_winner = static_cast<Winner>(m_active_player_index);
	}
}

void GameState::CheckDeadMinion(uint8_t player_index, uint8_t minion_index)
{
	Player& owner = m_players[player_index];
	Minion& dead_minion = owner.m_minions[minion_index];
	if (dead_minion.m_health <= 0)
	{
		if (dead_minion.HasDeathrattle())
		{
			PushDeathrattle(player_index, dead_minion);
		}
		owner.m_minions.RemoveAt(minion_index);
	}
}

void GameState::AttackMinion(uint8_t SourceIndex, uint8_t TargetIndex)
{
	Player& Active = m_players[m_active_player_index];
	Player& Opponent = m_players[OppositePlayer(m_active_player_index)];

	Minion& Attacker = Active.m_minions[SourceIndex];
	Minion& Victim = Opponent.m_minions[TargetIndex];

	Attacker.TakeDamage(Victim.m_attack);
	Victim.TakeDamage(Attacker.m_attack);

	Attacker.Attacked( );

	// Handle minion death
	// TODO: Refactor when handling simultaneous minion death
	CheckDeadMinion(m_active_player_index, SourceIndex);
	CheckDeadMinion(OppositePlayer(m_active_player_index), TargetIndex);

	CheckVictory( );
}

void GameState::HandlePendingSpellEffect(const SpellData& data, uint8_t owner_index)
{
	uint8_t opponent_index = OppositePlayer(owner_index);
	PackedTarget target = Move::TargetNone();
	switch (data.m_target_type)
	{
	case TargetType::Opponent:
		target = Move::TargetPlayer(opponent_index);
		break;
	case TargetType::SelfPlayer:
		target = Move::TargetPlayer(owner_index);
		break;
	}
	HandleSpell(data, target, owner_index);
}

void GameState::HandleSpell(const SpellData& spell_data, PackedTarget target_packed, uint8_t owner_index, bool affected_by_spelldamage)
{
	uint8_t target_player, target_minion;
	Move::UnpackTarget(target_packed, target_player, target_minion);
	uint8_t spelldamage = affected_by_spelldamage ? m_players[owner_index].CalculateSpelldamage( ) : 0;
	switch (spell_data.m_effect)
	{
	case SpellEffect::AddMana:
	{
		Player& p = m_players[target_player];
		p.m_mana += spell_data.m_param;
	}
	break;
	case SpellEffect::AddManaCrystal:
	{
		Player& p = m_players[target_player];
		p.m_max_mana += spell_data.m_param;
	}
	break;
	case SpellEffect::DrawCard:
	{
		Player& p = m_players[target_player];
		for (uint8_t i = 0; i < spell_data.m_param; ++i)
		{
			p.DrawOne( );
		}
	}
	break;
	case SpellEffect::DamageCharacter:
	{
		uint8_t dmg = spell_data.m_param + spelldamage;
		if (spell_data.m_target_type == TargetType::AllMinions)
		{
			ForEachMinion([=](Minion& m){ m.m_health -= dmg; });
			CheckDeadMinions( );
		}
		else if (spell_data.m_target_type == TargetType::AllCharacters)
		{
			ForEachPlayer([=](Player& p){ p.m_health -= dmg; });
			ForEachMinion([=](Minion& m){ m.m_health -= dmg; });
			CheckDeadMinions( );
		}
		else if (spell_data.m_target_type == TargetType::AllFriendlyCharacters)
		{

		}
		else if (target_minion == NoMinion)
		{
			// Target hero
			m_players[target_player].m_health -= dmg;
		}
		else
		{
			m_players[target_player].m_minions[target_minion].m_health -= dmg;
			CheckDeadMinion(target_player, target_minion);
		}

		CheckVictory( );
	}
		break;
	case SpellEffect::HealCharacter:
	{
		uint8_t amt = spell_data.m_param + spelldamage;
		if (spell_data.m_target_type == TargetType::AllMinions)
		{
			ForEachMinion([=](Minion& m){ m.Heal(amt); });
			CheckDeadMinions( );
		}
		else if (spell_data.m_target_type == TargetType::AllCharacters)
		{
			ForEachPlayer([=](Player& p){ p.Heal(amt); });
			ForEachMinion([=](Minion& m){ m.Heal(amt); });
			CheckDeadMinions( );
		}
		else if (spell_data.m_target_type == TargetType::AllFriendlyCharacters)
		{
			m_players[owner_index].Heal(amt);
			ForEachMinion(owner_index, [=](Minion& m){ m.Heal(amt); });
		}
		else if (target_minion == NoMinion)
		{
			m_players[target_player].Heal(spell_data.m_param);
		}
		else
		{
			m_players[target_player].m_minions[target_minion].Heal(spell_data.m_param);
		}
	}
		break;
	case SpellEffect::SetHealth:
	{
		m_players[target_player].m_health = spell_data.m_param;
	}
		break;
	case SpellEffect::AddMinionAura:
	{
		Minion& m = m_players[target_player].m_minions[target_minion];
		m.m_auras.Add(spell_data.m_aura);
		m.AddAuraEffects(spell_data.m_aura);
	}
		break;
	}
}

void GameState::PlayMinion(Card c, PackedTarget target_packed)
{
	const CardData* data = GetCardData(c);

	if (data->HasBattlecry())
	{
		HandleSpell(data->m_minion_battlecry, target_packed, m_active_player_index);
	}

	m_players[m_active_player_index].m_minions.Add({ data });
}

void GameState::CheckVictory( )
{
	if (m_players[0].m_health <= 0 && m_players[1].m_health <= 0)
	{
		m_winner = Winner::Draw;
	}
	else if (m_players[0].m_health <= 0)
	{
		m_winner = Winner::PlayerTwo;
	}
	else if (m_players[1].m_health <= 0)
	{
		m_winner = Winner::PlayerOne;
	}
}

void GameState::CheckDeadMinions( )
{
	for (uint8_t player_idx = 0; player_idx < 2; ++player_idx)
	{
		if (m_players[player_idx].m_minions.Num( ))
		{
			for (uint8_t minion_idx = m_players[player_idx].m_minions.Num( ) - 1;; --minion_idx)
			{
				if (m_players[player_idx].m_minions[minion_idx].m_health <= 0)
				{
					PushDeathrattle(player_idx, m_players[player_idx].m_minions[minion_idx]);
					m_players[player_idx].m_minions.RemoveAt(minion_idx);
				}
				if (minion_idx == 0)
					break;
			}
		}
	}
}

void GameState::PushDeathrattle(uint8_t owner_idx, const Minion& m)
{
	if (m.HasDeathrattle( ))
	{
		m_pending_spell_effects.Add({ m.m_source_card->m_minion_deathrattle, owner_idx });
	}
}

void GameState::PrintMove(const Move& m) const
{
	const Player& Active = m_players[m_active_player_index];
	const Player& Opponent = m_players[abs(m_active_player_index - 1)];

	const CardData* CardToPlay = nullptr;
	switch (m.m_type)
	{
	case MoveType::AttackHero:
		printf("Player %d: Attack hero with %s\n",
			m_active_player_index,
			Active.m_minions[m.m_source_index].GetName()
			);
		break;
	case MoveType::AttackMinion:
		printf("Player %d: Attack %s with %s\n",
			m_active_player_index,
			Opponent.m_minions[m.m_target_packed.m_minion].GetName(),
			Active.m_minions[m.m_source_index].GetName()
			);
		break;
	case MoveType::EndTurn:
		printf("Player %d: End turn\n", m_active_player_index);
		break;
	case MoveType::PlayCard:
		CardToPlay = GetCardData(m_players[m_active_player_index].m_hand[m.m_source_index]);
		printf("Player %d: Play %s\n", m_active_player_index, CardToPlay->m_name);
		break;
	}
}

void GameState::PrintState() const
{
	for (unsigned i = 0; i < 2; ++i)
	{
		printf("Player %d - %d - %d/%d\n", i, m_players[i].m_health, m_players[i].m_mana, m_players[i].m_max_mana );
		printf("Hand: ");
		for (uint8_t card = 0; card < m_players[i].m_hand.Num(); ++card)
		{
			const char* format = card == 0 ? "%s" : ", %s";
			printf(format, GetCardData(m_players[i].m_hand[card])->m_name);
		}
		printf("\n");
		printf("Minions: \n");
		for (uint8_t m = 0; m < m_players[i].m_minions.Num(); ++m)
		{
			const Minion& minion = m_players[i].m_minions[m];
			printf("%s %d/%d\n", minion.GetName(), minion.m_attack, minion.m_health);
		}
	}
}

const char* Minion::GetName() const
{
	return m_source_card->m_name;
}


text:
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

namespace Native {
  class Panel : public Widget<Gtk::Frame> {
  public:
    Panel() {
      this->handle->add(this->scrolledWindow);
      this->scrolledWindow.add(this->fixed);

      this->handle->signal_show().connect(delegate_ {
        this->scrolledWindow.show();
        this->fixed.show();
      });
    }

    void BorderStyle(System::Windows::Forms::BorderStyle borderStyle) {
      switch (borderStyle) {
      case System::Windows::Forms::BorderStyle::None: this->handle->set_shadow_type(Gtk::SHADOW_NONE); break;
      case System::Windows::Forms::BorderStyle::FixedSingle: this->handle->set_shadow_type(Gtk::SHADOW_IN); break;
      case System::Windows::Forms::BorderStyle::Fixed3D: this->handle->set_shadow_type(Gtk::SHADOW_ETCHED_IN); break;
      }
    }

    const Gtk::Container& Container() const override {return this->fixed;}

    Gtk::Container& Container() override {return this->fixed;}

    void Text(const string& text) override {}

  private:
    Gtk::ScrolledWindow scrolledWindow;
    Gtk::Fixed fixed;
  };
}

intptr Native::PanelApi::Create(const System::Windows::Forms::Panel& panel) {
  Native::Panel* handle = new Native::Panel();
  handle->Move(panel.Location().X, panel.Location().Y);
  handle->Text(panel.Text);
  handle->Visible(true);
  return (intptr)handle;
}

System::Drawing::Size Native::PanelApi::GetDefaultSize() {
  return System::Drawing::Size(200, 100);
}

void Native::PanelApi::SetBorderStyle(const System::Windows::Forms::Panel& panel) {
  ((Native::Panel*)panel.Handle())->BorderStyle(panel.BorderStyle);
}

#endif


text:
    <button onclick="createBackupPDF()">create backup PDF</button>
    <button onclick="createBackupPopup()">create backup popup with HTML</button>


text:
package yelpInterview;

public class _Leetcode07ContainerMostWater {

	public static void main(String[] args) {
		System.out.println(maxArea(new int[]{0,2}));

	}

	public static int maxArea(int[] height) {
		if(height.length==0||height.length<2)
			return 0;
		int left=0;
		int right=height.length-1;
		int max=0;
		while(left<right)
		{
			if(height[left]>height[right])
			{
				max=Math.max(max,(right-left) * height[right]);
				right--;
			}else{
				max=Math.max(max,(right-left) * height[left]);
				left++;
			}

		}
		return max;
	}

}


text:
// Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library

using System.Reflection;

public static partial class Extensions
{
    /// <summary>A FieldInfo extension method that gets a declaraction.</summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>The declaraction.</returns>
    public static string GetSignature(this FieldInfo @this)
    {
        return @this.Name;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TodosBackend
{
    [ServiceContract]
    public class TodoService
    {
        [OperationContract]
        public List<Todo> All()
        {
            using (var ctx = new TodoContext())
            {
                return ctx.Todos.ToList();
            }
        }

        [OperationContract]
        public void Speichern(List<Todo> todos)
        {
            using (var ctx = new TodoContext())
            {
                foreach (var todo in todos)
                {
                    var entity = ctx.Entry(todo);
                    entity.State = todo.Id == 0 ? System.Data.Entity.EntityState.Added : System.Data.Entity.EntityState.Modified;
                }
                ctx.SaveChanges();
            }
        }
    }
}


text:
close all;clear;clc;
addpath('/home/vangjush/Documents/ANN/Support Vector Machine/LSSVMlabv1_8_R2009b_R2011a')
%%
% data = load('breast_cancer_wisconsin_data.mat','-ascii'); function_type = 'c';
% data = load('shuttle.dat','-ascii'); function_type = 'c';  data = data(1:700,:);
data = load('california.dat','-ascii'); function_type = 'f';
addpath('../LSSVMlab')
%%
X = data(:,1:end-1);Y = data(:,end);
testX = [];testY = [];
%% Parameter for input space selection
%Please type >> help fsoperations; to get more information
k = 6;
% function_type = 'c'; %'c' - classification, 'f' - regression
kernel_type = 'RBF_kernel'; % or 'lin_kernel', 'poly_kernel'
global_opt = 'csa'; % 'csa' or 'ds'
%Process to be performed
user_process={'FS-LSSVM', 'SV_L0_norm'};
window = [15,20,25];
[e,s,t] = fslssvm(X,Y,k,function_type,kernel_type,global_opt,user_process,window,testX,testY);


text:
#ifndef INCLUDED_UDPSOCKET_H
#define INCLUDED_UDPSOCKET_H

#ifndef INCLUDED_NETWORKINGUTILITIES_H
#include "NetworkingUtils.h"
#endif /* INCLUDED_NETWORKINGUTILITIES_H */

#ifndef INCLUDED_IPENDPOINTNAME_H
#include "IpEndpointName.h"
#endif /* INCLUDED_IPENDPOINTNAME_H */

class PacketListener;
class TimerListener;

class UdpSocket;

class SocketReceiveMultiplexer{
    class Implementation;
    Implementation *impl_;

	friend class UdpSocket;

public:
    SocketReceiveMultiplexer();
    ~SocketReceiveMultiplexer();

	// only call the attach/detach methods _before_ calling Run

    // only one listener per socket, each socket at most once
    void AttachSocketListener( UdpSocket *socket, PacketListener *listener );
    void DetachSocketListener( UdpSocket *socket, PacketListener *listener );

    void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener );
	void AttachPeriodicTimerListener(
            int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener );
    void DetachPeriodicTimerListener( TimerListener *listener );

    void Run();      // loop and block processing messages indefinitely
	void RunUntilSigInt();
    void Break();    // call this from a listener to exit once the listener returns
    void AsynchronousBreak(); // call this from another thread or signal handler to exit the Run() state
};

class UdpSocket{
    class Implementation;
    Implementation *impl_;

	friend class SocketReceiveMultiplexer::Implementation;

public:

	// ctor throws std::runtime_error if there's a problem
	// initializing the socket.
	UdpSocket();
	virtual ~UdpSocket();

	// the socket is created in an unbound, unconnected state
	// such a socket can only be used to send to an arbitrary
	// address using SendTo(). To use Send() you need to first
	// connect to a remote endpoint using Connect(). To use
	// ReceiveFrom you need to first bind to a local endpoint
	// using Bind().

	// retrieve the local endpoint name when sending to 'to'
    IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const;

	// Connect to a remote endpoint which is used as the target
	// for calls to Send()
	void Connect( const IpEndpointName& remoteEndpoint );
	void Send( const char *data, int size );
    void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size );

	// Bind a local endpoint to receive incoming data. Endpoint
	// can be 'any' for the system to choose an endpoint
	void Bind( const IpEndpointName& localEndpoint );
	bool IsBound() const;

	int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size );
};

// convenience classes for transmitting and receiving
// they just call Connect and/or Bind in the ctor.
// note that you can still use a receive socket
// for transmitting etc

class UdpTransmitSocket : public UdpSocket{
public:
	UdpTransmitSocket( const IpEndpointName& remoteEndpoint )
		{ Connect( remoteEndpoint ); }
};

class UdpReceiveSocket : public UdpSocket{
public:
	UdpReceiveSocket( const IpEndpointName& localEndpoint )
		{ Bind( localEndpoint ); }
};

// UdpListeningReceiveSocket provides a simple way to bind one listener
// to a single socket without having to manually set up a SocketReceiveMultiplexer

class UdpListeningReceiveSocket : public UdpSocket{
    SocketReceiveMultiplexer mux_;
    PacketListener *listener_;
public:
	UdpListeningReceiveSocket( const IpEndpointName& localEndpoint, PacketListener *listener )
        : listener_( listener )
    {
        Bind( localEndpoint );
        mux_.AttachSocketListener( this, listener_ );
    }

    ~UdpListeningReceiveSocket()
        { mux_.DetachSocketListener( this, listener_ ); }

    // see SocketReceiveMultiplexer above for the behaviour of these methods...
    void Run() { mux_.Run(); }
	void RunUntilSigInt() { mux_.RunUntilSigInt(); }
    void Break() { mux_.Break(); }
    void AsynchronousBreak() { mux_.AsynchronousBreak(); }
};

#endif /* INCLUDED_UDPSOCKET_H */


text:
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.MultiTenancy;
using AbpODataDemo.Editions;
using AbpODataDemo.MultiTenancy;

namespace AbpODataDemo.EntityFrameworkCore.Seed.Tenants
{
    public class DefaultTenantBuilder
    {
        private readonly AbpODataDemoDbContext _context;

        public DefaultTenantBuilder(AbpODataDemoDbContext context)
        {
            _context = context;
        }

        public void Create()
        {
            CreateDefaultTenant();
        }

        private void CreateDefaultTenant()
        {
            // Default tenant

            var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == AbpTenantBase.DefaultTenantName);
            if (defaultTenant == null)
            {
                defaultTenant = new Tenant(AbpTenantBase.DefaultTenantName, AbpTenantBase.DefaultTenantName);

                var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
                if (defaultEdition != null)
                {
                    defaultTenant.EditionId = defaultEdition.Id;
                }

                _context.Tenants.Add(defaultTenant);
                _context.SaveChanges();
            }
        }
    }
}


text:
package org.openkilda.northbound.dto.v2.yflows;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
@AllArgsConstructor
@JsonNaming(value = SnakeCaseStrategy.class)
public class SubFlowPingPayload {
    String flowId;
    UniSubFlowPingPayload forward;
    UniSubFlowPingPayload reverse;
}