text:
/************************************************************************
 * TAISHAN.h - configuration for AMCC 440GX Ref
 ***********************************************************************/

#ifndef __CONFIG_H
#define __CONFIG_H

/*-----------------------------------------------------------------------
 * High Level Configuration Options
 *----------------------------------------------------------------------*/
#define CONFIG_TAISHAN		1	/* Board is taishan		*/
#define CONFIG_440GX		1	/* Specifc GX support		*/
#define CONFIG_440		1	/* ... PPC440 family		*/
#define CONFIG_SYS_CLK_FREQ	33333333 /* external freq to pll	*/

#define	CONFIG_SYS_TEXT_BASE	0xFFFC0000

/*
 * Include common defines/options for all AMCC eval boards
 */
#define CONFIG_HOSTNAME		taishan
#define CONFIG_USE_TTY		ttyS1
#include "amcc-common.h"

#define CONFIG_BOARD_EARLY_INIT_F 1	/* Call board_pre_init		*/
#define CONFIG_MISC_INIT_R	1	/* Call misc_init_r		*/

/*-----------------------------------------------------------------------
 * Base addresses -- Note these are effective addresses where the
 * actual resources get mapped (not physical addresses)
 *----------------------------------------------------------------------*/
#define CONFIG_SYS_FLASH_BASE		0xfc000000	/* start of FLASH	*/
#define CONFIG_SYS_PCI_MEMBASE		0x80000000	/* mapped pci memory	*/
#define CONFIG_SYS_ISRAM_BASE		0xc0000000	/* internal SRAM	*/
#define CONFIG_SYS_PCI_BASE		0xd0000000	/* internal PCI regs	*/

#define CONFIG_SYS_EBC0_FLASH_BASE	CONFIG_SYS_FLASH_BASE
#define CONFIG_SYS_EBC1_FPGA_BASE	(CONFIG_SYS_PERIPHERAL_BASE + 0x01000000)
#define CONFIG_SYS_EBC2_LCM_BASE	(CONFIG_SYS_PERIPHERAL_BASE + 0x02000000)
#define CONFIG_SYS_EBC3_CONN_BASE	(CONFIG_SYS_PERIPHERAL_BASE + 0x08000000)

#define CONFIG_SYS_GPIO_BASE		(CONFIG_SYS_PERIPHERAL_BASE + 0x00000700)

/*-----------------------------------------------------------------------
 * Initial RAM & stack pointer (placed in internal SRAM)
 *----------------------------------------------------------------------*/
#define CONFIG_SYS_TEMP_STACK_OCM	1
#define CONFIG_SYS_OCM_DATA_ADDR	CONFIG_SYS_ISRAM_BASE
#define CONFIG_SYS_INIT_RAM_ADDR	CONFIG_SYS_ISRAM_BASE  /* Initial RAM address	*/
#define CONFIG_SYS_INIT_RAM_SIZE	0x2000		/* Size of used area in RAM*/

#define CONFIG_SYS_GBL_DATA_OFFSET	(CONFIG_SYS_INIT_RAM_SIZE - GENERATED_GBL_DATA_SIZE)
#define CONFIG_SYS_INIT_SP_OFFSET	(CONFIG_SYS_GBL_DATA_OFFSET - 0x4)

/*-----------------------------------------------------------------------
 * Serial Port
 *----------------------------------------------------------------------*/
#define CONFIG_CONS_INDEX	2	/* Use UART1			*/
#define CONFIG_SYS_EXT_SERIAL_CLOCK	(1843200 * 6)	/* Ext clk @ 11.059 MHz */

/*-----------------------------------------------------------------------
 * Environment
 *----------------------------------------------------------------------*/
#define CONFIG_ENV_IS_IN_FLASH     1	/* use FLASH for environment vars	*/

/*-----------------------------------------------------------------------
 * FLASH related
 *----------------------------------------------------------------------*/
#define CONFIG_SYS_FLASH_CFI
#define CONFIG_FLASH_CFI_DRIVER
#define CONFIG_SYS_FLASH_EMPTY_INFO		/* print 'E' for empty sector on flinfo */
#define CONFIG_SYS_FLASH_USE_BUFFER_WRITE 1	/* use buffered writes (20x faster)	*/

#define CONFIG_SYS_FLASH_BANKS_LIST    {CONFIG_SYS_FLASH_BASE}
#define CONFIG_SYS_MAX_FLASH_BANKS     1		    /* number of banks	    */
#define CONFIG_SYS_MAX_FLASH_SECT	1024		    /* sectors per device   */

#undef	CONFIG_SYS_FLASH_CHECKSUM
#define CONFIG_SYS_FLASH_ERASE_TOUT	120000	/* Timeout for Flash Erase (in ms)	*/
#define CONFIG_SYS_FLASH_WRITE_TOUT	500	/* Timeout for Flash Write (in ms)	*/

#define CONFIG_ENV_SECT_SIZE	0x40000 /* size of one complete sector	*/
#define CONFIG_ENV_ADDR		(CONFIG_SYS_MONITOR_BASE-CONFIG_ENV_SECT_SIZE)
#define	CONFIG_ENV_SIZE		0x4000	/* Total Size of Environment Sector	*/

/* Address and size of Redundant Environment Sector	*/
#define CONFIG_ENV_ADDR_REDUND	(CONFIG_ENV_ADDR-CONFIG_ENV_SECT_SIZE)
#define CONFIG_ENV_SIZE_REDUND	(CONFIG_ENV_SIZE)

/*-----------------------------------------------------------------------
 * E2PROM bootstrap configure value
 *----------------------------------------------------------------------*/

/*
 * 800/133/66
 * IIC 0~15: 86 78 11 6a 61 A7 04 62 00 00 00 00 00 00 00 00
 */

/*
 * 800/160/80
 * IIC 0~15: 86 78 c1 a6 09 67 04 63 00 00 00 00 00 00 00 00
 */

/*-----------------------------------------------------------------------
 * DDR SDRAM
 *----------------------------------------------------------------------*/
#undef CONFIG_SPD_EEPROM		/* Don't use SPD EEPROM for setup	*/
#define CONFIG_SDRAM_BANK0	1	/* init onboard DDR SDRAM bank 0	*/
#define	CONFIG_SYS_SDRAM0_TR0		0xC10A401A
#undef CONFIG_SDRAM_ECC			/* enable ECC support			*/

/*-----------------------------------------------------------------------
 * I2C
 *----------------------------------------------------------------------*/
#define CONFIG_SYS_I2C_PPC4XX_SPEED_0		400000

#undef CONFIG_SYS_I2C_MULTI_EEPROMS
#define CONFIG_SYS_I2C_EEPROM_ADDR	0x50
#define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 1
#define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 3
#define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 10

#define CONFIG_SYS_BOOTSTRAP_IIC_ADDR	0x50

/* I2C SYSMON (LM75, AD7414 is almost compatible)			*/
#define CONFIG_DTT_LM75		1		/* ON Semi's LM75	*/
#define CONFIG_DTT_SENSORS	{0}		/* Sensor addresses	*/
#define CONFIG_SYS_DTT_MAX_TEMP	70
#define CONFIG_SYS_DTT_LOW_TEMP	-30
#define CONFIG_SYS_DTT_HYSTERESIS	3

/*
 * Default environment variables
 */
#define	CONFIG_EXTRA_ENV_SETTINGS					\
	CONFIG_AMCC_DEF_ENV						\
	CONFIG_AMCC_DEF_ENV_POWERPC					\
	CONFIG_AMCC_DEF_ENV_PPC_OLD					\
	CONFIG_AMCC_DEF_ENV_NOR_UPD					\
	"kernel_addr=fc000000\0"					\
	"ramdisk_addr=fc180000\0"					\
	"kozio=bootm 0xffe00000\0"					\
	""

/*-----------------------------------------------------------------------
 * Networking
 *----------------------------------------------------------------------*/
#define CONFIG_EMAC_NR_START	2	/* start with EMAC 2 (skip 0&1)	*/
#define CONFIG_PHY_ADDR		0xff	     /* no phy on EMAC0		*/
#define CONFIG_PHY1_ADDR	0xff	     /* no phy on EMAC1		*/
#define CONFIG_PHY2_ADDR	0x1
#define CONFIG_PHY3_ADDR	0x3
#define CONFIG_ET1011C_PHY	1
#define CONFIG_HAS_ETH0
#define CONFIG_HAS_ETH1
#define CONFIG_HAS_ETH2
#define CONFIG_HAS_ETH3
#define CONFIG_PHY_GIGE		1	/* Include GbE speed/duplex detection */
#define CONFIG_PHY_RESET        1       /* reset phy upon startup         */
#define CONFIG_PHY_RESET_DELAY	1000

/*
 * Commands additional to the ones defined in amcc-common.h
 */
#define CONFIG_CMD_DTT
#define CONFIG_CMD_PCI

/*-----------------------------------------------------------------------
 * PCI stuff
 *-----------------------------------------------------------------------
 */
/* General PCI */
#define CONFIG_PCI			/* include pci support		*/
#define CONFIG_PCI_INDIRECT_BRIDGE	/* indirect PCI bridge support */
#define CONFIG_PCI_PNP			/* do pci plug-and-play		*/
#define CONFIG_EEPRO100       1		/* include PCI EEPRO100		*/
#define CONFIG_PCI_SCAN_SHOW		/* show pci devices on startup	*/
#define CONFIG_SYS_PCI_TARGBASE    0x80000000	/* PCIaddr mapped to CONFIG_SYS_PCI_MEMBASE */

/* Board-specific PCI */
#define CONFIG_SYS_PCI_TARGET_INIT		/* let board init pci target    */

#define CONFIG_SYS_PCI_SUBSYS_VENDORID 0x10e8	/* AMCC */
#define CONFIG_SYS_PCI_SUBSYS_DEVICEID 0xcafe	/* Whatever */

#endif	/* __CONFIG_H */


text:
#include <QColor>
#include <QDebug>

#include "autopopper.h"

#define DEBUG(input__)    qDebug() << "[AutoPopper] " input__

// How far above our "detection line" we'll attempt a pop.
// (The balloon will have risen since we got the screen capture.)
#define OFFSET 75

AutoPopper::AutoPopper(bool enable, QObject *parent)
 : QObject(parent), enabled(enable)
{
    whitelist << Qt::green;
    whitelist << QColor(0xff, 0x11, 0x00); // Red balloons. All 99 of them.
    whitelist << QColor(0xff, 0x11, 0x99); // Magenta-ish ballooners.
    whitelist << QColor(0x33, 0xdd, 0xff); // Cyan-ish rubbers.
    whitelist << QColor(0xdd, 0xee, 0xee); // Gray balloons
    whitelist << QColor(0xff, 0xcc, 0xff); // A darling shade of pink.
    whitelist << Qt::yellow;
}

