text:
	#define LocalLog( s, ... ) NSLog( @"<%@:%d> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__,  [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
	#define LocalLog( s, ... )
#endif

#if !Cocos2UpdateLogging
    #undef LocalLog
    #define LocalLog( s, ... )
#endif

typedef enum
{
    Cocos2dVersionUpToDate = 0,
    Cocos2dVersionIncompatible,
    Cocos2dVersionProjectVersionUnknown,
} Cocos2dVersionComparisonResult;

static NSString *const REL_DEFAULT_COCOS2D_FOLDER_PATH = @"Source/libs/cocos2d-iphone/";
static NSString *const COCOS2D_BACKUP_EXTENSION = @"backup";
static NSString *const URL_COCOS2D_UPDATE_INFORMATION = @"http://www.spritebuilder.com/update/";

@interface Cocos2dUpdater ()

@property (nonatomic, weak, readwrite) AppDelegate *appDelegate;
@property (nonatomic, weak, readwrite) ProjectSettings *projectSettings;

@property (nonatomic, strong) NSTask *task;
@property (nonatomic, strong) NSFileHandle *outFile;
@property (nonatomic, getter=isCancelled) BOOL cancelled;
@property (nonatomic, copy) NSString *projectsCocos2dVersion;
@property (nonatomic, copy) NSString *spritebuildersCocos2dVersion;
@property (nonatomic, copy) NSString *backupFolderPath;

@end

@implementation Cocos2dUpdater

- (instancetype)init
{
    NSLog(@"Use initWithAppDelegate:projectSettings: to create instances");
    [self doesNotRecognizeSelector:_cmd];
    return nil;
}

- (instancetype)initWithAppDelegate:(AppDelegate *)appDelegate projectSettings:(ProjectSettings *)projectSettings
{
    NSAssert(projectSettings != nil, @"Project settings needed to instantiate the updater.");

    self = [super init];
    if (self)
    {
        self.appDelegate = appDelegate;
        self.projectSettings = projectSettings;

        self.spritebuildersCocos2dVersion = [self readSpriteBuildersCocos2dVersionFile];
        self.projectsCocos2dVersion = [self readProjectsCocos2dVersionFile];
    }
    return self;
}

- (void)updateAndBypassIgnore:(BOOL)bypassIgnore
{
    NSAssert(_projectSettings != nil, @"Project settings needed to instantiate the updater.");

    [self updateProjectSettingsIfUserCanUpdate];

    if ([self shouldIgnoreThisVersion] && !bypassIgnore)
    {
        LocalLog(@"[COCO2D-UPDATER] [INFO] Ignoring this version %@.", self.spritebuildersCocos2dVersion);
        return;
    }

    if ([self isCoco2dAGitSubmodule])
    {
        LocalLog(@"[COCO2D-UPDATER] [INFO] cocos2d-iphone git submodule found, skipping.");
        return;
    }

    [self setBackupFolderPath];
    UpdateActions updateAction = [self updateAction];

    if (updateAction == UpdateActionNothingToDo)
    {
        return;
    }

    if (updateAction == UpdateActionIgnoreVersion)
    {
        LocalLog(@"[COCO2D-UPDATER] [INFO] Now ignoring this version %@.", self.spritebuildersCocos2dVersion);
        [self setIgnoreThisVersion];
        return;
    }

    [self doUpdate];
}

- (void)updateProjectSettingsIfUserCanUpdate
{
    Cocos2dVersionComparisonResult compareResult = [self compareProjectsCocos2dVersionWithSpriteBuildersVersion];

   _projectSettings.canUpdateCocos2D = ![self isCoco2dAGitSubmodule]
               && ((compareResult == Cocos2dVersionIncompatible)
               || [self doesProjectsCocos2dFolderExistAndHasNoVersionfile]);;
}

- (BOOL)doesProjectsCocos2dFolderExistAndHasNoVersionfile
{
    Cocos2dVersionComparisonResult compareResult = [self compareProjectsCocos2dVersionWithSpriteBuildersVersion];

    return compareResult == Cocos2dVersionProjectVersionUnknown
                 && [self defaultProjectsCocos2dFolderExists];
}

- (UpdateActions)updateAction
{
    Cocos2dVersionComparisonResult compareResult = [self compareProjectsCocos2dVersionWithSpriteBuildersVersion];

    if (compareResult == Cocos2dVersionUpToDate)
    {
        return UpdateActionNothingToDo;
    }
    else if (compareResult == Cocos2dVersionIncompatible)
    {
        return  [_delegate updateAction:@"Your project is not using the latest version of Cocos2D. It's recommended that you update."
                 projectsCocos2dVersion:_projectsCocos2dVersion
           spriteBuildersCocos2dVersion:_spritebuildersCocos2dVersion
                             backupPath:_backupFolderPath];
    }
    else if ([self doesProjectsCocos2dFolderExistAndHasNoVersionfile])
    {
        return  [_delegate updateAction:@"Your project is probably not using the latest version of Cocos2D (the version file is missing, which indicates that you are using an old version). It's recommended that you update."
                 projectsCocos2dVersion:_projectsCocos2dVersion
           spriteBuildersCocos2dVersion:_spritebuildersCocos2dVersion
                             backupPath:_backupFolderPath];
    }
    else
    {
        return UpdateActionNothingToDo;
    }
}

- (void)doUpdate
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] updating...");

    __block NSError *error;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^
    {
        [self updateModalDialogStatusText:@"Unzipping sources"];

        BOOL updateResult = [self unzipProjectTemplateZip:&error]
            && [self renameCocos2dFolderToBackupFolder:&error]
            && [self copySpriteBuildersCocos2dFolderToProjectFolder:&error]
            && [self createSymbolicLinkToCocos2dProject:&error]
            && [self tidyUpTempFolder:&error];

		// cleaning only makes sense if update succeeded
		if (updateResult)
		{
			[CCBFileUtil cleanupSpriteBuilderProjectAtPath:_projectSettings.projectPath];
		}

        [self finishWithUpdateResult:updateResult error:error];
    });

    __weak id weakSelf = self;
    [_appDelegate modalStatusWindowStartWithTitle:@"Updating Cocos2D..." isIndeterminate:YES onCancelBlock:^
    {
        [weakSelf cancel];
    }];
}

- (void)setBackupFolderPath
{
    self.backupFolderPath = [[self defaultProjectsCocos2DFolderPath] availabeFileNameWithRollingNumberAndExtraExtension:COCOS2D_BACKUP_EXTENSION];
}

- (void)finishWithUpdateResult:(BOOL)status error:(NSError *)error
{
    [self runOnMainThread:^
    {
        [_appDelegate modalStatusWindowFinish];

        if (status)
        {
            LocalLog(@"[COCO2D-UPDATER] [INFO] Success!");
            _projectSettings.canUpdateCocos2D = NO;
            [_projectSettings.cocos2dUpdateIgnoredVersions removeObject:self.spritebuildersCocos2dVersion];
            [self openBrowserWithCocos2dUpdateInformation];

            [_delegate updateSucceeded];
        }
        else
        {
            LocalLog(@"[COCO2D-UPDATER] [INFO] Updating failed! Rolling back...");
            [self showUpdateErrorDialog:error];
            [self rollBack];
        }

    }];
}

- (void)runOnMainThread:(dispatch_block_t)block
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        #if !TESTING
		CFRunLoopPerformBlock(([[NSRunLoop mainRunLoop] getCFRunLoop]), (__bridge CFStringRef)NSModalPanelRunLoopMode, ^{
            block();
        });
        #else
        // For whatever reason the other run on main thread version does not complete the tests
        dispatch_async(dispatch_get_main_queue(), ^{
           block();
        });
        #endif
    }
}

- (void)openBrowserWithCocos2dUpdateInformation
{
    #if !TESTING
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    [workspace openURL:[NSURL URLWithString:URL_COCOS2D_UPDATE_INFORMATION]];
    #endif
}

