text:
<?php

namespace app\assets;
use yii\web\AssetBundle;

class ContactsAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/contacts.css',
    ];
    public $js = [
    ];
    public $depends = [
        'app\assets\AppAsset'
    ];
}

redpajama_set_name: RedPajamaGithub


text:
using namespace easyunit;

typedef oop (__stdcall * smifntype)(smiOop, smiOop);

extern "C" int expansion_count;
DECLARE(SmiPrimsTests)
  smifntype smiQuo;
  symbolOop quoSymbol;
END_DECLARE

SETUP(SmiPrimsTests) {
  quoSymbol = oopFactory::new_symbol("primitiveQuo:ifFail:");
  primitive_desc* prim = primitives::lookup(quoSymbol);
  smiQuo = smifntype(prim->fn());
}

TEARDOWN(SmiPrimsTests){
}

TESTF(SmiPrimsTests, quoShouldReturnDivideReceiverByArgument) {
  ASSERT_EQUALS(5, smiOop(smiQuo(as_smiOop(2), as_smiOop(10)))->value());
}

TESTF(SmiPrimsTests, quoShouldReturnReceiverHasWrongTypeWhenNotSMI) {
  oop result = smiQuo(as_smiOop(2), smiOop(quoSymbol));
  ASSERT_EQUALS((int)markSymbol(vmSymbols::receiver_has_wrong_type()), (int)result);
}


text:
table {
    border: solid 1px darkblue;
}
tr.header {
    background-color: cornflowerblue;
    height: 200px;
}


text:
#import "CDBCloudStore.h"
#import <CDBUUID/CDBUUID.h>

#define CDB_Store_Ubiqutos_URL_Postfix @".CDB.CDBCloudStore.store.ubiquitos.URL=NSURL"
#define CDB_Store_Current_State_Postfix @".CDB.CDBCloudStore.store.current.state=CDBCloudStoreState"
#define CDB_Store_SQLite_Files_Postfixes @[@"-shm", @"-wal"]
#define CDB_Store_Ubiquitos_Content_Local_Directory_Name @"CoreDataUbiquitySupport"

NSString * _Nonnull CDBCloudStoreWillChangeNotification = @"CDBCloudStoreWillChangeNotification";
NSString * _Nonnull CDBCloudStoreDidChangeNotification = @"CDBCloudStoreDidChangeNotification";

@interface CDBCloudStore ()

@property (strong, nonatomic, readwrite) NSURL * modelURL;
@property (strong, nonatomic, readwrite) NSString * name;
@property (strong, nonatomic, readwrite) NSManagedObjectModel * model;

@property (assign, nonatomic, readwrite) BOOL localStoreDisabled;
@property (strong, nonatomic, readwrite) NSManagedObjectContext * localContext;
@property (strong, nonatomic, readwrite) NSPersistentStore * localStore;
@property (strong, nonatomic) NSURL * localStoreURL;
@property (strong, nonatomic, readwrite) NSPersistentStoreCoordinator * localStoreCoordinator;

@property (assign, nonatomic, readwrite) BOOL ubiquitosStoreDisabled;
@property (strong, nonatomic, readwrite) NSManagedObjectContext * ubiquitosContext;
@property (strong, nonatomic, readwrite) NSPersistentStore * ubiqutosStore;
@property (strong, nonatomic) NSURL * ubiquitosStoreURL;
@property (strong, nonatomic, readwrite) NSURL * ubiquitosTempStoreURL;
@property (strong, nonatomic, readwrite) NSPersistentStoreCoordinator * ubiquitosStoreCoordinator;

@end

BOOL CDBCheckStoreState(CDBCloudStoreState state, NSUInteger option) {
    BOOL result = (state & option) > 0;
    return result;
}

CDBCloudStoreState CDBAddStoreState(CDBCloudStoreState state, NSUInteger option) {
    CDBCloudStoreState result = state | option;
    return result;
}

CDBCloudStoreState CDBRemoveStoreState(CDBCloudStoreState state, NSUInteger option) {
    CDBCloudStoreState result = state & ~option;
    return result;
}

@implementation CDBCloudStore

@synthesize state = _state;

#pragma mark - property -

- (BOOL)ubiquitous {
    BOOL result = CDBCheckStoreState(self.state, CDBCloudStoreUbiquitosActive);
    return result;
}

- (NSManagedObjectContext *)currentContext {
    NSManagedObjectContext * result = nil;

    if (self.ubiquitous) {
        result = self.ubiquitosContext;
    } else {
        result = self.localContext;
    }

    return result;
}

#pragma mark lazy loading

#pragma mark context

- (NSManagedObjectContext *)localContext {
    if (self.localStoreDisabled) {
        return nil;
    }

    if (_localContext == nil
        && self.localStoreCoordinator != nil) {
        _localContext =
            [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_localContext setPersistentStoreCoordinator:self.localStoreCoordinator];
    }
    return _localContext;
}

- (NSManagedObjectContext *)ubiquitosContext {
    if (self.ubiquitosStoreDisabled) {
        return nil;
    }

    if (_ubiquitosContext == nil
        && self.ubiquitosStoreCoordinator != nil) {
        _ubiquitosContext =
            [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_ubiquitosContext setPersistentStoreCoordinator:self.ubiquitosStoreCoordinator];
    }
    return _ubiquitosContext;
}

#pragma mark store options

- (NSDictionary *)localStoreOptions {
    if (_localStoreOptions == nil) {
        _localStoreOptions =  @{NSMigratePersistentStoresAutomaticallyOption: @YES,
                                NSInferMappingModelAutomaticallyOption: @YES,
                               };
    }
    return _localStoreOptions;
}

- (NSDictionary *)ubiquitosStoreOptions {
    if (_ubiquitosStoreOptions == nil && self.name != nil) {
        _ubiquitosStoreOptions =  @{NSMigratePersistentStoresAutomaticallyOption: @YES,
                                    NSInferMappingModelAutomaticallyOption: @YES,
                                    NSPersistentStoreUbiquitousContentNameKey: self.name,
                                   };
    }
    return _ubiquitosStoreOptions;
}

#pragma mark store coordinator

- (NSPersistentStoreCoordinator *)localStoreCoordinator {
    if (_localStoreCoordinator == nil
        && self.name != nil
        && self.model != nil) {
        NSPersistentStoreCoordinator * storeCoordinator = [self defaultStoreCoordinator];

        NSError * error = nil;
        NSPersistentStore * store =
            [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                           configuration:nil
                                                     URL:self.localStoreURL
                                                 options:self.localStoreOptions
                                                   error:&error];
        if (error == nil) {
            _localStoreCoordinator = storeCoordinator;
            _localStore = store;
//            [self notifyDelegateThatCoreDataStackCreatedForUbiquitos:NO];
        }
    }

    return _localStoreCoordinator;
}

- (NSPersistentStoreCoordinator *)ubiquitosStoreCoordinator {
    if (_ubiquitosStoreCoordinator == nil
        && self.name != nil
        && self.model != nil) {
        NSPersistentStoreCoordinator * storeCoordinator = [self defaultStoreCoordinator];

        NSError * error = nil;
        NSPersistentStore * store =
        [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                       configuration:nil
                                                 URL:self.ubiquitosTempStoreURL
                                             options:self.ubiquitosStoreOptions
                                               error:&error];
        if (error == nil) {
            _ubiquitosStoreCoordinator = storeCoordinator;
            _ubiqutosStore = store;
            [self subscribeToUbiquitosStoreNotifications];
//              [self notifyDelegateThatCoreDataStackCreatedForUbiquitos:YES];
        }
    }

    return _ubiquitosStoreCoordinator;
}

- (NSManagedObjectModel *)model {
    if (_model == nil
        && self.modelURL != nil) {
        _model = [[NSManagedObjectModel alloc] initWithContentsOfURL:self.modelURL];
    }

    return _model;
}

#pragma mark urls

- (NSURL *)localStoreURL {
    NSURL * result = [[self applicationDirectoryURLForPath:NSDocumentDirectory] URLByAppendingPathComponent:self.name];
    return result;
}

- (NSURL *)ubiquitosStoreURL {
    NSURL * result = [self loadUbiquitosStoreURLUsingName:self.name];
    return result;
}

- (NSURL *)ubiquitosTempStoreURL {
    NSURL * result = [[self applicationDirectoryURLForPath:NSLibraryDirectory] URLByAppendingPathComponent:self.name];;
    return result;
}

#pragma mark - life cycle -

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - notifications -

- (void)subscribeToUbiquitosStoreNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(storesWillChange:)
                                                 name:NSPersistentStoreCoordinatorStoresWillChangeNotification
                                               object:self.ubiquitosStoreCoordinator];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(storesDidChange:)
                                                 name:NSPersistentStoreCoordinatorStoresDidChangeNotification
                                               object:self.ubiquitosStoreCoordinator];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(persistentStoreDidImportUbiquitousContentChanges:)
                                                 name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
                                               object:self.ubiquitosStoreCoordinator];
}

- (void)unsubscribeFromUbiquitosStoreNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)postNotificationUsingName:(NSString *)name {
    [[NSNotificationCenter defaultCenter] postNotificationName:name
                                                        object:self];
}

#pragma mark - public -

- (void)initiateWithName:(NSString * _Nonnull)name
                modelURL:(NSURL * _Nonnull)modelURL {
    self.modelURL = modelURL;
    self.name = name;

    [self postNotificationUsingName:CDBCloudStoreWillChangeNotification];
}

- (void)updateForUbiquityActive:(BOOL)active
     usingSameUbiquityContainer:(BOOL)sameUbiquityContainer
                        withURL:(NSURL *)containerURL {
    if (self.name.length == 0) {
        [self changeStateTo:0];
        return;
    }

    CDBCloudStoreState state = [self loadCurrentStoreStateUsingName:self.name];

    if (sameUbiquityContainer == NO) {
        state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosInitiated);
        state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosActive);
    } else {
        state = CDBAddStoreState(state, CDBCloudStoreUbiquitosInitiated);
    }

    if (active) {
        state = CDBAddStoreState(state, CDBCloudStoreUbiquitosAvailable);
    } else {
        state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosAvailable);
        state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosActive);
    }

    [self changeStateTo:state];
}

- (void)replaceLocalStoreUsingUbiquitosOneWithCompletion:(CDBErrorCompletion _Nullable)completion {
    [self dismissAndDisableLocalCoreDataStack];

    [self removeCoreDataStoreAtURL:self.localStoreURL
                        completion:^(NSError * _Nullable deletionError) {
        NSMutableDictionary * migrationOptions = [self.localStoreOptions mutableCopy];
        migrationOptions[NSPersistentStoreRemoveUbiquitousMetadataOption] = @YES;

        NSError * error = nil;
        [self.ubiquitosStoreCoordinator migratePersistentStore:self.ubiqutosStore
                                                         toURL:self.localStoreURL
                                                       options:migrationOptions
                                                      withType:NSSQLiteStoreType
                                                         error:&error];
        [self enableLocalCoreDataStack];
        if (completion != nil) {
            completion(error);
        }
    }];
}

