Input:
	public void execute() throws Throwable
	{
		OlioPerson loggedPerson = this.getUtility().getPerson(this.getSessionState().getLoggedPersonId());
		if (!this.getUtility().isRegisteredPerson(loggedPerson))
		{
			this.getLogger().severe("Login required for adding an event");
			this.setFailed(true);
			return;
		}
		StringBuilder response = null;
		response = this.getHttpTransport().fetchUrl(this.getGenerator().getAddEventURL());
		this.trace(this.getGenerator().getAddEventURL());
		if (!this.getGenerator().checkHttpResponse(response.toString()))
		{
			this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
			throw new IOException("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
		}
		this.loadStatics(this.getGenerator().getAddEventStatics());
		this.trace(this.getGenerator().getAddEventStatics());
		String token = null;
		switch (this.getConfiguration().getIncarnation())
		{
			case OlioConfiguration.JAVA_INCARNATION:
				break;
			case OlioConfiguration.PHP_INCARNATION:
				break;
			case OlioConfiguration.RAILS_INCARNATION:
				token = this.parseAuthToken(response.toString());
				if ( token == null )
				{
					throw new Exception( "Authentication token could not be parsed" );
				}
				break;
		}
		OlioSocialEvent event = this.getUtility().newSocialEvent();
		event.submitterUserName = loggedPerson.userName;
		HttpPost reqPost = new HttpPost(this.getGenerator().getAddEventResultURL());
		MultipartEntity entity = new MultipartEntity();
		this.populateEntity(entity, event);
		switch (this.getConfiguration().getIncarnation())
		{
			case OlioConfiguration.JAVA_INCARNATION:
				break;
			case OlioConfiguration.PHP_INCARNATION:
				break;
			case OlioConfiguration.RAILS_INCARNATION:
				entity.addPart("authenticity_token", new StringBody(token));
				break;
		}
		reqPost.setEntity(entity);
		response = this.getHttpTransport().fetch(reqPost);
		this.trace(this.getGenerator().getAddEventResultURL());
		if (!this.getGenerator().checkHttpResponse(response.toString()))
		{
			this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
			throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
		}
		int index = response.toString().toLowerCase().indexOf("success");
		if (index == -1)
		{
			this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response);
			throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body");
		}
		this.getSessionState().setLastResponse(response.toString());
		this.setFailed(false);
	}

Output:
	public void execute() throws Throwable
	{
		OlioPerson loggedPerson = this.getUtility().getPerson(this.getSessionState().getLoggedPersonId());
		if (!this.getUtility().isRegisteredPerson(loggedPerson))
		{
			this.getLogger().severe("Login required for adding an event");
			this.setFailed(true);
			return;
		}
		StringBuilder response = null;
		response = this.getHttpTransport().fetchUrl(this.getGenerator().getAddEventURL());
		this.trace(this.getGenerator().getAddEventURL());
		if (!this.getGenerator().checkHttpResponse(response.toString()))
		{
			this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
			throw new IOException("Problems in performing request to URL: " + this.getGenerator().getAddEventURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
		}
		this.loadStatics(this.getGenerator().getAddEventStatics());
		this.trace(this.getGenerator().getAddEventStatics());
		String token = null;
		switch (this.getConfiguration().getIncarnation())
		{
			case OlioConfiguration.JAVA_INCARNATION:
				break;
			case OlioConfiguration.PHP_INCARNATION:
				break;
			case OlioConfiguration.RAILS_INCARNATION:
				token = this.parseAuthToken(response.toString());
				if ( token == null )
				{
					throw new Exception( "Authentication token could not be parsed" );
				}
				break;
		}
		OlioSocialEvent event = this.getUtility().newSocialEvent();
		event.submitterUserName = loggedPerson.userName;
		HttpPost reqPost = new HttpPost(this.getGenerator().getAddEventResultURL());
		MultipartEntity entity = new MultipartEntity();
		this.populateEntity(entity, event);
		switch (this.getConfiguration().getIncarnation())
		{
			case OlioConfiguration.JAVA_INCARNATION:
				break;
			case OlioConfiguration.PHP_INCARNATION:
				break;
			case OlioConfiguration.RAILS_INCARNATION:
				entity.addPart("authenticity_token", new StringBody(token));
				break;
		}
		reqPost.setEntity(entity);
		response = this.getHttpTransport().fetch(reqPost);
		this.trace(this.getGenerator().getAddEventResultURL());
		if (!this.getGenerator().checkHttpResponse(response.toString()))
		{
			this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
			throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
		}
		switch (this.getConfiguration().getIncarnation())
		{
			case OlioConfiguration.JAVA_INCARNATION:
				break;
			case OlioConfiguration.PHP_INCARNATION:
				break;
			case OlioConfiguration.RAILS_INCARNATION:
				int index = response.toString().toLowerCase().indexOf("event was successfully created.");
				if (index == -1)
				{
					this.getLogger().severe("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body. Server response: " + response);
					throw new IOException("Problems in performing request to URL: " + reqPost.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "): Could not find success message in result body");
				}
				break;
		}
		this.getSessionState().setLastResponse(response.toString());
		this.setFailed(false);
	}


Input:
	public void addPrimitiveDerivedSetOrGet(Type.Kind derivedTypeKind,
	                                        String derived,
	                                        String index,
	                                        Kind primitiveType,
	                                        String primitive,
	                                        boolean set) throws BackendException {
		List<String> indices = new LinkedList<String>();
		while(references.containsKey(derived)) {
			Map.Entry<String,List<String>> reference = references.get(derived);
			indices.addAll(reference.getValue());
			derived = reference.getKey();
		}
		switch(derivedTypeKind) {
			case ARRAY:
				indices.add(index);
				break;
			case STRUCT:
				DerivedType type = derivedTypes.get(derived);
				if(type instanceof LLVMBackendArrayType) {
					type = (DerivedType) ((LLVMBackendArrayType) type).getStorageType();
				}
				if(type instanceof LLVMBackendStructType) {
					List<Member> members = ((LLVMBackendStructType) type).getMembers();
					for(Member m: members) {
						if(m.getName().equals(index)) {
							indices.add(String.valueOf(members.indexOf(m)));
							break;
						}
					}
				}
				else {
					throw new BackendException("Unexpected final derived type: " + type.getClass().getName());
				}
				break;
			default:
				throw new BackendException("Unexpected derived type: " + derivedTypeKind.toString());
		}
		StringBuffer indexList = new StringBuffer();
		for(String i: indices) {
			indexList.append(", ");
			indexList.append(Module.getIRType(Type.Kind.LONG));
			indexList.append(" ");
			indexList.append(cdl(i, Type.Kind.LONG));
		}
		String primitiveIRType = Module.getIRType(primitiveType);
		DerivedType derivedType = derivedTypes.get(derived);
		String derivedIRType = "";
		if(derivedType instanceof LLVMBackendArrayType) {
			LLVMBackendArrayType derivedArType = (LLVMBackendArrayType) derivedType;
			derivedIRType = Module.getIRAType(derivedArType.getStorageType(), derivedArType.getDimensions());
			for(int idx = 0;
			    idx < derivedArType.getDimensions().size();
				idx++)
			{
				String dim = ""+derivedArType.getDimensions().get(idx);
				String elem= cdl(indices.get(idx),Type.Kind.LONG);
				gen("call void @aoob1(i64 " + elem + ", i64 " + dim + ")");
			}
		}
		else if(derivedType instanceof LLVMBackendStructType) {
			LLVMBackendStructType derivedStType = (LLVMBackendStructType) derivedType;
			derivedIRType = Module.getIRSType(derivedStType.getMembers());
		}
		else {
			throw new BackendException("Unexpected derived type: " + derivedType.getClass().getName());
		}
		if(set) {
			String derivedUseIdentifier1 = getUseIdentifierForVariable(derived);
			String derivedUseIdentifier2 = getUseIdentifierForVariable(derived);
			String derivedIdentifier = "%" + derived;
			primitive = cdl(primitive, primitiveType);
			gen(derivedUseIdentifier1 + " = getelementptr " + derivedIRType + "* " + derivedIdentifier + ", i64 0"
				+ indexList);
			gen("store " + primitiveIRType + " " + primitive + ", " + primitiveIRType + "* " + derivedUseIdentifier1);
		}
		else {
			String primitiveUseIdentifier = getUseIdentifierForVariable(primitive);
			String primitiveIdentifier = "%" + primitive;
			String derivedUseIdentifier = getUseIdentifierForVariable(derived);
			String derivedIdentifier = "%" + derived;
			gen(derivedUseIdentifier + " = getelementptr " + derivedIRType + "* " + derivedIdentifier + ", i64 0"
				+ indexList);
			gen(primitiveUseIdentifier + " = load " + primitiveIRType + "* " + derivedUseIdentifier);
			gen("store " + primitiveIRType + " " + primitiveUseIdentifier + ", " + primitiveIRType + "* " + primitiveIdentifier);
		}
	}

Output:
	public void addPrimitiveDerivedSetOrGet(Type.Kind derivedTypeKind,
	                                        String derived,
	                                        String index,
	                                        Kind primitiveType,
	                                        String primitive,
	                                        boolean set) throws BackendException {
		List<String> indices = new LinkedList<String>();
		while(references.containsKey(derived)) {
			Map.Entry<String,List<String>> reference = references.get(derived);
			indices.addAll(reference.getValue());
			derived = reference.getKey();
		}
		switch(derivedTypeKind) {
			case ARRAY:
				indices.add(index);
				break;
			case STRUCT:
				DerivedType type = derivedTypes.get(derived);
				if(type instanceof LLVMBackendArrayType) {
					type = (DerivedType) ((LLVMBackendArrayType) type).getStorageType();
				}
				if(type instanceof LLVMBackendStructType) {
					List<Member> members = ((LLVMBackendStructType) type).getMembers();
					for(Member m: members) {
						if(m.getName().equals(index)) {
							indices.add("#" + String.valueOf(members.indexOf(m)));
							break;
						}
					}
				}
				else {
					throw new BackendException("Unexpected final derived type: " + type.getClass().getName());
				}
				break;
			default:
				throw new BackendException("Unexpected derived type: " + derivedTypeKind.toString());
		}
		StringBuffer indexList = new StringBuffer();
		for(String i: indices) {
			indexList.append(", ");
			indexList.append(Module.getIRType(Type.Kind.LONG));
			indexList.append(" ");
			indexList.append(cdl(i, Type.Kind.LONG));
		}
		String primitiveIRType = Module.getIRType(primitiveType);
		DerivedType derivedType = derivedTypes.get(derived);
		String derivedIRType = "";
		if(derivedType instanceof LLVMBackendArrayType) {
			LLVMBackendArrayType derivedArType = (LLVMBackendArrayType) derivedType;
			derivedIRType = Module.getIRAType(derivedArType.getStorageType(), derivedArType.getDimensions());
			for(int idx = 0;
			    idx < derivedArType.getDimensions().size();
				idx++)
			{
				String dim = ""+derivedArType.getDimensions().get(idx);
				String elem= cdl(indices.get(idx),Type.Kind.LONG);
				gen("call void @aoob1(i64 " + elem + ", i64 " + dim + ")");
			}
		}
		else if(derivedType instanceof LLVMBackendStructType) {
			LLVMBackendStructType derivedStType = (LLVMBackendStructType) derivedType;
			derivedIRType = Module.getIRSType(derivedStType.getMembers());
		}
		else {
			throw new BackendException("Unexpected derived type: " + derivedType.getClass().getName());
		}
		if(set) {
			String derivedUseIdentifier1 = getUseIdentifierForVariable(derived);
			String derivedUseIdentifier2 = getUseIdentifierForVariable(derived);
			String derivedIdentifier = "%" + derived;
			primitive = cdl(primitive, primitiveType);
			gen(derivedUseIdentifier1 + " = getelementptr " + derivedIRType + "* " + derivedIdentifier + ", i64 0"
				+ indexList);
			gen("store " + primitiveIRType + " " + primitive + ", " + primitiveIRType + "* " + derivedUseIdentifier1);
		}
		else {
			String primitiveUseIdentifier = getUseIdentifierForVariable(primitive);
			String primitiveIdentifier = "%" + primitive;
			String derivedUseIdentifier = getUseIdentifierForVariable(derived);
			String derivedIdentifier = "%" + derived;
			gen(derivedUseIdentifier + " = getelementptr " + derivedIRType + "* " + derivedIdentifier + ", i64 0"
				+ indexList);
			gen(primitiveUseIdentifier + " = load " + primitiveIRType + "* " + derivedUseIdentifier);
			gen("store " + primitiveIRType + " " + primitiveUseIdentifier + ", " + primitiveIRType + "* " + primitiveIdentifier);
		}
	}


Input:
    private static void proceedExternalStoragePath() {
        String mExternalStoragePathName = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (Build.VERSION.SDK_INT >= 18) {
                if (mExternalStoragePathName.endsWith("/emulated/0")
                        || mExternalStoragePathName.endsWith("/emulated/0/")) {
                    mExternalStoragePathName = mExternalStoragePathName.replace("/emulated/0",
                            "/emulated/legacy");
                }
            }
            sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                    ? mExternalStoragePathName : mExternalStoragePathName + "/";
            sV4aRoot = sExternalStoragePath + "ViPER4Android/";
            sV4aKernelPath = sV4aRoot + "Kernel/";
            sV4aProfilePath = sV4aRoot + "Profile/";
        } else {
            boolean isPathFromSdkWorking = false;
            boolean isPathFromLegacyWorking = false;
            String externalPath;
            externalPath = mExternalStoragePathName.endsWith("/") ? mExternalStoragePathName
                    : mExternalStoragePathName + "/";
            externalPath = externalPath + "v4a_test_file";
            Log.i("ViPER4Android", "Now checking for external storage writable, file = "
                    + externalPath);
            if (checkWritable(externalPath)) {
                isPathFromSdkWorking = true;
            }
            externalPath = mExternalStoragePathName.endsWith("/") ? mExternalStoragePathName
                    : mExternalStoragePathName + "/";
            if (externalPath.endsWith("/emulated/0/")) {
                externalPath = externalPath.replace("/emulated/0/", "/emulated/legacy/");
                externalPath = externalPath + "v4a_test_file";
                Log.i("ViPER4Android", "Now checking for external storage writable, file = " + externalPath);
                if (checkWritable(externalPath)) {
                    isPathFromLegacyWorking = true;
                }
            }
            if (isPathFromLegacyWorking) {
                mExternalStoragePathName = mExternalStoragePathName.replace("/emulated/0",
                        "/emulated/legacy");
                sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                        ? mExternalStoragePathName : mExternalStoragePathName + "/";
                sV4aRoot = sExternalStoragePath + "ViPER4Android/";
                sV4aKernelPath = sV4aRoot + "Kernel/";
                sV4aProfilePath = sEnvironmentInitialized + "Profile/";
                Log.i("ViPER4Android", "External storage path = " + sExternalStoragePath);
                Log.i("ViPER4Android", "ViPER4Android root path = " + sV4aRoot);
                Log.i("ViPER4Android", "ViPER4Android kernel path = " + sV4aKernelPath);
                Log.i("ViPER4Android", "ViPER4Android profile path = " + sV4aProfilePath);
                return;
            }
            if (isPathFromSdkWorking) {
                sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                        ? mExternalStoragePathName : mExternalStoragePathName + "/";
                sV4aRoot = sExternalStoragePath + "ViPER4Android/";
                sV4aKernelPath = sV4aRoot + "Kernel/";
                sV4aProfilePath = sV4aRoot + "Profile/";
                Log.i("ViPER4Android", "External storage path = " + sExternalStoragePath);
                Log.i("ViPER4Android", "ViPER4Android root path = " + sV4aRoot);
                Log.i("ViPER4Android", "ViPER4Android kernel path = " + sV4aKernelPath);
                Log.i("ViPER4Android", "ViPER4Android profile path = " + sV4aProfilePath);
                return;
            }
            Log.i("ViPER4Android", "Really terrible thing, external storage detection failed. V4A may malfunction");
            sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                    ? mExternalStoragePathName : mExternalStoragePathName + "/";
            sV4aRoot = sExternalStoragePath + "ViPER4Android/";
            sV4aKernelPath = sV4aRoot + "Kernel/";
            sV4aProfilePath = sV4aRoot + "Profile/";
        }
    }

