text:
//
//  AsyncSocket.m
//
//  Created by Dustin Voss on Wed Jan 29 2003.
//  This class is in the public domain.
//  If used, I'd appreciate it if you credit me.
//
//  E-Mail: d-j-v@earthlink.net
//

#import "AsyncSocket.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>

#pragma mark Declarations

#define READQUEUE_CAPACITY	5			/* Initial capacity. */
#define WRITEQUEUE_CAPACITY 5			/* Initial capacity. */
#define READALL_CHUNKSIZE	256			/* Incremental increase in buffer size. */
#define WRITE_CHUNKSIZE		(4*1024)	/* Limit on size of each write pass. */

#define POLL_INTERVAL		1.0			/* Timer to check for overlooked activity. */

NSString *const AsyncSocketException = @"AsyncSocketException";
NSString *const AsyncSocketErrorDomain = @"AsyncSocketErrorDomain";

// This is a mutex lock used by all instances of AsyncSocket, to protect getaddrinfo.
// The man page says it is not thread-safe.
NSString *getaddrinfoLock = @"lock";

enum AsyncSocketFlags
{
	kDidCallConnectDeleg = 0x01,	// If set, connect delegate has been called.
	kDidPassConnectMethod = 0x02,	// If set, disconnection results in delegate call.
	kForbidReadsWrites = 0x04,		// If set, no new reads or writes are allowed.
	kDisconnectSoon = 0x08			// If set, disconnect as soon as nothing is queued.
};

@interface AsyncSocket (Private)
- (BOOL) isSocketConnected;
- (BOOL) areStreamsConnected;
- (NSString *) connectedHost: (CFSocketRef)socket;
- (UInt16) connectedPort: (CFSocketRef)socket;
- (NSString *) localHost: (CFSocketRef)socket;
- (UInt16) localPort: (CFSocketRef)socket;
- (NSString *) addressHost: (CFDataRef)cfaddr;
- (UInt16) addressPort: (CFDataRef)cfaddr;
- (void) doCFCallback:(CFSocketCallBackType)type forSocket:(CFSocketRef)sock withAddress:(NSData *)address withData:(const void *)pData;
- (void) doCFReadStreamCallback:(CFStreamEventType)type forStream:(CFReadStreamRef)stream;
- (void) doCFWriteStreamCallback:(CFStreamEventType)type forStream:(CFWriteStreamRef)stream;
- (void) doAcceptWithSocket:(CFSocketNativeHandle)newSocket;
- (void) doFinishConnectWithError:(SInt32)err;
- (BOOL) createStreamsFromNative:(CFSocketNativeHandle)native error:(NSError **)errPtr;
- (BOOL) createStreamsToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr;
- (NSData *) sockaddrFromString:(NSString *)addrStr port:(UInt16)port error:(NSError **)errPtr;
- (BOOL) setSocketFromStreamsAndReturnError:(NSError **)errPtr;
- (CFSocketRef) createAcceptSocketForAddress:(NSData *)addr error:(NSError **)errPtr;
- (void) attachAcceptSockets;
- (BOOL) attachStreamsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr;
- (BOOL) configureStreamsAndReturnError:(NSError **)errPtr;
- (BOOL) openStreamsAndReturnError:(NSError **)errPtr;
- (void) doStreamOpen;
- (void) closeWithError:(NSError *)err;
- (void) recoverUnreadData;
- (void) emptyQueues;
- (void) close;
- (NSError *) getAbortError;
- (NSError *) getStreamError;
- (NSError *) getSocketError;
- (NSError *) getReadTimeoutError;
- (NSError *) getWriteTimeoutError;
- (NSError *) errorFromCFStreamError:(CFStreamError)err;
- (void) maybeScheduleDisconnect;
- (void) doBytesAvailable;
- (void) completeCurrentRead;
- (void) endCurrentRead;
- (void) scheduleDequeueRead;
- (void) maybeDequeueRead;
- (void) doReadTimeout:(NSTimer *)timer;
- (void) doSendBytes;
- (void) completeCurrentWrite;
- (void) endCurrentWrite;
- (void) scheduleDequeueWrite;
- (void) maybeDequeueWrite;
- (void) doWriteTimeout:(NSTimer *)timer;
- (void) doPoll:(NSTimer *)timer;
@end

static void MyCFSocketCallback (CFSocketRef, CFSocketCallBackType, CFDataRef, const void *, void *);
static void MyCFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo);
static void MyCFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType type, void *pInfo);

#pragma mark -
#pragma mark AsyncReadPacket

@interface AsyncReadPacket : NSObject
{
@public
	NSMutableData *buffer;
	CFIndex bytesDone;
	NSTimeInterval timeout;
	long tag;
	NSData *term;
	BOOL readAllAvailableData;
}
- (id)initWithData:(NSMutableData *)d timeout:(NSTimeInterval)t tag:(long)i readAllAvailable:(BOOL)a terminator:(NSData *)e bufferOffset:(CFIndex)b;
- (void)dealloc;
@end

@implementation AsyncReadPacket
- (id)initWithData:(NSMutableData *)d timeout:(NSTimeInterval)t tag:(long)i readAllAvailable:(BOOL)a terminator:(NSData *)e  bufferOffset:(CFIndex)b
{
	self = [super init];
	buffer = [d retain];
	timeout = t;
	tag = i;
	term = [e copy];
	bytesDone = b;
	readAllAvailableData = a;
	return self;
}
- (void)dealloc
{
	[buffer release];
	[term release];
	[super dealloc];
}
@end

#pragma mark -
#pragma mark AsyncWritePacket

@interface AsyncWritePacket : NSObject
{
	@public
	NSData *buffer;
	CFIndex bytesDone;
	long tag;
	NSTimeInterval timeout;
}
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
- (void)dealloc;
@end

@implementation AsyncWritePacket
- (id)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i;
{
	self = [super init];
	buffer = [d retain];
	timeout = t;
	tag = i;
	bytesDone = 0;
	return self;
}
- (void)dealloc
{
	[buffer release];
	[super dealloc];
}
@end

@implementation AsyncSocket

#pragma mark -
#pragma mark Initialization

- (id) init
{
	return [self initWithDelegate:nil userData:0];
}

- (id) initWithDelegate:(id)delegate
{
	return [self initWithDelegate:delegate userData:0];
}

// Designated initializer.
- (id) initWithDelegate:(id)delegate userData:(long)userData
{
	self = [super init];

	theFlags = 0x00;
	theDelegate = delegate;
	theUserData = userData;
	thePollTimer = nil;

	theSocket = NULL;
	theSource = NULL;
	theSocket6 = NULL;
	theSource6 = NULL;
	theRunLoop = NULL;
	theReadStream = NULL;
	theWriteStream = NULL;

	theReadQueue = [[NSMutableArray alloc] initWithCapacity:READQUEUE_CAPACITY];
	theCurrentRead = nil;
	theReadTimer = nil;

	partialReadBuffer = nil;

	theWriteQueue = [[NSMutableArray alloc] initWithCapacity:WRITEQUEUE_CAPACITY];
	theCurrentWrite = nil;
	theWriteTimer = nil;

	// Socket context
	NSAssert (sizeof(CFSocketContext) == sizeof(CFStreamClientContext), @"CFSocketContext and CFStreamClientContext aren't the same size anymore. Contact the developer.");
	theContext.version = 0;
	theContext.info = self;
	theContext.retain = nil;
	theContext.release = nil;
	theContext.copyDescription = nil;

	return self;
}

// The socket may been initialized in a connected state and auto-released, so this should close it down cleanly.
- (void) dealloc
{
	[self close];
	[theReadQueue release];
	[theWriteQueue release];
	[NSObject cancelPreviousPerformRequestsWithTarget: theDelegate selector: @selector(onSocketDidDisconnect:) object:self];
	[NSObject cancelPreviousPerformRequestsWithTarget: self];
	[super dealloc];
}

#pragma mark -
#pragma mark Accessors

- (long) userData
{
	return theUserData;
}

- (void) setUserData:(long)userData
{
	theUserData = userData;
}

- (id) delegate
{
	return theDelegate;
}

- (void) setDelegate:(id)delegate
{
	theDelegate = delegate;
}

- (BOOL) canSafelySetDelegate
{
	return ([theReadQueue count] == 0 && [theWriteQueue count] == 0 && theCurrentRead == nil && theCurrentWrite == nil);
}

- (CFSocketRef) getCFSocket
{
	return theSocket;
}

- (CFReadStreamRef) getCFReadStream
{
	return theReadStream;
}

- (CFWriteStreamRef) getCFWriteStream
{
	return theWriteStream;
}

- (float) progressOfReadReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total
{
	if (!theCurrentRead) return NAN;
	BOOL hasTotal = (theCurrentRead->readAllAvailableData == NO &&
					 theCurrentRead->term == nil);
	CFIndex d = theCurrentRead->bytesDone;
	CFIndex t = hasTotal ? [theCurrentRead->buffer length] : 0;
	if (tag != NULL)   *tag = theCurrentRead->tag;
	if (done != NULL)  *done = d;
	if (total != NULL) *total = t;
	float ratio = (float)d/(float)t;
	return isnan(ratio) ? 1.0 : ratio; // 0 of 0 bytes is 100% done.
}

- (float) progressOfWriteReturningTag:(long *)tag bytesDone:(CFIndex *)done total:(CFIndex *)total
{
	if (!theCurrentWrite) return NAN;
	CFIndex d = theCurrentWrite->bytesDone;
	CFIndex t = [theCurrentWrite->buffer length];
	if (tag != NULL)   *tag = theCurrentWrite->tag;
	if (done != NULL)  *done = d;
	if (total != NULL) *total = t;
	return (float)d/(float)t;
}

#pragma mark -
#pragma mark Class Methods

// Return line separators.
+ (NSData *) CRLFData
{ return [NSData dataWithBytes:"\x0D\x0A" length:2]; }

+ (NSData *) CRData
{ return [NSData dataWithBytes:"\x0D" length:1]; }

+ (NSData *) LFData
{ return [NSData dataWithBytes:"\x0A" length:1]; }

+ (NSData *) ZeroData
{ return [NSData dataWithBytes:"" length:1]; }

#pragma mark -
#pragma mark Connection

- (BOOL) acceptOnPort:(UInt16)port error:(NSError **)errPtr
{
	return [self acceptOnAddress:nil port:port error:errPtr];
}