- (void)showUpdateErrorDialog:(NSError *)error
{
    if (!self.isCancelled)
    {
        [_delegate updateFailedWithError:error];
    }
}

- (void)rollBack
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] Rolling back.");
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *defaultCocos2DFolderPath = [self defaultProjectsCocos2DFolderPath];

    // Without the backup folder we can't say what went wrong but
    // it is safe to not do anything
    if (![fileManager fileExistsAtPath:self.backupFolderPath])
    {
        return;
    }

    if ([fileManager fileExistsAtPath:defaultCocos2DFolderPath])
    {
        [fileManager removeItemAtPath:defaultCocos2DFolderPath error:nil];
    }

    [fileManager moveItemAtPath:self.backupFolderPath toPath:defaultCocos2DFolderPath error:nil];
}

- (void)updateModalDialogStatusText:(NSString *)text
{
    [self runOnMainThread:^
    {
        [_appDelegate modalStatusWindowUpdateStatusText:text];
    }];
}

- (void)setIgnoreThisVersion
{
	// SI: added check for _spritebuildersCocos2dVersion being nil - happens if you click "Ignore this version" (at least in dev builds)
    if (self.spritebuildersCocos2dVersion
        && ![_projectSettings.cocos2dUpdateIgnoredVersions containsObject:self.spritebuildersCocos2dVersion])
    {
        [_projectSettings.cocos2dUpdateIgnoredVersions addObject:self.spritebuildersCocos2dVersion];
    }
}

- (BOOL)shouldIgnoreThisVersion
{
    return [_projectSettings.cocos2dUpdateIgnoredVersions containsObject:self.spritebuildersCocos2dVersion];
}

- (BOOL)unzipProjectTemplateZip:(NSError **)error
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *zipFile = [[NSBundle mainBundle] pathForResource:@"PROJECTNAME" ofType:@"zip" inDirectory:@"Generated"];
    NSString *tmpDir = [self tempFolderPathForUnzipping];

    if (![fileManager fileExistsAtPath:zipFile])
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] template file does not exist at path \"%@\"", zipFile);
        *error = [self errorForNonExistentTemplateFile:zipFile];
        return NO;
    }

    LocalLog(@"[COCO2D-UPDATER] [INFO] cleaning temp folder just in case before update does anything");
    if (![self tidyUpTempFolder:error])
    {
        return NO;
    }

    if (![fileManager createDirectoryAtPath:tmpDir withIntermediateDirectories:NO attributes:nil error:error])
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] could not create directory at path \"%@\" with error %@", tmpDir, error);
        return NO;
    }

    return [self unzipZipFile:zipFile inTmpDir:tmpDir error:error];
}

- (BOOL)unzipZipFile:(NSString *)zipFile inTmpDir:(NSString *)tmpDir error:(NSError **)error
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] unzipping template project archive to temp folder \"%@\"", tmpDir);

    self.task = [[NSTask alloc] init];
    [_task setCurrentDirectoryPath:tmpDir];
    [_task setLaunchPath:@"/usr/bin/unzip"];

    NSArray *args = @[@"-d", tmpDir, @"-o", zipFile];
    [_task setArguments:args];

    NSPipe *pipeStdOut = [NSPipe pipe];
    [_task setStandardOutput:pipeStdOut];
    self.outFile = [pipeStdOut fileHandleForReading];
    [_outFile waitForDataInBackgroundAndNotify];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dataAvailaCallback:)
                                                 name:NSFileHandleDataAvailableNotification
                                               object:nil];

    int status = 0;
    @try
    {
        [_task launch];
        [_task waitUntilExit];

        status = [_task terminationStatus];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    @catch (NSException *exception)
    {
        *error = [self errorForUnzipTaskWithException:exception zipFile:zipFile];
        NSLog(@"[COCO2D-UPDATER] [ERROR] unzipping failed: %@", *error);
        return NO;
    }

    if (status)
    {
        *error = [self errorForFailedUnzipTaskWithstatus:status];
        NSLog(@"[COCO2D-UPDATER] [ERROR] unzipping failed: %@", *error);
        return NO;
    }

    return YES;
}

- (void)dataAvailaCallback:(NSNotification *)notification
{
    NSFileHandle *fileHandle = notification.object;

    NSData *data = nil;
    while ((data = [fileHandle availableData]) && [data length])
    {
        NSString *output = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
        [self updateProgressOfCurrentUnzippedFilePath:output];
    }
}

- (void)updateProgressOfCurrentUnzippedFilePath:(NSString *)output
{
    NSRange tempPathRange = [output rangeOfString:[[self tempFolderPathForUnzipping] stringByAppendingString:@"/"]];
    if (tempPathRange.location != NSNotFound)
    {
        NSString *shortenedFilePath = [output stringByReplacingCharactersInRange:NSMakeRange(0, tempPathRange.location + tempPathRange.length)                                              withString:@""];
        [self updateModalDialogStatusText:[NSString stringWithFormat:@"Unzipping: %@", shortenedFilePath]];
    }
}

- (NSString *)tempFolderPathForUnzipping
{
    return [NSTemporaryDirectory() stringByAppendingPathComponent:@"com.spritebuilder.updatecocos2d"];
}

- (BOOL)tidyUpTempFolder:(NSError **)error
{
    NSFileManager *fileManager = [NSFileManager defaultManager];;

    NSString *tmpDir = [self tempFolderPathForUnzipping];
    LocalLog(@"[COCO2D-UPDATER] [INFO] tidying up temp folder: %@", tmpDir);

    [self updateModalDialogStatusText:@"Tidying up..."];

    if ([fileManager fileExistsAtPath:tmpDir]
        && ![fileManager removeItemAtPath:tmpDir error:error])
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] tidying up unzip folder: %@", *error);
        return NO;
    }
    return YES;
}

- (NSString *)readSpriteBuildersCocos2dVersionFile
{
    NSString *versionFilePath = [[NSBundle mainBundle] pathForResource:@"cocos2d_version" ofType:@"txt" inDirectory:@"Generated"];

    if (versionFilePath == nil)
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] Generated/cocos2d_version.txt could not be found! Version cannot be determined. If developing, rerun scripts/BuildDistribution.sh and try again.");
        return nil;
    }

    NSError *error;
    NSString *result = [NSString stringWithContentsOfFile:versionFilePath encoding:NSUTF8StringEncoding error:&error];
    result = [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!result)
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] reading SB's cocos2d version file: %@", error);
    }

    LocalLog(@"[COCO2D-UPDATER] [INFO] SpriteBuilder's cocos2d version: %@", result);

    return result;
}

static int copyFileCallback(int currentState, int stage, copyfile_state_t state, const char *fromPath, const char *toPath, void *context)
{
    Cocos2dUpdater *self = (__bridge Cocos2dUpdater *) context;
    if (self.isCancelled)
    {
        return COPYFILE_QUIT;
    }

    if (currentState == COPYFILE_COPY_DATA
        && stage == COPYFILE_PROGRESS)
    {
        off_t copiedBytes;
        const int returnCode = copyfile_state_get(state, COPYFILE_STATE_COPIED, &copiedBytes);
        if (returnCode == 0)
        {
            NSString *text = [NSString stringWithFormat:@"Copying: %s (%@)", fromPath, [NSByteCountFormatter stringFromByteCount:copiedBytes countStyle:NSByteCountFormatterCountStyleFile]];
            [self updateModalDialogStatusText:text];
            // NSLog(@"%@", text);
        }
    }
    else
    {
        NSString *text = [NSString stringWithFormat:@"Copying: %@", [NSString stringWithCString:toPath encoding:NSUTF8StringEncoding]] ;
        [self updateModalDialogStatusText:text];
        // NSLog(@"%@", text);
    }

    return COPYFILE_CONTINUE;
}

