text:
#import "KGOTableViewController.h"
#import "KGOTheme.h"
#import "KGOSearchDisplayController.h"
#import "Foundation+KGOAdditions.h"

#define GROUPED_SECTION_HEADER_VPADDING 24
#define PLAIN_SECTION_HEADER_VPADDING 5.0f

#define MAX_CELL_PADDING 20.0f

// maximum number of cells to keep in memory above and below the current cell
#define MAX_CELL_BUFFER_IPHONE 12
#define MAX_CELL_BUFFER_IPAD 25

@interface KGOTableController (Private)

- (NSMutableDictionary *)contentBufferForTableView:(UITableView *)tableView;

@end

@implementation KGOTableViewController

// in this implementation file watch out for the distinction between _viewController, _searchController, and self.viewController

@synthesize tableView = _tableView;

- (id)init {
    self = [super init];
    if (self) {
		_tableController = [[KGOTableController alloc] initWithViewController:self];
		_tableController.dataSource = self;
	}
	return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		_tableController = [[KGOTableController alloc] initWithViewController:self];
		_tableController.dataSource = self;
	}
	return self;
}

- (id)initWithStyle:(UITableViewStyle)style {
    self = [super init];
    if (self) {
		_tableController = [[KGOTableController alloc] initWithViewController:self];
		_tableController.dataSource = self;

		_didInitWithStyle = YES;
		_initStyle = style;
	}
	return self;
}

- (void)loadView {
	[super loadView];

	if (_didInitWithStyle) {
        self.tableView = [_tableController addTableViewWithStyle:_initStyle];
	}
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    if (selectedIndexPath) {
        [self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
    }
}

- (void)viewDidUnload {
	[super viewDidUnload];

	if (_didInitWithStyle) {
        self.tableView = nil;
	}
}

- (void)removeTableView:(UITableView *)tableView {
	[_tableController removeTableView:tableView];
    self.tableView = [_tableController topTableView];
}

- (void)addTableView:(UITableView *)tableView {
	[_tableController addTableView:tableView];
    self.tableView = [_tableController topTableView];
}

- (void)addTableView:(UITableView *)tableView withDataSource:(id<KGOTableViewDataSource>)dataSource {
	[_tableController addTableView:tableView withDataSource:dataSource];
    self.tableView = [_tableController topTableView];
}

- (UITableView *)addTableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style {
	return [_tableController addTableViewWithFrame:frame style:style];
}

- (void)bringTableViewToFront:(UITableView *)tableView {
    if (tableView != [_tableController topTableView]) {
        [tableView retain];
        [_tableController removeTableView:tableView];
        [_tableController addTableView:tableView];
        [tableView release];
    }
}

- (void)reloadDataForTableView:(UITableView *)tableView {
	[_tableController reloadDataForTableView:tableView];
}

- (void)decacheTableView:(UITableView *)tableView {
	[_tableController decacheTableView:tableView];
}

- (void)dealloc {
	self.tableView = nil;
	[_tableController release];
	[super dealloc];
}

#pragma mark forwarding of UITableViewDataSource

// we need to implement here the exact same methods as KGOTableController
// and make sure none of KGOTableController's implementations make
// references back to us

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	return [_tableController tableView:tableView cellForRowAtIndexPath:indexPath];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 0;
}

#pragma mark forwarding of UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	return [_tableController tableView:tableView heightForHeaderInSection:section];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	return [_tableController tableView:tableView viewForHeaderInSection:section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return [_tableController tableView:tableView heightForRowAtIndexPath:indexPath];
}

@end

#pragma mark -

@implementation KGOTableController

@synthesize dataSource = _dataSource, caching;

- (id)initWithTableView:(UITableView *)tableView dataSource:(id<KGOTableViewDataSource>)dataSource {
    self = [super init];
    if (self) {
		_currentTableView = tableView;
        _currentTableView.delegate = self;
        _currentTableView.dataSource = dataSource;
        _tableViewDataSources = [[NSMutableArray alloc] initWithObjects:dataSource, nil];
        _tableViews = [[NSMutableArray alloc] initWithObjects:_currentTableView, nil];
		_currentContentBuffer = [NSMutableDictionary dictionary];
		_cellContentBuffers = [[NSMutableArray alloc] initWithObjects:_currentContentBuffer, nil];
        _currentTableWidth = 0;

        _lastCachedRow = _lastCachedSection = 0;
	}
	return self;
}

- (id)initWithSearchController:(KGOSearchDisplayController *)searchController {
    self = [super init];
    if (self) {
		_searchController = searchController;

        _tableViews = [[NSMutableArray alloc] init];
        _tableViewDataSources = [[NSMutableArray alloc] init];
		_cellContentBuffers = [[NSMutableArray alloc] init];
		_currentContentBuffer = nil;
		_currentTableView = nil;
        _currentTableWidth = 0;

        _lastCachedRow = _lastCachedSection = 0;
	}
	return self;
}

- (id)initWithViewController:(KGOTableViewController *)viewController {
    self = [super init];
    if (self) {
        _viewController = viewController;

        _tableViews = [[NSMutableArray alloc] init];
        _tableViewDataSources = [[NSMutableArray alloc] init];
		_cellContentBuffers = [[NSMutableArray alloc] init];
		_currentContentBuffer = nil;
		_currentTableView = nil;
        _currentTableWidth = 0;

        _lastCachedRow = _lastCachedSection = 0;
    }
    return self;
}

- (void)dealloc {
    self.dataSource = nil;
    _viewController = nil;
	_searchController = nil;

    [_tableViews release];
    [_tableViewDataSources release];
    [_cellContentBuffers release];

    [super dealloc];
}

- (UIViewController *)viewController {
    if (_viewController) {
        return _viewController;
    } else if (_searchController) {
        return _searchController.searchContentsController;
    }
    return nil;
}

#pragma mark Table view queue

- (UITableView *)topTableView {
    return [_tableViews lastObject];
}

- (NSArray *)tableViews {
    return [NSArray arrayWithArray:_tableViews];
}

- (void)removeTableView:(UITableView *)tableView {
	if (tableView == _currentTableView) {
		_currentTableView = nil;
	}

	NSInteger tableViewIndex = [_tableViews indexOfObject:tableView];
    if (tableViewIndex != NSNotFound) {
        [tableView removeFromSuperview];

        [_tableViews removeObjectAtIndex:tableViewIndex];
        [_tableViewDataSources removeObjectAtIndex:tableViewIndex];
		[_cellContentBuffers removeObjectAtIndex:tableViewIndex];
    }
}

- (void)removeTableViewAtIndex:(NSInteger)tableViewIndex {
    UITableView *tableView = [_tableViews objectAtIndex:tableViewIndex];
    [tableView removeFromSuperview];

    [_tableViews removeObjectAtIndex:tableViewIndex];
    [_tableViewDataSources removeObjectAtIndex:tableViewIndex];
    [_cellContentBuffers removeObjectAtIndex:tableViewIndex];
}

