text:
//
//  SQLTool.m
//  EpiInfo
//
//  Created by John Copeland on 4/4/16.
//

#import "SQLTool.h"
#include <stdlib.h>

@implementation SQLTool
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self)
    {
        initialHeight = frame.size.height;

        [self setBackgroundColor:[UIColor whiteColor]];

        UIButton *resignButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [resignButton addTarget:self action:@selector(sqlStatementFieldResign:) forControlEvents:UIControlEventTouchUpInside];
        downRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(downSwipe:)];
        [downRecognizer setDirection:UISwipeGestureRecognizerDirectionDown];
        [downRecognizer setNumberOfTouchesRequired:1];
        [resignButton addGestureRecognizer:downRecognizer];
        [resignButton setBackgroundColor:[UIColor clearColor]];
        [self addSubview:resignButton];

        sqlStatementFieldBackground = [[UIView alloc] initWithFrame:CGRectMake(2, 2, frame.size.width - 4.0, 128)];
        [sqlStatementFieldBackground setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
        sqlStatementField = [[UITextView alloc] initWithFrame:CGRectMake(2, 2, sqlStatementFieldBackground.frame.size.width - 4.0, sqlStatementFieldBackground.frame.size.height - 4.0)];
        if (@available(iOS 11.0, *)) {
            [sqlStatementField setSmartQuotesType:UITextSmartQuotesTypeNo];
        } else {
            // Fallback on earlier versions
        }
        [sqlStatementField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [sqlStatementField setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
        [sqlStatementField setAutocorrectionType:UITextAutocorrectionTypeNo];
        [sqlStatementField setKeyboardType:UIKeyboardTypeDefault];
        [sqlStatementField setDelegate:self];
        [sqlStatementFieldBackground addSubview:sqlStatementField];
        [self addSubview:sqlStatementFieldBackground];

        UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 2, 90, 30)];
        [clearButton setImage:[UIImage imageNamed:@"ClearButtonBlue.png"] forState:UIControlStateNormal];
        [clearButton addTarget:self action:@selector(clearButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [clearButton setAccessibilityLabel:@"Clear without submitting."];
        [self addSubview:clearButton];

        UIButton *recallButton = [[UIButton alloc] initWithFrame:CGRectMake(clearButton.frame.origin.x + clearButton.frame.size.width + 2, clearButton.frame.origin.y, 90, 30)];
        [recallButton setImage:[UIImage imageNamed:@"RecallButtonBlue.png"] forState:UIControlStateNormal];
        [recallButton addTarget:self action:@selector(recallButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [recallButton setAccessibilityLabel:@"Recall last statement."];
        [self addSubview:recallButton];

        UIButton *submitButton = [[UIButton alloc] initWithFrame:CGRectMake(recallButton.frame.origin.x + recallButton.frame.size.width + 2, clearButton.frame.origin.y, 90, 30)];
        [submitButton setImage:[UIImage imageNamed:@"SubmitButtonBlue.png"] forState:UIControlStateNormal];
        [submitButton addTarget:self action:@selector(submitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [submitButton setAccessibilityLabel:@"Submit sequel statement"];
        [self addSubview:submitButton];

        UIButton *questionMarkButton = [[UIButton alloc] initWithFrame:CGRectMake(submitButton.frame.origin.x + submitButton.frame.size.width + 2, clearButton.frame.origin.y, clearButton.frame.size.height, clearButton.frame.size.height)];
        [questionMarkButton setImage:[UIImage imageNamed:@"QuestionMarkButton.png"] forState:UIControlStateNormal];
        [questionMarkButton addTarget:self action:@selector(questionMarkPressed:) forControlEvents:UIControlEventTouchUpInside];
        [questionMarkButton setAccessibilityLabel:@"SQL tool help."];
        [self addSubview:questionMarkButton];

        recentSubmissionsIndex = 0;
        recentSubmissions = [[NSMutableArray alloc] init];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
        {
            NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

            if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
            {
                NSString *selStmt = @"select sql_statement from __sqlite_recall_table__";
                const char *query_stmt = [selStmt UTF8String];
                sqlite3_stmt *statement;
                if (sqlite3_prepare_v2(epiinfoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                {
                    while (sqlite3_step(statement) == SQLITE_ROW)
                    {
                        [recentSubmissions addObject:[NSString stringWithUTF8String:[[NSString stringWithFormat:@"%s", sqlite3_column_text(statement, 0)] cStringUsingEncoding:NSMacOSRomanStringEncoding]]];
                    }
                }
                else
                {
                    //
                }
                sqlite3_finalize(statement);
            }
            sqlite3_close(epiinfoDB);
            recentSubmissionsIndex = (int)[recentSubmissions count] - 1;
        }
    }

    return self;
}

- (void)submitButtonPressed:(UIButton *)sender
{
    [results removeFromSuperview];
    results = nil;
    [self setContentSize:CGSizeMake(0, 0)];

    if ([[sqlStatementField text] length] < 1)
        return;

    NSMutableString *sqlStatement = [NSMutableString stringWithString:[sqlStatementField text]];
    while ([sqlStatement characterAtIndex:0] == ' ')
        [sqlStatement deleteCharactersInRange:NSMakeRange(0, 1)];

    if (![sqlStatement isEqualToString:(NSString *)[recentSubmissions lastObject]])
    {
        [recentSubmissions addObject:sqlStatement];

        if ([recentSubmissions count] > 100)
        {
            [recentSubmissions removeObjectAtIndex:0];
        }
    }
    recentSubmissionsIndex = (int)[recentSubmissions count] - 1;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if (![[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
    {
        return;
    }

    // Get data tables from SQLite database
    NSMutableArray *arrayOfDatasets = [[NSMutableArray alloc] init];
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
        {
            NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

            if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
            {
                NSString *selStmt = [NSString stringWithFormat:@"select name from sqlite_master order by name"];
                const char *query_stmt = [selStmt UTF8String];
                sqlite3_stmt *statement;
                if (sqlite3_prepare_v2(epiinfoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                {
                    while (sqlite3_step(statement) == SQLITE_ROW)
                    {
                        [arrayOfDatasets addObject:[[NSString stringWithFormat:@"%s", sqlite3_column_text(statement, 0)] lowercaseString]];
                    }
                }
                sqlite3_finalize(statement);
            }
            sqlite3_close(epiinfoDB);
        }
    }

    if ([sqlStatement length] > 5 && [[[sqlStatement substringWithRange:NSMakeRange(0, 6)] lowercaseString] isEqualToString:@"tables"])
    {
        [self sqlStatementFieldResign:sender];

        float resultsHeight = (float)[arrayOfDatasets count] * 40.0 + 40.0;
        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width - 4, resultsHeight)];
        [self addSubview:results];
//        [self sendSubviewToBack:results];

        UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, results.frame.size.width, 40)];
        [header setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
        [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]];
        [header setTextAlignment:NSTextAlignmentCenter];
        [header setTextColor:[UIColor whiteColor]];
        [header setText:@"Epi Info Tables on this Device"];
        [header setUserInteractionEnabled:YES];
        UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
        [headerTap setNumberOfTapsRequired:1];
        [header addGestureRecognizer:headerTap];
        [results addSubview:header];

        float yValue = 0.0;
        for (id table in arrayOfDatasets)
        {
            yValue += 40.0;
            UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(4, yValue, results.frame.size.width - 4, 40)];
            [rowLabel setBackgroundColor:[UIColor clearColor]];
            [rowLabel setTextColor:[UIColor blackColor]];
            [rowLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
            [rowLabel setTextAlignment:NSTextAlignmentLeft];
            [rowLabel setText:(NSString *)table];
            [rowLabel setUserInteractionEnabled:YES];
            UITapGestureRecognizer *rowLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [rowLabelTap setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *rowLabelLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [rowLabelLongPress setMinimumPressDuration:1.0];
            [rowLabel addGestureRecognizer:rowLabelTap];
            [rowLabel addGestureRecognizer:rowLabelLongPress];
            [results addSubview:rowLabel];
        }
        [self setContentSize:CGSizeMake(self.frame.size.width, results.frame.origin.y + results.frame.size.height + 80)];
    }

    else if (([sqlStatement length] > 4 && [[[sqlStatement substringWithRange:NSMakeRange(0, 5)] lowercaseString] isEqualToString:@"meta "]) || ([sqlStatement length] > 8 && [[[sqlStatement substringWithRange:NSMakeRange(0, 9)] lowercaseString] isEqualToString:@"metadata "]))
    {
        int tablePosition = 9;
        if ([[[sqlStatement substringWithRange:NSMakeRange(0, 5)] lowercaseString] isEqualToString:@"meta "])
        {
            tablePosition = 5;
        }

        NSMutableString *tableToMeta = [NSMutableString stringWithString:[sqlStatement substringFromIndex:tablePosition]];
        while ([tableToMeta characterAtIndex:0] == ' ')
            [tableToMeta deleteCharactersInRange:NSMakeRange(0, 1)];
        while ([tableToMeta characterAtIndex:[tableToMeta length] - 1] == ' ')
            [tableToMeta deleteCharactersInRange:NSMakeRange([tableToMeta length] - 1, 1)];

        if ([tableToMeta containsString:@" "])
        {
            float resultsHeight = 40.0;
            results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width - 4, resultsHeight)];
            [self addSubview:results];
//            [self sendSubviewToBack:results];

            UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, results.frame.size.width, 40)];
            [header setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
            [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];
            [header setTextAlignment:NSTextAlignmentCenter];
            [header setTextColor:[UIColor whiteColor]];
            [header setText:[NSString stringWithFormat:@"Too many arguments: %@", tableToMeta]];
            [header setUserInteractionEnabled:YES];
            UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [headerTap setNumberOfTapsRequired:1];
            [header addGestureRecognizer:headerTap];
            [results addSubview:header];
            return;
        }
        if (![arrayOfDatasets containsObject:[tableToMeta lowercaseString]])
        {
            float resultsHeight = 40.0;
            results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width - 4, resultsHeight)];
            [self addSubview:results];
//            [self sendSubviewToBack:results];

            UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, results.frame.size.width, 40)];
            [header setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
            [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];
            [header setTextAlignment:NSTextAlignmentCenter];
            [header setTextColor:[UIColor whiteColor]];
            [header setText:[NSString stringWithFormat:@"Table %@ not found.", tableToMeta]];
            [header setUserInteractionEnabled:YES];
            UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [headerTap setNumberOfTapsRequired:1];
            [header addGestureRecognizer:headerTap];
            [results addSubview:header];
            return;
        }

        [self sqlStatementFieldResign:sender];

        NSMutableArray *arrayOfColumns = [[NSMutableArray alloc] init];

        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
            {
                NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

                if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
                {
                    NSString *selStmt = [NSString stringWithFormat:@"select * from %@ limit 1", tableToMeta];
                    const char *query_stmt = [selStmt UTF8String];
                    sqlite3_stmt *statement;
                    if (sqlite3_prepare_v2(epiinfoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                    {
                        int i = 0;
                        while (sqlite3_column_name(statement, i))
                        {
                            [arrayOfColumns addObject:[[NSString alloc] initWithUTF8String:sqlite3_column_name(statement, i)]];
                            i++;
                        }
                    }
                    sqlite3_finalize(statement);
                }
                sqlite3_close(epiinfoDB);
            }
        }

        AnalysisDataObject *ado = [[AnalysisDataObject alloc] initWithStoredDataTable:tableToMeta];

        float resultsHeight = (float)[arrayOfColumns count] * 40.0 + 40.0;
        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width - 4, resultsHeight)];
        [self addSubview:results];
//        [self sendSubviewToBack:results];

        UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, results.frame.size.width, 40)];
        [header setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
        [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]];
        [header setTextAlignment:NSTextAlignmentCenter];
        [header setTextColor:[UIColor whiteColor]];
        [header setText:[NSString stringWithFormat:@"%@ Metadata", tableToMeta]];
        [header setUserInteractionEnabled:YES];
        UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
        [headerTap setNumberOfTapsRequired:1];
        [header addGestureRecognizer:headerTap];
        [results addSubview:header];

        float yValue = 0.0;
        {
            yValue += 40.0;
            UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(4, yValue, (results.frame.size.width - 4) * 0.667, 40)];
            [rowLabel setBackgroundColor:[UIColor clearColor]];
            [rowLabel setTextColor:[UIColor blackColor]];
            [rowLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];
            [rowLabel setTextAlignment:NSTextAlignmentLeft];
            [rowLabel setText:@"Number of Rows"];
            [rowLabel setNumberOfLines:0];
            [rowLabel setLineBreakMode:NSLineBreakByCharWrapping];
            [rowLabel setUserInteractionEnabled:YES];
            UITapGestureRecognizer *rowLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [rowLabelTap setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *rowLabelLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [rowLabelLongPress setMinimumPressDuration:1.0];
            [rowLabel addGestureRecognizer:rowLabelTap];
            [rowLabel addGestureRecognizer:rowLabelLongPress];
            [results addSubview:rowLabel];

            UILabel *rowLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(rowLabel.frame.origin.x + rowLabel.frame.size.width, yValue, (results.frame.size.width - 4) * .333, 40)];
            [rowLabel2 setBackgroundColor:[UIColor clearColor]];
            [rowLabel2 setTextColor:[UIColor blackColor]];
            [rowLabel2 setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];
            [rowLabel2 setTextAlignment:NSTextAlignmentLeft];
            [rowLabel2 setText:[NSString stringWithFormat:@"%lu", (unsigned long)[[ado dataSet] count]]];
            [rowLabel2 setUserInteractionEnabled:YES];
            UITapGestureRecognizer *rowLabelTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [rowLabelTap2 setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *rowLabelLongPress2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [rowLabelLongPress2 setMinimumPressDuration:1.0];
            [rowLabel2 addGestureRecognizer:rowLabelTap2];
            [rowLabel2 addGestureRecognizer:rowLabelLongPress2];
            [results addSubview:rowLabel2];
        }
        for (id key in arrayOfColumns)
        {
            yValue += 40.0;
            UILabel *rowLabel = [[UILabel alloc] initWithFrame:CGRectMake(4, yValue, (results.frame.size.width - 4) * 0.667, 40)];
            [rowLabel setBackgroundColor:[UIColor clearColor]];
            [rowLabel setTextColor:[UIColor blackColor]];
            [rowLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:16.0]];
            [rowLabel setTextAlignment:NSTextAlignmentLeft];
            [rowLabel setText:(NSString *)key];
            [rowLabel setNumberOfLines:0];
            [rowLabel setLineBreakMode:NSLineBreakByCharWrapping];
            [rowLabel setUserInteractionEnabled:YES];
            UITapGestureRecognizer *rowLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [rowLabelTap setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *rowLabelLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [rowLabelLongPress setMinimumPressDuration:1.0];
            [rowLabel addGestureRecognizer:rowLabelTap];
            [rowLabel addGestureRecognizer:rowLabelLongPress];
            [results addSubview:rowLabel];

            UILabel *rowLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(rowLabel.frame.origin.x + rowLabel.frame.size.width, yValue, (results.frame.size.width - 4) * .333, 40)];
            [rowLabel2 setBackgroundColor:[UIColor clearColor]];
            [rowLabel2 setTextColor:[UIColor blackColor]];
            [rowLabel2 setFont:[UIFont fontWithName:@"HelveticaNeue" size:16.0]];
            [rowLabel2 setTextAlignment:NSTextAlignmentLeft];
            [rowLabel2 setText:@"Int"];
            if ([(NSNumber *)[[ado dataTypes] objectForKey:[[ado columnNames] objectForKey:key]] intValue] == 1)
                [rowLabel2 setText:@"Float"];
            else if ([(NSNumber *)[[ado dataTypes] objectForKey:[[ado columnNames] objectForKey:key]] intValue] > 1)
                [rowLabel2 setText:@"Char"];
            else if ([[ado columnNames] count] == 0)
                [rowLabel2 setText:@"?"];
            if ([(NSNumber *)[[ado isOneZero] objectForKey:[[ado columnNames] objectForKey:key]] intValue] == 1)
                [rowLabel2 setText:@"1/0"];
            else if ([(NSNumber *)[[ado isYesNo] objectForKey:[[ado columnNames] objectForKey:key]] intValue] == 1)
                [rowLabel2 setText:@"Yes/No"];
            else if ([(NSNumber *)[[ado isTrueFalse] objectForKey:[[ado columnNames] objectForKey:key]] intValue] == 1)
                [rowLabel2 setText:@"True/False"];
            else if ([(NSNumber *)[[ado isBinary] objectForKey:[[ado columnNames] objectForKey:key]] intValue] == 1)
                [rowLabel2 setText:[[rowLabel2 text] stringByAppendingString:@" (Binary)"]];
            [rowLabel2 setUserInteractionEnabled:YES];
            UITapGestureRecognizer *rowLabelTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [rowLabelTap2 setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *rowLabelLongPress2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [rowLabelLongPress2 setMinimumPressDuration:1.0];
            [rowLabel2 addGestureRecognizer:rowLabelTap2];
            [rowLabel2 addGestureRecognizer:rowLabelLongPress2];
            [results addSubview:rowLabel2];
        }
        [self setContentSize:CGSizeMake(self.frame.size.width, results.frame.origin.y + results.frame.size.height + 120)];
    }

    else if ([sqlStatement length] > 6 && [[[sqlStatement substringWithRange:NSMakeRange(0, 7)] lowercaseString] isEqualToString:@"select "])
    {
        NSMutableArray *arrayOfColumns = [[NSMutableArray alloc] init];
        NSMutableArray *arrayOfWidths = [[NSMutableArray alloc] init];
        NSMutableArray *arrayOfRows = [[NSMutableArray alloc] init];
        BOOL querySucceeded = YES;
        float totalWidthOfResults = 0.0;
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
            {
                NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

                if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
                {
                    NSString *selStmt = sqlStatement;
                    const char *query_stmt = [selStmt UTF8String];
                    sqlite3_stmt *statement;
                    if (sqlite3_prepare_v2(epiinfoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                    {
                        [self sqlStatementFieldResign:sender];

                        BOOL firstRow = YES;
                        while (sqlite3_step(statement) == SQLITE_ROW)
                        {
                            NSMutableArray *rowArray = [[NSMutableArray alloc] init];
                            int i = 0;
                            while (sqlite3_column_name(statement, i))
                            {
                                if (firstRow)
                                {
                                    [arrayOfColumns addObject:[[NSString alloc] initWithUTF8String:sqlite3_column_name(statement, i)]];
                                    float cellWidth = [(NSString *)[arrayOfColumns lastObject] sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]}].width + 16.0;
                                    if (cellWidth < 80.0)
                                        cellWidth = 80.0;
                                    [arrayOfWidths addObject:[NSNumber numberWithFloat:cellWidth]];
                                    totalWidthOfResults += [(NSNumber *)[arrayOfWidths lastObject] intValue];
                                }
                                [rowArray addObject:[NSString stringWithUTF8String:[[NSString stringWithFormat:@"%s", sqlite3_column_text(statement, i)] cStringUsingEncoding:NSMacOSRomanStringEncoding]]];
                                i++;
                            }
                            firstRow = NO;
                            [arrayOfRows addObject:rowArray];
                        }
                    }
                    else
                    {
                        querySucceeded = NO;
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UITextView *sqlMessage = [[UITextView alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setEditable:NO];
                        [sqlMessage setText:[NSString stringWithFormat:@"SQL Error: %s", sqlite3_errmsg(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                    sqlite3_finalize(statement);
                }
                sqlite3_close(epiinfoDB);
            }
        }

        if (!querySucceeded)
            return;

        float resultsHeight = (float)[arrayOfRows count] * 40.0 + 40.0;
        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, totalWidthOfResults, resultsHeight)];
        [self addSubview:results];
//        [self sendSubviewToBack:results];

        int cells = 0;
        float xPos = 0.0;
        int index = 0;
        for (id key in arrayOfColumns)
        {
            UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(xPos, 0, [(NSNumber *)[arrayOfWidths objectAtIndex:index] floatValue], 40)];
            [header setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
            [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18.0]];
            [header setTextAlignment:NSTextAlignmentCenter];
            [header setTextColor:[UIColor whiteColor]];
            [header setText:[NSString stringWithFormat:@"%@", (NSString *)key]];
            [header setUserInteractionEnabled:YES];
            UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
            [headerTap setNumberOfTapsRequired:1];
            UILongPressGestureRecognizer *headerLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
            [headerLongPress setMinimumPressDuration:1.0];
            [header addGestureRecognizer:headerTap];
            [header addGestureRecognizer:headerLongPress];
            [results addSubview:header];
            xPos += [(NSNumber *)[arrayOfWidths objectAtIndex:index] floatValue];
            index++;
            cells ++;
        }

        float yValue = 0.0;
        for (id key in arrayOfRows)
        {
            yValue += 40.0;
            float xPosition = 0.0;
            int i = 0;
            for (id cell in (NSArray *)key)
            {
                UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(xPosition, yValue, [(NSNumber *)[arrayOfWidths objectAtIndex:i] floatValue], 40)];
                [header setBackgroundColor:[UIColor clearColor]];
                [header setFont:[UIFont fontWithName:@"HelveticaNeue" size:16.0]];
                [header setTextAlignment:NSTextAlignmentCenter];
                [header setTextColor:[UIColor blackColor]];
                [header setText:[NSString stringWithFormat:@"%@", (NSString *)cell]];
                [header setNumberOfLines:0];
                [header setLineBreakMode:NSLineBreakByCharWrapping];
                [header setUserInteractionEnabled:YES];
                UITapGestureRecognizer *headerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
                [headerTap setNumberOfTapsRequired:1];
                UILongPressGestureRecognizer *headerLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
                [headerLongPress setMinimumPressDuration:1.0];
                [header addGestureRecognizer:headerTap];
                [header addGestureRecognizer:headerLongPress];
                [results addSubview:header];
                xPosition += [(NSNumber *)[arrayOfWidths objectAtIndex:i] floatValue];
                i++;
                cells ++;
            }
            if (cells > 2000)
            {
                [results setFrame:CGRectMake(results.frame.origin.x, results.frame.origin.y, results.frame.size.width, yValue + 40.0 + 60.0)];
                UILabel *footer = [[UILabel alloc] initWithFrame:CGRectMake(0, yValue + 40.0, self.frame.size.width - 4.0, 60.0)];
                [footer setBackgroundColor:[UIColor clearColor]];
                [footer setFont:[UIFont fontWithName:@"HelveticaHeue" size:16.0]];
                [footer setTextColor:[UIColor blackColor]];
                [footer setText:[NSString stringWithFormat:@"Data display limit reached after %d rows.", (int)(yValue / 40.0)]];
                [footer setNumberOfLines:0];
                [footer setLineBreakMode:NSLineBreakByWordWrapping];
                [footer setUserInteractionEnabled:YES];
                UITapGestureRecognizer *footerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
                [footerTap setNumberOfTapsRequired:1];
                [footer addGestureRecognizer:footerTap];
                [results addSubview:footer];
                break;
            }
        }
        [self setContentSize:CGSizeMake(results.frame.origin.x + results.frame.size.width + 32.0, results.frame.origin.y + results.frame.size.height + 80)];
    }

    else if ([sqlStatement length] > 6 && [[[sqlStatement substringWithRange:NSMakeRange(0, 7)] lowercaseString] isEqualToString:@"update "])
    {
        if ([[sqlStatement lowercaseString] containsString:@"guid()"])
            sqlStatement = [NSMutableString stringWithString:[[sqlStatement lowercaseString] stringByReplacingOccurrencesOfString:@"guid()" withString:[NSString stringWithFormat:@"'%@'", CFBridgingRelease(CFUUIDCreateString(NULL, CFUUIDCreate(NULL)))]]];
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
            {
                NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

                if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
                {
                    char *errMsg;
                    NSString *sqlStmt = sqlStatement;
                    const char *sql_stmt = [sqlStmt UTF8String];
                    if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UILabel *sqlMessage = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setText:[NSString stringWithFormat:@"%d row(s) updated.", sqlite3_changes(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                    else
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UITextView *sqlMessage = [[UITextView alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setEditable:NO];
                        [sqlMessage setText:[NSString stringWithFormat:@"SQL Error: %s", sqlite3_errmsg(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                }
                sqlite3_close(epiinfoDB);
            }
        }
    }

    else if ([sqlStatement length] > 6 && [[[sqlStatement substringWithRange:NSMakeRange(0, 7)] lowercaseString] isEqualToString:@"insert "])
    {
        if ([[sqlStatement lowercaseString] containsString:@"guid()"])
            sqlStatement = [NSMutableString stringWithString:[[sqlStatement lowercaseString] stringByReplacingOccurrencesOfString:@"guid()" withString:[NSString stringWithFormat:@"'%@'", CFBridgingRelease(CFUUIDCreateString(NULL, CFUUIDCreate(NULL)))]]];
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
            {
                NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

                if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
                {
                    char *errMsg;
                    NSString *sqlStmt = sqlStatement;
                    const char *sql_stmt = [sqlStmt UTF8String];
                    if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UILabel *sqlMessage = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setText:[NSString stringWithFormat:@"%d row(s) inserted.", sqlite3_changes(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                    else
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UITextView *sqlMessage = [[UITextView alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setEditable:NO];
                        [sqlMessage setText:[NSString stringWithFormat:@"SQL Error: %s", sqlite3_errmsg(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
               }
                sqlite3_close(epiinfoDB);
            }
        }
    }

    else if ([sqlStatement length] > 6 && [[[sqlStatement substringWithRange:NSMakeRange(0, 7)] lowercaseString] isEqualToString:@"delete "])
    {
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
            {
                NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

                if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
                {
                    char *errMsg;
                    NSString *sqlStmt = sqlStatement;
                    const char *sql_stmt = [sqlStmt UTF8String];
                    if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UILabel *sqlMessage = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setText:[NSString stringWithFormat:@"%d row(s) deleted.", sqlite3_changes(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                    else
                    {
                        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
                        [self addSubview:results];
                        UITextView *sqlMessage = [[UITextView alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
                        [sqlMessage setEditable:NO];
                        [sqlMessage setText:[NSString stringWithFormat:@"SQL Error: %s", sqlite3_errmsg(epiinfoDB)]];
                        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
                        [results addSubview:sqlMessage];
                    }
                }
                sqlite3_close(epiinfoDB);
            }
        }
    }

    else if ([sqlStatement length] > 4 && [[[sqlStatement substringWithRange:NSMakeRange(0, 5)] lowercaseString] isEqualToString:@"drop "])
    {
        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 60)];
        [self addSubview:results];
        UILabel *sqlMessage = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 60)];
        [sqlMessage setText:[NSString stringWithFormat:@"DROP not supported. Use \"Table from Device\" to delete tables."]];
        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
        [sqlMessage setUserInteractionEnabled:YES];
        UITapGestureRecognizer *sqlMessageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
        [sqlMessageTap setNumberOfTapsRequired:1];
        [sqlMessage addGestureRecognizer:sqlMessageTap];
        [results addSubview:sqlMessage];
    }

    else if ([sqlStatement length] > 6 && [[[sqlStatement substringWithRange:NSMakeRange(0, 7)] lowercaseString] isEqualToString:@"create "])
    {
        results = [[UIView alloc] initWithFrame:CGRectMake(2, sqlStatementFieldBackground.frame.origin.y + sqlStatementFieldBackground.frame.size.height + 34, self.frame.size.width, 80)];
        [self addSubview:results];
        UILabel *sqlMessage = [[UILabel alloc] initWithFrame:CGRectMake(2, 0, results.frame.size.width - 4.0, 80)];
        [sqlMessage setNumberOfLines:0];
        [sqlMessage setLineBreakMode:NSLineBreakByWordWrapping];
        [sqlMessage setText:[NSString stringWithFormat:@"CREATE not supported. Tables are created in Enter Data or uploaded via .csv files."]];
        [sqlMessage setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0]];
        [sqlMessage setUserInteractionEnabled:YES];
        UITapGestureRecognizer *sqlMessageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sqlStatementFieldResign:)];
        [sqlMessageTap setNumberOfTapsRequired:1];
        [sqlMessage addGestureRecognizer:sqlMessageTap];
        [results addSubview:sqlMessage];
    }
}

- (void)questionMarkPressed:(UIButton *)sender
{
    instructionsView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, initialHeight - 54, self.frame.size.width, initialHeight - 54)];
    [instructionsView setBackgroundColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];
    [self addSubview:instructionsView];

    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(2, 2, instructionsView.frame.size.width - 4, instructionsView.frame.size.height - 4 + 200)];
    [whiteView setBackgroundColor:[UIColor whiteColor]];
    [instructionsView addSubview:whiteView];

    UILabel *header = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, whiteView.frame.size.width, 30.0)];
    [header setBackgroundColor:[UIColor clearColor]];
    [header setText:@"SQL Tool Help"];
    [header setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0]];
    [header setTextAlignment:NSTextAlignmentCenter];
    [header setTextColor:[UIColor blackColor]];
    [whiteView addSubview:header];

    UILabel *instructions = [[UILabel alloc] initWithFrame:CGRectMake(2, 30, whiteView.frame.size.width - 4, whiteView.frame.size.height - 30)];
    [instructions setBackgroundColor:[UIColor clearColor]];
    [instructions setFont:[UIFont fontWithName:@"HelveticaNeue" size:17.0]];
    [instructions setTextColor:[UIColor blackColor]];
    [instructions setTextAlignment:NSTextAlignmentLeft];
    [instructions setNumberOfLines:0];
    [instructions setLineBreakMode:NSLineBreakByWordWrapping];
    NSMutableString *instructionsText = [NSMutableString stringWithString:@"Swipe down on the SQL Tool to return to Analyze Data."];
    if (UIAccessibilityIsVoiceOverRunning())
        instructionsText = [NSMutableString stringWithString:@"To return to Analyze Data, close and re-open."];
    [instructionsText appendString:@"\n\nSubmit TABLES to get a list of Epi Info tables on this device."];
    [instructionsText appendString:@"\n\nSubmit METADATA <table name> (or META <table name>) to see a table's columns, data types, and number of rows."];
    [instructionsText appendString:@"\n\nTouch and hold an output field's or column header's text for one second to copy its value to the clipboard."];
    [instructionsText appendString:@"\n\nUse the guid() function to generate a unique GlobalRecordID. (Note: this function generates a single value per submit so do not use when updating more than one record.)"];
    [instructionsText appendString:@"\n\nSubmit an empty statement to clear the results output."];
    [instructions setText:instructionsText];
    [whiteView addSubview:instructions];
    [instructions sizeToFit];

    UIBarButtonItem *quitHelp = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(dismissInstructionsView:)];
    [quitHelp setAccessibilityLabel:@"Close SQL Tool Help"];
    [quitHelp setTintColor:[UIColor colorWithRed:59/255.0 green:106/255.0 blue:173/255.0 alpha:1.0]];

    UINavigationBar *quitHelpBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(2, 8, header.frame.size.width, 30.0)];
    [quitHelpBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [quitHelpBar setShadowImage:[UIImage new]];
    [quitHelpBar setTranslucent:YES];
    UINavigationItem *quitHelpItem = [[UINavigationItem alloc] initWithTitle:@""];
    [quitHelpItem setRightBarButtonItem:quitHelp];
    [quitHelpBar setItems:[NSArray arrayWithObject:quitHelpItem]];
    [instructionsView addSubview:quitHelpBar];

    UIButton *xButton = [[UIButton alloc] initWithFrame:CGRectMake(instructionsView.frame.size.width - 32.0, 2, 30, 30)];
    [xButton setBackgroundColor:[UIColor clearColor]];
    [xButton setImage:[UIImage imageNamed:@"StAndrewXButton.png"] forState:UIControlStateNormal];
    [xButton setTitle:@"Close the help screen" forState:UIControlStateNormal];
    [xButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    [xButton.layer setMasksToBounds:YES];
    [xButton.layer setCornerRadius:8.0];
    [xButton addTarget:self action:@selector(dismissInstructionsView:) forControlEvents:UIControlEventTouchUpInside];
//    [instructionsView addSubview:xButton];

    [instructionsView setContentSize:CGSizeMake(instructionsView.frame.size.width, instructions.frame.size.height)];

    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        [instructionsView setFrame:CGRectMake(0, 0, instructionsView.frame.size.width, instructionsView.frame.size.height)];
    } completion:^(BOOL finished){
    }];
}