// Setting up IPv4 and IPv6 accepting sockets.
- (BOOL) acceptOnAddress:(NSString *)hostaddr port:(UInt16)port error:(NSError **)errPtr
{
	if (theDelegate == NULL)
		[NSException raise:AsyncSocketException format:@"Attempting to accept without a delegate. Set a delegate first."];

	if (theSocket != NULL || theSocket6 != NULL)
		[NSException raise:AsyncSocketException format:@"Attempting to accept while connected or accepting connections. Disconnect first."];

	// Set up the listen sockaddr structs if needed.

	NSData *address = nil, *address6 = nil;
	if (hostaddr != nil && [hostaddr length] != 0)
	{
		address = [self sockaddrFromString:hostaddr port:port error:errPtr];
		if (!address) return NO;
	}
	else
	{
		// Set up the addresses.
		struct sockaddr_in nativeAddr =
		{
			/*sin_len*/			sizeof(struct sockaddr_in),
			/*sin_family*/		AF_INET,
			/*sin_port*/		htons (port),
			/*sin_addr*/		{ htonl (INADDR_ANY) },
			/*sin_zero*/		{ 0 }
		};
		struct sockaddr_in6 nativeAddr6 =
		{
			/*sin6_len*/		sizeof(struct sockaddr_in6),
			/*sin6_family*/		AF_INET6,
			/*sin6_port*/		htons (port),
			/*sin6_flowinfo*/	0,
			/*sin6_addr*/		in6addr_any,
			/*sin6_scope_id*/	0
		};

		// Wrap the native address structures for CFSocketSetAddress.
		address = [NSData dataWithBytesNoCopy:&nativeAddr length:sizeof(nativeAddr) freeWhenDone:NO];
		address6 = [NSData dataWithBytesNoCopy:&nativeAddr6 length:sizeof(nativeAddr6) freeWhenDone:NO];
	}

	// Create the sockets.

	if (address)
	{
		theSocket = [self createAcceptSocketForAddress:address error:errPtr];
		if (theSocket == NULL) goto Failed;
	}

	if (address6)
	{
		theSocket6 = [self createAcceptSocketForAddress:address6 error:errPtr];
		if (theSocket6 == NULL) goto Failed;
	}

	[self attachAcceptSockets];

	// Set the SO_REUSEADDR flags.

	int reuseOn = 1;
	if (theSocket)	setsockopt (CFSocketGetNative(theSocket), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
	if (theSocket6)	setsockopt (CFSocketGetNative(theSocket6), SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));

	// Set the local bindings which causes the sockets to start listening.

	CFSocketError err;
	if (theSocket)
	{
		err = CFSocketSetAddress (theSocket, (CFDataRef)address);
		if (err != kCFSocketSuccess) goto Failed;
	}
	if (theSocket6)
	{
		err = CFSocketSetAddress (theSocket6, (CFDataRef)address6);
		if (err != kCFSocketSuccess) goto Failed;
	}

	theFlags |= kDidPassConnectMethod;
	return YES;

Failed:;
	if (errPtr) *errPtr = [self getSocketError];
	return NO;
}

- (BOOL) connectToHost:(NSString*)hostname onPort:(UInt16)port error:(NSError **)errPtr
{
	if (theDelegate == NULL)
		[NSException raise:AsyncSocketException format:@"Attempting to connect without a delegate. Set a delegate first."];

	if (theSocket != NULL || theSocket6 != NULL)
		[NSException raise:AsyncSocketException format:@"Attempting to connect while connected or accepting connections. Disconnect first."];

	if (![self createStreamsToHost:hostname onPort:port error:errPtr]) goto Failed;
	if (![self attachStreamsToRunLoop:nil error:errPtr]) goto Failed;
	if (![self configureStreamsAndReturnError:errPtr]) goto Failed;
	if (![self openStreamsAndReturnError:errPtr]) goto Failed;

	theFlags |= kDidPassConnectMethod;
	return YES;

Failed:;
	[self close];
	return NO;
}

- (void) disconnect
{
	[self close];
}

- (void) disconnectAfterWriting
{
	theFlags |= kForbidReadsWrites;
	theFlags |= kDisconnectSoon;
	[self maybeScheduleDisconnect];
}

#pragma mark -
#pragma mark Accept Impl.

- (NSData *) sockaddrFromString:(NSString *)addrStr port:(UInt16)port error:(NSError **)errPtr
{
	NSData *resultData = nil;

	struct addrinfo hints = {0}, *result;
	hints.ai_family	 = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags	 = AI_NUMERICHOST | AI_PASSIVE;

	@synchronized (getaddrinfoLock)
	{
		NSData *addrStrData = [addrStr dataUsingEncoding:NSASCIIStringEncoding
									allowLossyConversion:YES];

		char portStr[] = "65535"; // Reserve space for max port number.
		snprintf(portStr, sizeof(portStr), "%u", port);

		int err = getaddrinfo ([addrStrData bytes], portStr,
							   (const struct addrinfo *)&hints,
							   (struct addrinfo **)&result);
		if (!err)
		{
			resultData = [NSData dataWithBytes:result->ai_addr
										length:result->ai_addrlen];
			freeaddrinfo (result);
		}
		else if (errPtr)
		{
			NSString *errMsg = [NSString stringWithCString: gai_strerror(err)
												  encoding: NSASCIIStringEncoding];

			NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
				errMsg, NSLocalizedDescriptionKey, nil];

			*errPtr = [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB"
									   code:err
								   userInfo:info];
		}
	}

	return resultData;
}

// Creates the accept sockets. Returns true if either IPv4 or IPv6 is created. If either is missing, an error is returned (even though the method may return true).
- (CFSocketRef) createAcceptSocketForAddress:(NSData *)addr error:(NSError **)errPtr
{
	struct sockaddr *pSockAddr = (struct sockaddr *)[addr bytes];
	int addressFamily = pSockAddr->sa_family;

	CFSocketRef socket = CFSocketCreate (kCFAllocatorDefault, addressFamily, SOCK_STREAM, 0, kCFSocketAcceptCallBack, (CFSocketCallBack)&MyCFSocketCallback, &theContext);

	if (socket == NULL && errPtr)
		*errPtr = [self getSocketError];

	return socket;
}

// Adds the sockets to the run-loop.
- (void) attachAcceptSockets
{
	theRunLoop = CFRunLoopGetCurrent();

	if (theSocket)
	{
		theSource  = CFSocketCreateRunLoopSource (kCFAllocatorDefault, theSocket, 0);
		CFRunLoopAddSource (theRunLoop, theSource, kCFRunLoopDefaultMode);
	}

	if (theSocket6)
	{
		theSource6 = CFSocketCreateRunLoopSource (kCFAllocatorDefault, theSocket6, 0);
		CFRunLoopAddSource (theRunLoop, theSource6, kCFRunLoopDefaultMode);
	}
}

// If I can't make the new socket, ignore this event.
- (void) doAcceptWithSocket:(CFSocketNativeHandle)newNative
{
	AsyncSocket *newSocket = [[[AsyncSocket alloc] initWithDelegate:theDelegate] autorelease];
	if (newSocket != nil)
	{
		NSRunLoop *runLoop = nil;
		if ([theDelegate respondsToSelector:@selector(onSocket:didAcceptNewSocket:)])
			[theDelegate onSocket:self didAcceptNewSocket:newSocket];

		if ([theDelegate respondsToSelector:@selector(onSocket:wantsRunLoopForNewSocket:)])
			runLoop = [theDelegate onSocket:self wantsRunLoopForNewSocket:newSocket];

		if (![newSocket createStreamsFromNative:newNative error:nil]) goto Failed;
		if (![newSocket attachStreamsToRunLoop:runLoop error:nil]) goto Failed;
		if (![newSocket configureStreamsAndReturnError:nil]) goto Failed;
		if (![newSocket openStreamsAndReturnError:nil]) goto Failed;

		newSocket->theFlags |= kDidPassConnectMethod;
	}
	return;

Failed:;
	// No NSError, but errors will still get logged from the above functions.
	[newSocket close];
	return;
}

#pragma mark -
#pragma mark Connect Impl.

// Creates the socket from a native socket.
- (BOOL) createStreamsFromNative:(CFSocketNativeHandle)native error:(NSError **)errPtr
{
	// Create the socket & streams.
	CFStreamCreatePairWithSocket (kCFAllocatorDefault, native, &theReadStream, &theWriteStream);
	if (theReadStream == NULL || theWriteStream == NULL)
	{
		NSError *err = [self getStreamError];
		NSLog (@"AsyncSocket %p couldn't create streams from accepted socket, %@", self, err);
		if (errPtr) *errPtr = err;
		return NO;
	}

	return YES;
}

- (BOOL) createStreamsToHost:(NSString *)hostname onPort:(UInt16)port error:(NSError **)errPtr
{
	// Create the socket & streams.
	CFStreamCreatePairWithSocketToHost (kCFAllocatorDefault, (CFStringRef)hostname, port, &theReadStream, &theWriteStream);
	if (theReadStream == NULL || theWriteStream == NULL)
	{
		if (errPtr) *errPtr = [self getStreamError];
		return NO;
	}

	return YES;
}

- (BOOL) attachStreamsToRunLoop:(NSRunLoop *)runLoop error:(NSError **)errPtr
{
	// Get the CFRunLoop to which the socket should be attached.
	theRunLoop = (runLoop == nil) ? CFRunLoopGetCurrent() : [runLoop getCFRunLoop];

	// Make read stream non-blocking.
	if (!CFReadStreamSetClient (theReadStream,
		kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered | kCFStreamEventOpenCompleted,
		(CFReadStreamClientCallBack)&MyCFReadStreamCallback,
		(CFStreamClientContext *)(&theContext) ))
	{
		NSLog (@"AsyncSocket %p couldn't attach read stream to run-loop,", self);
		goto Failed;
	}
	CFReadStreamScheduleWithRunLoop (theReadStream, theRunLoop, kCFRunLoopDefaultMode);

	// Make write stream non-blocking.
	if (!CFWriteStreamSetClient (theWriteStream,
		kCFStreamEventCanAcceptBytes | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered | kCFStreamEventOpenCompleted,
		(CFWriteStreamClientCallBack)&MyCFWriteStreamCallback,
		(CFStreamClientContext *)(&theContext) ))
	{
		NSLog (@"AsyncSocket %p couldn't attach write stream to run-loop,", self);
		goto Failed;
	}
	CFWriteStreamScheduleWithRunLoop (theWriteStream, theRunLoop, kCFRunLoopDefaultMode);

	return YES;

Failed:;
	NSError *err = [self getStreamError];
	NSLog (@"%@", err);
	if (errPtr) *errPtr = err;
	return NO;
}