Output:
    private static void proceedExternalStoragePath() {
        String mExternalStoragePathName = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (Build.VERSION.SDK_INT >= 18) {
                if (mExternalStoragePathName.endsWith("/emulated/0")
                        || mExternalStoragePathName.endsWith("/emulated/0/")) {
                    mExternalStoragePathName = mExternalStoragePathName.replace("/emulated/0",
                            "/emulated/legacy");
                }
            }
            sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                    ? mExternalStoragePathName : mExternalStoragePathName + "/";
            sV4aRoot = sExternalStoragePath + "ViPER4Android/";
            sV4aKernelPath = sV4aRoot + "Kernel/";
            sV4aProfilePath = sV4aRoot + "Profile/";
        } else {
            boolean isPathFromSdkWorking = false;
            boolean isPathFromLegacyWorking = false;
            String externalPath;
            externalPath = mExternalStoragePathName.endsWith("/") ? mExternalStoragePathName
                    : mExternalStoragePathName + "/";
            externalPath = externalPath + "v4a_test_file";
            Log.i("ViPER4Android", "Now checking for external storage writable, file = "
                    + externalPath);
            if (checkWritable(externalPath)) {
                isPathFromSdkWorking = true;
            }
            externalPath = mExternalStoragePathName.endsWith("/") ? mExternalStoragePathName
                    : mExternalStoragePathName + "/";
            if (externalPath.endsWith("/emulated/0/")) {
                externalPath = externalPath.replace("/emulated/0/", "/emulated/legacy/");
                externalPath = externalPath + "v4a_test_file";
                Log.i("ViPER4Android", "Now checking for external storage writable, file = " + externalPath);
                if (checkWritable(externalPath)) {
                    isPathFromLegacyWorking = true;
                }
            }
            if (isPathFromLegacyWorking) {
                mExternalStoragePathName = mExternalStoragePathName.replace("/emulated/0",
                        "/emulated/legacy");
                sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                        ? mExternalStoragePathName : mExternalStoragePathName + "/";
                sV4aRoot = sExternalStoragePath + "ViPER4Android/";
                sV4aKernelPath = sV4aRoot + "Kernel/";
                sV4aProfilePath = sV4aRoot + "Profile/";
                Log.i("ViPER4Android", "External storage path = " + sExternalStoragePath);
                Log.i("ViPER4Android", "ViPER4Android root path = " + sV4aRoot);
                Log.i("ViPER4Android", "ViPER4Android kernel path = " + sV4aKernelPath);
                Log.i("ViPER4Android", "ViPER4Android profile path = " + sV4aProfilePath);
                return;
            }
            if (isPathFromSdkWorking) {
                sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                        ? mExternalStoragePathName : mExternalStoragePathName + "/";
                sV4aRoot = sExternalStoragePath + "ViPER4Android/";
                sV4aKernelPath = sV4aRoot + "Kernel/";
                sV4aProfilePath = sV4aRoot + "Profile/";
                Log.i("ViPER4Android", "External storage path = " + sExternalStoragePath);
                Log.i("ViPER4Android", "ViPER4Android root path = " + sV4aRoot);
                Log.i("ViPER4Android", "ViPER4Android kernel path = " + sV4aKernelPath);
                Log.i("ViPER4Android", "ViPER4Android profile path = " + sV4aProfilePath);
                return;
            }
            Log.i("ViPER4Android", "Really terrible thing, external storage detection failed. V4A may malfunction");
            sExternalStoragePath = mExternalStoragePathName.endsWith("/")
                    ? mExternalStoragePathName : mExternalStoragePathName + "/";
            sV4aRoot = sExternalStoragePath + "ViPER4Android/";
            sV4aKernelPath = sV4aRoot + "Kernel/";
            sV4aProfilePath = sV4aRoot + "Profile/";
        }
    }


Input:
	public boolean canRun(Transmittable trns) {
		if (!trns.isPrivmsg())
			return false;
		String msg = trns.asPrivmsg().getMessage();
		Matcher matcher = COMMAND_PATTERN.matcher(msg);
		if (matcher.matches()) {
			int count = matcher.groupCount();
			String command = matcher.group(3);
			if (matcher.group(4) == null || matcher.group(4).isEmpty()) {
				return matcher.group(2).matches(getName());
			} else {
                System.out.println(command);
                System.out.println(matcher.group(4));
				return command.matches(getName()) && matcher.group(4).matches(getParameterRegex());
			}
		}
		return false;
	}

