text:
// DevXLauncher.cpp : Defines the entry point for the application.
//

#ifdef _WIN32
#include "stdafx.h"
#include "io.h"
#include <Winsock2.h>
#else
#define strcmpi	strcasecmp
#include "sys/types.h"
#include "sys/uio.h"
#include "unistd.h"
#include "sys/wait.h"
#include <string.h>
#endif

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#include "nameServCalls.h"
#include "debug.h"
#include "startproc.h"

int do_debug = 0;
FILE* log_fd;
char	dbgFileName[1024];

static char* read_line(int fd) {
int i;
static char line[1024];
char ch,prev = ' ';

   for(i=0;i<1024;i++) {
	    if(read(fd,&ch,1)!=1) break;
	    if(ch=='\n') break;
		if(ch!='\r')
		    line[i]=ch;
		else
			i--;
   }
   line[i]=0;
   return line;
}

static char* GetKey(char* str) {
static char key[1024];
int j = 0;

    for(int i = 0; i<1023; i++) {
        if(str[i]==0)   break;
		if(str[i]==':') break;
		key[j++]=str[i];
	}
	while(j>0 && key[j-1]==' ') j--;
	key[j]=0;
	return key;
}

static char* GetValue(char* str) {
static char value[1024];
int j=0;
int in_value = 0;

    for(int i = 0; i<1023; i++) {
		if(str[i]==0)   {
	        while(j>0 && value[j-1]==' ') j--;
			value[j]=0;
			break;
		}
		if(str[i]==':' && in_value==0 ) {
			in_value = 1;
			i++;
	        while(i<1023 && str[i]==' ' && str[i]!=0) i++;
		}
        if(in_value == 1)   value[j++]=str[i];
	}
	while(j>0 && value[j-1]==' ') j--;
	value[j]=0;
	// removing leading...
	if(value[0]=='"')
		strcpy(value,value+1);
	// ...and trailing quotes if any
	if(value[strlen(value)-1]=='"')
		value[strlen(value)-1] = 0;
	return value;
}

