text:
//
//  AppDelegate.m
//
// Copyright (c) 2016, OHSU. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//

#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#import "Zone.h"
#import "Zone+MakeAndMod.h"
#import "Measurement.h"
#import "Measurement+MakeAndMod.h"
#import "Mole.h"
#import "Mole+MakeAndMod.h"
#import "IntroAndEligibleRKModule.h"
#import "OnboardingViewController.h"
#import "BodyMapViewController.h"
#import "DashboardViewController.h"
#import <BridgeSDK/BridgeSDK.h>
#import "WelcomeCarouselViewController.h"
#import "ReconsentViewController.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

-(NSString *)certificateFileName
{

    /*This is the default for a production release, and make sure to add in the production .pem before testing and before releasing to app store, but TAKE IT OUT before committing to a public repo*/
    return @"ohsu-molemapper-production";

    /*This is the default for QA,*/
    //return @"ohsu-molemapper-staging";
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /*This is the setup for a production release*/
    [BridgeSDK setupWithStudy:@"ohsu-molemapper" environment:SBBEnvironmentProd];

    /*This is the setup for normal QA purposes*/
    //[BridgeSDK setupWithStudy:@"ohsu-molemapper" environment:SBBEnvironmentStaging];

    /*For testing against a filtered app version; Anything over build version 0 will return with 'validation failed' in json response. ohsu-molemapper-staging .pem can be used here*/
    //[BridgeSDK setupWithStudy:@"killswitch" environment:SBBEnvironmentProd];

    self.bridgeManager = [[BridgeManager alloc] init];
    self.bridgeManager.context = self.managedObjectContext;
    self.dataUploader = [[APCDataUploader alloc] init];
    self.user = [[MMUser alloc] init];

    [self clearCoreDataStoreOfInvalidMeasurements];

    [self loadAllZonesWithContext:self.managedObjectContext];

    [self setupStdUserDefaults];

    [self overridePageControlColors];

    [self renameLegacyStoredFilenamesInFileSystem];

    [self renameLegacyStoredFilenamesInCoreData];

    //[self setOnboardingBooleansBackToInitialValues];

//Do we want to try to send any unsent measurements here upon launch? Same for surveys?
//[self.bridgeManager signInAndSendMeasurements];

    [self showCorrectOnboardingScreenOrBodyMap];

    return YES;
}

-(void)showCorrectOnboardingScreenOrBodyMap
{
    if ([self shouldShowReconsentScreen])
    {
        [self showReconsentScreen];
    }

    else
    {
        if ([self shouldShowWelcomeScreenWithCarousel])
        {
            [self showWelcomeScreenWithCarousel];
        }
        else if ([self shouldShowOnboarding])
        {
            /*This is a series of tracked booleans in NSUserDefaults that will switch on
            as each step is completed, and then the previous step will be turned off,
            thus allowing the state to be 'saved' if the user opts out at any point
             See below for details on the various steps, which are all ResearchKit modules
             that are spun up from the 'base class' onboardingViewController
             [ud setBool:NO forKey:@"shouldShowEligibilityTest"];
             [ud setBool:NO forKey:@"shouldShowInfoScreens"];
             [ud setBool:NO forKey:@"shouldShowQuiz"];
             [ud setBool:NO forKey:@"shouldShowConsent"];
             [ud setBool:NO forKey:@"shouldShowBridgeSignup"];
             [ud setBool:NO forKey:@"shouldShowInitialSurvey"];*/
            [self showOnboarding];
        }
        else
        {
            [self showBodyMap];
        }
    }
}

//Primarily used for reset or debugging
-(void)setOnboardingBooleansBackToInitialValues
{
    //[self clearMeasurementsAlreadySentForDebugging];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

    //These 2 below should be set to Yes at the beginning to allow onboarding to proceed
    [ud setBool:YES forKey:@"shouldShowWelcomeScreenWithCarousel"];
    [ud setBool:YES forKey:@"shouldShowOnboarding"];
    //All of these below will be set to YES throughout the onboarding as each step is completed
    [ud setBool:NO forKey:@"shouldShowEligibilityTest"];
    [ud setBool:NO forKey:@"shouldShowInfoScreens"];
    [ud setBool:NO forKey:@"shouldShowQuiz"];
    [ud setBool:NO forKey:@"shouldShowConsent"];
    [ud setBool:NO forKey:@"shouldShowBridgeSignup"];
    [ud setBool:NO forKey:@"shouldShowInitialSurvey"];

    //[ud setBool:NO forKey:@"shouldShowIntroAndEligible"];
}

-(void)clearMeasurementsAlreadySentForDebugging
{
    NSMutableArray *mutable = [self.user.measurementsAlreadySentToBridge mutableCopy];
    [mutable removeAllObjects];
    NSArray *empty = mutable;
    self.user.measurementsAlreadySentToBridge = empty;
}

//user.hasEnrolled and user.hasConsented track *almost* identically
//Build version 4 is a new study with OHSU as sole study sponsor
-(BOOL)shouldShowReconsentScreen
{
    BOOL shouldShowReconsentScreen = NO;

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSBundle *mainBundle = [NSBundle mainBundle];
    int appVersion = [[mainBundle objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] intValue];

//ONLY USED FOR DEBUGGING, CHANGE THIS BACK OR
    //[ud setBool:NO forKey:@"reconsentHasBeenSeen"];
//ONLY USED FOR DEBUGGING, CHANGE THIS BACK

    if (appVersion == 4 &&
        self.user.hasEnrolled == YES &&
        [ud boolForKey:@"reconsentHasBeenSeen"] == NO)
    {
        shouldShowReconsentScreen = YES;
    }

    return shouldShowReconsentScreen;
}

-(void)showReconsentScreen
{
    ReconsentViewController *reconsent = [[UIStoryboard storyboardWithName:@"onboarding" bundle:nil] instantiateViewControllerWithIdentifier:@"reconsent"];
    [self setUpRootViewController:reconsent];
}

-(BOOL)shouldShowOnboarding
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    return [ud boolForKey:@"shouldShowOnboarding"];
}

-(void)showOnboarding
{
    //OnboardingVC will check environment variables (NSUserDefaults) to see which part of onboarding to spin up

    OnboardingViewController *onboarding = [[UIStoryboard storyboardWithName:@"onboarding" bundle:nil] instantiateViewControllerWithIdentifier:@"onboardingBase"];
    [self setUpRootViewController:onboarding];
}

-(BOOL)shouldShowWelcomeScreenWithCarousel
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    return [ud boolForKey:@"shouldShowWelcomeScreenWithCarousel"];
}

-(void)showWelcomeScreenWithCarousel
{
    WelcomeCarouselViewController* welcome = [[UIStoryboard storyboardWithName:@"onboarding" bundle:nil] instantiateViewControllerWithIdentifier:@"WelcomeCarouselViewController"];
    [self setUpRootViewController:welcome];
}

- (void)showBodyMap
{
    UITabBarController *tabBar = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"tabBar"];

    [UIView transitionWithView:self.window
                      duration:0.0
                       options:UIViewAnimationOptionTransitionNone
                    animations:^{
                        self.window.rootViewController = tabBar;
                        [self.window makeKeyAndVisible];
                    }
                    completion:nil];

}

- (void) setUpRootViewController: (UIViewController*) viewController
{

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    navController.navigationBar.translucent = NO;

    [UIView transitionWithView:self.window
                      duration:0.6
                       options:UIViewAnimationOptionTransitionNone
                    animations:^{
                        self.window.rootViewController = navController;
                        [self.window makeKeyAndVisible];
                    }
                    completion:nil];
}

/*
 In older versions of the app, filenames are stored with full explicit filepath, and these are overriden upon new version numebrs,
 losing data.  This will go through the filesystem and rename legacy files to have just a filename, not having the full filepath (stupid)
 */
-(void)renameLegacyStoredFilenamesInFileSystem
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *photoFilenames = [fm contentsOfDirectoryAtPath:documentsPath error:nil];
    if (photoFilenames == nil || [photoFilenames count] == 0) {return;}

    //Match 4 digits at beginning of filename and then .png This is a legacy format for zonePhoto names
    NSRegularExpression *zoneRegex = [NSRegularExpression regularExpressionWithPattern:@"^\\d{4}\\.png$"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                error:nil];
    for (NSString *fileName in photoFilenames)
    {
        NSRange fullLength = NSMakeRange(0, [fileName length]);
        NSUInteger zoneMatches = [zoneRegex numberOfMatchesInString:fileName options:0 range:fullLength];

        if (zoneMatches == 1)
        {
            NSString *currentName = [NSString stringWithFormat:@"%@/%@",documentsPath,fileName];
            NSString *correctZoneName = [NSString stringWithFormat:@"zone%@",fileName];
            NSString *updatedName = [NSString stringWithFormat:@"%@/%@",documentsPath,correctZoneName];
            [fm moveItemAtPath:currentName toPath:updatedName error:nil];
        }
    }
}

-(void)renameLegacyStoredFilenamesInCoreData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Zone" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"zoneID" ascending:YES]];
    NSArray *zones = [context executeFetchRequest:fetchRequest error:nil];

    if (!zones || [zones count] == 0) {return;}
    else
    {
        for (Zone *zone in zones)
        {
            NSString *zonePhotoFileName = [Zone imageFilenameForZoneID:zone.zoneID];
            zone.zonePhoto = zonePhotoFileName;
        }
    }

    [self saveContext];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Measurement"];
    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"whichMole" ascending:YES]];
    NSArray *measurementMatches = [context executeFetchRequest:request error:nil];

    if (!measurementMatches || [measurementMatches count] == 0) {return;}

    for (Measurement *measurement in measurementMatches)
    {
        //2delimitDec_29,_2014_17colon45colon56.png
        if (measurement.measurementID == nil) {continue;} //protect against nullified measurements?
        NSString *measurementID = measurement.measurementID;
        NSRange fullLength = NSMakeRange(0, [measurementID length]);

        //Match the filepath up to the documents directory that is in your filename
        NSRegularExpression *measureRegex = [NSRegularExpression regularExpressionWithPattern:@"^/\\S*Documents/" options:NSRegularExpressionCaseInsensitive error:nil];
        NSUInteger measureMatches = [measureRegex numberOfMatchesInString:measurementID options:0 range:fullLength];
        if (measureMatches == 1)
        {
            //swap out the directory structure before your filename with an empty string
            NSString *updatedMeasurementID = [measureRegex stringByReplacingMatchesInString:measurementID
                                                                                options:0
                                                                                range:fullLength
                                                                               withTemplate:@""];
            measurement.measurementID = updatedMeasurementID;
            measurement.measurementPhoto = updatedMeasurementID;
        }

    }

    [self saveContext];
}