- (void)dismissInstructionsView:(id)sender
{
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        [instructionsView setFrame:CGRectMake(0, initialHeight, instructionsView.frame.size.width, instructionsView.frame.size.height)];
    } completion:^(BOOL finished){
        [instructionsView removeFromSuperview];
    }];
}

-(void)clearButtonPressed:(UIButton *)sender
{
    [sqlStatementField setText:@""];
}

- (void)recallButtonPressed:(UIButton *)sender
{
    if ([recentSubmissions count] > recentSubmissionsIndex && recentSubmissionsIndex > -1)
        [sqlStatementField setText:(NSString *)[recentSubmissions objectAtIndex:recentSubmissionsIndex--]];
}

- (void)downSwipe:(UIButton *)sender
{
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        [self setFrame:CGRectMake(0, initialHeight, self.frame.size.width, self.frame.size.height)];
    } completion:^(BOOL finished){
        [self removeFromSuperview];
    }];
}

- (BOOL)sqlStatementFieldResign:(id)sender
{
    BOOL boo = [sqlStatementField resignFirstResponder];
    return boo;
}

- (void)longPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateRecognized)
    {
        UILabel *sender = (UILabel *)[gestureRecognizer view];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:[sender text]];

        // Replace deprecated UIAlertViews
//        UIAlertView *copyNotice = [[UIAlertView alloc] initWithTitle:@"Copy" message:@"Field text copied to clipboard." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [copyNotice show];
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"Copy" message:@"Field text copied to clipboard." preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        }];
        [alertC addAction:okAction];
        [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:alertC animated:YES completion:nil];
    }
}