- (BOOL)copySpriteBuildersCocos2dFolderToProjectFolder:(NSError **)error
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] copying unzipped cocos2d folder from temp to project");
    [self updateModalDialogStatusText:@"Copying files..."];

    NSString *unzippedCocos2dFolder = [[self tempFolderPathForUnzipping] stringByAppendingPathComponent:REL_DEFAULT_COCOS2D_FOLDER_PATH];

    const char *fromPath = [unzippedCocos2dFolder fileSystemRepresentation];
    const char *toPath = [[self defaultProjectsCocos2DFolderPath] fileSystemRepresentation];

    copyfile_state_t copyfileState = copyfile_state_alloc();
    copyfile_state_set(copyfileState, COPYFILE_STATE_STATUS_CB, &copyFileCallback);
    copyfile_state_set(copyfileState, COPYFILE_STATE_STATUS_CTX, (__bridge void *)self);

    int result = copyfile(fromPath, toPath, copyfileState, COPYFILE_ALL | COPYFILE_RECURSIVE);

    copyfile_state_free(copyfileState);

    if (result)
    {
        if (!self.isCancelled)
        {
            [NSError setNewErrorWithErrorPointer:error
                                            code:SBCocos2dUpdateCopyFilesError
                                         message:@"An error occured copying the cocos2d folder to the project directory."];

            LocalLog(@"[COCO2D-UPDATER] [ERROR] could not copy cocos2d folder from \"%@\" to \"%@\" with error %@",
                     unzippedCocos2dFolder, [self defaultProjectsCocos2DFolderPath], *error);
        }
        else
        {
            [NSError setNewErrorWithErrorPointer:error
                                            code:SBCocos2dUpdateUserCancelledError
                                         message:@"Update cancelled."];
        }
    }

    return result == 0;
}

- (BOOL)renameCocos2dFolderToBackupFolder:(NSError **)error
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] renaming project's cocos2d folder to backup name \"%@\"", self.backupFolderPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager moveItemAtPath:[self defaultProjectsCocos2DFolderPath]
                                            toPath:self.backupFolderPath
                                             error:error];
    if (!result)
    {
        LocalLog(@"[COCO2D-UPDATER] [ERROR] could not renamed cocos2d folder to backup folder name: from \"%@\" to \"%@\" with error %@",
                 [self defaultProjectsCocos2DFolderPath], self.backupFolderPath, *error);
    }
    return result;
}

- (BOOL)createSymbolicLinkToCocos2dProject:(NSError **)error
{
    // Previous versions of cocos2d had a project called cocos2d-ios.xcodeproj
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *oldProjectPath = [[self backupFolderPath] stringByAppendingPathComponent:@"cocos2d-ios.xcodeproj"];
    if ([fileManager fileExistsAtPath:oldProjectPath])
    {
        // Make a symbolic link so users don't have to update their cocos2d reference
        NSString *symbolicLinkPath = [[self defaultProjectsCocos2DFolderPath]
                                    stringByAppendingPathComponent:@"cocos2d-ios.xcodeproj"];

		// remove the existing cocos2d-ios.xcodeproj since this proj may still be included in the cocos2d distribution
		if ([fileManager fileExistsAtPath:symbolicLinkPath])
		{
			[fileManager removeItemAtPath:symbolicLinkPath error:nil];
		}

        BOOL result = [fileManager createSymbolicLinkAtPath:symbolicLinkPath
										withDestinationPath:@"cocos2d.xcodeproj"
													  error:error];
		return result;

    }
    return YES;  // No soft link is needed
}

- (Cocos2dVersionComparisonResult)compareProjectsCocos2dVersionWithSpriteBuildersVersion
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] Comparing version - SB: %@ with project: %@ ...", self.spritebuildersCocos2dVersion, self.projectsCocos2dVersion);

    if (!self.projectsCocos2dVersion)
    {
        return Cocos2dVersionProjectVersionUnknown;
    }

	SemanticVersioning * sbVersion = [[SemanticVersioning alloc] initWithString:self.spritebuildersCocos2dVersion];
	SemanticVersioning * projectVersion = [[SemanticVersioning alloc] initWithString:self.projectsCocos2dVersion];

	NSComparisonResult result = [sbVersion compare:projectVersion];

    return result == NSOrderedAscending || result == NSOrderedSame
        ? Cocos2dVersionUpToDate
        : Cocos2dVersionIncompatible;
}

- (BOOL)defaultProjectsCocos2dFolderExists
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:[self defaultProjectsCocos2DFolderPath]];
}

- (BOOL)isCoco2dAGitSubmodule
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] Testing if there's a .gitmodules file ...");

    NSString *rootDir = [_projectSettings.projectPath stringByDeletingLastPathComponent];
    NSString *gitmodulesPath = [rootDir stringByAppendingPathComponent:@".gitmodules"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:gitmodulesPath])
    {
        return NO;
    }

    NSError *error;
    NSString *submodulesContent = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:gitmodulesPath]
                                                           encoding:NSUTF8StringEncoding
                                                              error:&error];

    NSRange cocos2diPhoneTextPosition = [submodulesContent rangeOfString:@"cocos2d-iphone.git" options:NSCaseInsensitiveSearch];
    NSRange cocos2dSwiftTextPosition = [submodulesContent rangeOfString:@"cocos2d-swift.git" options:NSCaseInsensitiveSearch];
    BOOL result = cocos2diPhoneTextPosition.location != NSNotFound
                  || cocos2dSwiftTextPosition.location != NSNotFound;

    LocalLog(@"[COCO2D-UPDATER] [INFO] .gitmodules file found, contains cocos2d-iphone.git or cocos2d-swift.git? %d", result);

    return result;
}

- (NSString *)readProjectsCocos2dVersionFile
{
    NSString *versionFilePath = [self defaultProjectsCocos2DFolderPath];
    versionFilePath = [versionFilePath stringByAppendingPathComponent:@"VERSION"];

    __block NSString *version;
    NSString *fileContent = [NSString stringWithContentsOfFile:versionFilePath encoding:NSUTF8StringEncoding error:nil];
    [fileContent enumerateLinesUsingBlock:^(NSString *line, BOOL *stop)
    {
        version = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        *stop = YES;
    }];

    if (version)
    {
        LocalLog(@"[COCO2D-UPDATER] [INFO] Version file found in Project: %@", fileContent);
        return version;
    }
    return nil;
}

- (NSString *)defaultProjectsCocos2DFolderPath
{
    NSString *rootDir = [_projectSettings.projectPath stringByDeletingLastPathComponent];
    return [rootDir stringByAppendingPathComponent:REL_DEFAULT_COCOS2D_FOLDER_PATH];
}

- (void)cancel
{
    LocalLog(@"[COCO2D-UPDATER] [INFO] USER CANCELLED UPDATE");
    [_task terminate];
    self.cancelled = YES;
}

- (NSError *)errorForFailedUnzipTaskWithstatus:(int)status
{
    NSDictionary *userInfo = @{
            NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Unzip task exited with status code %d. See console app.", status]
    };

    return [NSError errorWithDomain:SBErrorDomain
                               code:SBCocos2dUpdateUnzipTemplateFailedError
                           userInfo:userInfo];
}