-(void)overridePageControlColors
{
    UIPageControl *pageControl = [UIPageControl appearance];
    pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
    pageControl.backgroundColor = [UIColor clearColor];
}

//Establishes default values for a number of booleans and counters used throughout the app
-(void)setupStdUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    //Setup the global repository for available moleIDs
    if (![standardUserDefaults objectForKey:@"nextMoleID"]) //check to see if already established stdUsrDefaults
    {
        int firstValidMoleID = 1;
        [standardUserDefaults setInteger:firstValidMoleID forKey:@"nextMoleID"];
    }
    //Setup default reference object
    if (![standardUserDefaults objectForKey:@"referenceObject"])
    {
        NSString *referenceObject = @"Dime";
        [standardUserDefaults setValue:referenceObject forKey:@"referenceObject"];
    }
    if (![standardUserDefaults objectForKey:@"moleNameGender"])
    {
        NSString *defaultMoleNameGender = @"Random";
        [standardUserDefaults setValue:defaultMoleNameGender forKey:@"moleNameGender"];
    }
    if (![standardUserDefaults objectForKey:@"exportReminderCounter"])
    {
        [standardUserDefaults setValue:@0 forKey:@"exportReminderCounter"];
    }
    if (![standardUserDefaults objectForKey:@"showDemoInfo"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"showDemoInfo"];
    }
    if (![standardUserDefaults objectForKey:@"shouldShowOnboarding"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"shouldShowOnboarding"];
    }
    if (![standardUserDefaults objectForKey:@"shouldShowEligibilityTest"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"shouldShowEligibilityTest"];
    }
    if (![standardUserDefaults objectForKey:@"shouldShowConsent"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"shouldShowConsent"];
    }
    if (![standardUserDefaults objectForKey:@"measurementsAlreadySentToBridge"])
    {
        [standardUserDefaults setObject:[NSArray array] forKey:@"measurementsAlreadySentToBridge"];
    }
    if (![standardUserDefaults objectForKey:@"shouldShowRememberCoinPopup"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"shouldShowRememberCoinPopup"];
    }
    if (![standardUserDefaults objectForKey:@"shouldShowWelcomeScreenWithCarousel"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"shouldShowWelcomeScreenWithCarousel"];
    }
    if (![standardUserDefaults objectForKey:@"reconsentHasBeenSeen"])
    {
        [standardUserDefaults setValue:[NSNumber numberWithBool:NO] forKey:@"reconsentHasBeenSeen"];
    }
    if (![standardUserDefaults objectForKey:@"removedMolesToDiagnoses"])
    {
        [standardUserDefaults setObject:[NSArray array] forKey:@"removedMolesToDiagnoses"];
    }

    //Legacy values
    /*
     if (![standardUserDefaults objectForKey:@"firstViewPinButton"])
     {
     [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstViewPinButton"];
     }
     if (![standardUserDefaults objectForKey:@"firstViewMovePin"])
     {
     [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstViewMovePin"];
     }
     if (![standardUserDefaults objectForKey:@"firstViewMeasurement"])
     {
     [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstViewMeasurement"];
     }
     if (![standardUserDefaults objectForKey:@"firstViewCallout"])
     {
     [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"firstViewCallout"];
     }
     if (![standardUserDefaults objectForKey:@"shouldShowIntroAndEligible"])
     {
     [standardUserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"shouldShowIntroAndEligible"];
     }
     */

}

//Loads all zones into persistent storage if they don't yet exist there, and sets bool for has image for each zone
//in NSUSERdefaults such that they will appear translucent without photo data.
- (void)loadAllZonesWithContext:(NSManagedObjectContext *)context
{
    NSArray *allZoneIDs = [Zone allZoneIDs];
    for (NSString *zoneID in allZoneIDs)
    {
        [Zone zoneForZoneID:zoneID withZonePhotoFileName:nil inManagedObjectContext:context];
    }
}

-(void)clearCoreDataStoreOfInvalidMeasurements
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Measurement"];
    request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"whichMole" ascending:YES]];
    NSArray *measurementMatches = [self.managedObjectContext executeFetchRequest:request error:nil];

    if (!measurementMatches || [measurementMatches count] == 0) {return;}

    for (Measurement *measurement in measurementMatches)
    {
        if (measurement.measurementID == nil)
        {
            NSLog(@"Measurement with invalid ID: %@",measurement.whichMole.moleName);
            [self.managedObjectContext deleteObject:measurement];
        }
    }

}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }

    //NOTE: THIS MUST HAVE THE SAME NAME AS THE XCDATAMODEL!!!
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"InterfaceTesting" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"interfaceTesting.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.

         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end


text:
import {getDockerHost} from './util'

export const webdriverConnectionDetails = {
  host: getDockerHost(),
  port: process.env.SCREENIE_DOCKER_WEBDRIVER_HUB_PORT, // this is generated in ../env.js
}

redpajama_set_name: RedPajamaGithub


text:
{% load static %}
{% load tags %}
{% load thumbnail %}

<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{% block title %}Project{% endblock %}</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="description" content="">
		<meta name="author" content="">

		<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
		<link href="{% static 'css/style.css' %}" rel="stylesheet">
		<link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet">

		<link rel="shortcut icon" href="{% static 'images/favicon.ico'%}">

		{% block header %}
		{% endblock %}

			Project
			<button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation"></button>

 Home

 Admin

				{% if request.user.is_authenticated %}

							{% if request.user.get_full_name %}{{ request.user.get_full_name }}{% else %}{{ request.user.username }}{% endif %}

								{% if logged_in_user_avatar %}

								{% endif %}

@{{ request.user.username }}

							{% if request.user.is_superuser %}

								Admin
							{%  endif %}

							Profile
							Settings
							Logout

				{% else %}

 Login

 Sign Up

				{% endif %}

		{% block content %}
		{% endblock %}

			© 2019 The Developer.

		{% block footer %}
		{% endblock %}


text:
           Angular 2 Input Mask - Text Mask

            docs

          <fieldset class="form-group">
            Date input

              <input type="text" class="form-control" [textMask]="{mask: dateMask}" [(ngModel)]="dateModel">

            ex. 99/99/9999
          </fieldset>
          <fieldset class="form-group">
            Phone input

              <input type="text" class="form-control" [textMask]="{mask: phoneMask}" [(ngModel)]="phoneModel">

            ex. (999) 999-9999
          </fieldset>
          <fieldset class="form-group">
            Taxpayer Identification Numbers

              <input type="text" class="form-control" [textMask]="{mask: taxMask}" [(ngModel)]="taxModel">

            ex. 99-9999999
          </fieldset>
          <fieldset class="form-group">
            Social Security Number

              <input type="text" class="form-control" [textMask]="{mask: ssnMask}" [(ngModel)]="ssnModel">

            ex. 999-99-9999
          </fieldset>
          <fieldset class="form-group">
            Eye Script

              <input type="text" class="form-control" [textMask]="{mask: eyeScriptMask}" [(ngModel)]="eyeScriptModel">

            ex. ~9.99 ~9.99 999
          </fieldset>
          <fieldset class="form-group">
            Credit Card Number

              <input type="text" class="form-control" [textMask]="{mask: ccnMask}" [(ngModel)]="ccnModel">

            ex. 9999 9999 9999 9999
          </fieldset>

          Ng2-select

          <ng-select
            [multiple]="true"
            [items]="items"
            (data)="refreshValue($event)"
            (selected)="selected($event)"
            (removed)="removed($event)"
            placeholder="No city selected">
          </ng-select>

          Timepicker
          A lightweight & configurable timepicker directive

          <timepicker [(ngModel)]="mytime" (change)="changed()" [hourStep]="hstep"
          [minuteStep]="mstep" [showMeridian]="ismeridian"
          [readonlyInput]="!isEnabled"></timepicker>

Time is: {{mytime}}

              Hours step is:
              <select class="form-control" [(ngModel)]="hstep">
                <option *ngFor="let opt of options.hstep" [value]="opt">{{opt}}</option>
              </select>

              Minutes step is:
              <select class="form-control" [(ngModel)]="mstep">
                <option *ngFor="let opt of options.mstep" [value]="opt">{{opt}}</option>
              </select>

          <button type="button" class="btn btn-info" (click)="toggleMode()">12H / 24H</button>
          <button type="button" class="btn btn-info" (click)="isEnabled=!isEnabled">Enable / Disable input</button>
          <button type="button" class="btn btn-primary" (click)="update()">Set to 14:00</button>
          <button type="button" class="btn btn-danger" (click)="clear()">Clear</button>

          Datepicker
          A lightweight & configurable datepicker component

Selected date is: {{ getDate() | date:'fullDate'}}

            <datepicker [(ngModel)]="dt" [minDate]="minDate" [showWeeks]="true"></datepicker>

          <button type="button" class="btn btn-info" (click)="today()">Today</button>
          <button type="button" class="btn btn-danger" (click)="clearDate()">Clear</button>
          <button type="button" class="btn btn-outline-secondary" (click)="toggleMin()" tooltip="After today restriction">Min date</button>


text:
package org.light4j.framework.mvc.sample.service;
import java.util.List;
import java.util.Map;

import org.light4j.framework.mvc.annotatiom.Service;
import org.light4j.framework.mvc.helper.DataBaseHelper;
import org.light4j.framework.mvc.sample.model.Customer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 提供客户数据服务
 *
 * @author longjiazuo
 *
 */
