text:
enum
{
	kRS274InputUnitMilliMeter,
	kRS274InputUnitInch,
	kRS274MotionModeRapid,
	kRS274MotionModeFeed,
	kRS274DistanceModeAbsolute,
	kRS274DistanceModeIncremental,
};

@implementation RS274Interpreter
{
	long			modalInputUnit, modalMotionMode, modalDistanceMode;

	NSMutableArray* machineParameters;

	double xAxis, yAxis, zAxis, aAxis, bAxis, cAxis;
	double feedRate;

	NSMutableArray* machineCommands;
}

@synthesize machineCommands;

- (id) init
{
	if (!(self = [super init]))
		return nil;

	modalInputUnit = kRS274InputUnitMilliMeter;
	modalMotionMode = kRS274MotionModeRapid;
	modalDistanceMode = kRS274DistanceModeAbsolute;

	machineParameters = [[NSMutableArray alloc] initWithCapacity: 5400];

	for (int i = 0; i < 5400; ++i)
	{
		[machineParameters addObject: @0.0];
	}

	[machineParameters replaceObjectAtIndex: 5220 withObject: @1.0];

	machineCommands = [[NSMutableArray alloc] init];

	return self;
}

- (void) interpretCommandBlocks: (NSArray*) commandBlocks;
{
	for (NSArray* commandBlock in commandBlocks)
		[self interpretCommandBlock: commandBlock];
}

- (NSArray*) interpretComments: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretParameterSets: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretFeedRateModeCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretFeedRateCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretSpindleSpeedCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretSelectToolCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretChangeToolCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretSpindleCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretCoolantCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretOverrideCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretDwellCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretActivePlaneCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretLengthUnitCommands: (NSArray*) commands
{
	long i = 0;
	for (id obj in commands)
	{
		if ([obj isKindOfClass: [RS274Command class]])
		{
			RS274Command* cmd = obj;
			if ((cmd.commandLetter == 'G') && ([cmd.value isEqual: @20]))
			{
				modalInputUnit = kRS274InputUnitInch;
				break;
			}
			else if ((cmd.commandLetter == 'G') && ([cmd.value isEqual: @21]))
			{
				modalInputUnit = kRS274InputUnitMilliMeter;
				break;
			}
		}
		++i;
	}
	if (i != commands.count)
		commands = [commands arrayByRemovingObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(i, 1)]];
	return commands;
}

- (NSArray*) interpretRadiusCompensationCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretLengthCompensationCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretCoordinateSystemSelectionCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretPathControlModeCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretDistanceModeCommands: (NSArray*) commands
{
	long i = 0;
	for (id obj in commands)
	{
		if ([obj isKindOfClass: [RS274Command class]])
		{
			RS274Command* cmd = obj;
			if ((cmd.commandLetter == 'G') && ([cmd.value isEqual: @90]))
			{
				modalDistanceMode = kRS274DistanceModeAbsolute;
				break;
			}
			else if ((cmd.commandLetter == 'G') && ([cmd.value isEqual: @91]))
			{
				modalDistanceMode = kRS274DistanceModeIncremental;
				break;
			}
		}
		++i;
	}
	if (i != commands.count)
		commands = [commands arrayByRemovingObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(i, 1)]];
	return commands;
}

- (NSArray*) interpretRetractModeCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretHomeCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretCoordinateSystemChangeCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretAxisOffsetCommands: (NSArray*) commands
{
	return commands;
}

- (NSArray*) interpretModalMotionCommands: (NSArray*) commands
{
	while (1)
	{
		long i = 0;
		for (id obj in commands)
		{
			if ([obj isKindOfClass: [RS274Command class]])
			{
				RS274Command* cmd = obj;
				if ((cmd.commandLetter == 'G') && ([cmd.value isEqual: @0] || [cmd.value isEqual: @1]))
					break;
			}
			++i;
		}

		if (i >= [commands count])
			break;

		long cmdIndex = i;

		long whichCommand = [[[commands objectAtIndex: cmdIndex] value] integerValue];

		switch (whichCommand) {
			case 0:
				modalMotionMode = kRS274MotionModeRapid;
				break;
			case 1:
				modalMotionMode = kRS274MotionModeFeed;
				break;

			default:
				break;
		}

		commands = [commands arrayByRemovingObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(cmdIndex, 1)]];

	}
	return commands;

}

- (void) dispatchMotionCommand
{
	double speed = 0.0;

	switch (modalMotionMode) {
		case kRS274MotionModeRapid:
			speed = -1;
			break;
		case kRS274MotionModeFeed:
			speed = feedRate;
			break;

		default:
			break;
	}

	GMachineCommandMove* cmd = [[GMachineCommandMove alloc] initWithSpeed: speed x: xAxis y: yAxis z: zAxis a: aAxis b: bAxis c: cAxis];
	[machineCommands addObject: cmd];

}

- (NSArray*) interpretMotionTargetCommands: (NSArray*) commands
{
	long i = 0;
	BOOL motionTargetFound = NO;
	while (i < [commands count])
	{
		BOOL removeCommand = YES;
		id obj = [commands objectAtIndex: i];
		if ([obj isKindOfClass: [RS274Command class]])
		{
			double scale = 0.0;
			if (modalInputUnit == kRS274InputUnitInch)
				scale = 25.4;
			else if (modalInputUnit == kRS274InputUnitMilliMeter)
				scale = 1.0;
			else
				assert(0);

			int cmdLetter = [obj commandLetter];
			double value = scale*[[obj value] doubleValue];
			if (modalDistanceMode == kRS274DistanceModeAbsolute)
			{
				switch (cmdLetter)
				{
					case 'A':
						aAxis = value;
						break;
					case 'B':
						bAxis = value;
						break;
					case 'C':
						cAxis = value;
						break;
					case 'X':
						xAxis = value;
						break;
					case 'Y':
						yAxis = value;
						break;
					case 'Z':
						zAxis = value;
						break;
					default:
						removeCommand = NO;
						break;
				}
			}
			else if (modalDistanceMode == kRS274DistanceModeIncremental)
			{
				switch (cmdLetter)
				{
					case 'A':
						aAxis += value;
						break;
					case 'B':
						bAxis += value;
						break;
					case 'C':
						cAxis += value;
						break;
					case 'X':
						xAxis += value;
						break;
					case 'Y':
						yAxis += value;
						break;
					case 'Z':
						zAxis += value;
						break;
					default:
						removeCommand = NO;
						break;
				}
			}
			else
				assert(0);
		}
		else
			removeCommand = NO;

		if (removeCommand)
		{
			motionTargetFound = YES;
			commands = [commands arrayByRemovingObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(i, 1)]];

		}
		else
			++i;
	}

	if (motionTargetFound)
		[self dispatchMotionCommand];

	return commands;

}

- (NSArray*) interpretMotionCommands: (NSArray*) commands
{
	commands = [self interpretModalMotionCommands: commands];
	commands = [self interpretMotionTargetCommands: commands];
	return commands;
}

- (NSArray*) interpretStopCommands: (NSArray*) commands
{
	return commands;
}

- (id) interpretCommandBlock: (NSArray*) commands
{

	commands = [self interpretComments: commands];
	commands = [self interpretParameterSets: commands];
	commands = [self interpretFeedRateModeCommands: commands];
	commands = [self interpretFeedRateCommands: commands];
	commands = [self interpretSpindleSpeedCommands: commands];
	commands = [self interpretSelectToolCommands: commands];
	commands = [self interpretChangeToolCommands: commands];
	commands = [self interpretSpindleCommands: commands];
	commands = [self interpretCoolantCommands: commands];
	commands = [self interpretOverrideCommands: commands];
	commands = [self interpretDwellCommands: commands];
	commands = [self interpretActivePlaneCommands: commands];
	commands = [self interpretLengthUnitCommands: commands];
	commands = [self interpretRadiusCompensationCommands: commands];
	commands = [self interpretLengthCompensationCommands: commands];
	commands = [self interpretCoordinateSystemSelectionCommands: commands];
	commands = [self interpretPathControlModeCommands: commands];
	commands = [self interpretDistanceModeCommands: commands];
	commands = [self interpretRetractModeCommands: commands];
	commands = [self interpretHomeCommands: commands];
	commands = [self interpretCoordinateSystemChangeCommands: commands];
	commands = [self interpretAxisOffsetCommands: commands];
	commands = [self interpretMotionCommands: commands];
	commands = [self interpretStopCommands: commands];

	return nil;
}

@end

@implementation GMachineCommand

@end

@implementation GMachineCommandMove

@synthesize xTarget,yTarget,zTarget,aTarget,bTarget,cTarget,speed;

- (id) initWithSpeed:(double)s x:(double)x y:(double)y z:(double)z a:(double)a b:(double)b c:(double)c
{
	if (!(self = [super init]))
		return nil;

	speed = s;
	xTarget = x;
	yTarget = y;
	zTarget = z;
	aTarget = a;
	bTarget = b;
	cTarget = c;

	return self;
}

@end


text:
<?php

declare(strict_types=1);

namespace Cortex\Auth\Http\Middleware;

use Closure;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Contracts\Routing\ResponseFactory;

class Reauthenticate
{
    /**
     * The response factory instance.
     *
     * @var \Illuminate\Contracts\Routing\ResponseFactory
     */
    protected $responseFactory;

    /**
     * The URL generator instance.
     *
     * @var \Illuminate\Contracts\Routing\UrlGenerator
     */
    protected $urlGenerator;