// No cool CV tricks here.
// Literally the least amount of effort possible to implement a Jerry.
//
// FIXME convert pixels to percentages...
void AutoPopper::handleImage(const QImage &img)
{
    if (!enabled) {
        return;
    }

    const int width = img.width();
    const int height = img.height();

    QColor prev(Qt::black);

    const int minRow = 100;    // Avoid title stuff
    const uint matchCount = 45;
    uint sameCount;

    for (int row = (height - 1); row > minRow; row --) {

        prev.setRgb(0, 0, 0);
        sameCount = 0;

        for(int col = 0; col < width; col++) {
            QColor val(img.pixel(col, row));

            if (prev == val && whitelist.contains(val)) {
                sameCount++;

                if (sameCount >= matchCount) {
                    if (row >= OFFSET) {
                        DEBUG("Attempting a balloon with color " << val.name()
                              << "at" << col << "," << row - OFFSET);

                        emit attemptPop(col - matchCount/2, row - OFFSET);

                        /* Skip a bunch of rows to see if we can recover
                         * anything we missed */
                        row -= 150;
                        break;
                    }
                }

            }

            prev = val;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifdef __APPLE__
  #include <OpenCL/cl.h>
#else
  #include <CL/cl.h>
#endif

/* Error Codes */
enum ClError {
  Success = CL_SUCCESS,
  DeviceNotFound = CL_DEVICE_NOT_FOUND,
  DeviceNotAvailable = CL_DEVICE_NOT_AVAILABLE,
  CompilerNotAvailable = CL_COMPILER_NOT_AVAILABLE,
  MemObjectAllocationFailure = CL_MEM_OBJECT_ALLOCATION_FAILURE,
  OutOfResources = CL_OUT_OF_RESOURCES,
  OutOfHostMemory = CL_OUT_OF_HOST_MEMORY,
  ProfilingInfoNotAvailable = CL_PROFILING_INFO_NOT_AVAILABLE,
  MemCopyOverlap = CL_MEM_COPY_OVERLAP,
  ImageFormatMismatch = CL_IMAGE_FORMAT_MISMATCH,
  ImageFormatNotSupported = CL_IMAGE_FORMAT_NOT_SUPPORTED,
  BuildProgramFailure = CL_BUILD_PROGRAM_FAILURE,
  MapFailure = CL_MAP_FAILURE,
  MisalignedSubBufferOffset = CL_MISALIGNED_SUB_BUFFER_OFFSET,
  ExecStatusErrorForEventsInWaitList = CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST,

  InvalidValue = CL_INVALID_VALUE,
  InvalidDeviceType = CL_INVALID_DEVICE_TYPE,
  InvalidPlatform = CL_INVALID_PLATFORM,
  InvalidDevice = CL_INVALID_DEVICE,
  InvalidContext = CL_INVALID_CONTEXT,
  InvalidQueueProperties = CL_INVALID_QUEUE_PROPERTIES,
  InvalidCommandQueue = CL_INVALID_COMMAND_QUEUE,
  InvalidHostPtr = CL_INVALID_HOST_PTR,
  InvalidMemObject = CL_INVALID_MEM_OBJECT,
  InvalidImageFormatDescriptor = CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,
  InvalidImageSize = CL_INVALID_IMAGE_SIZE,
  InvalidSampler = CL_INVALID_SAMPLER,
  InvalidBinary = CL_INVALID_BINARY,
  InvalidBuildOptions = CL_INVALID_BUILD_OPTIONS,
  InvalidProgram = CL_INVALID_PROGRAM,
  InvalidProgramExecutable = CL_INVALID_PROGRAM_EXECUTABLE,
  InvalidKernelName = CL_INVALID_KERNEL_NAME,
  InvalidKernelDefinition = CL_INVALID_KERNEL_DEFINITION,
  InvalidKernel = CL_INVALID_KERNEL,
  InvalidArgIndex = CL_INVALID_ARG_INDEX,
  InvalidArgValue = CL_INVALID_ARG_VALUE,
  InvalidArgSize = CL_INVALID_ARG_SIZE,
  InvalidKernelArgs = CL_INVALID_KERNEL_ARGS,
  InvalidWorkDimension = CL_INVALID_WORK_DIMENSION,
  InvalidWorkGroupSize = CL_INVALID_WORK_GROUP_SIZE,
  InvalidWorkItemSize = CL_INVALID_WORK_ITEM_SIZE,
  InvalidGlobalOffset = CL_INVALID_GLOBAL_OFFSET,
  InvalidEventWaitList = CL_INVALID_EVENT_WAIT_LIST,
  InvalidEvent = CL_INVALID_EVENT,
  InvalidOperation = CL_INVALID_OPERATION,
  InvalidGlObject = CL_INVALID_GL_OBJECT,
  InvalidBufferSize = CL_INVALID_BUFFER_SIZE,
  InvalidMipLevel = CL_INVALID_MIP_LEVEL,
  InvalidGlobalWorkSize = CL_INVALID_GLOBAL_WORK_SIZE
  #ifdef CL_VERSION_1_1
  , InvalidProperty = CL_INVALID_PROPERTY
  #endif
};

/* OpenCL Version */
enum ClVersion {
  ClVersion1_0 = CL_VERSION_1_0,
  ClVersion1_1 = CL_VERSION_1_1
};

/* cl_bool */
enum ClBool {
  ClFalse = CL_FALSE,
  ClTrue = CL_TRUE
};

/* cl_platform_info */
enum PlatformInfo {
  PlatformProfile = CL_PLATFORM_PROFILE,
  PlatformVersion = CL_PLATFORM_VERSION,
  PlatformName = CL_PLATFORM_NAME,
  PlatformVendor = CL_PLATFORM_VENDOR,
  PlatformExtensions = CL_PLATFORM_EXTENSIONS
};

/* cl_device_type */
enum DeviceType {
  DeviceTypeDefault = CL_DEVICE_TYPE_DEFAULT,
  DeviceTypeCpu = CL_DEVICE_TYPE_CPU,
  DeviceTypeGpu = CL_DEVICE_TYPE_GPU,
  DeviceTypeAccelerator = CL_DEVICE_TYPE_ACCELERATOR,
  DeviceTypeAll = CL_DEVICE_TYPE_ALL
};

/* cl_device_info */
enum DeviceInfo {
  DeviceType = CL_DEVICE_TYPE,
  DeviceVendorID = CL_DEVICE_VENDOR_ID,
  DeviceMaxComputeUnits = CL_DEVICE_MAX_COMPUTE_UNITS,
  DeviceMaxWorkItemDimensions = CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS,
  DeviceMaxWorkGroupSize = CL_DEVICE_MAX_WORK_GROUP_SIZE,
  DeviceMaxWorkItemSizes = CL_DEVICE_MAX_WORK_ITEM_SIZES,
  DevicePreferredVectorWidthChar = CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR,
  DevicePreferredVectorWidthShort = CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT,
  DevicePreferredVectorWidthInt = CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT,
  DevicePreferredVectorWidthLong = CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG,
  DevicePreferredVectorWidthFloat = CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT,
  DevicePreferredVectorWidthDouble = CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE,
  DeviceMaxClockFrequency = CL_DEVICE_MAX_CLOCK_FREQUENCY,
  DeviceAddressBits = CL_DEVICE_ADDRESS_BITS,
  DeviceMaxReadImageArgs = CL_DEVICE_MAX_READ_IMAGE_ARGS,
  DeviceMaxWriteImageArgs = CL_DEVICE_MAX_WRITE_IMAGE_ARGS,
  DeviceMaxMemAllocSize = CL_DEVICE_MAX_MEM_ALLOC_SIZE,
  DeviceImage2DMaxWidth = CL_DEVICE_IMAGE2D_MAX_WIDTH,
  DeviceImage2DMaxHeight = CL_DEVICE_IMAGE2D_MAX_HEIGHT,
  DeviceImage3DMaxWidth = CL_DEVICE_IMAGE3D_MAX_WIDTH,
  DeviceImage3DMaxHeight = CL_DEVICE_IMAGE3D_MAX_HEIGHT,
  DeviceImage3DMaxDepth = CL_DEVICE_IMAGE3D_MAX_DEPTH,
  DeviceImageSupport = CL_DEVICE_IMAGE_SUPPORT,
  DeviceMaxParameterSize = CL_DEVICE_MAX_PARAMETER_SIZE,
  DeviceMaxSamplers = CL_DEVICE_MAX_SAMPLERS,
  DeviceMemBaseAddrAlign = CL_DEVICE_MEM_BASE_ADDR_ALIGN,
  DeviceMinDataTypeAlignSize = CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE,
  DeviceSingleFPConfig = CL_DEVICE_SINGLE_FP_CONFIG,
  DeviceGlobalMemCacheType = CL_DEVICE_GLOBAL_MEM_CACHE_TYPE,
  DeviceGlobalMemCachelineSize = CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE,
  DeviceGlobalMemCacheSize = CL_DEVICE_GLOBAL_MEM_CACHE_SIZE,
  DeviceGlobalMemSize = CL_DEVICE_GLOBAL_MEM_SIZE,
  DeviceMaxConstantBufferSize = CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE,
  DeviceMaxConstantArgs = CL_DEVICE_MAX_CONSTANT_ARGS,
  DeviceLocalMemType = CL_DEVICE_LOCAL_MEM_TYPE,
  DeviceLocalMemSize = CL_DEVICE_LOCAL_MEM_SIZE,
  DeviceErrorCorrectionSupport = CL_DEVICE_ERROR_CORRECTION_SUPPORT,
  DeviceProfilingTimerResolution = CL_DEVICE_PROFILING_TIMER_RESOLUTION,
  DeviceEndianLittle = CL_DEVICE_ENDIAN_LITTLE,
  DeviceAvailable = CL_DEVICE_AVAILABLE,
  DeviceCompilerAvailable = CL_DEVICE_COMPILER_AVAILABLE,
  DeviceExecutionCapabilities = CL_DEVICE_EXECUTION_CAPABILITIES,
  DeviceQueueProperties = CL_DEVICE_QUEUE_PROPERTIES,
  DeviceName = CL_DEVICE_NAME,
  DeviceVendor = CL_DEVICE_VENDOR,
  DriverVersion = CL_DRIVER_VERSION,
  DeviceProfile = CL_DEVICE_PROFILE,
  DeviceVersion = CL_DEVICE_VERSION,
  DeviceExtensions = CL_DEVICE_EXTENSIONS,
  DevicePlatform = CL_DEVICE_PLATFORM,
  DevicePreferredVectorWidthHalf = CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF,
  DeviceHostUnifiedMemory = CL_DEVICE_HOST_UNIFIED_MEMORY,
  DeviceNativeVectorWidthChar = CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR,
  DeviceNativeVectorWidthShort = CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT,
  DeviceNativeVectorWidthInt = CL_DEVICE_NATIVE_VECTOR_WIDTH_INT,
  DeviceNativeVectorWidthLong = CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG,
  DeviceNativeVectorWidthFloat = CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT,
  DeviceNativeVectorWidthDouble = CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE,
  DeviceNativeVectorWidthHalf = CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF,
  DeviceOpenclCVersion = CL_DEVICE_OPENCL_C_VERSION
};

/* cl_device_fp_config */
enum DeviceFPConfig {
  FpDenorm = CL_FP_DENORM,
  FpInfNan = CL_FP_INF_NAN,
  FpRoundToNearest = CL_FP_ROUND_TO_NEAREST,
  FpRoundToZero = CL_FP_ROUND_TO_ZERO,
  FpRoundToInf = CL_FP_ROUND_TO_INF,
  FpFma = CL_FP_FMA,
  FpSoftFloat = CL_FP_SOFT_FLOAT
};

/* cl_device_mem_cache_type */
enum DeviceMemCacheType {
  None = CL_NONE,
  ReadOnlyCache = CL_READ_ONLY_CACHE,
  ReadWriteCache = CL_READ_WRITE_CACHE
};

/* cl_device_local_mem_type */
enum DeviceLocalMemType {
  Local = CL_LOCAL,
  Global = CL_GLOBAL
};

/* cl_device_exec_capabilities */
enum DeviceExecCapabilities {
  ExecKernel = CL_EXEC_KERNEL,
  ExecNativeKernel = CL_EXEC_NATIVE_KERNEL
};

/* cl_command_queue_properties */
enum CommandQueueProperties {
  QueueOutOfOrderExecModeEnable = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,
  QueueProfilingEnable = CL_QUEUE_PROFILING_ENABLE
};

/* cl_context_info */
enum ContextInfo {
  ContextReferenceCount = CL_CONTEXT_REFERENCE_COUNT,
  ContextDevices = CL_CONTEXT_DEVICES,
  ContextProperties = CL_CONTEXT_PROPERTIES,
  ContextNumDevices = CL_CONTEXT_NUM_DEVICES
};

/* cl_context_properties */
enum ClContextProperties {
  ClContextPlatform = CL_CONTEXT_PLATFORM
};

/* cl_command_queue_info */
enum CommandQueueInfo {
  QueueContext = CL_QUEUE_CONTEXT,
  QueueDevice = CL_QUEUE_DEVICE,
  QueueReferenceCount = CL_QUEUE_REFERENCE_COUNT,
  QueueProperties = CL_QUEUE_PROPERTIES
};

/* cl_mem_flags */
enum MemFlags {
  MemReadWrite = CL_MEM_READ_WRITE,
  MemWriteOnly = CL_MEM_WRITE_ONLY,
  MemReadOnly = CL_MEM_READ_ONLY,
  MemUseHostPtr = CL_MEM_USE_HOST_PTR,
  MemAllocHostPtr = CL_MEM_ALLOC_HOST_PTR,
  MemCopyHostPtr = CL_MEM_COPY_HOST_PTR
};

/* cl_channel_order */
enum ClChannelOrder {
  ClR = CL_R,
  ClA = CL_A,
  ClRg = CL_RG,
  ClRa = CL_RA,
  ClRgb = CL_RGB,
  ClRgba = CL_RGBA,
  ClBgra = CL_BGRA,
  ClArgb = CL_ARGB,
  ClIntensity = CL_INTENSITY,
  ClLuminance = CL_LUMINANCE,
  ClRx = CL_Rx,
  ClRgx = CL_RGx,
  ClRgbx = CL_RGBx
};

/* cl_channel_type */
enum ClChannelType {
  ClSnormInt8 = CL_SNORM_INT8,
  ClSnormInt16 = CL_SNORM_INT16,
  ClUnormInt8 = CL_UNORM_INT8,
  ClUnormInt16 = CL_UNORM_INT16,
  ClUnormShort565 = CL_UNORM_SHORT_565,
  ClUnormShort555 = CL_UNORM_SHORT_555,
  ClUnormInt101010 = CL_UNORM_INT_101010,
  ClSignedInt8 = CL_SIGNED_INT8,
  ClSignedInt16 = CL_SIGNED_INT16,
  ClSignedInt32 = CL_SIGNED_INT32,
  ClUnsignedInt8 = CL_UNSIGNED_INT8,
  ClUnsignedInt16 = CL_UNSIGNED_INT16,
  ClUnsignedInt32 = CL_UNSIGNED_INT32,
  ClHalfFloat = CL_HALF_FLOAT,
  ClFloat = CL_FLOAT
};

/* cl_mem_object_type */
enum MemObjectType {
  MemObjectBuffer = CL_MEM_OBJECT_BUFFER,
  MemObjectImage2D = CL_MEM_OBJECT_IMAGE2D,
  MemObjectImage3D = CL_MEM_OBJECT_IMAGE3D,
};

/* cl_mem_info */
enum MemInfo {
  MemType = CL_MEM_TYPE,
  MemFlags = CL_MEM_FLAGS,
  MemSize = CL_MEM_SIZE,
  MemHostPtr = CL_MEM_HOST_PTR,
  MemMapCount = CL_MEM_MAP_COUNT,
  MemReferenceCount = CL_MEM_REFERENCE_COUNT,
  MemContext = CL_MEM_CONTEXT,
  MemAssociatedMemobject = CL_MEM_ASSOCIATED_MEMOBJECT,
  MemOffset = CL_MEM_OFFSET
};

/* cl_image_info */
enum ImageInfo {
  ImageFormat = CL_IMAGE_FORMAT,
  ImageElementSize = CL_IMAGE_ELEMENT_SIZE,
  ImageRowPitch = CL_IMAGE_ROW_PITCH,
  ImageSlicePitch = CL_IMAGE_SLICE_PITCH,
  ImageWidth = CL_IMAGE_WIDTH,
  ImageHeight = CL_IMAGE_HEIGHT,
  ImageDepth = CL_IMAGE_DEPTH
};

/* cl_addressing_mode */
enum AddressingMode {
  AddressNone = CL_ADDRESS_NONE,
  AddressClampToEdge = CL_ADDRESS_CLAMP_TO_EDGE,
  AddressClamp = CL_ADDRESS_CLAMP,
  AddressRepeat = CL_ADDRESS_REPEAT,
  AddressMirroredRepeat = CL_ADDRESS_MIRRORED_REPEAT
};

/* cl_filter_mode */
enum FilterMode {
  FilterNearest = CL_FILTER_NEAREST,
  FilterLinear = CL_FILTER_LINEAR
};

/* cl_sampler_info */
enum SamplerInfo {
  SamplerReferenceCount = CL_SAMPLER_REFERENCE_COUNT,
  SamplerContext = CL_SAMPLER_CONTEXT,
  SamplerNormalizedCoords = CL_SAMPLER_NORMALIZED_COORDS,
  SamplerAddressingMode = CL_SAMPLER_ADDRESSING_MODE,
  SamplerFilterMode = CL_SAMPLER_FILTER_MODE
};

/* cl_map_flags */
enum MapFlags {
  MapRead = CL_MAP_READ,
  MapWrite = CL_MAP_WRITE
};

/* cl_program_info */
enum ProgramInfo {
  ProgramReferenceCount = CL_PROGRAM_REFERENCE_COUNT,
  ProgramContext = CL_PROGRAM_CONTEXT,
  ProgramNumDevices = CL_PROGRAM_NUM_DEVICES,
  ProgramDevices = CL_PROGRAM_DEVICES,
  ProgramSource = CL_PROGRAM_SOURCE,
  ProgramBinarySizes = CL_PROGRAM_BINARY_SIZES,
  ProgramBinaries = CL_PROGRAM_BINARIES
};

/* cl_program_build_info */
enum ProgramBuildInfo {
  ProgramBuildStatus = CL_PROGRAM_BUILD_STATUS,
  ProgramBuildOptions = CL_PROGRAM_BUILD_OPTIONS,
  ProgramBuildLog = CL_PROGRAM_BUILD_LOG
};

/* cl_build_status */
enum BuildStatus {
  BuildSuccess = CL_BUILD_SUCCESS,
  BuildNone = CL_BUILD_NONE,
  BuildError = CL_BUILD_ERROR,
  BuildInProgress = CL_BUILD_IN_PROGRESS
};

/* cl_kernel_info */
enum KernelInfo {
  KernelFunctionName = CL_KERNEL_FUNCTION_NAME,
  KernelNumArgs = CL_KERNEL_NUM_ARGS,
  KernelReferenceCount = CL_KERNEL_REFERENCE_COUNT,
  KernelContext = CL_KERNEL_CONTEXT,
  KernelProgram = CL_KERNEL_PROGRAM
};

/* cl_kernel_work_group_info */
enum KernelWorkGroupInfo {
  KernelWorkGroupSize = CL_KERNEL_WORK_GROUP_SIZE,
  KernelCompileWorkGroupSize = CL_KERNEL_COMPILE_WORK_GROUP_SIZE,
  KernelLocalMemSize = CL_KERNEL_LOCAL_MEM_SIZE,
  KernelPreferredWorkGroupSizeMultiple = CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
  KernelPrivateMemSize = CL_KERNEL_PRIVATE_MEM_SIZE
};

/* cl_event_info */
enum EventInfo {
  EventCommandQueue = CL_EVENT_COMMAND_QUEUE,
  EventCommandType = CL_EVENT_COMMAND_TYPE,
  EventReferenceCount = CL_EVENT_REFERENCE_COUNT,
  EventCommandExecutionStatus = CL_EVENT_COMMAND_EXECUTION_STATUS,
  EventContext = CL_EVENT_CONTEXT
};

/* cl_command_type */
enum CommandType {
  CommandNdrangeKernel = CL_COMMAND_NDRANGE_KERNEL,
  CommandTask = CL_COMMAND_TASK,
  CommandNativeKernel = CL_COMMAND_NATIVE_KERNEL,
  CommandReadBuffer = CL_COMMAND_READ_BUFFER,
  CommandWriteBuffer = CL_COMMAND_WRITE_BUFFER,
  CommandCopyBuffer = CL_COMMAND_COPY_BUFFER,
  CommandReadImage = CL_COMMAND_READ_IMAGE,
  CommandWriteImage = CL_COMMAND_WRITE_IMAGE,
  CommandCopyImage = CL_COMMAND_COPY_IMAGE,
  CommandCopyImageToBuffer = CL_COMMAND_COPY_IMAGE_TO_BUFFER,
  CommandCopyBufferToImage = CL_COMMAND_COPY_BUFFER_TO_IMAGE,
  CommandMapBuffer = CL_COMMAND_MAP_BUFFER,
  CommandMapImage = CL_COMMAND_MAP_IMAGE,
  CommandUnmapMemObject = CL_COMMAND_UNMAP_MEM_OBJECT,
  CommandMarker = CL_COMMAND_MARKER,
  CommandAcquireGlObjects = CL_COMMAND_ACQUIRE_GL_OBJECTS,
  CommandReleaseGlObjects = CL_COMMAND_RELEASE_GL_OBJECTS,
  CommandReadBufferRect = CL_COMMAND_READ_BUFFER_RECT,
  CommandWriteBufferRect = CL_COMMAND_WRITE_BUFFER_RECT,
  CommandCopyBufferRect = CL_COMMAND_COPY_BUFFER_RECT,
  CommandUser = CL_COMMAND_USER
};

/* command execution status */
enum ClCommandExecStatus {
  ClComplete = CL_COMPLETE,
  ClRunning = CL_RUNNING,
  ClSubmitted = CL_SUBMITTED,
  ClQueued = CL_QUEUED
};

/* cl_buffer_create_type */
enum BufferCreateType {
  BufferCreateTypeRegion = CL_BUFFER_CREATE_TYPE_REGION
};

/* cl_profiling_info */
enum ProfilingInfo {
  ProfilingCommandQueued = CL_PROFILING_COMMAND_QUEUED,
  ProfilingCommandSubmit = CL_PROFILING_COMMAND_SUBMIT,
  ProfilingCommandStart = CL_PROFILING_COMMAND_START,
  ProfilingCommandEnd = CL_PROFILING_COMMAND_END
};


text:
<!DOCTYPE html>

		<title>Time Management Blog</title>
		<link rel="stylesheet" href="stylesheets/time_management_blog_.css">

Pure Motion

Soup of the Day

Time Management

What is your biggest time management challenge with during Phase 0?

I actually do pretty well with time management, however I work during the day and I work asynchronously for a university - this means I am almost always on.

I go to work each day until 5:00.  I get home around 5:15 - short commute time is awesome!  I jump on the computer.  I then eat dinner with the family.  I then check up on my uni-students.  I then jump back on the computer.  I can stay focused on a topic for long periods of time.  Truthfully, I am having the hardest time with all of the, for me, new ins-n-outs of all the new accessories: +Google, Communities, Hangouts, Pairing, GPS, GitHub(did I only synch it to myself or also share it with the instructors.)

How will you combat that?

I will succeed by never giving up, by working with others, and by taking the necessary time to relax and regroup.

What techniques will you try?

When I hit a wall, I find that getting up and walking around and thinking through the problem helps.  I think the physical break as well as the actual walking helps shift gears in my mind.

I also find that reading something challenging, but non-Program related, like Philosophy, helps me "recenter/relax".  I think that this is because it requires me to stop.

Physical excerise is very helpful.  I am more productive.

What is your overall plan for Phase 0?

Work, Program, Family, Program, Individual Non-program time.

Just keep swimming... :)

2014, The Happiness Company


text:
/**
 * PortfolioAccountSummaryController
 * @namespace portfolio.account.summary.controller
 */

(function () {

    'use strict';

    angular
        .module('portfolio.account.summary')
        .controller('AccountSummaryController',
                    AccountSummaryController);

    AccountSummaryController.$inject = [ '$timeout', '$q', '$location',
                                         'Positions',
                                         'Securities', 'Accounts',
                                         'Currencies', 'portfolioConfig'];

    function AccountSummaryController($timeout, $q, $location, Positions,
                                      Securities, Accounts, Currencies,
                                      portfolioConfig) {
        var vm = this;

        vm.sortReverse = false;
        vm.sortColumn = '$key';

        /* Get the account id from URL */
        var accountID = $location.path().split("/")[3];

        var promises = {
            positions: Positions.all(accountID),
            securities: Securities.all(),
            accounts: Accounts.all(),
            currencies: Currencies.all(),
        }

        /*
           for now, Securities.all() returns an array, dictionary needed to
           be able to easily map ticker to name
        */
        vm.securities_d = {};

        vm.total_mktval = 0;
        vm.total_day_change = 0;

        activate();

        /**
         * @name activate
         * @desc
         * @memberOf portfolio.accountsummary.controller.AccountSummaryController
         */
        function activate() {

            $q.all(promises).then(promisesSuccessFn, promisesErrorFn);

            /**
             * @name positionsSuccessFn
             * @desc
             */
            function promisesSuccessFn(data, status, headers, config) {
                vm.positions = data.positions.data;
                vm.securities = data.securities.data;
                vm.accounts = data.accounts.data;
                vm.currencies = data.currencies.data;
                getLivePrices();
            }

            function promisesErrorFn(data, status, headers, config) {
                console.log('promisesErrorFn', data);
            }
        }

        function getLivePrices() {

            var i, delay, cumulative_delay = 0;
            var minTime = portfolioConfig.APIMinWaitTime;
            var maxTime = portfolioConfig.APIMinWaitTime;
            var refreshRate = 15; // minutes
            var ticker;

            for(i=0; i<vm.securities.length; i++) {
                ticker = vm.securities[i].ticker;
                if ( ticker === 'N/A' ) {
                    continue;
                }
                vm.securities_d[ticker] = vm.securities[i].name;
                delay = Math.random()*(maxTime-minTime+1)+minTime;
                cumulative_delay += delay;
                console.log(ticker, cumulative_delay, delay);
                /* call getQuoteForSecurity with 'ticker' argument */
                $timeout(getQuoteForSecurity, cumulative_delay, true, ticker, 'google-local');

            }

            vm.liveTimer = $timeout(function () {
                getLivePrices();
            }, refreshRate*60*1000);

            function getQuoteForSecurity(ticker, provider) {
                /* Stupid workaround for lack of default parameters ... */
                provider  = (typeof provider !== 'undefined') ?
                        provider : 'yahoo';
                /* Two possible providers for quote, Google and Yahoo */
                switch(provider) {
                    case 'yahoo':
                    Positions.yahoo_quote(ticker)
                        .then(positionsLiveSuccessYahooFn,
                              positionsLiveErrorYahooFn);
                    break;
                    case 'google':
                    Positions.google_quote(ticker)
                        .then(positionsLiveSuccessFn, positionsLiveErrorFn);
                    break;
                    case 'google-local':
                    Positions.google_local_quote(ticker)
                        .then(positionsLiveSuccessGoogleLocalFn,
                              positionsLiveErrorGoogleLocalFn);
                }
            }

            function positionsLiveSuccessGoogleLocalFn(data) {
                if  (!data.data) {
                    console.log("ei ollu");
                }

                var result = data.data;
                var ticker = result.ticker;
                var currency = result.currency;
                var price = result.price;
                var changePercentage = result.change_percentage;
                var change = result.change;
                var lastTrade = result.date;

                populateSecurityData(ticker, currency, price,
                                     changePercentage, change,
                                     lastTrade);
            }

            function positionsLiveErrorGoogleLocalFn(data) {
                console.log('GoogleLocal Failed', data);
            }

            function positionsLiveSuccessYahooFn(data, status, headers, config) {

                var result;
                var ticker;
                var currency;
                var price;
                var changePercentage;
                var change;
                var lastTrade;

                /* Yahoo returns 'null' as value for every field if we're
                 * asking for quote for unknown ticker
                 * ... or it might not return 'results' at all
                 * ... or eg. Change can be null if there're no transactions
                 * for today
                 */
                if ( data.data.query.results !== null ) {
                    result = data.data.query.results.quote;
                    ticker = result.symbol;
                    currency = result.Currency;
                    price = result.LastTradePriceOnly;
                    changePercentage = result.ChangeinPercent;
                    change = result.Change;
                    lastTrade = result.LastTradeDate;
                }
                if (  change === null || result === undefined ) {
                    return;
                }

                /* Strip off % character */
                changePercentage = changePercentage.slice(0, -1);

                populateSecurityData(ticker, currency, price,
                                     changePercentage, change,
                                     lastTrade);
            }

            function positionsLiveSuccessFn(data, status, headers, config) {

                var result = data[0];
                var ticker = result['t'];
                var currency = result['l_cur'];
                var price = result['lt_dts'];
                var changePercentage = result['cp'];
                var change = result['c'];
                var lastTrade = result['lt_dts'];

                /* Determine currency from Google's result */
                currency = getCurrency(currency);
                populateSecurityData(ticker, currency, price,
                                     changePercentage, change,
                                     lastTrade);
            }

            function populateSecurityData(ticker, currency, price,
                                          changePercentage,
                                          change, lastTrade) {

                var securityName;
                var securityCurrency;
                var ltDateSecs;

                if (typeof vm.positions === 'undefined') {
                    /* It should be impossible to get here with
                       vm.positions undefined, but just in case, do nothing  */
                    ;
                }
                else {
                    /* If ticker is not found, Yahoo returns null */
                    if ( typeof ticker !== 'undefined' ||  ticker !== null) {
                        securityName = vm.securities_d[ticker];
                        securityCurrency = currency;
                        fx.base = vm.currencies['base'];
                        fx.rates = vm.currencies.rates;
                        /*
                           vm.positions has securities whose count is
                           greater than zero. However, Securities.all()
                           service returns all securities in DB. Hence
                           it is possible that vm.positions[securityName]
                           is not defined
                        */
                        if ( typeof vm.positions[securityName] !== 'undefined' ) {
                            /* l is latest value */
                            vm.positions[securityName]['price'] = price;
                            vm.positions[securityName]['change'] = change;
                            vm.positions[securityName]['change_percentage'] = changePercentage;
                            /* parse return milliseconds, second wanted */
                            ltDateSecs = Date.parse(lastTrade) / 1000;
                            vm.positions[securityName]['latest_date'] =
                                moment.unix(ltDateSecs).format('YYYY-MM-DD');
                            /* convert currency uned in security price
                               to base currency and use the converted
                               value as market value for the security in
                               questinon
                            */
                            vm.positions[securityName]['mktval'] =
                                fx(vm.positions[securityName]['price'] *
                                vm.positions[securityName]['shares'])
                                .from(securityCurrency).to(fx.base);
                            vm.positions[securityName]['day_change'] =
                                vm.positions[securityName]['shares'] *
                                vm.positions[securityName]['change'];
                            if (typeof vm.positions[securityName]['day_change'] !== 'undefined') {
                                vm.positions[securityName]['day_change'] =
                                    fx(vm.positions[securityName]['day_change'])
                                    .from(securityCurrency)
                                    .to(fx.base);
                            }
                            // Update market value & daily change
                            vm.total_mktval = 0;
                            vm.total_day_change = 0;
                            for (var position in vm.positions) {
                                if (vm.positions.hasOwnProperty(position)) {
                                    vm.total_mktval +=
                                        vm.positions[position]['mktval'];
                                    if (typeof vm.positions[position]['day_change'] !== 'undefined') {
                                        vm.total_day_change +=
                                            vm.positions[position]['day_change'];
                                        console.log(vm.positions[position]);
                                        console.log(vm.positions[position]['day_change']);
                                    }
                                }
                            }
                        }
                    }
                }

            }
            function positionsLiveErrorYahooFn(data, status, headers, config) {
                console.log(data);
                console.log("Failed fetching data from Yahoo");
            }

            function positionsLiveErrorFn(data) {
                if (data.statusText === 'error') {
                    console.log('LiveError: Ketuiksi meni', data);
                }
                else {
                    console.log('LiveError', data);
                }
            }

            function getCurrency(l_cur) {
                /*
                 * l_cur represents lates value with currency
                 */
                if (l_cur.indexOf("\u20ac") !== -1 ) {
                    return 'EUR';
                } else {
                    return 'USD';
                }
            }
        }
    }
})();


text:
describe("Audition JavaScript Tests", function () {

    it("SpecRunner runs", function () {
        expect(JavaScriptAudition.itRuns()).toBeTruthy();
    });

    describe("Test Number and Roman numeral conversion", function () {

        it("Test Border", function () {
            expect(numberToRoman(0)).toEqual("The number is invalid");
            expect(numberToRoman(3001)).toEqual("The number is invalid");
        }); //end test border

        it("Test numberToRomanOnes", function () {
            expect(numberToRoman(1)).toEqual("I");
            expect(numberToRoman(2)).toEqual("II");
            expect(numberToRoman(3)).toEqual("III");
            expect(numberToRoman(4)).toEqual("IV");
            expect(numberToRoman(5)).toEqual("V");
            expect(numberToRoman(6)).toEqual("VI");
            expect(numberToRoman(7)).toEqual("VII");
            expect(numberToRoman(8)).toEqual("VIII");
            expect(numberToRoman(9)).toEqual("IX");
        }); //end test ones

        it("Test numberToRomanTens", function () {
            expect(numberToRoman(10)).toEqual("X");
            expect(numberToRoman(11)).toEqual("XI");
            expect(numberToRoman(12)).toEqual("XII");
            expect(numberToRoman(15)).toEqual("XV");
            expect(numberToRoman(22)).toEqual("XXII");
            expect(numberToRoman(32)).toEqual("XXXII");
            expect(numberToRoman(44)).toEqual("XLIV");
            expect(numberToRoman(29)).toEqual("XXIX");
        }); //end test tens

        it("Test numberToRomanHundreds", function () {
            expect(numberToRoman(100)).toEqual("C");
            expect(numberToRoman(219)).toEqual("CCXIX");
            expect(numberToRoman(348)).toEqual("CCCXLVIII");
            expect(numberToRoman(172)).toEqual("CLXXII");
            expect(numberToRoman(893)).toEqual("DCCCXCIII");
            expect(numberToRoman(962)).toEqual("CMLXII");
            expect(numberToRoman(321)).toEqual("CCCXXI");
            expect(numberToRoman(563)).toEqual("DLXIII");
        }); //end test hundreds

        it("Test numberToRomanThousands", function () {
            expect(numberToRoman(1000)).toEqual("M");
            expect(numberToRoman(1123)).toEqual("MCXXIII");
            expect(numberToRoman(3000)).toEqual("MMM");
            expect(numberToRoman(1238)).toEqual("MCCXXXVIII");
            expect(numberToRoman(2983)).toEqual("MMCMLXXXIII");
            expect(numberToRoman(2787)).toEqual("MMDCCLXXXVII");
            expect(numberToRoman(1980)).toEqual("MCMLXXX");
            expect(numberToRoman(2345)).toEqual("MMCCCXLV");
        }); //end test thousands

        it("Test RomanToNumOnes", function(){
            expect(romanToNumber("I")).toEqual(1);
            expect(romanToNumber("II")).toEqual(2);
            expect(romanToNumber("III")).toEqual(3);
            expect(romanToNumber("IV")).toEqual(4);
            expect(romanToNumber("V")).toEqual(5);
            expect(romanToNumber("VI")).toEqual(6);
            expect(romanToNumber("VII")).toEqual(7);
            expect(romanToNumber("VIII")).toEqual(8);
            expect(romanToNumber("IX")).toEqual(9);
        });

        it("Test RomanToNumTens", function(){
            expect(romanToNumber("X")).toEqual(10);
            expect(romanToNumber("XI")).toEqual(11);
            expect(romanToNumber("XII")).toEqual(12);
            expect(romanToNumber("XXVIII")).toEqual(28);
            expect(romanToNumber("XLIV")).toEqual(44);
            expect(romanToNumber("XLVI")).toEqual(46);
            expect(romanToNumber("XCVIII")).toEqual(98);
            expect(romanToNumber("XXIII")).toEqual(23);
        });

        it("Test RomanToNumHundreds", function(){
            expect(romanToNumber("C")).toEqual(100);
            expect(romanToNumber("CMXCIX")).toEqual(999);
            expect(romanToNumber("CDXXXII")).toEqual(432);
            expect(romanToNumber("DLXVII")).toEqual(567);
            expect(romanToNumber("DCCCLXXVI")).toEqual(876);
            expect(romanToNumber("CXXIII")).toEqual(123);
            expect(romanToNumber("DCLXX")).toEqual(670);
            expect(romanToNumber("DCCLXXXIX")).toEqual(789);
        });

        it("Test RomanToNumThousands", function(){
            expect(romanToNumber("M")).toEqual(1000);
            expect(romanToNumber("MMM")).toEqual(3000);
            expect(romanToNumber("MMCCXXXII")).toEqual(2232);
            expect(romanToNumber("MMCCCXXVIII")).toEqual(2328);
            expect(romanToNumber("MCCLXXXIX")).toEqual(1289);
            expect(romanToNumber("MCMXC")).toEqual(1990);
            expect(romanToNumber("MCMLXXVIII")).toEqual(1978);
            expect(romanToNumber("MMCCCIX")).toEqual(2309);
        });

    }); //end add your test

});


text:
var settings = require('../tests/settings.json');

casper.test.begin('editor tests', function(test) {
    casper.start(settings.baseUrl, function() {
        this.echo('Visiting: ' + settings.baseUrl, 'INFO');
        test.assertHttpStatus(200);

        casper.echo('Changing viewport to: ' + settings.viewport.width + 'x' + settings.viewport.height);
        casper.viewport(settings.viewport.width, settings.viewport.height);

        // Files to test
        var files = ['alpha', 'beta', 'gamma'];
        var prefix = 'new-'; // prefix for renamed file
        var filename;
        casper.eachThen(files, function (file) {
            filename = file.data;

            casper.echo('Creating file: ' + filename, 'INFO');

            // Create file
            casper.then(function () {
                this.waitForSelector('#create-file-input', function () {
                    this.sendKeys('#create-file-input', filename);
                });
            });
            casper.then(function () {
                this.waitForSelector('#create-file-button', function () {
                    this.click('#create-file-button');
                });
            });
            casper.then(function () {
                test.assertExists('#file-list a[data-name="' + filename + '"]', 'File: ' + filename + ' appeared in filelist');
                var selectedFileCheck = this.evaluate(function (filename) {
                    return $('#file-list a.file-selected').data('name') == filename;
                }, filename);
                test.assert(selectedFileCheck, 'File ' + filename + ' selected in filelist');
            });

            var newFilename = prefix + filename;
            // Rename file
            casper.then(function () {
                this.click('li[data-name="' + filename + '"] .rename-file');
            });
            casper.then(function () {
                this.waitForSelector('#file-list input[placeholder="New filename"]', function () {
                    this.sendKeys('#file-list input[placeholder="New filename"]', newFilename, {reset: true});
                });
            });
            casper.then(function () {
                var fname = this.evaluate(function () {
                    return $('#file-list').text();
                });
                this.click('#file-list li[data-name="' + filename + '"] .accept-rename');
            });
            casper.then(function () {
                this.waitWhileVisible('#file-list input[placeholder="New filename"]', function () {
                    test.assertExists('#file-list li[data-name="' + newFilename + '"]', 'File: ' + newFilename + ' renamed successfully');
                });
            });

            // Edit
            var testText = '// Great news today\n// We even have tests with casperjs\n\n// File: ' + newFilename;
            casper.then(function () {
                this.evaluate(function (testText) {
                    window.editor.editor.getSession().setValue(testText);
                }, testText);
            });
            casper.then(function () {
                var editorText = this.evaluate(function () {
                    return window.editor.editor.getSession().getValue();
                });
                test.assertEquals(editorText, testText, 'Editor contains the entered text');
            });
        });

        // Remove all files
        casper.then(function () {
            this.echo('Removing all files', 'INFO');
        });
        var newFiles = files.map(function (filename) {
            return prefix + filename;
        });
        casper.eachThen(newFiles, function (file) {
            filename = file.data;

            casper.echo('Selecting file: ' + filename, 'INFO');
            casper.then(function () {
                this.click('#file-list li[data-name="' + filename + '"] .filename');
                this.waitForSelector('#file-list li[data-name="' + filename + '"] .file-selected', function () {
                    test.assertExists('#file-list li[data-name="' + filename + '"] .file-selected', 'File selected successfully');
                });
            });

            casper.echo('Removing file: ' + filename, 'INFO');
            // Remove file
            casper.then(function () {
                this.waitForSelector('#file-list li[data-name="' + filename + '"] .remove-file', function () {
                    casper.click('#file-list li[data-name="' + filename + '"] .remove-file');
                });
            });
            casper.then(function () {
                this.waitWhileSelector('#file-list li[data-name="' + filename + '"]', function () {
                    test.assertDoesntExist('#file-list li[data-name="' + filename + '"]', 'File: ' + filename + ' removed successfully');
                });
            });
        });
    }).run(function() {
        test.done();
    });
});


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>VY Embed Testing</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/app.css">

Embed Code Testing

Lightbox - Staging

Lightbox - Prod


text:
//
//  ConnectViewController.m
//  BLETR
//
//  Created by D500 user on 12/9/26.
//  Copyright (c) 2012 ISSC Technologies Corporation. All rights reserved.
//
#import "AppDelegate.h"
#import "ConnectViewController.h"
#import "SettingAlertView.h"

@interface ConnectViewController ()

@end

@implementation ConnectViewController

//@synthesize actionButton;
@synthesize activityIndicatorView;
@synthesize statusLabel;
@synthesize connectionStatus;
@synthesize versionLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
        backButton.title = @"Back";
        self.navigationItem.backBarButtonItem = backButton;

        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 28, 57, 57)];
        [titleLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Icon_old"]]];
        [titleLabel setTextAlignment:NSTextAlignmentCenter];//aaa
        self.navigationItem.titleView = titleLabel;
        [titleLabel release];

        refreshButton = [[UIBarButtonItem alloc] initWithTitle:@"Refresh" style:UIBarButtonItemStyleBordered target:self action:@selector(refreshDeviceList:)];
        scanButton = [[UIBarButtonItem alloc] initWithTitle:@"  Scan  " style:UIBarButtonItemStyleBordered target:self action:@selector(startScan)];
        cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(actionButtonCancelScan:)];
        uuidSettingButton = [[UIBarButtonItem alloc] initWithTitle:@"UUID Setting" style:UIBarButtonItemStyleBordered target:self action:@selector(manualUUIDSetting:)];

        connectedDeviceInfo = [NSMutableArray new];
        connectingList = [NSMutableArray new];

        deviceInfo = [[DeviceInfo alloc]init];
        refreshDeviceListTimer = nil;
        uuidSettingViewController = nil;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
    [self setConnectionStatus:LE_STATUS_IDLE];
    [versionLabel setText:[NSString stringWithFormat:@"BLETR 1.02, %s", __DATE__]];

}

