text:
static const CGFloat SpacingBetweenControlAndWindow = 8.0;
static char *AttachedControlEnabledContext = "enabled";
static char *AttachedControlHiddenContext = "hidden";
static char *FieldEditorDelegateContext = "delegate";
static char *AttachedControlWindowContext = "window";

@interface NSView (Contains)
- (BOOL)containsSubview:(NSView*)view;
@end

@implementation NSView (Contains)
- (BOOL)containsSubview:(NSView*)view
{
	for (NSView *v in self.subviews)
	{
		if (v == view)
		{
			return YES;
		}

		if ([v containsSubview:view])
		{
			return YES;
		}
	}

	return NO;
}
@end

@interface GDCAutocomplete () <NSTextViewDelegate, GDCAutocompleteItemsViewDelegate>

@property (weak, nonatomic) NSControl *controlToComplete;
@property (strong, nonatomic) GDCAutocompleteFieldEditorDelegateInterceptor *interceptor;
@property (strong, nonatomic) NSText *fieldEditor;
@property (strong, nonatomic) NSView *containerView;
@property (strong, nonatomic) NSView *headerView;
@property (strong, nonatomic) NSView *footerView;
@property (strong, nonatomic) NSScrollView *scrollView;
@property (strong, nonatomic) GDCAutocompleteItemsView *itemsView;
@property (strong, nonatomic) NSWindow *controlWindow;
@property (strong, nonatomic) NSLayoutConstraint *scrollTopConstraint;
@property (strong, nonatomic) NSLayoutConstraint *scrollBottomConstraint;
@property (assign, nonatomic) BOOL isAttached;
@property (copy, nonatomic) NSString *originalInput;
@property (assign, nonatomic) BOOL autocompleteSubviews;

- (void)setupViews;
- (void)refreshSuggestedItems;
- (NSString*)titleForItem:(id)item;

@end

@implementation GDCAutocomplete

- (instancetype)initWithWindow:(NSWindow*)window
{
	if ((self = [super initWithWindow:[[GDCAutocompleteWindow alloc] init]]) != nil)
	{
		self.window.delegate = self;
		[self setupViews];
	}

	return self;
}

- (void)awakeFromNib
{
	if (self.controlToComplete != nil)
	{
		[self attachToControl:self.controlToComplete];
	}
}

#pragma mark -

- (void)createContainerView
{
	NSVisualEffectView *v = [[NSVisualEffectView alloc] initWithFrame:NSZeroRect];
	v.wantsLayer = YES;
	v.blendingMode = NSVisualEffectBlendingModeWithinWindow;
	v.material = NSVisualEffectMaterialMenu;
	v.state = NSVisualEffectStateActive;
	v.emphasized = YES;
	self.containerView = v;
	[self.window.contentView addSubview:self.containerView];
}

- (void)setupContainerViewConstraints
{
	self.containerView.translatesAutoresizingMaskIntoConstraints = NO;
	NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.containerView
														   attribute:NSLayoutAttributeTop
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.window.contentView
														   attribute:NSLayoutAttributeTop
														  multiplier:1.0
															constant:0.0];
	NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.containerView
															  attribute:NSLayoutAttributeBottom
															  relatedBy:NSLayoutRelationEqual
																 toItem:self.window.contentView
															  attribute:NSLayoutAttributeBottom
															 multiplier:1.0
															   constant:0.0];
	NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.containerView
															attribute:NSLayoutAttributeLeft
															relatedBy:NSLayoutRelationEqual
															   toItem:self.window.contentView
															attribute:NSLayoutAttributeLeft
														   multiplier:1.0
															 constant:0.0];
	NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.containerView
															 attribute:NSLayoutAttributeRight
															 relatedBy:NSLayoutRelationEqual
																toItem:self.window.contentView
															 attribute:NSLayoutAttributeRight
															multiplier:1.0
															  constant:0.0];
	[self.window.contentView addConstraint:top];
	[self.window.contentView addConstraint:bottom];
	[self.window.contentView addConstraint:left];
	[self.window.contentView addConstraint:right];
}

- (void)createHeaderView
{
	self.headerView = [[GDCAutocompleteHeaderView alloc] initWithFrame:NSZeroRect];
	[self.containerView addSubview:self.headerView];
}

- (void)setupHeaderViewConstraints
{
	self.headerView.translatesAutoresizingMaskIntoConstraints = NO;
	NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.headerView
															  attribute:NSLayoutAttributeHeight
															  relatedBy:NSLayoutRelationEqual
																 toItem:nil
															  attribute:NSLayoutAttributeNotAnAttribute
															 multiplier:1.0
															   constant:5.0];
	NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.headerView
														   attribute:NSLayoutAttributeTop
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.containerView
														   attribute:NSLayoutAttributeTop
														  multiplier:1.0
															constant:0.0];
	NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.headerView
															attribute:NSLayoutAttributeLeft
															relatedBy:NSLayoutRelationEqual
															   toItem:self.containerView
															attribute:NSLayoutAttributeLeft
														   multiplier:1.0
															 constant:0.0];
	NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.headerView
															 attribute:NSLayoutAttributeRight
															 relatedBy:NSLayoutRelationEqual
																toItem:self.containerView
															 attribute:NSLayoutAttributeRight
															multiplier:1.0
															  constant:0.0];
	[self.containerView addConstraint:height];
	[self.containerView addConstraint:top];
	[self.containerView addConstraint:left];
	[self.containerView addConstraint:right];
}

- (void)setCustomHeaderView:(NSView*)v
{
	NSAssert(self.customHeaderView == nil, @"Custom header view is already set");
	_customHeaderView = v;

	if (self.customHeaderView != nil)
	{
		self.headerView.hidden = YES;
		[self.containerView addSubview:self.customHeaderView];
		self.customHeaderView.translatesAutoresizingMaskIntoConstraints = NO;
		NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.customHeaderView
																  attribute:NSLayoutAttributeHeight
																  relatedBy:NSLayoutRelationEqual
																	 toItem:nil
																  attribute:NSLayoutAttributeNotAnAttribute
																 multiplier:1.0
																   constant:self.customHeaderView.bounds.size.height];
		NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.customHeaderView
															   attribute:NSLayoutAttributeTop
															   relatedBy:NSLayoutRelationEqual
																  toItem:self.containerView
															   attribute:NSLayoutAttributeTop
															  multiplier:1.0
																constant:0.0];
		NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.customHeaderView
																attribute:NSLayoutAttributeLeft
																relatedBy:NSLayoutRelationEqual
																   toItem:self.containerView
																attribute:NSLayoutAttributeLeft
															   multiplier:1.0
																 constant:0.0];
		NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.customHeaderView
																 attribute:NSLayoutAttributeRight
																 relatedBy:NSLayoutRelationEqual
																	toItem:self.containerView
																 attribute:NSLayoutAttributeRight
																multiplier:1.0
																  constant:0.0];
		[self.containerView addConstraint:height];
		[self.containerView addConstraint:top];
		[self.containerView addConstraint:left];
		[self.containerView addConstraint:right];
		[self.containerView removeConstraint:self.scrollTopConstraint];
		self.scrollTopConstraint = [NSLayoutConstraint constraintWithItem:self.scrollView
																attribute:NSLayoutAttributeTop
																relatedBy:NSLayoutRelationEqual
																   toItem:self.customHeaderView
																attribute:NSLayoutAttributeBottom
															   multiplier:1.0
																 constant:0.0];
		[self.containerView addConstraint:self.scrollTopConstraint];
	}
	else
	{
		self.customHeaderView.hidden = NO;
	}
}

- (void)createFooterView
{
	self.footerView = [[GDCAutocompleteFooterView alloc] initWithFrame:NSZeroRect];
	[self.containerView addSubview:self.footerView];
}

- (void)setupFooterViewConstraints
{
	self.footerView.translatesAutoresizingMaskIntoConstraints = NO;
	NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.footerView
															  attribute:NSLayoutAttributeHeight
															  relatedBy:NSLayoutRelationEqual
																 toItem:nil
															  attribute:NSLayoutAttributeNotAnAttribute
															 multiplier:1.0
															   constant:5.0];
	NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.footerView
														   attribute:NSLayoutAttributeBottom
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.containerView
														   attribute:NSLayoutAttributeBottom
														  multiplier:1.0
															   constant:0.0];
	NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.footerView
															attribute:NSLayoutAttributeLeft
															relatedBy:NSLayoutRelationEqual
															   toItem:self.containerView
															attribute:NSLayoutAttributeLeft
														   multiplier:1.0
															 constant:0.0];
	NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.footerView
															 attribute:NSLayoutAttributeRight
															 relatedBy:NSLayoutRelationEqual
																toItem:self.containerView
															 attribute:NSLayoutAttributeRight
															multiplier:1.0
															  constant:0.0];
	[self.containerView addConstraint:height];
	[self.containerView addConstraint:bottom];
	[self.containerView addConstraint:left];
	[self.containerView addConstraint:right];
}