    /**
     * Create a new middleware instance.
     *
     * @param \Illuminate\Contracts\Routing\ResponseFactory $responseFactory
     * @param \Illuminate\Contracts\Routing\UrlGenerator    $urlGenerator
     *
     * @return void
     */
    public function __construct(ResponseFactory $responseFactory, UrlGenerator $urlGenerator)
    {
        $this->responseFactory = $responseFactory;
        $this->urlGenerator = $urlGenerator;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @param string                   $type
     * @param int                      $timeout
     * @param bool                     $renew
     *
     * @return mixed
     */
    public function handle($request, Closure $next, string $type = 'password', int $timeout = null, bool $renew = false)
    {
        if ($this->shouldConfirmSession($request, $type, $timeout)) {
            if ($request->expectsJson()) {
                return $this->responseFactory->json([
                    'message' => trans('cortex/auth::common.password_required'),
                ], 423);
            }

            return $this->responseFactory->redirectGuest(
                $this->urlGenerator->route($request->route('accessarea').'.reauthentication.'.$type)
            );
        }

        ! $renew || $request->session()->put("auth.{$type}_confirmed_at", time());

        return $next($request);
    }

    /**
     * Determine if the confirmation timeout has expired.
     *
     * @param \Illuminate\Http\Request $request
     * @param string                   $type
     * @param int|null                 $timeout
     *
     * @return bool
     */
    protected function shouldConfirmSession($request, string $type = 'password', int $timeout = null)
    {
        $confirmedAt = time() - $request->session()->get("auth.{$type}_confirmed_at", 0);

        return $confirmedAt > config("auth.{$type}_timeout", $timeout ?? 10800);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main

// TODO implements these as parameters
//
// laser on command
// laser off command
// laser power
// power on delay

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"

	"github.com/eraclitux/cfgp"
)

var Version = "unknown-build"
var BuildTime = "unknown-time"

const (
	delayGcode     = "G4 P0.5"
	laserOnGcode   = "M3"
	laserOffGcode  = "M5 S0"
	plungeComment  = "; plunge"
	retractComment = "; Retract"
)

type Conf struct {
	Power   int  `cfgp:"power,% of laser power [0-100],"`
	Version bool `cfgp:"v,show version and exit,"`
}

// parsePower transform laser power from [0-100]% range
// to S[0-100] gcode parameter.
func parsePower(p int) (string, error) {
	if p < 0 || p > 100 {
		return "", fmt.Errorf("invalid power value: %d", p)
	}
	i := strconv.Itoa(p)
	return "S" + i, nil
}

func main() {
	c := Conf{}
	err := cfgp.Parse(&c)
	if err != nil {
		log.Fatal("Unable to parse configuration", err)
	}
	if c.Version {
		fmt.Println("to-laser - jscut post processor for Grbl laser cutters", Version, BuildTime)
		return
	}
	toPlunge := false
	toRetract := false
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		line := s.Text()
		if toPlunge {
			p, err := parsePower(c.Power)
			if err != nil {
				log.Fatalln(err)
			}
			fmt.Println(laserOnGcode, p)
			fmt.Println(delayGcode)
			toPlunge = false
		}
		if toRetract {
			fmt.Println(laserOffGcode)
			toRetract = false
		}
		matched, err := regexp.MatchString(plungeComment, line)
		if err != nil {
			log.Fatalln(err)
		}
		if matched {
			toPlunge = true
			continue
		}
		matched, err = regexp.MatchString(retractComment, line)
		if err != nil {
			log.Fatalln(err)
		}
		if matched {
			toRetract = true
			continue
		}
		// If line contains moves on Z axis skip it.
		matched, err = regexp.MatchString(".*Z.*", line)
		if err != nil {
			log.Fatalln(err)
		}
		if matched {
			continue
		}
		fmt.Println(line)
	}
	// Error parsing stdin.
	if err := s.Err(); err != nil {
		log.Fatalln(err)
	}
	// The End
	fmt.Println("M2")
}


text:
#import "CCScrollView.h"
#import "CCDirector.h"
#import "CGPointExtension.h"
#import "CCActionInterval.h"
#import "CCActionEase.h"
#import "CCActionInstant.h"
#import "CCResponderManager.h"
#import "CCTouch.h"
#if __CC_PLATFORM_IOS

// Includes for iOS
//#import "PlatformTouch+CC.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
#elif __CC_PLATFORM_ANDROID
#import "CCActivity.h"
#import "CCGestureListener.h"
// Includes for Mac
#elif __CC_PLATFORM_MAC

#endif

#pragma mark Constants

#define kCCScrollViewBoundsSlowDown 0.5
#define kCCScrollViewDeacceleration 0.95
#define kCCScrollViewVelocityLowerCap 20.0
#define kCCScrollViewAllowInteractionBelowVelocity 50.0
#define kCCScrollViewSnapDuration 0.4
#define kCCScrollViewSnapDurationFallOff 100.0
#define kCCScrollViewAutoPageSpeed 500.0
#define kCCScrollViewMaxOuterDistBeforeBounceBack 50.0
#define kCCScrollViewMinVelocityBeforeBounceBack 100.0

#define kCCScrollViewActionXTag 8080
#define kCCScrollViewActionYTag 8081

#pragma mark -
#pragma mark Helper classes

#if __CC_PLATFORM_IOS
@interface CCTapDownGestureRecognizer : UIGestureRecognizer
@end

@implementation CCTapDownGestureRecognizer

- (void)touchesBegan:(NSSet *)touches withEvent:(CCTouchEvent *)event
{
    if (self.state == UIGestureRecognizerStatePossible)
    {
        self.state = UIGestureRecognizerStateRecognized;
    }
}

@end

#endif

@interface CCMoveToX : CCActionInterval
{
	float _endPosition;
	float _startPos;
	void (^block)(void);
}
@end

@implementation CCMoveToX

-(id) initWithDuration: (CCTime) t positionX: (float) p callback:(void(^)(void))callback
{
	if( (self=[super initWithDuration: t]) ) {
		_endPosition = p;
		block = callback;
	}
	return self;
}

-(void) startWithTarget:(CCNode *)target
{
	[super startWithTarget:target];
	_startPos = target.position.x;
}

-(void) update: (CCTime) t
{
    CCNode *node = (CCNode*)_target;

    float positionDelta = _endPosition - _startPos;
    float x = _startPos + positionDelta * t;
    float y = node.position.y;

	node.position = ccp(x,y);
	block();
}
@end

@interface CCMoveToY : CCActionInterval
{
	float _endPosition;
	float _startPos;
	void (^block)(void);
}
@end

@implementation CCMoveToY

-(id) initWithDuration: (CCTime) t positionY: (float) p callback:(void(^)(void))callback
{
	if( (self=[super initWithDuration: t]) ) {
		_endPosition = p;
		block = [callback copy];
	}
	return self;
}

-(void) startWithTarget:(CCNode *)target
{
	[super startWithTarget:target];
	_startPos = target.position.y;
}

-(void) update: (CCTime) t
{
    CCNode *node = (CCNode*)_target;

    float positionDelta = _endPosition - _startPos;
    float y = _startPos + positionDelta * t;
    float x = node.position.x;

	node.position = ccp(x,y);
	block();
}
@end

#pragma mark -
#pragma mark CCScrollView

@implementation CCScrollView {
	BOOL _decelerating;

#if __CC_PLATFORM_MAC
	CGPoint _lastPosition;
#elif __CC_PLATFORM_ANDROID
    CCGestureListener *_listener;
    AndroidGestureDetector *_detector;
    CGPoint _rawScrollTranslation;
#endif
}

#pragma mark Initializers

- (id) init
{
    self = [self initWithContentNode:[CCNode node]];
    self.contentSizeType = CCSizeTypeNormalized;
    return self;
}

- (id) initWithContentNode:(CCNode*)contentNode
{
    self = [super init];
    if (!self) return NULL;

    _flipYCoordinates = YES;

    // Setup content node
    self.contentSize = CGSizeMake(1, 1);
    self.contentSizeType = CCSizeTypeNormalized;
    self.contentNode = contentNode;

    // Default properties
    _horizontalScrollEnabled = YES;
    _verticalScrollEnabled = YES;
    _bounces = YES;

#if __CC_PLATFORM_IOS

    // Create gesture recognizers
    _panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    _tapRecognizer = [[CCTapDownGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];

    _panRecognizer.delegate = self;
    _tapRecognizer.delegate = self;
#elif __CC_PLATFORM_ANDROID
    dispatch_async(dispatch_get_main_queue(), ^{
        _listener = [[CCGestureListener alloc] init];
        _listener.delegate = (id<CCGestureListenerDelegate>)self;
        _detector = [[AndroidGestureDetector alloc] initWithContext:[CCActivity currentActivity] listener:_listener];
    });
#elif __CC_PLATFORM_MAC

    // Use scroll wheel
    self.userInteractionEnabled = YES;
#endif

    self.userInteractionEnabled = YES;

    return self;
}

#pragma mark Setting content node
- (void) setContentNode:(CCNode *)contentNode
{
    if (_contentNode == contentNode) return;

    // Replace content node
    if (_contentNode) [self removeChild:_contentNode];
    _contentNode = contentNode;
    if (contentNode)
    {
        [self addChild:contentNode];

        // Update coordinate flipping
        self.flipYCoordinates = self.flipYCoordinates;
    }
}

- (void) setFlipYCoordinates:(BOOL)flipYCoordinates
{
    if (flipYCoordinates)
    {
        _contentNode.positionType = CCPositionTypeMake(CCPositionUnitPoints, CCPositionUnitPoints, CCPositionReferenceCornerTopLeft);
        _contentNode.anchorPoint = ccp(0,1);
    }
    else
    {
        _contentNode.positionType = CCPositionTypeMake(CCPositionUnitPoints, CCPositionUnitPoints, CCPositionReferenceCornerBottomLeft);
        _contentNode.anchorPoint = ccp(0,0);
    }

    _flipYCoordinates = flipYCoordinates;
}

#pragma mark Min/Max size

- (float) minScrollX
{
    return 0;
}

- (float) maxScrollX
{
    if (!_contentNode) return 0;

    float maxScroll = _contentNode.contentSizeInPoints.width - self.contentSizeInPoints.width;
    if (maxScroll < 0) maxScroll = 0;

    return maxScroll;
}

- (float) minScrollY
{
    return 0;
}

- (float) maxScrollY
{
    if (!_contentNode) return 0;

    float maxScroll = _contentNode.contentSizeInPoints.height - self.contentSizeInPoints.height;
    if (maxScroll < 0) maxScroll = 0;

    return maxScroll;
}

#pragma mark Paging

- (void) setHorizontalPage:(int)horizontalPage
{
    [self setHorizontalPage:horizontalPage animated:NO];
}

- (void) setHorizontalPage:(int)horizontalPage animated:(BOOL)animated
{
    NSAssert(horizontalPage >= 0 && horizontalPage < self.numHorizontalPages, @"Setting invalid horizontal page");

    CGPoint pos = self.scrollPosition;
    pos.x = horizontalPage * self.contentSizeInPoints.width;

    [self setScrollPosition:pos animated:animated];
    _horizontalPage = horizontalPage;
}

- (void) setVerticalPage:(int)verticalPage
{
    [self setVerticalPage:verticalPage animated:NO];
}

- (void) setVerticalPage:(int)verticalPage animated:(BOOL)animated
{
    NSAssert(verticalPage >= 0 && verticalPage < self.numVerticalPages, @"Setting invalid vertical page");

    CGPoint pos = self.scrollPosition;
    pos.y = verticalPage * self.contentSizeInPoints.height;

    [self setScrollPosition:pos animated:animated];
    _verticalPage = verticalPage;
}

- (int) numHorizontalPages
{
    if (!_pagingEnabled) return 0;
    if (!self.contentSizeInPoints.width || !_contentNode.contentSizeInPoints.width) return 0;

    return roundf(_contentNode.contentSizeInPoints.width / self.contentSizeInPoints.width);
}

- (int) numVerticalPages
{
    if (!_pagingEnabled) return 0;
    if (!self.contentSizeInPoints.height || !_contentNode.contentSizeInPoints.height) return 0;

    return roundf(_contentNode.contentSizeInPoints.height / self.contentSizeInPoints.height);
}

#pragma mark Panning and setting position

- (void) setScrollPosition:(CGPoint)newPos
{
    [self setScrollPosition:newPos animated:NO];
}

- (void) setScrollPosition:(CGPoint)newPos animated:(BOOL)animated
{
    // Check bounds
	newPos.x = MAX(MIN(newPos.x, self.maxScrollX), self.minScrollX);
	newPos.y = MAX(MIN(newPos.y, self.maxScrollY), self.minScrollY);

    [self updateAndroidScrollTranslation:newPos];

    BOOL xMoved = (newPos.x != self.scrollPosition.x);
    BOOL yMoved = (newPos.y != self.scrollPosition.y);

    if (animated)
    {
        CGPoint oldPos = self.scrollPosition;
        float dist = ccpDistance(newPos, oldPos);

        float duration = clampf(dist / kCCScrollViewSnapDurationFallOff, 0, kCCScrollViewSnapDuration);

        if (xMoved)
        {
            // Animate horizontally

            _velocity.x = 0;
            _animatingX = YES;

            // Create animation action
            CCActionInterval* action = [CCActionEaseOut actionWithAction:[[CCMoveToX alloc] initWithDuration:duration positionX:-newPos.x callback:^{
				[self scrollViewDidScroll];
			}] rate:2];
            CCActionCallFunc* callFunc = [CCActionCallFunc actionWithTarget:self selector:@selector(xAnimationDone)];
            action = [CCActionSequence actions:action, callFunc, nil];
            action.tag = kCCScrollViewActionXTag;
            [_contentNode runAction:action];
        }
        if (yMoved)
        {
            // Animate vertically

            _velocity.y = 0;
            _animatingY = YES;

            // Create animation action
            CCActionInterval* action = [CCActionEaseOut actionWithAction:[[CCMoveToY alloc] initWithDuration:duration positionY:-newPos.y callback:^{
				[self scrollViewDidScroll];
			}] rate:2];
            CCActionCallFunc* callFunc = [CCActionCallFunc actionWithTarget:self selector:@selector(yAnimationDone)];
            action = [CCActionSequence actions:action, callFunc, nil];
            action.tag = kCCScrollViewActionYTag;
            [_contentNode runAction:action];
        }
    }
    else
    {
#if __CC_PLATFORM_MAC
		_lastPosition = self.scrollPosition;
#endif
        [_contentNode stopActionByTag:kCCScrollViewActionXTag];
        [_contentNode stopActionByTag:kCCScrollViewActionYTag];
        _contentNode.position = ccpMult(newPos, -1);
    }
}

- (void)updateAndroidScrollTranslation:(CGPoint)worldPosition
{
#if __CC_PLATFORM_ANDROID
    _rawScrollTranslation = [self convertToWindowSpace:CGPointMake(-worldPosition.x, worldPosition.y)];
#endif
}

- (void) xAnimationDone
{
    _animatingX = NO;
}

- (void) yAnimationDone
{
    _animatingY = NO;
}

- (CGPoint) scrollPosition
{
    return ccpMult(_contentNode.position, -1);
}

- (void) panLayerToTarget:(CGPoint) newPos
{
    if (_bounces)
    {
        // Scroll at half speed outside of bounds
        if (newPos.x > self.maxScrollX)
        {
            float diff = newPos.x - self.maxScrollX;
            newPos.x = self.maxScrollX + diff * kCCScrollViewBoundsSlowDown;
        }
        if (newPos.x < self.minScrollX)
        {
            float diff = self.minScrollX - newPos.x;
            newPos.x = self.minScrollX - diff * kCCScrollViewBoundsSlowDown;
        }
        if (newPos.y > self.maxScrollY)
        {
            float diff = newPos.y - self.maxScrollY;
            newPos.y = self.maxScrollY + diff * kCCScrollViewBoundsSlowDown;
        }
        if (newPos.y < self.minScrollY)
        {
            float diff = self.minScrollY - newPos.y;
            newPos.y = self.minScrollY - diff * kCCScrollViewBoundsSlowDown;
        }
    }
    else
    {
        if (newPos.x > self.maxScrollX) newPos.x = self.maxScrollX;
        if (newPos.x < self.minScrollX) newPos.x = self.minScrollX;
        if (newPos.y > self.maxScrollY) newPos.y = self.maxScrollY;
        if (newPos.y < self.minScrollY) newPos.y = self.minScrollY;
    }
    [self scrollViewDidScroll];

    _contentNode.position = ccpMult(newPos, -1);
}

- (void) update:(CCTime)df
{
    float fps = 1.0/df;
    float p = 60/fps;

	if (! CGPointEqualToPoint(_velocity, CGPointZero) ) {
		[self scrollViewDidScroll];
	} else {

#if __CC_PLATFORM_IOS
		if ( _decelerating && !(_animatingX || _animatingY)) {
			[self scrollViewDidEndDecelerating];
			_decelerating = NO;
		}
#elif __CC_PLATFORM_MAC
		if ( _decelerating && CGPointEqualToPoint(_lastPosition, self.scrollPosition)) {
			[self scrollViewDidEndDecelerating];
			_decelerating = NO;
		}
#endif
    }

    if (!_isPanning)
    {
        if (_velocity.x != 0 || _velocity.y != 0)
        {
            CGPoint delta = ccpMult(_velocity, df);

            _contentNode.position = ccpAdd(_contentNode.position, delta);

            [self updateAndroidScrollTranslation:CGPointMake(_contentNode.position.x * -1, _contentNode.position.y * -1)];

            // Deaccelerate layer
            float deaccelerationX = kCCScrollViewDeacceleration;
            float deaccelerationY = kCCScrollViewDeacceleration;

            // Adjust for frame rate
            deaccelerationX = powf(deaccelerationX, p);

            // Update velocity
            _velocity.x *= deaccelerationX;
            _velocity.y *= deaccelerationY;

            // If velocity is low make it 0
            if (fabs(_velocity.x) < kCCScrollViewVelocityLowerCap) _velocity.x = 0;
            if (fabs(_velocity.y) < kCCScrollViewVelocityLowerCap) _velocity.y = 0;
        }

        if (_bounces)
        {
            // Bounce back to edge if layer is too far outside of the scroll area or if it is outside and moving slowly
            BOOL bounceToEdge = NO;
            CGPoint posTarget = self.scrollPosition;

            if (!_animatingX && !_pagingEnabled)
            {
                if ((posTarget.x < self.minScrollX && fabs(_velocity.x) < kCCScrollViewMinVelocityBeforeBounceBack) ||
                    (posTarget.x < self.minScrollX - kCCScrollViewMaxOuterDistBeforeBounceBack))
                {
                    bounceToEdge = YES;
                }

                if ((posTarget.x > self.maxScrollX && fabs(_velocity.x) < kCCScrollViewMinVelocityBeforeBounceBack) ||
                    (posTarget.x > self.maxScrollX + kCCScrollViewMaxOuterDistBeforeBounceBack))
                {
                    bounceToEdge = YES;
                }
            }
            if (!_animatingY && !_pagingEnabled)
            {
                if ((posTarget.y < self.minScrollY && fabs(_velocity.y) < kCCScrollViewMinVelocityBeforeBounceBack) ||
                    (posTarget.y < self.minScrollY - kCCScrollViewMaxOuterDistBeforeBounceBack))
                {
                    bounceToEdge = YES;
                }

                if ((posTarget.y > self.maxScrollY && fabs(_velocity.y) < kCCScrollViewMinVelocityBeforeBounceBack) ||
                    (posTarget.y > self.maxScrollY + kCCScrollViewMaxOuterDistBeforeBounceBack))
                {
                    bounceToEdge = YES;
                }
            }

            if (bounceToEdge)
            {
                // Setting the scroll position to the current position will force it to be in bounds
                [self setScrollPosition:posTarget animated:YES];
            }
        }
        else
        {
            if (!_pagingEnabled)
            {
                // Make sure we are within bounds
                [self setScrollPosition:self.scrollPosition animated:NO];
            }
        }
    }
}

#pragma mark Gesture recognizer

#if __CC_PLATFORM_IOS

- (void)handlePan:(UIGestureRecognizer *)gestureRecognizer
{
    CCDirector* dir = [CCDirector sharedDirector];
    UIPanGestureRecognizer* pgr = (UIPanGestureRecognizer*)gestureRecognizer;

    CGPoint rawTranslation = [pgr translationInView:dir.view];
    rawTranslation = [dir convertToGL:rawTranslation];
    rawTranslation = [self convertToNodeSpace:rawTranslation];

    if (pgr.state == UIGestureRecognizerStateBegan)
    {
		[self scrollViewWillBeginDragging];
        _animatingX = NO;
        _animatingY = NO;
        _rawTranslationStart = rawTranslation;
        _startScrollPos = self.scrollPosition;

        _isPanning = YES;
        [_contentNode stopActionByTag:kCCScrollViewActionXTag];
        [_contentNode stopActionByTag:kCCScrollViewActionYTag];
    }
    else if (pgr.state == UIGestureRecognizerStateChanged)
    {
        // Calculate the translation in node space
        CGPoint translation = ccpSub(_rawTranslationStart, rawTranslation);

        // Check if scroll directions has been disabled
        if (!_horizontalScrollEnabled) translation.x = 0;
        if (!_verticalScrollEnabled) translation.y = 0;

        if (_flipYCoordinates) translation.y = -translation.y;

        // Check bounds
        CGPoint newPos = ccpAdd(_startScrollPos, translation);

        // Update position
        [self panLayerToTarget:newPos];
    }
    else if (pgr.state == UIGestureRecognizerStateEnded)
    {

        // Calculate the velocity in node space
        CGPoint ref = [dir convertToGL:CGPointZero];
        ref = [self convertToNodeSpace:ref];

        CGPoint velocityRaw = [pgr velocityInView:dir.view];
        velocityRaw = [dir convertToGL:velocityRaw];
        velocityRaw = [self convertToNodeSpace:velocityRaw];

        _velocity = ccpSub(velocityRaw, ref);
        if (_flipYCoordinates) _velocity.y = -_velocity.y;

        // Check if scroll directions has been disabled
        if (!_horizontalScrollEnabled) _velocity.x = 0;
        if (!_verticalScrollEnabled) _velocity.y = 0;
		[self scrollViewDidEndDraggingAndWillDecelerate:!CGPointEqualToPoint(_velocity, CGPointZero)];

        // Setup a target if paging is enabled
        if (_pagingEnabled)
        {
            CGPoint posTarget = CGPointZero;

            // Calculate new horizontal page
            int pageX = roundf(self.scrollPosition.x/self.contentSizeInPoints.width);

            if (fabs(_velocity.x) >= kCCScrollViewAutoPageSpeed && _horizontalPage == pageX)
            {
                if (_velocity.x < 0) pageX += 1;
                else pageX -= 1;
            }

            pageX = clampf(pageX, 0, self.numHorizontalPages -1);
            _horizontalPage = pageX;

            posTarget.x = pageX * self.contentSizeInPoints.width;

            // Calculate new vertical page
            int pageY = roundf(self.scrollPosition.y/self.contentSizeInPoints.height);

            if (fabs(_velocity.y) >= kCCScrollViewAutoPageSpeed && _verticalPage == pageY)
            {
                if (_velocity.y < 0) pageY += 1;
                else pageY -= 1;
            }

            pageY = clampf(pageY, 0, self.numVerticalPages -1);
            _verticalPage = pageY;

            posTarget.y = pageY * self.contentSizeInPoints.height;

            [self setScrollPosition:posTarget animated:YES];

            _velocity = CGPointZero;
        }
        [self scrollViewWillBeginDecelerating];
		_decelerating = YES;
        _isPanning = NO;
    }
    else if (pgr.state == UIGestureRecognizerStateCancelled)
    {
        _isPanning = NO;
        _velocity = CGPointZero;
        _animatingX = NO;
        _animatingY = NO;

        [self setScrollPosition:self.scrollPosition animated:NO];
    }
}

- (void) handleTap:(UIGestureRecognizer *)gestureRecognizer
{
    // Stop layer from moving
    _velocity = CGPointZero;

    // Snap to a whole position
    CGPoint pos = _contentNode.position;
    pos.x = roundf(pos.x);
    pos.y = roundf(pos.y);
    _contentNode.position = pos;
}

- (BOOL) isAncestor:(CCNode*) ancestor toNode:(CCNode*)node
{
    for (CCNode* child in node.children)
    {
        if (child == ancestor) return YES;
        if ([self isAncestor:ancestor toNode:child]) return YES;
    }
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(CCTouch *)touch
{
    if (!_contentNode) return NO;
    if (!self.visible) return NO;
    if (!self.userInteractionEnabled) return NO;

    // Check for responders above this scroll view (and not within it). If there are responders above touch should go to them instead.
    CGPoint touchWorldPos = [touch locationInWorld];

    NSArray* responders = [[CCDirector sharedDirector].responderManager nodesAtPoint:touchWorldPos];
    BOOL foundSelf = NO;
    for (int i = (int)responders.count - 1; i >= 0; i--)
    {
        CCNode* responder = [responders objectAtIndex:i];
        if (foundSelf)
        {
            if (![self isAncestor:responder toNode:self])
            {
                return NO;
            }
        }
        else if (responder == self)
        {
            foundSelf = YES;
        }
    }

    // Allow touches to children if view is moving slowly
    BOOL slowMove = (fabs(_velocity.x) < kCCScrollViewAllowInteractionBelowVelocity &&
                     fabs(_velocity.y) < kCCScrollViewAllowInteractionBelowVelocity);

    if (gestureRecognizer == _tapRecognizer && (slowMove || _isPanning))
    {
        return NO;
    }

    // Check that the gesture is in the scroll view
    return [self hitTestWithWorldPos:[touch locationInWorld]];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return (otherGestureRecognizer == _panRecognizer || otherGestureRecognizer == _tapRecognizer);
}

- (void) onEnterTransitionDidFinish
{
    // Add recognizers to view
    UIView* view = [CCDirector sharedDirector].view;

    NSMutableArray* recognizers = [view.gestureRecognizers mutableCopy];
    if (!recognizers) recognizers = [NSMutableArray arrayWithCapacity:2];
    [recognizers insertObject:_panRecognizer atIndex:0];
    [recognizers insertObject:_tapRecognizer atIndex:0];

    view.gestureRecognizers = recognizers;
    [super onEnterTransitionDidFinish];
}

- (void) onExitTransitionDidStart
{
    // Remove recognizers from view
    UIView* view = [CCDirector sharedDirector].view;

    NSMutableArray* recognizers = [view.gestureRecognizers mutableCopy];
    [recognizers removeObject:_panRecognizer];
    [recognizers removeObject:_tapRecognizer];

    view.gestureRecognizers = recognizers;

    [super onExitTransitionDidStart];
}

#elif __CC_PLATFORM_ANDROID

- (void) onEnterTransitionDidFinish
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(_detector)
        {
            [[[CCDirector sharedDirector] view] addGestureDetector:_detector];
        }
    });
    [super onEnterTransitionDidFinish];
}

