text:
'use strict'

const test = require('blue-tape')
const filterAnyway = require('../index').filterAnyway
const utils = require('./test-utils')

const generatePromise = utils.generatePromise
const checkTimeNear = utils.checkTimeNear

test('filterAnyway array should work correctly', t => {
  return filterAnyway([1, 2, 3, 4, 5, 6], i => generatePromise({result: i % 2 === 0}))
    .then(r => {
      t.deepEqual(r.results, [2, 4, 6], 'should keep only the odd values')
      t.deepEqual(r.errors, [undefined, undefined, undefined, undefined, undefined, undefined])
    })
})

test('filterAnyway array should work in parallel', t => {
  const startTime = Date.now()
  return filterAnyway([1, 2, 3, 4, 5, 6], i => generatePromise({result: i % 2 === 0, delay: 100}))
    .then(() => {
      checkTimeNear(t, startTime, 100)
    })
})

test('filterAnyway array should work correctly with []', t => {
  return filterAnyway([], () => t.fail('This function should never be called'))
    .then(r => {
      t.deepEqual(r.results, [])
      t.deepEqual(r.errors, [])
    })
})

test('filterAnyway array should go on if one fails', t => {
  return filterAnyway([1, 2, 3, 4, 5, 6], i => {
      if (i === 2 || i === 5) return generatePromise({err: new Error('DOOM')})
      return generatePromise({result: i % 2 === 0, delay: 100})
    })
    .then(r => {
      t.deepEqual(r.results, [4, 6], 'should keep only the odd values')
      t.deepEqual(r.errors[0], undefined)
      t.deepEqual(r.errors[1].message, 'DOOM')
      t.deepEqual(r.errors[2], undefined)
      t.deepEqual(r.errors[3], undefined)
      t.deepEqual(r.errors[4].message, 'DOOM')
      t.deepEqual(r.errors[5], undefined)
    })
})

test('filterAnyway array should receive the key too', t => {
  return filterAnyway([1, 2, 3, 4, 5, 6], (i, k) => generatePromise({result: i % 2 === 0 && k % 2 === 1}))
    .then(r => {
      t.deepEqual(r.results, [ 2, 4, 6 ], 'should have the key')
    })
})

test('filterAnyway object should work correctly', t => {
  return filterAnyway({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}, i => generatePromise({result: i % 2 === 0}))
    .then(r => {
      t.deepEqual(r.results, {2: 2, 4: 4, 6: 6}, 'should keep only the odd values')
      t.deepEqual(r.errors, {})
    })
})

test('filterAnyway object should work in parallel', t => {
  const startTime = Date.now()
  return filterAnyway({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}, i => generatePromise({result: i % 2 === 0, delay: 100}))
    .then(() => {
      checkTimeNear(t, startTime, 100)
    })
})

test('filterAnyway object should work correctly with {}', t => {
  return filterAnyway({}, () => t.fail('This function should never be called'))
    .then(r => {
      t.deepEqual(r.results, {})
      t.deepEqual(r.errors, {})
    })
})

test('filterAnyway object should go on if one fails', t => {
  return filterAnyway({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}, i => {
      if (i === 2 || i === 5) return generatePromise({err: new Error('DOOM')})
      return generatePromise({result: i % 2 === 0, delay: 100})
    })
    .then(r => {
      t.deepEqual(r.results, {4: 4, 6: 6}, 'should keep only the odd values')
      t.deepEqual(r.errors[1], undefined)
      t.deepEqual(r.errors[2].message, 'DOOM')
      t.deepEqual(r.errors[3], undefined)
      t.deepEqual(r.errors[4], undefined)
      t.deepEqual(r.errors[5].message, 'DOOM')
      t.deepEqual(r.errors[6], undefined)
    })
})

test('filterAnyway object should receive the key too', t => {
  return filterAnyway({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}, (i, k) => generatePromise({result: i % 2 === 0 && k % 2 === 0}))
    .then(r => {
      t.deepEqual(r.results, { 2: 2, 4: 4, 6: 6 }, 'should have the key')
    })
})


text:
#include <CoreFoundation/CFNumber.h>
#include "CFInternal.h"
#include <CoreFoundation/CFPriv.h>
#include <math.h>
#include <float.h>

enum {
    kCFNumberSInt128Type = 17
};

typedef CF_ENUM(uint8_t, _CFNumberCanonicalTypeIndex) {
    kCFNumberSInt8CanonicalTypeIndex   = 0x0,
    kCFNumberSInt16CanonicalTypeIndex  = 0x1,
    kCFNumberSInt32CanonicalTypeIndex  = 0x2,
    kCFNumberSInt64CanonicalTypeIndex  = 0x3,
    kCFNumberFloat32CanonicalTypeIndex = 0x4,
    kCFNumberFloat64CanonicalTypeIndex = 0x5,
    kCFNumberSInt128CanonicalTypeIndex = 0x6,
};

static const CFNumberType __CFNumberCanonicalTypes[] = {
    [kCFNumberSInt8CanonicalTypeIndex] = kCFNumberSInt8Type,
    [kCFNumberSInt16CanonicalTypeIndex] = kCFNumberSInt16Type,
    [kCFNumberSInt32CanonicalTypeIndex] = kCFNumberSInt32Type,
    [kCFNumberSInt64CanonicalTypeIndex] = kCFNumberSInt64Type,
    [kCFNumberFloat32CanonicalTypeIndex] = kCFNumberFloat32Type,
    [kCFNumberFloat64CanonicalTypeIndex] = kCFNumberFloat64Type,
    [kCFNumberSInt128CanonicalTypeIndex] = kCFNumberSInt128Type,
};

static const uint8_t __CFNumberCanonicalTypeIndex[] = {
    [kCFNumberSInt8Type] = kCFNumberSInt8CanonicalTypeIndex,
    [kCFNumberSInt16Type] = kCFNumberSInt16CanonicalTypeIndex,
    [kCFNumberSInt32Type] = kCFNumberSInt32CanonicalTypeIndex,
    [kCFNumberSInt64Type] = kCFNumberSInt64CanonicalTypeIndex,
    [kCFNumberFloat32Type] = kCFNumberFloat32CanonicalTypeIndex,
    [kCFNumberFloat64Type] = kCFNumberFloat64CanonicalTypeIndex,
    [kCFNumberSInt128Type] = kCFNumberSInt128CanonicalTypeIndex,
};

/*
 ____ ____ ____ ____   ____ ____ ____ ____
 63                    47                32
 ____ ____ ____ ____   ____ ____ __pp fttt
 31                    15                0

 t: The type index of the canonical type
 f: A flag to tell if the type is a preserved type or a non preserved type (1 means preserved 0 means not preserved)
 p: Bits reserved for reinterpreting both the range of `p` and `t` as a preserved type
 _: Bits reserved for the remainder of the CFRuntime field.

*/

// NOTE: Only 6 bits are allowed in the runtime values!
#define __CFRuntimeGetNumberType(num) (__CFNumberCanonicalTypes[__CFRuntimeGetValue((num), 5, 0) & 0x7])
#define __CFRuntimeGetNumberPreservedType(num) (__CFRuntimeGetValue((num), 5, 0) & 0x3f)

#define __CFRuntimeSetNumberType(num, type) (__CFRuntimeSetValue((num), 5, 0, (__CFNumberCanonicalTypeIndex[type] & 0x7)))
#define __CFRuntimeSetNumberPreservedType(num, type) (__CFRuntimeSetValue((num), 5, 0, (type & 0x3f)))

#define __CFRuntimeIsPreservedNumber(num) (__CFRuntimeGetValue((num), 5, 0) & 0x8)

#if DEPLOYMENT_TARGET_WINDOWS
#define isnan(A) _isnan(A)
#define isinf(A) !_finite(A)
#define copysign(A, B) _copysign(A, B)
#endif

#define __CFAssertIsBoolean(cf) __CFGenericValidateType(cf, CFBooleanGetTypeID())

struct __CFBoolean {
    CFRuntimeBase _base;
};

static struct __CFBoolean __kCFBooleanTrue = {
    INIT_CFRUNTIME_BASE()
};
const CFBooleanRef kCFBooleanTrue = &__kCFBooleanTrue;

static struct __CFBoolean __kCFBooleanFalse = {
    INIT_CFRUNTIME_BASE()
};
const CFBooleanRef kCFBooleanFalse = &__kCFBooleanFalse;

static CFStringRef __CFBooleanCopyDescription(CFTypeRef cf) {
    CFBooleanRef boolean = (CFBooleanRef)cf;
    return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("<CFBoolean %p [%p]>{value = %s}"), cf, CFGetAllocator(cf), (boolean == kCFBooleanTrue) ? "true" : "false");
}

CF_PRIVATE CFStringRef __CFBooleanCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions) {
    CFBooleanRef boolean = (CFBooleanRef)cf;
    return (CFStringRef)CFRetain((boolean == kCFBooleanTrue) ? CFSTR("true") : CFSTR("false"));
}

static CFHashCode __CFBooleanHash(CFTypeRef cf) {
    CFBooleanRef boolean = (CFBooleanRef)cf;
    return (boolean == kCFBooleanTrue) ? _CFHashInt(1) : _CFHashInt(0);
}

static void __CFBooleanDeallocate(CFTypeRef cf) {
    CFAssert(false, __kCFLogAssertion, "Deallocated CFBoolean!");
}

static CFTypeID __kCFBooleanTypeID = _kCFRuntimeNotATypeID;

static const CFRuntimeClass __CFBooleanClass = {
    0,
    "CFBoolean",
    NULL,      // init
    NULL,      // copy
    __CFBooleanDeallocate,
    NULL,
    __CFBooleanHash,
    __CFBooleanCopyFormattingDescription,
    __CFBooleanCopyDescription
};

CFTypeID CFBooleanGetTypeID(void) {
    static dispatch_once_t initOnce;
    dispatch_once(&initOnce, ^{
        __kCFBooleanTypeID = _CFRuntimeRegisterClass(&__CFBooleanClass); // initOnce covered
        _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanTrue, __kCFBooleanTypeID);
        _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanFalse, __kCFBooleanTypeID);
    });
    return __kCFBooleanTypeID;
}

Boolean CFBooleanGetValue(CFBooleanRef boolean) {
    CF_OBJC_FUNCDISPATCHV(CFBooleanGetTypeID(), Boolean, (NSNumber *)boolean, boolValue);
    return (boolean == kCFBooleanTrue) ? true : false;
}

/*** CFNumber ***/

#define __CFAssertIsNumber(cf) __CFGenericValidateType(cf, CFNumberGetTypeID())
#define __CFAssertIsValidNumberType(type) CFAssert2((0 < type && type <= kCFNumberMaxType) || (type == kCFNumberSInt128Type), __kCFLogAssertion, "%s(): bad CFNumber type %ld", __PRETTY_FUNCTION__, type);

/* The IEEE bit patterns... Also have:
0x7f800000		float +Inf
0x7fc00000		float NaN
0xff800000		float -Inf
*/
#define BITSFORDOUBLENAN	((uint64_t)0x7ff8000000000000ULL)
#define BITSFORDOUBLEPOSINF	((uint64_t)0x7ff0000000000000ULL)
#define BITSFORDOUBLENEGINF	((uint64_t)0xfff0000000000000ULL)

// The union dance is to avoid needing hard coded values for different floating point ABIs, technically would be safe to hardcode values, but this way is future proofed
typedef union {
    Float32 floatValue;
    int32_t bits;
} Float32Bits;

typedef union {
    Float64 floatValue;
    int64_t bits;
} Float64Bits;

static const Float32Bits floatZeroBits = {.floatValue = 0.0f};
static const Float32Bits floatOneBits = {.floatValue = 1.0f};

static const Float64Bits doubleZeroBits = {.floatValue = 0.0f};
static const Float64Bits doubleOneBits = {.floatValue = 1.0f};

#define BITSFORFLOATZERO floatZeroBits.bits
#define BITSFORFLOATONE  floatOneBits.bits

#define BITSFORDOUBLEZERO doubleZeroBits.bits
#define BITSFORDOUBLEONE  doubleOneBits.bits

#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
#define FLOAT_POSITIVE_2_TO_THE_64	0x1.0p+64L
#define FLOAT_NEGATIVE_2_TO_THE_127	-0x1.0p+127L
#define FLOAT_POSITIVE_2_TO_THE_127	0x1.0p+127L
#elif DEPLOYMENT_TARGET_WINDOWS
#define FLOAT_POSITIVE_2_TO_THE_64	18446744073709551616.0
#define FLOAT_NEGATIVE_2_TO_THE_127	-170141183460469231731687303715884105728.0
#define FLOAT_POSITIVE_2_TO_THE_127	170141183460469231731687303715884105728.0
#else
#error Unknown or unspecified DEPLOYMENT_TARGET
#endif

typedef struct {	// NOTE WELL: these two fields may switch position someday, do not use '= {high, low}' -style initialization
    int64_t high;
    uint64_t low;
} CFSInt128Struct;

static uint8_t isNeg128(const CFSInt128Struct *in) {
    return in->high < 0;
}

static CFComparisonResult cmp128(const CFSInt128Struct *in1, const CFSInt128Struct *in2) {
    if (in1->high < in2->high) return kCFCompareLessThan;
    if (in1->high > in2->high) return kCFCompareGreaterThan;
    if (in1->low < in2->low) return kCFCompareLessThan;
    if (in1->low > in2->low) return kCFCompareGreaterThan;
    return kCFCompareEqualTo;
}