- (BOOL) configureStreamsAndReturnError:(NSError **)errPtr
{
	// Ensure the CF & BSD socket is closed when the streams are closed.
	CFReadStreamSetProperty(theReadStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
	CFWriteStreamSetProperty(theWriteStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);

	// Call the delegate method for further configuration.
	if ([theDelegate respondsToSelector:@selector(onSocketWillConnect:)])
		if ([theDelegate onSocketWillConnect:self] == NO)
			goto Aborted;

	return YES;

Aborted:;
	NSError *err = [self getAbortError];
	if (errPtr) *errPtr = err;
	return NO;
};

- (BOOL) openStreamsAndReturnError:(NSError **)errPtr
{
	if (!CFReadStreamOpen (theReadStream))
	{
		NSLog (@"AsyncSocket %p couldn't open read stream,", self);
		goto Failed;
	}

	if (!CFWriteStreamOpen (theWriteStream))
	{
		NSLog (@"AsyncSocket %p couldn't open write stream,", self);
		goto Failed;
	}

	return YES;

Failed:;
	NSError *err = [self getStreamError];
	NSLog (@"%@", err);
	if (errPtr) *errPtr = err;
	return NO;
}

// Called when read or write streams open. When the socket is connected and both streams are open, consider the AsyncSocket instance to be ready.
- (void) doStreamOpen
{
	NSError *err = nil;
	if ([self areStreamsConnected] && !(theFlags & kDidCallConnectDeleg))
	{
		// Get the socket.
		if (![self setSocketFromStreamsAndReturnError: &err])
		{
			NSLog (@"AsyncSocket %p couldn't get socket from streams, %@. Disconnecting.", self, err);
			[self closeWithError:err];
		}

		// Schedule a poll timer to make up for lost ready-to-read/write notifications. This doesn't have to have a tight poll interval, since it is a backup system.
		thePollTimer = [NSTimer scheduledTimerWithTimeInterval:POLL_INTERVAL target:self selector:@selector(doPoll:) userInfo:nil repeats:YES];

		// Call the delegate.
		CFDataRef peer = CFSocketCopyPeerAddress (theSocket);
		theFlags |= kDidCallConnectDeleg;
		if ([theDelegate respondsToSelector:@selector(onSocket:didConnectToHost:port:)])
			[theDelegate onSocket:self
				 didConnectToHost:[self addressHost:peer]
							 port:[self addressPort:peer]];
		CFRelease (peer);

		// Immediately deal with any already-queued requests.
		[self maybeDequeueRead];
		[self maybeDequeueWrite];
	}
}

- (BOOL) setSocketFromStreamsAndReturnError:(NSError **)errPtr
{
	CFSocketNativeHandle native;
	CFDataRef nativeProp = CFReadStreamCopyProperty (theReadStream, kCFStreamPropertySocketNativeHandle);
	if (nativeProp == NULL)
	{
		if (errPtr) *errPtr = [self getStreamError];
		goto Failed;
	}

	CFDataGetBytes (nativeProp, CFRangeMake(0, CFDataGetLength(nativeProp)), (UInt8 *)&native);
	CFRelease (nativeProp);

	theSocket = CFSocketCreateWithNative (kCFAllocatorDefault, native, 0, NULL, NULL);
	if (theSocket == NULL)
	{
		if (errPtr) *errPtr = [self getSocketError];
		goto Failed;
	}

	return YES;

Failed:;
	return NO;
}

#pragma mark -
#pragma mark Disconnect Impl.

// Sends error message and disconnects.
- (void) closeWithError:(NSError *)err
{
	if (theFlags & kDidPassConnectMethod)
	{
		// Try to salvage what data we can.
		[self recoverUnreadData];

		// Let the delegate know, so it can try to recover if it likes.
		if ([theDelegate respondsToSelector:@selector(onSocket:willDisconnectWithError:)])
			[theDelegate onSocket:self willDisconnectWithError:err];
	}
	[self close];
}

// Prepare partially read data for recovery.
- (void) recoverUnreadData
{
	if (theCurrentRead) [theCurrentRead->buffer setLength: theCurrentRead->bytesDone];
	partialReadBuffer = (theCurrentRead ? [theCurrentRead->buffer copy] : nil);
	[self emptyQueues];
}

- (void) emptyQueues
{
	if (theCurrentRead != nil)	[self endCurrentRead];
	if (theCurrentWrite != nil)	[self endCurrentWrite];
	[theReadQueue removeAllObjects];
	[theWriteQueue removeAllObjects];
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueRead) object:nil];
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(maybeDequeueWrite) object:nil];
}

// Disconnects. This is called for both error and clean disconnections.
- (void) close
{
	// Stop polling.
	[thePollTimer invalidate];
	thePollTimer = nil;

	// Empty queues.
	[self emptyQueues];
	[partialReadBuffer release];
	partialReadBuffer = nil;
	[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(disconnect) object:nil];

	// Close streams.
	if (theReadStream != NULL)
	{
		CFReadStreamUnscheduleFromRunLoop (theReadStream, theRunLoop, kCFRunLoopDefaultMode);
		CFReadStreamClose (theReadStream);
		CFRelease (theReadStream);
		theReadStream = NULL;
	}
	if (theWriteStream != NULL)
	{
		CFWriteStreamUnscheduleFromRunLoop (theWriteStream, theRunLoop, kCFRunLoopDefaultMode);
		CFWriteStreamClose (theWriteStream);
		CFRelease (theWriteStream);
		theWriteStream = NULL;
	}

	// Close sockets.
	if (theSocket != NULL)
	{
		CFSocketInvalidate (theSocket);
		CFRelease (theSocket);
		theSocket = NULL;
	}
	if (theSocket6 != NULL)
	{
		CFSocketInvalidate (theSocket6);
		CFRelease (theSocket6);
		theSocket6 = NULL;
	}
	if (theSource != NULL)
	{
		CFRunLoopRemoveSource (theRunLoop, theSource, kCFRunLoopDefaultMode);
		CFRelease (theSource);
		theSource = NULL;
	}
	if (theSource6 != NULL)
	{
		CFRunLoopRemoveSource (theRunLoop, theSource6, kCFRunLoopDefaultMode);
		CFRelease (theSource6);
		theSource6 = NULL;
	}
	theRunLoop = NULL;

	// If the client has passed the connect/accept method, then the connection has at least begun. Notify delegate that it is now ending.
	if (theFlags & kDidPassConnectMethod)
	{
		// Delay notification to give him freedom to release without returning here and core-dumping.
		if ([theDelegate respondsToSelector: @selector(onSocketDidDisconnect:)])
			[theDelegate performSelector:@selector(onSocketDidDisconnect:) withObject:self afterDelay:0];
	}

	// Clear flags.
	theFlags = 0x00;
}

#pragma mark -
#pragma mark Errors

- (NSError *) getStreamError
{
	CFStreamError err;
	if (theReadStream != NULL)
	{
		err = CFReadStreamGetError (theReadStream);
		if (err.error != 0) return [self errorFromCFStreamError: err];
	}

	if (theWriteStream != NULL)
	{
		err = CFWriteStreamGetError (theWriteStream);
		if (err.error != 0) return [self errorFromCFStreamError: err];
	}

	return nil;
}

// Unfortunately, CFSocket offers no feedback on its errors.
- (NSError *) getSocketError
{
	NSString *errMsg = NSLocalizedStringWithDefaultValue
		(@"AsyncSocketCFSocketError", @"AsyncSocket", [NSBundle mainBundle],
		 @"General CFSocket error", nil);
	NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
						  errMsg, NSLocalizedDescriptionKey, nil];

	return [NSError errorWithDomain: AsyncSocketErrorDomain
							   code: AsyncSocketCFSocketError
						   userInfo: info];
}

- (NSError *) getAbortError
{
	NSString *errMsg = NSLocalizedStringWithDefaultValue
		(@"AsyncSocketCanceledError", @"AsyncSocket", [NSBundle mainBundle],
		 @"Connection canceled", nil);
	NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
						  errMsg, NSLocalizedDescriptionKey, nil];

	return [NSError errorWithDomain: AsyncSocketErrorDomain
							   code: AsyncSocketCanceledError
						   userInfo: info];
}

- (NSError *) getReadTimeoutError
{
	NSString *errMsg = NSLocalizedStringWithDefaultValue
		(@"AsyncSocketReadTimeoutError", @"AsyncSocket", [NSBundle mainBundle],
		 @"Read operation timed out", nil);
	NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
						  errMsg, NSLocalizedDescriptionKey, nil];

	return [NSError errorWithDomain: AsyncSocketErrorDomain
							   code: AsyncSocketReadTimeoutError
						   userInfo: info];
}

- (NSError *) getWriteTimeoutError
{
	NSString *errMsg = NSLocalizedStringWithDefaultValue
		(@"AsyncSocketWriteTimeoutError", @"AsyncSocket", [NSBundle mainBundle],
		 @"Write operation timed out", nil);
	NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
						  errMsg, NSLocalizedDescriptionKey, nil];

	return [NSError errorWithDomain: AsyncSocketErrorDomain
							   code: AsyncSocketWriteTimeoutError
						   userInfo: info];
}

- (NSError *) errorFromCFStreamError:(CFStreamError)err
{
	if (err.domain == 0 && err.error == 0) return nil;

	// Can't use switch; these constants aren't int literals.
	NSString *domain = @"CFStreamError (unlisted domain)";
	NSString *message = nil;
	if      (err.domain == kCFStreamErrorDomainPOSIX)
		domain = NSPOSIXErrorDomain;
	else if (err.domain == kCFStreamErrorDomainMacOSStatus)
		domain = NSOSStatusErrorDomain;
	else if (err.domain == kCFStreamErrorDomainMach)
		domain = NSMachErrorDomain;
	else if (err.domain == kCFStreamErrorDomainNetDB)
	{
		domain = @"kCFStreamErrorDomainNetDB";
		message = [NSString stringWithCString: gai_strerror(err.error)
									 encoding: NSASCIIStringEncoding];
	}
	else if (err.domain == kCFStreamErrorDomainNetServices)
		domain = @"kCFStreamErrorDomainNetServices";
	else if (err.domain == kCFStreamErrorDomainSOCKS)
		domain = @"kCFStreamErrorDomainSOCKS";
	else if (err.domain == kCFStreamErrorDomainSystemConfiguration)
		domain = @"kCFStreamErrorDomainSystemConfiguration";
	else if (err.domain == kCFStreamErrorDomainSSL)
		domain = @"kCFStreamErrorDomainSSL";

	NSDictionary *info = nil;
	if (message != nil)
	{
		info = [NSDictionary dictionaryWithObjectsAndKeys:
				message, NSLocalizedDescriptionKey, nil];
	}
	return [NSError errorWithDomain:domain code:err.error userInfo:info];
}

#pragma mark -
#pragma mark Diagnostics

- (BOOL) isConnected
{
	return [self isSocketConnected] && [self areStreamsConnected];
}

- (NSString *) connectedHost
{
	return [self connectedHost:theSocket];
}

- (UInt16) connectedPort
{
	return [self connectedPort:theSocket];
}

- (NSString *) localHost
{
	return [self localHost:theSocket];
}

- (UInt16) localPort
{
	return [self localPort:theSocket];
}

- (NSString *) connectedHost: (CFSocketRef)socket
{
	if (socket == NULL) return nil;
	CFDataRef peeraddr;
	NSString *peerstr = nil;

	if (socket && (peeraddr = CFSocketCopyPeerAddress (socket)))
	{
		peerstr = [self addressHost:peeraddr];
		CFRelease (peeraddr);
	}

	return peerstr;
}

- (UInt16) connectedPort: (CFSocketRef)socket
{
	if (socket == NULL) return 0;
	CFDataRef peeraddr;
	UInt16 peerport = 0;

	if (socket && (peeraddr = CFSocketCopyPeerAddress (socket)))
	{
		peerport = [self addressPort:peeraddr];
		CFRelease (peeraddr);
	}

	return peerport;
}

- (NSString *) localHost: (CFSocketRef)socket
{
	if (socket == NULL) return nil;
	CFDataRef selfaddr;
	NSString *selfstr = nil;

	if (socket && (selfaddr = CFSocketCopyAddress (socket)))
	{
		selfstr = [self addressHost:selfaddr];
		CFRelease (selfaddr);
	}

	return selfstr;
}

- (UInt16) localPort: (CFSocketRef) socket
{
	if (socket == NULL) return 0;
	CFDataRef selfaddr;
	UInt16 selfport = 0;

	if (socket && (selfaddr = CFSocketCopyAddress (socket)))
	{
		selfport = [self addressPort:selfaddr];
		CFRelease (selfaddr);
	}

	return selfport;
}

- (BOOL) isSocketConnected
{
	if (theSocket == NULL && theSocket6 == NULL) return NO;
	return CFSocketIsValid (theSocket) || CFSocketIsValid (theSocket6);
}

- (BOOL) areStreamsConnected
{
	CFStreamStatus s;

	if (theReadStream != NULL)
	{
		s = CFReadStreamGetStatus (theReadStream);
		if ( !(s == kCFStreamStatusOpen || s == kCFStreamStatusReading || s == kCFStreamStatusError) )
			return NO;
	}
	else return NO;

	if (theWriteStream != NULL)
	{
		s = CFWriteStreamGetStatus (theWriteStream);
		if ( !(s == kCFStreamStatusOpen || s == kCFStreamStatusWriting || s == kCFStreamStatusError) )
			return NO;
	}
	else return NO;

	return YES;
}