@Service
public class CustomerService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CustomerService.class);

	/**
	 * 获取客户列表
	 *
	 * @return
	 */
	public List<Customer> getCustomerList() {
		String sql = "select * from customer";
		return DataBaseHelper.queryEntityList(Customer.class, sql);
	}

	/**
	 * 获取客户
	 *
	 * @param id
	 * @return
	 */
	public Customer getCustomer(long id) {
		String sql = "select * from customer where id=" + id;
		return DataBaseHelper.queryEntity(Customer.class, sql);
	}

	/**
	 * 创建客户
	 *
	 * @param fieldMap
	 * @return
	 */
	public boolean createCustomer(Map<String, Object> fieldMap) {
		return DataBaseHelper.insertEntity(Customer.class, fieldMap);
	}

	/**
	 * 更新客户
	 *
	 * @param id
	 * @param fieldMap
	 * @return
	 */
	public boolean updateCustomer(long id, Map<String, Object> fieldMap) {
		return DataBaseHelper.updateEntity(Customer.class, id, fieldMap);
	}

	/**
	 * 删除客户
	 *
	 * @param id
	 * @return
	 */
	public boolean deleteCustomer(long id) {
		return DataBaseHelper.deleteEntity(Customer.class, id);
	}
}


text:
package zipkin.server.internal;

import brave.Tracing;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.actuate.health.HealthAggregator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import zipkin.collector.CollectorMetrics;
import zipkin.collector.CollectorSampler;
import zipkin.internal.V2StorageComponent;
import zipkin.server.internal.brave.TracingStorageComponent;
import zipkin.server.internal.brave.TracingV2StorageComponent;
import zipkin.storage.StorageComponent;
import zipkin2.storage.InMemoryStorage;

@Configuration
public class ZipkinServerConfiguration {

  @Autowired(required = false) @Qualifier("httpTracingCustomizer")
  UndertowDeploymentInfoCustomizer httpTracingCustomizer;
  @Autowired(required = false) @Qualifier("httpRequestDurationCustomizer")
  UndertowDeploymentInfoCustomizer httpRequestDurationCustomizer;
  @Autowired(required = false)
  ZipkinHttpCollector httpCollector;

  /** Registers health for any components, even those not in this jar. */
  @Bean ZipkinHealthIndicator zipkinHealthIndicator(HealthAggregator healthAggregator) {
    return new ZipkinHealthIndicator(healthAggregator);
  }

  @Bean public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory(
    @Value("${zipkin.query.allowed-origins:*}") String allowedOrigins
  ) {
    UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
    CorsHandler cors = new CorsHandler(allowedOrigins);
    if (httpCollector != null) {
      factory.addDeploymentInfoCustomizers(
        info -> info.addInitialHandlerChainWrapper(httpCollector)
      );
    }
    factory.addDeploymentInfoCustomizers(
      info -> info.addInitialHandlerChainWrapper(cors)
    );
    if (httpTracingCustomizer != null) {
      factory.addDeploymentInfoCustomizers(httpTracingCustomizer);
    }
    if (httpRequestDurationCustomizer != null) {
      factory.addDeploymentInfoCustomizers(httpRequestDurationCustomizer);
    }
    return factory;
  }

  @Bean
  @ConditionalOnMissingBean(CollectorSampler.class)
  CollectorSampler traceIdSampler(@Value("${zipkin.collector.sample-rate:1.0}") float rate) {
    return CollectorSampler.create(rate);
  }

  @Bean
  @ConditionalOnMissingBean(CollectorMetrics.class)
  CollectorMetrics metrics(MeterRegistry registry) {
    // org.springframework.boot.actuate.metrics.buffer package is removed in boot v2. Temporarily,
    // this inlines the important code. Later we will switch to micrometer.
    return new ActuateCollectorMetrics(registry);
  }

  @Configuration
  @ConditionalOnSelfTracing
  static class TracingStorageComponentEnhancer implements BeanPostProcessor {

    @Autowired(required = false)
    Tracing tracing;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
      return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
      if (tracing == null) return bean;
      if (bean instanceof V2StorageComponent) {
        return new TracingV2StorageComponent(tracing, (V2StorageComponent) bean);
      } else if (bean instanceof StorageComponent) {
        return new TracingStorageComponent(tracing, (StorageComponent) bean);
      }
      return bean;
    }
  }

  /**
   * This is a special-case configuration if there's no StorageComponent of any kind. In-Mem can
   * supply both read apis, so we add two beans here.
   */
  @Configuration
  @Conditional(StorageTypeMemAbsentOrEmpty.class)
  @ConditionalOnMissingBean(StorageComponent.class)
  static class InMemoryConfiguration {
    @Bean StorageComponent storage(
      @Value("${zipkin.storage.strict-trace-id:true}") boolean strictTraceId,
      @Value("${zipkin.storage.search-enabled:true}") boolean searchEnabled,
      @Value("${zipkin.storage.mem.max-spans:500000}") int maxSpans) {
      return V2StorageComponent.create(InMemoryStorage.newBuilder()
        .strictTraceId(strictTraceId)
        .searchEnabled(searchEnabled)
        .maxSpanCount(maxSpans)
        .build());
    }

    @Bean InMemoryStorage v2Storage(V2StorageComponent component) {
      return (InMemoryStorage) component.delegate();
    }
  }

  static final class StorageTypeMemAbsentOrEmpty implements Condition {
    @Override public boolean matches(ConditionContext condition, AnnotatedTypeMetadata ignored) {
      String storageType = condition.getEnvironment().getProperty("zipkin.storage.type");
      if (storageType == null) return true;
      storageType = storageType.trim();
      if (storageType.isEmpty()) return true;
      return storageType.equals("mem");
    }
  }
}


text:
/* MicroJava Type Structures
 *
 * A type structure stores the type attributes of a declared object.
 */
package MicroJava;

import java.util.*;

class Struct {

    public static final int // structure kinds
            NONE  = 0,
            INT   = 1,
            CHAR  = 2,
            ARRAY = 3,
            CLASS = 4;
    public int kind;    // NONE, INT, CHAR, ARRAY, CLASS
    public Struct elemType; // ARRAY: element type
    public int nFields;  // CLASS: number of fields
    public Obj fields;   // CLASS: fields
    private final static Map hash;

    public Struct(int kind) {
        this.kind = kind;
    }

    public Struct(int kind, Struct elemType) {
        this.kind = kind;
        this.elemType = elemType;
    }

    // Checks if this is a reference type
    public boolean isRefType() {
        return kind == CLASS || kind == ARRAY;
    }

    // Checks if two types are equal
    public boolean equals(Struct other) {
        if (kind == ARRAY) {
            return other.kind == ARRAY && other.elemType == elemType;
        } else {
            return other == this;
        }
    }

    // Checks if two types are compatible (e.g. in a comparison)
    public boolean compatibleWith(Struct other) {
        return this.equals(other)
                || (this == Tab.nullType && other.isRefType())
                || (other == Tab.nullType && this.isRefType());
    }

    // Checks if an object with type "this" can be assigned to an object with type "dest"
    public boolean assignableTo(Struct dest) {
        return this.equals(dest)
                || (this == Tab.nullType && dest.isRefType())
                || (this.kind == ARRAY && dest.kind == ARRAY && dest.elemType == Tab.noType);
    }

    static {
        hash = new HashMap();
        hash.put(NONE, "none");
        hash.put(INT, "int");
        hash.put(CHAR, "char");
        hash.put(ARRAY, "array");
        hash.put(CLASS, "class");
    }

    public static String getKindName(int kind) {
        if (hash.containsKey(kind)) {
            return (String) hash.get(kind);
        }
        return "Not defined";
    }