bool getMemorySetings(HANDLE handle,char* memorySet) {
	char	curChar;
	DWORD	dwReaded;
	char	currentLine[1024];
	int		currentLineIDX = 0;
	char*	delim;
	char	parameter[1024];
	char	value[1024];

#ifdef _WIN32
	if( ReadFile(handle,&curChar,1,&dwReaded,NULL)==TRUE )
#else //UNIX
	if( read(handle,&curChar,1)>0 )
#endif
		if( curChar == ';' ) { //  Insure that prefs is saved in text mode.
							  //  Only true for older version of CR.
#ifdef _WIN32
			while(ReadFile(handle,&curChar,1,&dwReaded,NULL)==TRUE) {
#else //UNIX
			while(read(handle,&curChar,1)>0) {
#endif
				// skeep leading spaces
				if(currentLineIDX==0 && curChar==' ')
					continue;
				if(curChar != '\n' || curChar != '\r' ||
				   curChar != ' ' || curChar != '\t') {
					if (currentLineIDX >= 1024 ) {
						strcpy(memorySet,"-mx64M");
						break;
					}
					currentLine[currentLineIDX++]=curChar;
				}
				else {
					currentLine[currentLineIDX] = 0;
					if((delim = strchr(currentLine,'='))!=NULL) {
						strncpy(parameter,currentLine,delim-currentLine);
						parameter[delim-currentLine]=0;
						while(parameter[strlen(parameter)-1]==' ')
							parameter[strlen(parameter)-1] = 0;
						// next char - current is '='
						delim++;
						// trim all leading...
						while(*delim==' ')	delim++;
						strcpy(value,delim);
						// ...and trailing spaces
						while(value[strlen(value)-1]==' ')
							value[strlen(value)-1] = 0;
						// looking for necessary parameter
#ifdef _WIN32
						if(_stricmp(parameter,"Memory")==0) {
#else //UNIX
						if(strcasecmp(parameter,"Memory")==0) {
#endif
							sprintf(memorySet,"-mx%sM",value);
							break;
						}
					}
					currentLineIDX = 0;
					currentLine[currentLineIDX]=0;
				 }
			}
		}
		else {
			strcpy(memorySet,"-mx64M");
			return false;
		}
	return true;
}

extern int startExeMain(void);

static const int CODE_ROVER = 0;
static const int PROJECT_EDITOR = 1;

#ifdef _WIN32
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow) {
	char	argv[20][1024];
	int	argc=parseCommandLine(GetCommandLine(), argv);
	char	userName[1024] = "USER=";
	DWORD	bufSize = 1024;

	// setting user name environment variable...
	if(GetUserName( userName+strlen(userName), &bufSize)==TRUE)
		putenv(userName);

#else
int main(int argc, char* argv[]) {
#endif

 	// TODO: Place code here.
	int	bNameServerStarted = 0;
	int i, dont_start_CodeRover = 0;
	int	noService = 0;
	int	startApp = CODE_ROVER;
	char*	filename=NULL;
	char*	currentUser;

	// the first command line parameter is an executable name, so skip it
	for(i=1;i<argc;i++) {
		if(argv[i][0]!='-') {
			if(filename==NULL)
			    filename = strdup(argv[i]);
			continue;
		}
		if(strcmp(argv[i],"-debug")==0) {
			if(((i+1)<argc) && strlen(argv[i+1])>0) {
				do_debug=1;
				strcpy(dbgFileName,argv[++i]);
				_DBG_OPEN();
				if(log_fd==NULL)
					do_debug = 0;
			}
		} else {
			if(strcmp(argv[i],"-norover")==0)
				dont_start_CodeRover = 1;
			else {
				if(strcmp(argv[i],"-noservice")==0)
					noService = 1;
				else {
					if(strcmp(argv[i],"-rover")==0)
						startApp = CODE_ROVER;
					else {
						if(strcmp(argv[i],"-project")==0)
							startApp = PROJECT_EDITOR;
					}
				}
			}
		}
	}

	if((currentUser=getenv("USER"))!=NULL) {
		_DBG(fprintf(log_fd,"Current user is %s\n",currentUser));
	} else {
#ifdef _WIN32
		char	userNameBuff[1024];
		strcpy(userNameBuff,"USER=");
		unsigned	userWordLen = strlen(userNameBuff);
		unsigned long	maxLen = 1024-userWordLen;
		if(GetUserName(userNameBuff+userWordLen,&maxLen)==TRUE) {
			putenv(userNameBuff);
			if((currentUser=getenv("USER"))!=NULL) {
				_DBG(fprintf(log_fd,"Current user is %s\n",currentUser));
			} else {
				_DBG(fprintf(log_fd,"Current user is UNDEFINED.\n"));
			}
		}
#else
		_DBG(fprintf(log_fd,"Current user is UNDEFINED.\n"));
#endif
	}

	int fd = -1;
	if(filename!=NULL) {
		_DBG(fprintf(log_fd,"File name is %s\n",filename));
		fd = open(filename,O_RDONLY);
	}

	char *line;
	char *host=NULL;
	char *model=NULL;
	char *root=NULL;
	char *connection=NULL;

	if(fd>0) {
		_DBG(fprintf(log_fd,"Parsing file...\n"));
		do {
		   line = read_line(fd);
		   char* key = GetKey(line);
		   if(strcmpi(key,"HOST")==0)  {
			   host = strdup(GetValue(line));
				_DBG(fprintf(log_fd,"Host is \"%s\"\n",host));
		   }
		   if(strcmpi(key,"MODEL")==0)  {
			   model = strdup(GetValue(line));
				_DBG(fprintf(log_fd,"Model is \"%s\"\n",model));
		   }
		   if(strcmpi(key,"SOURCE-ROOT")==0)  {
			   root = strdup(GetValue(line));
				_DBG(fprintf(log_fd,"Source root is \"%s\"\n",root));
		   }
		   if(strcmpi(key,"CONNECTION")==0)  {
			   connection = strdup(GetValue(line));
				_DBG(fprintf(log_fd,"Connection is \"%s\"\n",connection));
		   }
		} while(strlen(line)>0);

		close(fd);
	}

#ifdef _WIN32
	WORD    wVersionRequested;
	WSADATA wsaData;
	int     err = 0;

	_DBG(fprintf(log_fd,"Calling WSAStartup... "));
	wVersionRequested = MAKEWORD(1, 1);
#ifndef VIEWER_ONLY
	err               = WSAStartup(wVersionRequested, &wsaData);
#endif
	if (err != 0) {
		_DBG(fprintf(log_fd,"no sockets available\n"));
		return -1;
	}
	_DBG(fprintf(log_fd,"OK\n"));
	putenv("DIS_NLUNIXSTYLE=1");
#endif

    char	install_path[2048];
	char*	envir;
    DWORD dwBufLen = 2048;

	_DBG(fprintf(log_fd,"Getting environment variable... "));
	envir = getenv("CODE_ROVER_HOME");
	if(envir!=NULL) {
		_DBG(fprintf(log_fd,"CODE_ROVER_HOME=%s\n",envir));
		strcpy(install_path,envir);
	} else {
		_DBG(fprintf(log_fd,"CODE_ROVER_HOME is not set.\n"));
#ifdef _WIN32
		HKEY hKey;
		_DBG(fprintf(log_fd,"Trying to get environment variable from registry...\n"));
		DWORD dwType = REG_SZ;
		char envVar[2048];
		char	crVar[1024];
		DWORD dwSize = 2048;
		RegOpenKey(HKEY_CURRENT_USER,"Environment",&hKey);
		if(RegQueryValueEx( hKey,"CODE_ROVER_HOME",NULL,&dwType,(unsigned char*)envVar,&dwSize) == ERROR_SUCCESS) {
			_DBG(fprintf(log_fd,"   Get key  - OK \n"));
			strcpy(crVar,"CODE_ROVER_HOME=");
			strcat(crVar,envVar);
			putenv(crVar);
			strcpy(install_path,envVar);
		} else {
			_DBG(fprintf(log_fd,"   Get key  - FAILED\n"));
			envir = getenv("PSETHOME");
			if(envir) {
				strcpy(crVar,"CODE_ROVER_HOME=");
				strcat(crVar,envir);
				putenv(crVar);
				strcpy(install_path,envir);
			} else
				strcpy(install_path,"");
		}
#endif
	}

	char right_install_path[4096];
    strcpy(right_install_path,install_path);
	if(install_path[strlen(install_path)-1]!='/' &&
	   install_path[strlen(install_path)-1]!='\\') {
	   strcat(right_install_path,"\\");
	}
	_DBG(fprintf(log_fd,"%s\n",right_install_path));
	char command[4096];
	int	service_port, tcp_addr;

#ifndef VIEWER_ONLY
	// Start nameserver at first
	_DBG(fprintf(log_fd,"Launching nameserv..."));
	if(NameServerGetService("test", service_port, tcp_addr) < 0) {
		if(LaunchNameServer(START_SERVER)==1) {
			bNameServerStarted = 1;
			_DBG(fprintf(log_fd,"OK\n"));
		} else {
			_DBG(fprintf(log_fd,"FAILED!!!\n"));
		}
	} else {
		_DBG(fprintf(log_fd,"OK\n"));
	}
#endif

#ifndef VIEWER_ONLY
#ifndef NO_DRIVERS
	// Will pick up developer studio driver here
	strcpy(command,"\"");
	strcat(command,right_install_path);
	strcat(command,"bin\\msdriver.exe");
	strcat(command,"\"");

	_DBG(fprintf(log_fd,command,strlen(command)));
	_DBG(fprintf(log_fd,"\n",1));

	_DBG(fprintf(log_fd,"Launching msdriver..."));
	if(start_new_process(command)!=-1) {
		_DBG(fprintf(log_fd,"OK\n"));
	} else {
		_DBG(fprintf(log_fd,"FAILED!!!\n"));
	}
#endif
#endif

#ifndef VIEWER_ONLY
#ifndef NO_DRIVERS
	// Will pick up Emacs driver here
	strcpy(command,"\"");
	strcat(command,right_install_path);
	strcat(command,"bin\\emacsclient.exe");
	strcat(command,"\"");

	_DBG(fprintf(log_fd,command,strlen(command)));
	_DBG(fprintf(log_fd,"\n",1));

	_DBG(fprintf(log_fd,"Launching emacsclient..."));
    	if(start_new_process(command)!=-1) {
		_DBG(fprintf(log_fd,"OK\n"));
	} else {
		_DBG(fprintf(log_fd,"FAILED!!!\n"));
	}
#endif
#endif

#ifndef VIEWER_ONLY
#ifndef NO_DRIVERS
	// Will pick up CM driver here
	strcpy(command,"\"");
	strcat(command,right_install_path);
	strcat(command,"bin\\CMDriver.exe");
	strcat(command,"\"");

	_DBG(fprintf(log_fd,command,strlen(command)));
	_DBG(fprintf(log_fd,"\n",1));

	_DBG(fprintf(log_fd,"Launching CMDriver..."));
    	if(start_new_process(command)!=-1) {
		_DBG(fprintf(log_fd,"OK\n"));
	} else {
		_DBG(fprintf(log_fd,"FAILED!!!\n"));
	}
#endif
#endif
	// Will start new applet which will run  Dislite.DisliteApp class

#ifdef _WIN32
	char	memorySet[15];
	char	prefFileName[1024];
	char*	userProfile = getenv("USERPROFILE");
	if(userProfile==NULL) {
		if(getenv("WINDIR")!=NULL)
			strcpy(prefFileName,getenv("WINDIR"));
	} else
		strcpy(prefFileName,userProfile);
	if(strlen(prefFileName)>0)
		if(prefFileName[strlen(prefFileName)-1]!='/' &&
		   prefFileName[strlen(prefFileName)-1]!='\\')
			strcat(prefFileName,"/");
	strcat(prefFileName,"preferences.dat");
	HANDLE	prefFile = CreateFile(prefFileName,GENERIC_READ,FILE_SHARE_READ,NULL,
								OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
	if(prefFile != INVALID_HANDLE_VALUE) {
		if(getMemorySetings(prefFile,memorySet)==false) {
			_DBG(fprintf(log_fd,"Settings reading FAILED. Using default value %s.\n",memorySet));
		} else {
			_DBG(fprintf(log_fd,"Memory settings value is %s.\n",memorySet));
		}
		CloseHandle(prefFile);
	} else {
		strcpy(memorySet,"-mx64M");
		_DBG(fprintf(log_fd,"No settings file. Using default value %s.\n",memorySet));
	}
#else //UNIX
	char	memorySet[15];
	char	prefFileName[1024];
	char*	userProfile = getenv("HOME");
	if(userProfile==NULL) {
		strcpy(prefFileName,"");
	} else
		strcpy(prefFileName,userProfile);
	if(strlen(prefFileName)>0)
		if(prefFileName[strlen(prefFileName)-1]!='/' &&
		   prefFileName[strlen(prefFileName)-1]!='\\')
			strcat(prefFileName,"/");
	strcat(prefFileName,"preferences.dat");
	int	prefFile = open(prefFileName,O_RDONLY);
	if(prefFile != -1) {
		if(getMemorySetings(prefFile,memorySet)==false) {
			_DBG(fprintf(log_fd,"Settings reading FAILED. Using default value %s.\n",memorySet));
		} else {
			_DBG(fprintf(log_fd,"Memory settings value is %s.\n",memorySet));
		}
		close(prefFile);
	} else {
		strcpy(memorySet,"-mx64M");
		_DBG(fprintf(log_fd,"No settings file. Using default value %s.\n",memorySet));
	}
#endif

	if( !dont_start_CodeRover ) {
		switch(startApp) {
		case CODE_ROVER:
			sprintf(command,"\"%sjre\\bin\\java\" %s -jar \"%slib\\CodeRover.jar\"",right_install_path, memorySet, right_install_path);
			strcat(command," ");
 			if(host!=NULL )
       			strcat(command,host);
			else
				strcat(command,"\"\"");
    		strcat(command," ");
    		if(model!=NULL)
				strcat(command,model);
    		else
				strcat(command,"\"\"");
			strcat(command," ");
			if(connection != NULL)
				strcat(command,connection);
			else
				strcat(command,"\"\"");
			strcat(command," ");
			if(root!=NULL)
				strcat(command,root);
			else
				strcat(command,"\"\"");
			break;
		case PROJECT_EDITOR:
			sprintf(command,"\"%sjre\\bin\\java\" -jar \"%slib\\ProjectEditor.jar\"",right_install_path, right_install_path);
			break;
		}

		_DBG(fprintf(log_fd,command,strlen(command)));
		_DBG(fprintf(log_fd,"\n",1));

		_DBG(fprintf(log_fd,"Launching application..."));
		if(start_new_process(command,START_NO_WAIT)!=-1){
			_DBG(fprintf(log_fd,"OK\n"));
		} else {
			_DBG(fprintf(log_fd,"FAILED!!!\n"));
#ifndef _WIN32
			printf("Failed to start CodeRover. Possibly link to java is incorrect.\n");
#endif
			exit(-1);
		}
	}

	free(filename);
	if(host) free(host);
	if(model) free(model);
	if(root) free(root);
	if(connection) free(connection);

#ifndef VIEWER_ONLY
#ifndef _WIN32
	const pid_t pid = fork();
    if(pid == 0) {
		int retCode = 0;
		if(!noService)
			retCode = startExeMain();
		if(bNameServerStarted == 1) {
			_DBG(fprintf(log_fd,"Closing nameserv..."));
			if(LaunchNameServer(STOP_SERVER)==1) {
				_DBG(fprintf(log_fd,"OK\n"));
			} else {
				_DBG(fprintf(log_fd,"FAILED!!!\n"));
			}
		}
		_DBG(fprintf(log_fd,"Program closed\n"));
		_DBG_CLOSE();
		return 0;
    } else {
		_DBG(fprintf(log_fd,"Program closed\n"));
		_DBG_CLOSE();
		return 0;
    }
#else
	int retCode = 0;
	if(!noService)
		retCode = startExeMain();
	if(bNameServerStarted == 1) {
		_DBG(fprintf(log_fd,"Closing nameserv..."));
		if(LaunchNameServer(STOP_SERVER)==1) {
			_DBG(fprintf(log_fd,"OK\n"));
		} else {
			_DBG(fprintf(log_fd,"FAILED!!!\n"));
		}
	}
	_DBG(fprintf(log_fd,"Program closed\n"));
	_DBG_CLOSE();
	return retCode;
#endif
#else
	_DBG_CLOSE();
	return 0;
#endif
}


text:
#import "DOMRange.h"

@interface DOMRange (MailExtras)
- (id)firstNode;
- (id)lastNode;
- (BOOL)isEquivalentToCollapsedRange;
- (BOOL)includeTemporarySelectionMarkers;
- (void)hoistRange;
- (id)stringValue;
- (id)attributedStringWithDocument:(id)arg1;
- (void)getBlockBoundaryParent:(id *)arg1 nextSibling:(id *)arg2 atStart:(BOOL)arg3;
- (void)fixIfEndpointIsAtBeginningOfLine;
- (void)fixIfStartIsAtEndOfContainerNode;
- (void)balanceContainers;
- (id)rangeOfContainingBlock;
- (BOOL)containsRichTextForMessageFont:(id)arg1;
- (id)attachmentsByURLFromDocument:(id)arg1;
- (void)attachments:(id *)arg1 urls:(id *)arg2 fromDocument:(id)arg3;
- (id)attachmentsFromDocument:(id)arg1;
- (id)stringRepresentation;
- (BOOL)isEqualToRange:(id)arg1;
- (BOOL)containsRange:(id)arg1;
- (void)setWithStringRepresentation:(id)arg1;
- (BOOL)isEditable;
- (BOOL)containsListElements;
- (BOOL)runSelectorOnContents:(SEL)arg1;
- (BOOL)hasNoSignificantContentsOrWhitespace;
- (BOOL)hasNoSignificantContentsOtherThanAttachments;
- (BOOL)hasNoSignificantContents;
@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\Persistent\Model;

/**
 * Persistent Factory
 */
class Factory
{
    /**
     * Object manager
     *
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * Construct
     *
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
    {
        $this->_objectManager = $objectManager;
    }

    /**
     * Creates models
     *
     * @param string $className
     * @param array $data
     * @return mixed
     */
    public function create($className, $data = [])
    {
        return $this->_objectManager->create($className, $data);
    }
}


text:
var validation_lang = {
	required: 'The %s field is required.',
	nozero: 'The %s field can not be zero.',
	exactlength: 'The %s field must be exactly %k characters in length.',
	minlength: 'The %s field must be at least %k characters long.',
	maxlength: 'The %s field must be less than %k characters long.',
	alpha: 'The %s field must be letters only.',
	alphanumeric: 'The %s field must be letters and numbers only.',
	numeric: 'The %s field must be a numeric value.',
	integer: 'The %s field must be an integer.',
	natrual: 'The %s field must be a natural number.',
	decimal: 'The %s field must be a decimal number.',
	between: 'The %s field must be a value between %k and %n.',
	matches: 'The %s field must match the field %k.',
	email: 'The %s field must be a valid email.',
	url: 'The %s field must be a valid url.',
	ip: 'The %s field must be a valid ip.',
	time: 'The %s field must be a valid time.',
	date: 'The %s field must be a valid date.',
	cc: 'The %s field is not a valid credit card number.'
};


text:
title: Docker
layout: docs
toc_min_level: 2
---

# Docker

Flynn has a built-in `docker-receive` app which wraps a Docker registry and
imports pushed Docker images into a Flynn cluster.

## Configuration

Before pushing images to a Flynn cluster, both the local `flynn` and `docker`
CLIs need to be configured.

Configure the `flynn` CLI by running:

```
$ flynn docker set-push-url
```

Configure the `docker` CLI by running:

```
$ flynn docker login
```

_If you see "Error configuring docker", follow the instructions which appear
above the error then re-run `flynn docker login`._

## Push an image

Run the following to push a Docker image to `docker-receive` and deploy it:

```
$ flynn -a APPNAME docker push IMAGE
```

where `APPNAME` is the name of an existing Flynn app and `IMAGE` is a reference
to a Docker image which is available to the local `docker` CLI (in other words,
an image which appears in the output of `docker images`).

## Routing

Flynn automatically registers the HTTP route `http://APPNAME.$CLUSTER_DOMAIN`
for the app. In order to receive HTTP traffic for this route, the app needs to
listen on the port which is set in the `PORT` environment variable.

## Example

Here is an example of deploying the [Flynn Node.js example app](https://github.com/flynn-examples/nodejs-flynn-example)
using `flynn docker push`.

Clone the git repository:

```
$ git clone https://github.com/flynn-examples/nodejs-flynn-example.git
$ cd nodejs-flynn-example
```

Build the Docker image:

```
$ docker build -t nodejs-flynn-example .
```

Create an app:

```
$ flynn create --remote "" nodejs
Created nodejs
```

_NOTE: the `--remote ""` flag prevents Flynn trying to configure the local
git repository with a `flynn` remote, something which is useful only when
deploying with `git push` rather than `flynn docker push`._

Push the Docker image:

```
$ flynn -a nodejs docker push nodejs-flynn-example
flynn: getting image config with "docker inspect -f {{ json .Config }} nodejs-flynn-example"
flynn: tagging Docker image with "docker tag nodejs-flynn-example docker.1.localflynn.com/nodejs:latest"
flynn: pushing Docker image with "docker push docker.1.localflynn.com/nodejs:latest"
The push refers to a repository [docker.1.localflynn.com/nodejs] (len: 1)
82b9b0ffb6da: Pushed
be8edf33c031: Pushed
...
767584930cea: Pushed
d34921bc2709: Pushed
latest: digest: sha256:be6aeade058f0df30a039a432aaf4cb21accd992d4c0df80ddb333b15f401b6a size: 16114
flynn: image pushed, waiting for artifact creation
flynn: deploying release using artifact URI http://flynn:dbd202007171356f4551160dede351ae@docker-receive.discoverd?name=nodejs&id=sha256:be6aeade058f0df30a039a432aaf4cb21accd992d4c0df80ddb333b15f401b6a
flynn: image deployed, scale it with 'flynn scale app=N'

```

You now have a release with an `app` process which runs using the pushed image
and has an `ENTRYPOINT`, `CMD` and `ENV` as taken from the Docker image's
config.

If this is the first deploy of the app, scale the `app` process to start it:

```
$ flynn -a nodejs scale app=1
scaling app: 0=>1

16:24:31.397 ==> app 4a7319af-af2c-4fe1-9a9a-2dd4d5bd3765 pending
16:24:31.398 ==> app host0-4a7319af-af2c-4fe1-9a9a-2dd4d5bd3765 starting
16:24:31.527 ==> app host0-4a7319af-af2c-4fe1-9a9a-2dd4d5bd3765 up

scale completed in 140.63784ms
```

The `app` process will be configured with a service name like `APPNAME-web` so
your Flynn apps can communicate with the deployed service internally using
`APPNAME-web.discoverd:PORT` (e.g. `nodejs-web.discoverd:8080`):

```
$ flynn -a nodejs run curl http://nodejs-web.discoverd:8080
Hello from Flynn on port 8080 from container 4a7319af-af2c-4fe1-9a9a-2dd4d5bd3765
```

The app can be reached externally via the automatically registered route
`http://APPNAME.$CLUSTER_DOMAIN`:

```
$ curl http://nodejs.1.localflynn.com
Hello from Flynn on port 8080 from container 4a7319af-af2c-4fe1-9a9a-2dd4d5bd3765
```


text:
<?php
namespace App\Command;

use App\Entity\GameRelease;
use App\Service\ConfigService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ImportGamesCommand extends Command
{
    private $em;
    private $configService;

    public function __construct(EntityManagerInterface $em, ConfigService $configService)
    {
        $this->em = $em;
        $this->configService = $configService;

        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setName('app:import-games')
            ->setDescription('Imports a list of video games from a CSV into the autocomplete list.')
            ->setHelp('This script populates the `game_releases` table using data from Wikipedia that has been pre-formatted'
                . ' and placed into an CSV. The CSV should consist of two columns: the first column should contain the name'
                . ' of the game, and the second column should contain a comma separated list of platform abbreviations.')
            ->addArgument('file', InputArgument::REQUIRED, 'Filename of the CSV to import')
            ->addOption('no-clear', null, InputOption::VALUE_NONE, 'Don\'t clear the list of games before importing');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $filename = $input->getArgument('file');

        if ($this->configService->isReadOnly()) {
            throw new \RuntimeException('Database is in read-only mode. Read-only mode must be disabled to run this script.');
        }

        if (!file_exists($filename)) {
            throw new \RuntimeException('File \'' . $filename . '\' does not exist.');
        }

        if (!$input->getOption('no-clear')) {
            $this->em->createQueryBuilder()->delete(GameRelease::class)->getQuery()->execute();
            $this->em->flush();
        }

        // The second and third characters are non-breaking spaces
        $search = [' ', "\xc2\xa0", "\xa0", 'Win', 'Mac', 'Lin', 'iOS', 'Droid', 'Android', 'WP', 'X360', 'XBO', 'PSVita', '3DS', 'HTCVive', 'OculusRift', 'PlayStationVR'];
        $replace = ['', '', '', 'pc', 'pc', 'pc', 'mobile', 'mobile', 'mobile', 'mobile', 'x360', 'xb1', 'vita', 'n3ds', 'pc,vr', 'pc,vr', 'ps4,vr'];
        $delete = ['PS2', 'NDS', 'DC', 'PSP', 'Fire', 'Ouya'];

        $allPlatforms = [
            'pc', 'vr', 'ps3', 'ps4', 'vita', 'psn', 'x360', 'xb1', 'xbla', 'wii', 'wiiu', 'wiiware', 'n3ds', 'mobile'
        ];

        $games = array();

        $csv = file($filename);
        foreach ($csv as $line) {
            $array = str_getcsv($line);
            $game = trim($array[0]);
            if (!isset($games[$game])) {
                $games[$game] = array_fill_keys($allPlatforms, false);
            }

            $platforms = explode(",", trim(str_replace($search, $replace, $array[1])));
            $platforms = array_diff($platforms, $delete);
            foreach ($platforms as $platform) {
                $platform = ucfirst(strtolower($platform));
                $games[$game][$platform] = true;
            }
        }

        foreach ($games as $name => $platforms) {
            $output->writeln('<fg=cyan>' . $name . '</>', OutputInterface::VERBOSITY_VERBOSE);

            $release = new GameRelease($name);
            $platforms = array_keys(array_filter($platforms));
            foreach ($platforms as $platform) {
                if (method_exists($release, 'set' . $platform)) {
                    $release->{'set'.$platform}(true);
                } else {
                    $output->writeln('<fg=yellow>Unknown platform for game <options=bold>' . $name . ' <fg=yellow>(' . $platform . ')</>');
                }
            }
            $this->em->persist($release);
        }

        $this->em->flush();

        $output->writeln('Import complete. ' . count($games) . ' games added.');
    }
}


text:
/**
 * BadRequestException.java
 * @author Vagisha Sharma
 * Sep 23, 2010
 */
package org.yeastrc.jqs.queue.ws;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

/**
 *
 */
public class BadRequestException extends WebApplicationException {

	/**
	 * Create a HTTP 400 (Bad Request) exception.
	 */
	public BadRequestException() {
		super(Response.status(Response.Status.BAD_REQUEST).build());
	}

	/**
	 * Create a HTTP 400 (Bad Request) exception.
	 * @param message the String that is the entity of the 400 response.
	 */
	public BadRequestException(String message) {
		super(Response.status(Response.Status.BAD_REQUEST).
				entity(message).type("text/plain").build());
	}
}


text: <link rel=stylesheet href=data/css/style.css><script src=/data/js/app.js></script>


text:
package br.com.rpmhospitalar.rpmhealth;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

public class AgendamentoActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener{

    private AutoCompleteTextView hospital;
    private AutoCompleteTextView convenio;
    private  AutoCompleteTextView paciente;
    private  AutoCompleteTextView medico;
    private Button bt_cirurgia;
    private TextView tv_cirurgia;
    private EditText et_data_cirurgia;

    int day, month, year, hour, minute;
    int dayFinal, monthFinal, yearFinal, hourFinal, minuteFinal;

    String[] hospitais = {"Unimed", "Santa Casa", "Copador", "Pasteur"};
    String[] convenios = {"U.rio", "Amil", "Bradesco"};
    String[] pacientes = {"Mariana Silva", "Marcos Andrade", "Mateus Silva", "Adriano Souza", "Maria Gomes", "Luana Costa"};
    String[] medicos = {"Antônio José", "Adriano Gomes", "Augusto Cesar Dias", "Amanda Souza"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agendamento);

        hospital = (AutoCompleteTextView)findViewById(R.id.hospitalAutoComplete);
        ArrayAdapter hospitalAdapter = new ArrayAdapter(this, android.R.layout.select_dialog_item, hospitais);

        convenio = (AutoCompleteTextView)findViewById(R.id.convenioAutoComplete);
        ArrayAdapter convenioAdapter = new ArrayAdapter(this, android.R.layout.select_dialog_item, convenios);

        paciente = (AutoCompleteTextView)findViewById(R.id.pacienteAutoComplete);
        ArrayAdapter pacienteAdapter = new ArrayAdapter(this, android.R.layout.select_dialog_item, pacientes);

        medico = (AutoCompleteTextView)findViewById(R.id.medicoAutoComplete);
        ArrayAdapter medicoAdapter = new ArrayAdapter(this, android.R.layout.select_dialog_item, medicos);

        bt_cirurgia = (Button)findViewById(R.id.bt_cirurgia);
        tv_cirurgia = (TextView)findViewById(R.id.tv_cirurgia);

        hospital.setAdapter(hospitalAdapter);
        hospital.setThreshold(3);

        convenio.setAdapter(convenioAdapter);
        convenio.setThreshold(3);

        paciente.setAdapter(pacienteAdapter);
        paciente.setThreshold(3);

        medico.setAdapter(medicoAdapter);
        medico.setThreshold(3);

        bt_cirurgia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(AgendamentoActivity.this,
                        AgendamentoActivity.this, year, month, day);
                datePickerDialog.show();
            }
        });
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        yearFinal = year;
        monthFinal = month + 1;
        dayFinal = dayOfMonth;
        Calendar calendar = Calendar.getInstance();
        hour = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);

        TimePickerDialog timePickerDialog = new TimePickerDialog(AgendamentoActivity.this,
                AgendamentoActivity.this, hour, minute, DateFormat.is24HourFormat(this));
        timePickerDialog.show();
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        hourFinal = hourOfDay;
        minuteFinal = minute;

//        tv_cirurgia.setText("year: "+ yearFinal+
//                " month: "+ monthFinal+
//                " day: "+ hourFinal+
//                " minutes: "+ minuteFinal);

        tv_cirurgia.setText(dayFinal+"/"+monthFinal+"/"+yearFinal);
    }
}