- (NSString *) addressHost: (CFDataRef)cfaddr
{
	if (cfaddr == NULL) return nil;
	char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
	struct sockaddr *pSockAddr = (struct sockaddr *) CFDataGetBytePtr (cfaddr);
	struct sockaddr_in  *pSockAddrV4 = (struct sockaddr_in *) pSockAddr;
	struct sockaddr_in6 *pSockAddrV6 = (struct sockaddr_in6 *)pSockAddr;

	const void *pAddr = (pSockAddr->sa_family == AF_INET) ?
							(void *)(&(pSockAddrV4->sin_addr)) :
							(void *)(&(pSockAddrV6->sin6_addr));

	const char *pStr = inet_ntop (pSockAddr->sa_family, pAddr, addrBuf, sizeof(addrBuf));
	if (pStr == NULL) [NSException raise: NSInternalInconsistencyException
								  format: @"Cannot convert address to string."];

	return [NSString stringWithCString:pStr encoding:NSASCIIStringEncoding];
}

- (UInt16) addressPort: (CFDataRef)cfaddr
{
	struct sockaddr_in *pAddr = (struct sockaddr_in *) CFDataGetBytePtr (cfaddr);
	return ntohs (pAddr->sin_port);
}

- (NSString *) description
{
	static const char *statstr[] = { "not open", "opening", "open", "reading", "writing", "at end", "closed", "has error" };
	CFStreamStatus rs = (theReadStream != NULL) ? CFReadStreamGetStatus (theReadStream) : 0;
	CFStreamStatus ws = (theWriteStream != NULL) ? CFWriteStreamGetStatus (theWriteStream) : 0;
	NSString *peerstr, *selfstr;
	CFDataRef peeraddr, selfaddr = NULL, selfaddr6 = NULL;

	if (theSocket && (peeraddr = CFSocketCopyPeerAddress (theSocket)))
	{
		peerstr = [NSString stringWithFormat: @"%@ %u", [self addressHost:peeraddr], [self addressPort:peeraddr]];
		CFRelease (peeraddr);
		peeraddr = NULL;
	}
	else peerstr = @"nowhere";

	if (theSocket)  selfaddr  = CFSocketCopyAddress (theSocket);
	if (theSocket6) selfaddr6 = CFSocketCopyAddress (theSocket6);
	if (theSocket || theSocket6)
	{
		if (theSocket6)
		{
			selfstr = [NSString stringWithFormat: @"%@/%@ %u", [self addressHost:selfaddr], [self addressHost:selfaddr6], [self addressPort:selfaddr]];
		}
		else
		{
			selfstr = [NSString stringWithFormat: @"%@ %u", [self addressHost:selfaddr], [self addressPort:selfaddr]];
		}

		if (selfaddr)  CFRelease (selfaddr);
		if (selfaddr6) CFRelease (selfaddr6);
		selfaddr = NULL;
		selfaddr6 = NULL;
	}
	else selfstr = @"nowhere";

	NSMutableString *ms = [[NSMutableString alloc] init];
	[ms appendString: [NSString stringWithFormat:@"<AsyncSocket %p #%u: Socket %p", self, [self hash], theSocket]];
	[ms appendString: [NSString stringWithFormat:@" local %@ remote %@ ", selfstr, peerstr ]];
	[ms appendString: [NSString stringWithFormat:@"has queued %d reads %d writes, ", [theReadQueue count], [theWriteQueue count] ]];

	if (theCurrentRead == nil)
		[ms appendString: @"no current read, "];
	else
	{
		int percentDone;
		if ([theCurrentRead->buffer length] != 0)
			percentDone = (float)theCurrentRead->bytesDone /
						  (float)[theCurrentRead->buffer length] * 100.0;
		else
			percentDone = 100;

		[ms appendString: [NSString stringWithFormat:@"currently read %u bytes (%d%% done), ",
			[theCurrentRead->buffer length],
			theCurrentRead->bytesDone ? percentDone : 0]];
	}

	if (theCurrentWrite == nil)
		[ms appendString: @"no current write, "];
	else
	{
		int percentDone;
		if ([theCurrentWrite->buffer length] != 0)
			percentDone = (float)theCurrentWrite->bytesDone /
						  (float)[theCurrentWrite->buffer length] * 100.0;
		else
			percentDone = 100;

		[ms appendString: [NSString stringWithFormat:@"currently written %u (%d%%), ",
			[theCurrentWrite->buffer length],
			theCurrentWrite->bytesDone ? percentDone : 0]];
	}

	[ms appendString: [NSString stringWithFormat:@"read stream %p %s, write stream %p %s", theReadStream, statstr [rs], theWriteStream, statstr [ws] ]];
	if (theFlags & kDisconnectSoon) [ms appendString: @", will disconnect soon"];
	if (![self isConnected]) [ms appendString: @", not connected"];

	 [ms appendString: @">"];

	return [ms autorelease];
}

#pragma mark -
#pragma mark Polling

- (void) doPoll:(NSTimer *)timer
{
	[self doBytesAvailable];
	[self doSendBytes];
}

#pragma mark -
#pragma mark Reading

- (void) readDataToLength:(CFIndex)length withTimeout:(NSTimeInterval)timeout tag:(long)tag;
{
	if (length == 0) return;
	if (theFlags & kForbidReadsWrites) return;

	NSMutableData *buffer = [[NSMutableData alloc] initWithLength:length];
	AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer timeout:timeout tag:tag readAllAvailable:NO terminator:nil bufferOffset:0];

	[theReadQueue addObject:packet];
	[self maybeDequeueRead];

	[packet release];
	[buffer release];
}

- (void) readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
{
	if (data == nil || [data length] == 0) return;
	if (theFlags & kForbidReadsWrites) return;

	NSMutableData *buffer = [[NSMutableData alloc] initWithLength:0];
	AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer timeout:timeout tag:tag readAllAvailable:NO terminator:data bufferOffset:0];

	[theReadQueue addObject:packet];
	[self maybeDequeueRead];

	[packet release];
	[buffer release];
}

- (void) readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
	if (theFlags & kForbidReadsWrites) return;

	// partialReadBuffer is used when recovering data from a broken connection.
	NSMutableData *buffer;
	if (partialReadBuffer)  buffer = [partialReadBuffer mutableCopy];
	else					buffer = [[NSMutableData alloc] initWithLength:0];

	AsyncReadPacket *packet = [[AsyncReadPacket alloc] initWithData:buffer timeout:timeout tag:tag readAllAvailable:YES terminator:nil bufferOffset:[buffer length]];

	[theReadQueue addObject:packet];
	[self maybeDequeueRead];

	[packet release];
	[buffer release];
}

// Puts a maybeDequeueRead on the run loop. An assumption here is that selectors will be performed consecutively within their priority.
- (void) scheduleDequeueRead
{
	[self performSelector:@selector(maybeDequeueRead) withObject:nil afterDelay:0];
}

// Start a new read.
- (void) maybeDequeueRead
{
	if (theCurrentRead == nil && [theReadQueue count] != 0 && theReadStream != NULL)
	{
		// Get new current read AsyncReadPacket.
		AsyncReadPacket *newPacket = [theReadQueue objectAtIndex:0];
		theCurrentRead = [newPacket retain];
		[theReadQueue removeObjectAtIndex:0];

		// Start time-out timer.
		if (theCurrentRead->timeout >= 0.0)
		{
			theReadTimer = [NSTimer scheduledTimerWithTimeInterval:theCurrentRead->timeout target:self selector:@selector(doReadTimeout:) userInfo:nil repeats:NO];
		}

		// Immediately read, if possible.
		[self doBytesAvailable];
	}
}

// Reads several bytes into the buffer.
- (void) doBytesAvailable
{
	if (theCurrentRead != nil && theReadStream != NULL)
	{
		BOOL error = NO, done = NO;
		while (!done && !error && CFReadStreamHasBytesAvailable (theReadStream))
		{
			// If reading all available data, make sure there's room in the packet buffer.
			if (theCurrentRead->readAllAvailableData == YES)
				[theCurrentRead->buffer increaseLengthBy:READALL_CHUNKSIZE];

			// If reading until data, just do one byte.
			if (theCurrentRead->term != nil)
				[theCurrentRead->buffer increaseLengthBy:1];

			// Number of bytes to read is space left in packet buffer.
			CFIndex bytesToRead = [theCurrentRead->buffer length] - theCurrentRead->bytesDone;

			// Read stuff into start of unfilled packet buffer space.
			UInt8 *packetbuf = (UInt8 *)( [theCurrentRead->buffer mutableBytes] + theCurrentRead->bytesDone );
			CFIndex bytesRead = CFReadStreamRead (theReadStream, packetbuf, bytesToRead);

			// Check results.
			if (bytesRead < 0)
			{
				bytesRead = 0;
				error = YES;
			}

			// Is packet done?
			theCurrentRead->bytesDone += bytesRead;
			if (theCurrentRead->readAllAvailableData != YES)
			{
				if (theCurrentRead->term != nil)
				{
					// Search for the terminating sequence in the buffer.
					int termlen = [theCurrentRead->term length];
					if (theCurrentRead->bytesDone >= termlen)
					{
						const void *buf = [theCurrentRead->buffer bytes] + (theCurrentRead->bytesDone - termlen);
						const void *seq = [theCurrentRead->term bytes];
						done = (memcmp (buf, seq, termlen) == 0);
					}
					else done = NO;
				}
				else
				{
					// Done when (sized) buffer is full.
					done = ([theCurrentRead->buffer length] == theCurrentRead->bytesDone);
				}
			}
			// else readAllAvailable doesn't end until all readable is read.
		}

		if (theCurrentRead->readAllAvailableData && theCurrentRead->bytesDone > 0)
			done = YES;	// Ran out of bytes, so the "read-all-data" type packet is done.

		if (done)
		{
			[self completeCurrentRead];
			if (!error) [self scheduleDequeueRead];
		}

		if (error)
		{
			CFStreamError err = CFReadStreamGetError (theReadStream);
			[self closeWithError: [self errorFromCFStreamError:err]];
			return;
		}
	}
}

// Ends current read and calls delegate.
- (void) completeCurrentRead
{
	NSAssert (theCurrentRead, @"Trying to complete current read when there is no current read.");
	[theCurrentRead->buffer setLength:theCurrentRead->bytesDone];
	if ([theDelegate respondsToSelector:@selector(onSocket:didReadData:withTag:)])
	{
		[theDelegate onSocket:self didReadData:theCurrentRead->buffer withTag:theCurrentRead->tag];
	}
	if (theCurrentRead != nil) [self endCurrentRead]; // Caller may have disconnected.
}

// Ends current read.
- (void) endCurrentRead
{
	NSAssert (theCurrentRead, @"Trying to end current read when there is no current read.");
	[theReadTimer invalidate];
	theReadTimer = nil;
	[theCurrentRead release];
	theCurrentRead = nil;
}

- (void) doReadTimeout:(NSTimer *)timer
{
	if (timer != theReadTimer) return; // Old timer. Ignore it.
	if (theCurrentRead != nil)
	{
		// Send what we got.
		[self endCurrentRead];
	}
	[self closeWithError: [self getReadTimeoutError]];
}