    public static String getTypeName(Struct struct) {
        if (struct.kind == ARRAY) {
            return Struct.getKindName(struct.elemType.kind) + "[]";
        }
        return Struct.getKindName(struct.kind);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.adk.mechanism;

import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Victor;

/**
 *
 * @author Techplex Engineer
 */
public class MiniBot implements Mechanism
{
	SpeedController bot	= new Victor(5);
	boolean pinPulled = false;
	Servo pinPuller = new Servo(6);
	Victor aligner = new Victor(4);
	//Servo guide = new Servo(2);

	/**
	 * Calls the MBDS stop method
	 */
	public void initialize()
	{
		stop();
		pinPull(1);
	}
	public void pinPull()
	{
		pinPulled = true;
		pinPuller.set(0);
	}

	public void align(boolean align)
	{
		if(align)
			aligner.set(-.5);
		else
			aligner.set(0);
	}

//	public void guideDwn()
//	{
//		guide.set(0);
//	}
//	public void guideUp()
//	{
//		guide.set(1);
//	}
//	public void guideGo(double a)
//	{
//			guide.set(a);
//	}
//
//	public void guidePrint()
//	{
//		System.out.println(guide.get());
//	}

	public void pinPull(boolean pos)
	{
		if(!pos)
		{
			pinPulled = false;
			pinPuller.set(1);
		}
		else
		{
			pinPulled = true;
			pinPuller.set(0);
		}
	}

	public void pinPull(double pos)
	{
		//pinPulled = true;
		pinPuller.set(pos);
	}

	/**
	 * Deploy's the minibot, simply runs the motor for a soecified amount of time.
	 */
	public void deploy()
	{
		if(pinPuller.get() < .8)
			bot.set(1);
		else
			this.pinPull();
	}
	/**
	 * Stops all the MBDS's motors
	 */
	public void stop()
	{
		bot.set(0);
	}

}


text:
\documentclass[12pt]{article}

\usepackage{fullpage}
\usepackage{verbatim}

\usepackage{listings}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{mathtools}
\usepackage{tikz}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage[colorlinks=true, allcolors=blue]{hyperref}

\title{CS 444\\
Lecture 15, March 2nd, 2020 \\
Matthew Walinga\\
20627018}

\begin{document}

\maketitle

\bigskip

\section{Casts and stuff}

\underline{$C,L,\sigma \vdash E : \tau_1 $  $\tau_1 := \tau_2 \vee \tau_2 := \tau_1$}

$C,L,\sigma \vdash (\tau_2) E$ : $\tau_2$
\newline

\underline{$C,L,\sigma \vdash E : \tau $  $\tau := D \vee D := \tau$}

$C,L,\sigma \vdash E \text{ instanceof } D $ : boolean

\section{Methods}

- Java closest match is JLS 15.12.2 (we won't do this, we check exact types only)
\newline

$\forall i:$ \underline{$C,L,\sigma \vdash E_i : \tau_i$  \quad static $\tau \;  m(\tau_1,...,\tau_k) \in $ continue(D)}

$C,L,\sigma \vdash D.m(E_1,...E_k) $ : E
\newline

$\forall i:$  \underline{$C,L,\sigma \vdash E_i : \tau_i \quad C,L,\sigma \vdash E : D \quad \tau \; m(\tau_1,...,\tau_k) \in$ continue(D)}

$C,L,\sigma \vdash E.m(E_1,...E_k) : \tau$
\newline

$\forall i:$  \underline{$C,L,\sigma \vdash E_i : \tau_i \quad D(\tau_1,...,\tau_k) \in D$}

$C,L,\sigma \vdash new D(E_1,...E_k) : D$
\newline

\subsection{Return types}

\underline{$C,L,\sigma \vdash E_i : \tau_i \quad \sigma := \tau$}

$C,L,\sigma \vdash \text{return } E$

$C,L,\sigma \vdash \text{return}$

\section{Arrays}

\underline{$C,L,\sigma \vdash E_1 : \tau_1[] \quad C,L,\sigma \vdash E_2 : \tau_2 \quad num(\tau_2)$}

$C,L,\sigma \vdash E_1[E_2] : \tau_1$
\newline

\underline{$C,L,\sigma \vdash E_1 : \tau_1[] \quad C,L,\sigma \vdash E_2 : \tau_2 \quad num(\tau_2) \quad C,L,\sigma \vdash E_3 : \tau_3 \quad \tau_1 := \tau_3$}

$C,L,\sigma \vdash E_1[E_2]  = E_3 : \tau_1$
\newline

\underline{$C,L,\sigma \vdash E : \tau[]$}

$C,L,\sigma \vdash E.length : int$
\newline

\underline{$C,L,\sigma \vdash E : \tau_2 \quad num(\tau_2)$}

$C,L,\sigma \vdash \text{new } \tau_1[E] : \tau_1[]$

\subsection{Array Assignability}

- Arrays can be assigned to the following types:

Object := $\sigma[]$

Cloneable := $\sigma[]$

java.io.Serializable := $\sigma[]$
\newline

\subsubsection{An evil example}

\underline{$D \leq C$}

$C[] := D[] \text{ if } C := D$ (covariant)
\newline

Here's some code as an example:
\newline

\begin{verbatim}
B[] bs = new B[1];
Object[] os = bs;
os[0] = new C();
B b = bs[0];
\end{verbatim}

This program is not type correct! It assigns a $C$-type object to a $B$-type object :o

The rule we defined makes the static type system \underline{unsound}
\newline

Solution: To preserve type-correctness, we must "tag" each array element. Java checks the dynamic type at every array store. This may result in a runtime exception: ArrayStoreException (JLS 10.10)
\newline

The covariant rule we defined above was the problem. Covariants should only be used for data structures that are read-only

\subsubsection{Other soundess holes}

- Casts are intentional soundness holes (programmer tells the compiler "trust me")

\subsubsection{A few more rules}

Two-dimensional arrays (not in Joos so who really cares, but here for completeness)

$\sigma[] := \tau[]$

$\sigma[][] := \tau[][]$

\section{Type-checking pseudocode (Joos)}

"Demand-driven approach"
\newline

(A)
\underline{premises}

	$C,L,\sigma \vdash E : \tau$

\begin{verbatim}
typecheck(E) {
	1. find a rule of the form (A) above
	2. check premises (with recursive calls to typecheck subexpressions)
	3. return tau
}
\end{verbatim}

\section{Static Analysis}

- analyze a program to prove properties of its runtime behaviour

- Applications: generate efficient optimized code

\newpage

\end{document}


text: SELECT SUM(min(f1)) FROM test1


text:
Shopmycourses

Présentation

Concept

Contacte-nous

FAQs

Parrainage

Nos partenariats

Travaille avec nous

Suis-nous

Charte de confidentialité

Conditions Générales d'Utilisation

Mentions légales

Shopmycourses


text:
<?php

namespace Lanin\Laravel\ApiDebugger;

class Storage
{
    /**
     * @var array
     */
    protected $dump = [];

    /**
     * @var Collection[]
     */
    protected $collections = [];

    /**
     * Set collection.
     *
     * @param Collection $collection
     */
    public function inject(Collection $collection)
    {
        $this->collections[] = $collection;
    }

    /**
     * Add vars to debug output.
     *
     * @param array $vars
     */
    public function dump($vars)
    {
        $this->dump[] = count($vars) == 1
            ? $vars[0]
            : $vars;
    }

    /**
     * If storage is empty.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return count($this->collections) == 0 && count($this->dump) == 0;
    }

    /**
     * Return result debug data.
     *
     * @return array
     */
    public function getData()
    {
        $return = [];

        foreach ($this->collections as $collection) {
            $return[$collection->name()] = $collection->items();
        }

        if (count($this->dump) != 0) {
            $return['dump'] = $this->dump;
        }

        return $return;
    }
}


text:
<?php

namespace Kunstmaan\AdminListBundle\Tests\AdminList\FilterType\DBAL;

use Doctrine\DBAL\Query\QueryBuilder;
use Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL\DateFilterType;
use ReflectionClass;
use Symfony\Component\HttpFoundation\Request;

class DateFilterTypeTest extends BaseDbalFilterTest
{
    /**
     * @var DateFilterType
     */
    protected $object;

    protected function setUp(): void
    {
        $this->object = new DateFilterType('date', 'e');
    }

    public function testBindRequest()
    {
        $request = new Request(['filter_comparator_date' => 'before', 'filter_value_date' => '01/01/2012']);

        $data = [];
        $uniqueId = 'date';
        $this->object->bindRequest($request, $data, $uniqueId);

        $this->assertEquals(['comparator' => 'before', 'value' => '01/01/2012'], $data);
    }

    /**
     * @param string $comparator  The comparator
     * @param string $whereClause The where clause
     * @param mixed  $value       The value
     * @param mixed  $testValue   The test value
     *
     * @dataProvider applyDataProvider
     */
    public function testApply($comparator, $whereClause, $value, $testValue)
    {
        $qb = $this->getQueryBuilder();
        $qb->select('*')
            ->from('entity', 'e');
        $this->object->setQueryBuilder($qb);
        $this->object->apply(['comparator' => $comparator, 'value' => $value], 'date');

        $this->assertEquals("SELECT * FROM entity e WHERE e.date $whereClause", $qb->getSQL());
        $this->assertEquals($testValue, $qb->getParameter('var_date'));
    }

    public static function applyDataProvider(): array
    {
        return [
            ['before', '<= :var_date', '20/12/2012', '2012-12-20'],
            ['after', '> :var_date', '21/12/2012', '2012-12-21'],
        ];
    }

    public function testGetTemplate()
    {
        $this->assertEquals('@KunstmaanAdminList/FilterType/dateFilter.html.twig', $this->object->getTemplate());
    }

    /**
     * @throws \ReflectionException
     */
    public function testApplyReturnsNull()
    {
        $queryBuilder = $this->createMock(QueryBuilder::class);
        $queryBuilder->expects($this->never())->method('setParameter');
        $mirror = new ReflectionClass(DateFilterType::class);
        $property = $mirror->getProperty('queryBuilder');
        $property->setAccessible(true);
        $property->setValue($this->object, $queryBuilder);
        $badData = [
            'value' => 'oopsNotADate',
            'comparator' => 'true',
        ];
        $this->object->apply($badData, uniqid());
    }
}


text:
<?php

use app\models\imperium\Imperium;
use app\models\imperium\Rules;
use app\models\imperium\Technologies;
use app\models\imperium\Unit;
use yii\helpers\Url;

/* @var $imperium Imperium */

$info = $imperium->getPlayers()->getRandomRaceInfo(); ?>
<div id="prep-inner" style="<?= !empty($info) ? 'background-image:url(/gfx/' . $info['img'] . '.png)' : '' ?>">

YOU HAVE BEEN CHOOSEN TO BE THE LEADER OF

<?= $imperium->getPlayers()->getRandomRace() ?>

<?php if (!empty($info)): ?>
TRADE AGREEMENTS: <?= $info['trades'][0] ?><?= $info['trades'][1] ?>

STARTING UNITS:

<?php foreach ($info['units'] as $name => $amount): ?>

        <td style="text-align:left" <?= !empty(Unit::description()[$name]) ?
            'data-container="body" data-toggle="popover" data-trigger="hover" data-placement="left" data-content="' . Unit::description()[$name] . '"' :
            '' ?>>
            <?= $name ?>

        <?= $amount ?>

<?php endforeach; ?>

TECHNOLOGIES:

<?php foreach ($info['technologies'] as $technology): ?>

        <td style="text-align:left" <?= !empty(Technologies::description()[$technology]) ?
            'data-container="body" data-toggle="popover" data-trigger="hover" data-placement="left" data-content="' . Technologies::description()[$technology] . '"' :
            '' ?>>
            <?= $technology ?>

<?php endforeach; ?>

SPECIAL ABILITIES:

<?php foreach ($info['specials'] as $special): ?>

<?= !empty(Rules::description()[$special]) ? Rules::description()[$special] : '' ?>

<?php endforeach; ?>

<?php endif; ?>

        <a href="<?= Url::to(['game/play', 'command' => Imperium::COMM_RACE_ACCEPT]) ?>" class="btn btn-lg green beep-bar">ACCEPT

<?php if ($imperium->getSettings()->getRaceChange() && $imperium->getHero()->getFirstRace() === null): ?>

        <a href="<?= Url::to(['game/play', 'command' => Imperium::COMM_RACE_DECLINE]) ?>" class="btn btn-danger btn-block btn-xs">DECLINE

<?php endif; ?>


text:
package com.asakusafw.testdriver.windgate.inprocess;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.windgate.core.AbortTask;
import com.asakusafw.windgate.core.GateProfile;
import com.asakusafw.workflow.executor.TaskExecutionContext;
import com.asakusafw.workflow.executor.TaskExecutor;
import com.asakusafw.workflow.model.CommandTaskInfo;
import com.asakusafw.workflow.model.TaskInfo;

/**
 * In-process {@link TaskExecutor} for {@code windgate/bin/finalize}.
 * @since 0.10.0
 */
public class InProcessWindGateFinalizeTaskExecutor implements TaskExecutor {

    static final Logger LOG = LoggerFactory.getLogger(InProcessWindGateFinalizeTaskExecutor.class);

    static final String COMMAND_SUFFIX = WindGateTaskExecutors.PATH_WINDGATE + "/bin/finalize"; //$NON-NLS-1$

    static final int ARG_BATCH_ID = WindGateTaskExecutors.ARG_PROFILE + 1;

    static final int ARG_FLOW_ID = ARG_BATCH_ID + 1;

    static final int ARG_EXECUTION_ID = ARG_FLOW_ID + 1;

    static final int MINIMUM_TOKENS = WindGateTaskExecutors.ARG_PROFILE + 1;

    @Override
    public boolean isSupported(TaskExecutionContext context, TaskInfo task) {
        return WindGateTaskExecutors.isSupported(context, task, COMMAND_SUFFIX, MINIMUM_TOKENS);
    }

    @Override
    public void execute(TaskExecutionContext context, TaskInfo task) throws InterruptedException, IOException {
        CommandTaskInfo mirror = (CommandTaskInfo) task;
        WindGateTaskExecutors.withLibraries(context, classLoadeer -> {
            GateProfile profile = WindGateTaskExecutors.loadProfile(context, classLoadeer, mirror);
            AbortTask windgate = new AbortTask(profile, context.getExecutionId());
            windgate.execute();
        });
    }
}


text:
package de.t7soft.android.t7home.smarthome.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class InputStream2String {

	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

	private InputStream2String() {
		// utility class
	}

	public static String copyFromInputStream(InputStream in, String encoding)
			throws IOException {
		StringWriter writer = new StringWriter();
		copy(in, writer, encoding);
		String outString = writer.toString();
		return outString;
	}

	private static void copy(InputStream input, Writer output, String encoding)
			throws IOException {
		if (encoding == null) {
			InputStreamReader in = new InputStreamReader(input);
			copy(in, output);
		} else {
			InputStreamReader in = new InputStreamReader(input, encoding);
			copy(in, output);
		}
	}

	private static int copy(Reader input, Writer output) throws IOException {
		long count = copyLarge(input, output);
		if (count > Integer.MAX_VALUE) {
			return -1;
		}
		return (int) count;
	}

	private static long copyLarge(Reader input, Writer output)
			throws IOException {
		char[] buffer = new char[DEFAULT_BUFFER_SIZE];
		long count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

}


text:
package fsnotify

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"

	"golang.org/x/sys/unix"
)

// darwinVersion returns version os Darwin (17 is macOS 10.13).
func darwinVersion() (int, error) {
	s, err := unix.Sysctl("kern.osrelease")
	if err != nil {
		return 0, err
	}
	s = strings.Split(s, ".")[0]
	return strconv.Atoi(s)
}

// testExchangedataForWatcher tests the watcher with the exchangedata operation on macOS.
//
// This is widely used for atomic saves on macOS, e.g. TextMate and in Apple's NSDocument.
//
// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html
// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20
func testExchangedataForWatcher(t *testing.T, watchDir bool) {
	osVersion, err := darwinVersion()
	if err != nil {
		t.Fatal("unable to get Darwin version:", err)
	}
	if osVersion >= 17 {
		t.Skip("Exchangedata is deprecated in macOS 10.13")
	}

	// Create directory to watch
	testDir1 := tempMkdir(t)

	// For the intermediate file
	testDir2 := tempMkdir(t)

	defer os.RemoveAll(testDir1)
	defer os.RemoveAll(testDir2)

	resolvedFilename := "TestFsnotifyEvents.file"

	// TextMate does:
	//
	// 1. exchangedata (intermediate, resolved)
	// 2. unlink intermediate
	//
	// Let's try to simulate that:
	resolved := filepath.Join(testDir1, resolvedFilename)
	intermediate := filepath.Join(testDir2, resolvedFilename+"~")

	// Make sure we create the file before we start watching
	createAndSyncFile(t, resolved)

	watcher := newWatcher(t)

	// Test both variants in isolation
	if watchDir {
		addWatch(t, watcher, testDir1)
	} else {
		addWatch(t, watcher, resolved)
	}

	// Receive errors on the error channel on a separate goroutine
	go func() {
		for err := range watcher.Errors {
			t.Errorf("error received: %s", err)
		}
	}()

	// Receive events on the event channel on a separate goroutine
	eventstream := watcher.Events
	var removeReceived counter
	var createReceived counter

	done := make(chan bool)

	go func() {
		for event := range eventstream {
			// Only count relevant events
			if event.Name == filepath.Clean(resolved) {
				if event.Op&Remove == Remove {
					removeReceived.increment()
				}
				if event.Op&Create == Create {
					createReceived.increment()
				}
			}
			t.Logf("event received: %s", event)
		}
		done <- true
	}()

	// Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop.
	for i := 1; i <= 3; i++ {
		// The intermediate file is created in a folder outside the watcher
		createAndSyncFile(t, intermediate)

		// 1. Swap
		if err := unix.Exchangedata(intermediate, resolved, 0); err != nil {
			t.Fatalf("[%d] exchangedata failed: %s", i, err)
		}

		time.Sleep(50 * time.Millisecond)

		// 2. Delete the intermediate file
		err := os.Remove(intermediate)

		if err != nil {
			t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err)
		}

		time.Sleep(50 * time.Millisecond)

	}

	// We expect this event to be received almost immediately, but let's wait 500 ms to be sure
	time.Sleep(500 * time.Millisecond)

	// The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two:
	if removeReceived.value() < 3 {
		t.Fatal("fsnotify remove events have not been received after 500 ms")
	}

	if createReceived.value() < 3 {
		t.Fatal("fsnotify create events have not been received after 500 ms")
	}

	watcher.Close()
	t.Log("waiting for the event channel to become closed...")
	select {
	case <-done:
		t.Log("event channel closed")
	case <-time.After(2 * time.Second):
		t.Fatal("event stream was not closed after 2 seconds")
	}
}

// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir.
func TestExchangedataInWatchedDir(t *testing.T) {
	testExchangedataForWatcher(t, true)
}

// TestExchangedataInWatchedDir test exchangedata operation on watched file.
func TestExchangedataInWatchedFile(t *testing.T) {
	testExchangedataForWatcher(t, false)
}

func createAndSyncFile(t *testing.T, filepath string) {
	f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		t.Fatalf("creating %s failed: %s", filepath, err)
	}
	f1.Sync()
	f1.Close()
}


text:
package org.apache.commons.imaging.formats.gif;

class GifHeaderInfo {
    public final byte identifier1;
    public final byte identifier2;
    public final byte identifier3;
    public final byte version1;
    public final byte version2;
    public final byte version3;