- (void)dismissAndDisableLocalCoreDataStack {
    [_localContext performBlockAndWait:^{
        [_localContext save:nil];
    }];

    self.localStoreDisabled = YES;

    _localContext = nil;
    _localStore = nil;
    _localStoreCoordinator = nil;
}

- (void)enableLocalCoreDataStack {
    self.localStoreDisabled = NO;
}

- (void)dismissAndDisableUbiquitosCoreDataStack {
    [_ubiquitosContext performBlockAndWait:^{
        [_ubiquitosContext save:nil];
    }];

    self.ubiquitosStoreDisabled = YES;

    [self unsubscribeFromUbiquitosStoreNotifications];

    _ubiquitosContext = nil;
    _ubiqutosStore = nil;
    _ubiquitosStoreCoordinator = nil;
}

- (void)enableUbiquitosCoreDataStack {
    self.ubiquitosStoreDisabled = NO;
    [self initiateUbiquitosConnection];
}

- (void)mergeUbiquitousContentChanges:(NSNotification *)changeNotification
                         usingContext:(NSManagedObjectContext *)context {
    if (context == nil) {
        return;
    }

    [context performBlock:^{
        [context mergeChangesFromContextDidSaveNotification:changeNotification];
    }];

    [self saveContext:context];
}

- (void)rebuildUbiquitosStoreFromUbiquitousContenWithCompletion:(CDBErrorCompletion _Nullable)completion {
    NSDictionary * options = self.ubiquitosStoreOptions;

    [self dismissAndDisableUbiquitosCoreDataStack];

    NSMutableDictionary * rebuildOptions = [options mutableCopy];
    rebuildOptions[NSPersistentStoreRebuildFromUbiquitousContentOption] = @(YES);
    self.ubiquitosStoreOptions = [rebuildOptions copy];

    [self enableUbiquitosCoreDataStack];
    [self touch:self.ubiquitosStoreCoordinator];

    self.ubiquitosStoreOptions = options;

    if (completion != nil) {
        completion(nil);
    }
}

- (void)removeLocalUbiquitousContentWithCompletion:(CDBErrorCompletion _Nullable)completion {

    NSURL * firstPossibleDirectory =
        [[self applicationDirectoryURLForPath:NSDocumentDirectory]
            URLByAppendingPathComponent:CDB_Store_Ubiquitos_Content_Local_Directory_Name
                            isDirectory:YES];
    NSURL * secondPossibleDirectory =
        [[self applicationDirectoryURLForPath:NSLibraryDirectory]
            URLByAppendingPathComponent:CDB_Store_Ubiquitos_Content_Local_Directory_Name
                            isDirectory:YES];

    [self dismissAndDisableUbiquitosCoreDataStack];

    [self coordinatedRemoveItemsAtURLs:@[firstPossibleDirectory, secondPossibleDirectory]
                            completion:^(NSError * _Nullable error) {
        [self enableUbiquitosCoreDataStack];

        if (completion != nil) {
            completion(error);
        }
    }];
}

- (void)removeAllUbiquitousContentWithCompletion:(CDBErrorCompletion _Nullable)completion {
    [self dismissAndDisableLocalCoreDataStack];
    [self dismissAndDisableUbiquitosCoreDataStack];

    NSError * error = nil;

    [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:self.ubiquitosStoreURL
                                                                         options:self.ubiquitosStoreOptions
                                                                           error:&error];

    if (error != nil) {
        DLogCDB(@"failed with error %@", error);
    }

    [self enableUbiquitosCoreDataStack];
    [self enableLocalCoreDataStack];

    if (completion != nil) {
        completion(error);
    }
}

- (void)removeAllUbiquitousStoreDataWithCompletion:(CDBErrorCompletion _Nullable)completion {

    NSError * error = nil;
    for (NSEntityDescription * entity in self.model.entities) {
        @autoreleasepool {
            [CDBCloudStore performRemovingAllObjectsForEntity:entity
                                                 usingContext:self.ubiquitosContext
                                                    batchSize:1000
                                                        error:&error];
            if (error != nil) {
                RLogCDB(YES, @"removing duplicates for entity %@ failed with %@", entity.name, error);
            }
        }
    }

    [self saveContext:self.ubiquitosContext];

    if (completion != nil) {
        completion(error);
    }
}

- (void)removeCoreDataStoreAtURL:(NSURL *)URL
                      completion:(CDBErrorCompletion)completion {
    if (URL.path.length == 0) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    NSMutableArray * URLsToRemove = [NSMutableArray array];
    [URLsToRemove addObject:URL];

    NSString * name = URL.lastPathComponent;
    NSURL * containingDirectoryURL = [URL URLByDeletingLastPathComponent];

    for (NSString * postfix in CDB_Store_SQLite_Files_Postfixes) {
        NSString * fileName = [name stringByAppendingString:postfix];
        NSURL * URLToDelete = [containingDirectoryURL URLByAppendingPathComponent:fileName];
        if (URLToDelete == nil) {
            continue;
        }
        [URLsToRemove addObject:URLToDelete];
    }

    [self coordinatedRemoveItemsAtURLs:URLsToRemove
                            completion:completion];
}

#pragma mark - private -

#pragma mark store state changing

- (void)changeStateTo:(CDBCloudStoreState)incomingState {
    if (self.state == incomingState) {
        return;
    }

    BOOL shouldPostDidChangeNotification = NO;

    if (CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosAvailable)
        && CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosInitiated)) {
        incomingState = CDBAddStoreState(incomingState, CDBCloudStoreUbiquitosActive);
    }

    if (CDBCheckStoreState(self.state, CDBCloudStoreUbiquitosActive)
        && (CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosActive) == NO)) {
        [self postNotificationUsingName:CDBCloudStoreWillChangeNotification];

        [self notifyDelegateThatStoreSwitchingToLocal];

        shouldPostDidChangeNotification = YES;
    }

    if ((CDBCheckStoreState(self.state, CDBCloudStoreUbiquitosActive) == NO)
        && CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosActive)) {
        [self postNotificationUsingName:CDBCloudStoreWillChangeNotification];

        [self touch:self.ubiquitosStoreCoordinator];

        [self storeSystemProvidedUbiquitosStoreData];

        [self notifyDelegateThatStoreSwitchingToUbiquitous];

        shouldPostDidChangeNotification = YES;
    }

    if (CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosAvailable)
        && CDBCheckStoreState(incomingState, CDBCloudStoreUbiquitosInitiated) == NO) {
        [self initiateUbiquitosConnection];
    }

    _state = incomingState;
    [self saveCurrentState:_state
                 usingName:self.name];

    if (shouldPostDidChangeNotification) {
        __weak typeof (self) wself = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            [wself postNotificationUsingName:CDBCloudStoreDidChangeNotification];
        });
    }

    [self notifyDelegateThatStoreDidChangeState];
}

- (void)initiateUbiquitosConnection {
    __weak typeof (self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [wself touch:self.ubiquitosStoreCoordinator];
    });
}

#pragma mark delegate method calls

- (void)notifyDelegateThatStoreSwitchingToUbiquitous {
    if ([self.delegate respondsToSelector:@selector(ubiquitousActivationBeginAtCDBCloudStore:)]) {
        [self.delegate ubiquitousActivationBeginAtCDBCloudStore:self];
    }
}

- (void)notifyDelegateThatStoreSwitchingToLocal {
    if ([self.delegate respondsToSelector:@selector(localActivationBeginAtCDBCloudStore:)]) {
        [self.delegate localActivationBeginAtCDBCloudStore:self];
    }
}

- (void)notifyDelegateThatStoreDidChangeState {
    if ([self.delegate respondsToSelector:@selector(didChangeStateOfCDBCloudStore:)]) {
        [self.delegate didChangeStateOfCDBCloudStore:self];
    }
}

- (void)notifyDelegateThatUserWillRemoveContentOfStore {
    if ([self.delegate respondsToSelector:@selector(didDetectThatUserWillRemoveContentOfCDBCloudStore:)]) {
        [self.delegate didDetectThatUserWillRemoveContentOfCDBCloudStore:self];
    }
}

//- (void)notifyDelegateThatCoreDataStackCreatedForUbiquitos:(BOOL)ubiquitos {
//    if ([self.delegate respondsToSelector:@selector(CDBCloudStore:didCreateCoreDataStackThatUbiquitous:)]) {
//        [self.delegate CDBCloudStore:self didCreateCoreDataStackThatUbiquitous:ubiquitos];
//    }
//}

#pragma mark context

- (void)saveContext:(NSManagedObjectContext *)context {
    [context performBlockAndWait:^{
        NSError * error = nil;

        if ([context hasChanges]) {
            [context save:&error];

            if (error != nil) {
                // perform error handling
                NSLog(@"%@", [error localizedDescription]);
            }
        }
    }];
}

- (void)resetContext:(NSManagedObjectContext *)context {
    [context performBlockAndWait:^{
        [context reset];
    }];
}

#pragma mark iCloud store changes handling

- (void)persistentStoreDidImportUbiquitousContentChanges:(NSNotification *)changeNotification {
    __weak typeof (self) wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([wself.delegate respondsToSelector:@selector(CDBCloudStore:didImportUbiquitousContentChanges:)]) {
            [wself.delegate CDBCloudStore:wself
        didImportUbiquitousContentChanges:changeNotification];
        } else {
            [wself mergeUbiquitousContentChanges:changeNotification
                                    usingContext:wself.ubiquitosContext];
        }

        [wself postNotificationUsingName:CDBCloudStoreDidChangeNotification];
    });
}

- (void)storesWillChange:(NSNotification *)notification {
    if ([NSThread isMainThread]) {
        [self handleStoresWillChange:notification];
        return;
    }
    __weak typeof (self) wself = self;
    dispatch_sync(dispatch_get_main_queue(), ^{
        [wself handleStoresWillChange:notification];
    });
}