- (void)setCustomFooterView:(NSView*)v
{
	NSAssert(self.customFooterView == nil, @"Custom footer view is already set");
	_customFooterView = v;

	if (self.customFooterView != nil)
	{
		self.footerView.hidden = YES;
		[self.containerView addSubview:self.customFooterView];
		self.customFooterView.translatesAutoresizingMaskIntoConstraints = NO;
		NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.customFooterView
																  attribute:NSLayoutAttributeHeight
																  relatedBy:NSLayoutRelationEqual
																	 toItem:nil
																  attribute:NSLayoutAttributeNotAnAttribute
																 multiplier:1.0
																   constant:self.customFooterView.bounds.size.height];
		NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.customFooterView
																  attribute:NSLayoutAttributeBottom
																  relatedBy:NSLayoutRelationEqual
																  toItem:self.containerView
																  attribute:NSLayoutAttributeBottom
																 multiplier:1.0
																   constant:0.0];
		NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.customFooterView
																attribute:NSLayoutAttributeLeft
																relatedBy:NSLayoutRelationEqual
																   toItem:self.containerView
																attribute:NSLayoutAttributeLeft
															   multiplier:1.0
																 constant:0.0];
		NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.customFooterView
																 attribute:NSLayoutAttributeRight
																 relatedBy:NSLayoutRelationEqual
																	toItem:self.containerView
																 attribute:NSLayoutAttributeRight
																multiplier:1.0
																  constant:0.0];
		[self.containerView addConstraint:height];
		[self.containerView addConstraint:bottom];
		[self.containerView addConstraint:left];
		[self.containerView addConstraint:right];
		[self.containerView removeConstraint:self.scrollBottomConstraint];
		self.scrollBottomConstraint = [NSLayoutConstraint constraintWithItem:self.scrollView
																   attribute:NSLayoutAttributeBottom
																   relatedBy:NSLayoutRelationEqual
																	  toItem:self.customFooterView
																   attribute:NSLayoutAttributeTop
																  multiplier:1.0
																	constant:0.0];
		[self.containerView addConstraint:self.scrollBottomConstraint];
	}
	else
	{
		self.customFooterView.hidden = NO;
	}
}

- (void)createScrollView
{
	self.scrollView = [[NSScrollView alloc] initWithFrame:NSZeroRect];
	self.scrollView.autohidesScrollers = YES;
	self.scrollView.hasHorizontalScroller = NO;
	self.scrollView.hasVerticalScroller = YES;
	self.scrollView.scrollerStyle = NSScrollerStyleOverlay;
	self.scrollView.horizontalScrollElasticity = NSScrollElasticityNone;
	self.scrollView.verticalScrollElasticity = NSScrollElasticityNone;
	self.scrollView.drawsBackground = NO;
	self.scrollView.borderType = NSNoBorder;
	[self.containerView addSubview:self.scrollView];
}

- (void)setupScrollViewConstraints
{
	self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
	NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.scrollView
														   attribute:NSLayoutAttributeTop
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.headerView
														   attribute:NSLayoutAttributeBottom
														  multiplier:1.0
															constant:0.0];
	NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.scrollView
															  attribute:NSLayoutAttributeBottom
															  relatedBy:NSLayoutRelationEqual
																 toItem:self.footerView
															  attribute:NSLayoutAttributeTop
															 multiplier:1.0
															   constant:0.0];
	NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.scrollView
															attribute:NSLayoutAttributeLeft
															relatedBy:NSLayoutRelationEqual
															   toItem:self.containerView
															attribute:NSLayoutAttributeLeft
														   multiplier:1.0
															 constant:0.0];
	NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.scrollView
															 attribute:NSLayoutAttributeRight
															 relatedBy:NSLayoutRelationEqual
																toItem:self.containerView
															 attribute:NSLayoutAttributeRight
															multiplier:1.0
															  constant:0.0];
	[self.containerView addConstraint:top];
	[self.containerView addConstraint:bottom];
	[self.containerView addConstraint:left];
	[self.containerView addConstraint:right];
	self.scrollTopConstraint = top;
	self.scrollBottomConstraint = bottom;
}

- (void)createItemsView
{
	self.itemsView = [[GDCAutocompleteItemsView alloc] initWithFrame:NSZeroRect];
	self.itemsView.target = self;
	self.itemsView.action = @selector(autocompleteViewDidSelectItem:);
	self.itemsView.delegate = self;
	self.scrollView.documentView = self.itemsView;
}

- (void)setupItemsViewConstraints
{
	self.itemsView.translatesAutoresizingMaskIntoConstraints = NO;
	NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.itemsView
														   attribute:NSLayoutAttributeTop
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.scrollView
														   attribute:NSLayoutAttributeTop
														  multiplier:1.0
															constant:0.0];
	NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.itemsView
														   attribute:NSLayoutAttributeBottom
														   relatedBy:NSLayoutRelationEqual
															  toItem:self.scrollView
														   attribute:NSLayoutAttributeBottom
														  multiplier:1.0
															   constant:0.0];
	NSLayoutConstraint *left = [NSLayoutConstraint constraintWithItem:self.itemsView
															attribute:NSLayoutAttributeLeft
															relatedBy:NSLayoutRelationEqual
															   toItem:self.scrollView
															attribute:NSLayoutAttributeLeft
														   multiplier:1.0
															 constant:0.0];
	NSLayoutConstraint *right = [NSLayoutConstraint constraintWithItem:self.itemsView
															 attribute:NSLayoutAttributeRight
															 relatedBy:NSLayoutRelationEqual
																toItem:self.scrollView
															 attribute:NSLayoutAttributeRight
															multiplier:1.0
															  constant:0.0];
	[self.scrollView addConstraint:top];
	[self.scrollView addConstraint:bottom];
	[self.scrollView addConstraint:left];
	[self.scrollView addConstraint:right];
}

- (void)setupViews
{
	[self createContainerView];
	[self createHeaderView];
	[self createFooterView];
	[self createScrollView];
	[self createItemsView];
	[self setupContainerViewConstraints];
	[self setupHeaderViewConstraints];
	[self setupFooterViewConstraints];
	[self setupScrollViewConstraints];
	[self setupItemsViewConstraints];
}

- (void)attachToControl:(NSControl*)control
{
	NSAssert(!self.isAttached, @"Already attached to a control");
	NSAssert(control != nil, @"Cannot attach to nil control");
	self.controlToComplete = control;
	[self.controlToComplete addObserver:self
						   forKeyPath:@"enabled"
							  options:0
							  context:AttachedControlEnabledContext];
	[self.controlToComplete addObserver:self
						   forKeyPath:@"hidden"
							  options:0
							  context:AttachedControlHiddenContext];
	[self.controlToComplete addObserver:self
							 forKeyPath:@"window"
								options:NSKeyValueObservingOptionInitial
								context:AttachedControlWindowContext];
	[self.itemsView bind:@"content" toObject:self withKeyPath:@"suggestedItems" options:nil];

	if ([self.controlToComplete isKindOfClass:[NSSearchField class]])
	{
		self.searchMode = YES;
	}

	if ([self.controlToComplete isKindOfClass:[NSTableView class]])
	{
		self.autocompleteSubviews = YES;
	}

	self.isAttached = YES;
}

- (void)detach
{
	NSAssert(self.isAttached, @"Already detached");

	if (self.controlWindow != nil)
	{
		[[NSNotificationCenter defaultCenter] removeObserver:self
														name:NSWindowDidResignKeyNotification
													  object:self.controlWindow];
	}

	[self.controlWindow removeChildWindow:self.window];
	[self.itemsView unbind:@"content"];
	[self.controlToComplete removeObserver:self forKeyPath:@"window" context:AttachedControlWindowContext];
	[self.controlToComplete removeObserver:self forKeyPath:@"hidden" context:AttachedControlHiddenContext];
	[self.controlToComplete removeObserver:self forKeyPath:@"enabled" context:AttachedControlEnabledContext];
}

#pragma mark -

// This is invoked when an item is selected with mouse
- (void)autocompleteViewDidSelectItem:(id)sender
{
	id item = self.itemsView.selectedItem;
	[self.delegate autocomplete:self didSelectItem:item];

	if (self.searchMode)
	{
		[self hideWindow:sender];
	}
	else
	{
		self.fieldEditor.string = [self titleForItem:item];
	}

	[self.controlToComplete.window makeFirstResponder:self.controlToComplete];
}

- (void)setSearchMode:(BOOL)likeMenu
{
	_searchMode = likeMenu;
	self.itemsView.highlightingTracksMouse = likeMenu;
}

- (NSCell*)cell
{
	return self.itemsView.cell;
}

- (void)setCell:(NSCell*)cell
{
	self.itemsView.cell = cell;
}