// allows out to be the same as in1 or in2
static void add128(CFSInt128Struct *out, CFSInt128Struct *in1, CFSInt128Struct *in2) {
    CFSInt128Struct tmp;
    tmp.low = in1->low + in2->low;
    tmp.high = in1->high + in2->high;
    if (UINT64_MAX - in1->low < in2->low) {
        tmp.high++;
    }
    *out = tmp;
}

// allows out to be the same as in
static void neg128(CFSInt128Struct *out, CFSInt128Struct *in) {
    uint64_t tmplow = ~in->low;
    out->low = tmplow + 1;
    out->high = ~in->high;
    if (UINT64_MAX == tmplow) {
	out->high++;
    }
}

static const CFSInt128Struct powersOf10[] = {
    { 0x4B3B4CA85A86C47ALL, 0x098A224000000000ULL },
    { 0x0785EE10D5DA46D9LL, 0x00F436A000000000ULL },
    { 0x00C097CE7BC90715LL, 0xB34B9F1000000000ULL },
    { 0x0013426172C74D82LL, 0x2B878FE800000000ULL },
    { 0x0001ED09BEAD87C0LL, 0x378D8E6400000000ULL },
    { 0x0000314DC6448D93LL, 0x38C15B0A00000000ULL },
    { 0x000004EE2D6D415BLL, 0x85ACEF8100000000ULL },
    { 0x0000007E37BE2022LL, 0xC0914B2680000000ULL },
    { 0x0000000C9F2C9CD0LL, 0x4674EDEA40000000ULL },
    { 0x00000001431E0FAELL, 0x6D7217CAA0000000ULL },
    { 0x00000000204FCE5ELL, 0x3E25026110000000ULL },
    { 0x00000000033B2E3CLL, 0x9FD0803CE8000000ULL },
    { 0x000000000052B7D2LL, 0xDCC80CD2E4000000ULL },
    { 0x0000000000084595LL, 0x161401484A000000ULL },
    { 0x000000000000D3C2LL, 0x1BCECCEDA1000000ULL },
    { 0x000000000000152DLL, 0x02C7E14AF6800000ULL },
    { 0x000000000000021ELL, 0x19E0C9BAB2400000ULL },
    { 0x0000000000000036LL, 0x35C9ADC5DEA00000ULL },
    { 0x0000000000000005LL, 0x6BC75E2D63100000ULL },
    { 0x0000000000000000LL, 0x8AC7230489E80000ULL },
    { 0x0000000000000000LL, 0x0DE0B6B3A7640000ULL },
    { 0x0000000000000000LL, 0x016345785D8A0000ULL },
    { 0x0000000000000000LL, 0x002386F26FC10000ULL },
    { 0x0000000000000000LL, 0x00038D7EA4C68000ULL },
    { 0x0000000000000000LL, 0x00005AF3107A4000ULL },
    { 0x0000000000000000LL, 0x000009184E72A000ULL },
    { 0x0000000000000000LL, 0x000000E8D4A51000ULL },
    { 0x0000000000000000LL, 0x000000174876E800ULL },
    { 0x0000000000000000LL, 0x00000002540BE400ULL },
    { 0x0000000000000000LL, 0x000000003B9ACA00ULL },
    { 0x0000000000000000LL, 0x0000000005F5E100ULL },
    { 0x0000000000000000LL, 0x0000000000989680ULL },
    { 0x0000000000000000LL, 0x00000000000F4240ULL },
    { 0x0000000000000000LL, 0x00000000000186A0ULL },
    { 0x0000000000000000LL, 0x0000000000002710ULL },
    { 0x0000000000000000LL, 0x00000000000003E8ULL },
    { 0x0000000000000000LL, 0x0000000000000064ULL },
    { 0x0000000000000000LL, 0x000000000000000AULL },
    { 0x0000000000000000LL, 0x0000000000000001ULL },
};

static const CFSInt128Struct neg_powersOf10[] = {
    { 0xB4C4B357A5793B85LL, 0xF675DDC000000000ULL },
    { 0xF87A11EF2A25B926LL, 0xFF0BC96000000000ULL },
    { 0xFF3F68318436F8EALL, 0x4CB460F000000000ULL },
    { 0xFFECBD9E8D38B27DLL, 0xD478701800000000ULL },
    { 0xFFFE12F64152783FLL, 0xC872719C00000000ULL },
    { 0xFFFFCEB239BB726CLL, 0xC73EA4F600000000ULL },
    { 0xFFFFFB11D292BEA4LL, 0x7A53107F00000000ULL },
    { 0xFFFFFF81C841DFDDLL, 0x3F6EB4D980000000ULL },
    { 0xFFFFFFF360D3632FLL, 0xB98B1215C0000000ULL },
    { 0xFFFFFFFEBCE1F051LL, 0x928DE83560000000ULL },
    { 0xFFFFFFFFDFB031A1LL, 0xC1DAFD9EF0000000ULL },
    { 0xFFFFFFFFFCC4D1C3LL, 0x602F7FC318000000ULL },
    { 0xFFFFFFFFFFAD482DLL, 0x2337F32D1C000000ULL },
    { 0xFFFFFFFFFFF7BA6ALL, 0xE9EBFEB7B6000000ULL },
    { 0xFFFFFFFFFFFF2C3DLL, 0xE43133125F000000ULL },
    { 0xFFFFFFFFFFFFEAD2LL, 0xFD381EB509800000ULL },
    { 0xFFFFFFFFFFFFFDE1LL, 0xE61F36454DC00000ULL },
    { 0xFFFFFFFFFFFFFFC9LL, 0xCA36523A21600000ULL },
    { 0xFFFFFFFFFFFFFFFALL, 0x9438A1D29CF00000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0x7538DCFB76180000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xF21F494C589C0000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFE9CBA87A2760000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFDC790D903F0000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFC72815B398000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFA50CEF85C000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFF6E7B18D6000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFF172B5AF000ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFE8B7891800ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFDABF41C00ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFC4653600ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFA0A1F00ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFF676980ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFF0BDC0ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFE7960ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFFD8F0ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFFFC18ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFFFF9CULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFFFFF6ULL },
    { 0xFFFFFFFFFFFFFFFFLL, 0xFFFFFFFFFFFFFFFFULL },
};

static void emit128(char *buffer, const CFSInt128Struct *in, Boolean forcePlus) {
    CFSInt128Struct tmp = *in;
    if (isNeg128(&tmp)) {
	neg128(&tmp, &tmp);
	*buffer++ = '-';
    } else if (forcePlus) {
	*buffer++ = '+';
    }
    Boolean doneOne = false;
    int idx;
    for (idx = 0; idx < sizeof(powersOf10) / sizeof(powersOf10[0]); idx++) {
	int count = 0;
        while (cmp128(&powersOf10[idx], &tmp) <= 0) {
	    add128(&tmp, &tmp, (CFSInt128Struct *)&neg_powersOf10[idx]);
	    count++;
	}
	if (0 != count || doneOne) {
	    *buffer++ = '0' + count;
	    doneOne = true;
	}
    }
    if (!doneOne) {
	*buffer++ = '0';
    }
    *buffer = '\0';
}

static void cvtSInt128ToFloat64(Float64 *out, const CFSInt128Struct *in) {
    // switching to a positive number results in better accuracy
    // for negative numbers close to zero, because the multiply
    // of -1 by 2^64 (scaling the Float64 high) is avoided
    Boolean wasNeg = false;
    CFSInt128Struct tmp = *in;
    if (isNeg128(&tmp)) {
	neg128(&tmp, &tmp);
	wasNeg = true;
    }
    Float64 d = (Float64)tmp.high * FLOAT_POSITIVE_2_TO_THE_64 + (Float64)tmp.low;
    if (wasNeg) d = -d;
    *out = d;
}

static void cvtFloat64ToSInt128(CFSInt128Struct *out, const Float64 *in) {
    CFSInt128Struct i;
    Float64 d = *in;
    if (d < FLOAT_NEGATIVE_2_TO_THE_127) {
	i.high = 0x8000000000000000LL;
	i.low = 0x0000000000000000ULL;
	*out = i;
	return;
    }
    if (FLOAT_POSITIVE_2_TO_THE_127<= d) {
	i.high = 0x7fffffffffffffffLL;
	i.low = 0xffffffffffffffffULL;
	*out = i;
	return;
    }
    Float64 t = floor(d / FLOAT_POSITIVE_2_TO_THE_64);
    i.high = (int64_t)t;
    i.low = (uint64_t)(d - t * FLOAT_POSITIVE_2_TO_THE_64);
    *out = i;
}

struct __CFNumber {
    CFRuntimeBase _base;
    uint64_t _pad; // need this space here for the constant objects
    /* 0 or 8 more bytes allocated here */
};

/* Seven bits in base:
    Bits 6..5: unused
    Bits 4..0: CFNumber type
*/

// Note: The isa for these things is fixed up later
static struct __CFNumber __kCFNumberNaN = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
const CFNumberRef kCFNumberNaN = &__kCFNumberNaN;

static struct __CFNumber __kCFNumberNegativeInfinity = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
const CFNumberRef kCFNumberNegativeInfinity = &__kCFNumberNegativeInfinity;

static struct __CFNumber __kCFNumberPositiveInfinity = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
const CFNumberRef kCFNumberPositiveInfinity = &__kCFNumberPositiveInfinity;

static struct __CFNumber __kCFNumberFloat32Zero = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
static const CFNumberRef kCFNumberFloat32Zero = &__kCFNumberFloat32Zero;

static struct __CFNumber __kCFNumberFloat32One = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
static const CFNumberRef kCFNumberFloat32One = &__kCFNumberFloat32One;

static struct __CFNumber __kCFNumberFloat64Zero = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
static const CFNumberRef kCFNumberFloat64Zero = &__kCFNumberFloat64Zero;

static struct __CFNumber __kCFNumberFloat64One = {
    INIT_CFRUNTIME_BASE(), 0ULL
};
static const CFNumberRef kCFNumberFloat64One = &__kCFNumberFloat64One;

static const struct {
    uint16_t canonicalType:5;	// canonical fixed-width type
    uint16_t floatBit:1;	// is float
    uint16_t storageBit:1;	// storage size (0: (float ? 4 : 8), 1: (float ? 8 : 16) bits)
    uint16_t lgByteSize:3;	// base-2 log byte size of public type
    uint16_t unused:6;
} __CFNumberTypeTable[] = {
    /* 0 */			{0, 0, 0, 0},

    /* kCFNumberSInt8Type */	{kCFNumberSInt8Type, 0, 0, 0, 0},
    /* kCFNumberSInt16Type */	{kCFNumberSInt16Type, 0, 0, 1, 0},
    /* kCFNumberSInt32Type */	{kCFNumberSInt32Type, 0, 0, 2, 0},
    /* kCFNumberSInt64Type */	{kCFNumberSInt64Type, 0, 0, 3, 0},
    /* kCFNumberFloat32Type */	{kCFNumberFloat32Type, 1, 0, 2, 0},
    /* kCFNumberFloat64Type */	{kCFNumberFloat64Type, 1, 1, 3, 0},

    /* kCFNumberCharType */	{kCFNumberSInt8Type, 0, 0, 0, 0},
    /* kCFNumberShortType */	{kCFNumberSInt16Type, 0, 0, 1, 0},
    /* kCFNumberIntType */	{kCFNumberSInt32Type, 0, 0, 2, 0},
#if __LP64__
    /* kCFNumberLongType */	{kCFNumberSInt64Type, 0, 0, 3, 0},
#else
    /* kCFNumberLongType */	{kCFNumberSInt32Type, 0, 0, 2, 0},
#endif
    /* kCFNumberLongLongType */	{kCFNumberSInt64Type, 0, 0, 3, 0},
    /* kCFNumberFloatType */	{kCFNumberFloat32Type, 1, 0, 2, 0},
    /* kCFNumberDoubleType */	{kCFNumberFloat64Type, 1, 1, 3, 0},

#if __LP64__
    /* kCFNumberCFIndexType */	{kCFNumberSInt64Type, 0, 0, 3, 0},
    /* kCFNumberNSIntegerType */ {kCFNumberSInt64Type, 0, 0, 3, 0},
    /* kCFNumberCGFloatType */	{kCFNumberFloat64Type, 1, 1, 3, 0},
#else
    /* kCFNumberCFIndexType */	{kCFNumberSInt32Type, 0, 0, 2, 0},
    /* kCFNumberNSIntegerType */ {kCFNumberSInt32Type, 0, 0, 2, 0},
    /* kCFNumberCGFloatType */	{kCFNumberFloat32Type, 1, 0, 2, 0},
#endif

    /* kCFNumberSInt128Type */	{kCFNumberSInt128Type, 0, 1, 4, 0},
};

CF_INLINE CFNumberType __CFNumberGetType(CFNumberRef num) {
    return __CFRuntimeGetNumberType(num);
}

#define CVT(SRC_TYPE, DST_TYPE, DST_MIN, DST_MAX) do { \
	SRC_TYPE sv; memmove(&sv, data, sizeof(SRC_TYPE)); \
	DST_TYPE dv = (sv < DST_MIN) ? (DST_TYPE)DST_MIN : (DST_TYPE)(((DST_MAX < sv) ? DST_MAX : sv)); \
	memmove(valuePtr, &dv, sizeof(DST_TYPE)); \
	SRC_TYPE vv = (SRC_TYPE)dv; return (vv == sv); \
	} while (0)