    public final int logicalScreenWidth;
    public final int logicalScreenHeight;
    public final byte packedFields;
    public final byte backgroundColorIndex;
    public final byte pixelAspectRatio;
    public final boolean globalColorTableFlag;
    public final byte colorResolution;
    public final boolean sortFlag;
    public final byte sizeOfGlobalColorTable;

    public GifHeaderInfo(final byte identifier1, final byte identifier2, final byte identifier3,
            final byte version1, final byte version2, final byte version3,
            final int logicalScreenWidth, final int logicalScreenHeight, final byte packedFields,
            final byte backgroundColorIndex, final byte pixelAspectRatio,
            final boolean globalColorTableFlag, final byte colorResolution,
            final boolean sortFlag, final byte sizeOfGlobalColorTable) {
        this.identifier1 = identifier1;
        this.identifier2 = identifier2;
        this.identifier3 = identifier3;
        this.version1 = version1;
        this.version2 = version2;
        this.version3 = version3;
        this.logicalScreenWidth = logicalScreenWidth;
        this.logicalScreenHeight = logicalScreenHeight;
        this.packedFields = packedFields;
        this.backgroundColorIndex = backgroundColorIndex;
        this.pixelAspectRatio = pixelAspectRatio;
        this.globalColorTableFlag = globalColorTableFlag;
        this.colorResolution = colorResolution;
        this.sortFlag = sortFlag;
        this.sizeOfGlobalColorTable = sizeOfGlobalColorTable;
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Custom binding for the fileSystemProvider API.

var binding = require('binding').Binding.create('fileSystemProvider');
var fileSystemProviderInternal =
    require('binding').Binding.create('fileSystemProviderInternal').generate();
var eventBindings = require('event_bindings');
var fileSystemNatives = requireNative('file_system_natives');
var GetDOMError = fileSystemNatives.GetDOMError;

/**
 * Maximum size of the thumbnail in bytes.
 * @type {number}
 * @const
 */
var METADATA_THUMBNAIL_SIZE_LIMIT = 32 * 1024 * 1024;

/**
 * Regular expression to validate if the thumbnail URI is a valid data URI,
 * taking into account allowed formats.
 * @type {RegExp}
 * @const
 */
var METADATA_THUMBNAIL_FORMAT = new RegExp(
    '^data:image/(png|jpeg|webp);', 'i');

/**
 * Annotates a date with its serialized value.
 * @param {Date} date Input date.
 * @return {Date} Date with an extra value attribute.
 */
function annotateDate(date) {
  // Copy in case the input date is frozen.
  var result = new Date(date.getTime());
  result.value = result.toString();
  return result;
}

/**
 * Verifies if the passed image URI is valid.
 * @param {*} uri Image URI.
 * @return {boolean} True if valid, valse otherwise.
 */
function verifyImageURI(uri) {
  // The URI is specified by a user, so the type may be incorrect.
  if (typeof uri != 'string' && !(uri instanceof String))
    return false;

  return METADATA_THUMBNAIL_FORMAT.test(uri);
}

/**
 * Annotates an entry metadata by serializing its modifiedTime value.
 * @param {EntryMetadata} metadata Input metadata.
 * @return {EntryMetadata} metadata Annotated metadata, which can be passed
 *     back to the C++ layer.
 */
function annotateMetadata(metadata) {
  var result = {
    isDirectory: metadata.isDirectory,
    name: metadata.name,
    size: metadata.size,
    modificationTime: annotateDate(metadata.modificationTime)
  };
  if ('mimeType' in metadata)
    result.mimeType = metadata.mimeType;
  if ('thumbnail' in metadata)
    result.thumbnail = metadata.thumbnail;
  return result;
}

/**
 * Massages arguments of an event raised by the File System Provider API.
 * @param {Array<*>} args Input arguments.
 * @param {function(Array<*>)} dispatch Closure to be called with massaged
 *     arguments.
 */
function massageArgumentsDefault(args, dispatch) {
  var executionStart = Date.now();
  var options = args[0];
  var onSuccessCallback = function(hasNext) {
    fileSystemProviderInternal.operationRequestedSuccess(
        options.fileSystemId, options.requestId, Date.now() - executionStart);
  };
  var onErrorCallback = function(error) {
    fileSystemProviderInternal.operationRequestedError(
        options.fileSystemId, options.requestId, error,
        Date.now() - executionStart);
  }
  dispatch([options, onSuccessCallback, onErrorCallback]);
}

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnmountRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onGetMetadataRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(metadata) {
        var error;
        // It is invalid to return a thumbnail when it's not requested. The
        // restriction is added in order to avoid fetching the thumbnail while
        // it's not needed.
        if (!options.thumbnail && metadata.thumbnail)
          error = 'Thumbnail data provided, but not requested.';

        // Check the format and size. Note, that in the C++ layer, there is
        // another sanity check to avoid passing any evil URL.
        if ('thumbnail' in metadata && !verifyImageURI(metadata.thumbnail))
          error = 'Thumbnail format invalid.';

        if ('thumbnail' in metadata &&
            metadata.thumbnail.length > METADATA_THUMBNAIL_SIZE_LIMIT) {
          error = 'Thumbnail data too large.';
        }

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.getMetadataRequestedSuccess(
            options.fileSystemId,
            options.requestId,
            annotateMetadata(metadata),
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }

      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadDirectoryRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(entries, hasNext) {
        var annotatedEntries = entries.map(annotateMetadata);
        // It is invalid to return a thumbnail when it's not requested.
        var error;
        annotatedEntries.forEach(function(metadata) {
          if (metadata.thumbnail) {
            var error =
                'Thumbnails must not be provided when reading a directory.';
            return;
          }
        });

        if (error) {
          console.error(error);
          fileSystemProviderInternal.operationRequestedError(
              options.fileSystemId, options.requestId, 'FAILED',
              Date.now() - executionStart);
          return;
        }

        fileSystemProviderInternal.readDirectoryRequestedSuccess(
            options.fileSystemId, options.requestId, annotatedEntries, hasNext,
            Date.now() - executionStart);
      };

      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onOpenFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCloseFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onReadFileRequested',
    function(args, dispatch) {
      var executionStart = Date.now();
      var options = args[0];
      var onSuccessCallback = function(data, hasNext) {
        fileSystemProviderInternal.readFileRequestedSuccess(
            options.fileSystemId, options.requestId, data, hasNext,
            Date.now() - executionStart);
      };
      var onErrorCallback = function(error) {
        fileSystemProviderInternal.operationRequestedError(
            options.fileSystemId, options.requestId, error,
            Date.now() - executionStart);
      }
      dispatch([options, onSuccessCallback, onErrorCallback]);
    });

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onDeleteEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCreateFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onCopyEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onMoveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onTruncateRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onWriteFileRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAbortRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onObserveDirectoryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onUnobserveEntryRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onAddWatcherRequested',
    massageArgumentsDefault);

eventBindings.registerArgumentMassager(
    'fileSystemProvider.onRemoveWatcherRequested',
    massageArgumentsDefault);

exports.binding = binding.generate();


text:
import {
  GraphQLID,
  GraphQLNonNull,
} from 'graphql'

import blogPostType from '../../types/blog-post'
import getProjection from '../../get-projection'
import BlogPostModel from '../../../models/blog-post'

export default {
  type: blogPostType,
  args: {
    id: {
      name: 'id',
      type: new GraphQLNonNull(GraphQLID),
    },
  },
  resolve(root, params, ctx, options) {
    const projection = getProjection(options.fieldASTs[0])

    return BlogPostModel
      .findById(params.id)
      .select(projection)
      .exec()
  },
}


text:
@implementation ListTableView

@end


text:
'use strict';

var CoreObject    = require('core-object');
var RSVP          = require('rsvp');

module.exports = CoreObject.extend({
  setup: function() {
    return RSVP.resolve();
  },
  changeToDependencySet: function() {
    return RSVP.resolve([{
      name: 'testDep',
      versionExpected: '2.0.0',
      versionSeen: '2.1.0'
    }]);
  },
  cleanup: function() {
    return RSVP.resolve();
  }
});


text:
class AddAddressFieldsToStockLocation < ActiveRecord::Migration
  def change
    remove_column :spree_stock_locations, :address_id