- (void)handleStoresWillChange:(NSNotification *)notification {

    NSPersistentStoreUbiquitousTransitionType transitionType =
        [self transitionTypeFromNotification:notification];

    CDBCloudStoreState state = self.state;
    switch (transitionType) {
        case NSPersistentStoreUbiquitousTransitionTypeAccountAdded: {
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeAccountRemoved: {
            state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosActive);
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeContentRemoved: {
            [self notifyDelegateThatUserWillRemoveContentOfStore];
            state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosAvailable);
            state = CDBRemoveStoreState(state, CDBCloudStoreUbiquitosActive);
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted: {
        }   break;

        default:
            break;
    }

    [self changeStateTo:state];

    [self saveContext:self.currentContext];
    [self resetContext:self.currentContext];
}

- (void)storesDidChange:(NSNotification *)notification {
    if ([NSThread isMainThread]) {
        [self handleStoresDidChange:notification];
        return;
    }
    __weak typeof (self) wself = self;
    dispatch_sync(dispatch_get_main_queue(), ^{
        [wself handleStoresDidChange:notification];
    });
}

- (void)handleStoresDidChange:(NSNotification *)notification {
    NSPersistentStoreUbiquitousTransitionType transitionType =
        [self transitionTypeFromNotification:notification];

    CDBCloudStoreState state = self.state;
    switch (transitionType) {
        case NSPersistentStoreUbiquitousTransitionTypeAccountAdded: {
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeAccountRemoved: {
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeContentRemoved: {
        }   break;

        case NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted: {
            state = CDBAddStoreState(state, CDBCloudStoreUbiquitosInitiated);
        }   break;

        default:
            break;
    }

    [self changeStateTo:state];
}

- (NSPersistentStoreUbiquitousTransitionType)transitionTypeFromNotification:(NSNotification *)notification {
    NSNumber * transition = notification.userInfo[@"NSPersistentStoreUbiquitousTransitionTypeKey"];
    NSPersistentStoreUbiquitousTransitionType result =
        (NSPersistentStoreUbiquitousTransitionType)transition.unsignedIntegerValue;
    return result;
}

#pragma mark directory urls

- (NSURL *)applicationDirectoryURLForPath:(NSSearchPathDirectory)pathDirectory {
    NSURL * result =
        [[[NSFileManager defaultManager] URLsForDirectory:pathDirectory inDomains:NSUserDomainMask] lastObject];
    return result;
}

#pragma mark store to user defaults

#pragma mark CDB.CDBCloudStore.store.ubiquitos.URL=NSURL

- (NSString *)ubiquitosStoreURLKeyUsingName:(NSString *)name {
    NSString * result = [name stringByAppendingString:CDB_Store_Ubiqutos_URL_Postfix];
    return result;
}

- (void)saveUbiquitosStoreURL:(NSURL *)storeURL
                    usingName:(NSString *)name {
    if (name.length == 0
        || storeURL == nil) {
        return;
    }

    NSString * key = [self ubiquitosStoreURLKeyUsingName:name];

    [[NSUserDefaults standardUserDefaults] setURL:storeURL
                                           forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSURL *)loadUbiquitosStoreURLUsingName:(NSString *)name {
    NSString * key = [self ubiquitosStoreURLKeyUsingName:name];

    NSURL * result = [[NSUserDefaults standardUserDefaults] URLForKey:key];
    return result;
}

#pragma mark CDB.CDBCloudStore.store.current.state=CDBCloudStoreState

- (NSString *)currentStoreTypeKeyUsingName:(NSString *)name {
    NSString * result = [name stringByAppendingString:CDB_Store_Current_State_Postfix];
    return result;
}

- (void)saveCurrentState:(CDBCloudStoreState)storeState
               usingName:(NSString *)name {
    if (name.length == 0) {
        return;
    }

    NSString * key = [self currentStoreTypeKeyUsingName:name];

    [[NSUserDefaults standardUserDefaults] setInteger:storeState
                                               forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (CDBCloudStoreState)loadCurrentStoreStateUsingName:(NSString *)name {
    NSString * key = [self currentStoreTypeKeyUsingName:name];

    CDBCloudStoreState result = (CDBCloudStoreState)[[NSUserDefaults standardUserDefaults] integerForKey:key];
    return result;
}

#pragma mark ubiquitos url store

- (void)storeSystemProvidedUbiquitosStoreData {
    NSURL * URL = self.ubiqutosStore.URL;
    DLogCDB(@"Ubiquios store URL %@", URL);
    [self saveUbiquitosStoreURL:URL
                      usingName:self.name];
}

#pragma mark store coordinator

- (NSPersistentStoreCoordinator *)defaultStoreCoordinator {
    if (self.model == nil) {
        return nil;
    }

    NSPersistentStoreCoordinator * result =
        [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
    return result;
}

#pragma mark touch

- (void)touch:(NSObject *)object {
    [object isKindOfClass:[object class]];
}

#pragma mark - files

- (void)coordinatedRemoveItemAtURL:(NSURL *)URL
                        completion:(CDBErrorCompletion)completion {
    __block NSError * error = nil;
    void (^ accessor)(NSURL * writingURL) = ^(NSURL* writingURL) {
        [[NSFileManager new] removeItemAtURL:writingURL
                                       error:&error];
    };

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        NSFileCoordinator * fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];

        [fileCoordinator coordinateWritingItemAtURL:URL
                                            options:NSFileCoordinatorWritingForDeleting
                                              error:nil
                                         byAccessor:accessor];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(error);
            }
        });
    });
}

/**
 * @brief:
 * note that we return last happend error only
**/

- (void)coordinatedRemoveItemsAtURLs:(NSArray *)URLs
                          completion:(CDBErrorCompletion)completion {
    NSMutableArray * URLsToRemove = [NSMutableArray array];
    for (NSURL * URL in URLs) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:URL.path] == NO) {
            continue;
        }
        [URLsToRemove addObject:URL];
    }

    if (URLsToRemove.count == 0) {
        if (completion != nil) {
            completion(nil);
        }
        return;
    }

    __block NSUInteger counter = URLsToRemove.count;
    __block NSError * removeError = nil;

    for (NSURL * URL in URLsToRemove) {
        [self coordinatedRemoveItemAtURL:URL
                              completion:^(NSError * _Nullable error) {
            if (error != nil) {
                removeError = error;
            }

            counter -= 1;

            if (counter == 0) {
                if (completion != nil) {
                    completion(removeError);
                }
            }
        }];
    }
}

#pragma mark - class -

#pragma mark duplicates handling

+ (void)performRemovingDublicatesForEntity:(NSEntityDescription *)entity
                         uniquePropertyKey:(NSString *)uniquePropertyKey
                              timestampKey:(NSString *)timestampKey
                              usingContext:(NSManagedObjectContext *)context
                                     error:(NSError **)error {
    NSError * internalError = nil;

    NSArray * valuesWithDupes = [self valuesWithDublicatesForEntity:entity
                                                  uniquePropertyKey:uniquePropertyKey
                                                       usingContext:context
                                                              error:&internalError];

    if (internalError != nil) {
        RLogCDB(YES, @"failed to fetch values with dupes for unique key - %@, entity %@",
                uniquePropertyKey, entity.name);
        *error = internalError;
        return;
    }

    RLogCDB(YES, @"found %ld not uniqued keys for entity %@",
            (unsigned long) valuesWithDupes.count, entity.name);

    internalError = nil;

    [self resolveDuplicatesForEntity:entity
                   uniquePropertyKey:uniquePropertyKey
                        timestampKey:timestampKey
           usingValuesWithDublicates:valuesWithDupes
                             context:context
                               error:&internalError];

    if (internalError != nil) {
        RLogCDB(YES, @"failed to resolve dupes for unique key - %@, timestamp key - %@, entity %@",
                uniquePropertyKey, timestampKey, entity.name);
        *error = internalError;
        return;
    }
}

+ (NSArray *)valuesWithDublicatesForEntity:(NSEntityDescription *)entity
                         uniquePropertyKey:(NSString *)uniquePropertyKey
                              usingContext:(NSManagedObjectContext *)context
                                     error:(NSError **)error {
    if (entity == nil
        || uniquePropertyKey.length == 0
        || context == nil) {
        return nil;
    }

    //    NSExpression * keyPathExpression = [NSExpression expressionForKeyPath:uniquePropertyKey];
    //    NSExpression * countExpression = [NSExpression expressionForFunction:@"count:" arguments:@[keyPathExpression]];
    NSExpression *countExpression = [NSExpression expressionWithFormat:@"count:(%K)", uniquePropertyKey];
    NSExpressionDescription * countExpressionDescription = [[NSExpressionDescription alloc] init];
    [countExpressionDescription setName:@"count"];
    [countExpressionDescription setExpression:countExpression];
    [countExpressionDescription setExpressionResultType:NSInteger64AttributeType];
    NSAttributeDescription * uniqueAttribute = [[entity attributesByName] objectForKey:uniquePropertyKey];

    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:entity.name];
    [request setPropertiesToFetch:@[uniqueAttribute, countExpressionDescription]];
    [request setPropertiesToGroupBy:@[uniqueAttribute]];
    [request setResultType:NSDictionaryResultType];

    NSError * internalError = nil;

    NSArray * fetchedDictionaries = [context executeFetchRequest:request
                                                           error:&internalError];

    if (internalError != nil) {
        RLogCDB(YES, @"failed to execute request: %@\
                      \r using context: %@\
                      \r error: %@",
                       request, context, internalError);
        *error = internalError;
        return nil;
    }

    NSMutableArray * result = [NSMutableArray array];
    for (NSDictionary * dict in fetchedDictionaries) {
        NSNumber * count = dict[@"count"];
        if ([count integerValue] > 1) {
            [result addObject:dict[uniquePropertyKey]];
        }
    }

    return [result copy];
}

+ (void)resolveDuplicatesForEntity:(NSEntityDescription *)entity
                 uniquePropertyKey:(NSString *)uniquePropertyKey
                      timestampKey:(NSString *)timestampKey
         usingValuesWithDublicates:(NSArray *)valuesWithDupes
                           context:(NSManagedObjectContext * _Nullable)context
                             error:(NSError **)error {

    NSFetchRequest * dupeRequest = [NSFetchRequest fetchRequestWithEntityName:entity.name];
    [dupeRequest setIncludesPendingChanges:NO];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"%K IN (%@)", uniquePropertyKey, valuesWithDupes];
    [dupeRequest setPredicate:predicate];
    NSSortDescriptor * uniquePropertySorted = [NSSortDescriptor sortDescriptorWithKey:uniquePropertyKey
                                                                            ascending:YES];
    [dupeRequest setSortDescriptors:@[uniquePropertySorted]];

    NSError * internalError = nil;

    NSArray * fetchedDupes = [context executeFetchRequest:dupeRequest
                                                    error:error];

    if (internalError != nil) {
        RLogCDB(YES, @"failed to execute dupeRequest: %@\
                \r using context: %@\
                \r error: %@",
                dupeRequest, context, internalError);
        *error = internalError;
        return;
    }

    NSUInteger removedDupesCount = 0;

    NSManagedObject * prevObject = nil;
    for (NSManagedObject * duplicate in fetchedDupes) {
        if (prevObject != nil) {
            NSString * prevObjectUniqueValue = [prevObject valueForKey:uniquePropertyKey];
            NSString * duplicateUniqueValue = [duplicate valueForKey:uniquePropertyKey];
            if ([duplicateUniqueValue isEqualToString:prevObjectUniqueValue]) {
                NSString * prevObjectTimestamp = [prevObject valueForKey:timestampKey];
                NSString * duplicateTimestamp = [duplicate valueForKey:timestampKey];
                if ([duplicateTimestamp compare:prevObjectTimestamp] == NSOrderedAscending) {
                    [context deleteObject:duplicate];
                } else {
                    [context deleteObject:prevObject];
                    prevObject = duplicate;
                }
                removedDupesCount++;
            } else {
                prevObject = duplicate;
            }
        } else {
            prevObject = duplicate;
        }
    }
    RLogCDB(YES, @"delete %ld dupes for unique key - %@, using newer timestamp logic at key - %@, entity %@",
            (unsigned long)removedDupesCount, uniquePropertyKey, timestampKey, entity.name);
}