- (void)removeAllTableViews {
    for (UITableView *tableView in _tableViews) {
        [tableView removeFromSuperview];
    }
    [_tableViews removeAllObjects];
    [_tableViewDataSources removeAllObjects];
    [_cellContentBuffers removeAllObjects];
}

- (void)addTableView:(UITableView *)tableView {
	[self addTableView:tableView withDataSource:self.dataSource];
}

- (void)addTableView:(UITableView *)tableView withDataSource:(id<KGOTableViewDataSource>)dataSource {
	[_tableViews addObject:tableView];
	[_tableViewDataSources addObject:dataSource];
	[_cellContentBuffers addObject:[NSMutableDictionary dictionary]];

    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

	if (_viewController) {
		tableView.delegate = _viewController;
		tableView.dataSource = _viewController;
	} else if (_searchController) {
		tableView.delegate = self;
		tableView.dataSource = _searchController;
	}

	[self.viewController.view addSubview:tableView];
}

- (UITableView *)addTableViewWithStyle:(UITableViewStyle)style {
    return [self addTableViewWithStyle:style dataSource:self.dataSource];
}

- (UITableView *)addTableViewWithStyle:(UITableViewStyle)style dataSource:(id<KGOTableViewDataSource>)dataSource {
	CGRect frame;
	if (_viewController) {
		frame = CGRectMake(0, 0, _viewController.view.bounds.size.width, _viewController.view.bounds.size.height);
	} else if (_searchController) {
        UIViewController *vc = _searchController.searchContentsController;
		frame = CGRectMake(0, 0, vc.view.bounds.size.width, vc.view.bounds.size.height);
    } else {
		return nil;
	}
    return [self addTableViewWithFrame:frame style:style dataSource:dataSource];
}

- (UITableView *)addTableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style {
	return [self addTableViewWithFrame:frame style:style dataSource:self.dataSource];
}

- (UITableView *)addTableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style dataSource:(id<KGOTableViewDataSource>)dataSource {
    UITableView *tableView = [[[UITableView alloc] initWithFrame:frame style:style] autorelease];

    if (style == UITableViewStyleGrouped) {
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView = nil;
    }

	[self addTableView:tableView withDataSource:dataSource];

    return tableView;
}

- (void)reloadDataForTableView:(UITableView *)tableView {
	[self decacheTableView:tableView];
	[tableView reloadData];
}

- (void)decacheTableView:(UITableView *)tableView {
	NSMutableDictionary *dict = [self contentBufferForTableView:tableView];
	[dict removeAllObjects];
}

- (id<KGOTableViewDataSource>)dataSourceForTableView:(UITableView *)tableView {
    NSInteger tableViewIndex = [_tableViews indexOfObject:tableView];
    if (tableViewIndex != NSNotFound) {
        return [_tableViewDataSources objectAtIndex:tableViewIndex];
    }
    return nil;
}

- (NSMutableDictionary *)contentBufferForTableView:(UITableView *)tableView {
    NSInteger tableViewIndex = [_tableViews indexOfObject:tableView];
    if (tableViewIndex != NSNotFound) {
		return [_cellContentBuffers objectAtIndex:tableViewIndex];
    }
    return nil;
}

- (BOOL)removeCachedViewsInSection:(NSInteger)section row:(NSInteger)row
{
    DLog(@"removing %d %d", section, row);
    NSString *key = [NSString stringWithFormat:@"%d.%d", section, row];
    if ([_currentContentBuffer objectForKey:key] != nil) {
        [_currentContentBuffer removeObjectForKey:key];
        DLog(@"removed %d %d", section, row);

        return YES;
    }
    return NO;
}

- (NSArray *)tableView:tableView cachedViewsForCellAtIndexPath:(NSIndexPath *)indexPath {

    if (!self.caching) {
        id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];
		if ([dataSource respondsToSelector:@selector(tableView:viewsForCellAtIndexPath:)]) {
			return [dataSource tableView:tableView viewsForCellAtIndexPath:indexPath];
		}
        return nil;
    }

	if (tableView != _currentTableView) {
		_currentContentBuffer = [self contentBufferForTableView:tableView];
		_currentTableView = tableView;
	}

    NSString *key = [NSString stringWithFormat:@"%d.%d", indexPath.section, indexPath.row];
    NSArray *views = [_currentContentBuffer objectForKey:key];
    if (!views) {
        id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];

        // clear the buffer if we're too far away from where we last cached
        // e.g. if the tableview is long, we will have cached cells at the very end
        // from heightForRowAtIndexPath by the time we start calling
        // cellForRowAtIndexPath at the beginning
        NSInteger maxCells = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) ? MAX_CELL_BUFFER_IPHONE : MAX_CELL_BUFFER_IPAD;
        NSInteger maxCellsInBuffer = 2 * maxCells + 1;

        KGOSign sign = KGOSignZero;

        if (_lastCachedSection == indexPath.section) { // most common
            if (abs(indexPath.row - _lastCachedRow) > maxCellsInBuffer) {
                DLog(@"%d %d %@", _lastCachedSection, _lastCachedRow, indexPath);
                [_currentContentBuffer removeAllObjects];
            }
            sign = KGOGetIntegerSign(indexPath.row - _lastCachedRow);

        } else if (_lastCachedSection > indexPath.section) { // second most common for use case mentioned above
            sign = KGOSignNegative;

            if (_lastCachedRow > maxCells) {
                [_currentContentBuffer removeAllObjects];

            } else {
                NSInteger numRowsBetween = _lastCachedRow + 1;
                for (int i = _lastCachedSection; i > indexPath.section; i--) {
                    numRowsBetween += [dataSource tableView:tableView numberOfRowsInSection:i];
                    if (numRowsBetween > maxCells) {
                        [_currentContentBuffer removeAllObjects];
                        break;
                    }
                }
            }

        } else { // can't think of a use case for this
            sign = KGOSignPositive;

            NSInteger rowsInSection = [dataSource tableView:tableView numberOfRowsInSection:_lastCachedSection];
            NSInteger numRowsBetween = rowsInSection - _lastCachedRow;
            if (numRowsBetween > maxCells) {
                [_currentContentBuffer removeAllObjects];

            } else {
                for (int i = _lastCachedSection; i < indexPath.section; i++) {
                    numRowsBetween += [dataSource tableView:tableView numberOfRowsInSection:i];
                    if (numRowsBetween > maxCells) {
                        [_currentContentBuffer removeAllObjects];
                        break;
                    }
                }
            }
        }

        // retrieve cached views.
		if ([dataSource respondsToSelector:@selector(tableView:viewsForCellAtIndexPath:)]) {
			views = [dataSource tableView:tableView viewsForCellAtIndexPath:indexPath];
		}
        if (!views) {
            views = [NSArray array]; // don't skip values so the cache stays continuous
        }

        [_currentContentBuffer setObject:views forKey:key];

        // clear the buffer if we've added too many things to it
        NSInteger numSections = 1;
        if ([dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
            numSections = [dataSource numberOfSectionsInTableView:tableView];
        }

        DLog(@"%d", _currentContentBuffer.count);
        if (_currentContentBuffer.count > maxCellsInBuffer) {

            if (sign == KGOSignPositive) {
                // clear cached cells before current cell
                NSInteger startRow = indexPath.row - maxCells - 1;
                NSInteger section = indexPath.section;
                while (startRow < 0 && section >= 0) {
                    section--;
                    if (section >= 0) {
                        startRow += [dataSource tableView:tableView numberOfRowsInSection:section] - 1;
                    }
                }

                while (startRow >= 0 && section >= 0 && [self removeCachedViewsInSection:section row:startRow]) {
                    startRow--;
                    if (startRow < 0) {
                        section--;
                        if (section >= 0) {
                            startRow = [dataSource tableView:tableView numberOfRowsInSection:section] - 1;
                        }
                    }
                }

            } else {
                // clear cached cells after current cell
                NSInteger startRow = indexPath.row + maxCells;
                NSInteger section = indexPath.section;
                NSInteger numRows = [dataSource tableView:tableView numberOfRowsInSection:section];
                while (startRow >= numRows && section < numSections) {
                    startRow -= numRows;
                    section++;
                    if (section < numSections) {
                        numRows = [dataSource tableView:tableView numberOfRowsInSection:section];
                    }
                }

                while (startRow < numRows && section < numSections && [self removeCachedViewsInSection:section row:startRow]) {
                    startRow++;
                    if (startRow >= numRows) {
                        startRow = 0;
                        section++;
                        if (section < numSections) {
                            numRows = [dataSource tableView:tableView numberOfRowsInSection:section];
                        }
                    }
                }
            }
        }

        _lastCachedSection = indexPath.section;
        _lastCachedRow = indexPath.row;

    }
    return views;
}