    add_column :spree_stock_locations, :address1, :string
    add_column :spree_stock_locations, :address2, :string
    add_column :spree_stock_locations, :city, :string
    add_column :spree_stock_locations, :state_id, :integer
    add_column :spree_stock_locations, :state_name, :string
    add_column :spree_stock_locations, :country_id, :integer
    add_column :spree_stock_locations, :zipcode, :string
    add_column :spree_stock_locations, :phone, :string

    usa = Spree::Country.where(:iso => 'US').first
    Spree::Country.reset_column_information
    Spree::StockLocation.update_all(:country_id => usa)
  end
end


text:
import { CompileIdentifierMetadata, CompileTokenMetadata } from './compile_metadata';
export declare class Identifiers {
    static ANALYZE_FOR_ENTRY_COMPONENTS: CompileIdentifierMetadata;
    static ViewUtils: CompileIdentifierMetadata;
    static AppView: CompileIdentifierMetadata;
    static DebugAppView: CompileIdentifierMetadata;
    static AppElement: CompileIdentifierMetadata;
    static ElementRef: CompileIdentifierMetadata;
    static ViewContainerRef: CompileIdentifierMetadata;
    static ChangeDetectorRef: CompileIdentifierMetadata;
    static RenderComponentType: CompileIdentifierMetadata;
    static QueryList: CompileIdentifierMetadata;
    static TemplateRef: CompileIdentifierMetadata;
    static TemplateRef_: CompileIdentifierMetadata;
    static CodegenComponentFactoryResolver: CompileIdentifierMetadata;
    static ComponentFactoryResolver: CompileIdentifierMetadata;
    static ComponentFactory: CompileIdentifierMetadata;
    static NgModuleFactory: CompileIdentifierMetadata;
    static NgModuleInjector: CompileIdentifierMetadata;
    static ValueUnwrapper: CompileIdentifierMetadata;
    static Injector: CompileIdentifierMetadata;
    static ViewEncapsulation: CompileIdentifierMetadata;
    static ViewType: CompileIdentifierMetadata;
    static ChangeDetectionStrategy: CompileIdentifierMetadata;
    static StaticNodeDebugInfo: CompileIdentifierMetadata;
    static DebugContext: CompileIdentifierMetadata;
    static Renderer: CompileIdentifierMetadata;
    static SimpleChange: CompileIdentifierMetadata;
    static UNINITIALIZED: CompileIdentifierMetadata;
    static ChangeDetectorStatus: CompileIdentifierMetadata;
    static checkBinding: CompileIdentifierMetadata;
    static flattenNestedViewRenderNodes: CompileIdentifierMetadata;
    static devModeEqual: CompileIdentifierMetadata;
    static interpolate: CompileIdentifierMetadata;
    static castByValue: CompileIdentifierMetadata;
    static EMPTY_ARRAY: CompileIdentifierMetadata;
    static EMPTY_MAP: CompileIdentifierMetadata;
    static pureProxies: CompileIdentifierMetadata[];
    static SecurityContext: CompileIdentifierMetadata;
    static AnimationKeyframe: CompileIdentifierMetadata;
    static AnimationStyles: CompileIdentifierMetadata;
    static NoOpAnimationPlayer: CompileIdentifierMetadata;
    static AnimationGroupPlayer: CompileIdentifierMetadata;
    static AnimationSequencePlayer: CompileIdentifierMetadata;
    static prepareFinalAnimationStyles: CompileIdentifierMetadata;
    static balanceAnimationKeyframes: CompileIdentifierMetadata;
    static clearStyles: CompileIdentifierMetadata;
    static renderStyles: CompileIdentifierMetadata;
    static collectAndResolveStyles: CompileIdentifierMetadata;
}
export declare function identifierToken(identifier: CompileIdentifierMetadata): CompileTokenMetadata;


text:
package org.apache.solr.search.xjoin;

import java.io.IOException;

import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;

/**
 * Interface for external process results factories.
 */
public interface XJoinResultsFactory<IdType> {

  /**
   * Initialise the factory with the given parameters.
   */
  @SuppressWarnings("rawtypes")
  public void init(NamedList args);