+ (void)performBatchPopulationForEntity:(NSEntityDescription *)entity
                usingPropertiesToUpdate:(NSDictionary *)propertiesToUpdate
                              predicate:(NSPredicate *)predicate
                              inContext:(NSManagedObjectContext *)context {
    if (entity == nil
        || context == nil
        || propertiesToUpdate == nil) {
        return;
    }

    RLogCDB(YES, @"update entity %@ with %@", entity.name, propertiesToUpdate);

    NSBatchUpdateRequest * request = [[NSBatchUpdateRequest alloc] initWithEntity:entity];
    request.predicate = [NSPredicate predicateWithFormat:@"uid = nil"];
    request.propertiesToUpdate = propertiesToUpdate;
    request.resultType = NSUpdatedObjectsCountResultType;

    NSError * error = nil;
    NSBatchUpdateResult * result = (NSBatchUpdateResult *)[context executeRequest:request
                                                                            error:&error];
    if (error != nil) {
        RLogCDB(YES, @" failed update entity %@ with %@", entity.name, error);
        return;
    }

    RLogCDB(YES, @"%@ entities updated entity %@", result.result, entity.name);
}

+ (void)performBatchUIDsPopulationForEntity:(NSEntityDescription *)entity
                     usingUniquePropertyKey:(NSString *)uniquePropertyKey
                                  batchSize:(NSUInteger)batchSize
                                  inContext:(NSManagedObjectContext *)context {
    if (entity == nil
        || context == nil
        || uniquePropertyKey.length == 0) {
        return;
    }

    if (batchSize == 0) {
        batchSize = 1000;
    }

    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:entity.name];
    request.predicate = [NSPredicate predicateWithFormat:@"%K = nil", uniquePropertyKey];
    request.fetchBatchSize = batchSize;

    NSError * error = nil;
    NSArray<NSManagedObject *> * results = [context executeFetchRequest:request
                                                                  error:&error];

    if (error != nil) {
        RLogCDB(YES, @" failed fetch empty UID objects for entity %@ at unique key - %@ - with %@",
                entity.name, uniquePropertyKey, error);
        return;
    }

    NSUInteger currentIndex = 0;

    while (error == nil
           && currentIndex < results.count) {
        NSUInteger maxAvailableLenght = results.count - currentIndex;
        NSUInteger length = maxAvailableLenght < batchSize ? maxAvailableLenght
                                                           : batchSize;
        NSRange currentBatchRange = NSMakeRange(currentIndex, length);
        if (NSMaxRange(currentBatchRange) <= results.count) {
            @autoreleasepool {
                NSArray * batch = [results subarrayWithRange:currentBatchRange];
                [self populateUIDsOfManagedObjects:batch
                            usingUniquePropertyKey:(NSString * _Nullable)uniquePropertyKey
                                         inContext:context
                                             error:&error];
            }
        }

        currentIndex = NSMaxRange(currentBatchRange);
    }

    if (error != nil) {
        RLogCDB(YES, @" failed update UIDs for entity %@  at unique key - %@ - with %@",
                entity.name, uniquePropertyKey, error);
        return;
    }

    RLogCDB(YES, @"%lu UIDs created at unique key - %@ - for entity %@",
            (unsigned long)results.count, uniquePropertyKey, entity.name);
}

+ (void)populateUIDsOfManagedObjects:(NSArray<NSManagedObject *> *)mananagedObjects
              usingUniquePropertyKey:(NSString *)uniquePropertyKey
                           inContext:(NSManagedObjectContext *)context
                               error:(NSError **)error {
    for (NSManagedObject * object in mananagedObjects) {
        [object setValue:[self generateEntityUID]
                  forKey:uniquePropertyKey];
    }
    [context performBlockAndWait:^{
        [context save:error];
        [context reset];
    }];
}

+ (void)performRemovingAllObjectsForEntity:(NSEntityDescription *)entity
                              usingContext:(NSManagedObjectContext *)context
                                 batchSize:(NSUInteger)batchSize
                                     error:(NSError **)error {
    if (entity == nil
        || context == nil) {
        return;
    }

    if (batchSize == 0) {
        batchSize = 1000;
    }

    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:entity.name];
    request.fetchBatchSize = batchSize;

    NSArray<NSManagedObject *> * results = [context executeFetchRequest:request
                                                                  error:error];

    if (*error != nil) {
        RLogCDB(YES, @" failed fetch objects for entity %@ %@",
                entity.name, *error);
        return;
    }

    NSUInteger currentIndex = 0;

    while (*error == nil
           && currentIndex < results.count) {
        NSUInteger maxAvailableLenght = results.count - currentIndex;
        NSUInteger length = maxAvailableLenght < batchSize ? maxAvailableLenght
        : batchSize;
        NSRange currentBatchRange = NSMakeRange(currentIndex, length);
        if (NSMaxRange(currentBatchRange) <= results.count) {
            @autoreleasepool {
                NSArray * batch = [results subarrayWithRange:currentBatchRange];
                [self removeManagedObjects:batch
                                 inContext:context
                                     error:error];
            }
        }

        currentIndex = NSMaxRange(currentBatchRange);
    }

    if (*error != nil) {
        RLogCDB(YES, @" failed remove objects for entity %@ %@",
                entity.name, *error);
        return;
    }
}

+ (void)removeManagedObjects:(NSArray<NSManagedObject *> *)mananagedObjects
                   inContext:(NSManagedObjectContext *)context
                       error:(NSError **)error {
    for (NSManagedObject * object in mananagedObjects) {
        [context deleteObject:object];
    }
    [context performBlockAndWait:^{
        [context save:error];
        [context reset];
    }];
}

+ (NSDate *)generateTimestamp {
    NSDate * result = [NSDate date];
    return result;
}

+ (NSString *)generateEntityUID {
    NSString * result = [CDBUUID UUIDString];
    return result;
}

@end


text:
package org.spongepowered.api.util.generator.dummy;

import org.spongepowered.api.util.generator.GeneratorUtils;

public class DummyClassGeneratorProvider {

    private final GeneratorUtils.LocalClassLoader classLoader = new GeneratorUtils.LocalClassLoader(DummyClassGenerator.class.getClassLoader());
    private final DummyClassGenerator generator = new DummyClassGenerator();
    private final String targetPackage;

    /**
     * Creates a new dummy class provider.
     *
     * @param targetPackage The target package
     */
    public DummyClassGeneratorProvider(String targetPackage) {
        this.targetPackage = targetPackage;
    }