- (NSError *)errorForUnzipTaskWithException:(NSException *)exception zipFile:(NSString *)zipFile
{
    NSDictionary *userInfo = @{
            @"zipFile" : zipFile,
            @"exception" : exception,
            NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Exception %@ thrown while running unzip task.", exception.name]};

    return [NSError errorWithDomain:SBErrorDomain
                                     code:SBCocos2dUpdateUnzipTaskError
                                 userInfo:userInfo];
}

- (NSError *)errorForNonExistentTemplateFile:(NSString *)zipFile
{
    NSDictionary *userInfo = @{
            @"zipFile" : zipFile,
            NSLocalizedDescriptionKey : @"Project template zip file does not exist, unable to extract newer cocos2d version."};

    return [NSError errorWithDomain:SBErrorDomain
                                     code:SBCocos2dUpdateTemplateZipFileDoesNotExistError
                                 userInfo:userInfo];
}

@end


text:
"""Tests for lstm_ssd_interleaved_mobilenet_v2_feature_extractor."""

import itertools
import numpy as np
import tensorflow as tf

from lstm_object_detection.models import lstm_ssd_interleaved_mobilenet_v2_feature_extractor
from object_detection.models import ssd_feature_extractor_test

slim = tf.contrib.slim

class LSTMSSDInterleavedMobilenetV2FeatureExtractorTest(
    ssd_feature_extractor_test.SsdFeatureExtractorTestBase):

  def _create_feature_extractor(self,
                                depth_multiplier,
                                pad_to_multiple,
                                is_quantized=False):
    """Constructs a new feature extractor.

    Args:
      depth_multiplier: float depth multiplier for feature extractor
      pad_to_multiple: the nearest multiple to zero pad the input height and
        width dimensions to.
      is_quantized: whether to quantize the graph.
    Returns:
      an ssd_meta_arch.SSDFeatureExtractor object.
    """
    min_depth = 32
    def conv_hyperparams_fn():
      with slim.arg_scope([slim.conv2d], normalizer_fn=slim.batch_norm), \
        slim.arg_scope([slim.batch_norm], is_training=False) as sc:
        return sc
    feature_extractor = (
        lstm_ssd_interleaved_mobilenet_v2_feature_extractor
        .LSTMSSDInterleavedMobilenetV2FeatureExtractor(False, depth_multiplier,
                                                       min_depth,
                                                       pad_to_multiple,
                                                       conv_hyperparams_fn))
    feature_extractor.lstm_state_depth = int(320 * depth_multiplier)
    feature_extractor.depth_multipliers = [
        depth_multiplier, depth_multiplier / 4.0
    ]
    feature_extractor.is_quantized = is_quantized
    return feature_extractor

  def test_extract_features_returns_correct_shapes_128(self):
    image_height = 128
    image_width = 128
    depth_multiplier = 1.0
    pad_to_multiple = 1
    expected_feature_map_shape = [(2, 4, 4, 640),
                                  (2, 2, 2, 256), (2, 1, 1, 256),
                                  (2, 1, 1, 256), (2, 1, 1, 256)]
    self.check_extract_features_returns_correct_shape(
        2, image_height, image_width, depth_multiplier, pad_to_multiple,
        expected_feature_map_shape)

  def test_extract_features_returns_correct_shapes_unroll10(self):
    image_height = 128
    image_width = 128
    depth_multiplier = 1.0
    pad_to_multiple = 1
    expected_feature_map_shape = [(10, 4, 4, 640),
                                  (10, 2, 2, 256), (10, 1, 1, 256),
                                  (10, 1, 1, 256), (10, 1, 1, 256)]
    self.check_extract_features_returns_correct_shape(
        10, image_height, image_width, depth_multiplier, pad_to_multiple,
        expected_feature_map_shape, unroll_length=10)

  def test_extract_features_returns_correct_shapes_320(self):
    image_height = 320
    image_width = 320
    depth_multiplier = 1.0
    pad_to_multiple = 1
    expected_feature_map_shape = [(2, 10, 10, 640),
                                  (2, 5, 5, 256), (2, 3, 3, 256),
                                  (2, 2, 2, 256), (2, 1, 1, 256)]
    self.check_extract_features_returns_correct_shape(
        2, image_height, image_width, depth_multiplier, pad_to_multiple,
        expected_feature_map_shape)

  def test_extract_features_returns_correct_shapes_enforcing_min_depth(self):
    image_height = 320
    image_width = 320
    depth_multiplier = 0.5**12
    pad_to_multiple = 1
    expected_feature_map_shape = [(2, 10, 10, 64),
                                  (2, 5, 5, 32), (2, 3, 3, 32),
                                  (2, 2, 2, 32), (2, 1, 1, 32)]
    self.check_extract_features_returns_correct_shape(
        2, image_height, image_width, depth_multiplier, pad_to_multiple,
        expected_feature_map_shape)

  def test_extract_features_returns_correct_shapes_with_pad_to_multiple(self):
    image_height = 299
    image_width = 299
    depth_multiplier = 1.0
    pad_to_multiple = 32
    expected_feature_map_shape = [(2, 10, 10, 640),
                                  (2, 5, 5, 256), (2, 3, 3, 256),
                                  (2, 2, 2, 256), (2, 1, 1, 256)]
    self.check_extract_features_returns_correct_shape(
        2, image_height, image_width, depth_multiplier, pad_to_multiple,
        expected_feature_map_shape)

  def test_preprocess_returns_correct_value_range(self):
    image_height = 128
    image_width = 128
    depth_multiplier = 1
    pad_to_multiple = 1
    test_image = np.random.rand(4, image_height, image_width, 3)
    feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                       pad_to_multiple)
    preprocessed_image = feature_extractor.preprocess(test_image)
    self.assertTrue(np.all(np.less_equal(np.abs(preprocessed_image), 1.0)))

  def test_variables_only_created_in_scope(self):
    depth_multiplier = 1
    pad_to_multiple = 1
    scope_names = ['MobilenetV2', 'LSTM', 'FeatureMap']
    self.check_feature_extractor_variables_under_scopes(
        depth_multiplier, pad_to_multiple, scope_names)

  def test_has_fused_batchnorm(self):
    image_height = 40
    image_width = 40
    depth_multiplier = 1
    pad_to_multiple = 32
    image_placeholder = tf.placeholder(tf.float32,
                                       [1, image_height, image_width, 3])
    feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                       pad_to_multiple)
    preprocessed_image = feature_extractor.preprocess(image_placeholder)
    _ = feature_extractor.extract_features(preprocessed_image, unroll_length=1)
    self.assertTrue(any(op.type == 'FusedBatchNorm'
                        for op in tf.get_default_graph().get_operations()))

  def test_variables_for_tflite(self):
    image_height = 40
    image_width = 40
    depth_multiplier = 1
    pad_to_multiple = 32
    image_placeholder = tf.placeholder(tf.float32,
                                       [1, image_height, image_width, 3])
    feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                       pad_to_multiple)
    preprocessed_image = feature_extractor.preprocess(image_placeholder)
    tflite_unsupported = ['SquaredDifference']
    _ = feature_extractor.extract_features(preprocessed_image, unroll_length=1)
    self.assertFalse(any(op.type in tflite_unsupported
                         for op in tf.get_default_graph().get_operations()))

  def test_output_nodes_for_tflite(self):
    image_height = 64
    image_width = 64
    depth_multiplier = 1.0
    pad_to_multiple = 1
    image_placeholder = tf.placeholder(tf.float32,
                                       [1, image_height, image_width, 3])
    feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                       pad_to_multiple)
    preprocessed_image = feature_extractor.preprocess(image_placeholder)
    _ = feature_extractor.extract_features(preprocessed_image, unroll_length=1)

    tflite_nodes = [
        'raw_inputs/init_lstm_c',
        'raw_inputs/init_lstm_h',
        'raw_inputs/base_endpoint',
        'raw_outputs/lstm_c',
        'raw_outputs/lstm_h',
        'raw_outputs/base_endpoint_1',
        'raw_outputs/base_endpoint_2'
    ]
    ops_names = [op.name for op in tf.get_default_graph().get_operations()]
    for node in tflite_nodes:
      self.assertTrue(any(node in s for s in ops_names))

  def test_fixed_concat_nodes(self):
    image_height = 64
    image_width = 64
    depth_multiplier = 1.0
    pad_to_multiple = 1
    image_placeholder = tf.placeholder(tf.float32,
                                       [1, image_height, image_width, 3])
    feature_extractor = self._create_feature_extractor(
        depth_multiplier, pad_to_multiple, is_quantized=True)
    preprocessed_image = feature_extractor.preprocess(image_placeholder)
    _ = feature_extractor.extract_features(preprocessed_image, unroll_length=1)

    concat_nodes = [
        'MobilenetV2_1/expanded_conv_16/project/Relu6',
        'MobilenetV2_2/expanded_conv_16/project/Relu6'
    ]
    ops_names = [op.name for op in tf.get_default_graph().get_operations()]
    for node in concat_nodes:
      self.assertTrue(any(node in s for s in ops_names))

  def test_lstm_states(self):
    image_height = 256
    image_width = 256
    depth_multiplier = 1
    pad_to_multiple = 1
    state_channel = 320
    init_state1 = {
        'lstm_state_c': tf.zeros(
            [image_height/32, image_width/32, state_channel]),
        'lstm_state_h': tf.zeros(
            [image_height/32, image_width/32, state_channel]),
        'lstm_state_step': tf.zeros([1])
    }
    init_state2 = {
        'lstm_state_c': tf.random_uniform(
            [image_height/32, image_width/32, state_channel]),
        'lstm_state_h': tf.random_uniform(
            [image_height/32, image_width/32, state_channel]),
        'lstm_state_step': tf.zeros([1])
    }
    seq = {'dummy': tf.random_uniform([2, 1, 1, 1])}
    stateful_reader1 = tf.contrib.training.SequenceQueueingStateSaver(
        batch_size=1, num_unroll=1, input_length=2, input_key='',
        input_sequences=seq, input_context={}, initial_states=init_state1,
        capacity=1)
    stateful_reader2 = tf.contrib.training.SequenceQueueingStateSaver(
        batch_size=1, num_unroll=1, input_length=2, input_key='',
        input_sequences=seq, input_context={}, initial_states=init_state2,
        capacity=1)
    image = tf.random_uniform([1, image_height, image_width, 3])
    feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                       pad_to_multiple)
    with tf.variable_scope('zero_state'):
      feature_maps1 = feature_extractor.extract_features(
          image, stateful_reader1.next_batch, unroll_length=1)
    with tf.variable_scope('random_state'):
      feature_maps2 = feature_extractor.extract_features(
          image, stateful_reader2.next_batch, unroll_length=1)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      sess.run(tf.local_variables_initializer())
      sess.run(tf.get_collection(tf.GraphKeys.TABLE_INITIALIZERS))
      sess.run([stateful_reader1.prefetch_op, stateful_reader2.prefetch_op])
      maps1, maps2 = sess.run([feature_maps1, feature_maps2])
      state = sess.run(stateful_reader1.next_batch.state('lstm_state_c'))
    # feature maps should be different because states are different
    self.assertFalse(np.all(np.equal(maps1[0], maps2[0])))
    # state should no longer be zero after update
    self.assertTrue(state.any())

  def check_extract_features_returns_correct_shape(
      self, batch_size, image_height, image_width, depth_multiplier,
      pad_to_multiple, expected_feature_map_shapes, unroll_length=1):
    def graph_fn(image_tensor):
      feature_extractor = self._create_feature_extractor(depth_multiplier,
                                                         pad_to_multiple)
      feature_maps = feature_extractor.extract_features(
          image_tensor, unroll_length=unroll_length)
      return feature_maps

    image_tensor = np.random.rand(batch_size, image_height, image_width,
                                  3).astype(np.float32)
    feature_maps = self.execute(graph_fn, [image_tensor])
    for feature_map, expected_shape in itertools.izip(
        feature_maps, expected_feature_map_shapes):
      self.assertAllEqual(feature_map.shape, expected_shape)

  def check_feature_extractor_variables_under_scopes(
      self, depth_multiplier, pad_to_multiple, scope_names):
    g = tf.Graph()
    with g.as_default():
      feature_extractor = self._create_feature_extractor(
          depth_multiplier, pad_to_multiple)
      preprocessed_inputs = tf.placeholder(tf.float32, (4, 320, 320, 3))
      feature_extractor.extract_features(
          preprocessed_inputs, unroll_length=1)
      variables = g.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
      for variable in variables:
        self.assertTrue(
            any([
                variable.name.startswith(scope_name)
                for scope_name in scope_names
            ]), 'Variable name: ' + variable.name +
            ' is not under any provided scopes: ' + ','.join(scope_names))