#define CVT128ToInt(SRC_TYPE, DST_TYPE, DST_MIN, DST_MAX) do { \
        SRC_TYPE sv; memmove(&sv, data, sizeof(SRC_TYPE)); \
	DST_TYPE dv; Boolean noLoss = false; \
	if (0 < sv.high || (0 == sv.high && (int64_t)DST_MAX < sv.low)) { \
	    dv = DST_MAX; \
	} else if (sv.high < -1 || (-1 == sv.high && sv.low < (int64_t)DST_MIN)) { \
	    dv = DST_MIN; \
	} else { \
	    dv = (DST_TYPE)sv.low; \
	    noLoss = true; \
	} \
        memmove(valuePtr, &dv, sizeof(DST_TYPE)); \
        return noLoss; \
        } while (0)

// returns false if the output value is not the same as the number's value, which
// can occur due to accuracy loss and the value not being within the target range
static Boolean __CFNumberGetValue(CFNumberRef number, CFNumberType type, void *valuePtr) {
    type = __CFNumberTypeTable[type].canonicalType;
    CFNumberType ntype = __CFNumberGetType(number);
    const void *data = &(number->_pad);
    Boolean floatBit = __CFNumberTypeTable[ntype].floatBit;
    Boolean storageBit = __CFNumberTypeTable[ntype].storageBit;
    switch (type) {
    case kCFNumberSInt8Type:
	if (floatBit) {
	    if (!storageBit) {
		CVT(Float32, int8_t, INT8_MIN, INT8_MAX);
	    } else {
		CVT(Float64, int8_t, INT8_MIN, INT8_MAX);
	    }
	} else {
	    if (!storageBit) {
		CVT(int64_t, int8_t, INT8_MIN, INT8_MAX);
	    } else {
		CVT128ToInt(CFSInt128Struct, int8_t, INT8_MIN, INT8_MAX);
	    }
	}
	return true;
    case kCFNumberSInt16Type:
	if (floatBit) {
	    if (!storageBit) {
                CVT(Float32, int16_t, INT16_MIN, INT16_MAX);
	    } else {
                CVT(Float64, int16_t, INT16_MIN, INT16_MAX);
	    }
	} else {
	    if (!storageBit) {
                CVT(int64_t, int16_t, INT16_MIN, INT16_MAX);
	    } else {
		CVT128ToInt(CFSInt128Struct, int16_t, INT16_MIN, INT16_MAX);
	    }
	}
	return true;
    case kCFNumberSInt32Type:
	if (floatBit) {
	    if (!storageBit) {
                CVT(Float32, int32_t, INT32_MIN, INT32_MAX);
	    } else {
                CVT(Float64, int32_t, INT32_MIN, INT32_MAX);
	    }
	} else {
	    if (!storageBit) {
                CVT(int64_t, int32_t, INT32_MIN, INT32_MAX);
	    } else {
		CVT128ToInt(CFSInt128Struct, int32_t, INT32_MIN, INT32_MAX);
	    }
	}
	return true;
    case kCFNumberSInt64Type:
	if (floatBit) {
	    if (!storageBit) {
                CVT(Float32, int64_t, INT64_MIN, INT64_MAX);
	    } else {
                CVT(Float64, int64_t, INT64_MIN, INT64_MAX);
	    }
	} else {
	    if (!storageBit) {
		memmove(valuePtr, data, 8);
	    } else {
		CVT128ToInt(CFSInt128Struct, int64_t, INT64_MIN, INT64_MAX);
	    }
	}
	return true;
    case kCFNumberSInt128Type:
	if (floatBit) {
	    if (!storageBit) {
		Float32 f;
		memmove(&f, data, 4);
		Float64 d = f;
		CFSInt128Struct i;
		cvtFloat64ToSInt128(&i, &d);
		memmove(valuePtr, &i, 16);
		Float64 d2;
		cvtSInt128ToFloat64(&d2, &i);
		Float32 f2 = (Float32)d2;
		return (f2 == f);
	    } else {
		Float64 d;
		memmove(&d, data, 8);
		CFSInt128Struct i;
		cvtFloat64ToSInt128(&i, &d);
		memmove(valuePtr, &i, 16);
		Float64 d2;
		cvtSInt128ToFloat64(&d2, &i);
		return (d2 == d);
	    }
	} else {
	    if (!storageBit) {
		int64_t j;
		memmove(&j, data, 8);
		CFSInt128Struct i;
		i.low = j;
		i.high = (j < 0) ? -1LL : 0LL;
		memmove(valuePtr, &i, 16);
	    } else {
		memmove(valuePtr, data, 16);
	    }
	}
	return true;
    case kCFNumberFloat32Type:
	if (floatBit) {
	    if (!storageBit) {
		memmove(valuePtr, data, 4);
	    } else {
		double d;
		memmove(&d, data, 8);
		if (isnan(d)) {
		    uint32_t l = 0x7fc00000;
		    memmove(valuePtr, &l, 4);
		    return true;
		} else if (isinf(d)) {
		    uint32_t l = 0x7f800000;
		    if (d < 0.0) l += 0x80000000UL;
		    memmove(valuePtr, &l, 4);
		    return true;
		}
		CVT(Float64, Float32, -FLT_MAX, FLT_MAX);
	    }
	} else {
	    if (!storageBit) {
		CVT(int64_t, Float32, -FLT_MAX, FLT_MAX);
	    } else {
		CFSInt128Struct i;
		memmove(&i, data, 16);
		Float64 d;
		cvtSInt128ToFloat64(&d, &i);
		Float32 f = (Float32)d;
		memmove(valuePtr, &f, 4);
		d = f;
		CFSInt128Struct i2;
		cvtFloat64ToSInt128(&i2, &d);
		return cmp128(&i2, &i) == kCFCompareEqualTo;
	    }
	}
	return true;
    case kCFNumberFloat64Type:
	if (floatBit) {
	    if (!storageBit) {
		float f;
		memmove(&f, data, 4);
		if (isnan(f)) {
		    uint64_t l = BITSFORDOUBLENAN;
		    memmove(valuePtr, &l, 8);
		    return true;
		} else if (isinf(f)) {
		    uint64_t l = BITSFORDOUBLEPOSINF;
		    if (f < 0.0) l += 0x8000000000000000ULL;
		    memmove(valuePtr, &l, 8);
		    return true;
		}
		CVT(Float32, Float64, -DBL_MAX, DBL_MAX);
	    } else {
		memmove(valuePtr, data, 8);
	    }
	} else {
	    if (!storageBit) {
		CVT(int64_t, Float64, -DBL_MAX, DBL_MAX);
	    } else {
                CFSInt128Struct i;
                memmove(&i, data, 16);
                Float64 d;
                cvtSInt128ToFloat64(&d, &i);
                memmove(valuePtr, &d, 8);
                CFSInt128Struct i2;
                cvtFloat64ToSInt128(&i2, &d);
                return cmp128(&i2, &i) == kCFCompareEqualTo;
	    }
	}
	return true;
    }
    return false;
}

#define CVT_COMPAT(SRC_TYPE, DST_TYPE, FT) do { \
	SRC_TYPE sv; memmove(&sv, data, sizeof(SRC_TYPE)); \
	DST_TYPE dv = (DST_TYPE)(sv); \
	memmove(valuePtr, &dv, sizeof(DST_TYPE)); \
	SRC_TYPE vv = (SRC_TYPE)dv; return (FT) || (vv == sv); \
	} while (0)

#define CVT128ToInt_COMPAT(SRC_TYPE, DST_TYPE) do { \
        SRC_TYPE sv; memmove(&sv, data, sizeof(SRC_TYPE)); \
	DST_TYPE dv; dv = (DST_TYPE)sv.low; \
        memmove(valuePtr, &dv, sizeof(DST_TYPE)); \
	uint64_t vv = (uint64_t)dv; return (vv == sv.low); \
        } while (0)

// this has the old cast-style behavior
static Boolean __CFNumberGetValueCompat(CFNumberRef number, CFNumberType type, void *valuePtr) {
    type = __CFNumberTypeTable[type].canonicalType;
    CFNumberType ntype = __CFNumberGetType(number);
    const void *data = &(number->_pad);
    switch (type) {
    case kCFNumberSInt8Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(Float32, int8_t, 0);
	    } else {
		CVT_COMPAT(Float64, int8_t, 0);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		// Leopard's implemenation of this always returned true. We should only return true when the conversion is lossless. However, there are some clients who use CFNumber with small unsigned values disguised as signed values. Since there is no CFNumber API yet for unsigned values, we need to accomodate those clients for now. <rdar://problem/6471866>
		// This accomodation should be removed if CFNumber ever provides API for unsigned values. <rdar://problem/6473890>
		int64_t sv; memmove(&sv, data, sizeof(int64_t));
		int8_t dv = (int8_t)(sv);
		memmove(valuePtr, &dv, sizeof(int8_t));
		int64_t vv = (int64_t)dv; return !_CFExecutableLinkedOnOrAfter(CFSystemVersionSnowLeopard) || ((sv >> 8LL) == 0LL) || (vv == sv);
	    } else {
		CVT128ToInt_COMPAT(CFSInt128Struct, int8_t);
	    }
	}
	return true;
    case kCFNumberSInt16Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(Float32, int16_t, 0);
	    } else {
		CVT_COMPAT(Float64, int16_t, 0);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		// Leopard's implemenation of this always returned true. We should only return true when the conversion is lossless. However, there are some clients who use CFNumber with small unsigned values disguised as signed values. Since there is no CFNumber API yet for unsigned values, we need to accomodate those clients for now. <rdar://problem/6471866>
		// This accomodation should be removed if CFNumber ever provides API for unsigned values. <rdar://problem/6473890>
		int64_t sv; memmove(&sv, data, sizeof(int64_t));
		int16_t dv = (int16_t)(sv);
		memmove(valuePtr, &dv, sizeof(int16_t));
		int64_t vv = (int64_t)dv; return !_CFExecutableLinkedOnOrAfter(CFSystemVersionSnowLeopard) || ((sv >> 16LL) == 0LL) || (vv == sv);
	    } else {
		CVT128ToInt_COMPAT(CFSInt128Struct, int16_t);
	    }
	}
	return true;
    case kCFNumberSInt32Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(Float32, int32_t, 0);
	    } else {
		CVT_COMPAT(Float64, int32_t, 0);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
                CVT_COMPAT(int64_t, int32_t, 0);
	    } else {
		CVT128ToInt_COMPAT(CFSInt128Struct, int32_t);
	    }
	}
	return true;
    case kCFNumberSInt64Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(Float32, int64_t, 0);
	    } else {
		CVT_COMPAT(Float64, int64_t, 0);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
                CVT_COMPAT(int64_t, int64_t, 0);
	    } else {
		CVT128ToInt_COMPAT(CFSInt128Struct, int64_t);
	    }
	}
	return true;
    case kCFNumberSInt128Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		Float32 f;
		memmove(&f, data, 4);
		Float64 d = f;
		CFSInt128Struct i;
		cvtFloat64ToSInt128(&i, &d);
		memmove(valuePtr, &i, 16);
		Float64 d2;
		cvtSInt128ToFloat64(&d2, &i);
		Float32 f2 = (Float32)d2;
		return (f2 == f);
	    } else {
		Float64 d;
		memmove(&d, data, 8);
		CFSInt128Struct i;
		cvtFloat64ToSInt128(&i, &d);
		memmove(valuePtr, &i, 16);
		Float64 d2;
		cvtSInt128ToFloat64(&d2, &i);
		return (d2 == d);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		int64_t j;
		memmove(&j, data, 8);
		CFSInt128Struct i;
		i.low = j;
		i.high = (j < 0) ? -1LL : 0LL;
		memmove(valuePtr, &i, 16);
	    } else {
		memmove(valuePtr, data, 16);
	    }
	}
	return true;
    case kCFNumberFloat32Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		memmove(valuePtr, data, 4);
	    } else {
		CVT_COMPAT(Float64, Float32, 0);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(int64_t, Float32, 0);
	    } else {
		CFSInt128Struct i;
		memmove(&i, data, 16);
		Float64 d;
		cvtSInt128ToFloat64(&d, &i);
		Float32 f = (Float32)d;
		memmove(valuePtr, &f, 4);
		d = f;
		CFSInt128Struct i2;
		cvtFloat64ToSInt128(&i2, &d);
		return cmp128(&i2, &i) == kCFCompareEqualTo;
	    }
	}
	return true;
    case kCFNumberFloat64Type:
	if (__CFNumberTypeTable[ntype].floatBit) {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(Float32, Float64, 0);
	    } else {
		memmove(valuePtr, data, 8);
	    }
	} else {
	    if (0 == __CFNumberTypeTable[ntype].storageBit) {
		CVT_COMPAT(int64_t, Float64, 0);
	    } else {
		CFSInt128Struct i;
		memmove(&i, data, 16);
		Float64 d;
		cvtSInt128ToFloat64(&d, &i);
		memmove(valuePtr, &d, 8);
		CFSInt128Struct i2;
		cvtFloat64ToSInt128(&i2, &d);
		return cmp128(&i2, &i) == kCFCompareEqualTo;
	    }
	}
	return true;
    }
    return false;
}