- (void)viewDidAppear:(BOOL)animated {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [[appDelegate navigationController] setToolbarHidden:NO animated:NO];
    if([connectedDeviceInfo count] == 0) {
        if (uuidSettingViewController.isUUIDAvailable) {
            [self configureTransparentServiceUUID:uuidSettingViewController.transServiceUUIDStr txUUID:uuidSettingViewController.transTxUUIDStr rxUUID:uuidSettingViewController.transRxUUIDStr];
        }
        else
            [self configureTransparentServiceUUID:nil txUUID:nil rxUUID:nil];
    }
    [self startScan];
}

- (void)viewDidUnload
{
    [devicesTableView release];
    devicesTableView = nil;
    [self setVersionLabel:nil];
    [refreshButton release];
    refreshButton = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    NSLog(@"[ConnectViewController] didReceiveMemoryWarning");
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [devicesTableView release];
    [versionLabel release];
    [refreshButton release];
    [cancelButton release];
    [scanButton release];
    [uuidSettingViewController release];
    [uuidSettingButton release];
    [super dealloc];
}

- (void) displayDevicesList {
    [devicesTableView reloadData];
}

- (void) switchToMainFeaturePage {
    NSLog(@"[ConnectViewController] switchToMainFeaturePage");

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if ([[[appDelegate navigationController] viewControllers] containsObject:[deviceInfo mainViewController]] == FALSE) {
        [[appDelegate navigationController] pushViewController:[deviceInfo mainViewController] animated:YES];
    }
}