- (void)dealloc
{
    NSLog(@"Deallocating!");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([[NSFileManager defaultManager] fileExistsAtPath:[[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase"]])
    {
        NSString *databasePath = [[paths objectAtIndex:0] stringByAppendingString:@"/EpiInfoDatabase/EpiInfo.db"];

        if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
        {
            char *errMsg;
            NSString *sqlStmt = @"drop table __sqlite_recall_table__";
            const char *sql_stmt = [sqlStmt UTF8String];
            if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
            {
                //
            }
            else
            {
                //
            }
        }
        if (sqlite3_open([databasePath UTF8String], &epiinfoDB) == SQLITE_OK)
        {
            char *errMsg;
            NSString *sqlStmt = @"create table __sqlite_recall_table__(sql_statement text)";
            const char *sql_stmt = [sqlStmt UTF8String];
            if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
            {
                for (int i = MAX(0, (int)recentSubmissions.count - 100); i < recentSubmissions.count; i++)
                {
                    NSString *recstmt = [recentSubmissions objectAtIndex:i];
                    sqlStmt = [NSString stringWithFormat:@"insert into __sqlite_recall_table__ values('%@')", [recstmt stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
                    const char *sql_stmt = [sqlStmt UTF8String];
                    if (sqlite3_exec(epiinfoDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
                    {
                        //
                    }
                    else
                    {
                        //
                    }
                }
            }
            else
            {
                //
            }
        }
        sqlite3_close(epiinfoDB);
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Cowtent\RestBundle\Controller;

use Cowtent\AccountBundle\Entity\AbstractUser;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;

abstract class AbstractController extends Controller
{
    /**
     * Get the account from the Security Token Storage.
     *
     * @throws UnsupportedUserException
     * @return mixed
     *
     * @see Controller::getUser()
     */
    public function getAccount()
    {
        $user = $this->getUser();

        if (!$user instanceof AbstractUser || !$user->getAccount()) {
            throw new UnsupportedUserException('Missing account for current user.');
        }

        return $user->getAccount();
    }
}


text:
import * as React from 'react';
import Box from '@material-ui/core/Box';

export default function TextOverflow() {
  return (
    <div style={{ width: 200, whiteSpace: 'nowrap' }}>
      <Box
        component="div"
        sx={{
          textOverflow: 'clip',
          my: 2,
          overflow: 'hidden',
          bgcolor: 'background.paper',
        }}
      >
        Text Overflow Clip. Text Overflow Clip.
      </Box>
      <Box
        component="div"
        sx={{
          textOverflow: 'ellipsis',
          my: 2,
          overflow: 'hidden',
          bgcolor: 'background.paper',
        }}
      >
        Text Overflow Ellipsis. Text Overflow Ellipsis
      </Box>
    </div>
  );
}


text:
{% if not craft.hasPackage('Users') %}
	{% exit 404 %}
{% endif %}

{% extends "_layouts/elementindex" %}
{% set title = "Users"|t %}
{% set elementType = 'User' %}

{% set docsUrl = 'http://buildwithcraft.com/docs/users' %}

{% block sidebar %}
	{% if currentUser.can('registerUsers') %}

			{{ "New User"|t }}

	{% endif %}

	{{ parent() }}
{% endblock %}


text:
package org.springframework.cloud.dataflow.server.rest.documentation;

import org.junit.Test;

import org.springframework.http.MediaType;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Gunnar Hillert
 */
public class MetricsForStreamAppsWithoutCollectorDocumentation extends BaseDocumentation {

	@Test
	public void getMetricsWithoutCollectorRunning() throws Exception {
		this.mockMvc.perform(get("/metrics/streams")
			.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk());
	}

}


text:
<?php

class cstore {
	static
		$cookie_name,
		$cookie_ttl,
		$cookie_secret;

	public static function setup($params) {
		self::$cookie_name = $params['cookie_name'];
		self::$cookie_ttl = $params['cookie_ttl'];
		self::$cookie_secret = $params['cookie_secret'];
	}

	public static function put($data) {
		$data = self::encode_decode(true, $data);
		setcookie(self::$cookie_name, $data, time() + self::$cookie_ttl, '/', config::$cookie_domain);
	}

	public static function get() {
		if (!empty($_COOKIE[ self::$cookie_name ])) {
			return self::encode_decode(false, $_COOKIE[ self::$cookie_name ]);
		}
		return array();
	}

	public static function delete() {
		setcookie(self::$cookie_name, '', time() - self::$cookie_ttl, '/', config::$cookie_domain);
	}

	private static function encode_decode($do_encode, $data) {
		if (config::$instance_type == 'dev') {
			return self::_encode_decode_plain($do_encode, $data);
		}
		else {
			return self::_encode_decode_crypt($do_encode, $data);
		}
	}

	private static function _encode_decode_plain($do_encode, $data) {
		if ($do_encode) {
			$default = '';
			$output = @json_encode($data);
		}
		else {
			$default = array();
			$output = @json_decode($data, true);
		}

		return $output ? $output : $default;
	}

	private static function _encode_decode_crypt($do_encode, $data) {
		$td = mcrypt_module_open('rijndael-128', '', 'ecb', '');
		$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);

		$key = substr(self::$cookie_secret, 0, mcrypt_enc_get_key_size($td));

		mcrypt_generic_init($td, $key, $iv);

		if ($do_encode) {
			$default = '';
			$output = @base64_encode(mcrypt_generic($td, json_encode($data)));
		}
		else {
			$default = array();
			$output = @json_decode(mdecrypt_generic($td, base64_decode($data)), true);
		}

		mcrypt_generic_deinit($td);
		mcrypt_module_close($td);

		return $output ? $output : $default;
	}
}


text:
package org.apache.geode.internal.cache;

import static org.junit.Assert.*;

import java.io.*;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.*;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.cache30.CacheTestCase;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.SerializableCallable;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;

/**
 * Tests a toData that always throws an IOException. This test does a put with the bad to data from
 * an accessor to see if it will keep trying to resend the put to the data store
 *
 *
 */
@Category(DistributedTest.class)
public class PRBadToDataDUnitTest extends JUnit4CacheTestCase {

  @Test
  public void testBadToData() {
    final Host host = Host.getHost(0);
    final VM vm1 = host.getVM(0);
    final VM vm2 = host.getVM(1);
    final String name = "PR_TEMP";

    final SerializableRunnable create = new CacheSerializableRunnable("Create PR accessor ") {
      public void run2() {
        final AttributesFactory factory = new AttributesFactory();
        factory.setPartitionAttributes(
            new PartitionAttributesFactory().setRedundantCopies(0).setLocalMaxMemory(0).create());
        final PartitionedRegion pr = (PartitionedRegion) createRootRegion(name, factory.create());
        assertNotNull(pr);
      }
    };
    vm1.invoke(create);

    final SerializableRunnable create2 = new SerializableRunnable("Create PR dataStore ") {
      public void run() {
        try {
          final AttributesFactory factory = new AttributesFactory();
          factory.setPartitionAttributes(new PartitionAttributesFactory().setRedundantCopies(0)
              .setLocalMaxMemory(100).create());
          final PartitionedRegion pr = (PartitionedRegion) createRootRegion(name, factory.create());
          assertNotNull(pr);
        } catch (final CacheException ex) {
          Assert.fail("While creating Partitioned region", ex);
        }
      }
    };
    vm2.invoke(create2);

    final SerializableRunnable putData = new SerializableRunnable("Puts Data") {
      public void run() {
        final PartitionedRegion pr = (PartitionedRegion) getRootRegion(name);
        assertNotNull(pr);
        try {
          pr.put("key", new DataSerializable() {
            public void toData(DataOutput out) throws IOException {
              throw new IOException("bad to data");
              // throw new ToDataException("bad to data");
            }

            public void fromData(DataInput in) throws IOException, ClassNotFoundException {
              // nothing needed
            }
          });
          fail("expected ToDataException");
        } catch (ToDataException expected) {
          // we want this put to fail with an exception instead of hanging due to retries
        }
      }
    };
    vm1.invoke(putData);
  }
}


text:
<?php

class NetGearWpTermTaxonomy
{
    private $term_taxonomy_id;
    private $term_id;
    private $taxonomy;
    private $description;
    private $parent;
    private $count;

    /**
     * @return mixed
     */
    public function getTermTaxonomyId()
    {
        return $this->term_taxonomy_id;
    }

    /**
     * @param mixed $term_taxonomy_id
     * @return NetGearWpTermTaxonomy
     */
    public function setTermTaxonomyId($term_taxonomy_id)
    {
        $this->term_taxonomy_id = $term_taxonomy_id;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getTermId()
    {
        return $this->term_id;
    }

    /**
     * @param mixed $term_id
     * @return NetGearWpTermTaxonomy
     */
    public function setTermId($term_id)
    {
        $this->term_id = $term_id;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getTaxonomy()
    {
        return $this->taxonomy;
    }

    /**
     * @param mixed $taxonomy
     * @return NetGearWpTermTaxonomy
     */
    public function setTaxonomy($taxonomy)
    {
        $this->taxonomy = $taxonomy;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param mixed $description
     * @return NetGearWpTermTaxonomy
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * @param mixed $parent
     * @return NetGearWpTermTaxonomy
     */
    public function setParent($parent)
    {
        $this->parent = $parent;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCount()
    {
        return $this->count;
    }

    /**
     * @param mixed $count
     * @return NetGearWpTermTaxonomy
     */
    public function setCount($count)
    {
        $this->count = $count;
        return $this;
    }

}


text:
/**
 * Created by huy on 6/28/2016.
 */
/// <reference path="services.js" />
'use strict';

angular.module('Client')
    .factory("ClientService", ['$q', 'CSService', function ($q, CSService) {
        var service = {};
        var currentClientId;

        service.saveAlias = function (alias) {
            if(currentClientId) {
                return CSService.saveAlias(currentClientId, alias);
            }
        }

        service.ignoreClient = function () {
            if(currentClientId) {
                return CSService.ignoreClient(currentClientId);
            }
        }

        service.getClientDetail = function (clientId) {
            if (clientId) {
                currentClientId = clientId;
                return CSService.getClientDetail(clientId).then(function (clientDetail) {
                    return clientDetail;
                });
            } else {
                return null;
            }
        };

        service.getAllConfigs = function (){
        	return CSService.getAllConfigs().then(function (json){
        		return json;
        	});
        }

        service.updateClient = function (client){

        	return CSService.updateClient(client);
        }

        return service;
    }]);


text:
<#
.SYNOPSIS
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    Example of how to use this cmdlet
.EXAMPLE
    Another example of how to use this cmdlet
.INPUTS
    Inputs to this cmdlet (if any)
.OUTPUTS
    Output from this cmdlet (if any)
.NOTES
    General notes
.COMPONENT
    The component this cmdlet belongs to
.ROLE
    The role this cmdlet belongs to
.FUNCTIONALITY
    The functionality that best describes this cmdlet
#>
function ConvertTo-TraktShow {
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param (
        # Param1 help description
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNull()]
        $InputObject
    )

    begin {
        $textInfo = (Get-Culture).TextInfo
    }

    process {
        $properties = @{
            Title = $InputObject.title
            Year = $InputObject.year
            IDs = $InputObject.ids
            overview = $InputObject.overview
            FirstAired = $null
            Airs = ''
            Runtime = $InputObject.runtime
            Certification = $InputObject.certification
            Network = $InputObject.network
            Country = $InputObject.country
            Trailer = $InputObject.trailer
            Homepage = $InputObject.homepage
            Status = $textInfo.ToTitleCase($InputObject.status)
            Rating = $InputObject.rating
            Votes = $InputObject.votes
            UpdatedAt = $null
            Language = $InputObject.language
            AvailableTranslations = $InputObject.available_translations
            Genres = $InputObject.genres
            AiredEpisodes = $InputObject.aired_episodes
        }

        if (-not [string]::IsNullOrEmpty($InputObject.first_aired)) {
            $properties.FirstAired  = $InputObject.first_aired | ConvertTo-LocalTime
        }

        if ($InputObject.status -ne 'ended') {
            if ([string]::IsNullOrEmpty($InputObject.airs.day) -eq $false -and [string]::IsNullOrEmpty($InputObject.airs.time) -eq $false -and [string]::IsNullOrEmpty($InputObject.airs.timezone) -eq $false) {
                $properties.Airs = '{0} at {1} {2} time' -f $InputObject.airs.day, $InputObject.airs.time, $InputObject.airs.timezone
            }
        }

        if (-not [string]::IsNullOrEmpty($InputObject.updated_at)) {
            $properties.UpdatedAt  = $InputObject.updated_at | ConvertTo-LocalTime
        }

        $psco = [PSCustomObject]$properties
        $psco.PSObject.TypeNames.Insert(0, 'Trakt.Show')
        $psco
    }
}


text:
#region Copyright (c) 2006-2007, Luke T. Maxon (Authored by Anders Lillrank)

#endregion

using System;
using System.Windows.Forms;

namespace Xunit.Extensions.Forms.TestApplications
{
  public partial class UnderscoreNameForm : Form
  {
    public UnderscoreNameForm()
    {
      InitializeComponent();
    }
  }
}


text:
filter_files = $(wildcard *.py)

dist_files = Makefile $(filter_files)

all: default-all

install:
	mkdir -p $(DESTDIR)/etc/conary/components/base/; \
	for f in $(filter_files); do \
		$(CP) -a $$f $(DESTDIR)/etc/conary/components/base/$$f; \
	done

dist: default-dist

clean: default-clean

include ../../../Make.rules


text:
package com.github.baoti.git.accounts;

import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

/**
 * Copy from android.accounts.AccountAuthenticatorActivity, change to extending FragmentActivity.
 *
 * Base class for implementing an Activity that is used to help implement an
 * AbstractAccountAuthenticator. If the AbstractAccountAuthenticator needs to use an activity
 * to handle the request then it can have the activity extend AccountAuthenticatorActivity.
 * The AbstractAccountAuthenticator passes in the response to the intent using the following:
 * <pre>
 *      intent.putExtra({@link AccountManager#KEY_ACCOUNT_AUTHENTICATOR_RESPONSE}, response);
 * </pre>
 * The activity then sets the result that is to be handed to the response via
 * {@link #setAccountAuthenticatorResult(android.os.Bundle)}.
 * This result will be sent as the result of the request when the activity finishes. If this
 * is never set or if it is set to null then error {@link AccountManager#ERROR_CODE_CANCELED}
 * will be called on the response.
 */
public class AccountAuthenticatorActivity extends FragmentActivity {

    public static final String EXTRA_ACCOUNT_TYPE = AccountManager.KEY_ACCOUNT_TYPE;
    public static final String EXTRA_AUTH_TOKEN_TYPE = "app:authTokenType";
    public static final String EXTRA_ACCOUNT_NAME = AccountManager.KEY_ACCOUNT_NAME;

    private static final String EXTRA_FRAGMENT_CLASS = "app:contentFragment";

    public static Intent buildIntent(Context context,
                                     AccountAuthenticatorResponse response,
                                     String accountType,
                                     String authTokenType) {
        return new Intent(context, AccountAuthenticatorActivity.class)
                .putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)
                .putExtra(EXTRA_ACCOUNT_TYPE, accountType)
                .putExtra(EXTRA_AUTH_TOKEN_TYPE, authTokenType);
    }

    public static Intent putAccountName(Intent intent, String accountName) {
        return intent.putExtra(EXTRA_ACCOUNT_NAME, accountName);
    }

    public static Intent putAuthenticateFragment(Intent intent,
                                      Class<? extends Fragment> fragmentClass) {
        return intent.putExtra(EXTRA_FRAGMENT_CLASS, fragmentClass.getCanonicalName());
    }

    private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
    private Bundle mResultBundle = null;

    /**
     * Set the result that is to be sent as the result of the request that caused this
     * Activity to be launched. If result is null or this method is never called then
     * the request will be canceled.
     * @param result this is returned as the result of the AbstractAccountAuthenticator request
     */
    public final void setAccountAuthenticatorResult(Bundle result) {
        mResultBundle = result;
    }

    /**
     * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
     * icicle is non-zero.
     * @param icicle the save instance data of this Activity, may be null
     */
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        mAccountAuthenticatorResponse =
                getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);

        if (mAccountAuthenticatorResponse != null) {
            mAccountAuthenticatorResponse.onRequestContinued();
        }

        if (icicle == null) {
            String fragmentClass = getIntent().getStringExtra(EXTRA_FRAGMENT_CLASS);
            getSupportFragmentManager().beginTransaction()
                    .setTransition(FragmentTransaction.TRANSIT_NONE)
                    .add(android.R.id.content, Fragment.instantiate(this, fragmentClass))
                    .commit();
        }
    }

    /**
     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
     */
    public void finish() {
        if (mAccountAuthenticatorResponse != null) {
            // send the result bundle back if set, otherwise send an error.
            if (mResultBundle != null) {
                mAccountAuthenticatorResponse.onResult(mResultBundle);
            } else {
                mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
                        "canceled");
            }
            mAccountAuthenticatorResponse = null;
        }
        super.finish();
    }
}


text:
<?php

namespace Webmozart\Console\Adapter;

use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Webmozart\Console\Api\IO\IO;

/**
 * Adapts an {@link IO} instance to Symfony's {@link OutputInterface} API.
 *
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class IOOutput implements OutputInterface
{
    /**
     * @var IO
     */
    private $io;

    /**
     * Creates a new composite output.
     *
     * @param IO $io The I/O.
     */
    public function __construct(IO $io)
    {
        $this->io = $io;
    }

    /**
     * Returns the standard output.
     *
     * @return IO The standard output.
     */
    public function getIO()
    {
        return $this->io;
    }

    /**
     * {@inheritdoc}
     */
    public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
    {
        foreach ((array) $messages as $message) {
            if ($newline) {
                $this->doWriteLine($message, $type);
            } else {
                $this->doWrite($message, $type);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function writeln($messages, $type = self::OUTPUT_NORMAL)
    {
        foreach ((array) $messages as $message) {
            $this->doWriteLine($message, $type);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setVerbosity($level)
    {
        switch ($level) {
            case self::VERBOSITY_QUIET:
                $this->io->setQuiet(true);
                break;
            case self::VERBOSITY_NORMAL:
                $this->io->setQuiet(false);
                $this->io->setVerbosity(IO::NORMAL);
                break;
            case self::VERBOSITY_VERBOSE:
                $this->io->setQuiet(false);
                $this->io->setVerbosity(IO::VERBOSE);
                break;
            case self::VERBOSITY_VERY_VERBOSE:
                $this->io->setQuiet(false);
                $this->io->setVerbosity(IO::VERY_VERBOSE);
                break;
            case self::VERBOSITY_DEBUG:
                $this->io->setQuiet(false);
                $this->io->setVerbosity(IO::DEBUG);
                break;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getVerbosity()
    {
        if ($this->io->isQuiet()) {
            return self::VERBOSITY_QUIET;
        }

        if ($this->io->isDebug()) {
            return self::VERBOSITY_DEBUG;
        }

        if ($this->io->isVeryVerbose()) {
            return self::VERBOSITY_VERY_VERBOSE;
        }

        if ($this->io->isVerbose()) {
            return self::VERBOSITY_VERBOSE;
        }

        return self::VERBOSITY_NORMAL;
    }

    /**
     * {@inheritdoc}
     */
    public function setDecorated($decorated)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function isDecorated()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function setFormatter(OutputFormatterInterface $formatter)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getFormatter()
    {
        return new FormatterAdapter($this->io);
    }

    private function doWriteLine($message, $type)
    {
        switch ($type) {
            case self::OUTPUT_PLAIN:
                $this->io->writeLine($this->io->removeFormat($message));
                break;
            case self::OUTPUT_RAW:
                $this->io->writeLineRaw($message);
                break;
            default:
                $this->io->writeLine($message);
                break;
        }
    }

    private function doWrite($message, $type)
    {
        switch ($type) {
            case self::OUTPUT_PLAIN:
                $this->io->write($this->io->removeFormat($message));
                break;
            case self::OUTPUT_RAW:
                $this->io->writeRaw($message);
                break;
            default:
                $this->io->write($message);
                break;
        }
    }
}


text:
import logging
import six
import cobra

from cobradb.base import Session, OldIDSynonym, Synonym, Reaction, Component
from cobradb.models import (Model, ModelGene, ModelReaction, ModelCompartmentalizedComponent,
                            Compartment, CompartmentalizedComponent, ReactionMatrix)
from cobradb.components import Gene, Metabolite
from cobradb.util import increment_id, make_reaction_copy_id, timing

from collections import defaultdict

@timing
def dump_model(cobra_id):
    session = Session()

    # find the model
    model_db = (session
                .query(Model)
                .filter(Model.cobra_id == cobra_id)
                .first())

    if model_db is None:
        session.commit()
        session.close()
        raise Exception('Could not find model %s' % cobra_id)

    model = cobra.core.Model(cobra_id)

    # genes
    logging.debug('Dumping genes')
    # get genes and original bigg ids (might be multiple)
    genes_db = (session
                .query(Gene.cobra_id, Gene.name, Synonym.synonym)
                .join(ModelGene, ModelGene.gene_id == Gene.id)
                .join(OldIDSynonym, OldIDSynonym.ome_id == ModelGene.id)
                .join(Synonym, Synonym.id == OldIDSynonym.synonym_id)
                .filter(ModelGene.model_id == model_db.id))
    gene_names = []
    old_gene_ids_dict = defaultdict(list)
    for gene_id, gene_name, old_id in genes_db:
        if gene_id not in old_gene_ids_dict:
            gene_names.append((gene_id, gene_name))
        old_gene_ids_dict[gene_id].append(old_id)

    for gene_id, gene_name in gene_names:
        gene = cobra.core.Gene(gene_id)
        gene.name = gene_name
        gene.notes = {'original_cobra_ids': old_gene_ids_dict[gene_id]}
        model.genes.append(gene)

    # reactions
    logging.debug('Dumping reactions')
    # get original bigg ids (might be multiple)
    reactions_db = (session
                    .query(ModelReaction, Reaction, Synonym.synonym)
                    .join(Reaction)
                    .join(OldIDSynonym, OldIDSynonym.ome_id == ModelReaction.id)
                    .join(Synonym, Synonym.id == OldIDSynonym.synonym_id)
                    .filter(ModelReaction.model_id == model_db.id))
    reactions_model_reactions = []
    found_model_reactions = set()
    old_reaction_ids_dict = defaultdict(list)
    for model_reaction, reaction, old_id in reactions_db:
        # there may be multiple model reactions for a given cobra_id
        if model_reaction.id not in found_model_reactions:
            reactions_model_reactions.append((model_reaction, reaction))
            found_model_reactions.add(model_reaction.id)
        old_reaction_ids_dict[reaction.cobra_id].append(old_id)

    # make dictionaries and cast results
    result_dicts = []
    for mr_db, r_db in reactions_model_reactions:
        d = {}
        d['cobra_id'] = r_db.cobra_id
        d['name'] = r_db.name
        d['gene_reaction_rule'] = mr_db.gene_reaction_rule
        d['lower_bound'] = float(mr_db.lower_bound)
        d['upper_bound'] = float(mr_db.upper_bound)
        d['objective_coefficient'] = float(mr_db.objective_coefficient)
        d['original_cobra_ids'] = old_reaction_ids_dict[r_db.cobra_id]
        d['subsystem'] = mr_db.subsystem
        d['copy_number'] = int(mr_db.copy_number)
        result_dicts.append(d)

    def filter_duplicates(result_dicts):
        """Find the reactions with multiple ModelReactions and increment names."""
        tups_by_cobra_id = defaultdict(list)
        # for each ModelReaction
        for d in result_dicts:
            # add to duplicates
            tups_by_cobra_id[d['cobra_id']].append(d)
        # duplicates have multiple ModelReactions
        duplicates = {k: v for k, v in six.iteritems(tups_by_cobra_id) if len(v) > 1}
        for cobra_id, dup_dicts in six.iteritems(duplicates):
            # add _copy1, copy2, etc. to the bigg ids for the duplicates
            for d in dup_dicts:
                d['cobra_id'] = make_reaction_copy_id(cobra_id, d['copy_number'])

        return result_dicts

    # fix duplicates
    result_filtered = filter_duplicates(result_dicts)

    reactions = []
    for result_dict in result_filtered:
        r = cobra.core.Reaction(result_dict['cobra_id'])
        r.name = result_dict['name']
        r.gene_reaction_rule = result_dict['gene_reaction_rule']
        r.lower_bound = result_dict['lower_bound']
        r.upper_bound = result_dict['upper_bound']
        r.objective_coefficient = result_dict['objective_coefficient']
        r.notes = {'original_cobra_ids': result_dict['original_cobra_ids']}
        r.subsystem = result_dict['subsystem']
        reactions.append(r)
    model.add_reactions(reactions)

    # metabolites
    logging.debug('Dumping metabolites')
    # get original bigg ids (might be multiple)
    metabolites_db = (session
                      .query(Metabolite.cobra_id,
                             Metabolite.name,
                             ModelCompartmentalizedComponent.formula,
                             ModelCompartmentalizedComponent.charge,
                             Compartment.cobra_id,
                             Synonym.synonym)
                      .join(CompartmentalizedComponent)
                      .join(Compartment)
                      .join(ModelCompartmentalizedComponent)
                      .join(OldIDSynonym, OldIDSynonym.ome_id == ModelCompartmentalizedComponent.id)
                      .join(Synonym)
                      .filter(ModelCompartmentalizedComponent.model_id == model_db.id))
    metabolite_names = []
    old_metabolite_ids_dict = defaultdict(list)
    for metabolite_id, metabolite_name, formula, charge, compartment_id, old_id in metabolites_db:
        if metabolite_id + '_' + compartment_id not in old_metabolite_ids_dict:
            metabolite_names.append((metabolite_id, metabolite_name, formula, charge, compartment_id))
        old_metabolite_ids_dict[metabolite_id + '_' + compartment_id].append(old_id)

    metabolites = []
    compartments = set()
    for component_id, component_name, formula, charge, compartment_id in metabolite_names:
        if component_id is not None and compartment_id is not None:
            m = cobra.core.Metabolite(id=component_id + '_' + compartment_id,
                                      compartment=compartment_id,
                                      formula=formula)
            m.charge = charge
            m.name = component_name
            m.notes = {'original_cobra_ids': old_metabolite_ids_dict[component_id + '_' + compartment_id]}
            compartments.add(compartment_id)
            metabolites.append(m)
    model.add_metabolites(metabolites)

    # compartments
    compartment_db = (session.query(Compartment)
                      .filter(Compartment.cobra_id.in_(compartments)))
    model.compartments = {i.cobra_id: i.name for i in compartment_db}

    # reaction matrix
    logging.debug('Dumping reaction matrix')
    matrix_db = (session
                 .query(ReactionMatrix.stoichiometry, Reaction.cobra_id,
                        Component.cobra_id, Compartment.cobra_id)
                 # component, compartment
                 .join(CompartmentalizedComponent)
                 .join(Component)
                 .join(Compartment)
                 # reaction
                 .join(Reaction)
                 .join(ModelReaction)
                 .filter(ModelReaction.model_id == model_db.id)
                 .distinct())  # make sure we don't duplicate

    # load metabolites
    for stoich, reaction_id, component_id, compartment_id in matrix_db:
        try:
            m = model.metabolites.get_by_id(component_id + '_' + compartment_id)
        except KeyError:
            logging.warning('Metabolite not found %s in compartment %s for reaction %s' % \
                            (component_id, compartment_id, reaction_id))
            continue
        # add to reactions
        if reaction_id in model.reactions:
            # check again that we don't duplicate
            r = model.reactions.get_by_id(reaction_id)
            if m not in r.metabolites:
                r.add_metabolites({m: float(stoich)})
        else:
            # try incremented ids
            while True:
                reaction_id = increment_id(reaction_id, 'copy')
                try:
                    # check again that we don't duplicate
                    r = model.reactions.get_by_id(reaction_id)
                    if m not in r.metabolites:
                        r.add_metabolites({m: float(stoich)})
                except KeyError:
                    break

    session.commit()
    session.close()

    cobra.manipulation.annotate.add_SBO(model)

    return model


text:
function sendMessage(){

}
//http://thenewboston.org/watch.php?cat=32&number=96 latest stopping point,
//having to find new videos to follow


text:
package org.onosproject.vtnrsc;

/**
 * Abstraction of an entity providing Port Pair information.
 * A port pair represents a service function instance.
 */
public interface PortPair {

    /**
     * Returns the ID of this port Pair.
     *
     * @return the port pair id
     */
    PortPairId portPairId();

    /**
     * Returns the tenant id of this port pair.
     *
     * @return an tenant id
     */
    TenantId tenantId();

    /**
     * Returns the description of this port pair.
     *
     * @return description of port pair
     */
    String name();

    /**
     * Returns the description of this port pair.
     *
     * @return description of port pair
     */
    String description();

    /**
     * Returns the ingress port of this port pair.
     *
     * @return ingress of port pair
     */
    String ingress();

    /**
     * Returns the egress port of this port pair.
     *
     * @return egress of port pair
     */
    String egress();

    /**
     * Returns whether this port pair is an exact match to the port pair given
     * in the argument.
     * <p>
     * Exact match means the Port port pairs match with the given port pair.
     * It does not consider the port pair id, name and description.
     * </p>
     * @param portPair other port pair to match against
     * @return true if the port pairs are an exact match, otherwise false
     */
    boolean exactMatch(PortPair portPair);

    /**
     * A port pair builder..
     */
    interface Builder {

        /**
         * Assigns the port pair id to this object.
         *
         * @param portPairId the port pair id
         * @return this the builder object
         */
        Builder setId(PortPairId portPairId);

        /**
         * Assigns tenant id to this object.
         *
         * @param tenantId tenant id of the port pair
         * @return this the builder object
         */
        Builder setTenantId(TenantId tenantId);

        /**
         * Assigns the name to this object.
         *
         * @param name name of the port pair
         * @return this the builder object
         */
        Builder setName(String name);

        /**
         * Assigns the description to this object.
         *
         * @param description description of the port pair
         * @return this the builder object
         */
        Builder setDescription(String description);

        /**
         * Assigns the ingress port to this object.
         *
         * @param port ingress port of the port pair
         * @return this the builder object
         */
        Builder setIngress(String port);

        /**
         * Assigns the egress port to this object.
         *
         * @param port egress port of the port pair
         * @return this the builder object
         */
        Builder setEgress(String port);

        /**
         * Builds a port pair object.
         *
         * @return a port pair.
         */
        PortPair build();
    }
}


text:
using System.Collections.Generic;
using System.Xml.Serialization;
using MonoGame.Extended.Tiled;

namespace MonoGame.Extended.Content.Pipeline.Tiled
{
    [XmlInclude(typeof(TiledMapTileLayerContent))]
    [XmlInclude(typeof(TiledMapImageLayerContent))]
    [XmlInclude(typeof(TiledMapObjectLayerContent))]
    public abstract class TiledMapLayerContent
    {
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }

        [XmlAttribute(AttributeName = "opacity")]
        public float Opacity { get; set; }

        [XmlAttribute(AttributeName = "visible")]
        public bool Visible { get; set; }

        [XmlAttribute(AttributeName = "offsetx")]
        public float OffsetX { get; set; }

        [XmlAttribute(AttributeName = "offsety")]
        public float OffsetY { get; set; }

        [XmlArray("properties")]
        [XmlArrayItem("property")]
        public List<TiledMapPropertyContent> Properties { get; set; }

        [XmlIgnore]
        public TiledMapLayerType Type { get; }

        [XmlIgnore]
        public TiledMapLayerModelContent[] Models { get; set; }

        protected TiledMapLayerContent(TiledMapLayerType type)
        {
            Type = type;
            Opacity = 1.0f;
            Visible = true;
            Properties = new List<TiledMapPropertyContent>();
        }

        public override string ToString()
        {
            return Name;
        }
    }
}


text:
package uk.ac.cam.gpe21.droidssl.mitm.socket.factory;

import uk.ac.cam.gpe21.droidssl.mitm.socket.SocketUtils;

import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public final class TproxySocketFactory extends SocketFactory {
	public TproxySocketFactory(SSLSocketFactory sslSocketFactory) {
		super(sslSocketFactory);
	}

	@Override
	public ServerSocket openServerSocket(InetSocketAddress address) throws IOException {
		ServerSocket socket = SocketUtils.openTproxyServerSocket();
		socket.bind(address);
		return socket;
	}

	@Override
	public Socket openSocket(InetSocketAddress source, InetSocketAddress destination) throws IOException {
		Socket socket = SocketUtils.openTproxySocket();

		/*
		 * We open two connections in quick succession (the first is to detect
		 * the use of SSL, the second is the actual connection that will be
		 * used for the rest of the MITM.) Therefore we need to enable
		 * SO_REUSEADDR to stop bind() from failing with the same source
		 * address in TPROXY mode.
		 */
		socket.setReuseAddress(true);

		socket.bind(source);
		socket.connect(destination);
		return socket;
	}
}


text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

namespace Google\Cloud\Tests\Trace\V1;

use Google\Devtools\Cloudtrace\V1\TraceServiceGrpcClient;
use Google\GAX\Testing\MockStubTrait;
use Google\Protobuf\Any;

class MockTraceServiceImpl extends TraceServiceGrpcClient
{
    use MockStubTrait;
}


text:
@interface LMYClassificationViewController ()

@end

@implementation LMYClassificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.view.backgroundColor = LMYColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256));

    [self setupNavigationBar];

}

- (void)setupNavigationBar
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackgroundWhite"] forBarMetrics:0];

    self.navigationItem.title = @"分类搜索";
}

@end


text:
cask 'bettertouchtool' do
  if MacOS.version <= :mavericks
    version '2.05'
    sha256 '41013cfeffee286a038363651db3dd315ff3a1e0cf07774d9ce852111be50a5a'

    # bettertouchtool.net/releases was verified as official when first introduced to the cask
    url "https://bettertouchtool.net/releases/btt#{version}_final_10_9.zip"
  else
    version '3.167'
    sha256 '575c3ec1ceb39905664e1cee88532db79b6784843cd27bff5e73f0239c50904d'

    # bettertouchtool.net/releases was verified as official when first introduced to the cask
    url "https://bettertouchtool.net/releases/btt#{version}.zip"
    appcast 'https://bettertouchtool.net/releases/'
  end

  name 'BetterTouchTool'
  homepage 'https://folivora.ai/'

  auto_updates true

  app 'BetterTouchTool.app'

  uninstall login_item: 'BetterTouchTool'

  zap trash: [
               '~/Library/Preferences/com.hegenberg.BetterTouchTool.plist',
               '~/Library/Application Support/BetterTouchTool',
             ]
end


text:
package gopher

import scala.util.Try

trait OChannel[F[_]:CpsAsyncMonad, A]:

   def awrite(a:A):F[Unit] =
     summon[CpsAsyncMonad[F]].adoptCallbackStyle(f =>
         addWriter(a, f)
     )

   inline def write(a:A): Unit = await(awrite(a))

   def addWriter(a:A, f: Try[Unit]=>Unit): Unit


text:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def get_app_index():
    return 'Hello, World!'

from blueprints import api_blueprint
app.register_blueprint(api_blueprint)

if __name__ == '__main__':
    app.config['DEBUG'] = True
    app.run(port=5002)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="array_marker_icons">
        <item>@drawable/ic_arch_of_galerius_and_rotunda</item>
        <item>@drawable/ic_navarinou_square</item>
        <item>@drawable/ic_roman_forum</item>
        <item>@drawable/ic_hagia_sophia_square</item>
        <item>@drawable/ic_byzantine_bath</item>
        <item>@drawable/ic_church_of_the_acheiropoietos</item>
        <item>@drawable/ic_church_of_the_holy_apostles</item>
        <item>@drawable/ic_church_of_hosios_david</item>
        <item>@drawable/ic_church_of_panagia_chalkeon</item>
        <item>@drawable/ic_church_of_saint_catherine</item>
        <item>@drawable/ic_church_of_saint_nicholas_orphanos</item>
        <item>@drawable/ic_church_of_saint_panteleimon</item>
        <item>@drawable/ic_church_of_prophet_elijah</item>
        <item>@drawable/ic_hagios_demetrios</item>
        <item>@drawable/ic_hagia_sophia</item>
        <item>@drawable/ic_walls_of_thessaloniki</item>
        <item>@drawable/ic_alaca_imaret_mosque</item>
        <item>@drawable/ic_upper_town</item>
        <item>@drawable/ic_bey_hamam</item>
        <item>@drawable/ic_karipeion_melathron</item>
        <item>@drawable/ic_government_house</item>
        <item>@drawable/ic_new_mosque</item>
        <item>@drawable/ic_white_tower</item>
        <item>@drawable/ic_alexandreio_melathron</item>
        <item>@drawable/ic_aristotelous_square</item>
        <item>@drawable/ic_ladadika</item>
        <item>@drawable/ic_modiano_market</item>
        <item>@drawable/ic_nationaltheatre_of_northern_greece</item>
        <item>@drawable/ic_ote_tower</item>
        <item>@drawable/ic_port_of_thessaloniki</item>
        <item>@drawable/ic_thessaloniki_concert_hall</item>
        <item>@drawable/ic_great_alexander_statue</item>
        <item>@drawable/ic_mouseio_makedonikou_agona</item>
        <item>@drawable/ic_jewish_museum</item>
        <item>@drawable/ic_archaeological_museum</item>
        <item>@drawable/ic_byzantine_museum</item>
    </string-array>

    <string-array name="array_marker_icons_small">
        <item>@drawable/ic_arch_of_galerius_and_rotunda_small</item>
        <item>@drawable/ic_navarinou_square_small</item>
        <item>@drawable/ic_roman_forum_small</item>
        <item>@drawable/ic_hagia_sophia_square_small</item>
        <item>@drawable/ic_byzandine_baths_small</item>
        <item>@drawable/ic_church_of_the_acheiropoietos_small</item>
        <item>@drawable/ic_church_of_the_holy_apostles_small</item>
        <item>@drawable/ic_church_of_hosios_david_small</item>
        <item>@drawable/ic_church_of_panagia_chalkeon_small</item>
        <item>@drawable/ic_church_of_saint_catherine_small</item>
        <item>@drawable/ic_church_of_saint_nicholas_orphanos_small</item>
        <item>@drawable/ic_church_of_saint_panteleimon_small</item>
        <item>@drawable/ic_church_of_prophet_elijah_small</item>
        <item>@drawable/ic_hagios_demetrios_small</item>
        <item>@drawable/ic_hagia_sophia_small</item>
        <item>@drawable/ic_walls_of_thessaloniki_small</item>
        <item>@drawable/ic_alaca_imaret_mosque_small</item>
        <item>@drawable/ic_upper_town_small</item>
        <item>@drawable/ic_bey_hamam_small</item>
        <item>@drawable/ic_karipeion_melathron_small</item>
        <item>@drawable/ic_government_house_small</item>
        <item>@drawable/ic_new_mosque_small</item>
        <item>@drawable/ic_white_tower_small</item>
        <item>@drawable/ic_alexandreio_melathron_small</item>
        <item>@drawable/ic_aristotelous_square_small</item>
        <item>@drawable/ic_ladadika_small</item>
        <item>@drawable/ic_modiano_market_small</item>
        <item>@drawable/ic_nationaltheatre_of_northern_greece_small</item>
        <item>@drawable/ic_ote_tower_small</item>
        <item>@drawable/ic_port_of_thessaloniki_small</item>
        <item>@drawable/ic_thessaloniki_concert_hall_small</item>
        <item>@drawable/ic_great_alexander_statue_small</item>
        <item>@drawable/ic_mouseio_makedonikou_agona_small</item>
        <item>@drawable/ic_jewish_museum_small</item>
        <item>@drawable/ic_archaeological_museum_small</item>
        <item>@drawable/ic_byzantine_museum_small</item>
    </string-array>

    <string-array name="array_markeritems_names">
        <item>Arch of Galerius and Rotunda</item>
        <item>Navarinou Square</item>
        <item>Roman Forum</item>
        <item>Agias Sofias Square</item>
        <item>Byzantine Bath</item>
        <item>Church of the Acheiropoietos</item>
        <item>Church of the Holy Apostles</item>
        <item>Church of Hosios David</item>
        <item>Church of Panagia Chalkeon</item>
        <item>Church of Saint Catherine, Thessaloniki</item>
        <item>Church of Saint Nicholas Orphanos</item>
        <item>Church of Saint Panteleimon</item>
        <item>Church of Prophet Elijah</item>
        <item>Hagios Demetrios</item>
        <item>Hagia Sophia</item>
        <item>Walls of Thessaloniki</item>
        <item>Alaca Imaret Mosque</item>
        <item>Upper Town</item>
        <item>Bey Hamam</item>
        <item>Karipeion Melathron</item>
        <item>Government House</item>
        <item>New Mosque</item>
        <item>White Tower of Thessaloniki</item>
        <item>Alexandreio Melathron</item>
        <item>Aristotelous Square</item>
        <item>Ladadika</item>
        <item>Modiano Market</item>
        <item>National Theatre of Northern Greece</item>
        <item>OTE Tower</item>
        <item>Port of Thessaloniki</item>
        <item>Thessaloniki Concert Hall</item>
        <item>Statue Alexander the Great</item>
        <item>Museum for the Macedonian Struggle (Thessaloniki)</item>
        <item>Jewish Museum of Thessaloniki</item>
        <item>Archaeological Museum of Thessaloniki</item>
        <item>Museum of Byzantine Culture</item>
    </string-array>

</resources>


text:
Transforms colors to [less operations](http://lesscss.org/functions/#color-operations) that needs to be applied
to the base color to get the desired color.

Currently colors parsed only as HEX: #fff, ccc, #ceceff.

## Usage

    c2o = require("colors-to-less-operations");

    base      = "#ff8000";
    dependent = "#bf8040";

    // will become "saturate(#ff8000, 20%); // #bf8040"
    dependentAsOperations = c2o.transformToLessOperations(base, dependent);

## Tests

Run `make test`.

## License & copyright

 * MIT
 * (c) 2014 github.com/garex, a@ustimen.co


text:
import status from '../constants/ResponseStatus';

//监测API 返回数据的状态
export default function checkDataStatus(data, dispatch, options = {}) {
  switch (data.status) {
    case status.SUCCESS:
      return true;
    case status.EXCEPTION:
      return false;
    default:
      return false;
  }
}


text:
require 'spec_helper'

describe "NatRecur.parse" do
  before(:each) do
    @start = Date.new(2050, 4, 16)
  end

  it "should parse basic recurrence names" do
    @start
  end
end