text:
(function (root) {

    'use strict';

    var Reading = {
        init: function (_settings) {
            settings = _settings;
        },

        feed: function (targets, x, y, fixationDuration) {

            var newFixation = false;
            if (prevFixDuration > fixationDuration) {
                prevFixX = lastX;
                prevFixY = lastY;
                newFixation = true;
            }

            prevFixDuration = fixationDuration;

            lastX = x;
            lastY = y;

            if (newFixation) {
                var dx = x - prevFixX;
                var dy = y - prevFixY;
                var saccade = Math.sqrt(dx * dx + dy * dy);

                isReadingFixation = saccade <= settings.maxSaccadeLength &&
                    Math.abs(dy) / dx <= settings.maxSaccadeAngleRatio;

                if (!isReadingFixation) {
                    yOffset = 0;
                }
                //console.log("new fix: " + dx + "," + dy + " = " + saccade + " : " + (isReadingFixation ? "reading" : "-"));
            }

            return {x: x, y: y + yOffset};
        },

        setSelected: function (target) {
            if (target && isReadingFixation) {
                var rect = target.getBoundingClientRect();
                yOffset = (rect.top + rect.height / 2) - lastY;
            }
            else {
                yOffset = 0;
            }
        },

        reset: function (target) {
            yOffset = 0;
            lastX = -1000;
            lastY = -1000;
            prevFixX = -1000;
            prevFixY = -1000;
            prevFixDuration = 0;
            isReadingFixation = false;
        }
    };

    // internal
    var settings;
    var yOffset;
    var lastX;
    var lastY;
    var prevFixX;
    var prevFixY;
    var prevFixDuration;
    var isReadingFixation;

    // Publication
    if (!root.GazeTargets) {
        root.GazeTargets = {};
    }

    if (!root.GazeTargets.Models) {
        root.GazeTargets.Models = {};
    }

    root.GazeTargets.Models.Reading = Reading;

})(window);