static CFStringRef __CFNumberCopyDescription(CFTypeRef cf) {
    CFNumberRef number = (CFNumberRef)cf;
    CFNumberType type = __CFNumberGetType(number);
    CFMutableStringRef mstr = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
    CFStringAppendFormat(mstr, NULL, CFSTR("<CFNumber %p [%p]>{value = "), cf, CFGetAllocator(cf));
    if (__CFNumberTypeTable[type].floatBit) {
	Float64 d;
        __CFNumberGetValue(number, kCFNumberFloat64Type, &d);
	if (isnan(d)) {
	    CFStringAppend(mstr, CFSTR("nan"));
	} else if (isinf(d)) {
	    CFStringAppend(mstr, (0.0 < d) ? CFSTR("+infinity") : CFSTR("-infinity"));
	} else if (0.0 == d) {
	    CFStringAppend(mstr, (copysign(1.0, d) < 0.0) ? CFSTR("-0.0") : CFSTR("+0.0"));
	} else {
	    CFStringAppendFormat(mstr, NULL, CFSTR("%+.*f"), (__CFNumberTypeTable[type].storageBit ? 20 : 10), d);
	}
	const char *typeName = "unknown float";
	switch (type) {
	case kCFNumberFloat32Type: typeName = "kCFNumberFloat32Type"; break;
	case kCFNumberFloat64Type: typeName = "kCFNumberFloat64Type"; break;
	}
	CFStringAppendFormat(mstr, NULL, CFSTR(", type = %s}"), typeName);
    } else {
	CFSInt128Struct i;
	__CFNumberGetValue(number, kCFNumberSInt128Type, &i);
	char buffer[128];
	emit128(buffer, &i, true);
	const char *typeName = "unknown integer";
	switch (type) {
	case kCFNumberSInt8Type: typeName = "kCFNumberSInt8Type"; break;
	case kCFNumberSInt16Type: typeName = "kCFNumberSInt16Type"; break;
	case kCFNumberSInt32Type: typeName = "kCFNumberSInt32Type"; break;
	case kCFNumberSInt64Type: typeName = "kCFNumberSInt64Type"; break;
	case kCFNumberSInt128Type: typeName = "kCFNumberSInt128Type"; break;
	}
	CFStringAppendFormat(mstr, NULL, CFSTR("%s, type = %s}"), buffer, typeName);
    }
    return mstr;
}

// This function separated out from __CFNumberCopyFormattingDescription() so the plist creation can use it as well.

static CFStringRef __CFNumberCreateFormattingDescriptionAsFloat64(CFAllocatorRef allocator, CFTypeRef cf) {
    Float64 d;
    CFNumberGetValue((CFNumberRef)cf, kCFNumberFloat64Type, &d);
    if (isnan(d)) {
	return (CFStringRef)CFRetain(CFSTR("nan"));
    }
    if (isinf(d)) {
	return (CFStringRef)CFRetain((0.0 < d) ? CFSTR("+infinity") : CFSTR("-infinity"));
    }
    if (0.0 == d) {
	return (CFStringRef)CFRetain(CFSTR("0.0"));
    }
    // if %g is used here, need to use DBL_DIG + 2 on Mac OS X, but %f needs +1
    return CFStringCreateWithFormat(allocator, NULL, CFSTR("%.*g"), DBL_DIG + 2, d);
}

CF_PRIVATE CFStringRef __CFNumberCopyFormattingDescriptionAsFloat64(CFTypeRef cf) {
    CFStringRef result = __CFNumberCreateFormattingDescriptionAsFloat64(kCFAllocatorSystemDefault, cf);
    return result;
}

CF_PRIVATE CFStringRef __CFNumberCreateFormattingDescription(CFAllocatorRef allocator, CFTypeRef cf, CFDictionaryRef formatOptions) {
    CFNumberRef number = (CFNumberRef)cf;
    CFNumberType type = __CFNumberGetType(number);
    if (__CFNumberTypeTable[type].floatBit) {
        return __CFNumberCreateFormattingDescriptionAsFloat64(allocator, number);
    }
    CFSInt128Struct i;
    __CFNumberGetValue(number, kCFNumberSInt128Type, &i);
    char buffer[128];
    emit128(buffer, &i, false);
    return CFStringCreateWithFormat(allocator, NULL, CFSTR("%s"), buffer);
}

static CFStringRef __CFNumberCopyFormattingDescription_new(CFTypeRef cf, CFDictionaryRef formatOptions) {
    CFNumberRef number = (CFNumberRef)cf;
    CFNumberType type = __CFNumberGetType(number);
    if (__CFNumberTypeTable[type].floatBit) {
        return __CFNumberCopyFormattingDescriptionAsFloat64(number);
    }
    CFSInt128Struct i;
    __CFNumberGetValue(number, kCFNumberSInt128Type, &i);
    char buffer[128];
    emit128(buffer, &i, false);
    return CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("%s"), buffer);
}

CF_PRIVATE CFStringRef __CFNumberCopyFormattingDescription(CFTypeRef cf, CFDictionaryRef formatOptions) {
    CFStringRef result = __CFNumberCopyFormattingDescription_new(cf, formatOptions);
    return result;
}

static Boolean __CFNumberEqual(CFTypeRef cf1, CFTypeRef cf2) {
    Boolean b = CFNumberCompare((CFNumberRef)cf1, (CFNumberRef)cf2, 0) == kCFCompareEqualTo;
    return b;
}

static CFHashCode __CFNumberHash(CFTypeRef cf) {
    CFHashCode h;
    CFNumberRef number = (CFNumberRef)cf;
    switch (__CFNumberGetType(number)) {
	case kCFNumberSInt8Type:
	case kCFNumberSInt16Type:
	case kCFNumberSInt32Type: {
	    SInt32 i;
	    __CFNumberGetValue(number, kCFNumberSInt32Type, &i);
	    h = _CFHashInt(i);
	    break;
	}
	default: {
	    Float64 d;
	    __CFNumberGetValue(number, kCFNumberFloat64Type, &d);
	    h = _CFHashDouble((double)d);
	    break;
	}
    }
    return h;
}

static CFTypeID __kCFNumberTypeID = _kCFRuntimeNotATypeID;

enum {
  kCFNumberCachingEnabled = 0,
  kCFNumberCachingDisabled = 1,
  kCFNumberCachingFullyDisabled = 2
};
static char __CFNumberCaching = kCFNumberCachingEnabled;

static const CFRuntimeClass __CFNumberClass = {
    0,
    "CFNumber",
    NULL,      // init
    NULL,      // copy
    NULL,
    __CFNumberEqual,
    __CFNumberHash,
    __CFNumberCopyFormattingDescription,
    __CFNumberCopyDescription
};

CF_PRIVATE void __CFNumberInitialize(void) {
    _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFNumberNaN, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberNaN, kCFNumberFloat64Type);
    __kCFNumberNaN._pad = BITSFORDOUBLENAN;

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberNegativeInfinity, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberNegativeInfinity, kCFNumberFloat64Type);
    __kCFNumberNegativeInfinity._pad = BITSFORDOUBLENEGINF;

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberPositiveInfinity, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberPositiveInfinity, kCFNumberFloat64Type);
    __kCFNumberPositiveInfinity._pad = BITSFORDOUBLEPOSINF;

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat32Zero, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberFloat32Zero, kCFNumberFloat32Type);
    __kCFNumberFloat32Zero._pad = BITSFORFLOATZERO;

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat32One, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberFloat32One, kCFNumberFloat32Type);
    __kCFNumberFloat32One._pad = BITSFORFLOATONE;
#if __BIG_ENDIAN__
    __kCFNumberFloat32One._pad = __kCFNumberFloat32One._pad << 32;
#endif

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat64Zero, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberFloat64Zero, kCFNumberFloat64Type);
    __kCFNumberFloat64Zero._pad = BITSFORDOUBLEZERO;

    _CFRuntimeSetInstanceTypeIDAndIsa(& __kCFNumberFloat64One, __kCFNumberTypeID);
    __CFRuntimeSetNumberType(&__kCFNumberFloat64One, kCFNumberFloat64Type);
    __kCFNumberFloat64One._pad = BITSFORDOUBLEONE;
#if DEPLOYMENT_RUNTIME_SWIFT
    _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanTrue, __kCFBooleanTypeID);
    _CFRuntimeSetInstanceTypeIDAndIsa(&__kCFBooleanFalse, __kCFBooleanTypeID);
#endif
}

CFTypeID CFNumberGetTypeID(void) {
    static dispatch_once_t initOnce;
    dispatch_once(&initOnce, ^{
        __kCFNumberTypeID = _CFRuntimeRegisterClass(&__CFNumberClass); // initOnce covered
#if !DEPLOYMENT_RUNTIME_SWIFT
        __CFNumberInitialize();
#endif

        const char *caching = __CFgetenv("CFNumberDisableCache");	// "all" to disable caching and tagging; anything else to disable caching; nothing to leave both enabled
        if (caching) __CFNumberCaching = (!strcmp(caching, "all")) ? kCFNumberCachingFullyDisabled : kCFNumberCachingDisabled;	// initial state above is kCFNumberCachingEnabled
    });
    return __kCFNumberTypeID;
}

#define MinCachedInt (-1)
#define MaxCachedInt (12)
#define NotToBeCached (MinCachedInt - 1)
static CFNumberRef __CFNumberCache[MaxCachedInt - MinCachedInt + 1] = {NULL};	// Storing CFNumberRefs for range MinCachedInt..MaxCachedInt

static inline void __CFNumberInit(CFNumberRef result, CFNumberType type, const void *valuePtr) {
    __CFAssertIsValidNumberType(type);

    uint64_t value;
    switch (__CFNumberTypeTable[type].canonicalType) {
        case kCFNumberSInt8Type:   value = (uint64_t)(int64_t)*(int8_t *)valuePtr; goto smallVal;
        case kCFNumberSInt16Type:  value = (uint64_t)(int64_t)*(int16_t *)valuePtr; goto smallVal;
        case kCFNumberSInt32Type:  value = (uint64_t)(int64_t)*(int32_t *)valuePtr; goto smallVal;
        smallVal: memmove((void *)&result->_pad, &value, 8); break;
        case kCFNumberSInt64Type:  memmove((void *)&result->_pad, valuePtr, 8); break;
        case kCFNumberSInt128Type: memmove((void *)&result->_pad, valuePtr, 16); break;
        case kCFNumberFloat32Type: memmove((void *)&result->_pad, valuePtr, 4); break;
        case kCFNumberFloat64Type: memmove((void *)&result->_pad, valuePtr, 8); break;
    }
}

static inline void _CFNumberInit(CFNumberRef result, CFNumberType type, const void *valuePtr) {
    __CFNumberInit(result, type, valuePtr);
}

void _CFNumberInitBool(CFNumberRef result, Boolean value) {
    _CFNumberInit(result, kCFNumberCharType, &value);
}

void _CFNumberInitInt8(CFNumberRef result, int8_t value) {
    _CFNumberInit(result, kCFNumberCharType, &value);
}

void _CFNumberInitUInt8(CFNumberRef result, uint8_t value) {
    _CFNumberInit(result, kCFNumberCharType, &value);
}

void _CFNumberInitInt16(CFNumberRef result, int16_t value) {
    _CFNumberInit(result, kCFNumberShortType, &value);
}

void _CFNumberInitUInt16(CFNumberRef result, uint16_t value) {
    _CFNumberInit(result, kCFNumberShortType, &value);
}

void _CFNumberInitInt32(CFNumberRef result, int32_t value) {
    _CFNumberInit(result, kCFNumberIntType, &value);
}

void _CFNumberInitUInt32(CFNumberRef result, uint32_t value) {
    _CFNumberInit(result, kCFNumberIntType, &value);
}

void _CFNumberInitInt(CFNumberRef result, long value) {
    _CFNumberInit(result, kCFNumberLongType, &value);
}

void _CFNumberInitUInt(CFNumberRef result, unsigned long value) {
    _CFNumberInit(result, kCFNumberLongType, &value);
}

void _CFNumberInitInt64(CFNumberRef result, int64_t value) {
    _CFNumberInit(result, kCFNumberLongLongType, &value);
}

void _CFNumberInitUInt64(CFNumberRef result, uint64_t value) {
    _CFNumberInit(result, kCFNumberLongLongType, &value);
}

void _CFNumberInitFloat(CFNumberRef result, float value) {
    _CFNumberInit(result, kCFNumberFloatType, &value);
}

void _CFNumberInitDouble(CFNumberRef result, double value) {
    _CFNumberInit(result, kCFNumberDoubleType, &value);
}