+ (BOOL)automaticallyNotifiesObserversOfSuggestedItems
{
	return NO;
}

- (void)setFieldEditor:(NSText*)fieldEditor
{
	if (self.fieldEditor != nil)
	{
		[self.fieldEditor removeObserver:self
							  forKeyPath:@"delegate"
								 context:FieldEditorDelegateContext];
		[[NSNotificationCenter defaultCenter] removeObserver:self
														name:NSViewFrameDidChangeNotification
													  object:self.fieldEditor];
		[[NSNotificationCenter defaultCenter] removeObserver:self
														name:NSTextDidChangeNotification
													  object:self.fieldEditor];
		[[NSNotificationCenter defaultCenter] removeObserver:self
														name:NSTextDidEndEditingNotification
													  object:self.fieldEditor];
	}

	_fieldEditor = fieldEditor;

	if (self.fieldEditor != nil)
	{
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(fieldEditorFrameDidChangeNotification:)
													 name:NSViewFrameDidChangeNotification
												   object:self.fieldEditor];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(fieldEditorTextDidChange:)
													 name:NSTextDidChangeNotification
												   object:self.fieldEditor];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(fieldEditorTextDidEndEditing:)
													 name:NSTextDidEndEditingNotification
												   object:self.fieldEditor];
		[fieldEditor addObserver:self
					  forKeyPath:@"delegate"
						 options:NSKeyValueObservingOptionInitial
						 context:FieldEditorDelegateContext];
	}
}

- (void)setSuggestedItems:(NSArray*)items
{
	[self willChangeValueForKey:@"suggestedItems"];
	_suggestedItems = items;
	[self didChangeValueForKey:@"suggestedItems"];
	[self layout];

	if (self.suggestedItems.count > 0)
	{
		if (self.searchMode)
		{
			[self.itemsView clearHighlighting];
		}
		else
		{
			[self.itemsView highlightIndex:0];
		}
	}
	else
	{
		[self hideWindow:nil];
	}
}

- (void)refreshSuggestedItems
{
	NSString *s = self.fieldEditor.string;
	[self.delegate autocomplete:self refreshSuggestedItemsForString:s];
}

- (NSString*)titleForItem:(id)item
{
	NSString *title = nil;

	if ([self.delegate respondsToSelector:@selector(autocomplete:titleForItem:)])
	{
		title = [self.delegate autocomplete:self titleForItem:item];
	}
	else if ([item isKindOfClass:[NSString class]])
	{
		title = item;
	}
	else
	{
		title = [item description];
	}

	return title;
}

- (void)updateFieldEditor
{
	if (self.searchMode)
	{
		return;
	}

	if (self.originalInput == nil)
	{
		return;
	}

	id item = self.itemsView.selectedItem;

	if (item != nil)
	{
		NSString *input = self.originalInput;
		NSString *title = [self titleForItem:item];

		if ([title hasPrefix:input])
		{
			self.fieldEditor.string = title;
			self.fieldEditor.selectedRange = NSMakeRange(input.length, title.length - input.length);
		}
	}
	else
	{
		// Restore the original input
		NSText *fieldEditor = self.fieldEditor;
		fieldEditor.string = self.originalInput;
	}
}

- (CGFloat)contentHeight
{
	NSView *h = self.customHeaderView != nil ? self.customHeaderView : self.headerView;
	NSView *f = self.customFooterView != nil ? self.customFooterView : self.footerView;
	CGFloat height = h.frame.size.height;
	height += self.itemsView.frame.size.height;
	height += f.frame.size.height;
	return height;
}

- (void)layout
{
	NSAssert(self.controlToComplete != nil, @"Autocomplete is not set to complete any control");

	[self.window.contentView layoutSubtreeIfNeeded];
	NSRect fieldEditorRect = self.fieldEditor.bounds;
	NSRect fieldEditorRectRelativeToWindow = [self.fieldEditor convertRect:fieldEditorRect toView:nil];
	NSRect fieldEditorRectRelativeToScreen = [self.fieldEditor.window convertRectToScreen:fieldEditorRectRelativeToWindow];
	NSRect frame = self.window.frame;

	// Respect minimum and maximum width.
	if (fieldEditorRectRelativeToScreen.size.width < self.window.minSize.width)
	{
		frame.size.width = self.window.minSize.width;
	}
	else if (fieldEditorRectRelativeToScreen.size.width > self.window.maxSize.width)
	{
		frame.size.width = self.window.maxSize.width;
	}
	else
	{
		frame.size.width = fieldEditorRectRelativeToScreen.size.width;
	}

	// Set window height to match content.
	frame.size.height = [self contentHeight];

	// Respect maximum height.
	if (self.itemsView.frame.size.height > self.window.maxSize.height)
	{
		frame.size.height = self.window.maxSize.height;
	}

	// Adjust the window origin (lower-left corner).
	frame.origin.x = fieldEditorRectRelativeToScreen.origin.x;
	frame.origin.y = fieldEditorRectRelativeToScreen.origin.y - frame.size.height - SpacingBetweenControlAndWindow;

	// Apply calculated frame if it differs from current frame.
	if (!NSEqualRects(self.window.frame, frame))
	{
		if ([self.delegate respondsToSelector:@selector(autocomplete:proposedRect:)])
		{
			frame = [self.delegate autocomplete:self proposedRect:frame];
		}

		[self.window setFrame:frame display:YES];
	}
}

- (void)fieldEditorFrameDidChangeNotification:(NSNotification*)notification
{
	[self layout];
}

- (void)controlWindowDidResignKey:(NSNotification*)notification
{
	[self hideWindow:nil];
}

- (void)showWindow:(id)sender
{
	if (self.suggestedItems.count > 0 && !NSEqualRects(self.window.frame, NSZeroRect))
	{
		if (!self.searchMode)
		{
			[self updateFieldEditor];
		}

		[self.controlWindow addChildWindow:self.window ordered:NSWindowAbove];
		[self layout];
        [self.window orderFront:nil];
		[self.window makeFirstResponder:self.itemsView];
	}
	else
	{
		[self hideWindow:sender];
	}
}

- (void)hideWindow:(id)sender
{
	if (self.window.isVisible)
	{
		[self.window orderOut:nil];
		[self.controlWindow removeChildWindow:self.window];
	}
}

- (void)fieldEditorTextDidChange:(NSNotification*)notification
{
	if (self.interceptor == nil)
	{
		return;
	}

	NSAssert(self.delegate != nil, @"Cannot autocomplete without delegate");
	NSAssert(notification.object == self.fieldEditor, @"Unexpected field editor");
	self.originalInput = self.fieldEditor.string;
    [self refreshSuggestedItems];

	if (self.fieldEditor.string.length > 0)
	{
		if (self.suggestedItems.firstObject == nil)
		{
			[self hideWindow:nil];
		}
	}
	else
	{
		[self hideWindow:nil];
	}
}

- (void)fieldEditorTextDidEndEditing:(NSNotification*)notification
{
	if (self.interceptor == nil)
	{
		return;
	}

	self.originalInput = nil;
	int movement = [[[notification userInfo] valueForKey:@"NSTextMovement"] intValue];

	// Check if editing ended with a keystroke that would apply a suggested item.
	if (movement == NSReturnTextMovement || movement == NSTabTextMovement || movement == NSBacktabTextMovement)
	{
		id item = self.itemsView.selectedItem;

		if (item != nil)
		{
			[self.delegate autocomplete:self didSelectItem:item];
		}
	}

	[self hideWindow:nil];
}

- (void)itemsView:(GDCAutocompleteItemsView*)view willDisplayCell:(NSCell*)cell atIndex:(NSUInteger)index
{
	id item = cell.representedObject;
	NSString *title = [self titleForItem:item];
	cell.stringValue = title;
}

- (void)itemsView:(GDCAutocompleteItemsView*)view updateFieldEditorForItemAtIndex:(NSUInteger)index
{
	if (self.window.isVisible && !self.searchMode)
	{
		[self updateFieldEditor];
	}
}

// Called by field editor via FieldEditorDelegateInterceptor.
- (BOOL)textView:(NSTextView*)aTextView doCommandBySelector:(SEL)aSelector
{
	if (aSelector == @selector(cancelOperation:) && !self.window.isVisible)
	{
		// Handle cancelOperation: to dismiss the window only when it's visible.
		// Otherwise let the real delegate handle it.
		return NO;
	}
	else if (aSelector == @selector(moveUp:) && !self.window.isVisible)
	{
		return NO;
	}
	else if (aSelector == @selector(moveDown:) && !self.window.isVisible)
	{
        if (self.suggestedItems.firstObject == nil)
        {
            return NO;
        }

        [self showWindow:nil];
        return YES;
	}

	return [self tryToPerform:aSelector with:aTextView];
}

- (void)deleteBackward:(id)sender
{
    [self.fieldEditor deleteBackward:sender];
    [self.itemsView clearHighlighting];
}