- (void) onExitTransitionDidStart
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(_detector)
        {
            [[[CCDirector sharedDirector] view] removeGestureDetector:_detector];
        }
    });

    [super onExitTransitionDidStart];
}

- (CCTouchPhase)handleGestureEvent:(AndroidMotionEvent *)start end:(AndroidMotionEvent *)end
{
    CCTouchPhase phase = CCTouchPhaseStationary;
    switch (start.action & AndroidMotionEventActionMask) {
        case AndroidMotionEventActionPointerDown:
        case AndroidMotionEventActionDown:
            phase = CCTouchPhaseBegan;
            break;
        case AndroidMotionEventActionMove:
            phase = CCTouchPhaseMoved;
            break;
        case AndroidMotionEventActionPointerUp:
        case AndroidMotionEventActionUp:
            phase = CCTouchPhaseEnded;
            break;
        case AndroidMotionEventActionCancel:
            phase = CCTouchPhaseCancelled;
            break;
        default:
            phase = CCTouchPhaseStationary;
    }
    switch (end.action & AndroidMotionEventActionMask) {
        case AndroidMotionEventActionPointerDown:
        case AndroidMotionEventActionDown:
            phase = CCTouchPhaseBegan;
            break;
        case AndroidMotionEventActionMove:
            phase = CCTouchPhaseMoved;
            break;
        case AndroidMotionEventActionPointerUp:
        case AndroidMotionEventActionUp:
            phase = CCTouchPhaseEnded;
            break;
        case AndroidMotionEventActionCancel:
            phase = CCTouchPhaseCancelled;
            break;
        default:
            phase = CCTouchPhaseStationary;
    }

    return phase;
}