  /**
   * Get external process results based on the given parameters.
   */
  public XJoinResults<IdType> getResults(SolrParams params) throws IOException;

}


text:
using System;
using System.Data;

///////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend.//
///////////////////////////////////////////////////////////
// This class is the front presentation of the UserLogic
// You should make partial classes based on this one, and
// then override the base methods if you want to provide
// custom logic on the accessors.

namespace VotingInfo.Database.Logic.Auth
{
	[Serializable]
	public partial class UserLogic : UserLogicBase
	{
		//Put your code in a separate file.  This is auto generated.
	}
}


text:
#include <linux/irq.h>
#include <linux/platform_device.h>
#include "adcLinuxDriver.h"
#include "adcLinuxDriverAPI.h"
#include <asm/uaccess.h>

long rghpadc_ioctl( struct file* filp, unsigned int cmd, unsigned long arg){

	int err = 0, tmp;
	int retval = 0;
	u32 valorParaElUsuario = 0;
	u32 valorAEscribir = 0;
	u32 actualConfig = 0;
	struct rghpadc_dev* dev;

	if (_IOC_TYPE(cmd) != RGHPADC_IOC_MAGIC) return -ENOTTY;
 	if (_IOC_NR(cmd) > RGHPADC_IOC_MAXNR) return -ENOTTY;
	if (_IOC_DIR(cmd) & _IOC_READ)
		err = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd));
	else if (_IOC_DIR(cmd) & _IOC_WRITE)
		err =  !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd));
	if (err) return -EFAULT;

	dev = (struct rghpadc_dev*)container_of(filp->private_data, struct rghpadc_dev, miscdev);

	switch(cmd){
		case RGHPADC_CAMBIAR_PUERTO:{
			retval = __get_user(valorAEscribir, (u32 __user *)arg);
			valorAEscribir &= 0x07U;
			dev->ultimaConfig = valorAEscribir;
			iowrite32( valorAEscribir, ((unsigned int*)dev->direccionRegistros)+0 );
			break;
		}
		case RGHPADC_CHANGEADDRESS:{
			retval = __get_user(valorAEscribir, (u32 __user *)arg);
			iowrite32( retval, ((unsigned int*)dev->direccionRegistros)+1 );
			break;
		}
		case RGHPADC_CLEAN_INTERRUPT:{
			retval = __get_user(valorAEscribir, (u32 __user *)arg);
			iowrite32( retval, ((unsigned int*)dev->direccionRegistros)+2 );
			break;
		}
		case RGHPADC_LEEARVALORADC:{
			dev->ultimoValorADC = ioread32( ((u32*)dev->direccionRegistros)+0 );
			__put_user(dev->ultimoValorADC, (u32 __user *)arg);
			break;
		}
		case RGHPADC_INICIAR_CAPTURA:{
			valorAEscribir = dev->ultimaConfig;
			valorAEscribir |= 0x80000000U;
			iowrite32( valorAEscribir, ((unsigned int*)dev->direccionRegistros)+0 );
			break;
		}
		case RGHPADC_REINICIAR:{
			valorAEscribir = dev->ultimaConfig;
			valorAEscribir |= 0x40000000U;
			iowrite32( valorAEscribir, ((unsigned int*)dev->direccionRegistros)+0 );
			break;
		}
		case RGHPADC_MEJORDIMLECTURA:{
			valorParaElUsuario = 0100000;//15 bits en cero
			__put_user(valorParaElUsuario, (u32 __user *)arg);
			break;
		}
		case RGHPADC_DIMTOTAL:{
			valorParaElUsuario = 0x100000;//20 bits en cero
			__put_user(valorParaElUsuario, (u32 __user *)arg);
			break;
		}
		default: { /* redundant, as cmd was checked against MAXNR */
    		return -ENOTTY;
		}
	}
	return retval;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4.DistanceBetweenPoints
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] firstPoint = Console.ReadLine()
                .Split(' ')
                .Select(int.Parse)
                .ToArray();
            int[] secondPoint = Console.ReadLine()
                .Split(' ')
                .Select(int.Parse)
                .ToArray();

            Point pointOne = new Point();
            Point pointTwo = new Point();

            pointOne.X = firstPoint[0];
            pointOne.Y = firstPoint[1];
            pointTwo.X = secondPoint[0];
            pointTwo.Y = secondPoint[1];

            CalcDistance(pointOne.X, pointOne.Y, pointTwo.X, pointTwo.Y);
        }

        private static void CalcDistance(int x1, int y1,int x2,int y2)
        {
            double distance = Math.Pow(Math.Abs(x1 - x2), 2) + Math.Pow(Math.Abs(y1 - y2), 2);
            Console.WriteLine(Math.Sqrt(distance));
        }
    }

    class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}


text:
<?php
/*
|--------------------------------------------------------------------------
| DeleteTaxFailAuthTest.php
|--------------------------------------------------------------------------
| Created by Shawn Legge
| Feature:
|    In order to prevent users from deleting taxes
|    As a user or a guest
|    I want to delete a tax
|
| Scenario:
|   Given: I am a user or a guest
|   When: I submit a request to a delete tax
|   Then: I should receive a redirect or an error message
*/
namespace Tests\Feature\acceptance\admin\tax;

use Tests\Feature\acceptance\http\AbstractHttpAjaxTestClass;

class DeleteTaxFailAuthTest extends AbstractHttpAjaxTestClass
{
    use \SetUpTaxTrait;

    protected $postRoute = 'admin/api/categories';

    protected $post = ['_method' => 'DELETE'];

    protected function setUp()
    {
        parent::setUp();
        $this->setUpTax();
        $this->postRoute = $this->postRoute . '/' . $this->tax->id;
    }

    /**
     * @group tax
     * @group acceptance
     * @test
     */
    public function guests_can_not_submit_this_form()
    {
        $this->setPostResponse(['_method' => 'DELETE']);
        $this->postResponse->assertStatus(401);
    }

    /**
     * @group tax
     * @group acceptance
     * @test
     */
    public function users_can_not_submit_this_form()
    {
        $this->setPostResponseUser(['_method' => 'DELETE']);
        $this->postResponse->assertStatus(404);
    }
}


text:
//Problem 1. Say Hello

//Write a method that asks the user for his name and prints "Hello, <name>"
//Write a program to test this method.

using System;

class Hello
{
    static void Main()
    {
        SayHello();
    }

    static void SayHello()
    {
        Console.Write("What is your name? ");
        string name = Console.ReadLine();
        Console.WriteLine("Hello, {0}!", name);
    }
}


text:
var sideA = document.getElementById('sideA');
var sideB = document.getElementById('sideB');
var sideC = document.getElementById('sideC');

var form = document.getElementById('pythagoreanForm');

form.onsubmit = function() {

  var result;

  if (sideA.value) {
    if (sideB.value) {
      result = Math.pow(sideA.value, 2) + Math.pow(sideB.value, 2);
      sideC.value = Math.sqrt(result);
      return false;
    } else if (sideC.value) {
      result = Math.pow(sideA.value, 2) + Math.pow(sideC.value, 2);
      sideB.value = Math.sqrt(result);
      return false;
    }
  }

  if (sideB.value) {
    if (sideA.value) {
      result = Math.pow(sideA.value, 2) + Math.pow(sideB.value, 2);
      sideC.value = Math.sqrt(result);
      return false;
    } else if (sideC.value) {
      result = Math.pow(sideB.value, 2) + Math.pow(sideC.value, 2);
      sideA.value = Math.sqrt(result);
      return false;
    }
  }

  // alert('the missing side is: ' + Math.sqrt(result));

  return false;
}


text:
package com.practise.cq.weibotest.util;

import android.graphics.Bitmap;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.practise.cq.weibotest.R;

/**
 * Created by CQ on 2016/5/17 0017.
 */
public class ImageOptionHelper {

    public static DisplayImageOptions getImageOptions(){
        DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
                .cacheOnDisk(true)
                .cacheInMemory(true)
                /*图片的颜色类型*/
                .bitmapConfig(Bitmap.Config.ARGB_4444)
//                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                /*加载时对应图片*/
                .showImageOnLoading(R.mipmap.timeline_image_failure)
                /*空地址对应图片*/
                .showImageForEmptyUri(R.mipmap.timeline_image_failure)
                /*加载失败对应图片*/
                .showImageOnFail(R.mipmap.timeline_image_failure)
                .build();
        return imageOptions;

    }

    /**显示圆形头像的设置*/
    public static DisplayImageOptions getAvatarOptions() {
        DisplayImageOptions	avatarOptions = new DisplayImageOptions.Builder()
                .cacheOnDisc()
                .cacheInMemory()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showStubImage(R.mipmap.avatar_default)
                .showImageForEmptyUri(R.mipmap.avatar_default)
                .showImageOnFail(R.mipmap.avatar_default)
                .displayer(new RoundedBitmapDisplayer(999))
                .build();
        return avatarOptions;
    }
    /**显示圆角图片的设置*/
    public static DisplayImageOptions getCornerOptions(int cornerRadiusPixels) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheOnDisc()
                .cacheInMemory()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showStubImage(R.mipmap.timeline_image_loading)
                .showImageForEmptyUri(R.mipmap.timeline_image_loading)
                .showImageOnFail(R.mipmap.timeline_image_loading)
                .displayer(new RoundedBitmapDisplayer(cornerRadiusPixels)).build();
        return options;
    }
}


text:
<?php

namespace Application\Models;

use Zend\Form\Form;

class Community {

	private $id;
	private $name;

	public function __construct($id, $name) {
		$this->id = $id;
		$this->name = $name;
	}

	public function getId() {
		return $this->id;
	}

	public function getName() {
		return $this->name;
	}

}


text:
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { IContainer } from '../../../../../model/IContainer';
import { FieldMetaItem, MetaInfo } from '../../../../../model/meta/field-meta';
import { ElementValidatorBase } from '../../../../../validation/element-validator-base';
import { RequiredFieldsValidator } from '../../../../../validation/required-fields-validator';
import { TextLengthValidator } from '../../../../../validation/text-length-validator';
import { ValidNameValidator } from '../../../../../validation/valid-name-validator';
import { ValidationResult } from '../../../../../validation/validation-result';
import { NavigatorService } from '../../../../navigation/modules/navigator/services/navigator.service';
import { ValidationCache, ValidationPair } from '../util/validation-cache';
import { ValidationErrorSeverity } from '../../../../../validation/validation-error-severity';

@Injectable()
export class ValidationService {

    private validationCache: ValidationCache;
    private validNameValidator: ValidNameValidator = new ValidNameValidator();
    private textLengthValidator: TextLengthValidator = new TextLengthValidator();

    constructor(private navigator: NavigatorService, translate: TranslateService) {
        this.validationCache = new ValidationCache(translate);
        navigator.hasNavigated.subscribe(() => this.validateCurrent());
    }

    public getValidationResults(parentElement: IContainer): ValidationPair[] {
        return parentElement ? this.validationCache.getValidationResults(parentElement.url) : [];
    }