Output:
	public boolean canRun(Transmittable trns) {
		if (!trns.isPrivmsg())
			return false;
		String msg = trns.asPrivmsg().getMessage();
		Matcher matcher = COMMAND_PATTERN.matcher(msg);
		if (matcher.matches()) {
			int count = matcher.groupCount();
			if (matcher.group(4) == null || matcher.group(4).isEmpty()) {
				return matcher.group(2).matches(getName());
			} else {
                return matcher.group(4).matches(getName()) && matcher.group(5).matches(getParameterRegex());
			}
		}
		return false;
	}


Input:
	public IRegion getDamageRegion(ITypedRegion partition, final DocumentEvent e, boolean documentPartitioningChanged) {
		if (documentPartitioningChanged)
			return partition;
		IRegion result = getDocument().readOnly(new UnitOfWork<IRegion>(){
			private final int offset = e.getOffset();
			private final int endOffset = offset + e.getLength();
			public IRegion exec(XtextResource resource) throws Exception {
				AbstractNode node = resource.getParseResult().getRootNode();
				AbstractNode start = null;
				AbstractNode end = null;
				while(node != null && start == null) {
					if (node instanceof CompositeNode) {
						for(AbstractNode child: ((CompositeNode) node).getChildren()) {
							if (child.getTotalOffset() <= offset && child.getTotalOffset() + child.getTotalLength() >= offset) {
								node = child;
								if (node instanceof LeafNode || node.getTotalOffset() == offset)
									start = node;
								break;
							}
						}
					} else {
						throw new IllegalStateException("node is not in expected range but is not a composite.");
					}
				}
				node = start;
				while(node != null && end == null) {
					if (node.getTotalLength() + node.getTotalOffset() >= endOffset) {
						while(end == null) {
							if (node instanceof CompositeNode) {
								for(int i = ((CompositeNode) node).getChildren().size() - 1; i >= 0; i--) {
									AbstractNode child = ((CompositeNode) node).getChildren().get(i);
									if (child.getTotalOffset() + child.getTotalLength() >= endOffset && child.getTotalOffset() <= endOffset) {
										node = child;
										if (node instanceof LeafNode || node.getTotalOffset() + node.getTotalLength() == endOffset)
											end = node;
										break;
									}
								}
							} else {
								end = node;
							}
						}
					} else {
						node = node.getParent();
					}
				}
				int startOffset = start != null ? start.getTotalOffset() : offset;
				int endOffset = end != null ? end.getTotalOffset() + end.getTotalLength() : this.endOffset;
				Range range = new Range(startOffset, endOffset);
				range.mergeAllErrors(resource.getParseResult().getRootNode());
				return new Region(range.getFromOffset(), range.getToOffset() - range.getFromOffset() + e.getText().length() - e.getLength());
			}
		});
		return result;
	}

Output:
	public IRegion getDamageRegion(ITypedRegion partition, final DocumentEvent e, boolean documentPartitioningChanged) {
		if (documentPartitioningChanged)
			return partition;
		IRegion result = getDocument().readOnly(new UnitOfWork<IRegion>(){
			private final int offset = e.getOffset();
			private final int endOffset = offset + e.getLength();
			public IRegion exec(XtextResource resource) throws Exception {
				AbstractNode node = resource.getParseResult().getRootNode();
				AbstractNode start = null;
				AbstractNode end = null;
				while(node != null && start == null) {
					if (node instanceof CompositeNode) {
						if (((CompositeNode) node).getChildren().isEmpty())
							break;
						for(AbstractNode child: ((CompositeNode) node).getChildren()) {
							if (child.getTotalOffset() <= offset && child.getTotalOffset() + child.getTotalLength() >= offset) {
								node = child;
								if (node instanceof LeafNode || node.getTotalOffset() == offset)
									start = node;
								break;
							}
						}
					} else {
						throw new IllegalStateException("node is not in expected range but is not a composite.");
					}
				}
				node = start;
				while(node != null && end == null) {
					if (node.getTotalLength() + node.getTotalOffset() >= endOffset) {
						while(end == null) {
							if (node instanceof CompositeNode) {
								for(int i = ((CompositeNode) node).getChildren().size() - 1; i >= 0; i--) {
									AbstractNode child = ((CompositeNode) node).getChildren().get(i);
									if (child.getTotalOffset() + child.getTotalLength() >= endOffset && child.getTotalOffset() <= endOffset) {
										node = child;
										if (node instanceof LeafNode || node.getTotalOffset() + node.getTotalLength() == endOffset)
											end = node;
										break;
									}
								}
							} else {
								end = node;
							}
						}
					} else {
						node = node.getParent();
					}
				}
				int startOffset = start != null ? start.getTotalOffset() : offset;
				int endOffset = end != null ? end.getTotalOffset() + end.getTotalLength() : this.endOffset;
				Range range = new Range(startOffset, endOffset);
				range.mergeAllErrors(resource.getParseResult().getRootNode());
				return new Region(range.getFromOffset(), range.getToOffset() - range.getFromOffset() + e.getText().length() - e.getLength());
			}
		});
		return result;
	}


Input:
    public void runTest(String test, boolean registerInfo) throws IOException, URISyntaxException {
        String dexFilePath = String.format("%s%sclasses.dex", test, File.separatorChar);
        DexFile dexFile = DexFileFactory.loadDexFile(findResource(dexFilePath), 15);
        baksmaliOptions options = new baksmaliOptions();
        if (registerInfo) {
            options.registerInfo = baksmaliOptions.ALL | baksmaliOptions.FULLMERGE;
            options.classPath = new ClassPath();
        }
        for (ClassDef classDef: dexFile.getClasses()) {
            StringWriter stringWriter = new StringWriter();
            IndentingWriter writer = new IndentingWriter(stringWriter);
            ClassDefinition classDefinition = new ClassDefinition(options, classDef);
            classDefinition.writeTo(writer);
            writer.close();
            String className = classDef.getType();
            String smaliPath = String.format("%s%s%s.smali", test, File.separatorChar,
                    className.substring(1, className.length() - 1));
            String smaliContents = readResource(smaliPath);
            Assert.assertEquals(smaliContents.replace("\r\n", "\n"), stringWriter.toString().replace("\r\n", "\n"));
        }
    }

Output:
    public void runTest(String test, boolean registerInfo) throws IOException, URISyntaxException {
        String dexFilePath = String.format("%s%sclasses.dex", test, File.separatorChar);
        DexFile dexFile = DexFileFactory.loadDexFile(findResource(dexFilePath), 15);
        baksmaliOptions options = new baksmaliOptions();
        if (registerInfo) {
            options.registerInfo = baksmaliOptions.ALL | baksmaliOptions.FULLMERGE;
            options.classPath = new ClassPath();
        }
        for (ClassDef classDef: dexFile.getClasses()) {
            StringWriter stringWriter = new StringWriter();
            IndentingWriter writer = new IndentingWriter(stringWriter);
            ClassDefinition classDefinition = new ClassDefinition(options, classDef);
            classDefinition.writeTo(writer);
            writer.close();
            String className = classDef.getType();
            String smaliPath = String.format("%s%s%s.smali", test, File.separatorChar,
                    className.substring(1, className.length() - 1));
            String smaliContents = readResource(smaliPath);
            Assert.assertEquals(smaliContents.replace("\r", "").replace("\n", System.lineSeparator()),
                    stringWriter.toString().replace("\r", "").replace("\n", System.lineSeparator()));
        }
    }