    /**
     * Creates a new class extended based on the provided {@code type} with the
     * provided {@code exceptionType} to throw for all methods provided by the
     * target class.
     *
     * @param type The type of class to generate
     * @param exceptionType The exception to throw
     * @param <T> The type of class
     * @return The generated class
     */
    @SuppressWarnings("unchecked")
    public <T> Class<T> create(final Class<T> type, Class<? extends Throwable> exceptionType) {
        String name = GeneratorUtils.getClassName(this.targetPackage, type, "DummyClass");

        return (Class<T>) this.classLoader.defineClass(name, this.generator.createClass(type, name, exceptionType));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping
    xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
    http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="BaconUser\Entity\User" table="user">
        <id name="id" type="integer">
            <generator strategy="AUTO"/>
        </id>

        <field name="email" type="string" unique="true" length="255"/>
        <field name="passwordHash" column="password_hash" type="string" length="128"/>
        <field name="username" type="string" length="255" unique="true" nullable="true"/>
        <field name="state" type="integer" length="3" nullable="true"/>
    </entity>
</doctrine-mapping>


text:
package meep

import (
	"fmt"
	"strings"
	"testing"
)

func TestReacharound(t *testing.T) {
	type Woop struct {
		TraitAutodescribing
		Wonk string
	}
	var err error
	err = &Woop{Wonk: "Bonk"}
	err = New(err)
	woop := err.(*Woop)
	if woop.Wonk != "Bonk" {
		t.Errorf("Bonk somehow became %q", woop.Wonk)
	}
	if woop.TraitAutodescribing.self == nil {
		t.Errorf("No impact")
	}
	if woop.TraitAutodescribing.self != err {
		t.Errorf("Drat")
	}
}

func TestAutodescribeSimple(t *testing.T) {
	type Woop struct {
		TraitAutodescribing
		Wonk string
	}
	err := New(&Woop{Wonk: "Bonk"})
	expect := `Error[meep.Woop]: Wonk="Bonk";`
	if expect != err.Error() {
		t.Errorf("expected %q, got %q", expect, err.Error())
	}
}

func TestAutodescribePlusCause(t *testing.T) {
	type Woop struct {
		TraitAutodescribing
		TraitCausable
		Wonk string
	}
	err := New(&Woop{
		Wonk:          "Bonk",
		TraitCausable: TraitCausable{fmt.Errorf("lecause")},
	})
	expect := `Error[meep.Woop]: Wonk="Bonk";` + "\n"
	expect += "\t" + `Caused by: lecause` + "\n"
	actual := err.Error()
	if expect != actual {
		t.Errorf("mismatch:\n  expected %q\n       got %q", expect, actual)
	}
	t.Logf("this is what a very basic error with a nested cause looks like:\n>>>\n%s\n<<<\n", actual)
}

func TestAutodescribePlusTraceableCause(t *testing.T) {
	type Woop struct {
		TraitAutodescribing
		TraitCausable
		Wonk string
	}
	type Boop struct {
		TraitTraceable
		TraitAutodescribing
	}
	err := New(&Woop{
		Wonk: "Bonk",
		TraitCausable: TraitCausable{
			New(&Boop{}),
		},
	})
	expect := `Error[meep.Woop]: Wonk="Bonk";` + "\n"
	expect += "\t" + `Caused by: Error[meep.Boop]:` + "\n"
	expect += "\t\t" + `Stack trace:` + "\n"
	expect += "\t\t\t" + `·> /trait_autodescriber_test.go:73: meep.TestAutodescribePlusTraceableCause` + "\n"

	// Cleanup is fun...
	actual := err.Error()
	// First, remove the local build path for this project.
	actual = stripCwd(actual)
	// Lines we expect following this -- as of go1.4 -- are:
	//   """
	//   expect += "\t\t\t" + `·> /usr/local/go/src/testing/testing.go:447: testing.tRunner` + "\n"
	//   expect += "\t\t\t" + `·> /usr/local/go/src/runtime/asm_amd64.s:2232: runtime.goexit` + "\n"
	//   """
	// And these are not universal or portable in *several* ways:
	//   - the line numbers aren't constant across go versions
	//   - the files aren't constant across platforms
	//   - indeed even the *number* of lines is not constant across platforms and versions
	//   - the prefix path may change if your GOROOT is unusual (as it is, on some CI platforms, even)
	// So, we must simply truncate them.
	actual = dropLastNLines(actual, 3) + "\n"

	if expect != actual {
		t.Errorf("mismatch:\n  expected %q\n       got %q", expect, actual)
	}
	t.Logf("this is what errors with causes that have stacktraces look like :D\n>>>\n%s\n<<<\n", err.Error())
}

func TestAutodescribePlusTraceableCauseDoubleTrouble(t *testing.T) {
	type Woop struct {
		TraitAutodescribing
		TraitCausable
		Wonk string
	}
	type Boop struct {
		TraitAutodescribing
		TraitCausable
		TraitTraceable
	}
	err := New(&Woop{
		Wonk: "Bonk",
		TraitCausable: TraitCausable{
			New(&Boop{
				TraitCausable: TraitCausable{
					New(&Boop{}),
				},
			}),
		},
	})
	expect := `Error[meep.Woop]: Wonk="Bonk";` + "\n"
	expect += "\t" + `Caused by: Error[meep.Boop]:` + "\n"
	expect += "\t\t" + `Caused by: Error[meep.Boop]:` + "\n"
	expect += "\t\t\t" + `Stack trace:` + "\n"
	expect += "\t\t\t\t" + `·> /trait_autodescriber_test.go:120: meep.TestAutodescribePlusTraceableCauseDoubleTrouble` + "\n"
	// variable: // expect += "\t\t\t\t" + `·> /usr/local/go/src/testing/testing.go:447: testing.tRunner` + "\n"
	// variable: // expect += "\t\t\t\t" + `·> /usr/local/go/src/runtime/asm_amd64.s:2232: runtime.goexit` + "\n"
	expect += "\t\t" + `Stack trace:` + "\n"
	expect += "\t\t\t" + `·> /trait_autodescriber_test.go:122: meep.TestAutodescribePlusTraceableCauseDoubleTrouble` + "\n"
	// variable: // expect += "\t\t\t" + `·> /usr/local/go/src/testing/testing.go:447: testing.tRunner` + "\n"
	// variable: // expect += "\t\t\t" + `·> /usr/local/go/src/runtime/asm_amd64.s:2232: runtime.goexit` + "\n"

	// Cleanup is fun...
	actual := err.Error()
	actual = stripCwd(actual)
	actual = dropLinesContaining(actual, ": testing.")
	actual = dropLinesContaining(actual, ": runtime.")

	if expect != actual {
		t.Errorf("mismatch:\n  expected %q\n       got %q", expect, actual)
	}

	// now again for printing (without the parts dropped for the assertion)
	actual = err.Error()
	actual = strings.Replace(actual, "\t", "\\t\t", -1)
	actual = strings.Replace(actual, "\n", "\\n\n", -1)
	t.Logf("this is what errors with causes that have stacktraces look like :D\n>>>\n%s\n<<<\n", actual)
}

func TestAutodescribeManyFields(t *testing.T) {
	type ErrBananaPancakes struct {
		TraitAutodescribing
		Alpha string
		Beta  int
		Gamma interface{}
		Delta string
	}
	err := New(&ErrBananaPancakes{
		Alpha: "unO",
		Beta:  1,
		Gamma: struct{}{},
		Delta: "ca\ttorce",
	})
	expect := `Error[meep.ErrBananaPancakes]: Alpha="unO";Beta=1;Gamma=struct {}{};Delta="ca\ttorce";`
	actual := err.Error()
	if expect != actual {
		t.Errorf("mismatch:\n  expected %q\n       got %q", expect, actual)
	}
}

func TestIndirectEmbed(t *testing.T) {
	type ErrBananaPancakes struct {
		AllTraits
		Alpha string
		Beta  int
	}
	err := New(&ErrBananaPancakes{
		Alpha: "fwee",
		Beta:  14,
	}, Cause(fmt.Errorf("a cause")))

	expect := `Error[meep.ErrBananaPancakes]: Alpha="fwee";Beta=14;` + "\n"
	expect += "\t" + `Stack trace:` + "\n"
	expect += "\t\t" + `·> /trait_autodescriber_test.go:184: meep.TestIndirectEmbed` + "\n"
	expect += "\t" + `Caused by: a cause` + "\n"

	// Cleanup is fun...
	actual := err.Error()
	actual = stripCwd(actual)
	actual = dropLinesContaining(actual, ": testing.")
	actual = dropLinesContaining(actual, ": runtime.")
	// Ok, this *really* gets to me.
	// Apparently a multi-line "New" func call:
	//  - in go1.4 and before, it's always seen from the last line.
	//  - in go1.5 and 1.6, is seen from the first line.
	//  - ... except when the race detector is on, in which case it's last line.
	//  - in go1.7 and beyond, it's always seen from the last line again.
	// Wild, right?  Whee.
	// See https://travis-ci.org/polydawn/meep/builds/155778432 .
	// So we'll just take that "first line" line number and uh.  Touch it a little.
	actual = strings.Replace(actual, ":181:", ":184:", 1)

	if expect != actual {
		t.Errorf("mismatch:\n  expected %q\n       got %q", expect, actual)
	}

	// now again for printing (without the parts dropped for the assertion)
	actual = err.Error()
	actual = strings.Replace(actual, "\t", "\\t\t", -1)
	actual = strings.Replace(actual, "\n", "\\n\n", -1)
	t.Logf("embedding meep.Meep shorthand looks about the same\n>>>\n%s\n<<<\n", actual)
}


text:
'use strict';

class ResolutionResponse {
  constructor() {
    this.dependencies = [];
    this.asyncDependencies = [];
    this.mainModuleId = null;
    this._mappings = Object.create(null);
    this._finalized = false;
  }

  _assertNotFinalized() {
    if (this._finalized) {
      throw new Error('Attempted to mutate finalized response.');
    }
  }

  _assertFinalized() {
    if (!this._finalized) {
      throw new Error('Attempted to access unfinalized response.');
    }
  }

  finalize() {
    return this._mainModule.getName().then(id => {
      this.mainModuleId = id;
      this._finalized = true;
      return this;
    });
  }

  pushDependency(module) {
    this._assertNotFinalized();
    if (this.dependencies.length === 0) {
      this._mainModule = module;
    }

    this.dependencies.push(module);
  }

  prependDependency(module) {
    this._assertNotFinalized();
    this.dependencies.unshift(module);
  }

  pushAsyncDependency(dependency) {
    this._assertNotFinalized();
    this.asyncDependencies.push(dependency);
  }

  setResolvedDependencyPairs(module, pairs) {
    this._assertNotFinalized();
    const hash = module.hash();
    if (this._mappings[hash] == null) {
      this._mappings[hash] = pairs;
    }
  }

  getResolvedDependencyPairs(module) {
    this._assertFinalized();
    return this._mappings[module.hash()];
  }
}

module.exports = ResolutionResponse;


text:
"use strict";

var React = require("react");

function isValidChild(object) {
  return object == null || React.isValidElement(object);
}

function isReactChildren(object) {
  return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}

module.exports = isReactChildren;


text:
package com.vivastream.security.oauth2.provider;

public class UserDetailsAlreadyExistsException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public UserDetailsAlreadyExistsException(String message) {
        super(message);
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.gamesManagement.model;

/**
 * Model definition for ScoresResetMultipleForAllRequest.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Play Game Management. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ScoresResetMultipleForAllRequest extends com.google.api.client.json.GenericJson {

  /**
   * Uniquely identifies the type of this resource. Value is always the fixed string
   * `gamesManagement#scoresResetMultipleForAllRequest`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * The IDs of leaderboards to reset.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("leaderboard_ids")
  private java.util.List<java.lang.String> leaderboardIds;

  /**
   * Uniquely identifies the type of this resource. Value is always the fixed string
   * `gamesManagement#scoresResetMultipleForAllRequest`.
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * Uniquely identifies the type of this resource. Value is always the fixed string
   * `gamesManagement#scoresResetMultipleForAllRequest`.
   * @param kind kind or {@code null} for none
   */
  public ScoresResetMultipleForAllRequest setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * The IDs of leaderboards to reset.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getLeaderboardIds() {
    return leaderboardIds;
  }

  /**
   * The IDs of leaderboards to reset.
   * @param leaderboardIds leaderboardIds or {@code null} for none
   */
  public ScoresResetMultipleForAllRequest setLeaderboardIds(java.util.List<java.lang.String> leaderboardIds) {
    this.leaderboardIds = leaderboardIds;
    return this;
  }

  @Override
  public ScoresResetMultipleForAllRequest set(String fieldName, Object value) {
    return (ScoresResetMultipleForAllRequest) super.set(fieldName, value);
  }

  @Override
  public ScoresResetMultipleForAllRequest clone() {
    return (ScoresResetMultipleForAllRequest) super.clone();
  }

}


text:
using SF.Common.Notifications;
using SF.Sys;
using SF.Sys.Auth;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using SF.Sys.Threading;
using SF.Common.Notifications.Senders;
using System.Collections.Generic;
using SF.Sys.Linq;
using SF.Externals.WeiXin.Mp;
using System.ComponentModel.DataAnnotations;

namespace SF.Externals.WeiXin.Devices
{
	public class WeiXinDeviceServiceSetting
	{
		/// <summary>
		/// 微信设备接口基地址
		/// </summary>
		[Required]
		public string ApiUriBase { get; set; } = "https://api.weixin.qq.com/device/";
	}
	/// <summary>
	/// 微信设备服务
	/// </summary>
	public class WeiXinDeviceService : IWeiXinDeviceService
	{
        public IAccessTokenManager AccessTokenManager { get; }
		public IUserProfileService UserProfileService { get; }
		public WeiXinDeviceServiceSetting Setting { get; }
		async Task<string> GetUserOpenId (long UserId)
		{
			var re = await UserProfileService.GetClaims(UserId, new[] { PredefinedClaimTypes.WeiXinMPId }, null);
			var id = re.FirstOrDefault();
			if (id == null)
				throw new PublicInvalidOperationException("用户未绑定微信服务号");
			return id.Value;
		}
		public WeiXinDeviceService(
			IAccessTokenManager AccessTokenManager,
			IUserProfileService UserProfileService,
			WeiXinDeviceServiceSetting Setting
			)
		{
			this.AccessTokenManager = AccessTokenManager;
			this.UserProfileService = UserProfileService;
			this.Setting = Setting;
		}

		interface IRespStatus
		{
			int errcode { get; }
			string errmsg { get; }
		}

		class getqrcode_resp_status : IRespStatus
		{
			public int ret_code { get; set; }
			public string error_info { get; set; }

			int IRespStatus.errcode => ret_code;

			string IRespStatus.errmsg => error_info;
		}
		class getqrcode_resp
		{
			public getqrcode_resp_status resp_msg { get; set; }
			public string deviceid { get; set; }
			public string qrticket { get; set; }
		}
		void ValidateResponse(IRespStatus status,string op)
		{
			if ((status?.errcode??0) != 0)
				throw new WeiXinException(status.errcode, $"{op}操作失败:{status.errcode}:{status.errmsg}");
		}

		public async Task<GetQrCodeResult> GetQrCode(string ProductId)
		{
			var re = await AccessTokenManager.RequestString(
				new Uri(Setting.ApiUriBase + "getqrcode")
				.WithQueryString(("product_id", ProductId)),
				null
				);
			var resp = Json.Parse<getqrcode_resp>(re);
			ValidateResponse(resp.resp_msg, "设备授权");
			if (resp.deviceid.IsNullOrEmpty())
				throw new WeiXinException(-1, "请求成功,但没有返回设备ID");
			var id = resp.deviceid.LastSplit2('_').Item2;
			return new GetQrCodeResult
			{
				DeviceId = id,
				QrCode = resp.qrticket
			};
		}

		class resp_status : IRespStatus
		{
			public int errcode { get; set; }
			public string errmsg { get; set; }
		}
		class auth_resp : resp_status
		{
			public resp_status[] resp { get; set; }
		}
		public async Task AuthorizeDevice(AuthorizeDeviceArgument Arg)
		{
			var devs = new[]{
				new
				{
					id = Arg.DeviceId,
					mac = Arg.Mac,
					connect_protocol = Arg.ConnectProtocols.Select(p => (int)p).Join("|"),
					auth_key = Arg.AuthKey,
					close_strategy = ((int)Arg.CloseStrategy).ToString(),
					conn_strategy = ((Arg.AutoReconnectOnPage ? 1 : 0) | (Arg.AutoRecordOnActive ? 4 : 0)).ToString(),
					crypt_method = ((int)Arg.CryptMethod).ToString(),
					auth_ver = Arg.AuthVersion,
					manu_mac_pos = Arg.ManuMacPos.ToString(),
					ser_mac_pos = Arg.SerMacPos.ToString(),
					ble_simple_protocol = Arg.BleSimpleProtocol
				}
			};
			var re = await AccessTokenManager.Json(
				new Uri(Setting.ApiUriBase + "authorize_device"),
				new
				{
					device_num = 1,
					device_list =devs,
					op_type = "0",
					product_id=Arg.ProductId
				}
				);

			var result = Json.Parse<auth_resp>(re);
			if(result.errcode== 100002)
			{
				re = await AccessTokenManager.Json(
				   new Uri(Setting.ApiUriBase + "authorize_device"),
				   new
				   {
					   device_num = 1,
					   device_list = devs,
					   op_type = "1",
					   product_id = Arg.ProductId
				   }
				   );
				result = Json.Parse<auth_resp>(re);
			}
			ValidateResponse(result, "设备授权");

			if (result.resp == null || result.resp.Length != 1)
				throw new WeiXinException(-1, $"设备授权失败:没有返回数据");
			ValidateResponse(result.resp[0], "设备授权");
		}
		class bind_resp
		{
			public resp_status base_resp { get; set; }
		}
		public async Task BindDevice(string DeviceId, long UserId, string Ticket)
		{
			var openId = await GetUserOpenId(UserId);

			var re = await AccessTokenManager.Json(
				new Uri(Setting.ApiUriBase +(Ticket==null? "compel_bind" : "bind")),
				new
				{
					ticket=Ticket,
					device_id=DeviceId,
					openid=openId
				}
				);
			var result = Json.Parse<bind_resp>(re);
			ValidateResponse(result.base_resp,"绑定设备");
		}

		public async Task UnbindDevice(string DeviceId, long UserId, string Ticket)
		{
			var openId = await GetUserOpenId(UserId);

			var re = await AccessTokenManager.Json(
				new Uri(Setting.ApiUriBase + (Ticket == null ? "compel_unbind" : "unbind")),
				new
				{
					ticket = Ticket,
					device_id = DeviceId,
					openid = openId
				}
				);
			var result = Json.Parse<bind_resp>(re);
			ValidateResponse(result.base_resp, "解绑设备");
		}
		class dev_status_resp : resp_status
		{
			public int status { get; set; }
			public string status_info { get; set; }
		}
		public async Task<DeviceStatus> GetDeviceStatus(string DeviceId)
		{
			var re = await AccessTokenManager.RequestString(
				new Uri(Setting.ApiUriBase + "get_stat")
				.WithQueryString(("device_id", DeviceId)),
				null
				);
			var resp = Json.Parse<dev_status_resp>(re);
			ValidateResponse(resp, "获取设备状态");
			switch (resp.status)
			{
				case 0:
					return DeviceStatus.Unauth;
				case 1:
					return DeviceStatus.Auth;
				case 2:
				case 3:
					return DeviceStatus.Binded;
				default:
					throw new WeiXinException(-1, $"不支持的设备状态:{resp.status}:{resp.status_info}");
			}
		}

	}
}


text:
import weakref

from uxie.utils import idle, join_to_file_dir, make_missing_dirs, join_to_settings_dir
from uxie.misc import BuilderAware

from snaked.util import set_activate_the_one_item

def on_snippet_saved(editor, ctx):
    from . import existing_snippet_contexts, load_snippets_for

    existing_snippet_contexts[ctx] = editor.uri
    load_snippets_for(ctx)

    editor.message('Snippets were updated')

class PreferencesDialog(BuilderAware):
    """glade-file: prefs.glade"""

    def __init__(self, existing_snippets):
        BuilderAware.__init__(self, join_to_file_dir(__file__, 'prefs.glade'))

        from snaked.core.manager import keymap
        self.activator = keymap.get_activator(self.window)
        self.activator.bind('Escape', self.hide)
        self.activator.bind('<alt>s', self.focus_search)
        self.existing_snippets = existing_snippets

        set_activate_the_one_item(self.search_entry, self.snippets_view)

    def hide(self):
        self.window.destroy()

    def show(self, editor):
        self.editor = weakref.ref(editor)
        self.fill_snippets(None)
        editor.request_transient_for.emit(self.window)
        self.window.show()

    def fill_snippets(self, search):
        self.snippets.clear()
        for name in sorted(self.existing_snippets):
            if not search or search in name:
                self.snippets.append((name,))

    def on_delete_event(self, *args):
        return False

    def on_search_entry_changed(self, *args):
        search = self.search_entry.get_text().strip().lower()
        idle(self.fill_snippets, search)

    def activate(self, *args):
        (model, iter) = self.snippets_view.get_selection().get_selected()
        if iter:
            name = model.get_value(iter, 0)
            self.edit_context(name)
        else:
            self.editor().message('You need select item')

    def focus_search(self):
        self.search_entry.grab_focus()

    def edit_context(self, ctx):
        user_snippet_filename = join_to_settings_dir('snaked', 'snippets', ctx + '.snippets')
        if ctx in self.existing_snippets and \
                self.existing_snippets[ctx] != user_snippet_filename:

            import shutil
            make_missing_dirs(user_snippet_filename)
            shutil.copy(self.existing_snippets[ctx], user_snippet_filename)

        idle(self.hide)
        e = self.editor().open_file(user_snippet_filename)
        e.connect('file-saved', on_snippet_saved, ctx)

    def on_create_snippet_activate(self, button):
        ctx = self.search_entry.get_text()
        if ctx:
            self.edit_context(ctx)
        else:
            self.editor().message('Enter snippet name in search entry', 3000)


text:
package com.example.listmaker.app.client.domain;

import java.util.List;

/**
 * Created by david on 7/5/14.
 */
public class ListWrapper<T> {

    private List<T> list;

    public ListWrapper(List<T> list) {
        this.list = list;
    }
    public List<T> getList() {
        return list;
    }

}


text:
#include "detail.hpp"

#include <SDL_ttf.h>

#include <algorithm>
#include <cctype>

namespace {
    enum { uc_user, uc_timeout, uc_interval };

    inline SDL_Event make_user_event(int code, void* p1 = 0, void* p2 = 0) {
        SDL_Event event;
        event.type = SDL_USEREVENT;
        event.user.type = SDL_USEREVENT;
        event.user.code = code;
        event.user.data1 = p1;
        event.user.data2 = p2;
        return event;
    }

    extern "C" Uint32 jacui_timeout_callback(Uint32 /*interval*/, void* param)
    {
        SDL_Event event = make_user_event(uc_timeout, param);
        SDL_PushEvent(&event); // no throw from extern "C"
        return 0;
    }

    extern "C" Uint32 jacui_interval_callback(Uint32 interval, void* param)
    {
        SDL_Event event = make_user_event(uc_interval, param);
        SDL_PushEvent(&event); // no throw from extern "C"
        return interval;
    }

    jacui::size2d get_screen_size()
    {
        SDL_Surface* s = SDL_GetVideoSurface();
        if (!s)
            jacui::detail::throw_error("error getting screen size");
        return jacui::size2d(s->w, s->h);
    }

    void set_screen_size(jacui::size2d size)
    {
        SDL_Surface* s = SDL_GetVideoSurface();
        if (!s)
            jacui::detail::throw_error("error resizing screen");
        if (!SDL_SetVideoMode(size.width, size.height, s->format->BitsPerPixel, s->flags))
            jacui::detail::throw_error("error resizing screen");

        SDL_Event event;
        event.type = SDL_VIDEOEXPOSE;
        event.expose.type = SDL_VIDEOEXPOSE;
        if (SDL_PushEvent(&event) < 0)
            jacui::detail::throw_error("error pushing event");
    }
}

namespace jacui {
    namespace detail {
        event_queue::event_queue() : ntimer(0)
        {
            std::fill(&timers[0], &timers[max_timers], SDL_TimerID(0));
            event_.type = SDL_NOEVENT;
        }

        event* event_queue::wait()
        {
            if (type() == event::quit)
                return 0;
            if (type() == event::resize)
                set_screen_size(size());
            if (type() == event::timer && is_timeout())
                clear_timer(timer());
            if (!SDL_WaitEvent(&event_))
                return 0;
            return is_user() ? user() : this;
        }

        event* event_queue::poll()
        {
            if (type() == event::quit)
                return 0;
            if (type() == event::resize)
                set_screen_size(size());
            if (type() == event::timer && is_timeout())
                clear_timer(timer());
            if (!SDL_PollEvent(&event_))
                return 0;
            return is_user() ? user() : this;
        }

        void event_queue::push(event* pe)
        {
            SDL_Event event = make_user_event(uc_user, pe);
            if (SDL_PushEvent(&event) < 0)
                throw_error("error pushing event");
        }

        timer_event::timer_type event_queue::set_timeout(unsigned long ms)
        {
            timer_type timer = make_timer();
            if (!(timers[timer] = SDL_AddTimer(ms, jacui_timeout_callback, &timers[timer])))
                throw_error("error setting timeout");
            return timer;
        }

        timer_event::timer_type event_queue::set_interval(unsigned long ms)
        {
            timer_type timer = make_timer();
            if (!(timers[timer] = SDL_AddTimer(ms, jacui_interval_callback, &timers[timer])))
                throw_error("error setting interval");
            return timer;
        }

        bool event_queue::clear_timer(timer_event::timer_type timer)
        {
            if (timer >= max_timers || !timers[timer])
                return false;
            SDL_RemoveTimer(timers[timer]);
            timers[timer] = 0;
            return true;
        }

        void event_queue::quit()
        {
            event_.type = SDL_QUIT;
        }

        event::event_type event_queue::type() const
        {
            switch (event_.type) {
            case SDL_ACTIVEEVENT:
                return event::noevent; // TODO: handle active
            case SDL_VIDEORESIZE:
                return event::resize;
            case SDL_VIDEOEXPOSE:
                return event::redraw;
            case SDL_MOUSEMOTION:
                return event::mousemove;
            case SDL_MOUSEBUTTONDOWN:
                return event::mousedown;
            case SDL_MOUSEBUTTONUP:
                return event::mouseup;
            case SDL_KEYDOWN:
                return event::keydown;
            case SDL_KEYUP:
                return event::keyup;
            case SDL_QUIT:
                return event::quit;
            case SDL_USEREVENT:
                switch (event_.user.code) {
                case uc_user:
                    return event::user;
                case uc_timeout:
                case uc_interval:
                    return event::timer;
                default:
                    return event::noevent;
                }
            default:
                return event::noevent;
            }
        }

        const char* event_queue::name() const
        {
            switch (event_.type) {
            case SDL_ACTIVEEVENT:
                return "active"; // TODO: handle active
            case SDL_VIDEORESIZE:
                return "resize";
            case SDL_VIDEOEXPOSE:
                return "redraw";
            case SDL_MOUSEMOTION:
                return "mousemove";
            case SDL_MOUSEBUTTONDOWN:
                return "mousedown";
            case SDL_MOUSEBUTTONUP:
                return "mouseup";
            case SDL_KEYDOWN:
                return "keydown";
            case SDL_KEYUP:
                return "keyup";
            case SDL_QUIT:
                return "quit";
            case SDL_USEREVENT:
                switch (event_.user.code) {
                case uc_user:
                    return "user";
                case uc_timeout:
                case uc_interval:
                    return "timer";
                default:
                    return "noevent";
                }
            default:
                return "noevent";
            }
        }

        void event_queue::cancel()
        {
            if (is_timeout() || is_interval())
                clear_timer(timer());
            event_.type = SDL_NOEVENT;
        }

        size2d event_queue::size() const
        {
            switch (event_.type) {
            case SDL_VIDEORESIZE:
                return size2d(event_.resize.w, event_.resize.h);
            default:
                return size2d();
            }
        }

        rect2d event_queue::rect() const
        {
            switch (event_.type) {
            case SDL_VIDEOEXPOSE:
                return get_screen_size();
            default:
                return rect2d();
            }
        }

        input_event::modmask_type event_queue::modifiers() const
        {
            switch (event_.type) {
            case SDL_KEYDOWN:
            case SDL_KEYUP:
                return event_.key.keysym.mod;
            default:
                return SDL_GetModState();
            }
        }

        mouse_event::button_type event_queue::button() const
        {
            switch (event_.type) {
            case SDL_MOUSEBUTTONUP:
            case SDL_MOUSEBUTTONDOWN:
                return event_.button.button;
            case SDL_MOUSEMOTION:
                if (event_.motion.state & SDL_BUTTON(1))
                    return lbutton;
                if (event_.motion.state & SDL_BUTTON(2))
                    return mbutton;
                if (event_.motion.state & SDL_BUTTON(3))
                    return rbutton;
                return 0;
            default:
                return 0;
            }
        }

        point2d event_queue::point() const
        {
            switch (event_.type) {
            case SDL_MOUSEMOTION:
                return point2d(event_.motion.x, event_.motion.y);
            case SDL_MOUSEBUTTONUP:
            case SDL_MOUSEBUTTONDOWN:
                return point2d(event_.button.x, event_.button.y);
            default:
                return point2d();
            }
        }

        keyboard_event::key_type event_queue::key() const
        {
            switch (event_.type) {
            case SDL_KEYDOWN:
            case SDL_KEYUP:
                // report uppercase characters for aesthetic reasons
                if (std::islower(event_.key.keysym.sym))
                    return std::toupper(event_.key.keysym.sym);
                else
                    return event_.key.keysym.sym;
            default:
                return 0;
            }
        }

        wchar_t event_queue::wchar() const
        {
            // assume wchar_t is (widened) UTF-16
            switch (event_.type) {
            case SDL_KEYDOWN:
                return event_.key.keysym.unicode;
            case SDL_KEYUP:
                return event_.key.keysym.unicode;
            default:
                return 0;
            }
        }

        timer_event::timer_type event_queue::timer() const
        {
            if (is_timeout() || is_interval())
                return static_cast<SDL_TimerID*>(event_.user.data1) - timers;
            else
                return 0;
        }

        event* event_queue::user() const
        {
            return is_user() ? static_cast<event*>(event_.user.data1) : 0;
        }

        bool event_queue::is_user() const
        {
            return event_.type == SDL_USEREVENT && event_.user.code == uc_user;
        }

        bool event_queue::is_timeout() const
        {
            return event_.type == SDL_USEREVENT && event_.user.code == uc_timeout;
        }

        bool event_queue::is_interval() const
        {
            return event_.type == SDL_USEREVENT && event_.user.code == uc_interval;
        }

        timer_event::timer_type event_queue::make_timer()
        {
            // round robin to avoid reusing "active" timers
            for (timer_type i = 1; i != max_timers; ++i) {
                timer_type n = (ntimer + i) % max_timers;
                if (n != 0 && !timers[n]) {
                    ntimer = n;
                    return n;
                }
            }

            throw error("maximum number of timers exceeded");
        }

        init::init()
        {
            if (count++ == 0) {
                if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_NOPARACHUTE) < 0)
                    throw_error("unable to initialize sdl");
                if (TTF_Init() < 0)
                    throw_error("unable to initialize ttf library");
                SDL_EnableUNICODE(true);
            }
        }

        init::~init()
        {
            if (--count == 0) {
                TTF_Quit();
                SDL_Quit();
            }
        }

        int init::count = 0;
    }
}