#pragma mark -
#pragma mark Writing

- (void) writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
{
	if (data == nil || [data length] == 0) return;
	if (theFlags & kForbidReadsWrites) return;

	AsyncWritePacket *packet = [[AsyncWritePacket alloc] initWithData:data timeout:timeout tag:tag];

	[theWriteQueue addObject:packet];
	[self maybeDequeueWrite];

	[packet release];
}

- (void) scheduleDequeueWrite
{
	[self performSelector:@selector(maybeDequeueWrite) withObject:nil afterDelay:0];
}

// Start a new write.
- (void) maybeDequeueWrite
{
	if (theCurrentWrite == nil && [theWriteQueue count] != 0 && theWriteStream != NULL)
	{
		// Get new current write AsyncWritePacket.
		AsyncWritePacket *newPacket = [theWriteQueue objectAtIndex:0];
		theCurrentWrite = [newPacket retain];
		[theWriteQueue removeObjectAtIndex:0];

		// Start time-out timer.
		if (theCurrentWrite->timeout >= 0.0)
		{
			theWriteTimer = [NSTimer scheduledTimerWithTimeInterval:theCurrentWrite->timeout target:self selector:@selector(doWriteTimeout:) userInfo:nil repeats:NO];
		}

		// Immediately write, if possible.
		[self doSendBytes];
	}
}

- (void) doSendBytes
{
	if (theCurrentWrite != nil && theWriteStream != NULL)
	{
		BOOL done = NO, error = NO;
		while (!done && !error && CFWriteStreamCanAcceptBytes (theWriteStream))
		{
			// Figure out what to write.
			CFIndex bytesRemaining = [theCurrentWrite->buffer length] - theCurrentWrite->bytesDone;
			CFIndex bytesToWrite = (bytesRemaining < WRITE_CHUNKSIZE) ? bytesRemaining : WRITE_CHUNKSIZE;
			UInt8 *writestart = (UInt8 *)([theCurrentWrite->buffer bytes] + theCurrentWrite->bytesDone);

			// Write.
			CFIndex bytesWritten = CFWriteStreamWrite (theWriteStream, writestart, bytesToWrite);

			// Check results.
			if (bytesWritten < 0)
			{
				bytesWritten = 0;
				error = YES;
			}

			// Is packet done?
			theCurrentWrite->bytesDone += bytesWritten;
			done = ([theCurrentWrite->buffer length] == theCurrentWrite->bytesDone);
		}

		if (done)
		{
			[self completeCurrentWrite];
			if (!error) [self scheduleDequeueWrite];
		}

		if (error)
		{
			CFStreamError err = CFWriteStreamGetError (theWriteStream);
			[self closeWithError: [self errorFromCFStreamError:err]];
			return;
		}
	}
}

// Ends current write and calls delegate.
- (void) completeCurrentWrite
{
	NSAssert (theCurrentWrite, @"Trying to complete current write when there is no current write.");
	if ([theDelegate respondsToSelector:@selector(onSocket:didWriteDataWithTag:)])
	{
		int tag = theCurrentWrite->tag;
		[theDelegate onSocket:self didWriteDataWithTag:tag];
	}
	if (theCurrentWrite != nil) [self endCurrentWrite]; // Caller may have disconnected.
}

// Ends current write.
- (void) endCurrentWrite
{
	NSAssert (theCurrentWrite, @"Trying to complete current write when there is no current write.");
	[theWriteTimer invalidate];
	theWriteTimer = nil;
	[theCurrentWrite release];
	theCurrentWrite = nil;
	[self maybeScheduleDisconnect];
}

// Checks to see if all writes have been completed for disconnectAfterWriting.
- (void) maybeScheduleDisconnect
{
	if (theFlags & kDisconnectSoon)
		if ([theWriteQueue count] == 0 && theCurrentWrite == nil)
			[self performSelector:@selector(disconnect) withObject:nil afterDelay:0];
}

- (void) doWriteTimeout:(NSTimer *)timer
{
	if (timer != theWriteTimer) return; // Old timer. Ignore it.
	if (theCurrentWrite != nil)
	{
		// Send what we got.
		[self completeCurrentWrite];
	}
	[self closeWithError: [self getWriteTimeoutError]];
}

#pragma mark -
#pragma mark CF Callbacks

- (void) doCFSocketCallback:(CFSocketCallBackType)type forSocket:(CFSocketRef)sock withAddress:(NSData *)address withData:(const void *)pData
{
	NSParameterAssert ((sock == theSocket) || (sock == theSocket6));
	switch (type)
	{
		case kCFSocketAcceptCallBack:
			[self doAcceptWithSocket: *((CFSocketNativeHandle *)pData)];
			break;
		default:
			NSLog (@"AsyncSocket %p received unexpected CFSocketCallBackType %d.", self, type);
			break;
	}
}

- (void) doCFReadStreamCallback:(CFStreamEventType)type forStream:(CFReadStreamRef)stream
{
	CFStreamError err;
	switch (type)
	{
		case kCFStreamEventOpenCompleted:
			[self doStreamOpen];
			break;
		case kCFStreamEventHasBytesAvailable:
			[self doBytesAvailable];
			break;
		case kCFStreamEventErrorOccurred:
		case kCFStreamEventEndEncountered:
			err = CFReadStreamGetError (theReadStream);
			[self closeWithError: [self errorFromCFStreamError:err]];
			break;
		default:
			NSLog (@"AsyncSocket %p received unexpected CFReadStream callback, CFStreamEventType %d.", self, type);
	}
}

- (void) doCFWriteStreamCallback:(CFStreamEventType)type forStream:(CFWriteStreamRef)stream
{
	CFStreamError err;
	switch (type)
	{
		case kCFStreamEventOpenCompleted:
			[self doStreamOpen];
			break;
		case kCFStreamEventCanAcceptBytes:
			[self doSendBytes];
			break;
		case kCFStreamEventErrorOccurred:
		case kCFStreamEventEndEncountered:
			err = CFWriteStreamGetError (theWriteStream);
			[self closeWithError: [self errorFromCFStreamError:err]];
			break;
		default:
			NSLog (@"AsyncSocket %p received unexpected CFWriteStream callback, CFStreamEventType %d.", self, type);
	}
}

// This is the callback we set up for CFSocket.
static void MyCFSocketCallback (CFSocketRef sref, CFSocketCallBackType type, CFDataRef address, const void *pData, void *pInfo)
{
	AsyncSocket *socket = (AsyncSocket *)pInfo;
	[socket doCFSocketCallback:type forSocket:sref withAddress:(NSData *)address withData:pData];
}

// This is the callback we set up for CFReadStream.
static void MyCFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
{
	AsyncSocket *socket = (AsyncSocket *)pInfo;
	[socket doCFReadStreamCallback:type forStream:stream];
}

// This is the callback we set up for CFWriteStream.
static void MyCFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType type, void *pInfo)
{
	AsyncSocket *socket = (AsyncSocket *)pInfo;
	[socket doCFWriteStreamCallback:type forStream:stream];
}

@end


text:
namespace HmLib.Abstractions
{
    public interface IObjectBuilder
    {
        void BeginArray(int count);
        void BeginItem();
        void BeginStruct(int count);
        void EndArray();
        void EndItem();
        void EndStruct();
        void WriteBase64String(string base64String);
        void WriteBooleanValue(bool value);
        void WriteDoubleValue(double value);
        void WriteInt32Value(int value);
        void WritePropertyName(string name);
        void WriteStringValue(string value);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

const Glob = require('glob').Glob;
const glob2base = require('glob2base');

const DEFAULT_IGNORES = [
    '**/.git/**',
    '**/.cdn-config.yml',
    '**/.gitignore',
    '**/.circleci/**',
];

exports.match = function matchGlob(pattern, opts) {
    if (pattern.startsWith('./')) {
        pattern = pattern.substring(2);
    }

    const ignore = [].concat(DEFAULT_IGNORES);

    if (opts.ignore) {
        if (Array.isArray(opts.ignore)) {
            ignore.push(...opts.ignore);
        } else {
            ignore.push(opts.ignore);
        }
    }

    opts.ignore = ignore;

    let g = new Glob(pattern, opts);
    let base = glob2base(g);
    let promise = new Promise((resolve, reject) => {
        g.on('error', reject);
        g.on('end', resolve);
    });

    promise.base = base;
    return promise;
};

(function () {
    const path = require('path');
    const srcDir = path.join(__dirname, '../../.tmp/build-test-lib/master');
    exports.match('./**', {
        cwd: srcDir, root: srcDir, nodir: true, dot: true
    }).then(console.log);
})();


text:
dlearn.stats package
====================

Module contents
---------------

.. automodule:: dlearn.stats
    :members:
    :undoc-members:
    :show-inheritance:


text:
import subprocess

for i in range(0,1000):
	print i
	subprocess.check_output( ['python graph.py '+str(i/200+1)+' > test/fcfs/fcfs_'+str(i)] ,shell = True )


text:
<?php

namespace LeeMason\Metable;

use Illuminate\Support\Collection;

trait Metable
{
    /**
     * Handles formatting the model value when in use.
     *
     * @param $value
     * @return Collection|mixed
     */
    public function getValueAttribute($value)
    {
        return $this->getValue($value);
    }

    /**
     * Handles setting the 'type' attribute based on the incoming value type.
     *
     * @param $value
     */
    public function setValueAttribute($value)
    {
        $this->attributes['value'] = $this->setValue($value);
    }

    /**
     * Internal function utilized by setValueAttribute to find the value type and set the attribute accordingly.
     *
     * @param $value
     * @return bool|float|int|string
     */
    private function setValue($value)
    {
        switch (gettype($value)) {
            case 'int':
            case 'integer':
                $this->attributes['type'] = 'int';

                return (int) $value;
            case 'real':
            case 'float':
            case 'double':
                $this->attributes['type'] = 'float';

                return (float) $value;
            case 'bool':
            case 'boolean':
                $this->attributes['type'] = 'bool';

                return (bool) $value;
            case 'object':
                if ($value instanceof Collection) {
                    $this->attributes['type'] = 'collection';

                    return json_encode($value);
                }
                $this->attributes['type'] = 'object';

                return json_encode($value);
            case 'array':
                $this->attributes['type'] = 'array';

                return json_encode($value);
            default:
                $this->attributes['type'] = 'string';

                return $value;
        }
    }