#pragma mark -
#pragma mark UITableViewDataSource wrapper

// we do not implement titleForHeaderInSection and titleForFooterInSection

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];

    NSArray *cachedViews = [self tableView:tableView cachedViewsForCellAtIndexPath:indexPath];
    UITableViewCell *cell = nil;
    KGOTableCellStyle internalStyle;
    UITableViewCellStyle style;
    UIFont *titleFont = nil;
    UIFont *subtitleFont = nil;

	if ([dataSource respondsToSelector:@selector(tableView:styleForCellAtIndexPath:)]) {
		internalStyle = [dataSource tableView:tableView styleForCellAtIndexPath:indexPath];
	} else {
		internalStyle = KGOTableCellStyleDefault;
	}

    switch (internalStyle) {
        case KGOTableCellStyleValue1:
            style = UITableViewCellStyleValue1;
            titleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListTitle];
            subtitleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyBodyText];
            break;
        case KGOTableCellStyleValue2:
            style = UITableViewCellStyleValue2;
            titleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListLabel];
            subtitleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListValue];
            break;
        case KGOTableCellStyleSubtitle:
            titleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListTitle];
            subtitleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListSubtitle];
            style = UITableViewCellStyleSubtitle;
            break;
        default:
            titleFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListTitle];
            style = UITableViewCellStyleDefault;
            break;
    }

	NSString *cellID = [NSString stringWithFormat:@"%d.%d", indexPath.section, internalStyle];
	cell = [tableView dequeueReusableCellWithIdentifier:cellID];

	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:cellID] autorelease];

	} else {
		for (UIView *aView in cell.contentView.subviews) {
			if (aView != cell.textLabel && aView != cell.detailTextLabel && aView != cell.imageView && aView != cell.accessoryView) {
				[aView removeFromSuperview];
			}
		}
	}

    // TODO: set theme colors as well

    cell.textLabel.font = titleFont;
    if (subtitleFont) {
        cell.detailTextLabel.font = subtitleFont;
    }

    if ([dataSource respondsToSelector:@selector(tableView:manipulatorForCellAtIndexPath:)]) {
        CellManipulator manipulateCell = [dataSource tableView:tableView manipulatorForCellAtIndexPath:indexPath];
        if (manipulateCell) {
            manipulateCell(cell);
        }
    }

	if (cachedViews.count) {
		for (UIView *aView in cachedViews) {
			[cell.contentView addSubview:aView];
		}
	}

    return cell;
}

// implementing this only because it is required by the protocol
// but it will never be called because the table view's dataSource property
// is not us but either a search display controller or table view controller
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

#pragma mark UITableViewDelegate methods

/*
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    // UITableView will call this early on since it needs heights for the whole
    // table before it can start drawing, so we put this check here
    CGFloat width = tableView.frame.size.width;
    if (_currentTableWidth && width != _currentTableWidth) {
        [self decacheTableView:tableView];
    }
    _currentTableWidth = width;

    CGFloat height = 0;

    id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];

    NSString *title = nil;
    if ([dataSource respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
        title = [dataSource tableView:tableView titleForHeaderInSection:section];
    }

    if (title) {
        if (tableView.style == UITableViewStylePlain) {
            height = [[[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertySectionHeader] lineHeight] + PLAIN_SECTION_HEADER_VPADDING;
        } else {
            height = [[[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertySectionHeaderGrouped] lineHeight] + GROUPED_SECTION_HEADER_VPADDING;
        }
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *views = [self tableView:tableView cachedViewsForCellAtIndexPath:indexPath];

    if (!views.count) {
        return tableView.rowHeight;
    }

    // the following assumes the cell has symmetrical minimum top padding and minimum bottom padding
    CGFloat ymin = MAX_CELL_PADDING;
    CGFloat ymax = 0.0;
    for (UIView *aView in views) {
        if (aView.frame.origin.y < ymin)
            ymin = aView.frame.origin.y;

        CGFloat bottom = aView.frame.origin.y + aView.frame.size.height;
        if (bottom > ymax)
            ymax = bottom;
    }
    return fmax(ymax + ymin, tableView.rowHeight);
}

/*
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
}
*/

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];
    NSString *title = nil;
    if ([dataSource respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
        title = [dataSource tableView:tableView titleForHeaderInSection:section];
    }

    if (!title)
        return nil;

    UIFont *font;
    UIColor *textColor;
    UIColor *bgColor;
    CGFloat hPadding = 10;
    CGFloat viewHeight;

    if (tableView.style == UITableViewStylePlain) {
        font = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertySectionHeader];
        textColor = [[KGOTheme sharedTheme] textColorForThemedProperty:KGOThemePropertySectionHeader];
        bgColor = [[KGOTheme sharedTheme] backgroundColorForPlainSectionHeader];
        viewHeight = font.lineHeight + PLAIN_SECTION_HEADER_VPADDING;
    } else {
        font = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertySectionHeaderGrouped];
        textColor = [[KGOTheme sharedTheme] textColorForThemedProperty:KGOThemePropertySectionHeaderGrouped];
        bgColor = [UIColor clearColor];
        viewHeight = font.lineHeight + GROUPED_SECTION_HEADER_VPADDING;
    }

    CGSize size = [title sizeWithFont:font];
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(hPadding, floor((viewHeight - size.height) / 2), tableView.bounds.size.width - hPadding * 2, size.height)] autorelease];

	label.text = title;
	label.textColor = textColor;
	label.font = font;
	label.backgroundColor = [UIColor clearColor];

	UIView *labelContainer = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.bounds.size.width, viewHeight)] autorelease];
	labelContainer.backgroundColor = bgColor;

	[labelContainer addSubview:label];

	return labelContainer;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    id<KGOTableViewDataSource> dataSource = [self dataSourceForTableView:tableView];
    if ([dataSource respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
        [dataSource tableView:tableView didSelectRowAtIndexPath:indexPath];
    }
}