text:
<ivysettings>
  <resolvers>
    <chain name="projectRepos">
      <filesystem name="projectLocalRepo">
        <ivy pattern="${ivy.settings.dir}/ivy-repo/[organization]-[module]-[revision].xml" />
      </filesystem>
			<ibiblio name="maven-repo2" m2compatible="true" root="http://repo1.maven.org/maven2/" />
    </chain>
  </resolvers>
  <settings defaultResolver="projectRepos" />
  <caches defaultCacheDir="${ivy.basedir}/ivyCache" />
</ivysettings>


text:
fatal=0

function grep_check {
  local pattern=$1
  local description=$2
  local fatalness=${3:-1}
  x=$(grep -i -E -r -Hn "$pattern" --exclude="*.gif" --exclude="*.png" --exclude="*.svg" --exclude-dir="design" --exclude-dir="contributing" --exclude-dir="build" --exclude-dir="html" documentation)
  if [ -n "$x" ]; then
    echo "$description:"
    echo "$x"
    y=$(echo "$x" | wc -l)
    ((fatal+=fatalness*y))
  fi
}

# Check for latin abbrevs
grep_check '[^[:alpha:]]?(e\.g\.[^[:alpha:]]?|[^[:alpha:]]eg[^[:alpha:]])' "Replace 'e.g'. with 'for example, '"
grep_check '[^[:alpha:]]?(i\.e\.[^[:alpha:]]?|[^[:alpha:]]ie[^[:alpha:]])' "Replace 'i.e'. with 'that is, '"
grep_check '[^[:alpha:]]?etc\.[^[:alpha:]]?' "Replace 'etc.'. with ' and so on.'"