    /**
     * Internal function utilized by getValueAttribute to get raw results from the db and format as they were set during insertion.
     *
     * @param $value
     * @return bool|float|Collection|int|mixed
     */
    private function getValue($value)
    {
        switch ($this->attributes['type']) {
            case 'int':
            case 'integer':
                return (int) $value;
            case 'real':
            case 'float':
            case 'double':
                return (float) $value;
            case 'bool':
            case 'boolean':
                return (bool) $value;
            case 'collection':
                return new Collection(json_decode($value, true));
            case 'object':
                return json_decode($value);
            case 'array':
                return json_decode($value, true);
            default:
                return $value;
        }
    }
}


text:
var http = require("http");
var server = http.createServer(function (req,res) {
    res.end("jsonp({name:'bob'})");
}).listen(8000);


text:
namespace blink {

PerspectiveTransformComponent* PerspectiveTransformComponent::create(const LengthValue* length, ExceptionState& exceptionState)
{
    if (length->containsPercent()) {
        exceptionState.throwTypeError("PerspectiveTransformComponent does not support LengthValues with percent units");
        return nullptr;
    }
    return new PerspectiveTransformComponent(length);
}

CSSFunctionValue* PerspectiveTransformComponent::toCSSValue() const
{
    CSSFunctionValue* result = CSSFunctionValue::create(CSSValuePerspective);
    result->append(m_length->toCSSValue());
    return result;
}

} // namespace blink


text:
#ifndef _TL_MATRIX_
#define _TL_MATRIX_

#include <iostream>
#include <array>
#include <vector>
#include "fftw3.h"
#include "exceptions.h"
#include "padding.h"

namespace toefl{

/*! @brief enum for telling to not allocate memory
  @ingroup containers
  */
enum Void{ TL_VOID = false //!< Use for not allocating memory in the matrix
            };

// forward declare friend functions of Matrix class
template <class T, enum Padding P>
class Matrix;

template<class T1, enum Padding P1, class T2, enum Padding P2>
void swap_fields( Matrix<T1, P1>& lhs, Matrix<T2, P2>& rhs);
template <class T, enum Padding P>
void permute_fields( Matrix<T, P>& first, Matrix<T, P>& second, Matrix<T, P>& third);
/*! @brief print a Matrix to the given outstream
 *
 * Matrix is printed linewise with a newline after each line.
 * @param os the outstream
 * @param mat the matrix to be printed
 * @return the outstream
 */
template <class T, enum Padding P>
std::ostream& operator<< ( std::ostream& os, const Matrix<T, P>& mat);
template <class T, enum Padding P>
std::istream& operator>> ( std::istream& is, Matrix<T, P>& mat);

/*! @brief Matrix class of constant size that provides fftw compatible dynamically allocated 2D fields
 *
 * @ingroup containers
 * The primary goal of the Matrix class is to provide a way to have
 * a dynamically continuously allocated 2d field for either real or complex values.
 * Once allocated the size (i.e. the number of rows and columns) of a Matrix cannot be changed any more.
 * The following example code should be pretty obvious:
 * \code
  Matrix<double> m(3, 3);
  m.zero();
  m( 4,2) = 3;
  std::cout << m << std::endl;
  \endcode
 *
 * Once you want to fourier transform a real matrix inplace you will be confronted
 * with two issues: The first thing is that the result is of complex type and
 * you probably want to calculate with complex numbers.
 * Therefore there should be a way for a matrix to somehow change its type
 * from real to complex. This is solved here by the globally defined swap_fields routine that exchanges the pointers to memory of two Matrices, even if the types are different.
 * So if you swap pointers between a real and a complex matrix you effectively made the complex matrix real and the real matrix complex.
 * If the additional allocated memory is of concern to you, there is the
 * allocate flag in the constructor that you can set to TL_VOID. Then no memory is allocated, the only way for such a matrix to get memory is by swap_ping_ it in from
 * another matrix by the swap_fields routine. See the example code:
 * \code
 Matrix<double> m(5, 10);
 Matrix<complex<double>> cm( 5,5, TL_VOID); //complex numbers have twice the size
 m.zero()
 m(0,1) = 5;
 swap_fields( m, cm); //now cm has an imaginary value at cm(0,0);
 \endcode
 * The second issue is that for an inplace transform
 * the input array needs to be padded regardless of whether you want to perform many
 * 1d (linewise) transformations or one 2d transformation.  Therefore there
 * needs to be a way to allocate a padded 2d field. This padded field then
 * behaves like an unpadded field in all situations except that it is fourier
 * transformable. See the fft.h file for further information on that topic.
 *
 * @tparam T This class is designed for primitive or trivial datatypes
 * ( the ones  that are "memcpy - able" ). This is important because
 * we want to swap pointers between different types if the total amount
 * of allocated memory is the same. T may in no case have dynamic allocated
 * memory itself.
 * @tparam P One of the values of the Padding enum,  TL_NONE(default)
 * \note The fftw_complex type does not work as a template paramter. (Mainly due to the comparison and istream and outstream methods)
 * However std::complex<double> should be byte compatible so you can use reinterpret_cast<fftw_complex*>() on the pointer you get with getPtr() to use fftw routines!
 * \note No errors are thrown if the macro TL_DEBUG is not defined
 */
template <class T, enum Padding P = TL_NONE>
class Matrix
{
  public:
    /*! @brief Construct an empty matrix*/
    //Matrix(): n(0), m(0), ptr( NULL){ }
    /*! @brief Allocate continous memory on the heap
     *
     * @param rows logical number of rows (cannot be changed as long as memory is allocated for that object)
     * @param cols logical number of columns (cannot be changed as long as memory is allocated for that object)
     * @param allocate determines whether memory should actually be allocated.
     *  Use TL_VOID if matrix should be empty! Then only the swap_fields function can make
     *  the matrix usable.
     *  \note The physical size of the actually allocated memory depends on the padding type.
     *  (In the case that memory is allocated)
     */
    Matrix( const size_t rows, const size_t cols, const bool allocate = true);

    /*! @brief Allocate and assign memory on the heap
     *
     * @param rows logical number of rows (cannot be changed as long as memory is allocated for that object)
     * @param cols logical number of columns (cannot be changed as long as memory is allocated for that object)
     * @param value Use operator= of type T to assign values
     */
    Matrix( const size_t rows, const size_t cols, const T& value);
    /*! @brief Free all allocated memory
     */
    ~Matrix();
    /*! @brief deep copy of an existing Matrix
     *
     * Copy of 1e6 double takes less than 0.01s
     * @param src the source matrix.
     * \note
     * If src is void then so will be this.
     */
    Matrix( const Matrix& src);

    /*! @brief Experimental move constructor in the new standard
     *
     * Does the same thing as the normal copy constructor.
     * @param temporary_src The temporary source matrix
     */
    Matrix( Matrix&& temporary_src);
    /*! @brief Deep assignment
     *
     * Copy every (including padded) value of the source Matrix
     * to the existing (non void) Matrix with equal numbers of rows and columns.
     * Copy of 1e6 double takes less than 0.01s
     * @param src the right hand side
     * @return this
     * @throws A Message if src is void or doesn't have the same size as this.
     */
    Matrix& operator=( const Matrix& src);

    /*! @brief Deep move assignment
     *
     * Effectively the same as deep assignment but modifies its source
     * @param temporary_src The temporary source matrix
     * @return this
     * @throws A Message if src is void or doesn't have the same size as this
     */
    Matrix& operator=( Matrix&& temporary_src);

    /*! @brief Allocate memory for void matrices
     *
     * This function uses the current values of n and m to
     * allocate the right amount of memory!
     * @throws A Message when called on non-void Matrices.
     */
    void allocate(){ allocate_();}

    /*! @brief number of rows
     *
     * Return the  number of rows the object manages (the one you specified in the constructor)
     * even if
     * no memory (or more in the padded case) is allocated.
     * This number doesn't change as long as memory is allocated for that object.
     * @return number of columns
     */
    const size_t rows() const {return n;}
    /*! @brief number of columns
     *
     * Return the number of columns the object manages (the one you specified in the constructor), even if
     * no memory is allocated.
     * This number doesn't change as long as memory is allocated for that object.
     * @return number of columns
     */
    const size_t cols() const {return m;}
    /*! @brief get the address of the first element
     *
     * Replaces the use of &m(0,0) which is kind of clumsy!
     * @return pointer to allocated memory
     * \attention DO NOT DELETE THIS POINTER!!
     *  This class manages the memory it allocates by itself.
     */
    T* getPtr() { return ptr;}

    /*! @brief Get the address of the first element for const reference
     *
     * Replaces the use of &m(0,0) which is kind of clumsy!
     * @return read only pointer to allocated memory
     * \attention DO NOT DELETE THIS POINTER!!
     *  This class manages the memory it allocates by itself.
     */
    T const * getPtr()const {return ptr;}

    /*! @brief Copy the data linearly and without padding to a std vector
     *
     * @return newly instantiated vector holding a copy of the matrix data
     */
    std::vector<T> copy() const
    {
        std::vector<T> vec( n*m);
        for( unsigned i=0; i<n; i++)
            for( unsigned j=0; j<m; j++)
                vec[i*m+j] = ptr[i*TotalNumberOf<P>::columns(m) + j];
        return vec;
    }

    /*! @brief uses operator= to set memory to 0
     *
     * takes less than 0.01s for 1e6 elements
     */
    inline void zero();
    /*! @brief checks whether matrix is empty i.e. no memory is allocated
     *
     * @return true if memory isn't allocated
     */
    bool isVoid() const { return (ptr == NULL) ? true : false;}

    /*! @brief two Matrices are considered equal if elements are equal
     *
     * @param rhs Matrix to be compared to this
     * @return true if rhs does not equal this
     */
    const bool operator!=( const Matrix& rhs) const;
    /*! @brief two Matrices are considered equal if elements are equal
     *
     * @param rhs Matrix to be compared to this
     * @return true if rhs equals this
     */
    const bool operator==( const Matrix& rhs) const {return !((*this != rhs));}
    //hier sollte kein overhead für vektoren liegen weil der Compiler den
    //Zugriff m(0,i) auf ptr[i] optimieren sollte

    /*! @brief access operator
     *
     * Performs a range check if TL_DEBUG is defined
     * @param i row index
     * @param j column index
     * @return reference to value at that location
     */
    inline T& operator()( const size_t i, const size_t j);

    /*! @brief const access operator
     *
     * Performs a range check if TL_DEBUG is defined
     * @param i row index
     * @param j column index
     * @return const value at that location
     */
    inline const T& operator()( const size_t i, const size_t j) const;