- (int) connectionStatus {
    return connectionStatus;
}

- (void) setConnectionStatus:(int)status {
    if (status == LE_STATUS_IDLE) {
        statusLabel.textColor = [UIColor redColor];
    }
    else {
        statusLabel.textColor = [UIColor blackColor];
    }
    connectionStatus = status;

    switch (status) {
        case LE_STATUS_IDLE:
            statusLabel.text = @"Idle";
            [activityIndicatorView stopAnimating];
            break;
        case LE_STATUS_SCANNING:
            [devicesTableView reloadData];
            statusLabel.text = @"Scanning...";
            [activityIndicatorView startAnimating];
            break;
        default:
            break;
    }
    [self updateButtonType];
}

- (IBAction)actionButtonCancelScan:(id)sender {
    NSLog(@"[ConnectViewController] actionButtonCancelScan");
    [self stopScan];
    [self setConnectionStatus:LE_STATUS_IDLE];
}

- (void)startScan {
    [super startScan];
    if ([connectingList count] > 0) {
        for (int i=0; i< [connectingList count]; i++) {
            MyPeripheral *connectingPeripheral = [connectingList objectAtIndex:i];

            if (connectingPeripheral.connectStaus == MYPERIPHERAL_CONNECT_STATUS_CONNECTING) {
                //NSLog(@"startScan add connecting List: %@",connectingPeripheral.advName);
                [devicesList addObject:connectingPeripheral];
            }
            else {
                [connectingList removeObjectAtIndex:i];
                //NSLog(@"startScan remove connecting List: %@",connectingPeripheral.advName);
            }
        }
    }
    [self setConnectionStatus:LE_STATUS_SCANNING];
}