    private static requiredFieldValidatorMap: { [className: string]: RequiredFieldsValidator };

    private static elementValidators: { [className: string]: ElementValidatorBase<IContainer>[] };

    public validate(element: IContainer, contents: IContainer[] = []): ValidationPair[] {
        return this.validateElement(element).concat(this.validateAll(contents));
    }

    public async validateCurrent(): Promise<void> {
        const element = this.navigator.currentElement;
        const contents = await this.navigator.currentContents;
        this.refreshValidation(element, contents);
    }

    private validateElement(element: IContainer): ValidationPair[] {
        if (element === undefined) {
            return [];
        }
        return this.validationCache.getValidationResults(element.url);
    }

    private validateAll(elements: IContainer[]): ValidationPair[] {
        return elements
            .map((element: IContainer) => this.validateElement(element))
            .reduce((a: ValidationPair[], b: ValidationPair[]) => a.concat(b), []);
    }

    public async refreshValidation(element: IContainer, contents: IContainer[] = [], clear = true): Promise<void> {
        if (clear) {
            this.validationCache.clear();
        }
        const requiredFieldsResults: ValidationResult = this.getRequiredFieldsValidator(element).validate(element);
        const validNameResult: ValidationResult = this.validNameValidator.validate(element);
        const textLengthValidationResult: ValidationResult = this.textLengthValidator.validate(element);
        const elementValidators = this.getElementValidators(element) || [];
        let elementResults: ValidationResult[] =
            elementValidators.map((validator: ElementValidatorBase<IContainer>) => validator.validate(element, contents))
                .concat(requiredFieldsResults)
                .concat(validNameResult)
                .concat(textLengthValidationResult);
        this.validationCache.addValidationResultsToCache(elementResults);
    }

    public get currentSeverities(): ValidationErrorSeverity[] {
        return this.validate(this.navigator.currentElement, this.navigator.currentContents)
            .map(validationResult => validationResult.severity);
    }

    public isValid(element: IContainer): boolean {
        const isValid = this.validationCache.isValid(element.url);
        return isValid;
    }

    public get currentValid(): boolean {
        return this.isValid(this.navigator.currentElement);
    }

    public allValid(contents: IContainer[]): boolean {
        if (!contents) {
            return true;
        }
        return contents.every((element: IContainer) => this.isValid(element));
    }

    private getRequiredFieldsValidator(element: IContainer): RequiredFieldsValidator {
        if (!ValidationService.requiredFieldValidatorMap) {
            ValidationService.requiredFieldValidatorMap = {};
        }
        let type: string = element.className;
        if (!ValidationService.requiredFieldValidatorMap[type]) {
            let fieldMetaInfo: FieldMetaItem[] = MetaInfo[type];
            let requiredFields: string[] = [];
            fieldMetaInfo.forEach((metaItem: FieldMetaItem) => {
                if (metaItem.required) {
                    requiredFields.push(metaItem.name);
                }
            });
            ValidationService.requiredFieldValidatorMap[type] = new RequiredFieldsValidator(requiredFields);
        }

        return ValidationService.requiredFieldValidatorMap[type];
    }

    private getElementValidators(element: IContainer): ElementValidatorBase<IContainer>[] {
        return ValidationService.elementValidators[element.className];
    }

    public static registerElementValidator<TV extends Function & (typeof ElementValidatorBase), TE extends { className: string }>(
        elementType: TE, validatorType: TV): void {
        if (ValidationService.elementValidators === undefined) {
            ValidationService.elementValidators = {};
        }
        const className: string = elementType.className;
        if (ValidationService.elementValidators[className] === undefined) {
            ValidationService.elementValidators[className] = [];
        }
        const validatorInstance: ElementValidatorBase<IContainer> = new (validatorType)();
        ValidationService.elementValidators[className].push(validatorInstance);
    }
}


text:
#pragma once

#include <cstdio>
#include <memory>
#include <sys/stat.h>

#include "InputSource.h"

namespace SFB {

	class FileInputSource : public InputSource
	{

	public:

		// Creation
		FileInputSource(CFURLRef url);

	private:

		// Bytestream access
		virtual bool _Open(CFErrorRef *error);
		virtual bool _Close(CFErrorRef *error);

		// Functionality
		virtual SInt64 _Read(void *buffer, SInt64 byteCount)	{ return (SInt64)::fread(buffer, 1, (size_t)byteCount, mFile.get()); }
		inline virtual bool _AtEOF() const						{ return ::feof(mFile.get()); }

		inline virtual SInt64 _GetOffset() const				{ return ::ftello(mFile.get()); }
		inline virtual SInt64 _GetLength() const				{ return mFilestats.st_size; }

		// Seeking support
		inline virtual bool _SupportsSeeking() const			{ return true; }
		virtual bool _SeekToOffset(SInt64 offset)				{ return (0 == ::fseeko(mFile.get(), offset, SEEK_SET)); }

		using unique_FILE_ptr = std::unique_ptr<std::FILE, std::function<int(std::FILE *)>>;

		// Data members
		struct stat						mFilestats;
		unique_FILE_ptr					mFile;
	};

}


text:
package com.yoghurt.crypto.transactions.client.place;

public interface AddressPlaceRouter {
  void goToAddress(String addr);
}


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>

    <artifactId>proxy</artifactId>
    <name>SPI: Proxy</name>
    <description>
        The code example for the Proxy
    </description>

    <parent>
        <groupId>com.hazelcast.samples.spi</groupId>
        <artifactId>spi</artifactId>
        <version>0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
</project>


text:
#include <jni.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdlib.h>
#include <uiohook.h>

#include "jni_Errors.h"
#include "jni_Globals.h"

static char log_buffer[1024];
static bool logger(JNIEnv *env, unsigned int level, const char *format, va_list args) {
	bool status = false;

	int log_size = vsnprintf(log_buffer, sizeof(log_buffer), format, args);

	if (log_size >= 0) {
		jstring name = (*env)->NewStringUTF(env, "org.jnativehook");
		jstring message = (*env)->NewStringUTF(env, log_buffer);

		jobject Logger_object = (*env)->CallStaticObjectMethod(
				env,
				java_util_logging_Logger->cls,
				java_util_logging_Logger->getLogger,
				name);

		switch (level) {
			case LOG_LEVEL_DEBUG:
				(*env)->CallVoidMethod(
					env,
					Logger_object,
					java_util_logging_Logger->fine,
					message);
				break;

			case LOG_LEVEL_INFO:
				(*env)->CallVoidMethod(
					env,
					Logger_object,
					java_util_logging_Logger->info,
					message);
				break;

			case LOG_LEVEL_WARN:
				(*env)->CallVoidMethod(
					env,
					Logger_object,
					java_util_logging_Logger->warning,
					message);
				break;

			case LOG_LEVEL_ERROR:
				(*env)->CallVoidMethod(
					env,
					Logger_object,
					java_util_logging_Logger->severe,
					message);
				break;
		}

		(*env)->DeleteLocalRef(env, name);
		(*env)->DeleteLocalRef(env, message);
		(*env)->DeleteLocalRef(env, Logger_object);

		status = true;
	}

	va_end(args);

	return status;
}

bool jni_Logger(JNIEnv *env, unsigned int level, const char *format, ...) {
	va_list args;
	va_start(args, format);

	return logger(env, level, format, args);
}

bool uiohook_LoggerCallback(unsigned int level, const char *format, ...) {
	bool status = false;

	JNIEnv *env = NULL;
	if ((*jvm)->GetEnv(jvm, (void **)(&env), jvm_attach_args.version) == JNI_OK) {
		va_list args;
		va_start(args, format);
		status = logger(env, level, format, args);
	}
	else {
		jni_Logger(env, LOG_LEVEL_ERROR, "%s [%u]: GetEnv failed!\n",
				__FUNCTION__, __LINE__);
	}

	return status;
}


text:
from swgpy.object import *

def create(kernel):
	result = Intangible()

	result.template = "object/draft_schematic/food/component/shared_container_large_glass.iff"
	result.attribute_template_id = -1
	result.stfName("string_id_table","")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
package com.haulmont.yarg.formatters.impl.doc.connector;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LinuxProcessManager extends JavaProcessManager implements ProcessManager {
    protected static final Pattern PS_OUTPUT_LINE = Pattern.compile("^\\s*(\\d+)\\s+(.*)$");

    protected String[] psCommand() {
        return new String[]{"/bin/ps", "-e", "-o", "pid,args"};
    }

    @Override
    public List<Long> findPid(String host, int port) {
        try {
            String regex = Pattern.quote(host) + ".*" + port;
            Pattern commandPattern = Pattern.compile(regex);
            List<String> lines = execute(psCommand());
            List<Long> result = new ArrayList<Long>();

            for (String line : lines) {
                Matcher lineMatcher = PS_OUTPUT_LINE.matcher(line);
                if (lineMatcher.matches()) {
                    String command = lineMatcher.group(2);
                    Matcher commandMatcher = commandPattern.matcher(command);
                    if (commandMatcher.find()) {
                        result.add(Long.parseLong(lineMatcher.group(1)));
                    }
                }
            }

            return result;
        } catch (IOException e) {
            log.error("An error occured while searching for soffice PID in linux system", e);
        }

        return Collections.singletonList(PID_UNKNOWN);
    }

    public void kill(Process process, List<Long> pids) {
        log.info("Linux office process manager is going to kill following processes " + pids);
        for (Long pid : pids) {
            try {
                if (PID_UNKNOWN != pid) {
                    execute("/bin/kill", "-KILL", Long.toString(pid));
                } else {
                    log.warn("Fail to kill open office process with platform dependent manager - PID not found.");
                    super.kill(process, Collections.singletonList(pid));
                }
            } catch (Exception e) {
                log.error(String.format("An error occurred while killing process %d in linux system. Process.destroy() will be called.", pid), e);
                super.kill(process, Collections.singletonList(pid));
            }
        }
    }

    protected List<String> execute(String... args) throws IOException {
        Process process = new ProcessBuilder(args).start();
        @SuppressWarnings("unchecked")
        List<String> lines = IOUtils.readLines(process.getInputStream());
        return lines;
    }

}