Input:
	public void onEnable() {
		try {
			System.out.println(GlobalConf.logPrefix+"Initalizing...");
			server = getServer();
			PluginManager pm = server.getPluginManager();
			System.out.println(GlobalConf.logPrefix+"Loading config and ban handler...");
			long oldtime = System.currentTimeMillis();
			GlobalConf.conf = getConfig();
			GlobalConf.loadConfig();
			HashMap<String, String> data = new HashMap<String, String>(15);
			data.put("username", GlobalConf.Sql.user);
			data.put("password", GlobalConf.Sql.pass);
			data.put("host", GlobalConf.Sql.host);
			data.put("port", GlobalConf.Sql.port);
			data.put("prefix", GlobalConf.Sql.prefix);
			data.put("db", GlobalConf.Sql.db);
			try {
				Class<?> rawClass = Class.forName(GlobalConf.Advanced.pkg+"."+GlobalConf.banHandlerConf+GlobalConf.Advanced.suffix);
				if (rawClass.isAssignableFrom(BanHandler.class)) {
					Class<?>[] arguments = {Map.class};
					banHandler = (BanHandler) rawClass.getDeclaredMethod("onEnable", arguments).invoke(null, data);
				} else {
					LOG.severe(GlobalConf.logPrefix+"Wierd ban handler given in config file! Aborting operation.");
					onFatal();
				}
			} catch (ClassNotFoundException e) {
				LOG.severe(GlobalConf.logPrefix+"Non-existant ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (SecurityException e) {
				LOG.severe(GlobalConf.logPrefix+"Somehow, a SecurityException occurred. Plugin conflict? Aborting operation.");
				onFatal();
			} catch (NoSuchMethodException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (IllegalArgumentException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (IllegalAccessException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (InvocationTargetException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (NullPointerException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (ClassCastException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			}
			long newtime = System.currentTimeMillis();
			System.out.println(GlobalConf.logPrefix+"Done. Took "+(newtime-oldtime)+" ms.");
			System.out.println(GlobalConf.logPrefix+"Registering events...");
			oldtime = System.currentTimeMillis();
			pm.registerEvents(new EventListener(), this);
			newtime = System.currentTimeMillis();
			System.out.println(GlobalConf.logPrefix+"Done. Took "+(newtime-oldtime)+" ms.");
		}
		catch (RuntimeException e) {
			setEnabled(false);
		}
	}

Output:
	public void onEnable() {
		try {
			System.out.println(GlobalConf.logPrefix+"Initalizing...");
			server = getServer();
			PluginManager pm = server.getPluginManager();
			System.out.println(GlobalConf.logPrefix+"Loading config and ban handler...");
			long oldtime = System.currentTimeMillis();
			GlobalConf.conf = getConfig();
			GlobalConf.loadConfig();
			HashMap<String, String> data = new HashMap<String, String>(15);
			data.put("username", GlobalConf.Sql.user);
			data.put("password", GlobalConf.Sql.pass);
			data.put("host", GlobalConf.Sql.host);
			data.put("port", GlobalConf.Sql.port);
			data.put("prefix", GlobalConf.Sql.prefix);
			data.put("db", GlobalConf.Sql.db);
			data.put("yaml", GlobalConf.Yaml.file);
			data.put("json", GlobalConf.Json.file);
			data.put("apiKey", GlobalConf.MCBans.apiKey);
			try {
				Class<?> rawClass = Class.forName(GlobalConf.Advanced.pkg+"."+GlobalConf.banHandlerConf+GlobalConf.Advanced.suffix);
				if (rawClass.isAssignableFrom(BanHandler.class)) {
					Class<?>[] arguments = {Map.class};
					banHandler = (BanHandler) rawClass.getDeclaredMethod("onEnable", arguments).invoke(null, data);
				} else {
					LOG.severe(GlobalConf.logPrefix+"Wierd ban handler given in config file! Aborting operation.");
					onFatal();
				}
			} catch (ClassNotFoundException e) {
				LOG.severe(GlobalConf.logPrefix+"Non-existant ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (SecurityException e) {
				LOG.severe(GlobalConf.logPrefix+"Somehow, a SecurityException occurred. Plugin conflict? Aborting operation.");
				onFatal();
			} catch (NoSuchMethodException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (IllegalArgumentException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (IllegalAccessException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (InvocationTargetException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (NullPointerException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			} catch (ClassCastException e) {
				LOG.severe(GlobalConf.logPrefix+"Bad ban handler given in config file! Aborting operation.");
				onFatal();
			}
			long newtime = System.currentTimeMillis();
			System.out.println(GlobalConf.logPrefix+"Done. Took "+(newtime-oldtime)+" ms.");
			System.out.println(GlobalConf.logPrefix+"Registering events...");
			oldtime = System.currentTimeMillis();
			pm.registerEvents(new EventListener(), this);
			newtime = System.currentTimeMillis();
			System.out.println(GlobalConf.logPrefix+"Done. Took "+(newtime-oldtime)+" ms.");
		}
		catch (RuntimeException e) {
			setEnabled(false);
		}
	}


Input:
    public static GLConfig fromgl(GL gl, GLContext ctx, GLCapabilitiesImmutable caps) {
	GLConfig c = new GLConfig();
	try {
	    c.glmajver = glgeti(gl, GL2.GL_MAJOR_VERSION);
	    c.glminver = glgeti(gl, GL2.GL_MINOR_VERSION);
	} catch(GLException e) {
	    c.glmajver = 1;
	    c.glminver = 0;
	}
	c.maxlights = glgeti(gl, GL2.GL_MAX_LIGHTS);
	c.exts = Arrays.asList(gl.glGetString(GL.GL_EXTENSIONS).split(" "));
	c.caps = caps;
	c.pref = GLSettings.defconf(c);
	String slv = glconds(gl, GL2.GL_SHADING_LANGUAGE_VERSION);
	if(slv != null) {
	    Matcher m = slvp.matcher(slv);
	    if(m.find()) {
		try {
		    int major = Integer.parseInt(m.group(1));
		    int minor = Integer.parseInt(m.group(2));
		    if((major > 0) || (major < 256) || (minor >= 0) || (minor < 256))
			c.glslver = (major << 8) | minor;
		} catch(NumberFormatException e) {
		}
	    }
	}
	return(c);
    }

Output:
    public static GLConfig fromgl(GL gl, GLContext ctx, GLCapabilitiesImmutable caps) {
	GLConfig c = new GLConfig();
	try {
	    c.glmajver = glgeti(gl, GL2.GL_MAJOR_VERSION);
	    c.glminver = glgeti(gl, GL2.GL_MINOR_VERSION);
	} catch(GOut.GLException e) {
	    c.glmajver = 1;
	    c.glminver = 0;
	}
	c.maxlights = glgeti(gl, GL2.GL_MAX_LIGHTS);
	c.exts = Arrays.asList(gl.glGetString(GL.GL_EXTENSIONS).split(" "));
	c.caps = caps;
	c.pref = GLSettings.defconf(c);
	String slv = glconds(gl, GL2.GL_SHADING_LANGUAGE_VERSION);
	if(slv != null) {
	    Matcher m = slvp.matcher(slv);
	    if(m.find()) {
		try {
		    int major = Integer.parseInt(m.group(1));
		    int minor = Integer.parseInt(m.group(2));
		    if((major > 0) || (major < 256) || (minor >= 0) || (minor < 256))
			c.glslver = (major << 8) | minor;
		} catch(NumberFormatException e) {
		}
	    }
	}
	return(c);
    }


Input:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String action = request.getParameter("Action");
    	String name = request.getParameter("User");
    	String pass = request.getParameter("Pass");
    	System.out.println(action);
    	ServletContext sc = request.getServletContext();
		AccountManager am = (AccountManager) sc.getAttribute("accounts");
    	if (action.equals("Create")) {
    		Account acct = am.createAccount(name, pass);
    		if (acct == null) {
    			request.getRequestDispatcher("/NameTaken.jsp").forward(request, response);
    		} else {
    			sc.setAttribute("user", name);
    			Account curracct = (Account) request.getSession().getAttribute("account");
    			curracct = acct;
    			request.getRequestDispatcher("/UserHome.jsp").forward(request, response);
    		}
    	} else if (action.equals("Delete")) {
    		am.deleteAccount(name);
    		request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
    	}  else if (action.equals("Logout")) {
    		am.logoutAccount((Account) request.getSession().getAttribute("account"));
    		request.getSession().setAttribute("account", null);
    		request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
    	}
    }

Output:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String action = request.getParameter("Action");
    	String name = request.getParameter("User");
    	String pass = request.getParameter("Pass");
    	System.out.println(action);
    	ServletContext sc = request.getServletContext();
		AccountManager am = (AccountManager) sc.getAttribute("accounts");
    	if (action.equals("Create")) {
    		Account acct = am.createAccount(name, pass);
    		if (acct == null) {
    			request.getSession().setAttribute("user", name);
    			request.getRequestDispatcher("/NameTaken.jsp").forward(request, response);
    		} else {
    			request.getSession().setAttribute("user", name);
    			request.getSession().setAttribute("account", acct);
    			request.getRequestDispatcher("/UserHome.jsp").forward(request, response);
    		}
    	} else if (action.equals("Delete")) {
    		am.deleteAccount(name);
    		request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
    	}  else if (action.equals("Logout")) {
    		am.logoutAccount((Account) request.getSession().getAttribute("account"));
    		request.getSession().setAttribute("account", null);
    		request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
    	}
    }


Input:
    public int vote(Authentication authentication,
                    Object object,
                    ConfigAttributeDefinition config) {
        if (! (authentication instanceof UsernamePasswordAuthenticationToken)) {
            return ACCESS_ABSTAIN;
        }
        CosmoUserDetails details =
            (CosmoUserDetails) authentication.getPrincipal();
        String username = details.getUser().getUsername();
        FilterInvocation fi = (FilterInvocation) object;
        String path = findResourcePath(fi);
        return path.startsWith(username) ? ACCESS_GRANTED : ACCESS_DENIED;
    }

Output:
    public int vote(Authentication authentication,
                    Object object,
                    ConfigAttributeDefinition config) {
        if (! (authentication instanceof UsernamePasswordAuthenticationToken)) {
            return ACCESS_ABSTAIN;
        }
        CosmoUserDetails details =
            (CosmoUserDetails) authentication.getPrincipal();
        String username = details.getUser().getUsername();
        FilterInvocation fi = (FilterInvocation) object;
        String path = findResourcePath(fi);
        if (path == null) {
            return ACCESS_DENIED;
        }
        return path.startsWith(username) ? ACCESS_GRANTED : ACCESS_DENIED;
    }


Input:
	public void setLookups() {
		diseaseType = new ArrayList();
		geneTypeColl = new ArrayList();
		diseaseType.add( new LabelValueBean( "Astrocytic", "astro" ) );
		diseaseType.add( new LabelValueBean( "Oligodendroglial", "oligo" ) );
		diseaseType.add( new LabelValueBean( "Ependymal cell", "Ependymal cell" ) );
		diseaseType.add( new LabelValueBean( "Mixed gliomas", "Mixed gliomas" ) );
		diseaseType.add( new LabelValueBean( "Neuroepithelial", "Neuroepithelial" ) );
		diseaseType.add( new LabelValueBean( "Choroid Plexus", "Choroid Plexus" ) );
		diseaseType.add( new LabelValueBean( "Neuronal and mixed neuronal-glial", "neuronal-glial" ) );
		diseaseType.add( new LabelValueBean( "Pineal Parenchyma", "Pineal Parenchyma" ));
		diseaseType.add( new LabelValueBean( "Embryonal", "Embryonal" ));
		diseaseType.add( new LabelValueBean( "Glioblastoma", "Glioblastoma" ));
		geneTypeColl.add( new LabelValueBean( "All Genes", "allgenes" ) );
		geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" ) );
		geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" ) );
		geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" ) );
	}

Output:
	public void setLookups() {
		diseaseType = new ArrayList();
		geneTypeColl = new ArrayList();
		diseaseType.add( new LabelValueBean( "Astrocytic", "ASTROCYTOMA" ) );
		diseaseType.add( new LabelValueBean( "Oligodendroglial", "OLIG" ) );
		diseaseType.add( new LabelValueBean( "Mixed gliomas", "MIXED" ) );
		diseaseType.add( new LabelValueBean( "Glioblastoma", "GBM" ));
		geneTypeColl.add( new LabelValueBean( "Name/Symbol", "genesymbol" ) );
		geneTypeColl.add( new LabelValueBean( "Locus Link Id", "genelocus" ) );
		geneTypeColl.add( new LabelValueBean( "GenBank AccNo.", "genbankno" ) );
	}


Input:
  public void visitNode(AstNode astNode) {
    if (astNode.getFirstChild(FlexGrammar.VARIABLE_DEF_KIND).getFirstChild(FlexKeyword.CONST) != null) {
      for (AstNode variableBindingNode : astNode.getFirstChild(FlexGrammar.VARIABLE_BINDING_LIST).getChildren(FlexGrammar.VARIABLE_BINDING)) {
        AstNode identifierNode = variableBindingNode
          .getFirstChild(FlexGrammar.TYPED_IDENTIFIER)
          .getFirstChild(FlexGrammar.IDENTIFIER);
        if (!identifierNode.getTokenValue().matches(format)) {
          getContext().createLineViolation(this, "Rename this constant name to match the regular expression {0}",
            identifierNode, format);
        }
      }
    }
  }

Output:
  public void visitNode(AstNode astNode) {
    if (astNode.getFirstChild(FlexGrammar.VARIABLE_DEF_KIND).getFirstChild(FlexKeyword.CONST) != null) {
      for (AstNode variableBindingNode : astNode.getFirstChild(FlexGrammar.VARIABLE_BINDING_LIST).getChildren(FlexGrammar.VARIABLE_BINDING)) {
        AstNode identifierNode = variableBindingNode
          .getFirstChild(FlexGrammar.TYPED_IDENTIFIER)
          .getFirstChild(FlexGrammar.IDENTIFIER);
        if (!identifierNode.getTokenValue().matches(format)) {
          getContext().createLineViolation(this, "Rename this constant ''{0}'' to match the regular expression {1}",
            identifierNode, identifierNode.getTokenValue(), format);
        }
      }
    }
  }


Input:
    private void makeItem() throws CollectException {
	try {
	    long timeout = session.getTimeout(IBaseSession.Timeout.M);
	    String tempDir = session.getTempDir();
	    StringBuffer sb = new StringBuffer(tempDir);
	    if (!tempDir.endsWith(session.getFilesystem().getDelimiter())) {
		sb.append(session.getFilesystem().getDelimiter());
	    }
	    sb.append("secpol.inf");
	    String secpol = sb.toString();
	    String cmd = "secedit.exe /export /areas SECURITYPOLICY /cfg " + secpol;
	    SafeCLI.ExecData data = SafeCLI.execData(cmd, null, session, timeout);
	    int code = data.getExitCode();
	    switch(code) {
	      case 0:
		IFile file = null;
		try {
		    file = session.getFilesystem().getFile(secpol, IFile.Flags.READWRITE);
		    IniFile config = new IniFile(file.getInputStream(), StringTools.UTF16LE);
		    items = new Vector<PasswordpolicyItem>();
		    PasswordpolicyItem item = Factories.sc.windows.createPasswordpolicyItem();
		    IProperty prop = config.getSection("System Access");
		    for (String key : prop) {
			if ("MaximumPasswordAge".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setMaxPasswdAge(type);
			} else if ("MinimumPasswordAge".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setMinPasswdAge(type);
			} else if ("MinimumPasswordLength".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setMinPasswdLen(type);
			} else if ("PasswordHistorySize".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setPasswordHistLen(type);
			} else if ("ClearTextPassword".equals(key)) {
			    EntityItemBoolType type = Factories.sc.core.createEntityItemBoolType();
			    type.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
			    type.setValue(prop.getProperty(key));
			    item.setReversibleEncryption(type);
			} else if ("PasswordComplexity".equals(key)) {
			    EntityItemBoolType type = Factories.sc.core.createEntityItemBoolType();
			    type.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
			    type.setValue(prop.getProperty(key));
			    item.setReversibleEncryption(type);
			}
		    }
		    items.add(item);
		} catch (NoSuchElementException e) {
		    error = new CollectException(e.getMessage(), FlagEnumeration.NOT_APPLICABLE);
		    throw error;
		} catch (IOException e) {
		    session.getLogger().warn(JOVALMsg.ERROR_IO, secpol, e.getMessage());
		} finally {
		    if (file != null) {
			file.delete();
		    }
		}
		break;
	      default:
		String output = new String(data.getData());
		String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_WIN_SECEDIT_CODE, Integer.toString(code), output);
		throw new Exception(msg);
	    }
	} catch (CollectException e) {
	    throw e;
	} catch (Exception e) {
	    session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
	    error = new CollectException(e.getMessage(), FlagEnumeration.ERROR);
	    throw error;
	}
    }

Output:
    private void makeItem() throws CollectException {
	try {
	    long timeout = session.getTimeout(IBaseSession.Timeout.M);
	    String tempDir = session.getTempDir();
	    StringBuffer sb = new StringBuffer(tempDir);
	    if (!tempDir.endsWith(session.getFilesystem().getDelimiter())) {
		sb.append(session.getFilesystem().getDelimiter());
	    }
	    sb.append("secpol.inf");
	    String secpol = sb.toString();
	    String cmd = "secedit.exe /export /areas SECURITYPOLICY /cfg " + secpol;
	    SafeCLI.ExecData data = SafeCLI.execData(cmd, null, session, timeout);
	    int code = data.getExitCode();
	    switch(code) {
	      case 0:
		IFile file = null;
		try {
		    file = session.getFilesystem().getFile(secpol, IFile.Flags.READWRITE);
		    IniFile config = new IniFile(file.getInputStream(), StringTools.UTF16LE);
		    items = new Vector<PasswordpolicyItem>();
		    PasswordpolicyItem item = Factories.sc.windows.createPasswordpolicyItem();
		    IProperty prop = config.getSection("System Access");
		    for (String key : prop) {
			if ("MaximumPasswordAge".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    long days = Long.parseLong(prop.getProperty(key));
			    long secs = days * 86400;
			    type.setValue(Long.toString(secs));
			    item.setMaxPasswdAge(type);
			} else if ("MinimumPasswordAge".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    long days = Long.parseLong(prop.getProperty(key));
			    long secs = days * 86400;
			    type.setValue(Long.toString(secs));
			    item.setMinPasswdAge(type);
			} else if ("MinimumPasswordLength".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setMinPasswdLen(type);
			} else if ("PasswordHistorySize".equals(key)) {
			    EntityItemIntType type = Factories.sc.core.createEntityItemIntType();
			    type.setDatatype(SimpleDatatypeEnumeration.INT.value());
			    type.setValue(prop.getProperty(key));
			    item.setPasswordHistLen(type);
			} else if ("ClearTextPassword".equals(key)) {
			    EntityItemBoolType type = Factories.sc.core.createEntityItemBoolType();
			    type.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
			    type.setValue(prop.getProperty(key));
			    item.setReversibleEncryption(type);
			} else if ("PasswordComplexity".equals(key)) {
			    EntityItemBoolType type = Factories.sc.core.createEntityItemBoolType();
			    type.setDatatype(SimpleDatatypeEnumeration.BOOLEAN.value());
			    type.setValue(prop.getProperty(key));
			    item.setReversibleEncryption(type);
			}
		    }
		    items.add(item);
		} catch (NoSuchElementException e) {
		    error = new CollectException(e.getMessage(), FlagEnumeration.NOT_APPLICABLE);
		    throw error;
		} catch (IOException e) {
		    session.getLogger().warn(JOVALMsg.ERROR_IO, secpol, e.getMessage());
		} finally {
		    if (file != null) {
			file.delete();
		    }
		}
		break;
	      default:
		String output = new String(data.getData());
		String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_WIN_SECEDIT_CODE, Integer.toString(code), output);
		throw new Exception(msg);
	    }
	} catch (CollectException e) {
	    throw e;
	} catch (Exception e) {
	    session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
	    error = new CollectException(e.getMessage(), FlagEnumeration.ERROR);
	    throw error;
	}
    }


Input:
	protected void zipSubmissions(Assignment2 assignment,
			List<AssignmentSubmission> submissionsWithHistory, OutputStream outputStream,
			StringBuilder exceptionMessage)
	{
		String assignmentTitle = assignment.getTitle();
		String contextId = externalLogic.getCurrentContextId();
		String currUserId = externalLogic.getCurrentUserId();
		List<String> viewableStudents = permissionLogic.getViewableStudentsForUserForItem(currUserId, assignment);
		Map<String, User> userIdUserMap = externalLogic.getUserIdUserMap(viewableStudents);
		String formatWithTime = bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_date_format_with_time");
		String formatNoTime = bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_date_format");
		DateFormat df_withTime = new SimpleDateFormat(formatWithTime, bundle.getLocale());
		DateFormat df_noTime = new SimpleDateFormat(formatNoTime, bundle.getLocale());
		if (!assignment.isGraded() && (submissionsWithHistory == null || submissionsWithHistory.isEmpty())) {
		    if (log.isDebugEnabled()) log.debug("Nothing to download!!");
		} else {
		    try
		    {
		        ZipOutputStream out = new ZipOutputStream(outputStream);
		        String root = Validator.escapeZipEntry(assignmentTitle) + Entity.SEPARATOR;
		        if (submissionsWithHistory != null && !submissionsWithHistory.isEmpty())
		        {
		            List<String> submissionFolderNames = new ArrayList<String>();
		            for (AssignmentSubmission s : submissionsWithHistory)
		            {
		                if (s.getSubmissionHistorySet() != null && !s.getSubmissionHistorySet().isEmpty()) {
		                    User submitterUser = userIdUserMap.get(s.getUserId());
		                    if (submitterUser != null) {
		                        String submissionFolder = submitterUser.getSortName();
		                        if (submissionFolderNames.contains(submissionFolder)) {
		                            submissionFolder = getUniqueFolderName(submissionFolder, submissionFolderNames);
		                        }
		                        submissionFolderNames.add(submissionFolder);
		                        Set<AssignmentSubmissionVersion> versionHistory = s.getSubmissionHistorySet();
		                        if (versionHistory != null && !versionHistory.isEmpty()) {
		                            List<String> versionFolderNames = new ArrayList<String>();
		                            for (AssignmentSubmissionVersion version : versionHistory) {
		                                if (version.getSubmittedDate() != null) {
		                                    String versionFolder = root + submissionFolder + Entity.SEPARATOR
		                                    + df_withTime.format(version.getSubmittedDate());
		                                    if (versionFolderNames.contains(versionFolder)) {
		                                        versionFolder = getUniqueFolderName(versionFolder, versionFolderNames);
		                                    }
		                                    versionFolderNames.add(versionFolder);
		                                    ZipEntry versionFolderEntry = new ZipEntry(
		                                            versionFolder);
		                                    out.putNextEntry(versionFolderEntry);
		                                    out.flush();
		                                    out.closeEntry();
		                                    if (version.getSubmittedText() != null && version.getSubmittedText().trim().length() > 0)
		                                    {
		                                        ZipEntry textEntry = new ZipEntry(versionFolder + Entity.SEPARATOR
		                                                + bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_submitted_text")
		                                                + ".txt");
		                                        out.putNextEntry(textEntry);
		                                        byte[] text = version.getSubmittedText().getBytes();
		                                        out.write(text);
		                                        textEntry.setSize(text.length);
		                                        out.closeEntry();
		                                    }
		                                    if (version.getSubmissionAttachSet() != null && !version.getSubmissionAttachSet().isEmpty()) {
		                                        zipAttachments(out, root + submissionFolder,
		                                                versionFolder, version.getSubmissionAttachSet());
		                                    }
		                                }
		                            }
		                        }
		                    }
		                }
		            }
		        }
		        if (assignment.isGraded() && assignment.getGradableObjectId() != null) {
		            StringBuilder gradesBuilder = new StringBuilder();
		            gradesBuilder.append(
		                    bundle.getFormattedMessage("assignment2.assignment_grade-assignment.downloadall.header",
		                            new Object[] {assignmentTitle}))
		                            .append("\n");
		            List<String> gradableStudents = permissionLogic.getGradableStudentsForUserForItem(currUserId, assignment);
		            if (gradableStudents != null && !gradableStudents.isEmpty()) {
		                Map<String, GradeInformation> userIdGradeMap = gradebookLogic.getGradeInformationForStudents(gradableStudents, assignment.getContextId(), assignment.getGradableObjectId());
		                for (String studentId : gradableStudents) {
		                    User student = userIdUserMap.get(studentId);
		                    if (student != null) {
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(student.getDisplayId());
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(",");
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(student.getSortName());
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(",");
		                        GradeInformation gradeInfo = userIdGradeMap.get(studentId);
		                        if (gradeInfo != null) {
		                            String gradebookGrade = "";
		                            String gradebookComment = "";
		                            if (gradeInfo.getGradebookGrade() != null) {
		                                gradebookGrade = gradeInfo.getGradebookGrade();
		                            }
		                            if (gradeInfo.getGradebookComment() != null) {
		                                gradebookComment = gradeInfo.getGradebookComment();
		                            }
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(gradebookGrade);
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(",");
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(gradebookComment);
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(",");
		                        } else {
		                            gradesBuilder.append(",,");
		                        }
		                        gradesBuilder.append("\n");
		                    }
		                }
		                ZipEntry gradesCSVEntry = new ZipEntry(root + assignmentTitle + "-" + contextId + "_" + df_noTime.format(new Date()) + ".csv");
		                out.putNextEntry(gradesCSVEntry);
		                byte[] grades = gradesBuilder.toString().getBytes();
		                out.write(grades);
		                gradesCSVEntry.setSize(grades.length);
		                out.closeEntry();
		            }
		        }
		        out.finish();
		        out.flush();
		        out.close();
		    }
		    catch (IOException e)
		    {
		        exceptionMessage.append("Cannot establish the IO to create zip file. ");
		        log
		        .debug(this
		                + ": getSubmissionsZip--IOException unable to create the zip file for assignment "
		                + assignmentTitle);
		    }
		}
	}

Output:
	protected void zipSubmissions(Assignment2 assignment,
			List<AssignmentSubmission> submissionsWithHistory, OutputStream outputStream,
			StringBuilder exceptionMessage)
	{
		String assignmentTitle = assignment.getTitle();
		String contextId = externalLogic.getCurrentContextId();
		String currUserId = externalLogic.getCurrentUserId();
		List<String> viewableStudents = permissionLogic.getViewableStudentsForUserForItem(currUserId, assignment);
		Map<String, User> userIdUserMap = externalLogic.getUserIdUserMap(viewableStudents);
		String formatWithTime = bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_date_format_with_time");
		String formatNoTime = bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_date_format");
		DateFormat df_withTime = new SimpleDateFormat(formatWithTime, bundle.getLocale());
		DateFormat df_noTime = new SimpleDateFormat(formatNoTime, bundle.getLocale());
		if (!assignment.isGraded() && (submissionsWithHistory == null || submissionsWithHistory.isEmpty())) {
		    if (log.isDebugEnabled()) log.debug("Nothing to download!!");
		} else {
		    try
		    {
		        ZipOutputStream out = new ZipOutputStream(outputStream);
		        String root = Validator.escapeZipEntry(assignmentTitle) + Entity.SEPARATOR;
		        if (submissionsWithHistory != null && !submissionsWithHistory.isEmpty())
		        {
		            List<String> submissionFolderNames = new ArrayList<String>();
		            for (AssignmentSubmission s : submissionsWithHistory)
		            {
		                if (s.getSubmissionHistorySet() != null && !s.getSubmissionHistorySet().isEmpty()) {
		                    User submitterUser = userIdUserMap.get(s.getUserId());
		                    if (submitterUser != null) {
		                        String submissionFolder = submitterUser.getSortName();
		                        if (submissionFolderNames.contains(submissionFolder)) {
		                            submissionFolder = getUniqueFolderName(submissionFolder, submissionFolderNames);
		                        }
		                        submissionFolderNames.add(submissionFolder);
		                        Set<AssignmentSubmissionVersion> versionHistory = s.getSubmissionHistorySet();
		                        if (versionHistory != null && !versionHistory.isEmpty()) {
		                            List<String> versionFolderNames = new ArrayList<String>();
		                            for (AssignmentSubmissionVersion version : versionHistory) {
		                                if (version.getSubmittedDate() != null) {
		                                    String versionFolder = root + submissionFolder + Entity.SEPARATOR
		                                    + df_withTime.format(version.getSubmittedDate());
		                                    if (versionFolderNames.contains(versionFolder)) {
		                                        versionFolder = getUniqueFolderName(versionFolder, versionFolderNames);
		                                    }
		                                    versionFolderNames.add(versionFolder);
		                                    ZipEntry versionFolderEntry = new ZipEntry(
		                                            versionFolder + Entity.SEPARATOR);
		                                    out.putNextEntry(versionFolderEntry);
		                                    out.closeEntry();
		                                    if (version.getSubmittedText() != null && version.getSubmittedText().trim().length() > 0)
		                                    {
		                                        String submittedTextFileName = bundle.getString("assignment2.assignment_grade_assignment.downloadall.filename_submitted_text") + ".txt";
		                                        ZipEntry textEntry = new ZipEntry(versionFolder + Entity.SEPARATOR
		                                                + submittedTextFileName);
		                                        out.putNextEntry(textEntry);
		                                        byte[] text = version.getSubmittedText().getBytes();
		                                        out.write(text);
		                                        textEntry.setSize(text.length);
		                                        out.closeEntry();
		                                    }
		                                    if (version.getSubmissionAttachSet() != null && !version.getSubmissionAttachSet().isEmpty()) {
		                                        zipAttachments(out, root + submissionFolder,
		                                                versionFolder, version.getSubmissionAttachSet());
		                                    }
		                                }
		                            }
		                        }
		                    }
		                }
		            }
		        }
		        if (assignment.isGraded() && assignment.getGradableObjectId() != null) {
		            StringBuilder gradesBuilder = new StringBuilder();
		            gradesBuilder.append(
		                    bundle.getFormattedMessage("assignment2.assignment_grade-assignment.downloadall.header",
		                            new Object[] {assignmentTitle}))
		                            .append("\n");
		            List<String> gradableStudents = permissionLogic.getGradableStudentsForUserForItem(currUserId, assignment);
		            if (gradableStudents != null && !gradableStudents.isEmpty()) {
		                Map<String, GradeInformation> userIdGradeMap = gradebookLogic.getGradeInformationForStudents(gradableStudents, assignment.getContextId(), assignment.getGradableObjectId());
		                for (String studentId : gradableStudents) {
		                    User student = userIdUserMap.get(studentId);
		                    if (student != null) {
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(student.getDisplayId());
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(",");
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(student.getSortName());
		                        gradesBuilder.append("\"");
		                        gradesBuilder.append(",");
		                        GradeInformation gradeInfo = userIdGradeMap.get(studentId);
		                        if (gradeInfo != null) {
		                            String gradebookGrade = "";
		                            String gradebookComment = "";
		                            if (gradeInfo.getGradebookGrade() != null) {
		                                gradebookGrade = gradeInfo.getGradebookGrade();
		                            }
		                            if (gradeInfo.getGradebookComment() != null) {
		                                gradebookComment = gradeInfo.getGradebookComment();
		                            }
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(gradebookGrade);
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(",");
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(gradebookComment);
		                            gradesBuilder.append("\"");
		                            gradesBuilder.append(",");
		                        } else {
		                            gradesBuilder.append(",,");
		                        }
		                        gradesBuilder.append("\n");
		                    }
		                }
		                ZipEntry gradesCSVEntry = new ZipEntry(root + assignmentTitle + "-" + contextId + "_" + df_noTime.format(new Date()) + ".csv");
		                out.putNextEntry(gradesCSVEntry);
		                byte[] grades = gradesBuilder.toString().getBytes();
		                out.write(grades);
		                gradesCSVEntry.setSize(grades.length);
		                out.closeEntry();
		            }
		        }
		        out.finish();
		        out.flush();
		        out.close();
		    }
		    catch (IOException e)
		    {
		        exceptionMessage.append("Cannot establish the IO to create zip file. ");
		        log
		        .debug(this
		                + ": getSubmissionsZip--IOException unable to create the zip file for assignment "
		                + assignmentTitle);
		    }
		}
	}


Input:
    public void populate(MetropolisGenerator generator,Chunk chunk) {
        ClipboardProviderWorldEdit clips = generator.getClipboardProvider();
        grid = generator.getGridProvider().getGrid(chunkX,chunkZ);
        GridRandom random = grid.getRandom();
        ContextProvider context = generator.getContextProvider();
        if(random.getChance(60)){
            List<Clipboard> schems = clips.getFit(chunkSizeX,chunkSizeZ, findRoad(),context.getContext(chunkX,chunkZ));
            if(schems!=null&&schems.size()>0){
                generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                parcel.populate(generator,chunk);
                return;
            }else {
                generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ) + "going over to fallback");
                schems = clips.getFit(chunkSizeX,chunkSizeZ, Direction.NORTH,context.getContext(chunkX,chunkZ));
                if(schems!=null&&schems.size()>0){
                    generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                    parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                    parcel.populate(generator,chunk);
                    return;
                }else {
                    generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ));
                }
            }
        }
        if((chunkSizeX<=2)&&(chunkSizeZ<=2)){
            List<Clipboard> schems = clips.getFit(chunkSizeX,chunkSizeZ, findRoad(),context.getContext(chunkX,chunkZ));
            if(schems!=null&&schems.size()>0){
                generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                parcel.populate(generator,chunk);
                return;
            }else {
                generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ) + "going over to fallback");
                schems = clips.getFit(chunkSizeX,chunkSizeZ, Direction.NORTH,context.getContext(chunkX,chunkZ));
                if(schems!=null&&schems.size()>0){
                    generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                    parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                    parcel.populate(generator,chunk);
                    return;
                }else {
                    parcel = new EmptyParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ);
                    generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ));
                }
            }
            return;
        }
        if(chunkSizeX>chunkSizeZ){
            int cut = random.getRandomInt(1,chunkSizeX-1);
            partitionX(grid,cut);
        }else {
            int cut = random.getRandomInt(1,chunkSizeZ-1);
            partitionZ(grid,cut);
        }
        partition1.populate(generator,chunk);
        partition2.populate(generator,chunk);
    }
    private Direction findRoad(){
        for(int i=0;i<chunkSizeX;i++){
            Parcel p = grid.getParcel(chunkX+i,chunkZ-1);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.NORTH;
            }
            p = grid.getParcel(chunkX+i,chunkZ+chunkSizeZ);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.SOUTH;
            }
        }
        for(int i=0;i<chunkSizeZ;i++){
            Parcel p = grid.getParcel(chunkX-1,chunkZ+i);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.WEST;
            }
            p = grid.getParcel(chunkX+chunkSizeX,chunkZ);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.EAST;
            }
        }
        return Direction.NONE;
    }
    private void partitionXwithRoads(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,cut,chunkSizeZ);
        for(int i=chunkZ;i<chunkZ+chunkSizeZ;i++){
            grid.setParcel(chunkX,i,new RoadParcel(grid,chunkX,i));
        }
        partition2 = new DistrictParcel(grid,chunkX+cut+1,chunkZ,chunkSizeX-cut-1,chunkSizeZ);
    }
    private void partitionX(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,cut,chunkSizeZ);
        partition2 = new DistrictParcel(grid,chunkX+cut,chunkZ,chunkSizeX-cut,chunkSizeZ);
    }
    private void partitionZwithRoads(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,chunkSizeX,cut);
        for(int i=chunkX;i<chunkX+chunkSizeX;i++){
            grid.setParcel(i,chunkZ+cut,new RoadParcel(grid,i,chunkZ));
        }
        partition2 = new DistrictParcel(grid,chunkX,chunkZ+cut+1,chunkSizeX,chunkSizeZ-cut-1);
    }
    private void partitionZ(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,chunkSizeX,cut);
        partition2 = new DistrictParcel(grid,chunkX,chunkZ+cut,chunkSizeX,chunkSizeZ-cut);
    }
}