- (void)stopScan {
    [super stopScan];
    if (refreshDeviceListTimer) {
        [refreshDeviceListTimer invalidate];
        refreshDeviceListTimer = nil;
    }
}

-(void)popToRootPage {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appDelegate.pageTransition == FALSE) {
        [[appDelegate navigationController] popToRootViewControllerAnimated:NO];
    }
    else {
        [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(popToRootPage) userInfo:nil repeats:NO];
    }
}

- (void)updateDiscoverPeripherals {
    [super updateDiscoverPeripherals];
    [devicesTableView reloadData];
}

- (void)updateMyPeripheralForDisconnect:(MyPeripheral *)myPeripheral {
    NSLog(@"updateMyPeripheralForDisconnect");//, %@", myPeripheral.advName);
    if (myPeripheral == controlPeripheral) {
        [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(popToRootPage) userInfo:nil repeats:NO];
    }

    for (int idx =0; idx< [connectedDeviceInfo count]; idx++) {
        DeviceInfo *tmpDeviceInfo = [connectedDeviceInfo objectAtIndex:idx];
        if (tmpDeviceInfo.myPeripheral == myPeripheral) {
            [connectedDeviceInfo removeObjectAtIndex:idx];
            //NSLog(@"updateMyPeripheralForDisconnect1");
            break;
        }
    }

    for (int idx =0; idx< [connectingList count]; idx++) {
        MyPeripheral *tmpPeripheral = [connectingList objectAtIndex:idx];
        if (tmpPeripheral == myPeripheral) {
            [connectingList removeObjectAtIndex:idx];
            //NSLog(@"updateMyPeripheralForDisconnect2");
            break;
        }
        else{
            //NSLog(@"updateMyPeripheralForDisconnect3 %@, %@", tmpPeripheral.advName, myPeripheral.advName);
        }

    }

    [self displayDevicesList];
    [self updateButtonType];

    if(connectionStatus == LE_STATUS_SCANNING){
        [self stopScan];
        [self startScan];
        [devicesTableView reloadData];
    }
}