    // friend functions
    /*! @brief swap memories of two equally sized matrices of arbitrary type
     *
     * Performs a range check if TL_DEBUG is defined.
     * The sizes of the actually allocated memory, which depend on padding and the value type, have to be equal.
     * @param lhs changes memory with rhs
     * @param rhs changes memory with lhs
     */
    template<class T1, enum Padding P1, class T2, enum Padding P2>
    friend void swap_fields( Matrix<T1, P1>& lhs, Matrix<T2, P2>& rhs);
    /*! @brief permute memory of matrices with the same type
     *
     * @param first contains third on output
     * @param second contains first on output
     * @param third contains second on output
     */
    friend void permute_fields<T, P>( Matrix& first, Matrix& second, Matrix& third);
    /*! @brief print a Matrix to the given outstream
     *
     * Matrix is printed linewise with a newline after each line.
     * @param os the outstream
     * @param mat the matrix to be printed
     * @return the outstream
     */
    friend std::ostream& operator<< <T,P> ( std::ostream& os, const Matrix& mat);
    /*! @brief read values into a Matrix from given istream
     *
     * The values are filled linewise into the matrix. Values are seperated by
     * whitespace charakters. (i.e. newline, blank, etc)
     * @param is the istream
     * @param mat the Matrix into which the values are written
     * @return the istream
     */
    friend std::istream& operator>> <T, P> ( std::istream& is, Matrix& mat);
  protected:
      //maybe an id (static int id) wouldn't be bad to identify in errors
  private:
    void allocate_(); //normal allocate function of Matrix class (called by constructors)
    size_t n; //!< # of columns
    size_t m; //!< # of rows
    T *ptr; //!< pointer to allocated memory
};

/////////////////////////////////////DEFINITIONS///////////////////////////////////////////////////////////////////////////////
template<class T1, enum Padding P1, class T2, enum Padding P2>
void swap_fields( Matrix<T1, P1>& lhs, Matrix<T2, P2>& rhs)
{
#ifdef TL_DEBUG
    if( TotalNumberOf<P1>::elements(lhs.n, lhs.m)*sizeof(T1) != TotalNumberOf<P2>::elements(rhs.n, rhs.m)*sizeof(T2))
        throw Message( "Swap not possible. Sizes not equal\n", _ping_);
#endif
    //test for self swap not necessary (not an error)
    T1 * ptr = lhs.ptr;
    lhs.ptr = reinterpret_cast<T1*>(rhs.ptr);
    rhs.ptr = reinterpret_cast<T2*>(ptr);
}

template <class T, enum Padding P>
Matrix<T, P>::Matrix( const size_t n, const size_t m, const bool allocate): n(n), m(m), ptr(NULL)
{
#ifdef TL_DEBUG
    if( n==0|| m==0)
        throw Message("Use TL_VOID to not allocate any memory!\n", _ping_);
#endif
    if( allocate)
        allocate_();
}

template< class T, enum Padding P>
Matrix<T,P>::Matrix( const size_t n, const size_t m, const T& value):n(n),m(m),ptr(NULL)
{
#ifdef TL_DEBUG
    if( n==0|| m==0)
        throw Message("Use TL_VOID to not allocate any memory!\n", _ping_);
#endif
    allocate_();
    for( unsigned i=0; i<TotalNumberOf<P>::elements(n,m); i++)
        ptr[i] = value;
}

template <class T, enum Padding P>
Matrix<T, P>::~Matrix()
{
    if( ptr!= NULL/*NULL*/)
        fftw_free( ptr);
}

template <class T, enum Padding P>
Matrix<T, P>::Matrix( const Matrix& src):n(src.n), m(src.m), ptr(NULL){
    if( src.ptr != NULL)
    {
        allocate_();
        for( size_t i =0; i < TotalNumberOf<P>::elements(n, m); i++)
            ptr[i] = src.ptr[i];
    }
}
template <class T, enum Padding P>
Matrix<T, P>::Matrix(  Matrix&& src):n(src.n), m(src.m), ptr(src.ptr){
    src.ptr = NULL;
}

template <class T, enum Padding P>
Matrix<T, P>& Matrix<T, P>::operator=( const Matrix& src)
{
    if( &src != this)
    {
#ifdef TL_DEBUG
        if( n!=src.n || m!=src.m)
            throw  Message( "Assignment error! Sizes not equal!", _ping_);
        if( ptr == NULL || src.ptr == NULL)
            throw Message( "Assigning to or from a void matrix!", _ping_);
#endif
        for( size_t i =0; i < TotalNumberOf<P>::elements(n, m); i++)
            ptr[i] = src.ptr[i];
    }
    return *this;
}

template <class T, enum Padding P>
Matrix<T, P>& Matrix<T, P>::operator=( Matrix&& src)
{
    if( &src != this)
    {
#ifdef TL_DEBUG
        if( n!=src.n || m!=src.m)
            throw  Message( "Assignment error! Sizes not equal!", _ping_);
        if( ptr == NULL || src.ptr == NULL)
            throw Message( "Assigning to or from a void matrix!", _ping_);
#endif
        ptr = src.ptr;
        src.ptr = NULL;
    }
    return *this;
}

template <class T, enum Padding P>
void Matrix<T, P>::allocate_()
{
    if( ptr == NULL) //allocate only if matrix is void
    {
        ptr = (T*)fftw_malloc( TotalNumberOf<P>::elements(n, m)*sizeof(T));
        if( ptr == NULL)
            throw AllocationError(n, m, _ping_);
    }
    else
        throw Message( "Memory already exists!", _ping_);
}

template <class T, enum Padding P>
T& Matrix<T, P>::operator()( const size_t i, const size_t j)
{
#ifdef TL_DEBUG
    if( i >= n || j >= m)
        throw BadIndex( i,n, j,m, _ping_);
    if( ptr == NULL)
        throw Message( "Trying to access a void matrix!", _ping_);
#endif
    return ptr[ i*TotalNumberOf<P>::columns(m) + j];
}

template <class T, enum Padding P>
const T&  Matrix<T, P>::operator()( const size_t i, const size_t j) const
{
#ifdef TL_DEBUG
    if( i >= n || j >= m)
        throw BadIndex( i,n, j,m, _ping_);
    if( ptr == NULL)
        throw Message( "Trying to access a void matrix!", _ping_);
#endif
    return ptr[ i*TotalNumberOf<P>::columns(m) + j];
}

template <class T, enum Padding P>
void Matrix<T, P>::zero(){
#ifdef TL_DEBUG
    if( ptr == NULL)
        throw  Message( "Trying to zero a void matrix!", _ping_);
#endif
    for( size_t i =0; i < TotalNumberOf<P>::elements(n, m); i++)
        ptr[i] = (T)0;
    //memset( ptr, 0, TotalNumberOf<P>::elements(n, m)*sizeof( T));
}

template <class T, enum Padding P>
void permute_fields( Matrix<T, P>& first, Matrix<T, P>& second, Matrix<T, P>& third)
{
#ifdef TL_DEBUG
    if( first.n!=second.n || first.m!=second.m || first.n != third.n || first.m != third.m)
        throw  Message( "Permutation error! Sizes not equal!", _ping_);
#endif
    T * ptr = first.ptr;
    first.ptr = third.ptr;
    third.ptr = second.ptr;
    second.ptr = ptr;
}

template <class T, enum Padding P>
std::ostream& operator<< ( std::ostream& os, const Matrix<T, P>& mat)
{
#ifdef TL_DEBUG
    if( mat.ptr == NULL)
        throw  Message( "Trying to output a void matrix!\n", _ping_);
#endif
     int w = os.width();
     for( size_t i=0; i<mat.n; i++)
     {
         for( size_t j=0; j<mat.m; j++)
         {
             os.width(w);
             os << mat(i,j)<<" ";	//(Feldbreite gilt immmer nur bis zur nächsten Ausgabe)
         }
         os << "\n";
     }
     return os;
}

template <class T, enum Padding P>
std::istream& operator>>( std::istream& is, Matrix<T, P>& mat)
{
#ifdef TL_DEBUG
    if( mat.ptr == NULL)
        throw  Message( "Trying to write in a void matrix!\n", _ping_);
#endif
    for( size_t i=0; i<mat.n; i++)
        for( size_t j=0; j<mat.m; j++)
            is >> mat(i, j);
    return is;
}

template< class T, enum Padding P>
const bool Matrix<T,P>::operator!= ( const Matrix& rhs) const
{
#ifdef TL_DEBUG
    if( n != rhs.n || m != rhs.m)
        throw Message( "Comparison not possible! Sizes not equal!\n", _ping_);
#endif
    for( size_t i = 0; i < n; i++)
        for( size_t j = 0; j < m; j++)
            if( (*this)( i, j) != rhs( i, j) )
                return true;
    return false;
}

} //namespace toefl

#endif //_TL_MATRIX_


text:
  Parigny-les-Vaux est
       un village
       géographiquement positionné dans le département de Nièvre en Bourgogne. Elle totalisait 968 habitants en 2008.

À proximité de Parigny-les-Vaux sont situées les villes de
Saint-Aubin-les-Forges à 6 km, 439 habitants,
Varennes-Vauzelles située à 4 km, 9 573 habitants,
Tronsanges localisée à 7 km, 356 habitants,
Urzy localisée à 6 km, 1 828 habitants,
Poiseux située à 7 km, 328 habitants,
Garchizy située à 6 km, 3 650 habitants,
 entre autres. De plus, Parigny-les-Vaux est située à seulement onze km de Nevers.

Si vous envisagez de demenager à Parigny-les-Vaux, vous pourrez facilement trouver une maison à vendre.

Le nombre de logements, à Parigny-les-Vaux, était réparti en 2011 en sept appartements et 463 maisons soit
 un marché plutôt équilibré.

À Parigny-les-Vaux, la valorisation moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 120 € du m². À la location la valeur moyenne se situe à 8,24 € du m² par mois.

La commune compte quelques  équipements sportifs, elle dispose, entre autres, de un équipement de roller/skate.


text:
package org.markn.contiki.z80.linker;

import java.io.IOException;
import java.io.OutputStream;

public class RelocationInformation {
  private byte _mode;
  private int _address;
  private int _data;
  public byte getMode() {
    return _mode;
  }
  public void setMode(byte mode) {
    this._mode = mode;
  }
  public int getAddress() {
    return _address;
  }
  public void setAddress(int address) {
    _address = address;
  }
  public int getData() {
    return _data;
  }
  public void setData(int data) {
    _data = data;
  }
  public void write(OutputStream stream) throws IOException {
    stream.write(_mode);
    stream.write(_address & 0xff);
    stream.write(_address >> 8);
    stream.write(_data & 0xff);
    stream.write(_data >> 8);
  }
  public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append((_mode & 0x80) > 0 ? 'E' : 'I');
    if ((_mode & 0x60) == 0x60) {
      buf.append("MB");
    } else if ((_mode & 0x20) > 0) {
      buf.append("LB");
    } else {
      buf.append("_W");
    }
//    buf.append((_mode & 0x60) > 0 ? 'M' : 'L');
//    buf.append((_mode & 0x20) > 0 ? 'B' : 'W');
    buf.append(String.format(":%04X:%04X", _address, _data));
    return buf.toString();
  }

}


text:
SYNONYM

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

#### Published in
Annls mycol. 14(6): 446 (1917)

#### Original name
Phyllachora merrillii Ricker, 1906

### Remarks
null


text:
Installation
============

Step 1: Download the Bundle
---------------------------

Open a command console, enter your project directory and execute the
following command to download the latest stable version of this bundle:

```bash
$ composer require sw-profile-bundle "~1"
```

This command requires you to have Composer installed globally, as explained
in the [installation chapter](https://getcomposer.org/doc/00-intro.md)
of the Composer documentation.

Step 2: Enable the Bundle
-------------------------

Then, enable the bundle by adding it to the list of registered bundles
in the `app/AppKernel.php` file of your project:

```php
<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...

            new SW\ProfileBundle\SWProfileBundle(),
        );

        // ...
    }

    // ...
}
```


text:
title: Telerik.Web.UI.FileExplorer.FilePathEventArgs
description: Telerik.Web.UI.FileExplorer.FilePathEventArgs
slug: Telerik.Web.UI.FileExplorer.FilePathEventArgs
---

# Telerik.Web.UI.FileExplorer.FilePathEventArgs : Sys.EventArgs

## Inheritance Hierarchy

* Sys.EventArgs
* *[Telerik.Web.UI.FileExplorer.FilePathEventArgs]({%slug Telerik.Web.UI.FileExplorer.FilePathEventArgs%})*

## Methods

###  get_path

Getter for the path

#### Parameters

#### Returns

`String` The file system path


text:
import sys

print(sys.path)

try:
    import Recursion
except Exception as e:
    print(e)

sys.path.append('../ch19')

print(sys.path)

try:
    import Recursion
except Exception as e:
    print(e)


text:
// Provides the base implementation for all model implementations
sap.ui.define(['jquery.sap.global', 'sap/ui/core/format/NumberFormat', 'sap/ui/model/SimpleType'],
	function(jQuery, NumberFormat, SimpleType) {
	"use strict";

	/**
	 * Constructor for a Integer type.
	 *
	 * @class
	 * This class represents integer simple types.
	 *
	 * @extends sap.ui.model.SimpleType
	 *
	 * @author SAP SE
	 * @version 1.28.5
	 *
	 * @constructor
	 * @public
	 * @param {object} [oFormatOptions] formatting options. Supports the same options as {@link sap.ui.core.format.NumberFormat.getIntegerInstance NumberFormat.getIntegerInstance}
	 * @param {object} [oFormatOptions.source] additional set of format options to be used if the property in the model is not of type string and needs formatting as well.
	 * 										   In case an empty object is given, the default is disabled grouping and a dot as decimal separator.
	 * @param {object} [oConstraints] value constraints.
	 * @param {int} [oConstraints.minimum] smallest value allowed for this type
	 * @param {int} [oConstraints.maximum] largest value allowed for this type
	 * @alias sap.ui.model.type.Integer
	 */
	var Integer = SimpleType.extend("sap.ui.model.type.Integer", /** @lends sap.ui.model.type.Integer.prototype */ {

		constructor : function () {
			SimpleType.apply(this, arguments);
			this.sName = "Integer";
		}

	});

	/**
	 * @see sap.ui.model.SimpleType.prototype.formatValue
	 */
	Integer.prototype.formatValue = function(vValue, sInternalType) {
		var iValue = vValue;
		if (vValue == undefined || vValue == null) {
			return null;
		}
		if (this.oInputFormat) {
			iValue = this.oInputFormat.parse(vValue);
			if (iValue == null) {
				throw new sap.ui.model.FormatException("Cannot format float: " + vValue + " has the wrong format");
			}
		}
		switch (this.getPrimitiveType(sInternalType)) {
			case "string":
				return this.oOutputFormat.format(iValue);
			case "int":
			case "float":
			case "any":
				return iValue;
			default:
				throw new sap.ui.model.FormatException("Don't know how to format Integer to " + sInternalType);
		}
	};

	/**
	 * @see sap.ui.model.SimpleType.prototype.parseValue
	 */
	Integer.prototype.parseValue = function(vValue, sInternalType) {
		var iResult, oBundle;
		switch (this.getPrimitiveType(sInternalType)) {
			case "string":
				iResult = this.oOutputFormat.parse(String(vValue));
				if (isNaN(iResult)) {
					oBundle = sap.ui.getCore().getLibraryResourceBundle();
					throw new sap.ui.model.ParseException(oBundle.getText("Integer.Invalid"));
				}
				break;
			case "float":
				iResult = Math.floor(vValue);
				if (iResult != vValue) {
					oBundle = sap.ui.getCore().getLibraryResourceBundle();
					throw new sap.ui.model.ParseException(oBundle.getText("Integer.Invalid"));
				}
				break;
			case "int":
				iResult = vValue;
				break;
			default:
				throw new sap.ui.model.ParseException("Don't know how to parse Integer from " + sInternalType);
		}
		if (this.oInputFormat) {
			iResult = this.oInputFormat.format(iResult);
		}
		return iResult;
	};

	/**
	 * @see sap.ui.model.SimpleType.prototype.validateValue
	 */
	Integer.prototype.validateValue = function(iValue) {
		if (this.oConstraints) {
			var oBundle = sap.ui.getCore().getLibraryResourceBundle(),
				aViolatedConstraints = [],
				aMessages = [];
			jQuery.each(this.oConstraints, function(sName, oContent) {
				switch (sName) {
					case "minimum":
						if (iValue < oContent) {
							aViolatedConstraints.push("minimum");
							aMessages.push(oBundle.getText("Integer.Minimum", [oContent]));
						}
						break;
					case "maximum":
						if (iValue > oContent) {
							aViolatedConstraints.push("maximum");
							aMessages.push(oBundle.getText("Integer.Maximum", [oContent]));
						}
				}
			});
			if (aViolatedConstraints.length > 0) {
				throw new sap.ui.model.ValidateException(aMessages.join(" "), aViolatedConstraints);
			}
		}
	};

	/**
	 * @see sap.ui.model.SimpleType.prototype.setFormatOptions
	 */
	Integer.prototype.setFormatOptions = function(oFormatOptions) {
		this.oFormatOptions = oFormatOptions;
		this._createFormats();
	};

	/**
	 * Called by the framework when any localization setting changed
	 * @private
	 */
	Integer.prototype._handleLocalizationChange = function() {
		this._createFormats();
	};

	/**
	 * Create formatters used by this type
	 * @private
	 */
	Integer.prototype._createFormats = function() {
		var oSourceOptions = this.oFormatOptions.source;
		this.oOutputFormat = NumberFormat.getIntegerInstance(this.oFormatOptions);
		if (oSourceOptions) {
			if (jQuery.isEmptyObject(oSourceOptions)) {
				oSourceOptions = {
					groupingEnabled: false,
					groupingSeparator: ",",
					decimalSeparator: "."
				};
			}
			this.oInputFormat = NumberFormat.getIntegerInstance(oSourceOptions);
		}
	};

	return Integer;

}, /* bExport= */ true);


text:
package org.jspare.unit.mock;

import lombok.SneakyThrows;
import org.jspare.core.InjectorAdapter;

import java.lang.reflect.Field;

/**
 * Injector adapater for {@link Mock} annotation.
 * Created by paulo.ferreira on 25/07/2017.
 */
public class MockStrategy implements InjectorAdapter {

  @Override
  public boolean isInjectable(Field field) {
    return field.isAnnotationPresent(Mock.class);
  }

  @Override
  @SneakyThrows
  public void inject(Object instance, Field field) {

    Object result = Mocks.injectMocks(field.getType());
    field.setAccessible(true);
    field.set(instance, result);
  }
}


text: browserify 005-client.js > bundle.js && node 001-server.js


text:
const fs = require('fs');
const path = require('path');

const packageJsonPath = require.resolve('jsesc').replace('jsesc.js', 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath));

const packageJsonPath2 = packageJsonPath.replace(
    '/e2e_packages_yarn_install_duplicate_for_determinism_testing/', '/e2e_packages_yarn_install/');
const packageJson2 = JSON.parse(fs.readFileSync(packageJsonPath2));

try {
  require.resolve('tmp');
  console.error(
      'expected tmp to not be installed by yarn as --prod was passed via args in yarn_install');
  process.exitCode = 1;
} catch (_) {
}

if (packageJsonPath === packageJsonPath2) {
  console.error('expected different json paths');
  process.exitCode = 1;
}
if (JSON.stringify(packageJson) !== JSON.stringify(packageJson2)) {
  console.error(
      'jsesc package.json files from two different yarn_install runs should have the same contents');
  process.exitCode = 1;
}


text:
package com.oklab.gitjourney.activities;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.oklab.gitjourney.R;
import com.oklab.gitjourney.adapters.UserProfileDetailAdapter;
import com.oklab.gitjourney.asynctasks.GitHubUserRepositoriesLoader;
import com.oklab.gitjourney.asynctasks.UserProfileAsyncTask;
import com.oklab.gitjourney.data.GitHubUserProfileDataEntry;
import com.oklab.gitjourney.data.ReposDataEntry;
import com.oklab.gitjourney.parsers.GitHubUserProfileDataParser;
import com.oklab.gitjourney.parsers.Parser;
import com.squareup.picasso.Picasso;

import java.util.List;
import java.util.Locale;

public class PersonalActivity extends AppCompatActivity implements UserProfileAsyncTask.OnProfilesLoadedListener<GitHubUserProfileDataEntry> {
    private static final String TAG = PersonalActivity.class.getSimpleName();
    UserProfileDetailAdapter userProfileDetailAdapter;
    private RecyclerView recyclerView;
    private ImageView profilePoster;
    private TextView repositories;
    private TextView following;
    private TextView followers;
    private GitHubUserProfileDataEntry entry;
    private int currentPage = 1;
    private boolean reposExhausted = false;
    private boolean loading = false;
    private GridLayoutManager gridLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String userLogin = getIntent().getStringExtra("userSessionData");