text:
package com.github.nmorel.gwtjackson.shared.advanced.jsontype;

import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.github.nmorel.gwtjackson.shared.AbstractTester;
import com.github.nmorel.gwtjackson.shared.ObjectReaderTester;
import com.github.nmorel.gwtjackson.shared.ObjectWriterTester;

/**
 * @author Nicolas Morel
 */
public final class PolymorphismIdNameAsWrapperObjectTester extends AbstractTester {

    @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT )
    @JsonPropertyOrder( alphabetic = true )
    @JsonSubTypes( {@JsonSubTypes.Type( value = Employee.class, name = "Employee" )} )
    public static abstract class Person {

        public String name;
    }

    public static class Employee extends Person {

        public int id;

        public String title;
    }

    @JsonTypeName( "Manager" )
    public static class Manager extends Employee {

        public List<Employee> managedEmployees;
    }

    public static class Customer extends Person {

        public int satisfaction;
    }

    public static final PolymorphismIdNameAsWrapperObjectTester INSTANCE = new PolymorphismIdNameAsWrapperObjectTester();

    private PolymorphismIdNameAsWrapperObjectTester() {
    }

    public void testSerialize( ObjectWriterTester<Person[]> writer ) {
        Person[] persons = new Person[4];

        Employee employee2 = new Employee();
        employee2.name = "Thomas";
        employee2.id = 2;
        employee2.title = "Waiter";
        persons[0] = employee2;

        Employee employee3 = new Employee();
        employee3.name = "Patricia";
        employee3.id = 3;
        employee3.title = "Cook";
        persons[1] = employee3;

        Manager manager = new Manager();
        manager.name = "Bob";
        manager.id = 1;
        manager.title = "Boss";
        manager.managedEmployees = Arrays.asList( employee2, employee3 );
        persons[2] = manager;

        Customer customer = new Customer();
        customer.name = "Brad";
        customer.satisfaction = 90;
        persons[3] = customer;

        String result = writer.write( persons );

        String expected = "[" +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":2," +
                "\"name\":\"Thomas\"," +
                "\"title\":\"Waiter\"" +
                "}" +
                "}," +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":3," +
                "\"name\":\"Patricia\"," +
                "\"title\":\"Cook\"" +
                "}" +
                "}," +
                "{" +
                "\"Manager\":" +
                "{" +
                "\"id\":1," +
                "\"managedEmployees\":" +
                "[" +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":2," +
                "\"name\":\"Thomas\"," +
                "\"title\":\"Waiter\"" +
                "}" +
                "}," +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":3," +
                "\"name\":\"Patricia\"," +
                "\"title\":\"Cook\"" +
                "}" +
                "}" +
                "]," +
                "\"name\":\"Bob\"," +
                "\"title\":\"Boss\"" +
                "}" +
                "}," +
                "{" +
                "\"PolymorphismIdNameAsWrapperObjectTester$Customer\":" +
                "{" +
                "\"name\":\"Brad\"," +
                "\"satisfaction\":90" +
                "}" +
                "}" +
                "]";

        assertEquals( expected, result );
    }

    public void testDeserialize( ObjectReaderTester<Person[]> reader ) {
        String input = "[" +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":2," +
                "\"name\":\"Thomas\"," +
                "\"title\":\"Waiter\"" +
                "}" +
                "}," +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":3," +
                "\"name\":\"Patricia\"," +
                "\"title\":\"Cook\"" +
                "}" +
                "}," +
                "{" +
                "\"Manager\":" +
                "{" +
                "\"id\":1," +
                "\"managedEmployees\":" +
                "[" +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":2," +
                "\"name\":\"Thomas\"," +
                "\"title\":\"Waiter\"" +
                "}" +
                "}," +
                "{" +
                "\"Employee\":" +
                "{" +
                "\"id\":3," +
                "\"name\":\"Patricia\"," +
                "\"title\":\"Cook\"" +
                "}" +
                "}" +
                "]," +
                "\"name\":\"Bob\"," +
                "\"title\":\"Boss\"" +
                "}" +
                "}," +
                "{" +
                "\"PolymorphismIdNameAsWrapperObjectTester$Customer\":" +
                "{" +
                "\"name\":\"Brad\"," +
                "\"satisfaction\":90" +
                "}" +
                "}" +
                "]";

        Person[] result = reader.read( input );
        {
            // Employee
            Employee employee = (Employee) result[0];
            assertEquals( 2, employee.id );
            assertEquals( "Waiter", employee.title );
            assertEquals( "Thomas", employee.name );
        }
        {
            // Employee
            Employee employee = (Employee) result[1];
            assertEquals( 3, employee.id );
            assertEquals( "Cook", employee.title );
            assertEquals( "Patricia", employee.name );
        }
        {
            // Manager
            Manager manager = (Manager) result[2];
            assertEquals( 1, manager.id );
            assertEquals( "Boss", manager.title );
            assertEquals( "Bob", manager.name );
            assertEquals( 2, manager.managedEmployees.size() );

            Employee employee1 = manager.managedEmployees.get( 0 );
            assertEquals( 2, employee1.id );
            assertEquals( "Waiter", employee1.title );
            assertEquals( "Thomas", employee1.name );

            Employee employee2 = manager.managedEmployees.get( 1 );
            assertEquals( 3, employee2.id );
            assertEquals( "Cook", employee2.title );
            assertEquals( "Patricia", employee2.name );
        }
        {
            // Customer
            Customer customer = (Customer) result[3];
            assertEquals( "Brad", customer.name );
            assertEquals( 90, customer.satisfaction );
        }
    }

}