- (void)updateMyPeripheralForNewConnected:(MyPeripheral *)myPeripheral {
    NSLog(@"[ConnectViewController] updateMyPeripheralForNewConnected");
    DeviceInfo *tmpDeviceInfo = [[DeviceInfo alloc]init];
    tmpDeviceInfo.mainViewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    tmpDeviceInfo.mainViewController.connectedPeripheral = myPeripheral;
    tmpDeviceInfo.myPeripheral = myPeripheral;
    tmpDeviceInfo.myPeripheral.connectStaus = myPeripheral.connectStaus;
   /*Connected List Filter*/
    bool b = FALSE;
    for (int idx =0; idx< [connectedDeviceInfo count]; idx++) {
        DeviceInfo *tmpDeviceInfo = [connectedDeviceInfo objectAtIndex:idx];
        if (tmpDeviceInfo.myPeripheral == myPeripheral) {
            b = TRUE;
            break;
        }
    }
    if (!b) {
        [connectedDeviceInfo addObject:tmpDeviceInfo];
    }
    else{
        NSLog(@"Connected List Filter!");
    }

    for (int idx =0; idx< [connectingList count]; idx++) {
        MyPeripheral *tmpPeripheral = [connectingList objectAtIndex:idx];
        if (tmpPeripheral == myPeripheral) {
            //NSLog(@"connectingList removeObject:%@",tmpPeripheral.advName);
            [connectingList removeObjectAtIndex:idx];
            break;
        }
    }

    for (int idx =0; idx< [devicesList count]; idx++) {
        MyPeripheral *tmpPeripheral = [devicesList objectAtIndex:idx];
        if (tmpPeripheral == myPeripheral) {
            //NSLog(@"devicesList removeObject:%@",tmpPeripheral.advName);
            [devicesList removeObjectAtIndex:idx];
            break;
        }
    }
    [self displayDevicesList];
    [self updateButtonType];
}