if __name__ == '__main__':
  tf.test.main()

redpajama_set_name: RedPajamaGithub


text:
@interface BBStackView (Private)

// \cond
- (void)setLength:(float)newLength;
- (void)registerSubview:(UIView *)view;
- (void)updateLayout;
- (void)viewFrameChanged:(NSDictionary *)change;
// \endcond

@end

@implementation BBStackView

@synthesize isRemovingSubview = _isRemovingSubview;
@synthesize delegate = _delegate;
@synthesize orientation = _orientation;

- (void)setOrientation:(BBStackViewOrientation)orientation {
    _orientation = orientation;
    [self updateLayout];
}

- (void)setLength:(float)newLength {
    if (self.orientation == BBStackViewOrientationVertical) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, newLength);
    } else {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newLength, self.frame.size.height);
    }
    [self.delegate stackViewLayoutDidChange:self];
}

- (void)registerSubview:(UIView *)view {
    [view addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:@selector(viewFrameChanged:)];
    [self updateLayout];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:(SEL)context withObject:change];
    #pragma clang diagnostic pop
}

- (id)init {
    self = [self initWithFrame:CGRectZero orientation:BBStackViewOrientationVertical];

    return self;
}

- (id)initWithFrame:(CGRect)frame orientation:(BBStackViewOrientation)orientation {
    self = [self initWithFrame:frame];
    if (self)
    {
        _orientation = orientation;
    }

    return self;
}