Output:
    public void populate(MetropolisGenerator generator,Chunk chunk) {
        ClipboardProviderWorldEdit clips = generator.getClipboardProvider();
        grid = generator.getGridProvider().getGrid(chunkX,chunkZ);
        GridRandom random = grid.getRandom();
        ContextProvider context = generator.getContextProvider();
        if(random.getChance(60)){
            List<Clipboard> schems = clips.getFit(chunkSizeX,chunkSizeZ, findRoad(),context.getContext(chunkX,chunkZ));
            if(schems!=null&&schems.size()>0){
                generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                parcel.populate(generator,chunk);
                return;
            }else {
                generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ) + "going over to fallback");
                schems = clips.getFit(chunkSizeX,chunkSizeZ, Direction.NORTH,context.getContext(chunkX,chunkZ));
                if(schems!=null&&schems.size()>0){
                    generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                    parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                    parcel.populate(generator,chunk);
                    return;
                }else {
                    generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ));
                }
            }
        }
        if((chunkSizeX<=2)&&(chunkSizeZ<=2)){
            List<Clipboard> schems = clips.getFit(chunkSizeX,chunkSizeZ, findRoad(),context.getContext(chunkX,chunkZ));
            if(schems!=null&&schems.size()>0){
                generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                parcel.populate(generator,chunk);
                return;
            }else {
                generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ) + "going over to fallback");
                schems = clips.getFit(chunkSizeX,chunkSizeZ, Direction.NORTH,context.getContext(chunkX,chunkZ));
                if(schems!=null&&schems.size()>0){
                    generator.reportDebug("Found "+schems.size()+" schematics for this spot, placing one");
                    parcel = new ClipboardParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ,schems.get(random.getRandomInt(schems.size())),context.getContext(chunkX,chunkZ));
                    parcel.populate(generator,chunk);
                    return;
                }else {
                    parcel = new EmptyParcel(grid,chunkX,chunkZ,chunkSizeX,chunkSizeZ);
                    generator.reportDebug("No schems found for size "+chunkSizeX+"x"+chunkSizeZ + " , context=" + context.getContext(chunkX,chunkZ));
                }
            }
            return;
        }
        if(chunkSizeX>chunkSizeZ){
            int cut = random.getRandomInt(1,chunkSizeX-1);
            partitionX(grid,cut);
        }else {
            int cut = random.getRandomInt(1,chunkSizeZ-1);
            partitionZ(grid,cut);
        }
        partition1.populate(generator,chunk);
        partition2.populate(generator,chunk);
    }
    private Direction findRoad(){
        for(int i=0;i<chunkSizeX;i++){
            Parcel p = grid.getParcel(chunkX+i,chunkZ-1);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.NORTH;
            }
            p = grid.getParcel(chunkX+i,chunkZ+chunkSizeZ);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.SOUTH;
            }
        }
        for(int i=0;i<chunkSizeZ;i++){
            Parcel p = grid.getParcel(chunkX-1,chunkZ+i);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.WEST;
            }
            p = grid.getParcel(chunkX+chunkSizeX,chunkZ);
            if(p!=null && p.getContextType().equals(ContextType.ROAD)){
                return Direction.EAST;
            }
        }
        return Direction.NONE;
    }
    private void partitionXwithRoads(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,cut,chunkSizeZ);
        for(int i=chunkZ;i<chunkZ+chunkSizeZ;i++){
            grid.setParcel(chunkX+cut,i,new RoadParcel(grid,chunkX+cut,i));
        }
        partition2 = new DistrictParcel(grid,chunkX+cut+1,chunkZ,chunkSizeX-cut-1,chunkSizeZ);
    }
    private void partitionX(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,cut,chunkSizeZ);
        partition2 = new DistrictParcel(grid,chunkX+cut,chunkZ,chunkSizeX-cut,chunkSizeZ);
    }
    private void partitionZwithRoads(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,chunkSizeX,cut);
        for(int i=chunkX;i<chunkX+chunkSizeX;i++){
            grid.setParcel(i,chunkZ+cut,new RoadParcel(grid,i,chunkZ+cut));
        }
        partition2 = new DistrictParcel(grid,chunkX,chunkZ+cut+1,chunkSizeX,chunkSizeZ-cut-1);
    }
    private void partitionZ(Grid grid,int cut){
        partition1 = new DistrictParcel(grid,chunkX,chunkZ,chunkSizeX,cut);
        partition2 = new DistrictParcel(grid,chunkX,chunkZ+cut,chunkSizeX,chunkSizeZ-cut);
    }
}