static CFNumberRef _CFNumberCreate(CFAllocatorRef allocator, CFNumberType type, const void *valuePtr) {
    __CFAssertIsValidNumberType(type);
//printf("+ [%p] CFNumberCreate(%p, %d, %p)\n", pthread_self(), allocator, type, valuePtr);

    if (!allocator) allocator = __CFGetDefaultAllocator();

    // Look for cases where we can return a cached instance.
    // We only use cached objects if the allocator is the system
    // default allocator, except for the special floating point
    // constant objects, where we return the cached object
    // regardless of allocator, since that is what has always
    // been done (and now must for compatibility).
    int64_t valToBeCached = NotToBeCached;
    if (__CFNumberTypeTable[type].floatBit) {
        CFNumberRef cached = NULL;
        if (0 == __CFNumberTypeTable[type].storageBit) {
            Float32Bits f = *(Float32Bits *)valuePtr;
            if (f.bits == BITSFORFLOATZERO) cached = kCFNumberFloat32Zero;
            else if (f.bits == BITSFORFLOATONE) cached = kCFNumberFloat32One;
            else if (isnan(f.floatValue)) cached = kCFNumberNaN;
            else if (isinf(f.floatValue)) cached = (f.floatValue < 0.0) ? kCFNumberNegativeInfinity : kCFNumberPositiveInfinity;

        } else {
            Float64Bits d = *(Float64Bits *)valuePtr;
            if (d.bits == BITSFORDOUBLEZERO) cached = kCFNumberFloat64Zero;
            else if (d.bits == BITSFORDOUBLEONE) cached = kCFNumberFloat64One;
            else if (isnan(d.floatValue)) cached = kCFNumberNaN;
            else if (isinf(d.floatValue)) cached = (d.floatValue < 0.0) ? kCFNumberNegativeInfinity : kCFNumberPositiveInfinity;
        }
        if (cached) return (CFNumberRef)CFRetain(cached);
    } else if (_CFAllocatorIsSystemDefault(allocator) && (__CFNumberCaching == kCFNumberCachingEnabled)) {
        switch (__CFNumberTypeTable[type].canonicalType) {
        case kCFNumberSInt8Type:   {int8_t  val = *(int8_t *)valuePtr;  if (MinCachedInt <= val && val <= MaxCachedInt) valToBeCached = (int64_t)val; break;}
        case kCFNumberSInt16Type:  {int16_t val = *(int16_t *)valuePtr; if (MinCachedInt <= val && val <= MaxCachedInt) valToBeCached = (int64_t)val; break;}
        case kCFNumberSInt32Type:  {int32_t val = *(int32_t *)valuePtr; if (MinCachedInt <= val && val <= MaxCachedInt) valToBeCached = (int64_t)val; break;}
        case kCFNumberSInt64Type:  {int64_t val = *(int64_t *)valuePtr; if (MinCachedInt <= val && val <= MaxCachedInt) valToBeCached = (int64_t)val; break;}
        }
        if (NotToBeCached != valToBeCached) {
            CFNumberRef cached = __CFNumberCache[valToBeCached - MinCachedInt];        // Atomic to access the value in the cache
            if (NULL != cached) return (CFNumberRef)CFRetain(cached);
        }
    }

    CFIndex size = 8 + ((!__CFNumberTypeTable[type].floatBit && __CFNumberTypeTable[type].storageBit) ? 8 : 0);
    CFNumberRef result = (CFNumberRef)_CFRuntimeCreateInstance(allocator, CFNumberGetTypeID(), size, NULL);
    if (NULL == result) {
	return NULL;
    }

    __CFRuntimeSetNumberType(result, (uint8_t)__CFNumberTypeTable[type].canonicalType);

    // should be initialized BEFORE ever caching it!
    __CFNumberInit(result, type, valuePtr);

    // for a value to be cached, we already have the value handy
    if (NotToBeCached != valToBeCached) {
	memmove((void *)&result->_pad, &valToBeCached, 8);
	// Put this in the cache unless the cache is already filled (by another thread).  If we do put it in the cache, retain it an extra time for the cache.
	// Note that we don't bother freeing this result and returning the cached value if the cache was filled, since cached CFNumbers are not guaranteed unique.
	// Barrier assures that the number that is placed in the cache is properly formed.
	CFNumberType origType = __CFNumberGetType(result);
	// Force all cached numbers to have the same type, so that the type does not
	// depend on the order and original type in/with which the numbers are created.
	// Forcing the type AFTER it was cached would cause a race condition with other
	// threads pulling the number object out of the cache and using it.
        __CFRuntimeSetNumberType(result, (uint8_t)kCFNumberSInt32Type);
	if (OSAtomicCompareAndSwapPtrBarrier(NULL, (void *)result, (void *volatile *)&__CFNumberCache[valToBeCached - MinCachedInt])) {
	    CFRetain(result);
	} else {
	    // Did not cache the number object, put original type back.
            __CFRuntimeSetNumberType(result, origType);
	}
	return result;
    }

    return result;
}

CFNumberRef CFNumberCreate(CFAllocatorRef allocator, CFNumberType type, const void *valuePtr) {
    return _CFNumberCreate(allocator, type, valuePtr);
}

CFNumberType CFNumberGetType(CFNumberRef number) {
    CF_OBJC_FUNCDISPATCHV(CFNumberGetTypeID(), CFNumberType, (NSNumber *)number, _cfNumberType);
    CF_SWIFT_FUNCDISPATCHV(CFNumberGetTypeID(), CFNumberType, (CFSwiftRef)number, NSNumber._cfNumberGetType);
    __CFAssertIsNumber(number);
    CFNumberType type = __CFNumberGetType(number);
    if (kCFNumberSInt128Type == type) type = kCFNumberSInt64Type; // must hide this type, since it is not public
    return type;
}

CF_EXPORT CFNumberType _CFNumberGetType2(CFNumberRef number) {
    CF_OBJC_FUNCDISPATCHV(CFNumberGetTypeID(), CFNumberType, (NSNumber *)number, _cfNumberType);
    __CFAssertIsNumber(number);
    return __CFNumberGetType(number);
}

CFIndex CFNumberGetByteSize(CFNumberRef number) {
    __CFAssertIsNumber(number);
    CFIndex r = 1 << __CFNumberTypeTable[CFNumberGetType(number)].lgByteSize;
    return r;
}

Boolean CFNumberIsFloatType(CFNumberRef number) {
    __CFAssertIsNumber(number);
    Boolean r = __CFNumberTypeTable[CFNumberGetType(number)].floatBit;
    return r;
}

Boolean CFNumberGetValue(CFNumberRef number, CFNumberType type, void *valuePtr) {
//printf("+ [%p] CFNumberGetValue(%p, %d, %p)\n", pthread_self(), number, type, valuePtr);

    CF_OBJC_FUNCDISPATCHV(CFNumberGetTypeID(), Boolean, (NSNumber *)number, _getValue:(void *)valuePtr forType:(CFNumberType)__CFNumberTypeTable[type].canonicalType);
    CF_SWIFT_FUNCDISPATCHV(CFNumberGetTypeID(), Boolean, (CFSwiftRef)number, NSNumber._getValue, valuePtr, (CFNumberType)__CFNumberTypeTable[type].canonicalType);
    __CFAssertIsNumber(number);
    __CFAssertIsValidNumberType(type);
    uint8_t localMemory[128];
    Boolean r = __CFNumberGetValueCompat(number, type, valuePtr ? valuePtr : localMemory);
    return r;
}

static CFComparisonResult CFNumberCompare_new(CFNumberRef number1, CFNumberRef number2, void *context) {
    CF_OBJC_FUNCDISPATCHV(CFNumberGetTypeID(), CFComparisonResult, (NSNumber *)number1, compare:(NSNumber *)number2);
    CF_OBJC_FUNCDISPATCHV(CFNumberGetTypeID(), CFComparisonResult, (NSNumber *)number2, _reverseCompare:(NSNumber *)number1);
    __CFAssertIsNumber(number1);
    __CFAssertIsNumber(number2);

    CFNumberType type1 = __CFNumberGetType(number1);
    CFNumberType type2 = __CFNumberGetType(number2);
    // Both numbers are integers
    if (!__CFNumberTypeTable[type1].floatBit && !__CFNumberTypeTable[type2].floatBit) {
        CFSInt128Struct i1, i2;
        __CFNumberGetValue(number1, kCFNumberSInt128Type, &i1);
        __CFNumberGetValue(number2, kCFNumberSInt128Type, &i2);
        return cmp128(&i1, &i2);
    }
    // Both numbers are floats
    if (__CFNumberTypeTable[type1].floatBit && __CFNumberTypeTable[type2].floatBit) {
	Float64 d1, d2;
        __CFNumberGetValue(number1, kCFNumberFloat64Type, &d1);
        __CFNumberGetValue(number2, kCFNumberFloat64Type, &d2);
	double s1 = copysign(1.0, d1);
	double s2 = copysign(1.0, d2);
	if (isnan(d1) && isnan(d2)) return kCFCompareEqualTo;
	if (isnan(d1)) return (s2 < 0.0) ? kCFCompareGreaterThan : kCFCompareLessThan;
	if (isnan(d2)) return (s1 < 0.0) ? kCFCompareLessThan : kCFCompareGreaterThan;
	// at this point, we know we don't have any NaNs
	if (s1 < s2) return kCFCompareLessThan;
	if (s2 < s1) return kCFCompareGreaterThan;
	// at this point, we know the signs are the same; do not combine these tests
	if (d1 < d2) return kCFCompareLessThan;
	if (d2 < d1) return kCFCompareGreaterThan;
        return kCFCompareEqualTo;
    }
    // One float, one integer; swap if necessary so number1 is the float
    Boolean swapResult = false;
    if (__CFNumberTypeTable[type2].floatBit) {
        CFNumberRef tmp = number1;
	number1 = number2;
	number2 = tmp;
	swapResult = true;
    }
    // At large integer values, the precision of double is quite low
    // e.g. all values roughly 2^127 +- 2^73 are represented by 1 double, 2^127.
    // If we just used double compare, that would make the 2^73 largest 128-bit
    // integers look equal, so we have to use integer comparison when possible.
    Float64 d1, d2;
    __CFNumberGetValue(number1, kCFNumberFloat64Type, &d1);
    // if the double value is really big, cannot be equal to integer
    // nan d1 will not compare true here
    if (d1 < FLOAT_NEGATIVE_2_TO_THE_127) {
	return !swapResult ? kCFCompareLessThan : kCFCompareGreaterThan;
    }
    if (FLOAT_POSITIVE_2_TO_THE_127 <= d1) {
	return !swapResult ? kCFCompareGreaterThan : kCFCompareLessThan;
    }
    CFSInt128Struct i1, i2;
    __CFNumberGetValue(number1, kCFNumberSInt128Type, &i1);
    __CFNumberGetValue(number2, kCFNumberSInt128Type, &i2);
    CFComparisonResult res = cmp128(&i1, &i2);
    if (kCFCompareEqualTo != res) {
	return !swapResult ? res : -res;
    }
    // now things are equal, but perhaps due to rounding or nan
    if (isnan(d1)) {
	if (isNeg128(&i2)) {
	    return !swapResult ? kCFCompareGreaterThan : kCFCompareLessThan;
	}
	// nan compares less than positive 0 too
	return !swapResult ? kCFCompareLessThan : kCFCompareGreaterThan;
    }
    // at this point, we know we don't have NaN
    double s1 = copysign(1.0, d1);
    double s2 = isNeg128(&i2) ? -1.0 : 1.0;
    if (s1 < s2) return !swapResult ? kCFCompareLessThan : kCFCompareGreaterThan;
    if (s2 < s1) return !swapResult ? kCFCompareGreaterThan : kCFCompareLessThan;
    // at this point, we know the signs are the same; do not combine these tests
    __CFNumberGetValue(number2, kCFNumberFloat64Type, &d2);
    if (d1 < d2) return !swapResult ? kCFCompareLessThan : kCFCompareGreaterThan;
    if (d2 < d1) return !swapResult ? kCFCompareGreaterThan : kCFCompareLessThan;
    return kCFCompareEqualTo;
}

CFComparisonResult CFNumberCompare(CFNumberRef number1, CFNumberRef number2, void *context) {
    CFComparisonResult r = CFNumberCompare_new(number1, number2, context);
    return r;
}

#undef __CFAssertIsBoolean
#undef __CFAssertIsNumber
#undef __CFAssertIsValidNumberType
#undef BITSFORDOUBLENAN
#undef BITSFORDOUBLEPOSINF
#undef BITSFORDOUBLENEGINF
#undef MinCachedInt
#undef MaxCachedInt
#undef NotToBeCached

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace MurphyPA.H2D.TestApp
{
	using System.Windows.Forms;
	/// <summary>
	/// Summary description for LoadFileWithDialogCommand.
	/// </summary>
	public class LoadFileWithDialogCommand : DiagramCommandBase
	{
		OpenFileDialog _OpenFileDialog;
		public LoadFileWithDialogCommand (IUIInterationContext context, OpenFileDialog openFileDialog, Button button, MenuItem menuItem)
			: base (context, button, menuItem)
		{
			_OpenFileDialog = openFileDialog;
		}

		public override void Execute()
		{
			_OpenFileDialog.InitialDirectory = Environment.CurrentDirectory;
			DialogResult dialogResult = _OpenFileDialog.ShowDialog ();
			if (dialogResult == DialogResult.OK)
			{
				Context.ClearModel ();
				LoadFile (_OpenFileDialog.FileName);
				Context.ShowHeader ();
				Context.Model.Header.ReadOnly = Context.Model.HasGlyphs ();
			}
		}

		private void LoadFile (string fileName)
		{
			LoadFileCommand command = new LoadFileCommand (fileName, Context);
			command.Execute ();
		}
	}
}


text:
namespace SharpNet.System.Abstract
{
    public interface IAcceptChars
    {
        void Accept(char val);
    }
}


text:
<?xml version='1.0' encoding='utf-8' ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		<title>EGit 3.0 New and Noteworthy - Bug Fixes</title>
		<link type="text/css" rel="stylesheet" href="../../../book.css"/>

				Bug Fixes

				Performance Improvements

				API changes