# And/or
grep_check '[^[:alpha:]]and/or[^[:alpha:]]' "Use either 'and' or 'or', but not 'and/or'"

# Contractions
grep_check '[^[:alpha:]](do|is|are|won|have|ca|does|did|had|has|must)n'"'"'?t[^[:alpha:]]' "Avoid 'nt contraction"
grep_check '[^[:alpha:]]it'"'"'s[^[:alpha:]]' "Avoid it's contraction"
grep_check '[^[:alpha:]]can not[^[:alpha:]]' "Use 'cannot' not 'can not'"
grep_check '\<a {ProductPlatformName}' "The article should be 'an' {ProductPlatformName}"
grep_check '\<a {ProductPlatformLongName}' "The article should be 'an' {ProductPlatformLongName}"

if [ $fatal -gt 0 ]; then
  echo "ERROR: ${fatal} docs problems found."
  exit 1
fi


text:
package com.squareup.wire;

import com.squareup.javapoet.JavaFile;
import java.nio.file.Path;

final class ConsoleWireLogger implements WireLogger {
  private final boolean isQuiet;

  public ConsoleWireLogger(boolean quiet) {
    this.isQuiet = quiet;
  }

  public void info(String message) {
    if (!isQuiet) {
      System.out.println(message);
    }
  }

  @Override public void artifact(Path outputPath, JavaFile javaFile) {
    if (isQuiet) {
      System.out.printf("%s.%s%n",
          javaFile.packageName, javaFile.typeSpec.name);
    } else {
      System.out.printf("Writing %s.%s to %s%n",
          javaFile.packageName, javaFile.typeSpec.name, outputPath);
    }
  }
}


text:
FROM iron/python:2

WORKDIR /app
ADD . /app

ENTRYPOINT ["python", "hello.py"]


text:
package org.robolectric.shadows;

import android.R;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.util.TestAnimationListener;

import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(TestRunners.WithDefaults.class)
public class AnimationTest {

  private TestAnimation animation;
  private ShadowAnimation shadow;
  private TestAnimationListener listener;

  @Before
  public void setUp() throws Exception {
    animation = new TestAnimation();
    shadow = shadowOf(animation);
    listener = new TestAnimationListener();
    animation.setAnimationListener(listener);
  }

  @Test
  public void startShouldInvokeStartCallback() throws Exception {
    assertThat(listener.wasStartCalled).isFalse();
    animation.start();
    assertThat(listener.wasStartCalled).isTrue();
    assertThat(listener.wasEndCalled).isFalse();
    assertThat(listener.wasRepeatCalled).isFalse();
  }

  @Test
  public void cancelShouldInvokeEndCallback() throws Exception {
    assertThat(listener.wasEndCalled).isFalse();
    animation.cancel();
    assertThat(listener.wasStartCalled).isFalse();
    assertThat(listener.wasEndCalled).isTrue();
    assertThat(listener.wasRepeatCalled).isFalse();
  }

  @Test
  public void invokeRepeatShouldInvokeRepeatCallback() throws Exception {
    assertThat(listener.wasRepeatCalled).isFalse();
    shadow.invokeRepeat();
    assertThat(listener.wasStartCalled).isFalse();
    assertThat(listener.wasEndCalled).isFalse();
    assertThat(listener.wasRepeatCalled).isTrue();
  }

  @Test
  public void invokeEndShouldInvokeEndCallback() throws Exception {
    assertThat(listener.wasEndCalled).isFalse();
    shadow.invokeEnd();
    assertThat(listener.wasStartCalled).isFalse();
    assertThat(listener.wasEndCalled).isTrue();
    assertThat(listener.wasRepeatCalled).isFalse();
  }

  @Test
  public void invokeEnd_endsTheAnimation() throws Exception {
    shadow.invokeEnd();
    assertThat(animation.hasEnded()).isTrue();
  }

  @Test
  public void cancel_endsTheAnimation() throws Exception {
    animation.cancel();
    assertThat(animation.hasEnded()).isTrue();
  }