Input:
	public void onClickLiveMap(View view) {
		boolean activated = liveMapButton.isChecked();
		boolean periodicUpdateEnabled = true;
		try {
			periodicUpdateEnabled = isPeriodicUpdateEnabled(this);
		} catch (Exception e) {
			Log.e(TAG, "Unable to receive info about current state of prediodic update events from Locus.", e);
		}
		if (activated && !periodicUpdateEnabled) {
			activated = false;
			liveMapButton.setChecked(activated);
			Toast.makeText(this, getText(R.string.livemap_disabled), Toast.LENGTH_LONG).show();
		} else if (activated) {
			Toast.makeText(this, getText(R.string.livemap_activated), Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, getText(R.string.livemap_deactivated), Toast.LENGTH_LONG).show();
		}
		prefs.edit().putBoolean(PrefConstants.LIVE_MAP, activated).commit();
		if (LocusUtils.isIntentMainFunction(getIntent())) {
			finish();
		}
	}

Output:
	public void onClickLiveMap(View view) {
		boolean activated = liveMapButton.isChecked();
		boolean periodicUpdateEnabled = true;
		try {
			periodicUpdateEnabled = isPeriodicUpdateEnabled(this);
		} catch (Exception e) {
			Log.e(TAG, "Unable to receive info about current state of periodic update events from Locus.", e);
		}
		if (activated && !periodicUpdateEnabled) {
			activated = false;
			liveMapButton.setChecked(activated);
			Toast.makeText(this, getText(R.string.livemap_disabled), Toast.LENGTH_LONG).show();
		} else if (activated) {
			Toast.makeText(this, getText(R.string.livemap_activated), Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, getText(R.string.livemap_deactivated), Toast.LENGTH_LONG).show();
		}
		prefs.edit().putBoolean(PrefConstants.LIVE_MAP, activated).commit();
		if (LocusUtils.isIntentMainFunction(getIntent())) {
			finish();
		}
	}