/*
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
*/

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 21: 342 (1923)

#### Original name
Ctenoderma petchii Syd., 1923

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of discourse in UD_Karelian-KKPP</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Karelian-KKPP: Relations: discourse

This relation is universal.

4 nodes (0%) are attached to their parents as discourse.

4 instances of discourse (100%) are right-to-left (child precedes parent).
Average distance between parent and child is 6.

The following 2 pairs of parts of speech are connected with discourse: <tt>VERB</tt>-<tt>INTJ</tt> (3; 75% instances), <tt>VERB</tt>-<tt>NOUN</tt> (1; 25% instances).

# visual-style 1	bgColor:blue
# visual-style 1	fgColor:white
# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 4 1 discourse	color:blue
1	Kyllä	kyllä	INTJ	INTJ	_	4	discourse	_	SpaceAfter=No
2	,	,	PUNCT	PUNCT	_	4	punct	_	_
3	kanšallisuš	kanšallisuš	NOUN	NOUN	Case=Nom|Number=Sing	4	nsubj	_	_
4	vaikuttau	vaikuttoa	VERB	VERB	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act	0	root	_	_
5	ihmiseh	ihmini	NOUN	NOUN	Case=Ill|Number=Sing	4	obl	_	_
6	luontoh	luonto	NOUN	NOUN	Case=Ill|Number=Sing	4	obl	_	SpaceAfter=No
7	.	.	PUNCT	PUNCT	_	4	punct	_	SpaceAfter=No

# visual-style 2	bgColor:blue
# visual-style 2	fgColor:white
# visual-style 6	bgColor:blue
# visual-style 6	fgColor:white
# visual-style 6 2 discourse	color:blue
1	Miun	mie	PRON	PRON	Case=Gen|Number=Sing|Person=1|PronType=Prs	2	nmod:poss	_	_
2	mieleštä	mieli	NOUN	NOUN	Case=Ela|Number=Sing	6	discourse	_	SpaceAfter=No
3	,	,	PUNCT	PUNCT	_	6	punct	_	_
4	lava	lava	NOUN	NOUN	Case=Nom|Number=Sing	6	nsubj	_	_
5	aina	aina	ADV	ADV	_	6	advmod	_	_
6	erottau	erottoa	VERB	VERB	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act	0	root	_	_
7	kaččojie	kaččoja	NOUN	NOUN	Case=Par|Number=Plur	6	obj	_	_
8	artistoista	artista	NOUN	NOUN	Case=Ela|Number=Plur	6	obl	_	SpaceAfter=No
9	.	.	PUNCT	PUNCT	_	6	punct	_	SpaceAfter=No

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<?php

namespace Twig;

class_exists('Twig_ExpressionParser');

if (\false) {
    class ExpressionParser extends \Twig_ExpressionParser
    {
    }
}


text:
<?php

namespace Apoutchika\MediaBundle\Tests\Filesystem;

use Apoutchika\MediaBundle\Filesystem\FilesystemManipulator;

class FtpTest extends  \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getLocalProvider
     */
    public function testLocal($configs, $response)
    {
        $fs = new FilesystemManipulator(array('ftp' => $configs));

        $this->assertEquals($response['path'], $fs->path($response['key']));
        $this->assertEquals($response['url'], $fs->url($response['key'], true));
    }

    public function getLocalProvider()
    {
        return array(

            array(
                array(
                    'url' => 'http://www.exemple.tld/medias',
                    'path' => '/web/medias',
                    'host' => 'ftp.exemple.tld',
                ), array(
                    'key' => 'original/test.png',
                    'path' => '/web/medias/original/test.png',
                    'url' => 'http://www.exemple.tld/medias/original/test.png',
                    'url_relative' => 'http://www.exemple.tld/medias/original/test.png',
                ),
            ),

            array(
                array(
                    'url' => 'http://www.exemple.tld/medias/',
                    'path' => '/web/medias/',
                    'host' => 'ftp.exemple.tld',
                ), array(
                    'key' => 'original/test.png',
                    'path' => '/web/medias/original/test.png',
                    'url' => 'http://www.exemple.tld/medias/original/test.png',
                    'url_relative' => 'http://www.exemple.tld/medias/original/test.png',
                ),
            ),

        );
    }
}


text:
package org.netbeans.modeler.actions;

import java.awt.Container;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import org.netbeans.api.visual.action.WidgetAction;
import org.netbeans.api.visual.widget.Scene;
import org.netbeans.api.visual.widget.Widget;
import org.netbeans.modeler.resource.toolbar.ImageUtil;
import org.openide.util.ImageUtilities;
import org.openide.util.Utilities;

public class PanAction extends WidgetAction.LockedAdapter {

    private Scene scene;
    private JScrollPane scrollPane;
    private Point lastLocation;
    public Cursor MOUSE_PRESSED;
    private Cursor MOUSE_RELEASED;

    private void initCursor() {
        MOUSE_PRESSED = Utilities.createCustomCursor(scene.getView(),
                ImageUtilities.icon2Image(ImageUtil.getInstance().getIcon("pan-closed-hand.gif")),
                "PanClosedHand");
        MOUSE_RELEASED = Utilities.createCustomCursor(scene.getView(),
                ImageUtilities.icon2Image(ImageUtil.getInstance().getIcon("pan-open-hand.gif")),
                "PanOpenedHand");
    }

    @Override
    protected boolean isLocked() {
        return scrollPane != null;
    }

    @Override
    public State mousePressed(Widget widget, WidgetMouseEvent event) {
        scene = widget.getScene();
        if (isLocked()) {
            return State.createLocked(widget, this);
        }
        if (event.getButton() == MouseEvent.BUTTON1) {
            scrollPane = findScrollPane(scene.getView());
            if (scrollPane != null) {
                if (MOUSE_PRESSED == null) {
                    initCursor();
                }
                scene.getView().setCursor(MOUSE_PRESSED);
                lastLocation = scene.convertSceneToView(widget.convertLocalToScene(event.getPoint()));
                SwingUtilities.convertPointToScreen(lastLocation, scene.getView());
                return State.createLocked(widget, this);
            }
        }
        return State.REJECTED;
    }