- (void)updateLayout {
    if (_isUpdating) return;

    _isUpdating = YES;
    float newLength = 0;
    for (UIView *view in self.subviews) {
        if (self.orientation == BBStackViewOrientationVertical) {
            view.frame = CGRectMake(view.frame.origin.x, newLength, view.frame.size.width, view.frame.size.height);
            newLength += view.frame.size.height;
        } else {
            view.frame = CGRectMake(newLength, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
            newLength += view.frame.size.width;
        }
    }
    [self setLength:newLength];
    _isUpdating = NO;
}

- (void)viewFrameChanged:(NSDictionary *)change {
    [self updateLayout];
}

- (void)dealloc {
    for (UIView *view in self.subviews)
    {
        [view removeObserver:self forKeyPath:@"frame"];
    }

    self.isRemovingSubview = YES;
}

- (void)didAddSubview:(UIView *)subview {
    [super didAddSubview:subview];
    [self registerSubview:subview];
}

- (void)willRemoveSubview:(UIView *)subview {
    DAssert(self.isRemovingSubview, @"Remove subviews from a stack view using the stack view's removeSubview: method or the layout will not be updated.");
    [super willRemoveSubview:subview];
}

- (void)addSpacer:(float)length {
    float width = 1, height = 1;
    if (self.orientation == BBStackViewOrientationHorizontal) {
        width = length;
    } else {
        height = length;
    }
    [self addSubview:[[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)]];
}

- (void)removeSubview:(UIView *)subview {
    self.isRemovingSubview = YES;
    [subview removeObserver:self forKeyPath:@"frame"];
    [subview removeFromSuperview];
    self.isRemovingSubview = NO;
    [self updateLayout];
}

@end


text:
function addMessage(message) {
    var flash = $('#flash');
    if (flash.is(":visible")) {
        flash.html(message);
    } else {
        flash = $('<div />', {
            id: "flash",
            text: message
        }).prependTo('body');
    }
    flash.setRemoveTimeout(5000);
}

function resetActiveField() {
    $('td, .entry').each(function () {
        $(this).removeClass('activeField');
    })
}

function updateEditedField() {
    var span = $('#editDone');
    var activeField = $('.activeField');
    var input = span.siblings();
    var value = input.val();
    if (activeField.hasClass('editColor')) {
        value = span.siblings('select').find('option:selected').text();
        activeField.css('color', value);
    }
    activeField.html(value);
    input.val('');
    activeField.removeClass('activeField');
    activeField.closest('tr').addClass('unsaved');
    span.parent().hide();
}

function daysBetween(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    if(date2_ms < date1_ms){
        return false;
    }

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// mini plugin that will hide an element according to the timout given
(function ($) {
    $.fn.setRemoveTimeout = function (milisecs) {
        var element = $(this);
        if (element.length > 0) {
            setTimeout(function () {
                $(element).slideUp().detach();
            }, milisecs);
        }
        return element;
    };
})(jQuery);

// plugin that will show or hide the loading image
(function ($) {
    $.fn.toggleLoadingImage = function () {
        var element = $(this);
        // we use .find for more secure results
        var loadingImg = element.children('.loadingImg');
        if (loadingImg.length > 0) {
            loadingImg.detach();
        } else {
            $('<div />', {'class': 'loadingImg'}).appendTo(element);
        }
    };
})(jQuery);

// "turn off" the lights and focus the specific element
(function ($) {
    $.fn.focusLight = function () {
        // set the default value for focusedDiv
        var element = $(this);
        //focusedDiv = typeof focusedDiv !== 'undefined' ? $(focusedDiv) : $(this);

        // add the shadow to the body
        $('<div />', {'id': 'shadow'}).appendTo('body');

        element.addClass('focused');

        return element;
    };
})(jQuery);

// "turn on" the lights
(function ($) {
    $.fn.unfocusLight = function () {
        var element = $(this);
        $('#shadow').detach();
        element.removeClass('focused');

        return element;
    };
})(jQuery);

// creates a date only datetimepicker
(function ($) {
    $.fn.datePicker = function () {
        // set the default value for focusedDiv
        var element = $(this);
        // add the shadow to the body
        element.datetimepicker({
            timepicker: false,
            format: 'd-m-Y',
            formatDate: 'd-m-Y',
            closeOnDateSelect:true,
            lang: 'el'
        });

        return element;
    };
})(jQuery);

// creates a time only datetimepicker
(function ($) {
    $.fn.timePicker = function () {
        // set the default value for focusedDiv
        var element = $(this);
        // add the shadow to the body
        element.datetimepicker({
            datepicker: false,
            format: 'H:i',
            closeOnDateSelect:true,
            lang: 'el'
        });

        return element;
    };
})(jQuery);

// create a default localized datetimepicker
(function ($) {
    $.fn.elDateTimePicker = function () {
        // set the default value for focusedDiv
        var element = $(this);
        // add the shadow to the body
        element.datetimepicker({
            closeOnTimeSelect:true,
            lang: 'el'
        });

        return element;
    };
})(jQuery);


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.florent37.materialviewpager.MaterialViewPager
        android:id="@+id/materialViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:viewpager_logo="@layout/header_logo"
        app:viewpager_pagerTitleStrip="@layout/material_view_pager_pagertitlestrip_standard"
        app:viewpager_logoMarginTop="100dp"
        app:viewpager_color="@color/colorPrimary"
        app:viewpager_headerHeight="200dp"
        app:viewpager_hideLogoWithFade="false"
        app:viewpager_hideToolbarAndTitle="true"
        app:viewpager_enableToolbarElevation="true"
        />

    <include layout="@layout/drawer" />

</android.support.v4.widget.DrawerLayout>


text:
LIBDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)"

# shellcheck source=prow/scripts/lib/log.sh
source "${LIBDIR}/../log.sh"
# shellcheck source=prow/scripts/lib/utils.sh
source "${LIBDIR}/../utils.sh"

# gardener::deprovision_cluster removes a Gardener cluster
#
# Arguments:
#
# required:
# p - project name
# c - lcuster name
# f - kubeconfig file path
function gardener::deprovision_cluster() {
  local OPTIND
  local projectName
  local clusterName
  local kubeconfigFile
  local namespace
  local wait="false"

  while getopts ":p:c:f:w:" opt; do
      case $opt in
          p)
            projectName="$OPTARG" ;;
          c)
            clusterName="$OPTARG" ;;
          f)
            kubeconfigFile="$OPTARG" ;;
          w)
            wait=${OPTARG:-$wait} ;;
          \?)
              echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
          :)
              echo "Option -$OPTARG argument not provided" >&2 ;;
      esac
  done

  utils::check_empty_arg "$projectName" "Project name is empty. Exiting..."
  utils::check_empty_arg "$clusterName" "Cluster name is empty. Exiting..."
  utils::check_empty_arg "$kubeconfigFile" "Kubeconfig file path is empty. Exiting..."

  log::info "Deprovision cluster: ${clusterName}"

  namespace="garden-${projectName}"

  kubectl annotate shoot "${clusterName}" confirmation.gardener.cloud/deletion=true \
    --overwrite \
    -n "${namespace}" \
    --kubeconfig "${kubeconfigFile}"
  kubectl delete shoot "${clusterName}" \
    --wait="${wait}" \
    --kubeconfig "${kubeconfigFile}" \
    -n "${namespace}"
}

# gardener::reprovision_cluster will generate new cluster name
# and start provisioning again
gardener::reprovision_cluster() {
    # Save bash options to restore them later
    bashOptions="$-"
    # disable pipefile to let function regenerate cluster name
    set +o pipefail
    log::info "cluster provisioning failed, trying provision new cluster"
    log::info "cleaning damaged cluster first"
    gardener::deprovision_cluster \
      -p "${GARDENER_KYMA_PROW_PROJECT_NAME}" \
      -c "${CLUSTER_NAME}" \
      -f "${GARDENER_KYMA_PROW_KUBECONFIG}"
    log::info "building new cluster name"
    utils::generate_commonName -n "${COMMON_NAME_PREFIX}"
    COMMON_NAME=${utils_generate_commonName_return_commonName:?}
    export COMMON_NAME
    CLUSTER_NAME="${COMMON_NAME}"
    export CLUSTER_NAME
    gardener::provision_cluster
    # restore bash options
    set -"${bashOptions}"
}


text:
<!DOCTYPE html>

    <title>Responsive Menu</title>
    <link href="responsiveMenu.css" rel="stylesheet" />

        <input type="radio" name="dropdown" id="hideMenuInput" class="menuHiddenRadio" />
        <input type="radio" name="dropdown" id="showMenuInput" class="menuHiddenRadio" />
        Menu
        Menu

                    Home

                    Galery

                    Promotions

                    Partners

                Contacts

            <input type="radio" name="article" id="home" checked="checked" class="articleSelector" />

                Home integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.
                Placerat suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.
                Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.

            <input type="radio" name="article" id="galery" class="articleSelector" />

                Galery suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.
                Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.
                Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.

            <input type="radio" name="article" id="promotions" class="articleSelector" />

                Promotions suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.
                Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.
                Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.

            <input type="radio" name="article" id="partners" class="articleSelector" />

                Partners suscipit, orci nisl iaculis eros, a tincidunt nisi odio eget lorem nulla condimentum tempor mattis ut vitae feugiat augue cras ut metus a risus iaculis scelerisque eu ac ante.
                Tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel.
                Fusce non varius purus aenean nec magna felis fusce vestibulum velit mollis odio sollicitudin lacinia aliquam posuere, sapien elementum lobortis tincidunt, turpis dui ornare nisl, sollicitudin interdum turpis nunc eget.

    <input type="radio" name="modal" id="modalRadioHide" class="targetInputs" />
    <input type="radio" name="modal" id="modalRadioShow" class="targetInputs" />

                    ×

Modal Header

Contacts

Contacts Contacts Contacts

Modal footer