Input:
  private boolean processCommandFromActive(DatanodeCommand cmd,
      BPServiceActor actor) throws IOException {
    if (cmd == null)
      return true;
    final BlockCommand bcmd =
      cmd instanceof BlockCommand? (BlockCommand)cmd: null;
    switch(cmd.getAction()) {
    case DatanodeProtocol.DNA_TRANSFER:
      dn.transferBlocks(bcmd.getBlockPoolId(), bcmd.getBlocks(), bcmd.getTargets());
      dn.metrics.incrBlocksReplicated(bcmd.getBlocks().length);
      break;
    case DatanodeProtocol.DNA_INVALIDATE:
      Block toDelete[] = bcmd.getBlocks();
      try {
        if (dn.blockScanner != null) {
          dn.blockScanner.deleteBlocks(bcmd.getBlockPoolId(), toDelete);
        }
        dn.getFSDataset().invalidate(bcmd.getBlockPoolId(), toDelete);
      } catch(IOException e) {
        dn.checkDiskError();
        throw e;
      }
      dn.metrics.incrBlocksRemoved(toDelete.length);
      break;
    case DatanodeProtocol.DNA_SHUTDOWN:
      throw new UnsupportedOperationException("Received unimplemented DNA_SHUTDOWN");
    case DatanodeProtocol.DNA_REGISTER:
      LOG.info("DatanodeCommand action: DNA_REGISTER");
      actor.reRegister();
      break;
    case DatanodeProtocol.DNA_FINALIZE:
      String bp = ((FinalizeCommand) cmd).getBlockPoolId();
      assert getBlockPoolId().equals(bp) :
        "BP " + getBlockPoolId() + " received DNA_FINALIZE " +
        "for other block pool " + bp;
      dn.finalizeUpgradeForPool(bp);
      break;
    case DatanodeProtocol.DNA_RECOVERBLOCK:
      String who = "NameNode at " + actor.getNNSocketAddress();
      dn.recoverBlocks(who, ((BlockRecoveryCommand)cmd).getRecoveringBlocks());
      break;
    case DatanodeProtocol.DNA_ACCESSKEYUPDATE:
      LOG.info("DatanodeCommand action: DNA_ACCESSKEYUPDATE");
      if (dn.isBlockTokenEnabled) {
        dn.blockPoolTokenSecretManager.addKeys(
            getBlockPoolId(),
            ((KeyUpdateCommand) cmd).getExportedKeys());
      }
      break;
    case DatanodeProtocol.DNA_BALANCERBANDWIDTHUPDATE:
      LOG.info("DatanodeCommand action: DNA_BALANCERBANDWIDTHUPDATE");
      long bandwidth =
                 ((BalancerBandwidthCommand) cmd).getBalancerBandwidthValue();
      if (bandwidth > 0) {
        DataXceiverServer dxcs =
                     (DataXceiverServer) dn.dataXceiverServer.getRunnable();
        LOG.info("Updating balance throttler bandwidth from "
            + dxcs.balanceThrottler.getBandwidth() + " bytes/s "
            + "to: " + bandwidth + " bytes/s.");
        dxcs.balanceThrottler.setBandwidth(bandwidth);
      }
      break;
    default:
      LOG.warn("Unknown DatanodeCommand action: " + cmd.getAction());
    }
    return true;
  }