- (BOOL)onScroll:(AndroidMotionEvent *)start end:(AndroidMotionEvent *)end distanceX:(float)dx distanceY:(float)dy
{
    _isPanning = YES;
    _velocity = CGPointZero;

    // Note about start and end events: We will get a CCTouchPhaseBegan for the start event, followed by CCTouchPhaseMoved in the end event
    CCTouchPhase phase = [self handleGestureEvent:start end:end];

    if(phase == CCTouchPhaseCancelled || phase == CCTouchPhaseEnded)
        _rawScrollTranslation = CGPointMake(0.0f, 0.0f);

    float scaleFactor = [[CCDirector sharedDirector] view].contentScaleFactor;

    dx /= scaleFactor;
    dy /= scaleFactor;

    _rawScrollTranslation.x -= dx;
    _rawScrollTranslation.y -= dy;

    CCDirector* dir = [CCDirector sharedDirector];
    [[CCActivity currentActivity] runOnGameThread:^{

        CGPoint translation = [dir convertToGL:_rawScrollTranslation];
        translation = [self convertToNodeSpace:translation];

        if (phase == CCTouchPhaseBegan)
        {
            [self scrollViewWillBeginDragging];
            _animatingX = NO;
            _animatingY = NO;
            _rawTranslationStart = translation;
            _startScrollPos = self.scrollPosition;

            _isPanning = YES;
            [_contentNode stopActionByTag:kCCScrollViewActionXTag];
            [_contentNode stopActionByTag:kCCScrollViewActionYTag];
        }
        else if (phase == CCTouchPhaseMoved)
        {
            // Calculate the translation in node space
            CGPoint trans = ccpSub(_rawTranslationStart, translation);

            // Check if scroll directions has been disabled
            if (!_horizontalScrollEnabled) trans.x = 0;
            if (!_verticalScrollEnabled) trans.y = 0;

            if (_flipYCoordinates) trans.y = -trans.y;

            // Check bounds
            CGPoint newPos = ccpAdd(_startScrollPos, trans);

            // Update position
            [self panLayerToTarget:newPos];

        }
        else if (phase == CCTouchPhaseEnded)
        {
            // stub
        }
        else if (phase == CCTouchPhaseCancelled)
        {
            _isPanning = NO;
            _velocity = CGPointZero;
            _animatingX = NO;
            _animatingY = NO;

            [self setScrollPosition:self.scrollPosition animated:NO];
        }
    } waitUntilDone:YES];
    return YES;
}

- (BOOL)onFling:(AndroidMotionEvent *)start end:(AndroidMotionEvent *)end velocityX:(float)vx velocityY:(float)vy
{
    static CGPoint rawTranslationFling;

    CCTouchPhase phase = [self handleGestureEvent:start end:end];

    if(phase == CCTouchPhaseCancelled || phase == CCTouchPhaseEnded)
        rawTranslationFling = CGPointMake(0.0f, 0.0f);

    float scaleFactor = [[CCDirector sharedDirector] view].contentScaleFactor;
    float x0 = [start xForPointerIndex:0] / scaleFactor;
    float x1 = [end xForPointerIndex:0] / scaleFactor;

    float y0 = [start yForPointerIndex:0] / scaleFactor;
    float y1 = [end yForPointerIndex:0] / scaleFactor;

    int64_t t0 = start.eventTime;
    int64_t t1 = end.eventTime;

    vx /= scaleFactor;
    vy /= scaleFactor;

    float dx = (x1 - x0) / scaleFactor;
    float dy = (y1 - y0) / scaleFactor;

    CGPoint velocityRaw = CGPointMake(vx, vy);
    rawTranslationFling.x -= dx / scaleFactor;
    rawTranslationFling.y -= dy / scaleFactor;

    CCDirector* dir = [CCDirector sharedDirector];
    [[CCActivity currentActivity] runOnGameThread:^{

        CGPoint translation = [dir convertToGL:rawTranslationFling];
        translation = [self convertToNodeSpace:translation];

        if (phase == CCTouchPhaseBegan)
        {
            [self scrollViewWillBeginDragging];
        }
        else if (phase == CCTouchPhaseMoved)
        {
            // stub
        }
        else if (phase == CCTouchPhaseEnded)
        {
            // Calculate the velocity in node space
            CGPoint ref = [dir convertToGL:CGPointZero];
            ref = [self convertToNodeSpace:ref];

            CGPoint velocity = [dir convertToGL:velocityRaw];
            velocity = [self convertToNodeSpace:velocity];

            _velocity = ccpSub(velocity, ref);
            if (_flipYCoordinates) _velocity.y = -_velocity.y;

            // Check if scroll directions has been disabled
            if (!_horizontalScrollEnabled) _velocity.x = 0;
            if (!_verticalScrollEnabled) _velocity.y = 0;
            [self scrollViewDidEndDraggingAndWillDecelerate:!CGPointEqualToPoint(_velocity, CGPointZero)];

            // Setup a target if paging is enabled
            if (_pagingEnabled)
            {
                CGPoint posTarget = CGPointZero;

                // Calculate new horizontal page
                int pageX = roundf(self.scrollPosition.x/self.contentSizeInPoints.width);

                if (fabs(_velocity.x) >= kCCScrollViewAutoPageSpeed && _horizontalPage == pageX)
                {
                    if (_velocity.x < 0) pageX += 1;
                    else pageX -= 1;
                }

                pageX = clampf(pageX, 0, self.numHorizontalPages -1);
                _horizontalPage = pageX;

                posTarget.x = pageX * self.contentSizeInPoints.width;

                // Calculate new vertical page
                int pageY = roundf(self.scrollPosition.y/self.contentSizeInPoints.height);

                if (fabs(_velocity.y) >= kCCScrollViewAutoPageSpeed && _verticalPage == pageY)
                {
                    if (_velocity.y < 0) pageY += 1;
                    else pageY -= 1;
                }

                pageY = clampf(pageY, 0, self.numVerticalPages -1);
                _verticalPage = pageY;

                posTarget.y = pageY * self.contentSizeInPoints.height;

                [self setScrollPosition:posTarget animated:YES];

                _velocity = CGPointZero;
            }
            [self scrollViewWillBeginDecelerating];

            _decelerating = YES;
            _isPanning = NO;
        }
        else if (phase == CCTouchPhaseCancelled)
        {
            _isPanning = NO;
            _velocity = CGPointZero;
            _animatingX = NO;
            _animatingY = NO;

            [self setScrollPosition:self.scrollPosition animated:NO];
        }
    } waitUntilDone:YES];
    return YES;
}

#elif __CC_PLATFORM_MAC

#define kCCScrollViewMinPagingDelta 7

- (void)scrollWheel:(NSEvent *)theEvent
{
	CCDirector* dir = [CCDirector sharedDirector];

    float deltaX = theEvent.deltaX;
    float deltaY = theEvent.deltaY;

	[self scrollViewDidScroll];

    switch (theEvent.phase) {
        case NSEventPhaseBegan:
            [self scrollViewWillBeginDragging];
            break;
        case NSEventPhaseEnded:
			//TODO: add logic to determine if it will decelerate
            [self scrollViewDidEndDraggingAndWillDecelerate:YES];
			_decelerating = YES;
        default:
            break;
    }

    if (theEvent.momentumPhase == NSEventPhaseBegan)
	{
		[self scrollViewWillBeginDecelerating];
    }

    // Calculate the delta in node space
    CGPoint ref = [dir convertToGL:CGPointZero];
    ref = [self convertToNodeSpace:ref];

    CGPoint deltaRaw = ccp(deltaX, deltaY);
    deltaRaw = [dir convertToGL:deltaRaw];

    deltaRaw = [self convertToNodeSpace:deltaRaw];

    CGPoint delta = ccpSub(deltaRaw, ref);

    // Flip coordinates
    if (_flipYCoordinates) delta.y = -delta.y;
    delta.x = -delta.x;

    // Handle disabled x/y axis
    if (!_horizontalScrollEnabled) delta.x = 0;
    if (!_verticalScrollEnabled) delta.y = 0;

    if (_pagingEnabled)
    {
        if (!_animatingX && _horizontalScrollEnabled)
        {
            // Update horizontal page
            int xPage = self.horizontalPage;
            int xOldPage = xPage;

            if (fabs(delta.x) >= kCCScrollViewMinPagingDelta)
            {
                if (delta.x > 0) xPage += 1;
                else xPage -= 1;
            }
            xPage = clampf(xPage, 0, self.numHorizontalPages - 1);

            if (xPage != xOldPage)
            {
                [self setHorizontalPage:xPage animated:YES];
            }
        }

        if (!_animatingY && _verticalScrollEnabled)
        {
            // Update horizontal page
            int yPage = self.verticalPage;
            int yOldPage = yPage;

            if (fabs(delta.y) >= kCCScrollViewMinPagingDelta)
            {
                if (delta.y > 0) yPage += 1;
                else yPage -= 1;
            }
            yPage = clampf(yPage, 0, self.numVerticalPages - 1);

            if (yPage != yOldPage)
            {
                [self setVerticalPage:yPage animated:YES];
            }
        }
    }
    else
    {
        // Update scroll position
        CGPoint scrollPos = self.scrollPosition;
        scrollPos = ccpAdd(delta, scrollPos);
		self.scrollPosition = scrollPos;
    }
}

#endif

#pragma mark - CCScrollViewDelegate Helpers

- (void)scrollViewDidScroll
{
    if ( [self.delegate respondsToSelector:@selector(scrollViewDidScroll:)] )
    {
        [self.delegate scrollViewDidScroll:self];
    }
}

- (void)scrollViewWillBeginDragging
{
    if ( [self.delegate respondsToSelector:@selector(scrollViewWillBeginDragging:)])
    {
        [self.delegate scrollViewWillBeginDragging:self];
    }
}
- (void)scrollViewDidEndDraggingAndWillDecelerate:(BOOL)decelerate
{
    if ([self.delegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)])
    {
        [self.delegate scrollViewDidEndDragging:self
                                 willDecelerate:decelerate];
    }
}
- (void)scrollViewWillBeginDecelerating
{
	if ( !_pagingEnabled )
    {
		if ( [self.delegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)])
		{
			[self.delegate scrollViewWillBeginDecelerating:self];
		}
	}

}
- (void)scrollViewDidEndDecelerating
{
    if ( [self.delegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)])
    {
        [self.delegate scrollViewDidEndDecelerating:self];
    }
}