- (void)cancelOperation:(id)sender
{
	[self.itemsView clearHighlighting];
	[self hideWindow:sender];
}

- (void)complete:(id)sender
{
	if (self.window.isVisible)
	{
		[self.itemsView clearHighlighting];
		[self hideWindow:nil];
	}
	else
	{
		[self refreshSuggestedItems];
		[self showWindow:sender];

		if (self.itemsView.selectedItem == nil)
		{
			[self.itemsView highlightIndex:0];
		}
	}
}

- (void)moveDown:(id)sender
{
	if (self.window.isVisible)
	{
		[self.itemsView moveDown:sender];
	}
}

- (void)moveUp:(id)sender
{
	if (self.window.isVisible)
	{
		[self.itemsView moveUp:sender];
	}
}

- (void)observeValueForKeyPath:(NSString*)keyPath
					  ofObject:(id)object
						change:(NSDictionary*)change
					   context:(void*)context
{
	if (context == FieldEditorDelegateContext)
	{
		NSAssert(self.fieldEditor == object, @"Unexpected field editor");
		id d = [object valueForKeyPath:keyPath];

		if (d != nil && d == self.interceptor)
		{
			// Ignore recursive invocation.
		}
		else if (d == self.controlToComplete)
		{
			// This applies to controls such as NSTextField, NSSearchField, and cell-based NSTableView.
			self.interceptor = [[GDCAutocompleteFieldEditorDelegateInterceptor alloc] initWithAutocomplete:self delegate:d];
			self.fieldEditor.delegate = self.interceptor;
		}
		else if ([self.controlToComplete containsSubview:object])
		{
			// This applies to controls such as view-based NSTableView.
			self.interceptor = [[GDCAutocompleteFieldEditorDelegateInterceptor alloc] initWithAutocomplete:self delegate:d];
			self.fieldEditor.delegate = self.interceptor;
		}
		else if (d != nil)
		{
			// Field editor is being used for a control we're not completing.
			self.interceptor = nil;
		}
		else
		{
			// Leave self.interceptor intact when d == nil.
		}
	}
	else if (context == AttachedControlHiddenContext)
	{
		if (![[object valueForKey:keyPath] boolValue])
		{
			[self hideWindow:nil];
		}
	}
	else if (context == AttachedControlEnabledContext)
	{
		if (![[object valueForKey:keyPath] boolValue])
		{
			[self hideWindow:nil];
		}
	}
	else if (context == AttachedControlWindowContext)
	{
		NSWindow *w = [object valueForKeyPath:keyPath];

		if (w == self.controlWindow)
		{
			// No change.
			return;
		}

		if (self.controlWindow != nil)
		{
			// Cleanup.
			self.fieldEditor = nil;
			[[NSNotificationCenter defaultCenter] removeObserver:self
															name:NSWindowDidResignKeyNotification
														  object:self.controlWindow];

			if (self.window.parentWindow != nil)
			{
				[self.controlWindow removeChildWindow:self.window];
			}

			self.controlWindow = nil;
		}

		if (w != nil)
		{
			// Setup.
			self.controlWindow = w;
			self.fieldEditor = [w fieldEditor:YES forObject:self.controlToComplete];
			[[NSNotificationCenter defaultCenter] addObserver:self
													 selector:@selector(controlWindowDidResignKey:)
														 name:NSWindowDidResignKeyNotification
													   object:self.controlWindow];
		}
	}
	else
	{
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}

@end


text:
var PermissionsCollection = require('../collections/permissions');
var PermissionView = require('./permission');

module.exports = require('ridge/views/page').extend({
  elements: {
    container: '.collection.container'
  },

  subviews: {
    paginations: [ '.pagination', require('ridge/views/pagination'), { template: 'admin/pagination', multi: true } ],
    search: [ '.search', require('ridge/views/search') ]
  },

  initialize: function(options) {
    this.collection = new PermissionsCollection();

    this.listenTo(this.collection, 'reset', this.reset);

    this.listenTo(this.state, 'change:query', this.fetch);
  },

  fetch: function(state, query) {
    this.collection.fetch({ reset: true, data: query });
  },

  attach: function() {
    this.collection.reset({
      totalCount: this.state.get('totalCount'),
      permissions: this.state.get('permissions')
    }, { parse: true });
  },

  reset: function (models, options) {
    _.invokeMap(this.modelViews, 'remove');

    this.modelViews = [];

    models.each(this.renderModel.bind(this));
  },

  renderModel: function(model) {
    this.modelViews.push(new PermissionView({
      model: model,
      data: this.data,
    }).enter(this.elements.container));
  },
});

redpajama_set_name: RedPajamaGithub


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.path;

/**
 * Node representing a property, providing Hibernate Validator specific functionality.
 *
 * @author Gunnar Morling
 */
public interface PropertyNode extends jakarta.validation.Path.PropertyNode {

	/**
	 * @return Returns the value of the bean property represented by this node.
	 */
	Object getValue();
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>eContract Badak NGL</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

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

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="../../plugins/datatables/dataTables.bootstrap.css">

  <link rel="stylesheet" href="../../plugins/datepicker/datepicker3.css">

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

  <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">

    <?php include("p3-header.php");?>

          Contract Order
          Prebid Meeting

 Home

Pre-Bid Meeting

0001/BB41/2017-041

Upload

          <form class="form-horizontal">

Informasi Kontrak

                Lihat dokumen yang telah ter-upload disini

                    Nomor Risalah Pre-Bid Meeting:

0001/BB41/2017-532

                    Nomor Kontrak:

CA-17001

                    Tanggal:

17-01-2016

                    Judul Kontrak:

Pengadaan Sistem Informasi Kepegawaian

                    Jenis Kontrak:

Lump Sum (LS), Harga Satuan (HS), Gabungan LS & HS

                          Maksimum ukuran tiap file yang diupload adalah 50MB!

                              Judul Dokumen
                              Filename
                              Act
                              Keterangan

                              Risalah Pre-Bid Meeting
                              <input type="file" id="" accept=".pdf">

                              Breakdown Penawaran
                              <input type="file" id="" accept=".pdf">

                          Tambahkan dokumen pendukung lainnya melalui kolom berikut.

                          Judul Dokumen :

                            <input id="inputJudulDokumen" type="text" class="input-sm form-control">

                          Filename :

                            <input id="inputFile" type="file" class="input-sm">

                          Keterangan :

                            <textarea id="inputKeterangan" rows="5" placeholder="Type Here.." class="form-control" style="resize:none"></textarea>

                        <button type="button" class="btn btn-primary btn-xs pull-right" id="btnAdd"> Add</button>

              <button type="button" class="btn btn-default btn-sm pull-right" style="margin-right: 5px;" data-toggle="modal" data-target="#uploadModal">
               Upload
              </button>

                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×</button>

Are You Sure?

Pastikan file pendukung yang Anda upload telah sesuai. Anda TIDAK DAPAT merubah Dokumen Pre-Bid Meeting dan Breakdown Anggaran setelah melakukan proses ini.

                      <button type="button" class="btn btn-sm pull-left" data-dismiss="modal">Close</button>
                      <button type="submit" class="btn btn-sm btn-success">Yes, I Want to Upload It</button>

                <button type="button" class="btn btn-default btn-sm pull-right" style="margin-right: 5px;">
                  Back
                </button>

          </form>

      Copyright © 2017  PT Badak NGL. All rights
      reserved.

Recent Activity

Langdon's Birthday

Will be 23 on April 24th

Frodo Updated His Profile

New phone +1(800)555-1234

Nora Joined Mailing List

nora@example.com

Cron Job 254 Executed

Execution time 5 seconds

Tasks Progress

                  Custom Template Design
                  70%

                  Update Resume
                  95%

                  Laravel Integration
                  50%

                  Back End Framework
                  68%

Stats Tab Content

          <form method="post">

General Settings

                Report panel usage
                <input type="checkbox" class="pull-right" checked>

                Some information about this general settings option

                Allow mail redirect
                <input type="checkbox" class="pull-right" checked>

                Other sets of options are available

                Expose author name in posts
                <input type="checkbox" class="pull-right" checked>

                Allow the user to show his name in blog posts

Chat Settings

                Show me as online
                <input type="checkbox" class="pull-right" checked>

                Turn off notifications
                <input type="checkbox" class="pull-right">

                Delete chat history

          </form>


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

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>

      <title>www.karolisram.com</title>

   <link>http://www.karolisram.com/</link>
   <description>Curious about Machine Learning, Data Analytics, E-commerce.</description>
   <language>en-uk</language>
   <managingEditor> Karolis Ramanauskas</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />

	<item>
	  <title>Circle made out of squares 🔴</title>
	  <link>//circle-out-of-rectangles-magic-with-d3-js/</link>
	  <author>Karolis Ramanauskas</author>
	  <pubDate>2017-02-10T16:16:00+00:00</pubDate>
	  <guid>//circle-out-of-rectangles-magic-with-d3-js/</guid>
	  <description><![CDATA[

Today I saw a neat way of drawing circles out of squares. Then one thing led another, and I've got a colorful animation built with D3.js demonstrating just that.

If you are curious how it was built and how the code works, I have left detailed comments in the code pen. You can also fork the pen to make your own alterations such as try out the animation with a different number of circles, zoom options,  different delays and animation speeds and so on. Have fun!

See the Pen Circle out of squares with D3.js by Karolis (@karolis) on CodePen.

	  ]]></description>
	</item>

</channel>
</rss>


text:
package net.tmclean.rna.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class MethodBuilder extends Builder<MethodBuilder, ClassBuilder>
{
	private CtClass cClass           = null;
	private String  name             = null;
	private CtClass returnType       = CtClass.voidType;
	private List<CtClass> parameters = new ArrayList<>( 0 );
	private String src               = null;

	private Map<String, Integer> paramOrderMap = new HashMap<>();
	private Map<Integer, String> paramInvOrderMap = new HashMap<>();

	private ClassBuilder classBuilder = null;
	private CtMethod method = null;

	public MethodBuilder( ClassBuilder classBuilder )
	{
		super( classBuilder.getPool() );

		logger.debug( "Creating new MethodBuilder for class" );

		this.classBuilder = classBuilder;
		this.cClass = this.classBuilder.getCTClass();
	}

	public MethodBuilder named( String name )
	{
		logger.debug( "Setting method name to {}", name );

		this.name = name;
		return this;
	}

	public MethodBuilder returns( Class<?> returnType ) throws NotFoundException
	{
		logger.debug( "Setting return type to {}", returnType.getName() );

		this.returnType = getPool().get( returnType.getName() );
		return this;
	}

	public MethodBuilder takes( String name, Class<?> paramType ) throws NotFoundException
	{
		logger.debug( "Adding method parameter with name {} and type {}", name, paramType.getName() );

		this.parameters.add( getPool().get( paramType.getName() ) );

		int ordinal = paramOrderMap.size();

		logger.debug( "Method parameter {} has ordinal {}", name, ordinal );

		this.paramOrderMap.put( name, ordinal );
		this.paramInvOrderMap.put( ordinal, name );

		return this;
	}

	public MethodBuilder withSource( String src )
	{
		logger.debug( "Setting method soruce {}", src );

		this.src = src;
		return this;
	}

	public MethodAnnotationBuilder annotatedBy( Class<?> annotationClass )
	{
		logger.debug( "Adding method annotation {}", annotationClass.getName() );

		return new MethodAnnotationBuilder( this, annotationClass );
	}

	public MethodParamAnnotationBuilder paramAnnotatedBy( String paramName, Class<?> annotationClass )
	{
		logger.debug( "Adding annotation {} to parameter {}", annotationClass.getName(), paramName );

		return new MethodParamAnnotationBuilder( this, paramName, annotationClass );
	}

	public MethodBuilder build() throws CannotCompileException
	{
		logger.debug( "Building method" );

		CtClass[] params = parameters.toArray( new CtClass[]{} );
		method = new CtMethod( returnType, name, params, cClass );
		method.setModifiers( getModifier() );
		method.setBody( src );

		return this;
	}

	@Override
	public ClassBuilder apply() throws CannotCompileException, NotFoundException
	{
		logger.debug( "Adding method to class" );

		cClass.addMethod( method );

		return this.classBuilder;
	}

	public CtClass getCTClass()
	{
		return this.cClass;
	}

	public CtMethod getCTMethod()
	{
		return this.method;
	}

	public int getParamOrdinal( String name )
	{
		logger.debug( "Attempting to find ordinal for parameter {}", name );

		int ordinal = this.paramOrderMap.get( name );

		logger.debug( "Parameter {} has ordinal {}", name, ordinal );

		return ordinal;
	}

	public String getParamAtOrdinal( int ordinal )
	{
		logger.debug( "Attempting to find ordinal at {}", ordinal );

		String param = this.paramInvOrderMap.get( ordinal );

		logger.debug( "Parameter at ordinal {} is named {}", ordinal, name );

		return param;
	}

	public int getNumParams()
	{
		return this.paramOrderMap.size();
	}
}


text:
package unluac.decompile.expression;

import unluac.decompile.Declaration;
import unluac.decompile.Decompiler;
import unluac.decompile.Output;
import unluac.decompile.Walker;

public class LocalVariable extends Expression {

  private final Declaration decl;

  public LocalVariable(Declaration decl) {
    super(PRECEDENCE_ATOMIC);
    this.decl = decl;
  }

  @Override
  public void walk(Walker w) {
    w.visitExpression(this);
  }

  @Override
  public int getConstantIndex() {
    return -1;
  }

  @Override
  public boolean isDotChain() {
    return true;
  }

  @Override
  public void print(Decompiler d, Output out) {
    out.print(decl.name);
  }

  @Override
  public boolean isBrief() {
    return true;
  }

}


text:
<div class="col-sm-<?php echo $content_width; ?> customer-greeting">

    <?php echo $customer_greeting; ?>


text:
package org.datavec.api.transform.transform.doubletransform;

import lombok.Data;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.transform.metadata.DoubleMetaData;
import org.datavec.api.writable.DoubleWritable;
import org.datavec.api.writable.Writable;
import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties;
import org.nd4j.shade.jackson.annotation.JsonProperty;

@Data
@JsonIgnoreProperties({"ratio", "inputSchema", "columnNumber"})
public class MinMaxNormalizer extends BaseDoubleTransform {

    protected final double min;
    protected final double max;
    protected final double newMin;
    protected final double newMax;
    protected final double ratio;

    public MinMaxNormalizer(String columnName, double min, double max) {
        this(columnName, min, max, 0, 1);
    }

    public MinMaxNormalizer(@JsonProperty("columnName") String columnName, @JsonProperty("min") double min,
                    @JsonProperty("max") double max, @JsonProperty("newMin") double newMin,
                    @JsonProperty("newMax") double newMax) {
        super(columnName);
        this.min = min;
        this.max = max;
        this.newMin = newMin;
        this.newMax = newMax;
        this.ratio = (newMax - newMin) / (max - min);
    }

    @Override
    public Writable map(Writable writable) {
        double val = writable.toDouble();
        if (Double.isNaN(val))
            return new DoubleWritable(0);
        return new DoubleWritable(ratio * (val - min) + newMin);
    }

    @Override
    public ColumnMetaData getNewColumnMetaData(String newColumnName, ColumnMetaData oldColumnMeta) {
        return new DoubleMetaData(newColumnName, newMin, newMax);
    }

    @Override
    public String toString() {
        return "MinMaxNormalizer(min=" + min + ",max=" + max + ",newMin=" + newMin + ",newMax=" + newMax + ")";
    }

    /**
     * Transform an object
     * in to another object
     *
     * @param input the record to transform
     * @return the transformed writable
     */
    @Override
    public Object map(Object input) {
        Number n = (Number) input;
        double val = n.doubleValue();
        if (Double.isNaN(val))
            return new DoubleWritable(0);
        return ratio * (val - min) + newMin;
    }
}


text:
// Copyright (c) Ratish Philip
//
//
// 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.
//
// This file is part of the CompositionProToolkit project:
// https://github.com/ratishphilip/CompositionProToolkit
//
// CompositionProToolkit v1.0.1
//

using System;
using System.Text.RegularExpressions;
using CompositionProToolkit.Win2d;
using CompositionProToolkit.Win2d.Core;
using CompositionProToolkit.Win2d.Geometry.Brush;
using CompositionProToolkit.Win2d.Geometry.Stroke;
using CompositionProToolkit.Win2d.Parsers;
using Microsoft.Graphics.Canvas;

namespace CompositionProToolkit.Win2d.Geometry.Stroke
{
    /// <summary>
    /// Represents a Stroke Element
    /// </summary>
    internal sealed class CanvasStrokeElement : AbstractCanvasStrokeElement
    {
        #region Fields

        private float _width;
        private ICanvasBrushElement _brush;
        private ICanvasStrokeStyleElement _style;
        private int _widthValidationCount;

        #endregion

        #region Construction / Initialization

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="match">Match object</param>
        public CanvasStrokeElement(Match match)
        {
            _width = 1f;
            _brush = null;
            _style = null;
            _widthValidationCount = 0;

            Initialize(match);
        }

        #endregion

        #region APIs

        /// <summary>
        /// Creates the ICanvasStroke from the parsed data
        /// </summary>
        /// <returns>ICanvasStroke</returns>
        public override ICanvasStroke CreateStroke(ICanvasResourceCreator resourceCreator)
        {
            return new CanvasStroke(_brush.CreateBrush(resourceCreator), _width, _style.Style);
        }

        #endregion

        #region Helpers

        /// <summary>
        /// Gets the Stroke Element Attributes from the Match
        /// </summary>
        /// <param name="match">Match object</param>
        protected override void GetAttributes(Match match)
        {
            // Stroke Width
            var group = match.Groups["StrokeWidth"];
            Single.TryParse(group.Value, out _width);
            // Sanitize by taking the absolute value
            _width = Math.Abs(_width);

            _widthValidationCount = RegexFactory.ValidationRegex.Replace(group.Value, String.Empty).Length;

            // Stroke Brush
            group = match.Groups["CanvasBrush"];
            if (group.Success)
            {
                _brush = CanvasBrushParser.Parse(group.Value);
            }

            // If the ICanvasBrushElement was not created, then the ICanvasStroke cannot be created
            if (_brush == null)
            {
                throw new NullReferenceException($"Unable to create a valid ICanvasBrush for the " +
                                                 $"ICanvasStroke with the following Brush data - '{group.Value}'");
            }

            // Stroke Style
            _style = CanvasStrokeStyleParser.Parse(match);
        }

        /// <summary>
        /// Gets the number of non-whitespace characters in the data
        /// </summary>
        protected override void Validate()
        {
            // Add 2 to the Validation Count to include the stroke command 'ST'
            ValidationCount += 2;
            // StrokeWidth Validation Count
            ValidationCount += _widthValidationCount;
            // Stroke Brush Validation Count
            if (_brush != null)
            {
                ValidationCount += _brush.ValidationCount;
            }
            // Stroke Style Validation Count
            if (_style != null)
            {
                ValidationCount += _style.ValidationCount;
            }
        }

        #endregion
    }
}


text:
@(title: String, module: String = "scrupal")(initScript: play.twirl.api.Html)(content: play.twirl.api.Html)(implicit context : scrupal.controllers.Context)
@import scrupal.views.html
@import play.twirl.api.Html
@import scrupal.controllers.routes.Assets
@defining[Html](Html(initScript.body)) { init: Html ⇒
@html.basicPage(title) @{init}  {
<body ng-controller="scrupal" ng-show="page_is_ready">
<div id="@module" class="container">
@content
@html.debug()
</div>
<script lang="javascript">
  var scrupal_module_to_load="@module";
</script>
<script data-main="@Assets.js_s("require-data-main.js")" type="text/javascript" src="@Assets.resolve("lib/requirejs/require.js")"></script>
</body>
}
}


text:
read -r STREAMNUM < .testrepository/next-stream
STREAMNUM=$(( $STREAMNUM-1 ))
cat .testrepository/$STREAMNUM | subunit-1to2 | subunit2junitxml > junit.xml


text:
<!--
    Copyright (c) 2015, 2016 Automation RockStars Ltd.
    All rights reserved. This program and the accompanying materials
    are made available under the terms of the Apache License v2.0
    which accompanies this distribution, and is available at
    http://www.apache.org/licenses/LICENSE-2.0

    Contributors:
        Automation RockStars - initial API and implementation
 -->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.automationrockstars</groupId>
        <artifactId>armor</artifactId>
        <version>2.0.4-SNAPSHOT</version>
    </parent>
    <artifactId>design</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>gir</module>
        <module>gir-data</module>
        <module>gir-cli</module>
        <module>gir-webdriver</module>
        <module>gireat</module>
        <module>gir-rest</module>
        <module>gir-mobile</module>
        <module>webdriver-sikulix-driver</module>
        <module>gir-screenplay</module>
    </modules>

    <build>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>

    </build>
</project>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/batch"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:batch="http://www.springframework.org/schema/batch"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:p="http://www.springframework.org/schema/p"
             xmlns:mongo="http://www.springframework.org/schema/data/mongo"
             xmlns:util="http://www.springframework.org/schema/util"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:elasticsearch="http://www.pilato.fr/schema/elasticsearch"
             xmlns:jee="http://www.springframework.org/schema/jee"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/util
			http://www.springframework.org/schema/util/spring-util.xsd
            http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

<!-- Configuration when using replicaSet -->
<!-- 	<mongo:mongo id="mongo" replica-set="${mongo.hosts}"/> -->

	<beans:bean id="mongo" class="com.store.catalog.mongo.config.CatalogMongoFactoryBean">
		<beans:property name="host" value="${mongo.host}" />
		<beans:property name="portAsString" value="${mongo.port}" />
	</beans:bean>

	<mongo:db-factory id="mongoDbFactory"
                  dbname="${mongo.db.name}"
                  mongo-ref="mongo"
                  />

</beans:beans>


text:
/* @LICENSE(MUSLC_MIT) */

#include "pthread_impl.h"
#include <semaphore.h>

static struct chain {
	struct chain *next;
	sem_t sem, sem2;
} *head, *cur;

static void (*callback)(void *), *context;
static int chainlen;
static sem_t chainlock, chaindone;
static pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;

static void handler(int sig, siginfo_t *si, void *ctx)
{
	struct chain ch;
	pthread_t self = __pthread_self();
	int old_errno = errno;

	if (chainlen == libc.threads_minus_1) return;

	sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});

	/* Threads which have already decremented themselves from the
	 * thread count must not act. Block further receipt of signals
	 * and return. */
	if (self->dead) {
		memset(&((ucontext_t *)ctx)->uc_sigmask, -1, 8);
		errno = old_errno;
		return;
	}

	sem_init(&ch.sem, 0, 0);
	sem_init(&ch.sem2, 0, 0);

	while (sem_wait(&chainlock));
	ch.next = head;
	head = &ch;
	if (++chainlen == libc.threads_minus_1) sem_post(&chaindone);
	sem_post(&chainlock);

	while (sem_wait(&ch.sem));
	callback(context);
	sem_post(&ch.sem2);
	while (sem_wait(&ch.sem));

	errno = old_errno;
}