  @Test
  public void simulateAnimationEndShouldInvokeApplyTransformationWith1() throws Exception {
    assertThat(animation.interpolatedTime).isEqualTo(0f);
    shadow.invokeEnd();
    assertThat(animation.interpolatedTime).isEqualTo(1f);
  }

  @Test
  public void testHasStarted() throws Exception {
    assertThat(animation.hasStarted()).isFalse();
    animation.start();
    assertThat(animation.hasStarted()).isTrue();
    animation.cancel();
    assertThat(animation.hasStarted()).isFalse();
  }

  @Test
  public void testDuration() throws Exception {
    assertThat(animation.getDuration()).isNotEqualTo(1000l);
    animation.setDuration(1000);
    assertThat(animation.getDuration()).isEqualTo(1000l);
  }

  @Test
  public void testInterpolation() throws Exception {
    assertThat(animation.getInterpolator()).isNull();
    LinearInterpolator i = new LinearInterpolator();
    animation.setInterpolator(i);
    assertThat((LinearInterpolator) animation.getInterpolator()).isSameAs(i);
  }

  @Test
  public void testRepeatCount() throws Exception {
    assertThat(animation.getRepeatCount()).isNotEqualTo(5);
    animation.setRepeatCount(5);
    assertThat(animation.getRepeatCount()).isEqualTo(5);
  }

  @Test
  public void testRepeatMode() throws Exception {
    assertThat(animation.getRepeatMode()).isNotEqualTo(Animation.REVERSE);
    animation.setRepeatMode(Animation.REVERSE);
    assertThat(animation.getRepeatMode()).isEqualTo(Animation.REVERSE);
  }

  @Test
  public void testStartOffset() throws Exception {
    assertThat(animation.getStartOffset()).isNotEqualTo(500l);
    animation.setStartOffset(500l);
    assertThat(animation.getStartOffset()).isEqualTo(500l);
  }

  @Test(expected=IllegalStateException.class)
  public void testNotLoadedFromResourceId() throws Exception {
    shadow.getLoadedFromResourceId();
  }

  @Test
  public void testLoadedFromResourceId() throws Exception {
    shadow.setLoadedFromResourceId(R.anim.fade_in);
    assertThat(shadow.getLoadedFromResourceId()).isEqualTo(R.anim.fade_in);
  }

  private class TestAnimation extends Animation {
    float interpolatedTime;
    Transformation t;

    @Override protected void applyTransformation(float interpolatedTime, Transformation t) {
      this.interpolatedTime = interpolatedTime;
      this.t = t;
    }
  }
}


text:
package skutek

package object abstraction
  extends Computation_exports
  with Handler_exports
  with internals.aux.AuxExports
  with skutek.utils.Exports


text:
package galileo.dht.hash;

import java.math.BigInteger;
import java.util.TreeMap;

/**
 * Creates an evenly-spaced hash ring network topology.  Note that nodes in the
 * topology are spaced evenly apart, but of course this does not guarantee the
 * data will hash uniformly.
 *
 * @author malensek
 */
public class BalancedHashRing<T> implements HashRing<T> {

    /** If set to True, the first position in the hash ring is randomized. */
    protected boolean randomize = false;

    protected HashFunction<T> function;
    protected BigInteger maxHash;

    /** Maps hash ring positions to ring entries */
    protected TreeMap<BigInteger, HashRingEntry> entryMap = new TreeMap<>();

    /**
     * Creates a BalancedHashRing using the provided hash function.  The
     * function will determine the size of the hash space and where nodes will
     * be placed in the topology.
     *
     * @param function HashFunction that defines the hash space being used.
     */
    public BalancedHashRing(HashFunction<T> function) {
        this(function, false);
    }

    /**
     * Creates a BalancedHashRing using the provided hash function.  The
     * function will determine the size of the hash space and where nodes will
     * be placed in the topology.
     *
     * @param function HashFunction that defines the hash space being used.
     */
    public BalancedHashRing(HashFunction<T> function, boolean randomize) {
        this.function = function;
        this.randomize = randomize;
        maxHash = function.maxValue();
    }

    /**
     * Insert a node into the hash ring internal data structures.  Nodes are
     * relinked with the proper neighbors.
     *
     * @param position place in the hash space
     * @param predecessor the predecessor node in the hash space.
     */
    private void addRingEntry(BigInteger position, HashRingEntry predecessor)
    throws HashTopologyException {
        if (entryMap.get(position) != null) {
            /* Something is already here! */
            System.out.println(position);
            throw new HashTopologyException("Hash space exhausted!");
        }

        HashRingEntry newEntry
            = new HashRingEntry(position, predecessor.neighbor);
        predecessor.neighbor = newEntry;
        entryMap.put(position, newEntry);
    }

    /**
     * Add a node to the overlay network topology.
     *
     * @param data unused for this hash ring; nodes are placed evenly based on
     * current topology characteristics.  You may safely pass 'null' to this
     * method.
     *
     * @return the location of the new node in the hash space.
     */
    @Override
    public BigInteger addNode(T data)
    throws HashTopologyException, HashException {
        /* Edge case: when there are no entries in the hash ring yet. */
        if (entryMap.values().size() == 0) {
            BigInteger pos;

            if (randomize) {
                /* Find a random location to start with */
                pos = function.randomHash();
            } else {
                pos = BigInteger.ZERO;
            }

            HashRingEntry firstEntry = new HashRingEntry(pos);
            entryMap.put(pos, firstEntry);

            return pos;
        }

        /* Edge case: only one entry in the hash ring */
        if (entryMap.values().size() == 1) {
            HashRingEntry firstEntry = entryMap.values().iterator().next();
            BigInteger halfSize = maxHash.divide(BigInteger.valueOf(2));
            BigInteger secondPos = firstEntry.position.add(halfSize);

            if (secondPos.compareTo(maxHash) > 0) {
                secondPos = secondPos.subtract(maxHash);
            }

            HashRingEntry secondEntry
                = new HashRingEntry(secondPos, firstEntry);
            firstEntry.neighbor = secondEntry;
            entryMap.put(secondPos, secondEntry);

            return secondPos;
        }

        /* Find the largest empty span of hash space */
        BigInteger largestSpan = BigInteger.ZERO;
        HashRingEntry largestEntry = null;
        for (HashRingEntry entry : entryMap.values()) {
            BigInteger len = lengthBetween(entry, entry.neighbor);
            if (len.compareTo(largestSpan) > 0) {
                largestSpan = len;
                largestEntry = entry;
            }
        }

        if (largestEntry == null) {
            return BigInteger.ONE.negate();
        }

        /* Put the new node in the middle of the largest span */
        BigInteger half = half(largestEntry, largestEntry.neighbor);
        addRingEntry(half, largestEntry);
        return half;
    }

    /**
     * Find the hash location in the middle of a hash span.  When the hash space
     * is represented as a continuous circle, a span begins at an arbitrary
     * starting point and then proceeds clockwise until it reaches its endpoint.
     *
     * @param start beginning of the hash span
     * @param end end of the hash span
     *
     * @return hash position in the middle of the span.
     */
    private BigInteger half(HashRingEntry start, HashRingEntry end) {
        BigInteger length = lengthBetween(start, end);
        /* half = start + length / 2 */
        BigInteger half
            = start.position.add(length.divide(BigInteger.valueOf(2)));

        if (maxHash.compareTo(half) >= 0) {
            return half;
        } else {
            return half.subtract(maxHash);
        }
    }

    /**
     * Determines the number of hash values between two positions on a hash
     * ring.  The hash space is viewed as a ring, starting with 0 and proceeding
     * clockwise until it reaches its maximum value.  A hash span starts at an
     * arbitrary position, and then proceeds clockwise until it reaches its
     * ending position.  The number of values between the two points is the hash
     * span length.
     *
     * @param start the start of the hash span being measured
     * @param end the end of the hash span being measured
     *
     * @return the length of the hash span
     */
    private BigInteger lengthBetween(HashRingEntry start, HashRingEntry end) {
        BigInteger difference = end.position.subtract(start.position);

        if (difference.compareTo(BigInteger.ZERO) >= 0) {
            return difference;
        } else {
            /* Wraparound */
            /* wrapped = (MAX_HASH - start) + end */
            BigInteger wrapped
                = maxHash.subtract(start.position).add(end.position);
            return wrapped;
        }
    }