@end


text:
#include "mkn/kul/cli.hpp"
#include "mkn/kul/log.hpp"
#include "mkn/kul/os.hpp"
#include "mkn/kul/threads.hpp"

#if __has_include("benchmark/benchmark.h")
#include "benchmark/benchmark.h"
#else
#include "benchmark/benchmark_api.h"
#endif

void createDeleteFile(benchmark::State &state) {
  while (state.KeepRunning()) {
    mkn::kul::File f("tmp.tmp");
    f.mk();
    f.rm();
  }
}
BENCHMARK(createDeleteFile)->Unit(benchmark::kMicrosecond);

void parseStringAsCommandLineArguments(benchmark::State &state) {
  while (state.KeepRunning()) {
    std::vector<std::string> v;
    mkn::kul::cli::asArgs("/path/to \"words in quotes\" words\\ not\\ in\\ quotes end", v);
  }
}
BENCHMARK(parseStringAsCommandLineArguments)->Unit(benchmark::kMicrosecond);

void splitStringByChar(benchmark::State &state) {
  while (state.KeepRunning()) {
    std::vector<std::string> v;
    mkn::kul::String::SPLIT("split - by - char - dash", '-', v);
  }
}
BENCHMARK(splitStringByChar)->Unit(benchmark::kMicrosecond);

void splitStringByString(benchmark::State &state) {
  while (state.KeepRunning()) {
    std::vector<std::string> v;
    mkn::kul::String::SPLIT("split - by - char - dash", "-", v);
  }
}
BENCHMARK(splitStringByString)->Unit(benchmark::kMicrosecond);

void splitStringByEscapedChar(benchmark::State &state) {
  while (state.KeepRunning()) {
    std::vector<std::string> v;
    mkn::kul::String::ESC_SPLIT("split \\- by - char - dash", '-', v);
  }
}
BENCHMARK(splitStringByEscapedChar)->Unit(benchmark::kMicrosecond);

auto lambda = [](uint a, uint b) {
  auto c = (a + b);
  (void)c;
};

void concurrentThreadPool(benchmark::State &state) {
  while (state.KeepRunning()) {
    mkn::kul::ConcurrentThreadPool<> ctp(3, 1);
    for (size_t i = 0; i < 10000; i++) ctp.async(std::bind(lambda, 2, 4));
    ctp.block().finish().join();
  }
}
BENCHMARK(concurrentThreadPool)->Unit(benchmark::kMicrosecond);

void chroncurrentThreadPool(benchmark::State &state) {
  while (state.KeepRunning()) {
    mkn::kul::ChroncurrentThreadPool<> ctp(3, 1);
    for (size_t i = 0; i < 10000; i++) ctp.async(std::bind(lambda, 2, 4));
    ctp.block().finish().join();
  }
}
BENCHMARK(chroncurrentThreadPool)->Unit(benchmark::kMicrosecond);

int main(int argc, char **argv) {
  ::benchmark::Initialize(&argc, argv);
  ::benchmark::RunSpecifiedBenchmarks();
}


text:
import React from 'react';
import { Route } from 'react-router-dom';
import LoadableWithLoading from '@ncigdc/components/LoadableWithLoading';

export default (
  <Route
    path="/projects/:id"
    component={LoadableWithLoading({ loader: () => import('./ProjectRoute') })}
  />
);


text:
@interface ViewController () <CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *jingdu;
@property (weak, nonatomic) IBOutlet UITextField *weidu;
@property (nonatomic ,strong) CLLocationManager *manager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.manager requestAlwaysAuthorization];
    [self.manager startUpdatingLocation];
    self.manager.delegate = self;
    self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations firstObject];
    CLLocationCoordinate2D cor = location.coordinate;

    self.jingdu.text = [NSString stringWithFormat:@"%f",cor.longitude];
    self.weidu.text = [NSString stringWithFormat:@"%f",cor.latitude];

    [self.jingdu sizeToFit];
    [self.weidu sizeToFit];

}

#pragma mark --lazy

- (CLLocationManager *)manager {
    if (!_manager) {
        _manager = [[CLLocationManager alloc] init];
    }
    return _manager;
}

@end


text:
@interface MOORefreshView : UIView <MOOTriggerView>
{
    UIActivityIndicatorView *_activityView;
    UIImageView *_arrowView;
    UILabel *_titleLabel;

    NSString *_loadingText;
    NSString *_pullToRefreshText;
    NSString *_releaseText;

    NSTimeInterval _arrowFadeAnimationDuration;
    NSTimeInterval _arrowSpinAnimationDuration;
    NSTimeInterval _contentInsetAnimationDuration;

    BOOL _loading;
    BOOL _triggered;
}

@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) UIImageView *arrowView;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) NSString *loadingText;
@property (nonatomic, strong) NSString *pullToRefreshText;
@property (nonatomic, strong) NSString *releaseText;

@property (nonatomic, assign) NSTimeInterval arrowFadeAnimationDuration;
@property (nonatomic, assign) NSTimeInterval arrowSpinAnimationDuration;
@property (nonatomic, assign) NSTimeInterval contentInsetAnimationDuration;

@property (nonatomic, assign, readonly, getter = isLoading) BOOL loading;
@property (nonatomic, assign, readonly, getter = isTriggered) BOOL triggered;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea umbrinella Pers.

### Remarks
null


text:
require 'fileutils'

module YARD
  module Server
    # This exception is raised when {LibraryVersion#prepare!} fails, or discovers
    # that the library is not "prepared" to be served by
    class LibraryNotPreparedError < RuntimeError; end

    # A library version encapsulates a library's documentation at a specific version.
    # Although the version is optional, this allows for creating multiple documentation
    # points for a specific library, each representing a unique version. The term
    # "library" used in other parts of the YARD::Server documentation refers to
    # objects of this class unless otherwise noted.
    #
    # A library points to a location where a {#yardoc_file} is located so that
    # its documentation may be loaded and served. Optionally, a {#source_path} is
    # given to point to a location where any extra files (and {YARD::CLI::Yardoc .yardopts})
    # should be loaded from. Both of these methods may not be known immediately,
    # since the yardoc file may not be built until later. Resolving the yardoc
    # file and source path are dependent on the specific library "source type" used.
    # Source types (known as "library source") are discussed in detail below.
    #
    # == Using with Adapters
    # A list of libraries need to be passed into adapters upon creation. In
    # most cases, you will never do this manually, but if you use a {RackMiddleware},
    # you will need to pass in this list yourself. To build this list of libraries,
    # you should create a hash of library names mapped to an *Array* of LibraryVersion
    # objects. For example:
    #
    #   {'mylib' => [LibraryVersion.new('mylib', '1.0', ...),
    #                LibraryVersion.new('mylib', '2.0', ...)]}
    #
    # Note that you can also use {Adapter#add_library} for convenience.
    #
    # The "array" part is required, even for just one library version.
    #
    # == Library Sources
    # The {#source} method represents the library source type, ie. where the
    # library "comes from". It might come from "disk", or it might come from a
    # "gem" (technically the disk, but a separate type nonetheless). In these
    # two cases, the yardoc file sits somewhere on your filesystem, though
    # it may also be built dynamically if it does not yet exist. This behaviour
    # is controlled through the {#prepare!} method, which prepares the yardoc file
    # given a specific library source. We will see how this works in detail in
    # the following section.
    #
    # == Implementing a Custom Library Source
    # YARD can be extended to support custom library sources in order to
    # build or retrieve a yardoc file at runtime from many different locations.
    #
    # To implement this behaviour, two methods must be added to the +LibraryVersion+
    # class, +#load_yardoc_from_SOURCE+ and +#source_path_for_SOURCE+. In both
    # cases, "SOURCE" represents the source type used in {#source} when creating
    # the library object. The +#source_path_for_SOURCE+ method is called upon
    # creation and should return the location where the source code for the library
    # lives. The load method is called from {#prepare!} if there is no yardoc file
    # and should set {#yardoc_file}. Below is a full example for
    # implementing a custom library source, +:http+, which reads packaged .yardoc
    # databases from zipped archives off of an HTTP server.
    #
    # @example Implementing a Custom Library Source
    #   # Adds the source type "http" for .yardoc files zipped on HTTP servers
    #   class LibraryVersion
    #     def load_yardoc_from_http
    #       return if yardoc_file # we have the library
    #
    #       # otherwise download it in a thread and return immediately
    #       Thread.new do
    #         # zip/unzip method implementations are not shown
    #         download_zip_file("http://mysite.com/yardocs/#{self}.zip")
    #         unzip_file_to("/path/to/yardocs/#{self}")
    #         self.yardoc_file = "/path/to/yardocs/#{self}/.yardoc"
    #         self.source_path = self.yardoc_file
    #       end
    #
    #       # tell the server it's not ready yet (but it might be next time)
    #       raise LibraryNotPreparedError
    #     end
    #
    #     # we set this later
    #     def source_path_for_http; nil end
    #   end
    #
    #   # Creating a library of this source type:
    #   LibraryVersion.new('name', '1.0', nil, :http)
    #
    class LibraryVersion
      # @return [String] the name of the library
      attr_accessor :name

      # @return [String] the version of the specific library
      attr_accessor :version

      # @return [String] the location of the yardoc file used to load the object
      #   information from.
      # @return [nil] if no yardoc file exists yet. In this case, {#prepare!} will
      #   be called on this library to build the yardoc file.
      attr_accessor :yardoc_file

      # @return [Symbol] the source type representing where the yardoc should be
      #   loaded from. Defaults are +:disk+ and +:gem+, though custom sources
      #   may be implemented. This value is used to inform {#prepare!} about how
      #   to load the necessary data in order to display documentation for an object.
      # @see LibraryVersion LibraryVersion documentation for "Implementing a Custom Library Source"
      attr_accessor :source

      # @return [String] the location of the source code for a library. This
      #   value is filled by calling +#source_path_for_SOURCE+ on this class.
      # @return [nil] if there is no source code
      # @see LibraryVersion LibraryVersion documentation for "Implementing a Custom Library Source"
      attr_accessor :source_path

      # @param [String] name the name of the library
      # @param [String] version the specific (usually, but not always, numeric) library
      #   version
      # @param [String] yardoc the location of the yardoc file, or nil if it is
      #   generated later
      # @param [Symbol] source the location of the files used to build the yardoc.
      #   Builtin source types are +:disk+ or +:gem+.
      def initialize(name, version = nil, yardoc = nil, source = :disk)
        self.name = name
        self.yardoc_file = yardoc
        self.version = version
        self.source = source
        self.source_path = load_source_path
      end

      # @param [Boolean] url_format if true, returns the string in a URI-compatible
      #   format (for appending to a URL). Otherwise, it is given in a more human
      #   readable format.
      # @return [String] the string representation of the library.
      def to_s(url_format = true)
        version ? "#{name}#{url_format ? '/' : '-'}#{version}" : "#{name}"
      end

      # @return [Fixnum] used for Hash mapping.
      def hash; to_s.hash end

      # @return [Boolean] whether another LibraryVersion is equal to this one
      def eql?(other)
        other.is_a?(LibraryVersion) && other.name == name &&
          other.version == version && other.yardoc_file == yardoc_file
      end
      alias == eql?
      alias equal? eql?

      # @note You should not directly override this method. Instead, implement
      #   +load_yardoc_from_SOURCENAME+ when implementing loading for a specific
      #   source type. See the {LibraryVersion} documentation for "Implementing
      #   a Custom Library Source"
      #
      # Prepares a library to be displayed by the server. This callback is
      # performed before each request on a library to ensure that it is loaded
      # and ready to be viewed. If any steps need to be performed prior to loading,
      # they are performed through this method (though they should be implemented
      # through the +load_yardoc_from_SOURCE+ method).
      #
      # @raise [LibraryNotPreparedError] if the library is not ready to be
      #   displayed. Usually when raising this error, you would simultaneously
      #   begin preparing the library for subsequent requests, although this
      #   is not necessary.
      def prepare!
        return if yardoc_file
        meth = "load_yardoc_from_#{source}"
        send(meth) if respond_to?(meth, true)
      end

      # @return [Gem::Specification] a gemspec object for a given library. Used
      #   for :gem source types.
      # @return [nil] if there is no installed gem for the library
      def gemspec
        ver = version ? "= #{version}" : ">= 0"
        Gem.source_index.find_name(name, ver).first
      end

      protected

      # Called when a library of source type "disk" is to be prepared. In this
      # case, the {#yardoc_file} should already be set, so nothing needs to be
      # done.
      def load_yardoc_from_disk
        nil
      end

      # Called when a library of source type "gem" is to be prepared. In this
      # case, the {#yardoc_file} needs to point to the correct location for
      # the installed gem. The yardoc file is built if it has not been done.
      #
      # @raise [LibraryNotPreparedError] if the gem does not have an existing
      #   yardoc file.
      def load_yardoc_from_gem
        require 'rubygems'
        ver = version ? "= #{version}" : ">= 0"
        self.yardoc_file = Registry.yardoc_file_for_gem(name, ver)
        unless yardoc_file && File.directory?(yardoc_file)
          Thread.new do
            # Build gem docs on demand
            log.debug "Building gem docs for #{to_s(false)}"
            CLI::Gems.run(name, ver)
            self.yardoc_file = Registry.yardoc_file_for_gem(name, ver)
            FileUtils.touch(File.join(yardoc_file, 'complete'))
          end
        end
        unless yardoc_file && File.exist?(File.join(yardoc_file, 'complete'))
          raise LibraryNotPreparedError
        end
      end

      # @return [String] the source path for a disk source
      def source_path_for_disk
        File.dirname(yardoc_file) if yardoc_file
      end

      # @return [String] the source path for a gem source
      def source_path_for_gem
        gemspec.full_gem_path if gemspec
      end

      private

      def load_source_path
        meth = "source_path_for_#{source}"
        send(meth) if respond_to?(meth, true)
      end
    end
  end