void __synccall(void (*func)(void *), void *ctx)
{
	pthread_t self;
	struct sigaction sa;
	struct chain *next;
	uint64_t oldmask;

	if (!libc.threads_minus_1) {
		func(ctx);
		return;
	}

	pthread_rwlock_wrlock(&lock);

	__syscall(SYS_rt_sigprocmask, SIG_BLOCK, SIGALL_SET,
		&oldmask, __SYSCALL_SSLEN);

	sem_init(&chaindone, 0, 0);
	sem_init(&chainlock, 0, 1);
	chainlen = 0;
	callback = func;
	context = ctx;

	sa.sa_flags = SA_SIGINFO | SA_RESTART;
	sa.sa_sigaction = handler;
	sigfillset(&sa.sa_mask);
	__libc_sigaction(SIGSYNCCALL, &sa, 0);

	self = __pthread_self();
	sigqueue(self->pid, SIGSYNCCALL, (union sigval){0});
	while (sem_wait(&chaindone));

	for (cur=head; cur; cur=cur->next) {
		sem_post(&cur->sem);
		while (sem_wait(&cur->sem2));
	}
	func(ctx);

	for (cur=head; cur; cur=next) {
		next = cur->next;
		sem_post(&cur->sem);
	}

	sa.sa_flags = 0;
	sa.sa_handler = SIG_IGN;
	__libc_sigaction(SIGSYNCCALL, &sa, 0);

	__syscall(SYS_rt_sigprocmask, SIG_SETMASK,
		&oldmask, 0, __SYSCALL_SSLEN);

	pthread_rwlock_unlock(&lock);
}