text:
This is an experiment to
 1. learn Haskell
 2. place all nodes in a Graph nicely onto a 2-dimensional grid

Of course I first tried a "force field simulation" but was not happy with the resulting layout.
Force fields are great, interactively, to show and explore a graph. But I am looking for a more
rigid and stable layout that just shows my graph in an orderly fashion.

And I am not shying away from "brute force". The Haskell implementation that I am now working on
works from the following principle:

1. read the edges
2. find the "starting nodes" (the ones that have no predecessor)
3. place the starting nodes on the grid
4. for each edge of the non-starter kind
    1. find the possible placings, close to the node that precedes it in the graph
    2. if we can place it at the first placing, go for it and try to place the remainder
    3. if the remainder fails, try the next possible placing
    4. if all possible placings fail, fail to place this node
5. if we placed all nodes, print out the placements, else "No Placements"

This should basically try out all possible layouts untill it finds a suitable one.

Some functions that I am now working on:

 * the possible placings for a node are all points directly arround the preceding node
 * we start exploring new nodes to the East, North, West or South, depending on what quadrant we are in
 * we rotate these possible placings clockwize for x >= 0 and anticlockwize for x < 0

 * the starting positions are points around (0,0), starting at a certain distance and increasing from there


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('skills', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='skills',
            name='skill',
            field=models.CharField(max_length=30),
        ),
    ]