// DataSource methods
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSLog(@"[ConnectViewController] numberOfRowsInSection,device count = %d", [devicesList count]);
    switch (section) {
        case 0:
            return [connectedDeviceInfo count];
        case 1:
            return [devicesList count];
        default:
            return 0;
        }
    }

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell;

    switch (indexPath.section) {
        case 0:
        {
            //NSLog(@"[ConnectViewController] CellForRowAtIndexPath section 0, Row = %d",[indexPath row]);
            cell = [tableView dequeueReusableCellWithIdentifier:@"connectedList"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"connectedList"] autorelease];
            }
            DeviceInfo *tmpDeviceInfo = [connectedDeviceInfo objectAtIndex:indexPath.row];

            cell.textLabel.text = tmpDeviceInfo.myPeripheral.advName;
            cell.detailTextLabel.text = @"connected";
            cell.accessoryView = nil;
            if (cell.textLabel.text == nil)
                cell.textLabel.text = @"Unknow";

            UIButton *accessoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [accessoryButton addTarget:self action:@selector(actionButtonDisconnect:)  forControlEvents:UIControlEventTouchUpInside];
            accessoryButton.tag = indexPath.row;
            [accessoryButton setTitle:@"Disonnect" forState:UIControlStateNormal];
            [accessoryButton setFrame:CGRectMake(0,0,100,35)];
            cell.accessoryView  = accessoryButton;
        }
            break;

        case 1:
        {
            //NSLog(@"[ConnectViewController] CellForRowAtIndexPath section 1, Row = %d",[indexPath row]);

            cell = [tableView dequeueReusableCellWithIdentifier:@"devicesList"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"devicesList"] autorelease];
            }
            MyPeripheral *tmpPeripheral = [devicesList objectAtIndex:indexPath.row];
            cell.textLabel.text = tmpPeripheral.advName;
            cell.detailTextLabel.text = @"";
            cell.accessoryView = nil;
            if (tmpPeripheral.connectStaus == MYPERIPHERAL_CONNECT_STATUS_CONNECTING) {
                cell.detailTextLabel.text = @"connecting...";
                UIButton *accessoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                [accessoryButton addTarget:self action:@selector(actionButtonCancelConnect:)  forControlEvents:UIControlEventTouchUpInside];
                accessoryButton.tag = indexPath.row;
                [accessoryButton setTitle:@"Cancel" forState:UIControlStateNormal];
                [accessoryButton setFrame:CGRectMake(0,0,100,35)];
                cell.accessoryView  = accessoryButton;

            }

            if (cell.textLabel.text == nil)
                cell.textLabel.text = @"Unknow";
        }
            break;
    }

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

	NSString *title = nil;
	switch (section) {
        case 0:
            title = @"Connected Device:";
            break;
		case 1:
			title = @"Discovered Devices:";
			break;

		default:
			break;
	}
	return title;
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            //NSLog(@"[ConnectViewController] didSelectRowAtIndexPath section 0, Row = %d",[indexPath row]);
            deviceInfo = [connectedDeviceInfo objectAtIndex:indexPath.row];
            controlPeripheral = deviceInfo.myPeripheral;
            [self stopScan];
            [self setConnectionStatus:LE_STATUS_IDLE];
            [activityIndicatorView stopAnimating];
            if (refreshDeviceListTimer) {
                [refreshDeviceListTimer invalidate];
                refreshDeviceListTimer = nil;
            }
            [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(switchToMainFeaturePage) userInfo:nil repeats:NO];
        }
            break;
        case 1:
        {
            //Derek
            NSLog(@"[ConnectViewController] didSelectRowAtIndexPath section 0, Row = %d",[indexPath row]);
            int count = [devicesList count];
            if ((count != 0) && count > indexPath.row) {
                MyPeripheral *tmpPeripheral = [devicesList objectAtIndex:indexPath.row];
                if (tmpPeripheral.connectStaus != MYPERIPHERAL_CONNECT_STATUS_IDLE) {
                    //NSLog(@"Device is not idle - break");
                    break;
                }
                [self connectDevice:tmpPeripheral];
                tmpPeripheral.connectStaus = MYPERIPHERAL_CONNECT_STATUS_CONNECTING;
                [devicesList replaceObjectAtIndex:indexPath.row withObject:tmpPeripheral];
                [connectingList addObject:tmpPeripheral];
                [self displayDevicesList];
                [self updateButtonType];
            }
            break;
        }
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)refreshDeviceList:(id)sender {
    NSLog(@"[ConnectViewController] refreshDeviceList");
        [self stopScan];
        [self startScan];
        [devicesTableView reloadData];
}

- (IBAction)manualUUIDSetting:(id)sender {
    if (uuidSettingViewController == nil) {
        uuidSettingViewController = [[UUIDSettingViewController alloc] initWithNibName:@"UUIDSettingViewController" bundle:nil];
    }
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if ([[[appDelegate navigationController] viewControllers] containsObject:uuidSettingViewController] == FALSE) {
        [[appDelegate navigationController] pushViewController:uuidSettingViewController animated:YES];
    }
}

//Derek
- (IBAction)actionButtonDisconnect:(id)sender {
    //NSLog(@"[ConnectViewController] actionButtonDisconnect idx = %d",[sender tag]);
    int idx = [sender tag];
    DeviceInfo *tmpDeviceInfo = [connectedDeviceInfo objectAtIndex:idx];
    [self disconnectDevice:tmpDeviceInfo.myPeripheral];
}

//Derek
- (IBAction)actionButtonCancelConnect:(id)sender {
    //NSLog(@"[ConnectViewController] actionButtonCancelConnect idx = %d",[sender tag]);
    int idx = [sender tag];
    MyPeripheral *tmpPeripheral = [devicesList objectAtIndex:idx];
    tmpPeripheral.connectStaus = MYPERIPHERAL_CONNECT_STATUS_IDLE;
    [devicesList replaceObjectAtIndex:idx withObject:tmpPeripheral];

    for (int idx =0; idx< [connectingList count]; idx++) {
        MyPeripheral *tmpConnectingPeripheral = [connectingList objectAtIndex:idx];
        if (tmpConnectingPeripheral == tmpPeripheral) {
            [connectingList removeObjectAtIndex:idx];
            break;
        }
    }

    [self disconnectDevice:tmpPeripheral];
    [self displayDevicesList];
    [self updateButtonType];
}

- (void) updateButtonType {
    NSArray *toolbarItems = nil;
    switch (connectionStatus) {
        case LE_STATUS_IDLE:
            if (([connectedDeviceInfo count] > 0)||([connectingList count] > 0)) {
                toolbarItems = [[NSArray alloc] initWithObjects:scanButton, nil];
            }
            else {
                toolbarItems = [[NSArray alloc] initWithObjects:scanButton, uuidSettingButton, nil];
            }
            [self setToolbarItems:toolbarItems animated:NO];
            [toolbarItems release];
            break;
        case LE_STATUS_SCANNING:
            if (([connectedDeviceInfo count] > 0)||([connectingList count] > 0)) {
                toolbarItems = [[NSArray alloc] initWithObjects:refreshButton,cancelButton , nil];
            }
            else {
                toolbarItems = [[NSArray alloc] initWithObjects: refreshButton,cancelButton, uuidSettingButton, nil];
            }
            [self setToolbarItems:toolbarItems animated:NO];
            [toolbarItems release];
            break;
    }
}

@end


text:
package com.github.reikje.specifiers

trait SupportedStringConversion {
  /**
    * Returns the specifier which the subclass can convert, i.e. '''%u'''.
    * @return String
    */
  val specifier: String

  /**
    * Converts the given value into a String representation.
    * @param value a value that the subclass can convert
    * @return String
    */
  def convert(value: Any): String
}


text:
cask 'projectlibre' do
  version '1.8.0'
  sha256 '0132bcf33b7e792ed0693888982b1163e5397c7820329188f0f916b2e0246ec7'

  # sourceforge.net/projectlibre was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/projectlibre/ProjectLibre/#{version.major_minor}/ProjectLibre-#{version}.dmg"
  appcast 'https://sourceforge.net/projects/projectlibre/rss?path=/ProjectLibre'
  name 'ProjectLibre'
  homepage 'https://www.projectlibre.com/'

  app 'ProjectLibre.app'
end


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.storage.mem;

import java.util.Map;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import org.apache.aurora.scheduler.storage.QuotaStore;
import org.apache.aurora.scheduler.storage.entities.IResourceAggregate;

/**
 * An in-memory quota store.
 */
class MemQuotaStore implements QuotaStore.Mutable {

  private final Map<String, IResourceAggregate> quotas = Maps.newConcurrentMap();

  @Override
  public void deleteQuotas() {
    quotas.clear();
  }

  @Override
  public void removeQuota(String role) {
    quotas.remove(role);
  }

  @Override
  public void saveQuota(String role, IResourceAggregate quota) {
    quotas.put(role, quota);
  }

  @Override
  public Optional<IResourceAggregate> fetchQuota(String role) {
    return Optional.fromNullable(quotas.get(role));
  }

  @Override
  public Map<String, IResourceAggregate> fetchQuotas() {
    return ImmutableMap.copyOf(quotas);
  }
}


text:
import { Identification } from '../../index';

export class IdentificationSessionOutdatedError implements Error {
    public name: string;
    public message: string;
    constructor() {
        this.name = 'Session outdated';
        this.message = 'Original request is updated.';
    }
}

export class IdentificationRequesterUnmatchedError implements Error {
    public name: string;
    public message: string;
    constructor() {
        this.name = 'Requester unmatched.';
        this.message = 'Requester unmatched.';
    }
}

// このオブジェクトを作るのは難しい。リポジトリにアクセスして使って作らないといけないのでFactoryが必要
export class IdentificationSession {
    private originalRequest: Identification.Request;         // uid -> Request
    private snapshot: Identification.RequestSnapshot;
    private acceptedBy: Identification.User;
    private token: string;
    private receivedToken: string;

    // このセッションの有効性チェック
    validateSession(): boolean {
        // RULE: スナップショットとリクエストが同一であること
        return this.originalRequest.isIdentical( this.snapshot );
    }

    // 新しいリクエストを受け入れるときの有効性チェック
    validateNewRequest(): boolean {
        // RULE: 更新時の新しいリクエストの条件 = 同一ユーザかつ更新されている
        let res = ( this.originalRequest.isIdentical( this.snapshot ) )
               && ( this.originalRequest.isUpdated( this.snapshot ) );
        return res;
    }

    // 暫定: 乱数で6桁
    private generateToken(): string {
        let rnd: number;
        let tmp: string;
        let newToken: string;

        rnd = Math.floor( 100000 * Math.random() );
        tmp = '000000' + rnd.toString();
        newToken = tmp.slice( 6 - tmp.length );

        return newToken;
    }

    // セッションの更新(新しいリクエストを受け入れる)
    // 不変条件: トークンを新しくする
    updateSession() {
        if( !this.validateNewRequest() ){
            throw new IdentificationRequesterUnmatchedError;
        }
        this.updateToken();
        this.snapshot = this.originalRequest.takeSnapshot();
    }

    // 合言葉の更新
    // 不変条件: 更新と同時に受け取った合言葉も消す
    updateToken(): void {
        if( !this.validateSession() ){
            throw new IdentificationSessionOutdatedError;
        }
        // 新しい合言葉は絶対に一致しない
        this.receivedToken = '******';
        this.token = this.generateToken();
    }

    // 受け取った合言葉の入力
    receiveToken( receivedToken: string ) {
        if( !this.validateSession() ){
            throw new IdentificationSessionOutdatedError;
        }
        this.receivedToken = receivedToken;
    }

    // 合言葉の判定
    isTokenMatched(): boolean {
        return this.token === this.receivedToken;
    }

    getToken(): string {
        // 確認者には見せないようにする(アプリケーション層の仕事)
        return this.token;
    }

    // 本人確認実施
    identify(): Identification.UserIdentity {
        if( !this.validateSession() ){
            throw new IdentificationSessionOutdatedError;
        }
        return new Identification.UserIdentity(
                this.originalRequest.user,
                this.originalRequest.cid,
                this.acceptedBy,
                null );
    }
}


text:
package com.spotify.crunch.lib;

import com.google.common.collect.ImmutableMap;
import org.apache.crunch.PTable;
import org.apache.crunch.impl.mem.MemPipeline;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.*;
import static org.apache.crunch.types.avro.Avros.*;

public class AveragesTest {
  @Test
  public void testMeanValue() {
    PTable<String, Integer> testTable = MemPipeline.typedTableOf(
            tableOf(strings(), ints()),
            "a", 2,
            "a", 10,
            "b", 3,
            "c", 3,
            "c", 4,
            "c", 5);
    Map<String, Double> actual = Averages.meanValue(testTable).materializeToMap();
    Map<String, Double> expected = ImmutableMap.of(
            "a", 6.0,
            "b", 3.0,
            "c", 4.0
    );

    assertEquals(expected, actual);
  }

}