    private JScrollPane findScrollPane(JComponent component) {
        for (;;) {
            if (component == null) {
                return null;
            }
            if (component instanceof JScrollPane) {
                return ((JScrollPane) component);
            }
            Container parent = component.getParent();
            if (!(parent instanceof JComponent)) {
                return null;
            }
            component = (JComponent) parent;
        }
    }

    @Override
    public State mouseReleased(Widget widget, WidgetMouseEvent event) {
        if (MOUSE_RELEASED == null) {
            initCursor();
        }

        boolean state = pan(widget, event.getPoint());
        if (state) {
            scrollPane = null;
        }
        scene.getView().setCursor(MOUSE_RELEASED);
        return state ? State.createLocked(widget, this) : State.REJECTED;
    }

    @Override
    public State mouseDragged(Widget widget, WidgetMouseEvent event) {
        return pan(widget, event.getPoint()) ? State.createLocked(widget, this) : State.REJECTED;
    }

    private boolean pan(Widget widget, Point newLocation) {
        if (scrollPane == null || scene != widget.getScene()) {
            return false;
        }
        newLocation = scene.convertSceneToView(widget.convertLocalToScene(newLocation));
        SwingUtilities.convertPointToScreen(newLocation, scene.getView());
        JComponent view = scene.getView();
        view.setCursor(MOUSE_PRESSED);
        Rectangle rectangle = view.getVisibleRect();
        rectangle.x += lastLocation.x - newLocation.x;
        rectangle.y += lastLocation.y - newLocation.y;
        view.scrollRectToVisible(rectangle);
        lastLocation = newLocation;
        return true;
    }

}


text:
package act.test.util;

import act.app.App;
import act.job.AppJobManager;
import act.test.classloading.ActTestClassLoader;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import org.osgl.$;
import org.osgl.util.E;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Properties;

/**
 * Allow it to run the test in the context of {@link ActTestClassLoader}
 */
public class ActTestRunner extends Runner {

    private Object innerRunner;
    private Class<? extends Runner> innerRunnerClass;
    private ActTestClassLoader classLoader;

    public ActTestRunner(Class<?> testFileClass) {
        AppJobManager jobManager = Mockito.mock(AppJobManager.class);
        App app = Mockito.mock(App.class);
        Mockito.when(app.jobManager()).thenReturn(jobManager);
        List<String> pattern = ActClassDiscoverer.getActClassNamePatternsOn(testFileClass);
        classLoader =  new ActTestClassLoader(app, pattern);
        URL url = getClass().getResource("/act-test.properties");
        if (null != url) {
            Properties p = new Properties();
            try {
                p.load(url.openStream());
            } catch (IOException e) {
                throw E.ioException(e);
            }
            classLoader.testProperties(p);
        }
        // When it runs (in intellij IDEA) multiple test cases that extends ActTestBase
        // multiple ActTestClassLoader will be created and the
        // last will be come the current thread's context class loader
        // which will trigger strange error when deserialize data from
        // mongodb. Thus we need to comment out this line
        // Thread.currentThread().setContextClassLoader(classLoader);
        innerRunnerClass = $.classForName(JUnit4.class.getName(), classLoader);
        String testFileClassName = testFileClass.getName();
        Class<?> testClass = $.classForName(testFileClassName, classLoader);
        innerRunner = $.newInstance(innerRunnerClass, testClass);
    }

    @Override
    public Description getDescription() {
        try {
            return (Description) innerRunnerClass.getMethod("getDescription").invoke(innerRunner);
        } catch (Exception e) {
            throw new RuntimeException("Could not get description", e);
        }
    }

    @Override
    public void run(RunNotifier notifier) {
        try {
            innerRunnerClass.getMethod("run", RunNotifier.class).invoke(innerRunner, notifier);
        } catch (Exception e) {
            notifier.fireTestFailure(new Failure(getDescription(), e));
        }
    }
}


text:
<?php
/**
 * Rogério Adriano <rogerioadris@gmail.com>
 */

namespace Rakuten\Dados\Produto;

use Rakuten\Exceptions\ParameterInvalidException;

/**
 * Class Base
 */
abstract class Base
{
    /**
     * O número 1 é o identificador que a linha em questao é referente a um cadastro de produto.
     * A linha com o inicio 2 é referente a um de produto (cores, tamanhos, voltagens, etc. Um SKU).
     *
     *  1 - Cadastro de produto
     *  2 - Variação de um produto
     *
     * @var integer
     */
    private $identificador;

    /**
     * Código Interno.
     *
     * Este código é utilizado para que você
     * identifique o produto na sua empresa.
     * Quando se tem uma integração e os
     * pedidos ao serem enviados para a
     * integração, serão identificados com esse
     * código.
     *
     ******************************************
     *
     * Part Number do produto. O
     * PartNumber é um número interno que
     * identifica a variação de cada produto.
     * Importante: Este número precisa ser
     * único e não pode ser igual ao código
     * interno de outro produto.
     *
     * @var string
     */
    private $codigo;

    /**
     * Identificador 1,2 ou 3
     *
     * @return integer
     */
    public function getIdentificador()
    {
        return $this->identificador;
    }

    /**
     * @param integer $identificador Valores válido 1, 2 ou 3
     *
     * @return $this
     */
    public function setIdentificador($identificador)
    {
        settype($identificador, 'integer');
        if (preg_match('/^([1-3]+)$/', $identificador) === 0) {
            throw new ParameterInvalidException('Identificador deve ser um valor entre 1 e 3');
        }
        $this->identificador = $identificador;

        return $this;
    }

    /**
     * identificador = 1 - Código Interno.
     * identificador = 2 - Part Number do produto.
     *
     * @return string
     */
    public function getCodigo()
    {
        return $this->codigo;
    }

    /**
     * identificador = 1 - Código Interno.
     * identificador = 2 - Part Number do produto.
     *
     * @param string $codigo
     *
     * @return $this
     */
    public function setCodigo($codigo)
    {
        if (strlen($codigo) > 25 || preg_match('/( |&|\?)/', $codigo)) {
            throw new ParameterInvalidException('Código Interno do Produto deve ter no máximo 25 caracteres');
        }
        $this->codigo = $codigo;

        return $this;
    }