text:
import { FirebaseNamespace, FirebaseApp } from "@firebase/app-types";
import { Auth } from "./Auth";
import { EmailAuthProvider } from "./EmailAuthProvider";
import { FacebookAuthProvider } from "./FacebookAuthProvider";
import { GithubAuthProvider } from "./GithubAuthProvider";
import { GoogleAuthProvider } from "./GoogleAuthProvider";
import { TwitterAuthProvider } from "./TwitterAuthProvider";
import { SAMLAuthProvider } from "./SAMLAuthProvider";
import { OAuthProvider } from "./OAuthProvider";
import { PhoneAuthProvider } from "./PhoneAuthProvider";
import { RecaptchaVerifier } from "./RecaptchaVerifier";
import { FirebaseAuth } from "@firebase/auth-types";

// tslint:disable-next-line: no-object-literal-type-assertion
const api: Partial<FirebaseNamespace["auth"]> = {
  Auth: Auth as any,
  EmailAuthProvider,
  FacebookAuthProvider,
  GithubAuthProvider,
  GoogleAuthProvider,
  TwitterAuthProvider,
  SAMLAuthProvider,
  OAuthProvider,
  PhoneAuthProvider,
  RecaptchaVerifier
};

const fn = (): FirebaseAuth => {
  throw new Error("not allowed");
};

export default (api || fn) as FirebaseNamespace["auth"];


text:
import os
import torch
import mlogger
import numpy as np

from builtins import range

np.random.seed(1234)

def random_data_generator():
    """ fake data generator
    """
    n_batches = np.random.randint(1, 10)
    for _ in range(n_batches):
        batch_size = np.random.randint(1, 5)
        data = np.random.normal(size=(batch_size, 3))
        target = np.random.randint(10, size=batch_size)
        yield (data, target)

def training_data():
    return random_data_generator()

def validation_data():
    return random_data_generator()

def test_data():
    return random_data_generator()

def oracle(data, target):
    """ fake metric data generator
    """
    loss = np.random.rand()
    acc1 = np.random.rand() + 70
    acck = np.random.rand() + 90

    return loss, acc1, acck

# some hyper-parameters of the experiment
use_visdom = True
lr = 0.01
n_epochs = 10

#----------------------------------------------------------
# Prepare logging
#----------------------------------------------------------

# log the hyperparameters of the experiment
if use_visdom:
    plotter = mlogger.VisdomPlotter({'env': 'my_experiment', 'server': 'http://localhost', 'port': 8097},
                                   manual_update=True)
else:
    plotter = None

xp = mlogger.Container()

xp.config = mlogger.Config(plotter=plotter)
xp.config.update(lr=lr, n_epochs=n_epochs)

xp.epoch = mlogger.metric.Simple()

xp.train = mlogger.Container()
xp.train.acc1 = mlogger.metric.Average(plotter=plotter, plot_title="Accuracy@1", plot_legend="training")
xp.train.acck = mlogger.metric.Average(plotter=plotter, plot_title="Accuracy@k", plot_legend="training")
xp.train.loss = mlogger.metric.Average(plotter=plotter, plot_title="Objective")
xp.train.timer = mlogger.metric.Timer(plotter=plotter, plot_title="Time", plot_legend="training")

xp.val = mlogger.Container()
xp.val.acc1 = mlogger.metric.Average(plotter=plotter, plot_title="Accuracy@1", plot_legend="validation")
xp.val.acck = mlogger.metric.Average(plotter=plotter, plot_title="Accuracy@k", plot_legend="validation")
xp.val.timer = mlogger.metric.Timer(plotter=plotter, plot_title="Time", plot_legend="validation")

xp.val_best = mlogger.Container()
xp.val_best.acc1 = mlogger.metric.Maximum(plotter=plotter, plot_title="Accuracy@1", plot_legend="validation-best")
xp.val_best.acck = mlogger.metric.Maximum(plotter=plotter, plot_title="Accuracy@k", plot_legend="validation-best")

#----------------------------------------------------------
# Training
#----------------------------------------------------------

for epoch in range(n_epochs):
    # train model
    for metric in xp.train.metrics():
        metric.reset()
    for (x, y) in training_data():
        loss, acc1, acck = oracle(x, y)
        # accumulate metrics (average over mini-batches)
        batch_size = len(x)
        xp.train.loss.update(loss, weighting=batch_size)
        xp.train.acc1.update(acc1, weighting=batch_size)
        xp.train.acck.update(acck, weighting=batch_size)
    xp.train.timer.update()
    for metric in xp.train.metrics():
        metric.log()

    # reset metrics in container xp.val
    # (does not include xp.val_best.acc1 and xp.val_best.acck, which we do not want to reset)
    for metric in xp.val.metrics():
        metric.reset()

    # update values on validation set
    for (x, y) in validation_data():
        _, acc1, acck = oracle(x, y)
        batch_size = len(x)
        xp.val.acc1.update(acc1, weighting=batch_size)
        xp.val.acck.update(acck, weighting=batch_size)
    xp.val.timer.update()
    # log values on validation set
    for metric in xp.val.metrics():
        metric.log()

    # update best values on validation set
    xp.val_best.acc1.update(xp.val.acc1.value)
    xp.val_best.acck.update(xp.val.acck.value)
    # log best values on validation set
    for metric in xp.val_best.metrics():
        metric.log()

print("=" * 50)
print("Best Performance On Validation Data:")
print("-" * 50)
print("Prec@1: \t {0:.2f}%".format(xp.val_best.acc1.value))
print("Prec@k: \t {0:.2f}%".format(xp.val_best.acck.value))

plotter.update_plots()

#----------------------------------------------------------
# Save & load experiment
#----------------------------------------------------------

xp.train.loss.reset()
xp.train.loss.update(1)
print('Train loss value before saving state: {}'.format(xp.train.loss.value))

xp.save_to('state.json')

new_plotter = mlogger.VisdomPlotter(visdom_opts={'env': 'my_experiment', 'server': 'http://localhost', 'port': 8097},
                                    manual_update=True)

new_xp = mlogger.load_container('state.json')
new_xp.plot_on(new_plotter)
new_plotter.update_plots()

print('Current train loss value: {}'.format(new_xp.train.loss.value))
new_xp.train.loss.update(2)
print('Updated train loss value: {}'.format(new_xp.train.loss.value))

# # remove the file
os.remove('state.json')


text:
int main(int argc, char **argv) {
	return test_lrec_evaluators_main(argc, argv);
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: The Qt 4 Style API</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

The Qt 4 Style API

A

A

A

                Print

  <link rel="prev" href="qt4-network.html" />
  <link rel="next" href="qt4-threads.html" />

The Network Module in Qt 4
Thread Support in Qt 4

Contents

General Overview

Example Code

Comparison with Qt 3

The Qt 4 Style API

Qt's style API is responsible for performing the widget drawing for built-in widgets. The Qt 4 style API has been revised to make it possible for a style to draw widgets without calling any functions on the widget.

Because Qt 4 is split across multiple libraries, Qt needed this update to be able to draw widgets from other libraries than QtGui. For application developers, this has other benefits, such as more managable parameter lists and the possibility of drawing any graphical element without having a widget of a specific type.

General Overview

The QStyle class is an abstract base class that encapsulates the look and feel of a GUI. Qt's built-in widgets use it to perform nearly all of their drawing, ensuring that they look exactly like the equivalent native widgets.

Most draw functions now take four arguments:

an enum value specifying which graphical element to draw

a QStyleOption specifying how and where to render that element

a QPainter that should be used to draw the element

a QWidget on which the drawing is performed (optional)

The style gets all the information it needs to render the graphical element from QStyleOption. The widget is passed as the last argument in case the style needs it to perform special effects (such as animated default buttons on Mac OS X), but it isn't mandatory. In fact, QStyle can be used to draw on any paint device, not just widgets, by setting the QPainter properly.

Thanks to QStyleOption, it is now possible to make QStyle draw widgets without linking in any code for the widget. This is how Qt's built-in styles can draw Qt 3 widgets such as Q3ListView without necessarily linking against the Qt3Support library. Another significant benefit of the new approach is that it's now possible to use QStyle's draw functions on other widgets than the built-in widgets; for example, you can draw a combobox on any widget, not just on a QComboBox.

QStyleOption has various subclasses for the various types of graphical elements that can be drawn, and it's possible to create custom subclasses. For example, the QStyle::PE_FrameFocusRect element expects a QStyleOptionFocusRect argument. This is documented for each enum value.

When reimplementing QStyle functions that take a QStyleOption parameter, you often need to cast the QStyleOption to a subclass (e.g., QStyleOptionFocusRect). For safety, you can use qstyleoption_cast() to ensure that the pointer type is correct. If the object isn't of the right type, qstyleoption_cast() returns 0. For example:

 const QStyleOptionFocusRect *focusRectOption =
         qstyleoption_cast<const QStyleOptionFocusRect *>(option);
 if (focusRectOption) {
     ...
 }

For performance reasons, there are few member functions and the access to the variables is direct. This "low-level" feel makes the structures use straightforward and emphasizes that these are simply parameters used by the style functions. In addition, the caller of a QStyle function usually creates QStyleOption objects on the stack. This combined with Qt's extensive use of implicit sharing for types such as QString, QPalette, and QColor ensures that no memory allocation needlessly takes place. (Dynamic memory allocation can be an expensive operation, especially when drawing very often in a short time.)

Example Code

The following code snippet illustrates how to use QStyle to draw the focus rectangle from a custom widget's paintEvent():

 void MyWidget::paintEvent(QPaintEvent *event)
 {
     QPainter painter(this);
     ...

     QStyleOptionFocusRect option(1);
     option.init(this);
     option.backgroundColor = palette().color(QPalette::Window);

     style().drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter,
                           this);
 }