end


text:
from cssqc.qualityWarning import QualityWarning
from cssyacc import Whitespace, Statement
from cssqc.helpers import isProperty

from pkg_resources import resource_string

def getHelp():
    return """Validate property names."""

class propertyValidate:
    def __init__(self, data):
        self.properties = set()

        o = resource_string('cssqc', 'order/alphabetical.dat').decode('utf-8')
        for x in o.split('\n'):
            self.properties.add(x)

    def on_Statement(self, s):
        if isProperty(s):
            if s.text[0][0] in self.properties \
                or s.text[0][0][0] == '-' \
                or s.text[0][0][0] == '@':
                return []
            else:
                return [QualityWarning('propertyValidate', s.text[0][1], 'Invalid property.')]
        else:
            return []


text:
module ActiveAny::Associations
  module ForeignAssociation
    def foreign_key_present?
      if reflection.klass.primary_key
        owner.attribute_present?(reflection.record_class_primary_key)
      else
        false
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <stroke
        android:width="2dp"
        android:color="#55000000"/>
    <solid
        android:color="#80006699"/>
    <corners
        android:radius="10dp"/>
    <padding
        android:bottom="4dp"
        android:left="4dp"
        android:right="4dp"
        android:top="4dp"/>

</shape>


text:
{% extends 'dashboard_base.html' %}

{% load staticfiles custom_filters %}

{% block content %}

Bibliotik Data Refresh

         Home
        Bibliotik Data Refresh

                    {% spaceless %}

Biblitoik Data Refresh

                    {% endspaceless %}

                        <textarea id="refresh_log" class="form-control" style="height: 600px;"></textarea>

{% endblock %}

{% block body_scripts %}
    {{ block.super }}

    {% include 'dashboard_search_redirect.html' %}

{% endblock %}


text:
namespace omaha {

namespace vista {

// Exercises RunAsUser() with explorer token. For Vista, the call to
// StartProcessWithTokenOfProcess() will succeed only if the caller is SYSTEM.
TEST(VistaUtilsTest, StartProcessWithExplorerTokenTest) {
  CString path = ConcatenatePath(app_util::GetSystemDir(), _T("cmd.exe"));
  EnclosePath(&path);
  path += _T(" /c exit 702");
  uint32 pid(0);
  EXPECT_SUCCEEDED(GetExplorerPidForCurrentUserOrSession(&pid));

  HRESULT hr = StartProcessWithTokenOfProcess(pid, path);
  if (!vista_util::IsVistaOrLater()) {
    EXPECT_SUCCEEDED(hr);
    return;
  }

  bool is_system = false;
  EXPECT_SUCCEEDED(IsSystemProcess(&is_system));
  if (is_system) {
    EXPECT_SUCCEEDED(hr);
    return;
  }

  EXPECT_EQ(HRESULT_FROM_WIN32(ERROR_PRIVILEGE_NOT_HELD), hr);
}

// Exercises RunAsUser() with current user token.
TEST(VistaUtilsTest, RunAsCurrentUserTest) {
  CString cmd_path = ConcatenatePath(app_util::GetSystemDir(), _T("cmd.exe"));
  EnclosePath(&cmd_path);
  CString exit_path = cmd_path + _T(" /c exit 702");
  EXPECT_SUCCEEDED(vista::RunAsCurrentUser(exit_path, NULL, NULL));

  scoped_process process;
  EXPECT_SUCCEEDED(
      vista::RunAsCurrentUser(exit_path, NULL, address(process)));
  ASSERT_EQ(WAIT_OBJECT_0, WaitForSingleObject(get(process), 16 * kMsPerSec));
  DWORD exit_code;
  ASSERT_TRUE(::GetExitCodeProcess(get(process), &exit_code));
  ASSERT_EQ(702, exit_code);
  reset(process);

  scoped_handle stdout_pipe;
  CString echo_path = cmd_path + _T(" /c \"echo Hello World\"");
  EXPECT_SUCCEEDED(vista::RunAsCurrentUser(echo_path,
                                           address(stdout_pipe),
                                           address(process)));
  ASSERT_EQ(WAIT_OBJECT_0, WaitForSingleObject(get(process), 16 * kMsPerSec));
  char buffer[32] = {0};
  DWORD bytes_read = 0;
  ASSERT_TRUE(::ReadFile(get(stdout_pipe),
                         buffer,
                         arraysize(buffer) - 1,
                         &bytes_read,
                         NULL));
  ASSERT_EQ(13, bytes_read);
  ASSERT_EQ(CString(_T("Hello World\r\n")),
            AnsiToWideString(buffer, bytes_read + 1));
}

}  // namespace vista

}  // namespace omaha


text:
import { ColumnOptions, getMetadataArgsStorage } from "../../";
import { ColumnMetadataArgs } from "../../metadata-args/ColumnMetadataArgs";

/**
 * This column will store a delete date of the soft-deleted object.
 * This date is being updated each time you soft-delete the object.
 */
export function DeleteDateColumn(options?: ColumnOptions): PropertyDecorator {
    return function(object: Object, propertyName: string) {
        getMetadataArgsStorage().columns.push({
            target: object.constructor,
            propertyName: propertyName,
            mode: "deleteDate",
            options: options || {}
        } as ColumnMetadataArgs);
    };
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <title>HTML Lesson 2 - Image and hyperlink</title>

HTML Lesson 2

Image and Hyperlink

The img tag

<img src="dir/path/hot-chicks.jpg"
  alt="Natures beauty captured in an image.">

What? No closing or empty tag.

Relax HTML is "almost" XML but more relaxed, everybody forgot to close them anyway.

dir/path/image.jpg Is you Windows broken? Paths go like C:\windowse\system32\virus.dll

An example folder structure

All paths in GNU/Linux (and OS X) start from one root

/

Lets say we have the following folder structure

o
├─o home
│ ├─o Desktop
│ └─o Documents
│
├─o media
│ └─o MyUSBstick
…

Moving down

o
├ …
├─o media
… └─o MyUSBstick
    └─o secret-stash
      └─o rainbow-dash.jpg

Access all your files by adding / between folders

/media/MyUSBstick/secret-stash/rainbow-dash.jpg

From the current directory

o
├─o home
│ ├─★ Desktop
│ │ └─o web-dev-course
│ │   └─o presentation.md
│ └─o Documents
│
├─o media
│ └─o MyUSBstick
    …

 ? show tree
if you are in e.g. /home/Desktop you can start with

.

from the current location and go to a subfolder

./web-dev-course/presentation.md

which is the same as writing

/home/Desktop/web-dev-course/presentation.md

From the current directory

But since this is so common we can just leave away the

.

and write

web-dev-course/presentation.md

which is still the same as writing

/home/Desktop/web-dev-course/presentation.md

Moving one level up

o
├─o home
│ ├─★ Desktop
│ └─o Documents
│   └─o my-love-poem.txt
│
├─o media
│ └─o MyUSBstick
…

 ? show tree
Go one level up from /home/Desktop with

..

to access your documents you could write

../Documents/my-love-poem.txt

which is the same as writing

/home/Documents/my-love-poem.txt

Did you get it already?

How do I go two levels up?

Don't worry we will partice it in the exercise.

Now lets move to H in HTML.

The hyperlink/anchor tag a

The hyperlink is one of the inventions of the 20th centry

<a href="path/to/other-document.html">
  I'm a link. Nice to meet you.
</a>

With a link you can reference another document and

let your reader access it INSTANTLY

Yaay no more going to the library.

References: within, local, external

The href attribute can reference within a file

<a href="#chapert1">go to chapter 1</a>

or to another local file

<a href="with/slash.html">I'm relative</a>

or to an external file.

<a href="https://xkcd.com/1144/">Re: Re: fun</a>

Reference within: anchor

To reference a within a document use an anchor

<a name="chapter4"></a> <!-- this is invisible -->

then create a link that points to that anchor

Click <a href="#chapter4">here</a> to read chapter 4.

Reference local: absolute, relative

The href attribute can take absolute paths

<a href="/starts/with/slash.html">absolute root</a>

or relative paths, where you can leave away the ./.

<a href="with/slash.html">I'm relative</a>

Do you remember moving one level up?

<a href="../its/possible.html">sacré bleu</a>

Reference external

To reference external files use a URL

<a href="https://xkcd.com/1144/">Re: Re: fun</a>

Yeay computer gibberish, let's see what it means.

The Uniform Resource Locator

http://www.example.com/patH/index.html

The Protocol

Tells how the data will be transported.

The Host

Maps (with some detours) to a computer.

The Path

Is used to find the requested data on the host computer.

The Uniform Resource Locator

http://www.example.com/patH/index.html

The Protocol

Your browser knows http, https, ftp, file.

The Host

Is not case sensitve. wWw.gOoGlE.CoM

The Path

Is (almost always) case sensitve, just like the file system

... on GUN/Linux.

The End

Continue with

Text Editing 1: Working with many files; better HTML editing (15 min)

or go back to the overview.

Falko Krause

      select

      https://github.com/select/learn-web-development

☷


text:
<?php
use rrsoacis\system\Config;
?>

Config

                Name
                Value

            <template id="agent_config_list_template">

            </template>


text:
/* magicBackground https://github.com/AvtreAB/magicBackground */

var MagicBackground = function() {
	this.elements = document.getElementsByClassName("video-background");

	if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
		if(this.elements.length > 0) {
			for (i = 0, elmLength = elements.length; i < elmLength; i++) {
				this.elements[i].innerHTML = "";
			}
		}
	}

	for (i = 0, elmLength = this.elements.length; i < elmLength; i++) {
		var videoElement = this.elements[i].getElementsByTagName("VIDEO")[0];

		if(videoElement) {
			this.addEvent(videoElement, "loadedmetadata", this.resize.bind(this));
		}

		if(videoElement.readyState > 0) {
			this.resize();
		}
	}

	this.addEvent(window, "resize", this.resize.bind(this));
}

MagicBackground.prototype.addEvent = function(object, type, callback) {
	if (object == null || typeof(object) == 'undefined') return;

    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
}