    @Override
    public BigInteger locate(T data) throws HashException {
        BigInteger hashLocation = function.hash(data);
        BigInteger node = entryMap.ceilingKey(hashLocation);

        /* Wraparound edge case */
        if (node == null) {
            node = entryMap.ceilingKey(BigInteger.ZERO);
        }

        return node;
    }

    /**
     * Formats the hash ring as node-to-predecessor pair Strings.
     *
     * @return network links and nodes in String format.
     */
    @Override
    public String toString() {
        String str = "";
        HashRingEntry firstEntry = entryMap.values().iterator().next();
        HashRingEntry currentEntry = firstEntry;
        HashRingEntry nextEntry;

        do {
            nextEntry = currentEntry.neighbor;
            str += currentEntry.position + " -> " + nextEntry.position;
            str += System.lineSeparator();
            currentEntry = nextEntry;
        } while (currentEntry != firstEntry);

        return str;
    }
}


text:
'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import sdk from '../../../index';
import { _t } from '../../../languageHandler';
import MatrixClientPeg from '../../../MatrixClientPeg';
import Modal from "../../../Modal";
import dis from "../../../dispatcher";
import RateLimitedFunc from '../../../ratelimitedfunc';

import * as linkify from 'linkifyjs';
import linkifyElement from 'linkifyjs/element';
import linkifyMatrix from '../../../linkify-matrix';
import AccessibleButton from '../elements/AccessibleButton';
import ManageIntegsButton from '../elements/ManageIntegsButton';
import {CancelButton} from './SimpleRoomHeader';
import SettingsStore from "../../../settings/SettingsStore";

linkifyMatrix(linkify);

module.exports = React.createClass({
    displayName: 'RoomHeader',

    propTypes: {
        room: PropTypes.object,
        oobData: PropTypes.object,
        editing: PropTypes.bool,
        saving: PropTypes.bool,
        inRoom: PropTypes.bool,
        collapsedRhs: PropTypes.bool,
        onSettingsClick: PropTypes.func,
        onPinnedClick: PropTypes.func,
        onSaveClick: PropTypes.func,
        onSearchClick: PropTypes.func,
        onLeaveClick: PropTypes.func,
        onCancelClick: PropTypes.func,
    },

    getDefaultProps: function() {
        return {
            editing: false,
            inRoom: false,
            onSaveClick: function() {},
            onCancelClick: null,
        };
    },

    componentDidMount: function() {
        const cli = MatrixClientPeg.get();
        cli.on("RoomState.events", this._onRoomStateEvents);
        cli.on("Room.accountData", this._onRoomAccountData);

        // When a room name occurs, RoomState.events is fired *before*
        // room.name is updated. So we have to listen to Room.name as well as
        // RoomState.events.
        if (this.props.room) {
            this.props.room.on("Room.name", this._onRoomNameChange);
        }
    },

    componentDidUpdate: function() {
        if (this.refs.topic) {
            linkifyElement(this.refs.topic, linkifyMatrix.options);
        }
    },

    componentWillUnmount: function() {
        if (this.props.room) {
            this.props.room.removeListener("Room.name", this._onRoomNameChange);
        }
        const cli = MatrixClientPeg.get();
        if (cli) {
            cli.removeListener("RoomState.events", this._onRoomStateEvents);
            cli.removeListener("Room.accountData", this._onRoomAccountData);
        }
    },

    _onRoomStateEvents: function(event, state) {
        if (!this.props.room || event.getRoomId() !== this.props.room.roomId) {
            return;
        }

        // redisplay the room name, topic, etc.
        this._rateLimitedUpdate();
    },

    _onRoomAccountData: function(event, room) {
        if (!this.props.room || room.roomId !== this.props.room.roomId) return;
        if (event.getType() !== "im.vector.room.read_pins") return;

        this._rateLimitedUpdate();
    },

    _rateLimitedUpdate: new RateLimitedFunc(function() {
        /* eslint-disable babel/no-invalid-this */
        this.forceUpdate();
    }, 500),

    _onRoomNameChange: function(room) {
        this.forceUpdate();
    },

    onAvatarPickerClick: function(ev) {
        if (this.refs.file_label) {
            this.refs.file_label.click();
        }
    },

    onAvatarSelected: function(ev) {
        const changeAvatar = this.refs.changeAvatar;
        if (!changeAvatar) {
            console.error("No ChangeAvatar found to upload image to!");
            return;
        }
        changeAvatar.onFileSelected(ev).catch(function(err) {
            const errMsg = (typeof err === "string") ? err : (err.error || "");
            const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
            console.error("Failed to set avatar: " + errMsg);
            Modal.createTrackedDialog('Failed to set avatar', '', ErrorDialog, {
                title: _t("Error"),
                description: _t("Failed to set avatar."),
            });
        }).done();
    },

    onAvatarRemoveClick: function() {
        MatrixClientPeg.get().sendStateEvent(this.props.room.roomId, 'm.room.avatar', {url: null}, '');
    },

    onShowRhsClick: function(ev) {
        dis.dispatch({ action: 'show_right_panel' });
    },

    onShareRoomClick: function(ev) {
        const ShareDialog = sdk.getComponent("dialogs.ShareDialog");
        Modal.createTrackedDialog('share room dialog', '', ShareDialog, {
            target: this.props.room,
        });
    },

    _hasUnreadPins: function() {
        const currentPinEvent = this.props.room.currentState.getStateEvents("m.room.pinned_events", '');
        if (!currentPinEvent) return false;
        if (currentPinEvent.getContent().pinned && currentPinEvent.getContent().pinned.length <= 0) {
            return false; // no pins == nothing to read
        }

        const readPinsEvent = this.props.room.getAccountData("im.vector.room.read_pins");
        if (readPinsEvent && readPinsEvent.getContent()) {
            const readStateEvents = readPinsEvent.getContent().event_ids || [];
            if (readStateEvents) {
                return !readStateEvents.includes(currentPinEvent.getId());
            }
        }

        // There's pins, and we haven't read any of them
        return true;
    },

    _hasPins: function() {
        const currentPinEvent = this.props.room.currentState.getStateEvents("m.room.pinned_events", '');
        if (!currentPinEvent) return false;

        return !(currentPinEvent.getContent().pinned && currentPinEvent.getContent().pinned.length <= 0);
    },

    /**
     * After editing the settings, get the new name for the room
     *
     * @return {?string} newName or undefined if we didn't let the user edit the room name
     */
    getEditedName: function() {
        let newName;
        if (this.refs.nameEditor) {
            newName = this.refs.nameEditor.getRoomName();
        }
        return newName;
    },

    /**
     * After editing the settings, get the new topic for the room
     *
     * @return {?string} newTopic or undefined if we didn't let the user edit the room topic
     */
    getEditedTopic: function() {
        let newTopic;
        if (this.refs.topicEditor) {
            newTopic = this.refs.topicEditor.getTopic();
        }
        return newTopic;
    },

    render: function() {
        const RoomAvatar = sdk.getComponent("avatars.RoomAvatar");
        const ChangeAvatar = sdk.getComponent("settings.ChangeAvatar");
        const TintableSvg = sdk.getComponent("elements.TintableSvg");
        const EmojiText = sdk.getComponent('elements.EmojiText');

        let name = null;
        let searchStatus = null;
        let topicElement = null;
        let cancelButton = null;
        let spinner = null;
        let saveButton = null;
        let settingsButton = null;
        let pinnedEventsButton = null;

        let canSetRoomName;
        let canSetRoomAvatar;
        let canSetRoomTopic;
        if (this.props.editing) {
            // calculate permissions.  XXX: this should be done on mount or something
            const userId = MatrixClientPeg.get().credentials.userId;

            canSetRoomName = this.props.room.currentState.maySendStateEvent('m.room.name', userId);
            canSetRoomAvatar = this.props.room.currentState.maySendStateEvent('m.room.avatar', userId);
            canSetRoomTopic = this.props.room.currentState.maySendStateEvent('m.room.topic', userId);

            saveButton = (
                <AccessibleButton className="mx_RoomHeader_textButton" onClick={this.props.onSaveClick}>
                    { _t("Save") }
                </AccessibleButton>
            );
        }

        if (this.props.onCancelClick) {
            cancelButton = <CancelButton onClick={this.props.onCancelClick} />;
        }

        if (this.props.saving) {
            const Spinner = sdk.getComponent("elements.Spinner");
            spinner =
<Spinner />
;
        }

        if (canSetRoomName) {
            const RoomNameEditor = sdk.getComponent("rooms.RoomNameEditor");
            name = <RoomNameEditor ref="nameEditor" room={this.props.room} />;
        } else {
            // don't display the search count until the search completes and
            // gives us a valid (possibly zero) searchCount.
            if (this.props.searchInfo &&
                this.props.searchInfo.searchCount !== undefined &&
                this.props.searchInfo.searchCount !== null) {
                searchStatus =

                    { _t("(~%(count)s results)", { count: this.props.searchInfo.searchCount }) }

;
            }

            // XXX: this is a bit inefficient - we could just compare room.name for 'Empty room'...
            let settingsHint = false;
            const members = this.props.room ? this.props.room.getJoinedMembers() : undefined;
            if (members) {
                if (members.length === 1 && members[0].userId === MatrixClientPeg.get().credentials.userId) {
                    const nameEvent = this.props.room.currentState.getStateEvents('m.room.name', '');
                    if (!nameEvent || !nameEvent.getContent().name) {
                        settingsHint = true;
                    }
                }
            }

            let roomName = _t("Join Room");
            if (this.props.oobData && this.props.oobData.name) {
                roomName = this.props.oobData.name;
            } else if (this.props.room) {
                roomName = this.props.room.name;
            }

            const emojiTextClasses = classNames('mx_RoomHeader_nametext', { mx_RoomHeader_settingsHint: settingsHint });
            name =

                    <EmojiText dir="auto" element="div" className={emojiTextClasses} title={roomName}>{ roomName }</EmojiText>
                    { searchStatus }

;
        }

        if (canSetRoomTopic) {
            const RoomTopicEditor = sdk.getComponent("rooms.RoomTopicEditor");
            topicElement = <RoomTopicEditor ref="topicEditor" room={this.props.room} />;
        } else {
            let topic;
            if (this.props.room) {
                const ev = this.props.room.currentState.getStateEvents('m.room.topic', '');
                if (ev) {
                    topic = ev.getContent().topic;
                }
            }
            if (topic) {
                topicElement =

{ topic }
;
            }
        }

        let roomAvatar = null;
        if (canSetRoomAvatar) {
            roomAvatar = (

                        <ChangeAvatar ref="changeAvatar" room={this.props.room} showUploadSection={false} width={48} height={48} />

                        <input id="avatarInput" type="file" onChange={this.onAvatarSelected} />

            );
        } else if (this.props.room || (this.props.oobData && this.props.oobData.name)) {
            roomAvatar = (
                <RoomAvatar room={this.props.room} width={48} height={48} oobData={this.props.oobData}
                    viewAvatarOnClick={true} />
            );
        }

        if (this.props.onSettingsClick) {
            settingsButton =
                <AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSettingsClick} title={_t("Settings")}>
                    <TintableSvg src="img/icons-settings-room.svg" width="16" height="16" />
                </AccessibleButton>;
        }

        if (this.props.onPinnedClick && SettingsStore.isFeatureEnabled('feature_pinning')) {
            let pinsIndicator = null;
            if (this._hasUnreadPins()) {
                pinsIndicator = (
);
            } else if (this._hasPins()) {
                pinsIndicator = (
);
            }

            pinnedEventsButton =
                <AccessibleButton className="mx_RoomHeader_button mx_RoomHeader_pinnedButton"
                                  onClick={this.props.onPinnedClick} title={_t("Pinned Messages")}>
                    { pinsIndicator }
                    <TintableSvg src="img/icons-pin.svg" width="16" height="16" />
                </AccessibleButton>;
        }

//        var leave_button;
//        if (this.props.onLeaveClick) {
//            leave_button =
//

//                    <TintableSvg src="img/leave.svg" width="26" height="20"/>
//
;
//        }

        let forgetButton;
        if (this.props.onForgetClick) {
            forgetButton =
                <AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onForgetClick} title={_t("Forget room")}>
                    <TintableSvg src="img/leave.svg" width="26" height="20" />
                </AccessibleButton>;
        }

        let searchButton;
        if (this.props.onSearchClick && this.props.inRoom) {
            searchButton =
                <AccessibleButton className="mx_RoomHeader_button" onClick={this.props.onSearchClick} title={_t("Search")}>
                    <TintableSvg src="img/icons-search.svg" width="35" height="35" />
                </AccessibleButton>;
        }

        let shareRoomButton;
        if (this.props.inRoom) {
            shareRoomButton =
                <AccessibleButton className="mx_RoomHeader_button" onClick={this.onShareRoomClick} title={_t('Share room')}>
                    <TintableSvg src="img/icons-share.svg" width="16" height="16" />
                </AccessibleButton>;
        }

        let rightPanelButtons;
        if (this.props.collapsedRhs) {
            rightPanelButtons =
                <AccessibleButton className="mx_RoomHeader_button" onClick={this.onShowRhsClick} title={_t('Show panel')}>
                    <TintableSvg src="img/maximise.svg" width="10" height="16" />
                </AccessibleButton>;
        }

        let rightRow;
        let manageIntegsButton;
        if (this.props.room && this.props.room.roomId && this.props.inRoom) {
            manageIntegsButton = <ManageIntegsButton
                room={this.props.room}
            />;
        }

        if (!this.props.editing) {
            rightRow =

                    { settingsButton }
                    { pinnedEventsButton }
                    { shareRoomButton }
                    { manageIntegsButton }
                    { forgetButton }
                    { searchButton }
                    { rightPanelButtons }

;
        }

        return (

                            { roomAvatar }

                            { name }
                            { topicElement }

                    { spinner }
                    { saveButton }
                    { cancelButton }
                    { rightRow }

        );
    },
});