Bug Fixes

Fix commit keyboard shortcut Ctrl+# (
				bug 363648).

Fix rebase pulldown in toolbar not being accessible during rebase (
				bug 387184).

Fix NPE when operating on a selection containing a linked resource pointing to a file or directory outside of a workspace project git repository (
				bug 406922).

Fix branch names shown in Configure Branch dialog (
				bug 407465).

			116 Bugs and 23 enhancement requests were closed

				Performance Improvements

				API changes


text:
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var path = require("path");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');

module.exports = function(ENV, options) {
  return {
    /**
     * Resolve
     * Make bower_components available for the resolvers
     */
    resolve: {
      root: [path.join(__dirname, "./bower_components")],
      alias: {
        appConstants: "./" + ENV + ".constants.js"
      }
    },
    /**
     * Entry
     * Reference: http://webpack.github.io/docs/configuration.html#entry
     * Should be an empty object if it's generating a test build
     * Karma will set this when it's a test build
     */
    entry: {
      app: './client/app/app.js'
    },
    /**
     * ESLint
     * use the .eslint config
     * optionally enable autofix to force rules
     */
    eslint: {
      configFile: '.eslintrc',
      //fix: true
    },
    /**
     * Output
     * Reference: http://console.github.io/docs/configuration.html#output
     * Should be an empty object if it's generating a test build
     * Karma will handle setting it up for you when it's a test build
     */
    output: {
      // Absolute output directory
      path: __dirname + '/../dist',
      publicPath: 'http://localhost:' + options.devServerPort+"/",
      filename: '[name].bundle.js',
      chunkFilename: '[name].bundle.js'
    },
    /**
     * Devtool settings
     * Reference: http://webpack.github.io/docs/configuration.html#devtool
     */
    devtool: '#eval-module-source-map',
    /**
     * PostCSS
     * Reference: https://github.com/postcss/autoprefixer-core
     * Add vendor prefixes to your css
     */
    postcss: [
      autoprefixer({
        browsers: ['last 2 version']
      })
    ],
    /**
     * Dev server configuration
     * Reference: http://webpack.github.io/docs/configuration.html#devserver
     * Reference: http://webpack.github.io/docs/webpack-dev-server.html
     */
    devServer: {
      contentBase: '../dist',
      stats: {
        modules: false,
        cached: false,
        colors: true,
        chunk: true,
        inline: true,
        progres: true,
        hot: true
      },
      port: options.devServerPort
    },
    /**
     * Loaders
     * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
     * List: http://webpack.github.io/docs/list-of-loaders.html
     * This handles most of the magic responsible for converting modules
     */
    module: {
      preloaders: [],
      loaders: [{
        // JS LOADER
        // Reference: https://github.com/babel/babel-loader
        test: /\.(js|jsx)$/,
        loader: 'babel',
        exclude: [/node_modules/, /bower_components/]
      },
      {
        // ASSET LOADER
        // Reference: https://github.com/webpack/file-loader
        // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
        // Rename the file using the asset hash
        // Pass along the updated reference to your code
        // You can add here any file extension you want to get copied to your output
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
        loader: "file-loader?name=[name].[ext]"
      }, {
        // HTML LOADER
        // Reference: https://github.com/webpack/raw-loader
        // Allow loading html through js
        test: /\.html$/,
        loader: 'raw'
      },
       {
        test: /\.css$/,
        // Reference: https://github.com/webpack/extract-text-webpack-plugin
        // Extract css files in production builds
        //
        // Reference: https://github.com/webpack/style-loader
        // Use style-loader in development for hot-loading
        loader: ExtractTextPlugin.extract('style',
          'css?sourceMap!postcss')
      },
      {
       // Sass Loader
       test: /\.scss$/,
       loaders: ["style", "css", "sass"]
      },
      {
        // ESLint loader
        test: /\.js$/,
        loader: "eslint-loader",
        exclude: [/node_modules/, /bower_components/]
      }]
    },
    /**
     * Plugins
     * Reference: http://webpack.github.io/docs/configuration.html#plugins
     * List: http://webpack.github.io/docs/list-of-plugins.html
     */
    plugins: [

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
    // Extract css files
    // Disabled when in test mode or not in build mode
      new ExtractTextPlugin('[name].css', {
      }),
      new ngAnnotatePlugin({
        add: true,
        // other ng-annotate options here
      }),
      new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(
          "../bower.json", ["main"])
      ),
      new HtmlWebpackPlugin({
        template:'./client/index.html',
        inject: 'body'
      }),
      new webpack.ProvidePlugin({
        moment         : "moment",
        "window.moment": "moment"
      }),
      new webpack.ProvidePlugin({
        _         : "lodash",
        "window._": "lodash"
      })
    ]
  }
}


text:
.RadEDomMouseOver
{
	background-color:#efefef;
	border:1px dashed red;
}

.RadEContent, .RadEContentBordered
{
	padding:3px;

	background-image: none;
	margin: 0px;
	text-align: left;
	scrollbar-face-color: #BACBF4;
	scrollbar-highlight-color: #FFFFFF;
	scrollbar-shadow-color: #7E9FD2;
	scrollbar-3dlight-color: #E6EEFC;
	scrollbar-arrow-color: #4D6185;
	scrollbar-track-color: #F7F7F3;
	scrollbar-darkshadow-color: #C6D1DC;
	word-wrap: break-word;
}

.RadEContentBordered form
{
	 background-color:#efefef;
	 border:1px dashed #555555;
}
/* CSS class for A name */

.RadEContentBordered table
{
	BORDER-RIGHT: #999999 1px dashed;
	BORDER-BOTTOM: #999999 1px dashed;
}

.RadEContentBordered table td
{
	PADDING: 2px;
	BORDER-TOP: #999999 1px dashed;
	BORDER-LEFT: #999999 1px dashed;
}

.RadEContentBordered table th
{
	PADDING: 2px;
	BORDER-TOP: #000000 1px dashed;
	BORDER-LEFT: #000000 1px dashed;
}


text:
from .sqlite_platform import SQLitePlatform
from .mysql_platform import MySQLPlatform
from .mysql57_platform import MySQL57Platform
from .postgres_platform import PostgresPlatform


text:
"use strict";

//var mongoDbUrl = process.env.NODE_ENV === 'test' ?
//	'mongodb://localhost/selu-test' :
//	'mongodb://localhost/selu';
//
var app = require('./app/index');
app('mongodb://localhost/selu');


text:
from django.db import migrations, models

from part.models import Part

def update_tree(apps, schema_editor):
    # Update the MPTT for Part model
    Part.objects.rebuild()

def nupdate_tree(apps, schema_editor):  # pragma: no cover
    pass