MagicBackground.prototype.resize = function(event) {
	if(this.elements.length > 0) {
		for (i = 0, elmLength = this.elements.length; i < elmLength; i++) {
			var containerElement = this.elements[i];
			var videoElement = containerElement.getElementsByTagName("VIDEO")[0];

			if(videoElement) {
				var videoDimensions = {
					"height" : videoElement.videoHeight,
					"width" : videoElement.videoWidth
				};
				console.log(videoDimensions);
				var containerDimensions = {
					"height" : containerElement.clientHeight,
					"width" : containerElement.clientWidth
				};
				console.log(containerDimensions);
				containerElement.classList.remove("set-height", "set-width");

				if(videoDimensions.width / videoDimensions.height >= containerDimensions.width / containerDimensions.height) {
					containerElement.className += " set-height";
					console.log("Setting height");
				}
				else {
					containerElement.className += " set-width";
					console.log("Setting width");
				}
			}
		}
	}
};


text:
using System;
using System.Linq;
using System.Collections.Generic;

namespace Solutionizer.Extensions {
    public static class EnumerableExtensions {
        public static IEnumerable<R> Flatten<T,R>(this IEnumerable<T> self, Func<T, IEnumerable<R>> selector, Func<T, IEnumerable<T>> children) {
            foreach (var item in self) {
                foreach (var r in selector(item)) {
                    yield return r;
                }
                foreach (var child in children(item).Flatten(selector, children)) {
                    yield return child;
                }
            }
        }

        public static IEnumerable<TResult> Flatten<T,TResult,U>(this IEnumerable<T> self, Func<U, IEnumerable<T>> children) where TResult : T where U : T {
            if (self == null) {
                throw new ArgumentNullException("self");
            }

            foreach (var item in self.OfType<TResult>()) {
                yield return item;
            }

            foreach (var child in self.OfType<U>().SelectMany(item2 => children(item2).Flatten<T,TResult, U>(children))) {
                yield return child;
            }
        }
    }
}


text:
require 'capistrano/recipes/deploy/scm/subversion'

# use switch instead of update to sync the subversion repository (so that it handles a possible repository change)
Capistrano::Deploy::SCM::Subversion.class_eval do
  def sync(revision, destination)
    scm :switch, verbose, authentication, "-r#{revision}", repository, destination
  end
end


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// The interface IWorkbookWorksheetPivotTablesCollectionRequestBuilder.
    /// </summary>
    public partial interface IWorkbookWorksheetPivotTablesCollectionRequestBuilder
    {
        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <returns>The built request.</returns>
        IWorkbookWorksheetPivotTablesCollectionRequest Request();

        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <param name="options">The query and header options for the request.</param>
        /// <returns>The built request.</returns>
        IWorkbookWorksheetPivotTablesCollectionRequest Request(IEnumerable<Option> options);

        /// <summary>
        /// Gets an <see cref="IWorkbookPivotTableRequestBuilder"/> for the specified WorkbookPivotTable.
        /// </summary>
        /// <param name="id">The ID for the WorkbookPivotTable.</param>
        /// <returns>The <see cref="IWorkbookPivotTableRequestBuilder"/>.</returns>
        IWorkbookPivotTableRequestBuilder this[string id] { get; }

        /// <summary>
        /// Gets the request builder for WorkbookPivotTableRefreshAll.
        /// </summary>
        /// <returns>The <see cref="IWorkbookPivotTableRefreshAllRequestBuilder"/>.</returns>
        IWorkbookPivotTableRefreshAllRequestBuilder RefreshAll();
    }
}


text:
<c-addon>

            Select a provider:

                    <input id="provider-virtualbox" data-bind="checked: provider" type="radio" value="virtualbox" />
                    VirtualBox

            Select a distribution:

                    <input id="distro-ubuntu140464" data-bind="checked: distribution" type="radio" value="ubuntu/trusty64" />
                    Ubuntu Trusty 14.04 LTS x64

                    <input id="distro-ubuntu140432" data-bind="checked: distribution" type="radio" value="ubuntu/trusty32" />
                    Ubuntu Trusty 14.04 LTS x32

            IP Address:
            <input type="text" class="form-control" id="ip-address" placeholder="Enter IPv4 Address" data-bind="value: ip" />

            Hostname:
            <input type="text" class="form-control" id="hostname" placeholder="Hostname" data-bind="value: hostname" />

            Memory:
            <input type="number" class="form-control" id="memory" placeholder="Enter Memory in MB" data-bind="value: memory" />

            CPU's:
            <input type="number" class="form-control" id="cpu" placeholder="Enter number of CPU's" data-bind="value: cpu_count" />

            Forward Ports:

                    Host port:
                    <input type="number" class="form-control" id="host-port" placeholder="Host port" data-bind="value: host" />

                    VM port:
                    <input type="number" class="form-control" id="vm-port" placeholder="VM port" data-bind="value: vm" />

              Add forward port

            Synced Folders:

                    Folder Source:
                    <input type="text" class="form-control" id="from" placeholder="Folder Source" data-bind="value: from" />

                    Folder Target:
                    <input type="text" class="form-control" id="to" placeholder="Folder Target" data-bind="value: to" />

                        Shared Folder Type

                                <input id="type" data-bind="checked: type" type="radio" value="default" />
                                Default

                                <input data-bind="checked: type" type="radio" value="nfs" />
                                NFS

                                <input data-bind="checked: type" type="radio" value="smb" />
                                Samba

                                <input data-bind="checked: type" type="radio" value="rsync" />
                                RSync

              Add synced folder

</c-addon>


text:
package es.agustruiz.deadpoolcomics.presentation.navigator;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import javax.inject.Inject;
import javax.inject.Singleton;

import es.agustruiz.deadpoolcomics.Utils;
import es.agustruiz.deadpoolcomics.presentation.model.ComicPresentation;
import es.agustruiz.deadpoolcomics.presentation.view.activity.BaseActivity;
import es.agustruiz.deadpoolcomics.presentation.view.activity.ComicDetailsActivity;
import es.agustruiz.deadpoolcomics.presentation.view.activity.ComicListActivity;

@Singleton
public class Navigator {

//    private static final String LOG_TAG = Navigator.class.getSimpleName()+ Utils.AGUST_TAG;

    @Inject
    public void Navigator(){
        // Empty
    }

    public void goToComicList(Context context){
        if(context!=null){
            context.startActivity(new Intent(context, ComicListActivity.class));
        }
    }

    public void goToComicDetails(Context context, int comicId){
        if (context != null) {
            context.startActivity(ComicDetailsActivity.getCallingIntent(context, comicId));
        }
    }

}


text:
//Opens a socket with the server.
//Updates the speed, previous time, current time,
//throttle percentage and brake percentage.