text:
package io.netty.handler.codec.compression;

import io.netty.channel.embedded.EmbeddedChannel;

import static com.ning.compress.lzf.LZFChunk.MAX_CHUNK_LEN;

public class LengthAwareLzfIntegrationTest extends LzfIntegrationTest {

    @Override
    protected EmbeddedChannel createEncoder() {
        return new EmbeddedChannel(new LzfEncoder(false, MAX_CHUNK_LEN, 2 * 1024 * 1024));
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yeyu.dearinformaton.fragment.videoFragment.CommonfindFragment">

    <ListView
        android:id="@+id/find_listview"
        android:scrollbars="none"
        android:divider="@null"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>


text:
package org.optaplanner.core.impl.score.stream.drools.common;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public abstract class DroolsAbstractUniCollectingGroupByCollectorProcessor<ResultContainer, InTuple, KeyTuple, OutTuple>
        extends DroolsAbstractGroupByCollectorProcessor<InTuple, KeyTuple, OutTuple> {

    private final Map<KeyTuple, ResultContainer> containersMap = new HashMap<>(0);
    // LinkedHashMap to maintain a consistent iteration order of resulting pairs.
    private final Map<KeyTuple, OutTuple> resultMap = new LinkedHashMap<>(0);

    @Override
    public Runnable accumulate(InTuple input) {
        KeyTuple key = toKey(input);
        ResultContainer container = containersMap.computeIfAbsent(key, __ -> newContainer());
        Runnable undo = process(input, container);
        addTuple(key);
        return () -> {
            undo.run();
            long currentCount = removeTuple(key);
            if (currentCount == 0L) {
                containersMap.remove(key);
                resultMap.remove(key);
            }
        };
    }

    @Override
    public Collection<OutTuple> finish() {
        Set<KeyTuple> dirtyTupleSet = clearDirtyTupleSet();
        if (!dirtyTupleSet.isEmpty()) {
            for (KeyTuple tuple : dirtyTupleSet) {
                resultMap.put(tuple, toResult(tuple, containersMap.get(tuple)));
            }
        }
        return resultMap.values();
    }

    protected abstract KeyTuple toKey(InTuple tuple);

    protected abstract ResultContainer newContainer();

    protected abstract Runnable process(InTuple tuple, ResultContainer container);

    protected abstract OutTuple toResult(KeyTuple key, ResultContainer container);

}