class Migration(migrations.Migration):

    atomic = False

    dependencies = [
        ('part', '0038_auto_20200513_0016'),
    ]

    operations = [
        migrations.AddField(
            model_name='part',
            name='level',
            field=models.PositiveIntegerField(default=0, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='part',
            name='lft',
            field=models.PositiveIntegerField(default=0, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='part',
            name='rght',
            field=models.PositiveIntegerField(default=0, editable=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='part',
            name='tree_id',
            field=models.PositiveIntegerField(db_index=True, default=0, editable=False),
            preserve_default=False,
        ),

        migrations.RunPython(update_tree, reverse_code=nupdate_tree)
    ]


text:
<m:GetItemResponse xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
      <m:ResponseMessages>
        <m:GetItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Items>
            <t:Message>
              <t:ItemId Id="EEE" ChangeKey="999"/>
              <t:Subject>I am a subject. Hear me roar.</t:Subject>
              <t:Sensitivity>Normal</t:Sensitivity>
              <t:Body BodyType="HTML">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ullamcorper egestas accumsan. Nulla rhoncus porttitor dictum. Curabitur ac nulla a orci sollicitudin blandit at quis odio. Integer eleifend fringilla bibendum. Sed condimentum, lectus vitae suscipit sollicitudin, quam tortor faucibus nisl, ac tristique lectus justo in leo. Aliquam placerat arcu erat, vel lobortis dui. Nulla posuere sodales sapien eu interdum. Cras in pretium ante. Pellentesque ut velit est. Quisque nisl risus, molestie vel porta in, pellentesque a odio. Curabitur sit amet faucibus lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas et fermentum enim. Nulla ac dolor elit. Quisque eu dui sapien, ac tincidunt orci.</t:Body>
              <t:Attachments>
                <t:ItemAttachment>
                  <t:AttachmentId Id="XXX"/>
                  <t:Name>I have attached myself to this message.</t:Name>
                  <t:ContentType>message/rfc822</t:ContentType>
                </t:ItemAttachment>
              </t:Attachments>
              <t:Size>5496</t:Size>
              <t:DateTimeSent>2009-12-02T16:38:47Z</t:DateTimeSent>
              <t:DateTimeCreated>2009-12-02T16:38:47Z</t:DateTimeCreated>
              <t:ResponseObjects>
                <t:ForwardItem/>
              </t:ResponseObjects>
              <t:HasAttachments>true</t:HasAttachments>
              <t:ToRecipients>
                <t:Mailbox>
                  <t:Name>doesnotexist@example.com</t:Name>
                  <t:EmailAddress>doesnotexist@example.com</t:EmailAddress>
                  <t:RoutingType>SMTP</t:RoutingType>
                </t:Mailbox>
              </t:ToRecipients>
              <t:IsReadReceiptRequested>false</t:IsReadReceiptRequested>
              <t:IsDeliveryReceiptRequested>false</t:IsDeliveryReceiptRequested>
              <t:From>
                <t:Mailbox>
                  <t:Name>Mail Delivery System</t:Name>
                  <t:EmailAddress>MAILER-DAEMON@example.com</t:EmailAddress>
                  <t:RoutingType>SMTP</t:RoutingType>
                </t:Mailbox>
              </t:From>
              <t:IsRead>true</t:IsRead>
            </t:Message>
          </m:Items>
        </m:GetItemResponseMessage>
      </m:ResponseMessages>
    </m:GetItemResponse>


text:
<?php

namespace Genesis\API\Constants\Transaction\Parameters\Threeds\V2\MerchantRisk;

/**
 * Indicates whether the cardholder is reordering previously purchased merchandise.
 *
 * Class ReorderItemIndicators
 * @package Genesis\API\Constants\Transaction\Parameters\Threeds\V2\MerchantRisk
 */
class ReorderItemIndicators
{
    /**
     * First Time
     */
    const FIRST_TIME = 'first_time';

    /**
     * Reordered
     */
    const REORDERED  ='reordered';

    /**
     * Get all the Reorder Item Indicators
     *
     * @return array
     */
    public static function getAll()
    {
        return [
            self::FIRST_TIME, self::REORDERED
        ];
    }
}


text:
typedef struct request_t {
    char *buf;
    off_t offset;
    time_t time;
} request_t;

void handle_request(request_t * req);
#endif                          //__REQUEST_H__


text:
require "spec_helper"

RSpec.describe SphereEngine do
  it "has a version number" do
    expect(SphereEngine::VERSION).not_to be nil
  end
end


text:
  	General

  	Advanced

  	Install


text:
"use strict";

import Immutable from "immutable";

export class Atom {
  /**
   * @constructor
   * Constructs a new Atom from an immutable object.
   * If the object is mutable, it will be converted automatically to an Immutable.js object.
   */
  constructor(immutableObject) {
    if(immutableObject instanceof Immutable.Iterable) {
      this._ref = immutableObject;
    } else {
      this._ref = Immutable.fromJS(immutableObject);
    }
    this._lock = false;
    this._listeners = Immutable.List([]);
  }

  /**
   * @return The referenced immutable structure
   */
  deref() {
    return this._ref;
  }

  /**
   * Adds a new change listener to the store
   * @param listener A callback function
   */
  addChangeListener(listener) {
    this._listeners = this._listeners.push(listener);
  }

  /**
   * Atomically sets the value of atom to newval if and only if the current value of the atom is identical to oldval.
   * @param oldval The expected current value of the atom
   * @param newval The targeted value of the atom
   * @return The success of the operation
   */
  compareAndSet(oldval, newval) {
    // Really bad mutex implementation (multithreaded node.js won't work, but this may not happen)
    // TODO: do something better
    while(this._lock) {}
    this._lock = true;

    var updated = false;
    if(this.deref().equals(oldval)) {
      if(newval instanceof Immutable.Iterable) {
        this._ref = newval;
      } else {
        this._ref = Immutable.fromJS(newval);
      }
      updated = true;
    }
    this._lock = false;
    this._listeners.forEach((listener) => {
      listener(this._ref);
    });
    return updated;
  }

  /*
   * Atomically swaps the value of atom to be: f.apply(currentValueOfAtom, args)
   * Note that f may be called multiple times, and thus should be free of side effects.
   * @param f The pure function to apply on the swap
   * @param *args The other expected args to apply on the swap
   * @return The swapped new value
   */
  swap(f) {
    var args = Array.prototype.slice.call(arguments, 1);
    // TODO: Make it better too
    while(!this.compareAndSet(this._ref, f.apply(this._ref, args))) {}
    return this._ref;
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace CatLib._3rd.SharpCompress.Compressors.LZMA
{
    internal class Bcj2DecoderStream : DecoderStream2
    {
        private const int kNumTopBits = 24;
        private const uint kTopValue = (1 << kNumTopBits);

        private class RangeDecoder
        {
            internal readonly Stream mStream;
            internal uint Range;
            internal uint Code;

            public RangeDecoder(Stream stream)
            {
                mStream = stream;
                Range = 0xFFFFFFFF;
                for (int i = 0; i < 5; i++)
                {
                    Code = (Code << 8) | ReadByte();
                }
            }

            public byte ReadByte()
            {
                int bt = mStream.ReadByte();
                if (bt < 0)
                {
                    throw new EndOfStreamException();
                }

                return (byte)bt;
            }

            public void Dispose()
            {
                mStream.Dispose();
            }
        }

        private class StatusDecoder
        {
            private const int numMoveBits = 5;

            private const int kNumBitModelTotalBits = 11;
            private const uint kBitModelTotal = 1u << kNumBitModelTotalBits;

            private uint Prob;

            public StatusDecoder()
            {
                Prob = kBitModelTotal / 2;
            }

            private void UpdateModel(uint symbol)
            {
                /*
                Prob -= (Prob + ((symbol - 1) & ((1 << numMoveBits) - 1))) >> numMoveBits;
                Prob += (1 - symbol) << (kNumBitModelTotalBits - numMoveBits);
                */
                if (symbol == 0)
                {
                    Prob += (kBitModelTotal - Prob) >> numMoveBits;
                }
                else
                {
                    Prob -= (Prob) >> numMoveBits;
                }
            }

            public uint Decode(RangeDecoder decoder)
            {
                uint newBound = (decoder.Range >> kNumBitModelTotalBits) * Prob;
                if (decoder.Code < newBound)
                {
                    decoder.Range = newBound;
                    Prob += (kBitModelTotal - Prob) >> numMoveBits;
                    if (decoder.Range < kTopValue)
                    {
                        decoder.Code = (decoder.Code << 8) | decoder.ReadByte();
                        decoder.Range <<= 8;
                    }
                    return 0;
                }
                decoder.Range -= newBound;
                decoder.Code -= newBound;
                Prob -= Prob >> numMoveBits;
                if (decoder.Range < kTopValue)
                {
                    decoder.Code = (decoder.Code << 8) | decoder.ReadByte();
                    decoder.Range <<= 8;
                }
                return 1;
            }
        }

        private readonly Stream mMainStream;
        private readonly Stream mCallStream;
        private readonly Stream mJumpStream;
        private readonly RangeDecoder mRangeDecoder;
        private readonly StatusDecoder[] mStatusDecoder;
        private long mWritten;
        private readonly IEnumerator<byte> mIter;
        private bool mFinished;
        private bool isDisposed;

        public Bcj2DecoderStream(Stream[] streams, byte[] info, long limit)
        {
            if (info != null && info.Length > 0)
            {
                throw new NotSupportedException();
            }

            if (streams.Length != 4)
            {
                throw new NotSupportedException();
            }

            mMainStream = streams[0];
            mCallStream = streams[1];
            mJumpStream = streams[2];
            mRangeDecoder = new RangeDecoder(streams[3]);

            mStatusDecoder = new StatusDecoder[256 + 2];
            for (int i = 0; i < mStatusDecoder.Length; i++)
            {
                mStatusDecoder[i] = new StatusDecoder();
            }

            mIter = Run().GetEnumerator();
        }

        protected override void Dispose(bool disposing)
        {
            if (isDisposed)
            {
                return;
            }
            isDisposed = true;
            base.Dispose(disposing);
            mMainStream.Dispose();
            mCallStream.Dispose();
            mJumpStream.Dispose();
        }

        private static bool IsJcc(byte b0, byte b1)
        {
            return b0 == 0x0F
                   && (b1 & 0xF0) == 0x80;
        }

        private static bool IsJ(byte b0, byte b1)
        {
            return (b1 & 0xFE) == 0xE8
                   || IsJcc(b0, b1);
        }

        private static int GetIndex(byte b0, byte b1)
        {
            if (b1 == 0xE8)
            {
                return b0;
            }
            if (b1 == 0xE9)
            {
                return 256;
            }
            return 257;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (count == 0 || mFinished)
            {
                return 0;
            }

            for (int i = 0; i < count; i++)
            {
                if (!mIter.MoveNext())
                {
                    mFinished = true;
                    return i;
                }

                buffer[offset + i] = mIter.Current;
            }

            return count;
        }

        public IEnumerable<byte> Run()
        {
            const uint kBurstSize = (1u << 18);

            byte prevByte = 0;
            uint processedBytes = 0;
            for (;;)
            {
                byte b = 0;
                uint i;
                for (i = 0; i < kBurstSize; i++)
                {
                    int tmp = mMainStream.ReadByte();
                    if (tmp < 0)
                    {
                        yield break;
                    }

                    b = (byte)tmp;
                    mWritten++;
                    yield return b;
                    if (IsJ(prevByte, b))
                    {
                        break;
                    }

                    prevByte = b;
                }

                processedBytes += i;
                if (i == kBurstSize)
                {
                    continue;
                }

                if (mStatusDecoder[GetIndex(prevByte, b)].Decode(mRangeDecoder) == 1)
                {
                    Stream s = (b == 0xE8) ? mCallStream : mJumpStream;

                    uint src = 0;
                    for (i = 0; i < 4; i++)
                    {
                        int b0 = s.ReadByte();
                        if (b0 < 0)
                        {
                            throw new EndOfStreamException();
                        }

                        src <<= 8;
                        src |= (uint)b0;
                    }

                    uint dest = src - (uint)(mWritten + 4);
                    mWritten++;
                    yield return (byte)dest;
                    mWritten++;
                    yield return (byte)(dest >> 8);
                    mWritten++;
                    yield return (byte)(dest >> 16);
                    mWritten++;
                    yield return (byte)(dest >> 24);
                    prevByte = (byte)(dest >> 24);
                    processedBytes += 4;
                }
                else
                {
                    prevByte = b;
                }
            }
        }
    }
}


text:
<?php

namespace Wukka\Test;

use Exception;

/**
* Sometimes it is difficult to test all possible behaviors of a class through straightforward
* blackbox testing. When external dependencies cannot easily be passed in consider making a stub
* factory methods for them and injecting a stub so you can control the behavior.
*
* When I do have to test with a stub class, I often do both. I test as much as possible without using
* stubs at all to make sure those external depencies work. then I inject stubs in to test things like
* error cases that aren't easily simulated, like database error handling, or conditions that trigger
* exceptions.
*/

class Stub {

    protected $m;

    public function __construct( array $methods ){
        $this->m = array();
        foreach( $methods as $k => $v ){
            if( ! $v instanceof \Closure ) throw new Exception("invalid method handler for: $k");
            $this->m[ strtolower( $k ) ] = $v;
        }
    }

    public function __call( $method, array $args ){
        $method = strtolower( $method );
        if( ! isset( $this->m[ $method ] ) ) throw new Exception('call to undefined method: ' . $method);
        $cb = $this->m[ $method ];
        return call_user_func_array( $cb, $args );
    }

    public function __isset($k ){
        if( isset( $this->m['__isset'] )) return $this->__call('__isset', array( $k ) );
        $v = $this->__get( $k );
        return isset( $v );
    }

    public function __get( $k ){
        return $this->__call('__get', array( $k ) );
    }

    public function __set( $k, $v){
        return $this->__call('__set', array( $k, $v ) );
    }

    public function __unset( $k ){
        if( isset( $this->m['__unset'] )) {
            $this->__call('__unset', array( $k ) );
            return;
        }
        $this->__call('__set', array( $k, NULL ) );
    }
}


text:
`vkontakte_api` — ruby-адаптер для ВКонтакте API. Он позволяет вызывать методы API, загружать файлы на сервера ВКонтакте, а также поддерживает все 3 доступных способа авторизации (при этом позволяя использовать стороннее решение).

## English version
For English version please go [here](README_en.md).

## Установка

``` ruby
# Gemfile
gem 'vkontakte_api', '~> 1.4'
```

или просто

``` sh
$ gem install vkontakte_api
```

## Использование

### Вызов методов

``` ruby
# создаем клиент
@vk = VkontakteApi::Client.new
# и вызываем методы API
@vk.users.get(user_ids: 1)

# в ruby принято использовать snake_case в названиях методов,
# поэтому likes.getList становится likes.get_list
@vk.likes.get_list
# также названия методов, которые возвращают '1' или '0',
# заканчиваются на '?', а возвращаемые значения приводятся
# к true или false
@vk.is_app_user? # => false

# если ВКонтакте ожидает получить параметр в виде списка,
# разделенного запятыми, то его можно передать массивом
users = @vk.users.get(user_ids: [1, 2, 3])

# большинство методов возвращает структуры Hashie::Mash
# и массивы из них
users.first.uid        # => 1
users.first.first_name # => "Павел"
users.first.last_name  # => "Дуров"

# если метод, возвращающий массив, вызывается с блоком,
# то блок будет выполнен для каждого элемента,
# и метод вернет обработанный массив
fields = [:first_name, :last_name, :screen_name]
@vk.friends.get(user_id: 2, fields: fields) do |friend|
  "#{friend.first_name} '#{friend.screen_name}' #{friend.last_name}"
end
# => ["Павел 'durov' Дуров"]
```

### Загрузка файлов

Загрузка файлов на сервера ВКонтакте осуществляется в несколько этапов: сначала вызывается метод API, возвращающий URL для загрузки, затем происходит сама загрузка файлов, и после этого в некоторых случаях нужно вызвать другой метод API, передав в параметрах данные, возвращенные сервером после предыдущего запроса. Вызываемые методы API зависят от типа загружаемых файлов и описаны в [соответствующем разделе документации](https://vk.com/dev/upload_files).

Файлы передаются в формате хэша, где ключом является название параметра в запросе (указано в документации, например для загрузки фото на стену это будет `photo`), а значением — массив из 2 строк: полный путь к файлу и его MIME-тип:

``` ruby
url = 'http://cs303110.vkontakte.ru/upload.php?act=do_add'
VkontakteApi.upload(url: url, photo: ['/path/to/file.jpg', 'image/jpeg'])
```

Если загружаемый файл доступен как открытый IO-объект, его можно передать альтернативным синтаксисом — IO-объект, MIME-тип и путь к файлу:

``` ruby
url = 'http://cs303110.vkontakte.ru/upload.php?act=do_add'
VkontakteApi.upload(url: url, photo: [file_io, 'image/jpeg', '/path/to/file.jpg'])
```

Метод вернет ответ сервера ВКонтакте, преобразованный в `Hashie::Mash`; его можно использовать при вызове метода API на последнем этапе процесса загрузки.

### Авторизация

Для вызова большинства методов требуется токен доступа (access token). Чтобы получить его, можно использовать авторизацию, встроенную в `vkontakte_api`, либо положиться на какой-то другой механизм (например, [OmniAuth](https://github.com/intridea/omniauth)). В последнем случае в результате авторизации будет получен токен, который нужно будет передать в `VkontakteApi::Client.new`.

Для работы с ВКонтакте API предусмотрено 3 типа авторизации: для сайтов, для клиентских приложений (мобильных либо десктопных, имеющих доступ к управлению браузером) и специальный тип авторизации серверов приложений для вызова административных методов без авторизации самого пользователя. Более подробно они описаны [тут](https://vk.com/dev/authentication); рассмотрим, как работать с ними средствами `vkontakte_api`.

Для авторизации необходимо задать параметры `app_id` (ID приложения), `app_secret` (защищенный ключ) и `redirect_uri` (адрес, куда пользователь будет направлен после предоставления прав приложению) в настройках `VkontakteApi.configure`. Более подробно о конфигурировании `vkontakte_api` см. далее в соответствующем разделе.

##### Сайт

Авторизация сайтов проходит в 2 шага. Сначала пользователь перенаправляется на страницу ВКонтакте для подтверждения запрошенных у него прав сайта на доступ к его данным. Со списком возможных прав можно ознакомиться [здесь](https://vk.com/dev/permissions). Допустим, нужно получить доступ к друзьям (`friends`) и фотографиям (`photos`) пользователя.

В соответствии с [рекомендациями](http://tools.ietf.org/html/draft-ietf-oauth-v2-30#section-10.12) в протоколе OAuth2 для защиты от [CSRF](http://ru.wikipedia.org/wiki/%D0%9F%D0%BE%D0%B4%D0%B4%D0%B5%D0%BB%D0%BA%D0%B0_%D0%BC%D0%B5%D0%B6%D1%81%D0%B0%D0%B9%D1%82%D0%BE%D0%B2%D1%8B%D1%85_%D0%B7%D0%B0%D0%BF%D1%80%D0%BE%D1%81%D0%BE%D0%B2), нужно передать параметр `state`, содержащий случайное значение.

``` ruby
session[:state] = Digest::MD5.hexdigest(rand.to_s)
redirect_to VkontakteApi.authorization_url(scope: [:notify, :friends, :photos], state: session[:state])
```

После подтверждения пользователь перенаправляется на указанный в настройках `redirect_uri`, причем в параметрах будет передан код, по которому можно получить токен доступа, а также переданный ранее `state`. Если `state` не совпадает с тем, который был использован при отправлении пользователя на ВКонтакте, то скорее всего это попытка CSRF-атаки — стоит отправить пользователя на повторную авторизацию.

``` ruby
redirect_to login_url, alert: 'Ошибка авторизации' if params[:state] != session[:state]
```

`vkontakte_api` предоставляет метод `VkontakteApi.authorize`, который делает запрос к ВКонтакте, получает токен и создает клиент; нужно лишь передать ему код:

``` ruby
@vk = VkontakteApi.authorize(code: params[:code])
# и теперь можно вызывать методы API на объекте @vk
@vk.is_app_user?
```

Клиент будет содержать id пользователя, авторизовавшего приложение; его можно получить с помощью метода `VkontakteApi::Client#user_id`:

``` ruby
@vk.user_id # => 123456
```

Также в этот момент полезно сохранить полученный токен (и, при необходимости, id пользователя) в БД либо в сессии, чтобы использовать их повторно:

``` ruby
current_user.token = @vk.token
current_user.vk_id = @vk.user_id
current_user.save
# позже
@vk = VkontakteApi::Client.new(current_user.token)
```

##### Клиентское приложение

Авторизация клиентского приложения несколько проще — не нужно получать токен отдельным запросом, он выдается сразу после редиректа пользователя.

``` ruby
# пользователь направляется на следующий урл
VkontakteApi.authorization_url(type: :client, scope: [:friends, :photos])
```

Необходимо принимать во внимание, что `redirect_uri` нужно выставлять на `http://api.vkontakte.ru/blank.html`, иначе не получится вызывать методы, доступные клиентским приложениям.

Когда пользователь подтвердит права приложения, он будет перенаправлен на `redirect_uri`, при этом в параметре `access_token` будет токен, который нужно передать в `VkontakteApi::Client.new`.

##### Сервер приложения

Последний тип авторизации — самый простой, т.к. не предполагает участия пользователя.

``` ruby
@vk = VkontakteApi.authorize(type: :app_server)
```

### Прочее

Если клиент API (объект класса `VkontakteApi::Client`) был создан с помощью метода `VkontakteApi.authorize`, он будет содержать информацию об id текущего пользователя (`user_id`) и о времени истечения токена (`expires_at`). Получить их можно с помощью соответствующих методов:

``` ruby
vk = VkontakteApi.authorize(code: 'c1493e81f69fce1b43')
# => #<VkontakteApi::Client:0x007fa578f00ad0>
vk.user_id    # => 628985
vk.expires_at # => 2012-12-18 23:22:55 +0400
# можно проверить, истекло ли время жизни токена
vk.expired?   # => false
```

Также можно получить список прав доступа, которые дает данный токен, в виде, аналогичном формату параметра `scope` в авторизации:

``` ruby
vk.scope # => [:friends, :groups]
```

Это работает на основе метода `getUserSettings`, причем результат запоминается после первого обращения.

Чтобы создать короткий синоним `VK` для модуля `VkontakteApi`, достаточно вызвать метод `VkontakteApi.register_alias`:

``` ruby
VkontakteApi.register_alias
VK::Client.new # => #<VkontakteApi::Client:0x007fa578d6d948>
```

При необходимости можно удалить синоним методом `VkontakteApi.unregister_alias`:

``` ruby
VK.unregister_alias
VK # => NameError: uninitialized constant VK
```

### Обработка ошибок

Если ВКонтакте API возвращает ошибку, выбрасывается исключение класса `VkontakteApi::Error`.

``` ruby
vk = VK::Client.new
vk.friends.get(user_id: 1, fields: [:first_name, :last_name, :photo])
# VkontakteApi::Error: VKontakte returned an error 7: 'Permission to perform this action is denied' after calling method 'friends.get' with parameters {"user_id"=>"1", "fields"=>"first_name,last_name,photo"}.
```

Особый случай ошибки — 14: необходимо ввести код с captcha.
В этом случае можно получить параметры капчи методами
`VkontakteApi::Error#captcha_sid` и `VkontakteApi::Error#captcha_img` — например,
[так](https://github.com/7even/vkontakte_api/issues/10#issuecomment-11666091).

### Логгирование

`vkontakte_api` логгирует служебную информацию о запросах при вызове методов.
По умолчанию все пишется в `STDOUT`, но в настройке можно указать
любой другой совместимый логгер, например `Rails.logger`.

Есть возможность логгирования 3 типов информации,
каждому соответствует ключ в глобальных настройках.

|                        | ключ настройки  | по умолчанию | уровень логгирования |
| ---------------------- | --------------- | ------------ | -------------------- |
| URL запроса            | `log_requests`  | `true`       | `debug`              |
| JSON ответа при ошибке | `log_errors`    | `true`       | `warn`               |
| JSON удачного ответа   | `log_responses` | `false`      | `debug`              |

Таким образом, в rails-приложении с настройками по умолчанию в production
записываются только ответы сервера при ошибках;
в development также логгируются URL-ы запросов.

### Пример использования

Пример использования `vkontakte_api` совместно с `eventmachine` можно посмотреть
[здесь](https://github.com/7even/vkontakte_on_em).

Также был написан [пример использования с rails](https://github.com/7even/vkontakte_on_rails),
но он больше не работает из-за отсутствия прав на вызов метода `newsfeed.get`.

## Настройка

Глобальные параметры `vkontakte_api` задаются в блоке `VkontakteApi.configure` следующим образом:

``` ruby
VkontakteApi.configure do |config|
  # параметры, необходимые для авторизации средствами vkontakte_api
  # (не нужны при использовании сторонней авторизации)
  config.app_id       = '123'
  config.app_secret   = 'AbCdE654'
  config.redirect_uri = 'http://example.com/oauth/callback'

  # faraday-адаптер для сетевых запросов
  config.adapter = :net_http
  # HTTP-метод для вызова методов API (:get или :post)
  config.http_verb = :post
  # параметры для faraday-соединения
  config.faraday_options = {
    ssl: {
      ca_path:  '/usr/lib/ssl/certs'
    },
    proxy: {
      uri:      'http://proxy.example.com',
      user:     'foo',
      password: 'bar'
    }
  }
  # максимальное количество повторов запроса при ошибках
  # работает только если переключить http_verb в :get
  config.max_retries = 2

  # логгер
  config.logger        = Rails.logger
  config.log_requests  = true  # URL-ы запросов
  config.log_errors    = true  # ошибки
  config.log_responses = false # удачные ответы

  # используемая версия API
  config.api_version = '5.21'
end
```

По умолчанию для HTTP-запросов используется `Net::HTTP`; можно выбрать
[любой другой адаптер](https://github.com/lostisland/faraday/blob/master/lib/faraday/adapter.rb),
поддерживаемый `faraday`.

ВКонтакте [позволяет](https://vk.com/dev/api_requests)
использовать как `GET`-, так и `POST`-запросы при вызове методов API.
По умолчанию `vkontakte_api` использует `POST`, но в настройке `http_verb`
можно указать `:get`, чтобы совершать `GET`-запросы.

При необходимости можно указать параметры для faraday-соединения — например,
параметры прокси-сервера или путь к SSL-сертификатам.

Чтобы при каждом вызове API-метода передавалась определенная версия API, можно
указать ее в конфигурации в `api_version`. По умолчанию версия не указана.

Чтобы сгенерировать файл с настройками по умолчанию в rails-приложении,
можно воспользоваться генератором `vkontakte_api:install`:

``` sh
$ cd /path/to/app
$ rails generate vkontakte_api:install
```

## JSON-парсер

`vkontakte_api` использует парсер [Oj](https://github.com/ohler55/oj) — это
единственный парсер, который не показал [ошибок](https://github.com/7even/vkontakte_api/issues/1)
при парсинге JSON, генерируемого ВКонтакте.

Также в библиотеке `multi_json` (обертка для различных JSON-парсеров,
которая выбирает самый быстрый из установленных в системе и парсит им)
`Oj` поддерживается и имеет наивысший приоритет; поэтому если он установлен
в системе, `multi_json` будет использовать именно его.

## Roadmap

* CLI-интерфейс с автоматической авторизацией

## Участие в разработке

Если вы хотите поучаствовать в разработке проекта, форкните репозиторий,
положите свои изменения в отдельную ветку, покройте их спеками
и отправьте мне pull request.

`vkontakte_api` тестируется под MRI `2.1`, `2.2`, `2.3` и `2.4`, а также JRuby `9.x`.
Если в одной из этих сред что-то работает неправильно, либо вообще не работает,
то это следует считать багом, и написать об этом
в [issues на Github](https://github.com/7even/vkontakte_api/issues).


text:
<?php

namespace Drupal\FunctionalTests\Routing;

use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Tests\BrowserTestBase;

/**
 * Tests the route cache when the language is not in the path.
 *
 * @group language
 */
class RouteCachingNonPathLanguageNegotiationTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['language', 'block'];

  /**
   * The admin user.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  protected function setUp() {
    parent::setUp();

    // Create and log in user.
    $this->adminUser = $this->drupalCreateUser(['administer blocks', 'administer languages', 'access administration pages']);
    $this->drupalLogin($this->adminUser);

    // Add language.
    ConfigurableLanguage::createFromLangcode('fr')->save();

    // Enable session language detection and selection.
    $edit = [
      'language_interface[enabled][language-url]' => FALSE,
      'language_interface[enabled][language-session]' => TRUE,
    ];
    $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));

    // A more common scenario is domain-based negotiation but that can not be
    // tested. Session negotiation by default is not considered by the URL
    // language type that is used to resolve the alias. Explicitly enable
    // that to be able to test this scenario.
    // @todo Improve in https://www.drupal.org/project/drupal/issues/1125428.
    $this->config('language.types')
      ->set('negotiation.language_url.enabled', ['language-session' => 0])
      ->save();

    // Enable the language switching block.
    $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, [
      'id' => 'test_language_block',
    ]);

  }

  /**
   * Tests aliases when the negotiated language is not in the path.
   */
  public function testAliases() {
    // Switch to French and try to access the now inaccessible block.
    $this->drupalGet('');

    // Create an alias for user/UID just for en, make sure that this is a 404
    // on the french page exist in english, no matter which language is
    // checked first. Create the alias after visiting frontpage to make sure
    // there is no existing cache entry for this that affects the tests.
    \Drupal::service('path.alias_storage')->save('/user/' . $this->adminUser->id(), '/user-page', 'en');

    $this->clickLink('French');
    $this->drupalGet('user-page');
    $this->assertSession()->statusCodeEquals(404);

    // Switch to english, make sure it works now.
    $this->clickLink('English');
    $this->drupalGet('user-page');
    $this->assertSession()->statusCodeEquals(200);

    // Clear cache and repeat the check, this time with english first.
    $this->resetAll();
    $this->drupalGet('user-page');
    $this->assertSession()->statusCodeEquals(200);

    $this->clickLink('French');
    $this->drupalGet('user-page');
    $this->assertSession()->statusCodeEquals(404);
  }

}


text:
package io.github.taverna_extras.component.registry;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.net.URL;

import io.github.taverna_extras.component.api.Family;
import io.github.taverna_extras.component.api.Version;
import io.github.taverna_extras.component.api.profile.Profile;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import org.apache.taverna.scufl2.api.container.WorkflowBundle;
import org.apache.taverna.scufl2.api.io.WorkflowBundleIO;

/**
 *
 *
 * @author David Withers
 */
@Ignore
public class ComponentVersionTest extends Harness {
	private Family componentFamily;
	private WorkflowBundle bundle;
	private Version componentVersion;

	@Before
	public void setUp() throws Exception {
		URL dataflowUrl = getClass().getClassLoader().getResource(
				"beanshell_test.t2flow");
		assertNotNull(dataflowUrl);
		bundle = new WorkflowBundleIO().readBundle(dataflowUrl, null);
		URL componentProfileUrl = getClass().getClassLoader().getResource(
				"ValidationComponent.xml");
		assertNotNull(componentProfileUrl);
		Profile componentProfile = util.getProfile(componentProfileUrl);
		componentFamily = componentRegistry.createComponentFamily(
				"Test Component Family", componentProfile, "Some description",
				null, null);
		componentVersion = componentFamily.createComponentBasedOn(
				"Test Component", "Some description", bundle);
	}

	@After
	public void tearDown() throws Exception {
		componentRegistry.removeComponentFamily(componentFamily);
	}

	@Test
	public void testGetVersionNumber() throws Exception {
		assertNotNull(componentVersion.getVersionNumber());
		assertEquals(componentVersion.getVersionNumber(),
				componentVersion.getVersionNumber());
	}

	@Test
	public void testGetDescription() throws Exception {
		assertNotNull(componentVersion.getDescription());
	}

	@Test
	public void testGetDataflow() throws Exception {
		assertNotNull(componentVersion.getImplementation());
		assertEquals(bundle.getIdentifier(), componentVersion.getImplementation()
				.getIdentifier());
	}

	@Test
	public void testGetComponent() throws Exception {
		assertNotNull(componentVersion.getComponent());
	}

}


text:
@interface GWTagTextField : UITextField
@property (nonatomic, copy) void(^deleteBlock)();
@end


text:
/*
*   BeHappy
*
* fenêtre d'info sur le progrès de l'update
*
*
* version DK
*/

#ifndef INFOWINDOW_H
#define INFOWINDOW_H

#include <Window.h>

class InfoWindow : public BWindow
{
public:
	InfoWindow(BRect,BWindow*);
	~InfoWindow();

	void MessageReceived(BMessage *);

private:
	BStringView *line1;
	BStringView *line2;
	BStatusBar *bar;
};

#endif //INFOWINDOW_H