$(document).ready(function(){
    var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');

    //updates the car speed
    socket.on('updateSpeed', function(msg) {
        $('#speed_list').html('' + msg.speed + '');
    });
    setInterval(getSpeed, 180);
    function getSpeed() {
        socket.emit('update', {data : {}});
    }

    //updates the previous time and displays on the testing dashboard
    socket.on('updatePtime', function(msg) {
        $('#prev_time').html('
' + msg.prev + '
');
    });
    setInterval(getPtime, 100);
    function getPtime() {
        socket.emit('update ptime', {data : {}});
    }

    //updates the current time and displays on the testing dashboard
    socket.on('updateCtime', function(msg) {
        $('#curr_time').html('
' + msg.curr + '
');
    });
    setInterval(getCtime, 100);
    function getCtime() {
        socket.emit('current time', {data : {}});
    }

    //updates the brake fill and displays to the left of the speed
    socket.on('updateBrake', function(msg) {
        var b_percent = msg.brake * 100;
        var str_b_percent = b_percent.toString();
        var brake = str_b_percent.concat("%");
        $(".brake_bar_fill").css( "height", brake );
    });
    setInterval(getBrake, 80);
    function getBrake() {
        socket.emit('update brake', {data : {}});
    }

    //updates the throttle fill and displays to the right of the speed
    socket.on('updateThrottle', function(msg) {
        var throt_p =  msg.throttle*100;
        var str_throttle = throt_p.toString();
        var throttle = str_throttle.concat("%");
        $(".throttle_bar_fill").css("height", throttle );
    });
    setInterval(getThrottle, 80);
    function getThrottle() {
        socket.emit('update throttle', {data : {}});
    }

    //Displays an S if wheel spinning
    socket.on('updateSpin', function(msg) {
        var spin = msg.spin;
        if (spin) {
            $(".upper_left").css("color", "#D80000");
        }
    })
    setInterval(getSpin, 200);
    function getSpin() {
        socket.emit('update spin', {data: {}});
    }

    //Display an L if wheel locking
    socket.on('updateLock', function(msg) {
        var lock = msg.lock;
        if (lock) {
            $(".upper_right").css("color", "#D80000");
        }
    })
    setInterval(getLock, 200);
    function getLock() {
        socket.emit('update lock', {data: {}});
    }

 });


text:
package org.scalacoin.protocol.rpc

import org.scalacoin.marshallers.MarshallerUtil
import org.scalacoin.marshallers.rpc.bitcoincore.blockchain.{BlockchainInfoMarshaller, ConfirmedUnspentTransactionOutputMarshaller, MemPoolInfoMarshaller}
import org.scalacoin.marshallers.rpc.bitcoincore.mining.MiningInfoMarshaller
import org.scalacoin.marshallers.rpc.bitcoincore.networking.NetworkMarshaller
import org.scalacoin.marshallers.rpc.bitcoincore.wallet.WalletMarshaller
import org.scalacoin.protocol.Address
import org.scalacoin.protocol.rpc.bitcoincore.blockchain.{BlockchainInfo, ConfirmedUnspentTransactionOutput, MemPoolInfo}
import org.scalacoin.protocol.rpc.bitcoincore.mining.GetMiningInfo
import org.scalacoin.protocol.rpc.bitcoincore.networking.{NetworkInfo, PeerInfo}
import org.scalacoin.protocol.rpc.bitcoincore.wallet.WalletInfo
import spray.json._

import scala.sys.process._

/**
 * Created by Tom on 1/14/2016.
 */
class ScalaRPCClient (client : String, network : String) extends MarshallerUtil {
  /**
   * Refer to this reference for list of RPCs
   * https://bitcoin.org/en/developer-reference#rpcs
 *
   * @param command
   * @return
   */
  def sendCommand(command : String) : String = {
    val cmd = client + " " + network + " " + command
    val result = cmd.!!
    result
  }

  /**
   * This will stop the server
 *
   * @return
   */
  def stop = sendCommand("stop")

  /**
   * The number of blocks in the local best block chain. For a new node with only the hardcoded genesis block,
   * this number will be 0
   * https://bitcoin.org/en/developer-reference#getblockcount
 *
   * @return
   */
  def getBlockCount : Int = sendCommand("getblockcount").trim.toInt

  /**
   * The getmempoolinfo RPC returns information about the node's current transaction memory pool.
   * https://bitcoin.org/en/developer-reference#getmempoolinfo
 *
   * @return
   */
  def getMemPoolInfo : MemPoolInfo = {
    val result : String = sendCommand("getmempoolinfo")
    MemPoolInfoMarshaller.MemPoolInfoFormatter.read(result.parseJson)
  }

  /**
   * Information about the current state of the local block chain.
   * https://bitcoin.org/en/developer-reference#getblockchaininfo
 *
   * @return
   */
  def getBlockChainInfo : BlockchainInfo = {
    val result : String = sendCommand("getblockchaininfo")
    BlockchainInfoMarshaller.BlockchainInfoFormatter.read(result.parseJson)
  }

  /**
   * The gettxoutsetinfo RPC returns statistics about the confirmed unspent transaction output (UTXO) set.
   * Note that this call may take some time and that it only counts outputs from confirmed transactions—it does
   * not count outputs from the memory pool.
   * https://bitcoin.org/en/developer-reference#gettxoutsetinfo
 *
   * @return
   */
  def getTxOutSetInfo : ConfirmedUnspentTransactionOutput = {
    val result : String = sendCommand("gettxoutsetinfo")
    ConfirmedUnspentTransactionOutputMarshaller.ConfirmedUnspentTransactionOutputFormatter.read(result.parseJson)
  }

  /**
   * The getmininginfo RPC returns various mining-related information.
   * https://bitcoin.org/en/developer-reference#getmininginfo
 *
   * @return
   */
  def getMiningInfo : GetMiningInfo = {
    val result : String = sendCommand("getmininginfo")
    MiningInfoMarshaller.MiningInfoFormatter.read(result.parseJson)
  }

  /**
   * The getnetworkinfo RPC returns information about the node's connection to the network.
   * https://bitcoin.org/en/developer-reference#getnetworkinfo
 *
   * @return
   */
  def getNetworkInfo : NetworkInfo = {
    val result : String = sendCommand("getnetworkinfo")
    NetworkMarshaller.NetworkInfoFormatter.read(result.parseJson)
  }

  /**
   * The getpeerinfo RPC returns data about each connected network node.
   * https://bitcoin.org/en/developer-reference#getpeerinfo
 *
   * @return
   */
  def getPeerInfo : Seq[PeerInfo] = {
    val result : String = sendCommand("getpeerinfo")
    val json = result.parseJson
    convertToPeerInfoSeq(json)
  }

  /**
   * The getwalletinfo RPC provides information about the wallet.
   * https://bitcoin.org/en/developer-reference#getwalletinfo
 *
   * @return
   */
  def getWalletInfo : WalletInfo = {
    val result : String = sendCommand("getwalletinfo")
    WalletMarshaller.WalletFormatter.read(result.parseJson)
  }

  /**
   * The difficulty of creating a block with the same target threshold (nBits) as the highest-height block in the local
   * best block chain. The number is a a multiple of the minimum difficulty
   * https://bitcoin.org/en/developer-reference#getdifficulty
 *
   * @return
   */
  def getDifficulty : Double = sendCommand("getdifficulty").trim.toDouble

  /**
   * The getnewaddress RPC returns a new Bitcoin address for receiving payments. If an account is specified,
   * payments received with the address will be credited to that account.
   * https://bitcoin.org/en/developer-reference#getnewaddress
 *
   * @return
   */
  def getNewAddress : String = sendCommand("getnewaddress")

  /**
   * The getrawchangeaddress RPC returns a new Bitcoin address for receiving change. This is for use with raw
   * transactions, not normal use.
   * https://bitcoin.org/en/developer-reference#getrawchangeaddress
 *
   * @return
   */
  def getRawChangeAddress : String = sendCommand("getrawchangeaddress")

  /**
   * The getbalance RPC gets the balance in decimal bitcoins across all accounts or for a particular account.
   * https://bitcoin.org/en/developer-reference#getbalance
 *
   * @return
   */
  def getBalance : Double = sendCommand("getbalance").toDouble

  /**
   * The hash of the block header from the most recent block on the best block chain,
   * encoded as hex in RPC byte order
   * https://bitcoin.org/en/developer-reference#getbalance
 *
   * @return
   */
  def getBestBlockHash : String = sendCommand("getbestblockhash")

  /**
    * Returns a p2sh address and adds it to the wallet.
    * https://bitcoin.org/en/developer-reference#addmultisigaddress
 *
    * @param sigsRequired
    * @param addressesInJsonFormat
    * @return
    */

  /*
   def sendCommand(command : String) : String = {
    val cmd = client + " " + network + " " + command
    val result = cmd.!!
    result
  }
   */
  def generateMultiSigAddress(sigsRequired : Int, addressesInJsonFormat: String) : Address = {
    val cmd = "addmultisigaddress " + sigsRequired + " " + addressesInJsonFormat
    val result : String = sendCommand(cmd)
    Address(result)
  }

  def createMultiSigAddress(sigsRequired: Int, addressesInJsonFormat : String) : String = {
    val cmd = "createmultisig " + sigsRequired + " " + addressesInJsonFormat
    val result : String = sendCommand(cmd)
    result
  }

  def multi(command : String, sigsRequired : Int, addressesInJsonFormat : String) : String = {
    val cmd = command + " " + sigsRequired + " " + addressesInJsonFormat
    sendCommand(cmd)
  }
}


text:
class Maxminddb
  def bye
    self.hello + " bye"
  end
end


text:
package org.deeplearning4j.nn.weights;

import org.deeplearning4j.nn.conf.ConvolutionMode;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.*;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.junit.Test;
import org.nd4j.linalg.activations.impl.ActivationIdentity;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;

import static org.junit.Assert.assertEquals;

/**
 * Test cases for {@link WeightInitIdentity}
 *
 * @author Christian Skarby
 */
public class WeightInitIdentityTest {

    /**
     * Test identity mapping for 1d convolution
     */
    @Test
    public void testIdConv1D() {
        final INDArray input = Nd4j.randn(DataType.FLOAT, 1,5,7);
        final String inputName = "input";
        final String conv = "conv";
        final String output = "output";
        final ComputationGraph graph = new ComputationGraph(new NeuralNetConfiguration.Builder()
                .graphBuilder()
                .setInputTypes(InputType.inferInputType(input))
                .addInputs(inputName)
                .setOutputs(output)
                .layer(conv, new Convolution1DLayer.Builder(7)
                        .convolutionMode(ConvolutionMode.Same)
                        .nOut(input.size(1))
                        .weightInit(new WeightInitIdentity())
                        .activation(new ActivationIdentity())
                        .build(), inputName)
                .layer(output, new RnnLossLayer.Builder().activation(new ActivationIdentity()).build(), conv)
                .build());
        graph.init();

        assertEquals("Mapping was not identity!", input, graph.outputSingle(input).reshape(input.shape()));
    }

    /**
     * Test identity mapping for 2d convolution
     */
    @Test
    public void testIdConv2D() {
        final INDArray input = Nd4j.randn(DataType.FLOAT,1,5,7,11);
        final String inputName = "input";
        final String conv = "conv";
        final String output = "output";
        final ComputationGraph graph = new ComputationGraph(new NeuralNetConfiguration.Builder()
                .graphBuilder()
                .setInputTypes(InputType.inferInputType(input))
                .addInputs(inputName)
                .setOutputs(output)
                .layer(conv, new ConvolutionLayer.Builder(3,5)
                        .convolutionMode(ConvolutionMode.Same)
                        .nOut(input.size(1))
                        .weightInit(new WeightInitIdentity())
                        .activation(new ActivationIdentity())
                        .build(), inputName)
                .layer(output, new CnnLossLayer.Builder().activation(new ActivationIdentity()).build(), conv)
                .build());
        graph.init();

        assertEquals("Mapping was not identity!", input, graph.outputSingle(input));
    }

    /**
     * Test identity mapping for 3d convolution
     */
    @Test
    public void testIdConv3D() {
        final INDArray input = Nd4j.randn(DataType.FLOAT, 1,5,7,11,13);
        final String inputName = "input";
        final String conv = "conv";
        final String output = "output";
        final ComputationGraph graph = new ComputationGraph(new NeuralNetConfiguration.Builder()
                .graphBuilder()
                .setInputTypes(InputType.inferInputType(input))
                .addInputs(inputName)
                .setOutputs(output)
                .layer(conv, new Convolution3D.Builder(3,7,5)
                        .convolutionMode(ConvolutionMode.Same)
                        .dataFormat(Convolution3D.DataFormat.NCDHW)
                        .nOut(input.size(1))
                        .weightInit(new WeightInitIdentity())
                        .activation(new ActivationIdentity())
                        .build(), inputName)
                .layer(output, new Cnn3DLossLayer.Builder(Convolution3D.DataFormat.NCDHW).activation(new ActivationIdentity()).build(), conv)
                .build());
        graph.init();

        assertEquals("Mapping was not identity!", input, graph.outputSingle(input));
    }
}


text:
<!doctype html>
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if (gte IE 9)| IEMobile |!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
    <head>
        <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="csrf-param" content="7vf95Qo6ovib_R3EXTwwPL-v">

        <title><?php echo GUST_TITLE; ?> · <?php echo GUST_VERSION; ?></title>
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
        <meta name="apple-mobile-web-app-capable" content="yes" />

        <link rel="shortcut icon" href="/wp-admin/images/wp-logo-2x.png">
        <meta http-equiv="cleartype" content="on">

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700&subset=latin,latin-ext">
        <link rel="stylesheet" href="<?php echo GUST_PLUGIN_URL; ?>/assets/screen.css"/>
        <link rel="stylesheet" href="<?php echo GUST_PLUGIN_URL; ?>/assets/jquery.nouislider.min.css"/>
        <link rel="stylesheet" href="//cdn.jsdelivr.net/codemirror/3.14.0/codemirror.css"/>
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css"/>
    </head>
    <body class="<?php echo ($body_class?$body_class:'manage'); ?>">


text:
package com.leacox.motif.extract;

import com.leacox.motif.extract.matchers.Matcher;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Abstract base class for all DecomposableMatchBuilder classes.
 *
 * @author John Leacox
 */
public abstract class DecomposableMatchBuilder<T> {
  final List<Matcher<Object>> fieldMatchers;
  final FieldExtractor<T> fieldExtractor;

  DecomposableMatchBuilder(List<Matcher<Object>> fieldMatchers, FieldExtractor<T> fieldExtractor) {
    this.fieldMatchers = fieldMatchers;
    this.fieldExtractor = fieldExtractor;
  }

  protected TreeMap<Integer, List<Matcher<Object>>> getChildMatchersByIndex(
      Map<Integer, DecomposableMatchBuilder> nestedBuildersByIndex) {
    TreeMap<Integer, List<Matcher<Object>>> childMatchersByIndex = new TreeMap<>();
    for (Map.Entry<Integer, DecomposableMatchBuilder> entry : nestedBuildersByIndex.entrySet()) {
      childMatchersByIndex.put(entry.getKey(), entry.getValue().fieldMatchers);
    }

    return childMatchersByIndex;
  }

  protected List<Matcher<Object>> getChildMatchers(
      Map<Integer, DecomposableMatchBuilder> nestedBuildersByIndex) {
    TreeMap<Integer, List<Matcher<Object>>> childMatchersByIndex =
        getChildMatchersByIndex(nestedBuildersByIndex);

    return NestedMatchers.buildNestedMatchers(this.fieldMatchers, childMatchersByIndex);
  }

  protected TreeMap<Integer, FieldExtractor> getChildExtractorsByIndex(
      Map<Integer, DecomposableMatchBuilder> nestedBuildersByIndex) {
    TreeMap<Integer, FieldExtractor> childExtractorsByIndex = new TreeMap<>();
    for (Map.Entry<Integer, DecomposableMatchBuilder> entry : nestedBuildersByIndex.entrySet()) {
      childExtractorsByIndex.put(entry.getKey(), entry.getValue().fieldExtractor);
    }

    return childExtractorsByIndex;
  }

  protected NestedFieldExtractor<T> getNestedFieldExtractor(
      Map<Integer, DecomposableMatchBuilder> buildersByIndex) {
    return new NestedFieldExtractor<>(fieldExtractor, getChildExtractorsByIndex(buildersByIndex));
  }
}


text:
package org.apache.jsieve.comparators;

import org.apache.jsieve.exception.SievePatternException;

/**
 * Class AsciiCasemap implements the EQUALITY operation of the i;ascii-casemap
 * comparator as defined by RFC2244, section 3.4 - "With this function the
 * values "hello" and "HELLO" have the same ordinal value and are considered
 * equal".
 */
public class AsciiCasemap implements Comparator {

    /**
     * Constructor for AsciiCasemap.
     */
    public AsciiCasemap() {
        super();
    }

    /**
     * @see org.apache.jsieve.comparators.Equals#equals(String, String)
     */
    public boolean equals(String string1, String string2) {
        return ComparatorUtils.equals(string1.toUpperCase(), string2
                .toUpperCase());
    }

    /**
     * @see org.apache.jsieve.comparators.Contains#contains(String, String)
     */
    public boolean contains(String container, String content) {
        return ComparatorUtils.contains(container.toUpperCase(), content
                .toUpperCase());
    }

    /**
     * @see org.apache.jsieve.comparators.Matches#matches(String, String)
     */
    public boolean matches(String string, String glob)
            throws SievePatternException {
        return ComparatorUtils
                .matches(string.toUpperCase(), glob.toUpperCase());
    }

}