text:
class UpgradeComparisons < Sequel::Migration
  def marshal(v)
    [Marshal.dump(v)].pack('m')
  end

  def up
    alter_table(:comparisons) do
      add_column :lhs_type, String
      add_column :lhs_value, String
      add_column :operator, String
      add_column :rhs_type, String
      add_column :rhs_value, String
    end
    dataset = self[:comparisons]
    dataset.each do |comparison|
      dataset.filter(:id => comparison[:id]).update({
        :lhs_type => "field", :lhs_value => marshal(comparison[:field_1_id]),
        :rhs_type => "field", :rhs_value => marshal(comparison[:field_2_id]),
        :operator => "equals"
      })
    end
    alter_table(:comparisons) do
      drop_column :field_1_id
      drop_column :field_2_id
    end

    alter_table(:matchers) { drop_column(:comparator_name) }
    alter_table(:matchers_versions) { drop_column(:comparator_name) }
  end

  def down
    raise "This migration is not reversible."
  end
end


text:
#ifndef __GSL_MATRIX_CHAR_H__
#define __GSL_MATRIX_CHAR_H__

#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_char.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif

__BEGIN_DECLS

typedef struct
{
  size_t size1;
  size_t size2;
  size_t tda;
  char * data;
  gsl_block_char * block;
  int owner;
} gsl_matrix_char;

typedef struct
{
  gsl_matrix_char matrix;
} _gsl_matrix_char_view;

typedef _gsl_matrix_char_view gsl_matrix_char_view;

typedef struct
{
  gsl_matrix_char matrix;
} _gsl_matrix_char_const_view;

typedef const _gsl_matrix_char_const_view gsl_matrix_char_const_view;

/* Allocation */

gsl_matrix_char *
gsl_matrix_char_alloc (const size_t n1, const size_t n2);

gsl_matrix_char *
gsl_matrix_char_calloc (const size_t n1, const size_t n2);

gsl_matrix_char *
gsl_matrix_char_alloc_from_block (gsl_block_char * b,
                                   const size_t offset,
                                   const size_t n1,
                                   const size_t n2,
                                   const size_t d2);

gsl_matrix_char *
gsl_matrix_char_alloc_from_matrix (gsl_matrix_char * m,
                                    const size_t k1,
                                    const size_t k2,
                                    const size_t n1,
                                    const size_t n2);

gsl_vector_char *
gsl_vector_char_alloc_row_from_matrix (gsl_matrix_char * m,
                                        const size_t i);

gsl_vector_char *
gsl_vector_char_alloc_col_from_matrix (gsl_matrix_char * m,
                                        const size_t j);

void gsl_matrix_char_free (gsl_matrix_char * m);

/* Views */

_gsl_matrix_char_view
gsl_matrix_char_submatrix (gsl_matrix_char * m,
                            const size_t i, const size_t j,
                            const size_t n1, const size_t n2);

_gsl_vector_char_view
gsl_matrix_char_row (gsl_matrix_char * m, const size_t i);

_gsl_vector_char_view
gsl_matrix_char_column (gsl_matrix_char * m, const size_t j);

_gsl_vector_char_view
gsl_matrix_char_diagonal (gsl_matrix_char * m);

_gsl_vector_char_view
gsl_matrix_char_subdiagonal (gsl_matrix_char * m, const size_t k);

_gsl_vector_char_view
gsl_matrix_char_superdiagonal (gsl_matrix_char * m, const size_t k);

_gsl_matrix_char_view
gsl_matrix_char_view_array (char * base,
                             const size_t n1,
                             const size_t n2);

_gsl_matrix_char_view
gsl_matrix_char_view_array_with_tda (char * base,
                                      const size_t n1,
                                      const size_t n2,
                                      const size_t tda);

_gsl_matrix_char_view
gsl_matrix_char_view_vector (gsl_vector_char * v,
                              const size_t n1,
                              const size_t n2);

_gsl_matrix_char_view
gsl_matrix_char_view_vector_with_tda (gsl_vector_char * v,
                                       const size_t n1,
                                       const size_t n2,
                                       const size_t tda);

_gsl_matrix_char_const_view
gsl_matrix_char_const_submatrix (const gsl_matrix_char * m,
                                  const size_t i, const size_t j,
                                  const size_t n1, const size_t n2);

_gsl_vector_char_const_view
gsl_matrix_char_const_row (const gsl_matrix_char * m,
                            const size_t i);

_gsl_vector_char_const_view
gsl_matrix_char_const_column (const gsl_matrix_char * m,
                               const size_t j);

_gsl_vector_char_const_view
gsl_matrix_char_const_diagonal (const gsl_matrix_char * m);

_gsl_vector_char_const_view
gsl_matrix_char_const_subdiagonal (const gsl_matrix_char * m,
                                    const size_t k);

_gsl_vector_char_const_view
gsl_matrix_char_const_superdiagonal (const gsl_matrix_char * m,
                                      const size_t k);

_gsl_matrix_char_const_view
gsl_matrix_char_const_view_array (const char * base,
                                   const size_t n1,
                                   const size_t n2);

_gsl_matrix_char_const_view
gsl_matrix_char_const_view_array_with_tda (const char * base,
                                            const size_t n1,
                                            const size_t n2,
                                            const size_t tda);

_gsl_matrix_char_const_view
gsl_matrix_char_const_view_vector (const gsl_vector_char * v,
                                    const size_t n1,
                                    const size_t n2);

_gsl_matrix_char_const_view
gsl_matrix_char_const_view_vector_with_tda (const gsl_vector_char * v,
                                             const size_t n1,
                                             const size_t n2,
                                             const size_t tda);

/* Operations */

char   gsl_matrix_char_get(const gsl_matrix_char * m, const size_t i, const size_t j);
void    gsl_matrix_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char x);

char * gsl_matrix_char_ptr(gsl_matrix_char * m, const size_t i, const size_t j);
const char * gsl_matrix_char_const_ptr(const gsl_matrix_char * m, const size_t i, const size_t j);

void gsl_matrix_char_set_zero (gsl_matrix_char * m);
void gsl_matrix_char_set_identity (gsl_matrix_char * m);
void gsl_matrix_char_set_all (gsl_matrix_char * m, char x);

int gsl_matrix_char_fread (FILE * stream, gsl_matrix_char * m) ;
int gsl_matrix_char_fwrite (FILE * stream, const gsl_matrix_char * m) ;
int gsl_matrix_char_fscanf (FILE * stream, gsl_matrix_char * m);
int gsl_matrix_char_fprintf (FILE * stream, const gsl_matrix_char * m, const char * format);

int gsl_matrix_char_memcpy(gsl_matrix_char * dest, const gsl_matrix_char * src);
int gsl_matrix_char_swap(gsl_matrix_char * m1, gsl_matrix_char * m2);

int gsl_matrix_char_swap_rows(gsl_matrix_char * m, const size_t i, const size_t j);
int gsl_matrix_char_swap_columns(gsl_matrix_char * m, const size_t i, const size_t j);
int gsl_matrix_char_swap_rowcol(gsl_matrix_char * m, const size_t i, const size_t j);
int gsl_matrix_char_transpose (gsl_matrix_char * m);
int gsl_matrix_char_transpose_memcpy (gsl_matrix_char * dest, const gsl_matrix_char * src);

char gsl_matrix_char_max (const gsl_matrix_char * m);
char gsl_matrix_char_min (const gsl_matrix_char * m);
void gsl_matrix_char_minmax (const gsl_matrix_char * m, char * min_out, char * max_out);

void gsl_matrix_char_max_index (const gsl_matrix_char * m, size_t * imax, size_t *jmax);
void gsl_matrix_char_min_index (const gsl_matrix_char * m, size_t * imin, size_t *jmin);
void gsl_matrix_char_minmax_index (const gsl_matrix_char * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);

int gsl_matrix_char_isnull (const gsl_matrix_char * m);

int gsl_matrix_char_add (gsl_matrix_char * a, const gsl_matrix_char * b);
int gsl_matrix_char_sub (gsl_matrix_char * a, const gsl_matrix_char * b);
int gsl_matrix_char_mul_elements (gsl_matrix_char * a, const gsl_matrix_char * b);
int gsl_matrix_char_div_elements (gsl_matrix_char * a, const gsl_matrix_char * b);
int gsl_matrix_char_scale (gsl_matrix_char * a, const double x);
int gsl_matrix_char_add_constant (gsl_matrix_char * a, const double x);
int gsl_matrix_char_add_diagonal (gsl_matrix_char * a, const double x);

/***********************************************************************/
/* The functions below are obsolete                                    */
/***********************************************************************/
int gsl_matrix_char_get_row(gsl_vector_char * v, const gsl_matrix_char * m, const size_t i);
int gsl_matrix_char_get_col(gsl_vector_char * v, const gsl_matrix_char * m, const size_t j);
int gsl_matrix_char_set_row(gsl_matrix_char * m, const size_t i, const gsl_vector_char * v);
int gsl_matrix_char_set_col(gsl_matrix_char * m, const size_t j, const gsl_vector_char * v);

/* inline functions if you are using GCC */

#ifdef HAVE_INLINE
extern inline
char
gsl_matrix_char_get(const gsl_matrix_char * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
  if (i >= m->size1)
    {
      GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
    }
  else if (j >= m->size2)
    {
      GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
    }
#endif
  return m->data[i * m->tda + j] ;
}

extern inline
void
gsl_matrix_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char x)
{
#if GSL_RANGE_CHECK
  if (i >= m->size1)
    {
      GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
    }
  else if (j >= m->size2)
    {
      GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
    }
#endif
  m->data[i * m->tda + j] = x ;
}

extern inline
char *
gsl_matrix_char_ptr(gsl_matrix_char * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
  if (i >= m->size1)
    {
      GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
    }
  else if (j >= m->size2)
    {
      GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
    }
#endif
  return (char *) (m->data + (i * m->tda + j)) ;
}

extern inline
const char *
gsl_matrix_char_const_ptr(const gsl_matrix_char * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
  if (i >= m->size1)
    {
      GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
    }
  else if (j >= m->size2)
    {
      GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
    }
#endif
  return (const char *) (m->data + (i * m->tda + j)) ;
}

#endif

__END_DECLS

#endif /* __GSL_MATRIX_CHAR_H__ */


text:
/* eslint quotes: [0] */
/* eslint import/no-commonjs: [0] */

module.exports = require('./dist/config').default;