Output:
  private boolean processCommandFromActive(DatanodeCommand cmd,
      BPServiceActor actor) throws IOException {
    if (cmd == null)
      return true;
    final BlockCommand bcmd =
      cmd instanceof BlockCommand? (BlockCommand)cmd: null;
    switch(cmd.getAction()) {
    case DatanodeProtocol.DNA_TRANSFER:
      dn.transferBlocks(bcmd.getBlockPoolId(), bcmd.getBlocks(), bcmd.getTargets());
      dn.metrics.incrBlocksReplicated(bcmd.getBlocks().length);
      break;
    case DatanodeProtocol.DNA_INVALIDATE:
      Block toDelete[] = bcmd.getBlocks();
      try {
        if (dn.blockScanner != null) {
          dn.blockScanner.deleteBlocks(bcmd.getBlockPoolId(), toDelete);
        }
        dn.getFSDataset().invalidate(bcmd.getBlockPoolId(), toDelete);
      } catch(IOException e) {
        throw e;
      }
      dn.metrics.incrBlocksRemoved(toDelete.length);
      break;
    case DatanodeProtocol.DNA_SHUTDOWN:
      throw new UnsupportedOperationException("Received unimplemented DNA_SHUTDOWN");
    case DatanodeProtocol.DNA_REGISTER:
      LOG.info("DatanodeCommand action: DNA_REGISTER");
      actor.reRegister();
      break;
    case DatanodeProtocol.DNA_FINALIZE:
      String bp = ((FinalizeCommand) cmd).getBlockPoolId();
      assert getBlockPoolId().equals(bp) :
        "BP " + getBlockPoolId() + " received DNA_FINALIZE " +
        "for other block pool " + bp;
      dn.finalizeUpgradeForPool(bp);
      break;
    case DatanodeProtocol.DNA_RECOVERBLOCK:
      String who = "NameNode at " + actor.getNNSocketAddress();
      dn.recoverBlocks(who, ((BlockRecoveryCommand)cmd).getRecoveringBlocks());
      break;
    case DatanodeProtocol.DNA_ACCESSKEYUPDATE:
      LOG.info("DatanodeCommand action: DNA_ACCESSKEYUPDATE");
      if (dn.isBlockTokenEnabled) {
        dn.blockPoolTokenSecretManager.addKeys(
            getBlockPoolId(),
            ((KeyUpdateCommand) cmd).getExportedKeys());
      }
      break;
    case DatanodeProtocol.DNA_BALANCERBANDWIDTHUPDATE:
      LOG.info("DatanodeCommand action: DNA_BALANCERBANDWIDTHUPDATE");
      long bandwidth =
                 ((BalancerBandwidthCommand) cmd).getBalancerBandwidthValue();
      if (bandwidth > 0) {
        DataXceiverServer dxcs =
                     (DataXceiverServer) dn.dataXceiverServer.getRunnable();
        LOG.info("Updating balance throttler bandwidth from "
            + dxcs.balanceThrottler.getBandwidth() + " bytes/s "
            + "to: " + bandwidth + " bytes/s.");
        dxcs.balanceThrottler.setBandwidth(bandwidth);
      }
      break;
    default:
      LOG.warn("Unknown DatanodeCommand action: " + cmd.getAction());
    }
    return true;
  }


Input:
	public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) {
		SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
		sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
		try {
			IProfile profile = profileChangeRequest.getProfile();
			Object[] updatedPlan = updatePlannerInfo(profileChangeRequest);
			URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null;
			Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties());
			List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits()));
			extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits()));
			if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString()))
				extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
			IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4));
			Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext);
			IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4));
			if (slice == null)
				return new ProvisioningPlan(slicer.getStatus());
			Projector projector = new Projector(slice, newSelectionContext);
			projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4));
			IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4));
			if (s.getSeverity() == IStatus.CANCEL)
				return new ProvisioningPlan(s);
			if (s.getSeverity() == IStatus.ERROR) {
				sub.setTaskName(Messages.Planner_NoSolution);
				if (!(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
					return new ProvisioningPlan(s);
				boolean newExplanation = Boolean.getBoolean("p2.new.explanation");
				LogHelper.log(s);
				if (!newExplanation) {
					IStatus oldResolverStatus = new NewDependencyExpander(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, null, availableIUs, newSelectionContext, false).expand(sub.newChild(ExpandWork / 4));
					if (!oldResolverStatus.isOK())
						s = oldResolverStatus;
					return new ProvisioningPlan(oldResolverStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, null));
				}
				Set explanation = projector.getExplanation();
				IStatus explanationStatus = new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, explanation.toString(), null);
				return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation));
			}
			if (Tracing.DEBUG && s.getSeverity() != IStatus.OK)
				LogHelper.log(s);
			s = Status.OK_STATUS;
			Collection newState = projector.extractSolution();
			newState.remove(updatedPlan[0]);
			ResolutionHelper newStateHelper = new ResolutionHelper(newSelectionContext, null);
			newState = newStateHelper.attachCUs(newState);
			ResolutionHelper oldStateHelper = new ResolutionHelper(createSelectionContext(profile.getProperties()), null);
			Collection oldState = oldStateHelper.attachCUs(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
			return generateProvisioningPlan(s, oldState, newState, profileChangeRequest);
		} catch (OperationCanceledException e) {
			return new ProvisioningPlan(Status.CANCEL_STATUS);
		} finally {
			sub.done();
		}
	}

Output:
	public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) {
		SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
		sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
		try {
			IProfile profile = profileChangeRequest.getProfile();
			Object[] updatedPlan = updatePlannerInfo(profileChangeRequest);
			URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null;
			Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties());
			List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits()));
			extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits()));
			if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString()))
				extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
			IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4));
			Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext);
			IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4));
			if (slice == null)
				return new ProvisioningPlan(slicer.getStatus());
			Projector projector = new Projector(slice, newSelectionContext);
			projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4));
			IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4));
			if (s.getSeverity() == IStatus.CANCEL)
				return new ProvisioningPlan(s);
			if (s.getSeverity() == IStatus.ERROR) {
				sub.setTaskName(Messages.Planner_NoSolution);
				LogHelper.log(s);
				if (context != null && !(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
					return new ProvisioningPlan(s);
				boolean newExplanation = Boolean.getBoolean("p2.new.explanation");
				if (!newExplanation) {
					IStatus oldResolverStatus = new NewDependencyExpander(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, null, availableIUs, newSelectionContext, false).expand(sub.newChild(ExpandWork / 4));
					if (!oldResolverStatus.isOK())
						s = oldResolverStatus;
					return new ProvisioningPlan(oldResolverStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, null));
				}
				Set explanation = projector.getExplanation();
				IStatus explanationStatus = new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, explanation.toString(), null);
				return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation));
			}
			if (Tracing.DEBUG && s.getSeverity() != IStatus.OK)
				LogHelper.log(s);
			s = Status.OK_STATUS;
			Collection newState = projector.extractSolution();
			newState.remove(updatedPlan[0]);
			ResolutionHelper newStateHelper = new ResolutionHelper(newSelectionContext, null);
			newState = newStateHelper.attachCUs(newState);
			ResolutionHelper oldStateHelper = new ResolutionHelper(createSelectionContext(profile.getProperties()), null);
			Collection oldState = oldStateHelper.attachCUs(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
			return generateProvisioningPlan(s, oldState, newState, profileChangeRequest);
		} catch (OperationCanceledException e) {
			return new ProvisioningPlan(Status.CANCEL_STATUS);
		} finally {
			sub.done();
		}
	}


Input:
	public <A> A requireAncestorTag(Class<A> tagClass) {
		TagStack ts = getTagStack();
		if (ts.size()>1) {
			for (int i=ts.size()-2;i>=0;--i) {
				PolygraphTag tag=ts.get(i);
				if (!tagClass.isInstance(tag)) {
					@SuppressWarnings("unchecked")
					A tag2 = (A)tag;
					return tag2;
				}
			}
		}
		throw new PolygraphTemplateException(String.format("Ancestor tag of type %s expected but not found.",tagClass.getName()));
	}

Output:
	public <A> A requireAncestorTag(Class<A> tagClass) {
		TagStack ts = getTagStack();
		if (ts.size()>1) {
			for (int i=ts.size()-2;i>=0;--i) {
				PolygraphTag tag=ts.get(i);
				if (tagClass.isInstance(tag)) {
					@SuppressWarnings("unchecked")
					A tag2 = (A)tag;
					return tag2;
				}
			}
		}
		throw new PolygraphTemplateException(String.format("Ancestor tag of type %s expected but not found.",tagClass.getName()));
	}