The next example shows how to derive from an existing style to customize the look of a graphical element:

 class CustomStyle : public QWindowsStyle
 {
     Q_OBJECT

 public:
     CustomStyle()
     ~CustomStyle() {}

     void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                        QPainter *painter, const QWidget *widget) const;
 };

 void CustomStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                                 QPainter *painter, const QWidget *widget) const
 {
     if (element == PE_IndicatorSpinUp || element == PE_IndicatorSpinDown) {
         QPolygon points(3);
         int x = option->rect.x();
         int y = option->rect.y();
         int w = option->rect.width() / 2;
         int h = option->rect.height() / 2;
         x += (option->rect.width() - w) / 2;
         y += (option->rect.height() - h) / 2;

         if (element == PE_IndicatorSpinUp) {
             points[0] = QPoint(x, y + h);
             points[1] = QPoint(x + w, y + h);
             points[2] = QPoint(x + w / 2, y);
         } else { // PE_SpinBoxDown
             points[0] = QPoint(x, y);
             points[1] = QPoint(x + w, y);
             points[2] = QPoint(x + w / 2, y + h);
         }

         if (option->state & State_Enabled) {
             painter->setPen(option->palette.mid().color());
             painter->setBrush(option->palette.buttonText());
         } else {
             painter->setPen(option->palette.buttonText().color());
             painter->setBrush(option->palette.mid());
         }
         painter->drawPolygon(points);
     } else {
         QWindowsStyle::drawPrimitive(element, option, painter, widget);
     }
 }

See also the Styles Example for a more detailed description of how custom styles can be created.

Comparison with Qt 3

The QStyle class has a similar API in Qt 4 as in Qt 3, with more or less the same functions. What has changed is the signature of the functions and the role played by QStyleOption. For example, here's the signature of the QStyle::drawControl() function in Qt 3:

 void drawControl(ControlElement element,
                  QPainter *painter,
                  const QWidget *widget,
                  const QRect &rect,
                  const QColorGroup &colorGroup,
                  SFlags how = Style_Default,
                  const QStyleOption &option = QStyleOption::Default) const;

Here's the signature of the same function in Qt 4:

 void drawControl(ControlElement element,
                  const QStyleOption *option,
                  QPainter *painter,
                  const QWidget *widget = 0) const;

In Qt 3, some of the information required to draw a graphical element was stored in a QStyleOption parameter, while the rest was deduced by querying the widget. In Qt 4, everything is stored in the QStyleOption parameter.

The Network Module in Qt 4
Thread Support in Qt 4

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
package com.vaadin.ui;

import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;

import com.vaadin.shared.ui.passwordfield.PasswordFieldState;
import com.vaadin.ui.declarative.DesignAttributeHandler;
import com.vaadin.ui.declarative.DesignContext;

/**
 * A field that is used to enter secret text information like passwords. The
 * entered text is not displayed on the screen.
 */
public class PasswordField extends TextField {

    /**
     * Constructs an empty PasswordField.
     */
    public PasswordField() {
        setValue("");
    }

    /**
     * Constructs a PasswordField with given value and caption.
     *
     * @param caption
     *            the caption for the field
     * @param value
     *            the value for the field, not {@code null}
     */
    public PasswordField(String caption, String value) {
        setValue(value);
        setCaption(caption);
    }

    /**
     * Constructs a PasswordField with given caption.
     *
     * @param caption
     *            the caption for the field
     */
    public PasswordField(String caption) {
        this();
        setCaption(caption);
    }

    /**
     * Constructs a new {@code PasswordField} with a value change listener.
     *

     * The listener is called when the value of this {@code PasswordField} is
     * changed either by the user or programmatically.
     *
     * @param valueChangeListener
     *            the value change listener, not {@code null}
     * @since 8.0
     */
    public PasswordField(ValueChangeListener<String> valueChangeListener) {
        super(valueChangeListener);
    }

    /**
     * Constructs a new {@code PasswordField} with the given caption and a value
     * change listener.
     *

     * The listener is called when the value of this {@code PasswordField} is
     * changed either by the user or programmatically.
     *
     * @param caption
     *            the caption for the field
     * @param valueChangeListener
     *            the value change listener, not {@code null}
     * @since 8.0
     */
    public PasswordField(String caption,
            ValueChangeListener<String> valueChangeListener) {
        super(caption, valueChangeListener);
    }

    /**
     * Constructs a new {@code PasswordField} with the given caption, initial
     * text contents and a value change listener.
     *

     * The listener is called when the value of this {@code PasswordField} is
     * changed either by the user or programmatically.
     *
     * @param caption
     *            the caption for the field
     * @param value
     *            the value for the field, not {@code null}
     * @param valueChangeListener
     *            the value change listener, not {@code null}
     * @since 8.0
     */
    public PasswordField(String caption, String value,
            ValueChangeListener<String> valueChangeListener) {
        super(caption, value, valueChangeListener);
    }

    @Override
    public void readDesign(Element design, DesignContext designContext) {
        super.readDesign(design, designContext);
        Attributes attr = design.attributes();
        if (attr.hasKey("value")) {
            doSetValue(DesignAttributeHandler.readAttribute("value", attr,
                    String.class));
        }
    }

    @Override
    public void writeDesign(Element design, DesignContext designContext) {
        super.writeDesign(design, designContext);
        AbstractTextField def = designContext.getDefaultInstance(this);
        Attributes attr = design.attributes();
        DesignAttributeHandler.writeAttribute("value", attr, getValue(),
                def.getValue(), String.class, designContext);
    }

    @Override
    protected PasswordFieldState getState() {
        return (PasswordFieldState) super.getState();
    }

    @Override
    protected PasswordFieldState getState(boolean markAsDirty) {
        return (PasswordFieldState) super.getState(markAsDirty);
    }
}


text:
#ifndef GLMARK2_SHARED_LIBRARY_H_
#define GLMARK2_SHARED_LIBRARY_H_

#include <initializer_list>

class SharedLibrary
{
public:
    SharedLibrary();
    ~SharedLibrary();

    bool open(const char *name);
    bool open_from_alternatives(std::initializer_list<const char*> alt_names);
    void close();

    void *handle() const;
    void *load(const char *symbol) const;

private:
    void *handle_;
};

#endif /* GLMARK2_SHARED_LIBRARY_H_ */