    /**
     * @param  string|float  $string
     *
     * @return boolean
     */
    protected function convertStringToFloat($string)
    {
        if (is_string($string) && strpos($string, ',') !== false) {
            $string = str_replace(array('.', ','), array('', '.'), $string);
        }
        return (float)number_format((float)$string, 2, '.', '');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>io.github.bakersemail</groupId>
	<artifactId>replacer-maven-plugin</artifactId>
	<packaging>maven-plugin</packaging>
	<version>1.5.4-SNAPSHOT</version>
	<url>https://github.com/bakersemail/maven-replacer-plugin</url>
	<name>replacer-maven-plugin Maven Plugin</name>

	<parent>
		<artifactId>oss-parent</artifactId>
		<groupId>org.sonatype.oss</groupId>
		<version>7</version>
	</parent>

	<description>
		Maven plugin to replace tokens in a given file with a value
	</description>
	<scm>
		<url>https://github.com/bakersemail/maven-replacer-plugin.git</url>
		<connection>scm:git:https://github.com/bakersemail/maven-replacer-plugin.git</connection>
		<developerConnection>scm:git:https://github.com/bakersemail/maven-replacer-plugin.git</developerConnection>
	</scm>
	<licenses>
		<license>
			<name>MIT License</name>
			<url>http://www.opensource.org/licenses/mit-license.php</url>
			<distribution>repo</distribution>
			<comments>
Copyright (c) 2009-2014. Steven Baker - bakersemail@hotmail.com.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</comments>
		</license>
	</licenses>

	<issueManagement>
		<url>https://github.com/bakersemail/maven-replacer-plugin</url>
	</issueManagement>
	<distributionManagement>
    		<repository>
      			<id>sonatype-nexus-staging</id>
      			<name>Nexus Staging Repository</name>
     	 		<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    		</repository>
  	</distributionManagement>
	<developers>
		<developer>
			<id>bakersemail@hotmail.com</id>
			<name>Steven Baker</name>
			<email>bakersemail@hotmail.com</email>
		</developer>
	</developers>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>dashboard-maven-plugin</artifactId>
					<version>1.0.0-beta-1</version>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>dashboard-maven-plugin</artifactId>
				<version>1.0.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-plugin-plugin</artifactId>
				<version>3.1</version>
				<executions>
					<execution>
						<id>generated-helpmojo</id>
						<goals>
							<goal>helpmojo</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<targetJdk>1.5</targetJdk>
				</configuration>
			</plugin>
		</plugins>
	</reporting>

	<dependencies>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-plugin-api</artifactId>
			<version>3.0.3</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant</artifactId>
			<version>1.9.15</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.8.5</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.7</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.12.0</version>
        </dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.1</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
from unittest import TestCase
from resource import resource
from useful.singleton import forgetAllSingletons
import os

class TestRequest(TestCase):
    def setUp(self):
        self.settings = resource.request_settings()
        self.req = resource.Request(self.settings)
        self.linkses = ['http://es.wikipedia.org/wiki/']
        self.linkFile = 'http://malc0de.com/bl/BOOT'
        self.link_redirect = 'http://goo.gl/gK3uW'

    def tearDown(self):
        forgetAllSingletons()

    def testZip(self):
        self.req.getRequest('http://css3menu.com/download/winff5jo0awd')
        os.remove('css3menu-setup.zip')

    def testImage(self):
        self.req.getRequest(
            'http://www.autoweek.com/storyimage/CW/20121126/LOSANGELES/121129926/AR/0/2014-Ford-Fiesta-ST-LA-auto-show.jpg')
        os.remove('2014-Ford-Fiesta-ST-LA-auto-show.jpg')

    def testReturn(self):
        #To test the decorated getRequest method
        data = self.req.getRequest(self.linkses[0])
        self.assertEqual(data, self.req.html)
        self.assertEqual(len(self.req.history), 2)

    def testStatus(self):
        self.req.getRequest(self.linkses[0])
        self.assertEqual(self.req.status_code, 200)
        self.assertEqual(self.req.info.getheader("Content-Language"), "es")

    def testIsFile(self):
        self.req.getRequest(self.linkFile)
        self.assertTrue(self.req.isFile)

    def testPersistanceFile(self):
        self.req.getRequest(self.linkFile)
        self.assertTrue(os.path.exists("BOOT"))
        os.remove("BOOT")

    def testPdfPersistance(self):
        file = "PasoaPasoSIRADiG.pdf"
        afipPDF = 'www.afip.gob.ar/572web/documentos/PasoaPasoSIRADiG.pdf'
        self.req.getRequest(afipPDF)
        self.assertTrue(os.path.exists(file))
        os.remove(file)

    def testRedirect(self):
        self.req.getRequest(self.link_redirect)
        self.assertEqual(len(self.req.history), 2)
        self.assertEqual(self.req.status_code, 200)

    def testNoRedirect(self):
        self.settings = resource.request_settings(redirects=False)
        self.req.settings = self.settings #Override setting
        self.req.getRequest(self.link_redirect)
        self.assertEqual(self.req.status_code, 301)
        self.assertEqual(len(self.req.history), 1)

    def testJson(self):
        import json

        data = self.req.getRequest('https://github.com/timeline.json')
        jsondata = json.loads(data)
        self.assertTrue(hasattr(self.req, 'json'))
        self.assertEqual(jsondata, self.req.json())


text:
from django.db.models import Model
from django.db.models.base import ModelBase, subclass_exception

from django.apps import apps
from django.apps.config import MODELS_MODULE_NAME
from django.core.exceptions import (ObjectDoesNotExist,
    MultipleObjectsReturned, FieldError)
from django.db.models.fields.related import OneToOneField
from django.db.models.options import Options
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning

import warnings
import sys

class CrateOptions(Options):

    DEFAULT_NUMBER_OF_SHARDS = 5
    DEFAULT_NUMBER_OF_REPLICAS = '0-all'
    DEFAULT_CLUSTERED_BY_COLUMN = None
    DEFAULT_PARTITIONED_BY = []
    DEFAULT_REFRESH_INTERVAL = None

    def __init__(self, meta, app_label=None):
        super(CrateOptions, self).__init__(meta, app_label=app_label)

        self.number_of_shards = self.get_and_del_attr(self.meta, "number_of_shards", self.DEFAULT_NUMBER_OF_SHARDS)
        self.number_of_replicas = self.get_and_del_attr(self.meta, "number_of_replicas", self.DEFAULT_NUMBER_OF_REPLICAS)
        self.clustered_by = self.get_and_del_attr(self.meta, "clustered_by", self.DEFAULT_CLUSTERED_BY_COLUMN)
        self.partitioned_by = self.get_and_del_attr(self.meta, "partitioned_by", self.DEFAULT_PARTITIONED_BY)
        self.refresh_interval = self.get_and_del_attr(self.meta, "refresh_interval", self.DEFAULT_REFRESH_INTERVAL)

    def get_and_del_attr(self, obj, attr_name, default=None):
        attr = getattr(obj, attr_name, None)
        try:
            delattr(obj, attr_name)
        except AttributeError:
            pass # not there, that's ok
        return attr

class CrateModelBase(ModelBase):

    def __new__(cls, name, bases, attrs):
        """
        HACK: had to copy the whole method in order to change the Options implementation
        to support Crate options - WTF!!!
        """

        super_new = super(ModelBase, cls).__new__

        # Also ensure initialization is only performed for subclasses of Model
        # (excluding Model class itself).
        parents = [b for b in bases if isinstance(b, ModelBase)]
        if not parents or name == 'CrateModel':
            return super_new(cls, name, bases, attrs)

        # Create the class.
        module = attrs.pop('__module__')
        new_class = super_new(cls, name, bases, {'__module__': module})
        attr_meta = attrs.pop('Meta', None)
        abstract = getattr(attr_meta, 'abstract', False)
        if not attr_meta:
            meta = getattr(new_class, 'Meta', None)
        else:
            meta = attr_meta
        base_meta = getattr(new_class, '_meta', None)

        # Look for an application configuration to attach the model to.
        app_config = apps.get_containing_app_config(module)

        if getattr(meta, 'app_label', None) is None:

            if app_config is None:
                # If the model is imported before the configuration for its
                # application is created (#21719), or isn't in an installed
                # application (#21680), use the legacy logic to figure out the
                # app_label by looking one level up from the package or module
                # named 'models'. If no such package or module exists, fall
                # back to looking one level up from the module this model is
                # defined in.

                # For 'django.contrib.sites.models', this would be 'sites'.
                # For 'geo.models.places' this would be 'geo'.

                msg = (
                    "Model class %s.%s doesn't declare an explicit app_label "
                    "and either isn't in an application in INSTALLED_APPS or "
                    "else was imported before its application was loaded. " %
                    (module, name))
                if abstract:
                    msg += "Its app_label will be set to None in Django 1.9."
                else:
                    msg += "This will no longer be supported in Django 1.9."
                warnings.warn(msg, RemovedInDjango19Warning, stacklevel=2)

                model_module = sys.modules[new_class.__module__]
                package_components = model_module.__name__.split('.')
                package_components.reverse()  # find the last occurrence of 'models'
                try:
                    app_label_index = package_components.index(MODELS_MODULE_NAME) + 1
                except ValueError:
                    app_label_index = 1
                kwargs = {"app_label": package_components[app_label_index]}

            else:
                kwargs = {"app_label": app_config.label}

        else:
            kwargs = {}

        # THIS IS OUR CHANGE
        new_class.add_to_class('_meta', CrateOptions(meta, **kwargs))
        if not abstract:
            new_class.add_to_class(
                'DoesNotExist',
                subclass_exception(
                    str('DoesNotExist'),
                    tuple(x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (ObjectDoesNotExist,),
                    module,
                    attached_to=new_class))
            new_class.add_to_class(
                'MultipleObjectsReturned',
                subclass_exception(
                    str('MultipleObjectsReturned'),
                    tuple(x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract) or (MultipleObjectsReturned,),
                    module,
                    attached_to=new_class))
            if base_meta and not base_meta.abstract:
                # Non-abstract child classes inherit some attributes from their
                # non-abstract parent (unless an ABC comes before it in the
                # method resolution order).
                if not hasattr(meta, 'ordering'):
                    new_class._meta.ordering = base_meta.ordering
                if not hasattr(meta, 'get_latest_by'):
                    new_class._meta.get_latest_by = base_meta.get_latest_by

        is_proxy = new_class._meta.proxy

        # If the model is a proxy, ensure that the base class
        # hasn't been swapped out.
        if is_proxy and base_meta and base_meta.swapped:
            raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped))