void __synccall_lock()
{
	pthread_rwlock_rdlock(&lock);
}

void __synccall_unlock()
{
	pthread_rwlock_unlock(&lock);
}


text:
cask :v1 => 'scriptql' do
  version :latest
  sha256 :no_check

  url 'http://www.kainjow.com/downloads/ScriptQL_qlgenerator.zip'
  homepage 'http://www.kainjow.com/'
  license :unknown

  qlplugin 'ScriptQL.qlgenerator'
end


text:
module Day4 where

import           Data.Char              (chr, ord)
import           Data.List              (find, group, intercalate, sort, sortBy)
import           Data.Ord
import           Text.Megaparsec        hiding (Pos)
import           Text.Megaparsec.Lexer  hiding (space)
import           Text.Megaparsec.String

data Room =
  Room [Char]
       Int
       [Char]
  deriving (Show)

name :: Room -> String
name (Room n _ _) = n

sector :: Room -> Int
sector (Room _ s _) = s

roomsP :: Parser [Room]
roomsP = roomP `endBy` newline
  where
    roomP = Room <$> nameP <*> sect <*> checksum
    nameP = intercalate "-" <$> many lowerChar `endBy` char '-'
    sect = fromIntegral <$> integer
    checksum = char '[' *> many lowerChar <* char ']'