        setContentView(R.layout.activity_personal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(userLogin);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        recyclerView = (RecyclerView) findViewById(R.id.repo_details);
        recyclerView.setNestedScrollingEnabled(false);
        profilePoster = (ImageView) findViewById(R.id.profile_poster);
        repositories = (TextView) findViewById(R.id.repositories);
        following = (TextView) findViewById(R.id.following);
        followers = (TextView) findViewById(R.id.followers);

        Parser<GitHubUserProfileDataEntry> parser = new GitHubUserProfileDataParser();
        new UserProfileAsyncTask<GitHubUserProfileDataEntry>(this, this, parser).execute();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setVisibility(View.GONE); //TODO: delete this line when edit functionality will be done
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO: implement an edit activity
            }
        });
    }

    @Override
    public void OnProfilesLoaded(GitHubUserProfileDataEntry dataEntry) {
        entry = dataEntry;
        userProfileDetailAdapter = new UserProfileDetailAdapter(this);
        gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(userProfileDetailAdapter);
        recyclerView.addOnScrollListener(new UserProfileItemsListOnScrollListener());
        populateUserProfileData();
        Log.v(TAG, "onActivityCreated");
        Bundle bundle = new Bundle();
        bundle.putInt("page", currentPage++);
        bundle.putString("login", dataEntry.getLogin());
        getSupportLoaderManager().initLoader(0, bundle, new ReposLoaderCallbacks());
    }

    private void populateUserProfileData() {
        repositories.setText(String.format(Locale.getDefault(), "%d", entry.getPublicRepos()));
        followers.setText(String.format(Locale.getDefault(), "%d", entry.getFollowers()));
        following.setText(String.format(Locale.getDefault(), "%d", entry.getFollowing()));

        Picasso pic = Picasso.with(this);
        if (entry.getImageUri() == null || entry.getImageUri().isEmpty()) {
            pic.load(R.drawable.octocat)
                    .fit().centerCrop()
                    .into(profilePoster);
        } else {
            pic.load(entry.getImageUri())
                    .fit().centerCrop()
                    .error(R.drawable.octocat)
                    .into(profilePoster);
        }
    }

    private class UserProfileItemsListOnScrollListener extends RecyclerView.OnScrollListener {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastScrollPosition = gridLayoutManager.findLastCompletelyVisibleItemPosition();
            int itemsCount = userProfileDetailAdapter.getItemCount();
            if (lastScrollPosition == itemsCount - 1 && !reposExhausted && !loading) {
                loading = true;
                Bundle bundle = new Bundle();
                bundle.putInt("page", currentPage++);
                bundle.putString("login", entry.getLogin());
                getSupportLoaderManager().initLoader(0, bundle, new ReposLoaderCallbacks());
            }
        }
    }

    private class ReposLoaderCallbacks implements LoaderManager.LoaderCallbacks<List<ReposDataEntry>> {

        @Override
        public Loader<List<ReposDataEntry>> onCreateLoader(int id, Bundle args) {
            return new GitHubUserRepositoriesLoader(PersonalActivity.this, args.getInt("page"), args.getString("login"), true);
        }

        @Override
        public void onLoadFinished(Loader<List<ReposDataEntry>> loader, List<ReposDataEntry> reposDataEntryList) {
            loading = false;
            if (reposDataEntryList != null && reposDataEntryList.isEmpty()) {
                reposExhausted = true;
                getLoaderManager().destroyLoader(loader.getId());
                return;
            }
            userProfileDetailAdapter.addAll(reposDataEntryList);
            getLoaderManager().destroyLoader(loader.getId());
        }

        @Override
        public void onLoaderReset(Loader<List<ReposDataEntry>> loader) {
            loading = false;
        }
    }
}