        if getattr(new_class, '_default_manager', None):
            if not is_proxy:
                # Multi-table inheritance doesn't inherit default manager from
                # parents.
                new_class._default_manager = None
                new_class._base_manager = None
            else:
                # Proxy classes do inherit parent's default manager, if none is
                # set explicitly.
                new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
                new_class._base_manager = new_class._base_manager._copy_to_model(new_class)

        # Add all attributes to the class.
        for obj_name, obj in attrs.items():
            new_class.add_to_class(obj_name, obj)

        # All the fields of any type declared on this model
        new_fields = (
            new_class._meta.local_fields +
            new_class._meta.local_many_to_many +
            new_class._meta.virtual_fields
        )
        field_names = set(f.name for f in new_fields)

        # Basic setup for proxy models.
        if is_proxy:
            base = None
            for parent in [kls for kls in parents if hasattr(kls, '_meta')]:
                if parent._meta.abstract:
                    if parent._meta.fields:
                        raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name)
                    else:
                        continue
                if base is not None:
                    raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
                else:
                    base = parent
            if base is None:
                raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
            new_class._meta.setup_proxy(base)
            new_class._meta.concrete_model = base._meta.concrete_model
        else:
            new_class._meta.concrete_model = new_class

        # Collect the parent links for multi-table inheritance.
        parent_links = {}
        for base in reversed([new_class] + parents):
            # Conceptually equivalent to `if base is Model`.
            if not hasattr(base, '_meta'):
                continue
            # Skip concrete parent classes.
            if base != new_class and not base._meta.abstract:
                continue
            # Locate OneToOneField instances.
            for field in base._meta.local_fields:
                if isinstance(field, OneToOneField):
                    parent_links[field.rel.to] = field

        # Do the appropriate setup for any model parents.
        for base in parents:
            original_base = base
            if not hasattr(base, '_meta'):
                # Things without _meta aren't functional models, so they're
                # uninteresting parents.
                continue

            parent_fields = base._meta.local_fields + base._meta.local_many_to_many
            # Check for clashes between locally declared fields and those
            # on the base classes (we cannot handle shadowed fields at the
            # moment).
            for field in parent_fields:
                if field.name in field_names:
                    raise FieldError(
                        'Local field %r in class %r clashes '
                        'with field of similar name from '
                        'base class %r' % (field.name, name, base.__name__)
                    )
            if not base._meta.abstract:
                # Concrete classes...
                base = base._meta.concrete_model
                if base in parent_links:
                    field = parent_links[base]
                elif not is_proxy:
                    attr_name = '%s_ptr' % base._meta.model_name
                    field = OneToOneField(base, name=attr_name,
                            auto_created=True, parent_link=True)
                    # Only add the ptr field if it's not already present;
                    # e.g. migrations will already have it specified
                    if not hasattr(new_class, attr_name):
                        new_class.add_to_class(attr_name, field)
                else:
                    field = None
                new_class._meta.parents[base] = field
            else:
                # .. and abstract ones.
                for field in parent_fields:
                    new_class.add_to_class(field.name, copy.deepcopy(field))

                # Pass any non-abstract parent classes onto child.
                new_class._meta.parents.update(base._meta.parents)

            # Inherit managers from the abstract base classes.
            new_class.copy_managers(base._meta.abstract_managers)

            # Proxy models inherit the non-abstract managers from their base,
            # unless they have redefined any of them.
            if is_proxy:
                new_class.copy_managers(original_base._meta.concrete_managers)

            # Inherit virtual fields (like GenericForeignKey) from the parent
            # class
            for field in base._meta.virtual_fields:
                if base._meta.abstract and field.name in field_names:
                    raise FieldError(
                        'Local field %r in class %r clashes '
                        'with field of similar name from '
                        'abstract base class %r' % (field.name, name, base.__name__)
                    )
                new_class.add_to_class(field.name, copy.deepcopy(field))

        if abstract:
            # Abstract base models can't be instantiated and don't appear in
            # the list of models for an app. We do the final setup for them a
            # little differently from normal models.
            attr_meta.abstract = False
            new_class.Meta = attr_meta
            return new_class

        new_class._prepare()
        new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
        return new_class