text:
.class Lcom/android/internal/app/PlatLogoActivity$5;
.super Ljava/lang/Object;
.source "PlatLogoActivity.java"

# interfaces
.implements Landroid/view/View$OnKeyListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/app/PlatLogoActivity;->onAttachedToWindow()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/app/PlatLogoActivity;

.field final synthetic val$im:Landroid/view/View;

# direct methods
.method constructor <init>(Lcom/android/internal/app/PlatLogoActivity;Landroid/view/View;)V
    .locals 0
    .param p1, "this$0"    # Lcom/android/internal/app/PlatLogoActivity;
    .param p2, "val$im"    # Landroid/view/View;

    .prologue
    .line 173
    iput-object p1, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iput-object p2, p0, Lcom/android/internal/app/PlatLogoActivity$5;->val$im:Landroid/view/View;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onKey(Landroid/view/View;ILandroid/view/KeyEvent;)Z
    .locals 2
    .param p1, "v"    # Landroid/view/View;
    .param p2, "keyCode"    # I
    .param p3, "event"    # Landroid/view/KeyEvent;

    .prologue
    const/4 v1, 0x0

    .line 176
    const/4 v0, 0x4

    if-eq p2, v0, :cond_3

    invoke-virtual {p3}, Landroid/view/KeyEvent;->getAction()I

    move-result v0

    if-nez v0, :cond_3

    .line 177
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iget v0, v0, Lcom/android/internal/app/PlatLogoActivity;->mKeyCount:I

    if-nez v0, :cond_0

    .line 178
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iget-object v1, p0, Lcom/android/internal/app/PlatLogoActivity$5;->val$im:Landroid/view/View;

    invoke-virtual {v0, v1}, Lcom/android/internal/app/PlatLogoActivity;->showMarshmallow(Landroid/view/View;)V

    .line 180
    :cond_0
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iget v1, v0, Lcom/android/internal/app/PlatLogoActivity;->mKeyCount:I

    add-int/lit8 v1, v1, 0x1

    iput v1, v0, Lcom/android/internal/app/PlatLogoActivity;->mKeyCount:I

    .line 181
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iget v0, v0, Lcom/android/internal/app/PlatLogoActivity;->mKeyCount:I

    const/4 v1, 0x2

    if-le v0, v1, :cond_1

    .line 182
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->this$0:Lcom/android/internal/app/PlatLogoActivity;

    iget v0, v0, Lcom/android/internal/app/PlatLogoActivity;->mTapCount:I

    const/4 v1, 0x5

    if-le v0, v1, :cond_2

    .line 183
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->val$im:Landroid/view/View;

    invoke-virtual {v0}, Landroid/view/View;->performLongClick()Z

    .line 188
    :cond_1
    :goto_0
    const/4 v0, 0x1

    return v0

    .line 185
    :cond_2
    iget-object v0, p0, Lcom/android/internal/app/PlatLogoActivity$5;->val$im:Landroid/view/View;

    invoke-virtual {v0}, Landroid/view/View;->performClick()Z

    goto :goto_0

    .line 190
    :cond_3
    return v1
.end method


text:
from datetime import datetime
import re
from analysis import Analysis
from src.shell.parser.couple import CoupleLogParser

class CoupleAnalysis(Analysis):

    def __init__(self, pgm, logfile, data=None):
        Analysis.__init__(self, pgm, logfile)

        self.data = data
        if data is None:
            self.protos = None

    def parse_log(self):
        self.log = CoupleLogParser(self.logfile)
        return

#        self.log = list()
#        with open(self.logfile, "r") as f:
#            for line in f.readlines():
#                a, b, c, d, e = line[:-1].split(" ")
#                self.log.append((a, c, e))
#

    def display(self):
        for f, g, c in self.log.get():
            print("({0}, {1}) -- {2}".format(f, g, c))
        print()
        self.print_general_info()


text:
const generateMarkdown = require('../../bin/generateMarkdown/generateMarkdown');

const invalidInput = {};

describe('generateMarkdown with invalid input', () => {
  it('should throw an error', () => {
    expect(() => {
      generateMarkdown('ComponentName', invalidInput);
    }).toThrow();
  });
});

describe('generateMarkdown with valid input', () => {
  it('should generate a markdown table', () => {
    const validInput = {
      description: '',
      methods: [],
      props:
      {
        children:
      {
        type: { name: 'string', value: 'asdf' },
        required: true,
        description: 'The component that will be wrapped by i18n provider.',
      },
        locale:
        {
          type: { name: 'string', value: 'asdf' },
          required: true,
          description: 'The locale name.',
        },
        messages:
        {
          type: { name: 'string', value: 'asdf' },
          required: true,
          description: 'Translations messages object.',
        },
      },
    };

    expect(generateMarkdown('ComponentName', validInput)).toMatchSnapshot();
  });
});


text:
<template name="MuiNotifications2">
  <div>
    {{> React component=notifications}}
  </div>
</template>


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appProdUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);

        if (0 === strpos($pathinfo, '/log')) {
            // logout
            if ($pathinfo === '/logout') {
                return array('_route' => 'logout');
            }

            if (0 === strpos($pathinfo, '/login')) {
                // login
                if ($pathinfo === '/login') {
                    return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\SecurityController::loginAction',  '_route' => 'login',);
                }

                // login_check
                if ($pathinfo === '/login_check') {
                    return array('_route' => 'login_check');
                }

            }

        }

        // giftlet_homepage
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'giftlet_homepage');
            }

            return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::indexAction',  '_route' => 'giftlet_homepage',);
        }

        if (0 === strpos($pathinfo, '/user')) {
            // giftlet_user
            if (rtrim($pathinfo, '/') === '/user') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'giftlet_user');
                }

                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::indexAction',  '_route' => 'giftlet_user',);
            }

            // giftlet_user_show
            if (preg_match('#^/user/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'giftlet_user_show')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::showAction',));
            }

            // giftlet_user_new
            if ($pathinfo === '/user/new') {
                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::newAction',  '_route' => 'giftlet_user_new',);
            }

            // giftlet_user_create
            if ($pathinfo === '/user/create') {
                if ($this->context->getMethod() != 'POST') {
                    $allow[] = 'POST';
                    goto not_giftlet_user_create;
                }

                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::createAction',  '_route' => 'giftlet_user_create',);
            }
            not_giftlet_user_create:

            // giftlet_user_edit
            if (preg_match('#^/user/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'giftlet_user_edit')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::editAction',));
            }

            // giftlet_user_update
            if (preg_match('#^/user/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
                    $allow = array_merge($allow, array('POST', 'PUT'));
                    goto not_giftlet_user_update;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'giftlet_user_update')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::updateAction',));
            }
            not_giftlet_user_update:

            // giftlet_user_delete
            if (preg_match('#^/user/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
                    $allow = array_merge($allow, array('POST', 'DELETE'));
                    goto not_giftlet_user_delete;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'giftlet_user_delete')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\UserController::deleteAction',));
            }
            not_giftlet_user_delete:

        }

        if (0 === strpos($pathinfo, '/gift')) {
            // gift
            if (rtrim($pathinfo, '/') === '/gift') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'gift');
                }

                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::indexAction',  '_route' => 'gift',);
            }

            // gift_show
            if (preg_match('#^/gift/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'gift_show')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::showAction',));
            }

            // gift_new
            if ($pathinfo === '/gift/new') {
                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::newAction',  '_route' => 'gift_new',);
            }

            // gift_create
            if ($pathinfo === '/gift/create') {
                if ($this->context->getMethod() != 'POST') {
                    $allow[] = 'POST';
                    goto not_gift_create;
                }

                return array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::createAction',  '_route' => 'gift_create',);
            }
            not_gift_create:

            // gift_edit
            if (preg_match('#^/gift/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'gift_edit')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::editAction',));
            }

            // gift_update
            if (preg_match('#^/gift/(?P<id>[^/]++)/update$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('POST', 'PUT'))) {
                    $allow = array_merge($allow, array('POST', 'PUT'));
                    goto not_gift_update;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'gift_update')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::updateAction',));
            }
            not_gift_update:

            // gift_delete
            if (preg_match('#^/gift/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('POST', 'DELETE'))) {
                    $allow = array_merge($allow, array('POST', 'DELETE'));
                    goto not_gift_delete;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'gift_delete')), array (  '_controller' => 'giftlet\\giftletBundle\\Controller\\GiftController::deleteAction',));
            }
            not_gift_delete:

        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}