isReal :: Room -> Bool
isReal (Room name _ checksum) =
  map head (take 5 $ sortBy ordr $ group $ sort $ filter (/= '-') name) == checksum
  where
    ordr b a
      | comparing length a b == EQ = comparing head b a
      | otherwise = comparing length a b

part1 :: [Room] -> Int
part1 = sum . map sector . filter isReal

rot :: Int -> Char -> Char
rot _ '-' = ' '
rot n c = chr (a + ((ord c - a + n) `mod` (z - a + 1)))
  where
    a = ord 'a'
    z = ord 'z'

part2 :: [Room] -> Maybe Int
part2 = fmap sector . find (\r -> name r == "northpole object storage") . decrypt
  where
    decrypt = map (\(Room n s c) -> Room (map (rot s) n) s c)

main :: IO ()
main = do
  let inputFile = "input/day4.txt"
  input <- readFile inputFile
  let Right rooms = parse roomsP inputFile input
  print $ part1 rooms
  mapM_ print $ part2 rooms


text:
FITSIO.jl
=========

Flexible Image Transport System (FITS) support for Julia

[docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg
[docs-latest-url]: http://juliaastro.github.io/FITSIO.jl/latest/

[docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-stable-url]: http://juliaastro.github.io/FITSIO.jl/stable/

[![Build Status](https://img.shields.io/travis/JuliaAstro/FITSIO.jl.svg?style=flat-square&label=linux)](https://travis-ci.org/JuliaAstro/FITSIO.jl)
[![Build status](https://img.shields.io/appveyor/ci/kbarbary/fitsio-jl.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/kbarbary/fitsio-jl/branch/master)
[![Coverage Status](http://img.shields.io/coveralls/JuliaAstro/FITSIO.jl.svg?style=flat-square)](https://coveralls.io/r/JuliaAstro/FITSIO.jl?branch=master)

**Documentation:** http://juliaastro.github.io/FITSIO.jl/latest/

**License:** MIT


text:
using System.Collections.Generic;

namespace Orchard.Reports.Services {
    /// <summary>
    /// Service for handling reports. Reports provide user-accessible log-like functionality.
    /// </summary>
    /// <remarks>
    /// You can use <see cref="Orchard.Reports.Services.IReportsCoordinator"/> to create reports through a simplified interface.
    /// </remarks>
    public interface IReportsManager : ISingletonDependency {
        void Add(int reportId, ReportEntryType type, string message);
        int CreateReport(string title, string activityName);
        Report Get(int reportId);
        IEnumerable<Report> GetReports();
        void Flush();
    }
}


text:
package org.systemsbiology.addama.commons.httpclient.support;

import org.apache.commons.httpclient.HttpMethod;

import java.io.InputStream;

/**
 * @author hrovira
 */
public abstract class InputStreamResponseCallback implements ResponseCallback {

    public Object onResponse(int statusCode, HttpMethod method) throws HttpClientResponseException {
        try {
            InputStream inputStream = method.getResponseBodyAsStream();
            return onResponse(statusCode, method, inputStream);
        } catch (Exception e) {
            throw new HttpClientResponseException(statusCode, method, e);
        }
    }

    public abstract Object onResponse(int statusCode, HttpMethod method, InputStream inputStream) throws Exception;

}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Lender.Slos.DataInterchange.Moles</name>
    </assembly>
    <members>
        <member name="T:Lender.Slos.DataInterchange.Moles.MExport">
            Mole type of <see cref="T:Lender.Slos.DataInterchange.Export"/>
            .
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MExport.#ctor">
            Initializes a new mole
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MExport.#ctor(Lender.Slos.DataInterchange.Export)">
            Initializes a new mole for the given instance
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MExport.BehaveAsCurrent">
            Assigns the 'Current' behavior for all methods of the moled type
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MExport.BehaveAsNotImplemented">
            Assigns the 'NotImplemented' behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.Behavior">
            Assigns the behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.Constructor">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Export.#ctor"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.DataGet">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Export.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.DataSetString">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Export.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.SaveFileInfo">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Export.Save(System.IO.FileInfo)"/>

        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.MExport.AllInstances">
            Define moles for all instances members
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.AllInstances.DataGet">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Export.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.AllInstances.DataSetString">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Export.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MExport.AllInstances.SaveFileInfo">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Export.Save(System.IO.FileInfo)"/>

        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.MFileSystem">
            Mole type of <see cref="T:Lender.Slos.DataInterchange.FileSystem"/>
            .
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MFileSystem.#ctor">
            Initializes a new instance
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MFileSystem.BehaveAsCurrent">
            Assigns the 'Current' behavior for all methods of the moled type
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MFileSystem.BehaveAsNotImplemented">
            Assigns the 'NotImplemented' behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MFileSystem.Behavior">
            Assigns the behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MFileSystem.ReadAllTextFileInfo">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.FileSystem.ReadAllText(System.IO.FileInfo)"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MFileSystem.WriteAllTextFileInfoString">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.FileSystem.WriteAllText(System.IO.FileInfo,System.String)"/>

        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.MImport">
            Mole type of <see cref="T:Lender.Slos.DataInterchange.Import"/>
            .
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MImport.#ctor">
            Initializes a new mole
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MImport.#ctor(Lender.Slos.DataInterchange.Import)">
            Initializes a new mole for the given instance
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MImport.BehaveAsCurrent">
            Assigns the 'Current' behavior for all methods of the moled type
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.MImport.BehaveAsNotImplemented">
            Assigns the 'NotImplemented' behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.Behavior">
            Assigns the behavior for all methods of the moled type
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.Constructor">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Import.#ctor"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.DataGet">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Import.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.DataSetString">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Import.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.LoadFileInfo">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Import.Load(System.IO.FileInfo)"/>

        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.MImport.AllInstances">
            Define moles for all instances members
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.AllInstances.DataGet">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Import.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.AllInstances.DataSetString">
            Sets the mole of <see cref="P:Lender.Slos.DataInterchange.Import.Data"/>

        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.MImport.AllInstances.LoadFileInfo">
            Sets the mole of <see cref="M:Lender.Slos.DataInterchange.Import.Load(System.IO.FileInfo)"/>

        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.SExport">
            Stub type of <see cref="T:Lender.Slos.DataInterchange.Export"/>
            .
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.SExport.#ctor">
            Initializes a new instance
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.SExport.InitializeStub">
            Initializes a new instance of type SExport
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.SExport.CallBase">
            Gets or sets a value that indicates if the base method should be called instead of the fallback behavior
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.SExport.InstanceBehavior">
            Gets or sets the instance behavior.
        </member>
        <member name="T:Lender.Slos.DataInterchange.Moles.SImport">
            Stub type of <see cref="T:Lender.Slos.DataInterchange.Import"/>
            .
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.SImport.#ctor">
            Initializes a new instance
        </member>
        <member name="M:Lender.Slos.DataInterchange.Moles.SImport.InitializeStub">
            Initializes a new instance of type SImport
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.SImport.CallBase">
            Gets or sets a value that indicates if the base method should be called instead of the fallback behavior
        </member>
        <member name="P:Lender.Slos.DataInterchange.Moles.SImport.InstanceBehavior">
            Gets or sets the instance behavior.
        </member>
    </members>
</doc>


text:
package org.boon.di;

public class Bacon extends FoodImpl implements Food {
    boolean crispy;
    String tag;
}


text:
(function (flow, $, d3, Backbone) {
    "use strict";

    // View for displaying a collection that enables
    // setting it as active and/or the save location
    // for analyses and datasets
    flow.VariableView = Backbone.View.extend({
        tagName: 'li',
        className: 'list-group-item',

        events: {
            'click .edit': function () {
                this.editView.model = this.model;
                this.editView.render();
            },

            'click .delete': function () {
                this.collection.remove(this.model);
            }
        },

        initialize: function (settings) {
            this.editView = settings.editView;
            this.collection = settings.collection;
            this.model.on('change', this.render, this);
        },

        render: function () {
            this.$el.html($('#variable-template').html());
            this.$('.name').text(this.model.get('name') + ' [' + this.model.get('type') + ':' + this.model.get('format') + ']');
            return this;
        }
    });

}(window.flow, window.$, window.d3, window.Backbone));


text:
package wechat4j.message;

import java.io.Serializable;

/**
 * News message
 *
 * @author renbin.fang.
 * @date 2014/8/26.
 */
public class NewsMessage implements Serializable {
    private String title;
    private String description;
    private String picUrl;
    private String url;

    /**
     * Constructor
     */
    public NewsMessage() {
    }

    /**
     * Constructor
     *
     * @param title
     * @param description
     * @param picUrl
     * @param url
     */
    public NewsMessage(String title, String description, String picUrl, String url) {
        this.title = title;
        this.description = description;
        this.picUrl = picUrl;
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public String toString() {
        return "NewsMessage{" +
                "title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", picUrl='" + picUrl + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}


text:
import React, { Component } from "react";
import axios from "axios";
import _ from "lodash";
import CreateTodo from "./todo/create-todo";
import TodoList from "./todo/todo-list";

const BASE_URL = "http://localhost:3000";
var todos = [];

export default class TodoComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todos
    };
    this.init = this.init.bind(this);
  }

  componentDidMount() {
    this.init();
  }

  init() {
    var self = this;
    axios
      .get(BASE_URL + "/todos/getAll")
      .then(function(response) {
        self.setState({ todos: response.data.result.Items });
      })
      .catch(function(error) {
        self.setState({ todos: [{}, {}] });
        console.log(error);
      });
  }

  render() {
    return (

My Todo List

        <CreateTodo createTask={this.createTask.bind(this)} />
        <TodoList
          todos={this.state.todos}
          toggleTask={this.toggleTask.bind(this)}
          saveTask={this.saveTask.bind(this)}
          deleteTask={this.deleteTask.bind(this)}
        />

    );
  }

  createTask(task) {
    var self = this;
    self.state.todos.unshift(task);
    self.setState({ todos: self.state.todos });
    axios
      .post(BASE_URL + "/todos", task)
      .then(function(response) {})
      .catch(function(error) {
        console.log(error);
      });
  }

  toggleTask(task) {
    const foundTodo = _.find(this.state.todos, todo => todo.id === task.id);
    foundTodo.isCompleted = !foundTodo.isCompleted;
    this.setState({ todos: this.state.todos });
    axios
      .put(BASE_URL + "/todos/status", {
        id: task.id,
        isCompleted: foundTodo.isCompleted
      })
      .then(function(response) {})
      .catch(function(error) {
        console.log(error);
      });
  }

  saveTask(oldTask, newTask) {
    var self = this;
    const foundTodo = _.find(self.state.todos, todo => todo.id === oldTask.id);
    foundTodo.task = newTask;
    self.setState({ todos: self.state.todos });
    axios
      .put(BASE_URL + "/todos/update", {
        id: oldTask.id,
        task: newTask
      })
      .then(function(response) {})
      .catch(function(error) {
        console.log(error);
      });
  }

  deleteTask(taskToDelete) {
    var self = this;
    _.remove(self.state.todos, todo => todo.id === taskToDelete.id);
    self.setState({ todos: self.state.todos });
    axios
      .delete(BASE_URL + "/todos/delete/" + taskToDelete.id)
      .then(function(response) {})
      .catch(function(error) {
        console.log(error);
      });
  }
}


text: default_app_config = 'spirit.topic.favorite.apps.SpiritTopicFavoriteConfig'


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('fundraising', '0001_squashed_0037_auto_20150709_1619'),
    ]

    operations = [
        migrations.AlterField(
            model_name='donation',
            name='donor',
            field=models.ForeignKey(to='fundraising.DjangoHero'),
        ),
    ]


text:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class EntrustResetupTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        Schema::table('assigned_roles', function (Blueprint $table) {
            $table->dropForeign('assigned_roles_user_id_foreign');
            $table->dropForeign('assigned_roles_role_id_foreign');
        });

        Schema::table('permission_role', function (Blueprint $table) {
            $table->dropForeign('permission_role_permission_id_foreign');
            $table->dropForeign('permission_role_role_id_foreign');
        });

        Schema::drop('assigned_roles');
        Schema::drop('permission_role');
        Schema::drop('roles');
        Schema::drop('permissions');

        // Create table for storing roles
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // Create table for associating roles to users (Many-to-Many)
        Schema::create('role_user', function (Blueprint $table) {
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('user_id')->references('id')->on('users')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->primary(['user_id', 'role_id']);
        });

        // Create table for storing permissions
        Schema::create('permissions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('display_name')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });

        // Create table for associating permissions to roles (Many-to-Many)
        Schema::create('permission_role', function (Blueprint $table) {
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')->references('id')->on('permissions')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')
                ->onUpdate('cascade')->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return  void
     */
    public function down()
    {
        Schema::drop('permission_role');
        Schema::drop('permissions');
        Schema::drop('role_user');
        Schema::drop('roles');
    }
}


text:
<?php

class FantasySwordWorld2Controller extends ControllerBase
{
    public function initialize()
    {
        parent::initialize();
        $this->view->setVar("pageTitle", 'FANTASY SWORD WORLD 2');
    }

    public function indexAction()
    {
        if ($this->request->isPost()) {
            if (empty($this->request->getPost("call_action"))) {
                // nothing to do
            } else {
                $callAction = $this->request->getPost("call_action");
                switch ($callAction) {
                    case 'generate_all':
                        // 生成する性別の取得
                        $gender = $this->__getGender();
                        $this->view->setVar('gender', $gender['body']);
                        $this->__generateNormalNameAction($gender['type']);
                        $this->__generateAnotherNameAction();
                        $this->__generatePersonalityAction();
                        break;
                    default:
                        // nothing to do.
                }
            }
        }
    }

    /**
     * @return array
     *
     * FIXME: gender model に移動
     */
    private function __getGender()
    {
        // ru語には女性苗字と男性苗字が存在するため、ここで男性女性をかならず決める
        $gender = (empty($this->request->getPost("gender")) ? '' : $this->request->getPost("gender"));
        if (empty($gender) || $gender == 'all') {
            $genderList = array('male', 'female');
            $gender = $genderList[mt_rand(0, count($genderList) - 1)];
        }
        $body = 'UNKNOWN';
        switch ($gender) {
            case 'male':
                $body = '男性';
                break;
            case 'female':
                $body = '女性';
                break;
            default:
                // nothing to do
        }
        return array('type' => $gender, 'body' => $body);
    }

    /**
     * @param string $gender
     */
    private function __generateNormalNameAction($gender = 'all')
    {
        $nation = (empty($this->request->getPost("nation")) ? '' : $this->request->getPost("nation"));
        // 姓名データ生成
        $model = new MasterNormalNames();
        $names = $model->findNormalNames(1, $nation, $gender);
        $this->view->setVar('normalNames', $names);
        // 処理の都合上ここで出自(parent)のデータ生成
        $model2 = new MasterNations();
        $parent = array(
            'father' => 'UNKNOWN',
            'mother' => 'UNKNOWN',
        );
        if ($nation != 'all') {
            $parentRecord = $model2->findFirst("nation_id = '$nation'");
            $parent = array(
                'father' => $parentRecord->body_ja,
                'mother' => $parentRecord->body_ja
            );
        } else {
            foreach ($names as $name) {
                // 0 or 1
                $hash = array(0, 1);
                $keys = array_rand($hash, 2);
                shuffle($keys);
                $fatherRecord = $model2->findFirst("nation_id = '" . $name['nation'][$keys[0]] . "'");
                $motherRecord = $model2->findFirst("nation_id = '" . $name['nation'][$keys[1]] . "'");
                $parent = array(
                    'father' => $fatherRecord->body_ja,
                    'mother' => $motherRecord->body_ja
                );
            }
        }
        $this->view->setVar('parent', $parent);
    }

    /**
     *
     */
    private function __generateAnotherNameAction()
    {
        $model = new MasterAnotherNames();
        $this->view->setVar('anotherNames', $model->findAnotherNames(1));
    }

    /**
     *
     */
    private function __generatePersonalityAction()
    {
        $model = new MasterPersonalities();
        $this->view->setVar('personalities', $model->findPersonalities(1));
    }

}


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>FANTASTIC SHOP</title>

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

    <link href="css/shop-homepage.css" rel="stylesheet">

    <link href="favicon.ico" rel="icon">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                FANTASTIC SHOP

                        ¿Quiénes somos?

                        Testimonios

                        Contacto

                        Acceder

		    		<form role="form">
		    			<fieldset>

Crea una cuenta nueva

                                <input type="text" name="name" id="name" class="form-control input-lg" placeholder="Nombre">

                                <input type="text" name="surname" id="surname" class="form-control input-lg" placeholder="Apellidos">

                                <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email">

		    					<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Contraseña">

                                <textarea rows="5" name="sentence" id="sentence" class="form-control input-lg" placeholder="Frase personal identificativa, única e intransferible"></textarea>

									Crear cuenta

						</fieldset>
					</form>

Copyright © Start Bootstrap & IPO USAL 2017


text:
layout: fullpage
title: CSS Scroll Snap Full page demo (pure HTML/CSS)
tags: [Demo]
share_image: https://i.imgur.com/hndMbNo.png
share_description: CSS Scroll Snap Full page demo
article_link: css-scroll-snap
demo_code_url: scroll-snap-full-screen
disable_default_css: true
---

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

                    Error:
                    Scroll Snap is not supported in the current browser.

                        jQuery Scrollify plugin is used instead of it

                    Read the article

                    Check the code on Github

Screen 1

                Scroll for more

Screen 2

Screen 3

                        Back to top

Screen 4

        Screen 1
        Screen 2
        Screen 3
        Screen 4