class CrateModel(six.with_metaclass(CrateModelBase, Model)):
    """
    the model to use when storing stuff in crate
    it allows us to specify options in Meta we otherwise couldn't use
    """


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Century Local</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

Century Local

Welcome

Century Local is active in local B2C retail sales facilitating a niche market with high quality personal consumer electronic products and gifts.

Authors and Contributors

@centurylocal is owned by @centuryholdingsgroup founded in 2016 by @jeffcentury all rights reserved

Support or Contact

Need Help? Visit our main site century local or contact support and we'll help you sort it out.

        Copyright 2016 Century Holdings Group


text:
"""
===============================
Using geometric transformations
===============================

In this example, we will see how to use geometric transformations in the context
of image processing.
"""

from __future__ import print_function

import math
import numpy as np
import matplotlib.pyplot as plt

from skimage import data
from skimage import transform as tf

margins = dict(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)

######################################################################
# Basics
# ======
#
# Several different geometric transformation types are supported: similarity,
# affine, projective and polynomial.
#
# Geometric transformations can either be created using the explicit
# parameters (e.g. scale, shear, rotation and translation) or the
# transformation matrix:
#
# First we create a transformation using explicit parameters:

tform = tf.SimilarityTransform(scale=1, rotation=math.pi / 2,
                               translation=(0, 1))
print(tform.params)

######################################################################
# Alternatively you can define a transformation by the transformation matrix
# itself:

matrix = tform.params.copy()
matrix[1, 2] = 2
tform2 = tf.SimilarityTransform(matrix)

######################################################################
# These transformation objects can then be used to apply forward and inverse
# coordinate transformations between the source and destination coordinate
# systems:

coord = [1, 0]
print(tform2(coord))
print(tform2.inverse(tform(coord)))

######################################################################
# Image warping
# =============
#
# Geometric transformations can also be used to warp images:

text = data.text()

tform = tf.SimilarityTransform(scale=1, rotation=math.pi / 4,
                               translation=(text.shape[0] / 2, -100))

rotated = tf.warp(text, tform)
back_rotated = tf.warp(rotated, tform.inverse)

fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(8, 3))
fig.subplots_adjust(**margins)
plt.gray()
ax1.imshow(text)
ax1.axis('off')
ax2.imshow(rotated)
ax2.axis('off')
ax3.imshow(back_rotated)
ax3.axis('off')

######################################################################
# Parameter estimation
# ====================
#
# In addition to the basic functionality mentioned above you can also
# estimate the parameters of a geometric transformation using the least-
# squares method.
#
# This can amongst other things be used for image registration or
# rectification, where you have a set of control points or
# homologous/corresponding points in two images.
#
# Let's assume we want to recognize letters on a photograph which was not
# taken from the front but at a certain angle. In the simplest case of a
# plane paper surface the letters are projectively distorted. Simple matching
# algorithms would not be able to match such symbols. One solution to this
# problem would be to warp the image so that the distortion is removed and
# then apply a matching algorithm:

text = data.text()

src = np.array((
    (0, 0),
    (0, 50),
    (300, 50),
    (300, 0)
))
dst = np.array((
    (155, 15),
    (65, 40),
    (260, 130),
    (360, 95)
))

tform3 = tf.ProjectiveTransform()
tform3.estimate(src, dst)
warped = tf.warp(text, tform3, output_shape=(50, 300))

fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(8, 3))
fig.subplots_adjust(**margins)
plt.gray()
ax1.imshow(text)
ax1.plot(dst[:, 0], dst[:, 1], '.r')
ax1.axis('off')
ax2.imshow(warped)
ax2.axis('off')


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>信息修改</title>

  <link href="../../css/bootstrap.min.css" rel="stylesheet">
  <link href="../../css/bootstrap.css" rel="stylesheet">

  <link href="../../css/zaozao.css" rel="stylesheet">

  <link rel="stylesheet" href="../../css/3rd_party/flickity.css" media="screen">

  <link href="../../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <base href="/">

      <input id="textinput" name="textinput" type="text" placeholder="用户名和头像都可以修改(初始头像和用户名与微信绑定)" class="form-control input-md">

宝宝信息

宝宝姓名

        <input id="textinput" name="textinput" type="text" placeholder="王二狗" class="form-control input-md">

宝宝性别

            <input type="radio" name="radios" id="radios-0" value="1" checked="checked">
            男

            <input type="radio" name="radios" id="radios-1" value="2">
            女

宝宝血型

      <select id="selectbasic" name="selectbasic" class="form-control">
              <option value="1">A型</option>
              <option value="2">B型</option>
              <option value="">AB型</option>
              <option value="">O型</option>
              <option value="">其他</option>
              <option value="">不清楚</option>
      </select>

出生日期

年

      <select id="selectbasic" name="selectbasic" class="form-control">
              <option value="1">2010</option>
              <option value="2">2011</option>
              <option value="">2012</option>
              <option value="">2013</option>
              <option value="">2014</option>
              <option value="">2015</option>
              <option value="">2016</option>
      </select>

月

      <select id="selectbasic" name="selectbasic" class="form-control">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="">3</option>
              <option value="">4</option>
              <option value="">5</option>
              <option value="">6</option>
              <option value="">7</option>
              <option value="">8</option>
              <option value="">9</option>
              <option value="">10</option>
              <option value="">11</option>
              <option value="">12</option>
      </select>

日

      <select id="selectbasic" name="selectbasic" class="form-control">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="">3</option>
            <option value="">4</option>
            <option value="">5</option>
            <option value="">6</option>
            <option value="">7</option>
            <option value="">8</option>
            <option value="">9</option>
            <option value="">10</option>
            <option value="">11</option>
            <option value="">12</option>
            <option value="">13</option>
            <option value="">14</option>
            <option value="">15</option>
            <option value="">16</option>
            <option value="">17</option>
            <option value="">18</option>
            <option value="">19</option>
            <option value="">20</option>
            <option value="">21</option>
            <option value="">22</option>
            <option value="">23</option>
            <option value="">24</option>
            <option value="">25</option>
            <option value="">26</option>
            <option value="">27</option>
            <option value="">28</option>
            <option value="">29</option>
            <option value="">30</option>
            <option value="">31</option>
            </select>

      确定

首页

早早TV