text:
package org.ebayopensource.turmeric.runtime.common.impl.internal.config;

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

import javax.wsdl.Definition;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;

import org.ebayopensource.turmeric.runtime.binding.BindingConstants;
import org.ebayopensource.turmeric.runtime.common.exceptions.ErrorDataFactory;
import org.ebayopensource.turmeric.runtime.common.exceptions.ServiceCreationException;
import org.ebayopensource.turmeric.runtime.common.types.SOAConstants;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.ebayopensource.turmeric.runtime.errorlibrary.ErrorConstants;

public class TypeMappingConfigMapper {
	private static final String TRUE = "TRUE";
	private static final String ATTR_PACKAGE_NAME = "name";
	private static final String ATTR_PACKAGE_XML_NS = "xml-namespace";
	private static final String BASIC_XML_TYPE_JAVA_PACKAGE = "java.lang";
	private static final String ATTR_METHOD_NAME = "methodName";
	public static void map(String filename, Element topLevel, TypeMappingConfigHolder dst) throws ServiceCreationException {
		String enforceSingleNS = topLevel.getAttribute("enable-namespace-folding");
		dst.setEnableNamespaceFolding((enforceSingleNS != null && TRUE.equals(enforceSingleNS)) ? true : false);
		Element operationList = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_OPERATIONLIST);
		NodeList operations = DomParseUtils.getImmediateChildrenByTagName(operationList, SOAConstants.XML_NODE_OPERATION);
		List<String> operationsInWsdl = new ArrayList<String>();
		for (int i = 0; i < operations.getLength(); i++) {
			Element inOperation = (Element) operations.item(i);
			String name = inOperation.getAttribute("name");
			operationsInWsdl.add(name);
		}
		if(!operationsInWsdl.contains(SOAConstants.OP_GET_VERSION)){
			addOperation(filename, topLevel);
			dst.setOperationAdded(true);
		}

		addCachePolicyOperation(filename, topLevel);
		// dst.setOperationAdded(true); // only needed for getVersion calls

		Element packageMap = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_PACKAGEMAP);
		NodeList packages = DomParseUtils.getImmediateChildrenByTagName(packageMap, SOAConstants.XML_NODE_PACKAGE);
		Map<String,String> pkgToNs = new HashMap<String,String>();
		for (int i = 0; i < packages.getLength(); i++) {
			Element onePackage = (Element) packages.item(i);
			String javaPackage = onePackage.getAttribute("name");
			String xmlNamespace = onePackage.getAttribute("xml-namespace");
			// TODO - temporary hack for backward compatibility - need to find all instances of the old typemappings and fix them.
//			if (SOAConstants.OLD_DEFAULT_SERVICE_NAMESPACE.equals(xmlNamespace)) {
//				xmlNamespace = SOAConstants.DEFAULT_SERVICE_NAMESPACE;
//			}
			pkgToNs.put(javaPackage, xmlNamespace);
			dst.setXmlNamespaceFromJavaPackage(javaPackage, xmlNamespace);
		}
		operations = DomParseUtils.getImmediateChildrenByTagName(operationList, SOAConstants.XML_NODE_OPERATION);
		for (int i = 0; i < operations.getLength(); i++) {
			Element inOperation = (Element) operations.item(i);
			String name = inOperation.getAttribute("name");
			OperationConfig outOperation = new OperationConfig();
			outOperation.setName(name);
			if(inOperation.hasAttribute(ATTR_METHOD_NAME))
			{
				outOperation.setMethodName(inOperation.getAttribute(ATTR_METHOD_NAME));
			}
			else
			{
				outOperation.setMethodName(name);
			}
			MessageTypeConfig messageTypeConfig = parseMessageTypeConfig(filename, pkgToNs, inOperation, SOAConstants.XML_NODE_REQUEST_MESSAGE);
			if (messageTypeConfig != null) {
				outOperation.setRequestMessage(messageTypeConfig);
			}
			messageTypeConfig = parseMessageTypeConfig(filename, pkgToNs, inOperation, SOAConstants.XML_NODE_RESPONSE_MESSAGE);
			if (messageTypeConfig != null) {
				outOperation.setResponseMessage(messageTypeConfig);
			}
			messageTypeConfig = parseMessageTypeConfig(filename, pkgToNs, inOperation, SOAConstants.XML_NODE_ERROR_MESSAGE);
			if (messageTypeConfig != null) {
				outOperation.setErrorMessage(messageTypeConfig);
			}
			parseMessageHeaderList(filename, pkgToNs, outOperation.getRequestHeader(), inOperation, SOAConstants.XML_NODE_REQUEST_HEADER);
			parseMessageHeaderList(filename, pkgToNs, outOperation.getResponseHeader(), inOperation, SOAConstants.XML_NODE_RESPONSE_HEADER);
			dst.setOperation(name, outOperation);
		}

		Element javaTypeList = (Element) DomParseUtils.getSingleNode(filename, topLevel, "java-type-list");
		if ( javaTypeList != null ) {
			NodeList javaTypes = DomParseUtils.getImmediateChildrenByTagName(javaTypeList, SOAConstants.XML_NODE_JAVA_TYPE_NAME);
			if ( javaTypes != null ) {
				for (int i = 0; i < javaTypes.getLength(); i++) {
					Element javaClass = (Element) javaTypes.item(i);
					String name = javaClass.getTextContent();
					dst.addJavaTypes( name );
				}
			}
		}
	}

	private static void parseMessageHeaderList(String filename, Map<String, String> pkgToNs, List<MessageHeaderConfig> headerList, Element inOperation, String headerName) throws ServiceCreationException {
		NodeList headerElements = DomParseUtils.getImmediateChildrenByTagName(inOperation, headerName);
		for (int i = 0; i < headerElements.getLength(); i++) {
			Element headerElement = (Element) headerElements.item(i);
			MessageHeaderConfig messageHeaderConfig = parseMessageHeaderConfig(filename, pkgToNs, headerElement);
			headerList.add(messageHeaderConfig);
		}
	}

	private static MessageHeaderConfig parseMessageHeaderConfig(String filename, Map<String, String> pkgToNs,
			Element headerElement) throws ServiceCreationException {
		MessageHeaderConfig messageHeaderConfig = new MessageHeaderConfig();
		String javaType = DomParseUtils.getElementText(filename, headerElement, SOAConstants.XML_NODE_JAVA_TYPE_NAME);
		messageHeaderConfig.setJavaTypeName(javaType);
		String xmlLocalTypeName = DomParseUtils.getElementText(filename, headerElement, SOAConstants.XML_NODE_XML_TYPE_NAME);
		messageHeaderConfig.setXmlTypeName(qualifyXmlName(pkgToNs, javaType, xmlLocalTypeName));
		String xmlLocalElementName = DomParseUtils.getElementText(filename, headerElement, SOAConstants.XML_NODE_XML_ELEMENT_NAME);
		QName xmlElementName = QName.valueOf(xmlLocalElementName);
		messageHeaderConfig.setXmlElementName(xmlElementName);
		return messageHeaderConfig;
	}

	private static MessageTypeConfig parseMessageTypeConfig(String filename, Map<String, String> pkgToNs, Element operation, String name) throws ServiceCreationException {
		Element oneMessage = (Element) DomParseUtils.getSingleNode(filename, operation, name);
		if (oneMessage == null) {
			return null;
		}
		MessageTypeConfig messageTypeConfig = new MessageTypeConfig();
		String javaType = DomParseUtils.getElementText(filename, oneMessage, SOAConstants.XML_NODE_JAVA_TYPE_NAME);
		messageTypeConfig.setJavaTypeName(javaType);
		String xmlLocalTypeName = DomParseUtils.getElementText(filename, oneMessage, SOAConstants.XML_NODE_XML_TYPE_NAME);
		messageTypeConfig.setXmlTypeName(qualifyXmlName(pkgToNs, javaType, xmlLocalTypeName));
		String xmlLocalElementName = DomParseUtils.getElementText(filename, oneMessage, SOAConstants.XML_NODE_XML_ELEMENT_NAME);
		QName xmlElementName = QName.valueOf(xmlLocalElementName);
		if( XMLConstants.NULL_NS_URI.equals(xmlElementName.getNamespaceURI()) ) {
			xmlElementName = qualifyXmlName(pkgToNs, javaType, xmlLocalElementName);
		}
		messageTypeConfig.setXmlElementName(xmlElementName);
		Boolean hasAttachment = DomParseUtils.getElementBoolean(filename, oneMessage, SOAConstants.XML_NODE_HAS_ATTACHMENT);
		if (hasAttachment != null && hasAttachment.booleanValue()) {
			messageTypeConfig.setHasAttachment(true);
		} else {
			messageTypeConfig.setHasAttachment(false);
		}

		return messageTypeConfig;
	}

	private static QName qualifyXmlName(Map<String, String> pkgToNs, String javaType, String localpart) throws ServiceCreationException {
		if (localpart == null) {
			return null;
		}
		String packageName = getPackageName(javaType);
		String namespace = null;
		if (packageName != null) {
			namespace = pkgToNs.get(packageName);
			if (namespace == null) {
				throw new ServiceCreationException(ErrorDataFactory.createErrorData(ErrorConstants.CFG_TYPEMAP_JAVA_NO_PACKAGE_MATCH,
						ErrorConstants.ERRORDOMAIN, new Object[] {javaType}));
			}
		}
		return new QName(namespace, localpart);
	}

	private static String getPackageName(String javaType) throws ServiceCreationException {
		if (javaType == null) {
			return null;
		}
		int lastDot = javaType.lastIndexOf(".");
		if (lastDot == -1) {
			// Typically this is a primitive like integer.  For now, we'll assume java.lang since typemappings
			// is an auto-generated file.
			return BASIC_XML_TYPE_JAVA_PACKAGE;
		}
		return javaType.substring(0, lastDot);
	}

	private static void addOperation(String filename, Element topLevel) throws ServiceCreationException{
		Element packageMap = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_PACKAGEMAP);
		NodeList packages = DomParseUtils.getImmediateChildrenByTagName(packageMap, SOAConstants.XML_NODE_PACKAGE);
		if(packages != null && packages.getLength() > 0){
			Element onePackage = (Element) packages.item(0);
			Element newPackageMapping = (Element)onePackage.cloneNode(false);
			newPackageMapping.setAttribute(ATTR_PACKAGE_NAME, BASIC_XML_TYPE_JAVA_PACKAGE);
			newPackageMapping.setAttribute(ATTR_PACKAGE_XML_NS, BindingConstants.XMLSCHEMA_URI);
			packageMap.appendChild(newPackageMapping);
		}
		Element operationList = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_OPERATIONLIST);
		NodeList operations = DomParseUtils.getImmediateChildrenByTagName(operationList, SOAConstants.XML_NODE_OPERATION);

		if(operations != null && operations.getLength() > 0){
			Element firstOperation = (Element) operations.item(0);
			Element newOperation = (Element) firstOperation.cloneNode(true);
			newOperation.setAttribute("name", SOAConstants.OP_GET_VERSION);
			NodeList newOperationParams = newOperation.getChildNodes();
			int numberOfParams = newOperationParams.getLength();
			int notRemoved = 0;
			for (int i = 0; i < numberOfParams; i++) {
				Node childNode = newOperationParams.item(notRemoved);
				if(childNode.getNodeName() == SOAConstants.XML_NODE_RESPONSE_MESSAGE){
					NodeList respParams = childNode.getChildNodes();
					for (int j = 0; j < respParams.getLength(); j++) {
						Node respParam = respParams.item(j);

						if(respParam.getNodeName() == SOAConstants.XML_NODE_JAVA_TYPE_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("java.lang.String");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_XML_TYPE_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("VersionString");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_XML_ELEMENT_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("version");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_HAS_ATTACHMENT && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("false");
					}
					notRemoved++;
				}else
					newOperation.removeChild(childNode);
			}

			operationList.appendChild(newOperation);
		}

	}

	private static void addCachePolicyOperation(String filename, Element topLevel) throws ServiceCreationException{
		Element packageMap = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_PACKAGEMAP);
		NodeList packages = DomParseUtils.getImmediateChildrenByTagName(packageMap, SOAConstants.XML_NODE_PACKAGE);
		if(packages != null && packages.getLength() > 0){
			Element onePackage = (Element) packages.item(0);
			Element newPackageMapping = (Element)onePackage.cloneNode(false);
			newPackageMapping.setAttribute(ATTR_PACKAGE_NAME, BASIC_XML_TYPE_JAVA_PACKAGE);
			newPackageMapping.setAttribute(ATTR_PACKAGE_XML_NS, BindingConstants.XMLSCHEMA_URI);
			packageMap.appendChild(newPackageMapping);
		}
		Element operationList = (Element) DomParseUtils.getSingleNode(filename, topLevel, SOAConstants.XML_NODE_OPERATIONLIST);
		NodeList operations = DomParseUtils.getImmediateChildrenByTagName(operationList, SOAConstants.XML_NODE_OPERATION);

		if(operations != null && operations.getLength() > 0){
			Element firstOperation = (Element) operations.item(0);
			Element newOperation = (Element) firstOperation.cloneNode(true);
			newOperation.setAttribute("name", SOAConstants.OP_GET_CACHE_POLICY);
			NodeList newOperationParams = newOperation.getChildNodes();
			int numberOfParams = newOperationParams.getLength();
			int notRemoved = 0;
			for (int i = 0; i < numberOfParams; i++) {
				Node childNode = newOperationParams.item(notRemoved);
				if(childNode.getNodeName() == SOAConstants.XML_NODE_RESPONSE_MESSAGE){
					NodeList respParams = childNode.getChildNodes();
					for (int j = 0; j < respParams.getLength(); j++) {
						Node respParam = respParams.item(j);

						if(respParam.getNodeName() == SOAConstants.XML_NODE_JAVA_TYPE_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("java.lang.String");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_XML_TYPE_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("CachePolicy");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_XML_ELEMENT_NAME && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("cachepolicy");
						else if(respParam.getNodeName() == SOAConstants.XML_NODE_HAS_ATTACHMENT && respParam.getFirstChild() != null)
							respParam.getFirstChild().setNodeValue("false");
					}
					notRemoved++;
				}else
					newOperation.removeChild(childNode);
			}

			operationList.appendChild(newOperation);
		}

	}

	public static void map(String filename, Element topLevel,
			QName oldSvcQName, QName svcQName, Definition wsdlDef,
			TypeMappingConfigHolder dst) throws ServiceCreationException {
		changeNameSpace(filename, topLevel, oldSvcQName, svcQName, wsdlDef);
		map(filename, topLevel, dst);
	}

	private static void changeNameSpace(String fileName, Element typeMapping,
			QName oldSvcQName, QName svcQName, Definition wsdlDef)
			throws ServiceCreationException {
		String targetWSDLNS = wsdlDef != null ? wsdlDef.getTargetNamespace()
				: svcQName.getNamespaceURI();
		Element operationList = (Element) DomParseUtils.getSingleNode(fileName,
				typeMapping, SOAConstants.XML_NODE_OPERATIONLIST);
		NodeList operations = DomParseUtils.getImmediateChildrenByTagName(
				operationList, SOAConstants.XML_NODE_OPERATION);

		HashMap<String, String> oldToNewNameSpace = new HashMap<String, String>();

		changeNameSpaceMessages(fileName, wsdlDef, oldSvcQName, svcQName,
				targetWSDLNS, operations, oldToNewNameSpace);

		changeNameSpaceForPackageMap(fileName, typeMapping, oldToNewNameSpace);
	}

	private static void changeNameSpaceForPackageMap(String fileName,
			Element typeMapping, HashMap<String, String> oldToNewNameSpace)
			throws ServiceCreationException {
		Element packageMapList = (Element) DomParseUtils.getSingleNode(
				fileName, typeMapping, SOAConstants.XML_NODE_PACKAGEMAP);
		NodeList packages = DomParseUtils.getImmediateChildrenByTagName(
				packageMapList, SOAConstants.XML_NODE_PACKAGE);
		HashMap<String, String> nsToResplace = new HashMap<String, String>();
		// Replace ns for packages
		for (int i = 0; i < packages.getLength(); i++) {
			// Get the package
			Element inPackage = (Element) packages.item(i);
			String javaPackage = inPackage.getAttribute(ATTR_PACKAGE_NAME);
			String newXMLNs = oldToNewNameSpace.get(javaPackage);
			if (newXMLNs != null) {
				nsToResplace.put(inPackage.getAttribute(ATTR_PACKAGE_XML_NS),
						newXMLNs);
				inPackage.setAttribute(ATTR_PACKAGE_XML_NS, newXMLNs);
			}
		}
		// Relace other NS mappings
		for (int i = 0; i < packages.getLength(); i++) {
			// Get the package
			Element inPackage = (Element) packages.item(i);
			String XMLSNs = inPackage.getAttribute(ATTR_PACKAGE_XML_NS);
			String newXMLNs = nsToResplace.get(XMLSNs);
			if (newXMLNs != null) {
				inPackage.setAttribute(ATTR_PACKAGE_XML_NS, newXMLNs);
			}
		}

	}

	private static void changeNameSpaceMessages(String fileName,
			Definition wsdlDef, QName oldSvcQName, QName svcQName,
			String targetWSDLNS, NodeList operations,
			HashMap<String, String> oldToNewNameSpace)
			throws ServiceCreationException {
		for (int i = 0; i < operations.getLength(); i++) {
			// Get the operation
			Element inOperation = (Element) operations.item(i);
			changeNameSpaceMessage(fileName, wsdlDef, oldSvcQName, svcQName,
					targetWSDLNS, oldToNewNameSpace, inOperation);
		}
	}

	private static void changeNameSpaceMessage(String fileName,
			Definition wsdlDef, QName oldSvcQName, QName svcQName,
			String targetWSDLNS, HashMap<String, String> oldToNewNameSpace,
			Element inOperation) throws ServiceCreationException {
		changeNameSpaceInnerMessage(fileName, wsdlDef, oldSvcQName, svcQName,
				targetWSDLNS, oldToNewNameSpace, inOperation,
				SOAConstants.XML_NODE_REQUEST_MESSAGE, false);
		changeNameSpaceInnerMessage(fileName, wsdlDef, oldSvcQName, svcQName,
				targetWSDLNS, oldToNewNameSpace, inOperation,
				SOAConstants.XML_NODE_RESPONSE_MESSAGE, false);
		changeNameSpaceInnerMessage(fileName, wsdlDef, oldSvcQName, svcQName,
				targetWSDLNS, oldToNewNameSpace, inOperation,
				SOAConstants.XML_NODE_ERROR_MESSAGE, true);
	}

	private static void changeNameSpaceInnerMessage(String fileName,
			Definition wsdlDef, QName oldSvcQName, QName svcQName,
			String targetWSDLNS, HashMap<String, String> oldToNewNameSpace,
			Element inOperation, String xmlMessageName, boolean ignoreMismatch)
			throws ServiceCreationException {
		// Get Request Message
		Element reqMessage = (Element) DomParseUtils.getSingleNode(fileName,
				inOperation, xmlMessageName);
		if (reqMessage == null) {
			return;
		}
		// Get XML-element-Name Element
		Element xmlTypeElement = DomParseUtils.getSingleElement(fileName,
				reqMessage, SOAConstants.XML_NODE_XML_ELEMENT_NAME);

		Element javaTypeElement = DomParseUtils.getSingleElement(fileName,
				reqMessage, SOAConstants.XML_NODE_JAVA_TYPE_NAME);

		if (xmlTypeElement == null || javaTypeElement == null) {
			return;
		}
		// Get XML Element Name content
		String xmlTypeElementStr = xmlTypeElement.getTextContent();

		// Get Java type Name
		String javaTypeName = javaTypeElement.getTextContent();

		// Get QName out of it
		QName qNameTM = QName.valueOf(xmlTypeElementStr);

		// First check if the WSDL can get this message
		//Raghu: Turning off the wsdl mismatch validation. As we need to plugin
		// wsdl schema parsing for doing the same.
	/*	if (wsdlDef != null) {
			retroFitQName(wsdlDef, svcQName, targetWSDLNS,
					oldToNewNameSpace, xmlTypeElement, javaTypeName, qNameTM,
					ignoreMismatch);
		} else {*/
			retroFitQName(oldSvcQName.getNamespaceURI(), targetWSDLNS,
					oldToNewNameSpace, xmlTypeElement, javaTypeName, qNameTM);
		/*}*/
	}

	private static void retroFitQName(String oldNS, String targetWSDLNS,
			HashMap<String, String> oldToNewNameSpace, Element xmlTypeElement,
			String javaTypeName, QName qNameTM) throws ServiceCreationException {
		if (oldNS.equals(qNameTM.getNamespaceURI()) || qNameTM.getNamespaceURI().isEmpty()) {
			QName qNameWSDLNS = new QName(targetWSDLNS, qNameTM.getLocalPart());
			// Retro-fit the element
			xmlTypeElement.setTextContent(qNameWSDLNS.toString());

			String packageName = getPackageName(javaTypeName);
			if (packageName != null) {
				oldToNewNameSpace.put(packageName, targetWSDLNS);
			}
		}
	}

/*	private static void retroFitQName(Definition wsdlDef, QName svcQName,
			String targetWSDLNS, HashMap<String, String> oldToNewNameSpace,
			Element xmlTypeElement, String javaTypeName, QName qNameTM,
			boolean ignoreMismatch) throws ServiceCreationException {
		Message message = wsdlDef.getMessage(qNameTM);
		if (message == null) {
			// Try QName with
			QName qNameWSDLNS = new QName(targetWSDLNS, qNameTM.getLocalPart());

			message = wsdlDef.getMessage(qNameWSDLNS);
			if (message == null) {
				if (!ignoreMismatch) {
					throw new ServiceCreationException(
					ErrorDataFactory.createErrorData(ErrorConstants.CFG_GENERIC_ERROR,
					ErrorConstants.ERRORDOMAIN, new Object[] { qNameTM.toString(),
									svcQName.toString() }));
				}
				return;
			}
			// Retro-fit the element
			xmlTypeElement.setTextContent(qNameWSDLNS.toString());

			String packageName = getPackageName(javaTypeName);
			if (packageName != null) {
				oldToNewNameSpace.put(packageName, targetWSDLNS);
			}
		}
	}
	*/

}

redpajama_set_name: RedPajamaGithub


text:
package com.bah.culvert.data;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.bah.culvert.test.Utils;

public class ResultTest {

  @Before
  public void setup() {
  }

  @Test
  public void testResultConstructors() {
    Result r1 = new Result();
    Result r2 = new Result(new byte[] { 0, 0, 0, 3 });

    r1.setRecordId(new byte[] { 0, 0, 0, 4 });

    Assert.assertArrayEquals(new byte[] { 0, 0, 0, 3 }, r2.getRecordId());
    Assert.assertArrayEquals(new byte[] { 0, 0, 0, 4 }, r1.getRecordId());
  }

  @Test
  public void testResultCopy() {
    Result r1 = new Result();
    Result r2 = new Result(new byte[] { 0, 0, 0, 3 });
    r1.copy(r2);

    Assert.assertArrayEquals(new byte[] { 0, 0, 0, 3 }, r2.getRecordId());
    Assert.assertArrayEquals(new byte[] { 0, 0, 0, 3 }, r1.getRecordId());
  }

  @Test
  public void testResultSetValues() {
    CKeyValue ckv = new CKeyValue(new byte[] { 0, 0, 0, 8 });
    Result r1 = new Result();
    Result r2 = new Result(new byte[] { 0, 0, 0, 3 });
    r1.setValues((CKeyValue[]) null);
    r2.setValues(ckv);

    Assert.assertNotNull(r1.getKeyValues());
    Assert.assertNotNull(r2.getKeyValues());
  }

  @Test
  public void testResultWrite() throws InstantiationException,
      IllegalAccessException, IOException {

    // test simple ckv
    CKeyValue ckv = new CKeyValue(new byte[] { 0, 0, 0, 8 });
    Result r1 = new Result(ckv);
    Result ret = (Result) Utils.testReadWrite(r1);
    assertEquals(1, ret.getKeyValues().size());
    assertEquals(ckv, ret.getKeyValues().get(0));

    // test more complex ckv
    ckv = new CKeyValue(new byte[] { 1 }, new byte[] { 2 }, new byte[] { 3, 4 });
    r1 = new Result(ckv);
    ret = (Result) Utils.testReadWrite(r1);
    assertEquals(1, ret.getKeyValues().size());
    assertEquals(ckv, ret.getKeyValues().get(0));
  }

  /**
   * Test that we find the right values in a result
   * @throws Throwable on failure
   */
  @Test
  public void testGetValues() throws Throwable {

    List<CKeyValue> keys = new ArrayList<CKeyValue>();
    keys.add(new CKeyValue(new byte[] { 1 }, new byte[] { 2 },
        new byte[] { 3 }, new byte[] { 4 }));
    keys.add(new CKeyValue(new byte[] { 1 }, new byte[] { 2 },
        new byte[] { 5 }, new byte[] { 4, 1 }));
    keys.add(new CKeyValue(new byte[] { 1 }, new byte[] { 6 },
        new byte[] { 5 }, new byte[] { 4 }));
    keys.add(new CKeyValue(new byte[] { 2 }, new byte[] { 2 },
        new byte[] { 3 }, new byte[] { 4 }));
    Result result = new Result(keys.toArray(new CKeyValue[0]));

    Assert.assertArrayEquals(new byte[] { 4 },
        result.getValue(new byte[] { 2 }, new byte[] { 3 }).getValue());
    Assert.assertArrayEquals(new byte[] { 4, 1 },
        result.getValue(new byte[] { 2 }, new byte[] { 5 }).getValue());
    Assert.assertArrayEquals(new byte[] { 4 },
        result.getValue(new byte[] { 6 }, new byte[] { 5 }).getValue());
    Assert.assertArrayEquals(new byte[] { 4 },
        result.getValue(new byte[] { 2 }, new byte[] { 3 }).getValue());
    Assert.assertEquals(null,
        result.getValue(new byte[] { 2 }, new byte[] { 2 }));
  }

}


text:
/*
This file is part of WebNES.

WebNES is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

WebNES is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with WebNES.  If not, see <http://www.gnu.org/licenses/>.
*/

this.Gui = this.Gui || {};

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

window.onload = function() {

	// This allows a list box to be on the page to load a given nes file local to the site
	var sel = $('#loadGameComboBox');
	if ( sel ) {
		sel['change'](function(){
			var value = $(this)['val']();
			if ( value.length > 0 ) {
				console.log( "Loading ROM " + value );
				Gui.App.loadRomFromUrl( value );
			}
		});
	}

	// And this is the select box for selecting a WebGL shader
	sel = $('#shaderListComboBox');
	if ( sel ) {
		sel['change'](function(){
			var value = $(this)['val']();
			if ( value.length > 0 ) {
				console.log( "Loading shader " + value );
				Gui.App.loadShaderFromUrl( value );
			} else {
				Gui.App.loadShaderFromUrl( null );
			}
		});
	}

	var requestedGameToLoad = getParameterByName( 'gameUrl' );
	Gui.App.start( { createGuiComponents: true, loadUrl: requestedGameToLoad } );
};


text:
"""
Class 6
Exercise 3
Author Mat
"""

"""
3a.Convert the IP address validation code (Class4, exercise1) into a function,
take one variable 'ip_address' and return either True or False (depending on
whether 'ip_address' is a valid IP).  Only include IP address checking in the
function--no prompting for input, no printing to standard output.
"""

def validate_ip_address (ip_address) :

    octets = ip_address.split(".")

    if len(octets) != 4:
        return False
    else:
        a,b,c,d = octets

    try:
        int_a = int(a)
        int_b = int(b)
        int_c = int(c)
        int_d = int(d)

    except ValueError as e:
        # int() conversion failed:
        return False

    # check 1st octet
    if int_a < 1 or int_a > 223 or int_a == 127:
        return False

    # check 2nd 3rd and 4th octet
    elif (  (int_b not in range (0, 256)) or
            (int_c not in range (0, 256)) or
            (int_d not in range (0, 256))) :
        return False

    # check 169.254.x.x
    elif int_a == 169 and int_b == 254:
        return False

    # validated as an IP address!
    return True


text:
// Vex Flow Notation
// Mohit Muthanna <mohit@muthanna.com>
//
// Copyright Mohit Muthanna 2010
//
// Requires vex.js.

/** @constructor */
Vex.Flow.TabNote = function(tab_struct) {
  if (arguments.length > 0) this.init(tab_struct);
}
Vex.Flow.TabNote.prototype = new Vex.Flow.Note();
Vex.Flow.TabNote.superclass = Vex.Flow.Note.prototype;
Vex.Flow.TabNote.constructor = Vex.Flow.TabNote;

Vex.Flow.TabNote.prototype.init = function(tab_struct) {
  var superclass = Vex.Flow.TabNote.superclass;
  superclass.init.call(this, tab_struct);

  // Note properties
  this.positions = tab_struct.positions; // [{ str: X, fret: X }]
  this.modifiers = [];
  this.render_options = {
    glyph_font_scale: 30 // font size for note heads and rests
  }

  this.noteGlyph =
    Vex.Flow.durationToGlyph(this.duration, this.noteType);
  if (!this.noteGlyph) {
    throw new Vex.RuntimeError("BadArguments",
        "Invalid note initialization data (No glyph found): " +
        JSON.stringify(tab_struct));
  }

  this.ghost = false; // Renders parenthesis around notes
  this.updateWidth();
}

Vex.Flow.TabNote.prototype.setGhost = function(ghost) {
  this.ghost = ghost;
  this.updateWidth();
  return this;
}

Vex.Flow.TabNote.prototype.updateWidth = function() {
  this.glyphs = [];
  this.width = 0;
  for (var i = 0; i < this.positions.length; ++i) {
    var fret = this.positions[i].fret;
    if (this.ghost) fret = "(" + fret + ")";
    var glyph = Vex.Flow.tabToGlyph(fret);
    this.glyphs.push(glyph);
    this.width = (glyph.width > this.width) ? glyph.width : this.width;
  }
}

Vex.Flow.TabNote.prototype.setStave = function(stave) {
  var superclass = Vex.Flow.TabNote.superclass;
  superclass.setStave.call(this, stave);
  this.context = stave.context;
  this.width = 0;

  // Calculate the fret number width based on font used
  if (this.context) {
    for (var i = 0; i < this.glyphs.length; ++i) {
      var text = "" + this.glyphs[i].text;
      if (text.toUpperCase() != "X")
        this.glyphs[i].width = this.context.measureText(text).width;
      this.width = (this.glyphs[i].width > this.width) ?
        this.glyphs[i].width : this.width;
    }
  }

  var ys = [];

  // Setup y coordinates for score.
  for (var i = 0; i < this.positions.length; ++i) {
    var line = this.positions[i].str;
    ys.push(this.stave.getYForLine(line - 1));
  }

  return this.setYs(ys);
}

// Get the Tab Positions for each note in chord
Vex.Flow.TabNote.prototype.getPositions = function() {
  return this.positions;
}

Vex.Flow.TabNote.prototype.addToModifierContext = function(mc) {
  this.setModifierContext(mc);
  for (var i = 0; i < this.modifiers.length; ++i) {
    this.modifierContext.addModifier(this.modifiers[i]);
  }
  this.preFormatted = false;
  return this;
}

Vex.Flow.TabNote.prototype.addModifier = function(modifier, index) {
  modifier.setNote(this);
  modifier.setIndex(index || 0);
  this.modifiers.push(modifier);
  this.setPreFormatted(false);
  return this;
}

Vex.Flow.TabNote.prototype.getTieRightX = function() {
  var tieStartX = this.getAbsoluteX();
  var note_glyph_width = this.noteGlyph.head_width;
  tieStartX += (note_glyph_width / 2);
  tieStartX += ((-this.width / 2) + this.width + 2);

  return tieStartX;
}

Vex.Flow.TabNote.prototype.getTieLeftX = function() {
  var tieEndX = this.getAbsoluteX();
  var note_glyph_width = this.noteGlyph.head_width;
  tieEndX += (note_glyph_width / 2);
  tieEndX -= ((this.width / 2) + 2);

  return tieEndX;
}

Vex.Flow.TabNote.prototype.getModifierStartXY = function(position, index) {
  if (!this.preFormatted) throw new Vex.RERR("UnformattedNote",
      "Can't call GetModifierStartXY on an unformatted note");

  if (this.ys.length == 0) throw new Vex.RERR("NoYValues",
      "No Y-Values calculated for this note.");

  var x = 0;
  if (position == Vex.Flow.Modifier.Position.LEFT) {
    x = -1 * 2;  // extra_left_px
  } else if (position == Vex.Flow.Modifier.Position.RIGHT) {
    x = this.width + 2; // extra_right_px
  } else if (position == Vex.Flow.Modifier.Position.BELOW ||
             position == Vex.Flow.Modifier.Position.ABOVE) {
      var note_glyph_width = this.noteGlyph.head_width;
      x = note_glyph_width / 2;
  }

  return {x: this.getAbsoluteX() + x, y: this.ys[index]};
}

// Pre-render formatting
Vex.Flow.TabNote.prototype.preFormat = function() {
  if (this.preFormatted) return;
  if (this.modifierContext) this.modifierContext.preFormat();
  // width is already set during init()
  this.setPreFormatted(true);
}

Vex.Flow.TabNote.prototype.draw = function() {
  if (!this.context) throw new Vex.RERR("NoCanvasContext",
      "Can't draw without a canvas context.");
  if (!this.stave) throw new Vex.RERR("NoStave", "Can't draw without a stave.");
  if (this.ys.length == 0) throw new Vex.RERR("NoYValues",
      "Can't draw note without Y values.");

  var ctx = this.context;
  var x = this.getAbsoluteX();
  var ys = this.ys;

  for (var i = 0; i < this.positions.length; ++i) {
    var y = ys[i];

    var glyph = this.glyphs[i];

    // Center the fret text beneath the notation note head
    var note_glyph_width = this.noteGlyph.head_width;
    var tab_x = x + (note_glyph_width / 2) - (glyph.width / 2);

    ctx.clearRect(tab_x - 2, y - 3, glyph.width + 4, 6);

    if (glyph.code) {
      Vex.Flow.renderGlyph(ctx, tab_x, y + 5 + glyph.shift_y,
          this.render_options.glyph_font_scale, glyph.code);
    } else {
      var text = glyph.text.toString();
      ctx.fillText(text, tab_x, y + 5);
    }
  }

  // Draw the modifiers
  for (var i = 0; i < this.modifiers.length; ++i) {
    var modifier = this.modifiers[i];
    modifier.setContext(this.context);
    modifier.draw();
  }
}


text:
require 'pathname'

require 'puppet/forge'
require 'puppet/module_tool'

module Puppet::ModuleTool
  class InstalledModules < Semantic::Dependency::Source
    attr_reader :modules, :by_name

    def priority
      10
    end

    def initialize(env)
      @env = env
      modules = env.modules_by_path

      @fetched = []
      @modules = {}
      @by_name = {}
      env.modulepath.each do |path|
        modules[path].each do |mod|
          @by_name[mod.name] = mod
          next unless mod.has_metadata?
          release = ModuleRelease.new(self, mod)
          @modules[release.name] ||= release
        end
      end

      @modules.freeze
    end

    # Fetches {ModuleRelease} entries for each release of the named module.
    #
    # @param name [String] the module name to look up
    # @return [Array<Semantic::Dependency::ModuleRelease>] a list of releases for
    #         the given name
    # @see Semantic::Dependency::Source#fetch
    def fetch(name)
      name = name.tr('/', '-')

      if @modules.key? name
        @fetched << name
        [ @modules[name] ]
      else
        [ ]
      end
    end

    def fetched
      @fetched
    end

    class ModuleRelease < Semantic::Dependency::ModuleRelease
      attr_reader :mod, :metadata

      def initialize(source, mod)
        @mod = mod
        @metadata = mod.metadata
        name = mod.forge_name.tr('/', '-')
        version = Semantic::Version.parse(mod.version)
        release = "#{name}@#{version}"

        super(source, name, version, {})

        if mod.dependencies
          mod.dependencies.each do |dep|
            results = Puppet::ModuleTool.parse_module_dependency(release, dep)
            dep_name, parsed_range, range = results

            dep.tap do |dep|
              add_constraint('initialize', dep_name, range.to_s) do |node|
                parsed_range === node.version
              end
            end
          end
        end
      end

      def install_dir
        Pathname.new(@mod.path).dirname
      end

      def install(dir)
        # If we're already installed, there's no need for us to faff about.
      end

      def prepare
        # We're already installed; what preparation remains?
      end
    end
  end
end


text:
package com.lahodiuk.bp.example;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

import com.lahodiuk.bp.Edge;
import com.lahodiuk.bp.Node;
import com.lahodiuk.bp.Potential;

/**
 * Classify chemical compounds, using network of chemical reactions: <br/>
 * Inference of chemical compound types, using network of chemical reactions
 */
public class ChemicalReactionsNetworkDemo {

	public static final int ITERATIONS_NUMBER = 10;

	public static void main(String[] args) throws Exception {

		List<String> configuration = new BufferedReader(new InputStreamReader(
				ChemicalReactionsNetworkDemo.class.getResourceAsStream("/ChemicalReactionsNetwork.txt"),
				StandardCharsets.UTF_8)).lines().collect(Collectors.toList());

		ReactionsNetwork reactionsNetwork = configureReactionsNetwork(configuration);

		inference(reactionsNetwork, ITERATIONS_NUMBER);

		reactionsNetwork.printResults();
	}

	public static void inference(ReactionsNetwork reactionsNetwork, int iterationsNumber) {
		reactionsNetwork.inference(iterationsNumber);
	}

	private static Rule parseRule(String input) {
		String[] parts = input.split("=");

		String reagentsPart = parts[0];
		List<String> reagents = new ArrayList<>();
		for (String reagent : reagentsPart.split("\\+")) {
			reagents.add(reagent.trim());
		}

		List<String> products = new ArrayList<>();
		if (parts.length > 1) {
			String productsPart = parts[1];
			for (String product : productsPart.split("\\+")) {
				products.add(product.trim());
			}
		}

		return new Rule().reagentTypes(reagents).productTypes(products);
	}

	private static Reaction parseReaction(String input) {
		String[] parts = input.split("=");
		String reagentsPart = parts[0];

		List<String> reagents = new ArrayList<>();
		for (String reagent : reagentsPart.split("\\+")) {
			reagents.add(reagent.trim());
		}

		List<String> products = new ArrayList<>();
		if (parts.length > 1) {
			String productsPart = parts[1];
			for (String product : productsPart.split("\\+")) {
				products.add(product.trim());
			}
		}

		return new Reaction().reagents(reagents).products(products);
	}

	private enum InputReaderState {
		NOTHING,
		READING_RULES,
		READING_COMPOUND_TYPES,
		READING_REACTIONS,
		READING_COMPOUND_TYPES_PROBABILITY
	}

	public static ReactionsNetwork configureReactionsNetwork(List<String> rawTextLines) {

		ReactionsNetwork reactionsNetwork = new ReactionsNetwork();

		InputReaderState currentState = InputReaderState.NOTHING;
		for (String s : rawTextLines) {
			if (s.isEmpty()) {
				continue;
			} else if ("#Rules".equals(s)) {
				currentState = InputReaderState.READING_RULES;
			} else if ("#CompoundTypes".equals(s)) {
				currentState = InputReaderState.READING_COMPOUND_TYPES;
			} else if ("#CompoundTypesProbability".equals(s)) {
				currentState = InputReaderState.READING_COMPOUND_TYPES_PROBABILITY;
			} else if ("#Reactions".equals(s)) {
				currentState = InputReaderState.READING_REACTIONS;
			} else if (s.startsWith("#")) {
				continue;
			} else {
				switch (currentState) {

				case READING_RULES:
					Rule rule = parseRule(s);
					reactionsNetwork.addRuleWithAllowedPermutations(rule);
					break;

				case READING_REACTIONS:
					Reaction reaction = parseReaction(s);
					reactionsNetwork.addReaction(reaction);
					break;

				case READING_COMPOUND_TYPES:
					String[] parts = s.split(":");
					String compound = parts[0].trim();
					String type = parts[1].trim();
					reactionsNetwork.setPriorCompoundState(compound, type);
					break;

				case READING_COMPOUND_TYPES_PROBABILITY:
					CompoundNode.EPSILON = 1.0 - Double.parseDouble(s);
					break;

				default:
					throw new RuntimeException("Unreachable code. Current line of text is: " + s);
				}
			}
		}

		return reactionsNetwork;
	}

	public static class Rule {
		private List<String> reagentTypes = new ArrayList<>();
		private List<String> productTypes = new ArrayList<>();

		public Rule reagentTypes(List<String> reagents) {
			this.reagentTypes.addAll(reagents);
			return this;
		}

		public Rule productTypes(List<String> products) {
			this.productTypes.addAll(products);
			return this;
		}

		public List<String> getProductTypes() {
			return this.productTypes;
		}

		public List<String> getReagentTypes() {
			return this.reagentTypes;
		}
	}

	public static class Reaction {
		private List<String> reagents = new ArrayList<>();
		private List<String> products = new ArrayList<>();

		public Reaction reagents(List<String> reagents) {
			this.reagents.addAll(reagents);
			return this;
		}

		public Reaction products(List<String> products) {
			this.products.addAll(products);
			return this;
		}

		public List<String> getProducts() {
			return this.products;
		}

		public List<String> getReagents() {
			return this.reagents;
		}
	}

	public static class ReactionsNetwork {

		private List<Rule> rules = new ArrayList<>();
		private List<Reaction> reactions = new ArrayList<>();

		private Map<Integer, Set<Rule>> reagentsCountToRules = new HashMap<>();
		private Map<Integer, Set<Rule>> productsCountToRules = new HashMap<>();

		private Map<Reaction, ReactionNode> reactionToReactionNode = new HashMap<>();
		private Map<String, CompoundNode> compoundToCompoundNode = new TreeMap<>();

		private List<Edge<?, ?>> edges = new ArrayList<>();

		public ReactionsNetwork addRule(Rule ruleVariant) {
			this.rules.add(ruleVariant);
			return this;
		}

		public ReactionsNetwork addRuleWithAllowedPermutations(Rule rule) {
			Set<List<String>> reagentsPermutations = permutations(rule.getReagentTypes());
			Set<List<String>> productsPermutations = permutations(rule.getProductTypes());

			for (List<String> reagents : reagentsPermutations) {
				for (List<String> products : productsPermutations) {
					Rule ruleVariant = new Rule().reagentTypes(reagents).productTypes(products);
					this.addRule(ruleVariant);
				}
			}

			return this;
		}

		public ReactionsNetwork addReaction(Reaction reaction) {
			this.reactions.add(reaction);
			return this;
		}

		public ReactionsNetwork setPriorCompoundState(String compound, String priorState) {
			this.compoundToCompoundNode.put(compound, new CompoundNode(priorState));
			return this;
		}

		private static <T> Set<List<T>> permutations(List<T> seq) {
			Set<List<T>> resultsCollector = new HashSet<>();
			permutations(new ArrayList<T>(seq),
					new LinkedList<>(seq),
					resultsCollector);
			return resultsCollector;
		}

		private static <T> void permutations(
				List<T> buffer,
				List<T> available,
				Set<List<T>> resultsCollector) {

			if (available.isEmpty()) {
				// No elements available
				// Store copy of buffer to results collector
				resultsCollector.add(new ArrayList<>(buffer));
			} else {
				// Calculate index of current position in buffer
				int position = buffer.size() - available.size();
				for (int i = 0; i < available.size(); i++) {
					// Pick element from list of available elements
					// (decreasing size of available variants by 1)
					T element = available.remove(i);
					// Write picked element to buffer into given position
					buffer.set(position, element);
					// Generate permutations for the rest of elements
					permutations(buffer, available, resultsCollector);
					// Return back picked element
					available.add(i, buffer.get(position));
					// And pick next element on next iteration
				}
			}
		}

		private void buildNetwork() {

			this.processRules();

			this.processReactions();

			for (Reaction reaction : this.reactionToReactionNode.keySet()) {
				ReactionNode reactionNode = this.reactionToReactionNode.get(reaction);

				List<String> reagents = reaction.getReagents();

				for (int position = 0; position < reagents.size(); position++) {
					String reagent = reagents.get(position);
					CompoundNode reagentNode = this.compoundToCompoundNode.get(reagent);
					this.edges.add(Edge.connect(reagentNode, reactionNode, new ReagentReactionCompatibilityPotential(position)));
				}

				List<String> products = reaction.getProducts();

				for (int position = 0; position < products.size(); position++) {
					String product = products.get(position);
					CompoundNode productNode = this.compoundToCompoundNode.get(product);
					this.edges.add(Edge.connect(productNode, reactionNode, new ProductReactionCompatibilityPotential(position)));
				}
			}
		}

		private void processRules() {
			for (Rule rule : this.rules) {
				int reagentsCount = rule.getReagentTypes().size();
				Set<Rule> rulesWithSameNumberOfReagents = this.reagentsCountToRules.get(reagentsCount);
				if (rulesWithSameNumberOfReagents == null) {
					rulesWithSameNumberOfReagents = new HashSet<>();
				}
				rulesWithSameNumberOfReagents.add(rule);
				this.reagentsCountToRules.put(reagentsCount, rulesWithSameNumberOfReagents);

				int productsCount = rule.getProductTypes().size();
				Set<Rule> rulesWithSameNumberOfProducts = this.productsCountToRules.get(productsCount);
				if (rulesWithSameNumberOfProducts == null) {
					rulesWithSameNumberOfProducts = new HashSet<>();
				}
				rulesWithSameNumberOfProducts.add(rule);
				this.productsCountToRules.put(productsCount, rulesWithSameNumberOfProducts);
			}
		}

		public void processReactions() {

			Set<String> possibleCompoundTypes = new HashSet<>();
			for (Rule rule : this.rules) {
				possibleCompoundTypes.addAll(rule.getReagentTypes());
				possibleCompoundTypes.addAll(rule.getProductTypes());
			}

			for (Reaction reaction : this.reactions) {
				int reagentsCount = reaction.getReagents().size();
				int productsCount = reaction.getProducts().size();

				Set<Rule> mostProbableRules = this.getMostProbableRulesByReagentsAndProductsCount(reagentsCount, productsCount);

				this.reactionToReactionNode.put(reaction, new ReactionNode(mostProbableRules));

				for (String reagent : reaction.getReagents()) {
					if (this.compoundToCompoundNode.get(reagent) == null) {
						this.compoundToCompoundNode.put(reagent, new CompoundNode(possibleCompoundTypes));
					} else {
						this.compoundToCompoundNode.get(reagent).setStates(possibleCompoundTypes);
					}
				}

				for (String product : reaction.getProducts()) {
					if (this.compoundToCompoundNode.get(product) == null) {
						this.compoundToCompoundNode.put(product, new CompoundNode(possibleCompoundTypes));
					} else {
						this.compoundToCompoundNode.get(product).setStates(possibleCompoundTypes);
					}
				}
			}
		}

		private Set<Rule> getMostProbableRulesByReagentsAndProductsCount(int reagentsCount, int productsCount) {
			Set<Rule> mostProbableStatesByReagentsCount = this.reagentsCountToRules.get(reagentsCount);
			Set<Rule> mostProbableStatesByProductsCount = this.productsCountToRules.get(productsCount);

			Set<Rule> mostProbableRules = new HashSet<>();

			// Intersection of sets
			if ((mostProbableStatesByProductsCount != null) && (mostProbableStatesByReagentsCount != null)) {
				for (Rule s : mostProbableStatesByProductsCount) {
					if (mostProbableStatesByReagentsCount.contains(s)) {
						mostProbableRules.add(s);
					}
				}
			}

			if (mostProbableRules.isEmpty()) {
				// throw new
				// RuntimeException("Can't find any reactions withs given numbers of products and reagents");
				mostProbableRules = new HashSet<>(this.rules);
			}

			return mostProbableRules;
		}

		public ReactionsNetwork inference(int times) {
			this.buildNetwork();
			System.out.println("Compound nodes: " + this.compoundToCompoundNode.size());
			System.out.println("Reaction nodes: " + this.reactionToReactionNode.size());

			for (int i = 0; i < times; i++) {
				for (Edge<?, ?> edge : this.edges) {
					edge.updateMessagesNode1ToNode2();
				}
				for (Edge<?, ?> edge : this.edges) {
					edge.refreshMessagesNode1ToNode2();
				}
				for (Edge<?, ?> edge : this.edges) {
					edge.updateMessagesNode2ToNode1();
				}
				for (Edge<?, ?> edge : this.edges) {
					edge.refreshMessagesNode2ToNode1();
				}
			}
			return this;
		}

		public void printResults() {
			for (String compound : this.compoundToCompoundNode.keySet()) {
				// System.out.println(compound + "\t" +
				// this.compoundToCompoundNode.get(compound).getPosteriorProbabilities());
				System.out.println(compound + "\t" +
						this.compoundToCompoundNode.get(compound).getMostProbableState()
						+ "\t"
						+
						this.compoundToCompoundNode.get(compound).getPosteriorProbabilities().get(this.compoundToCompoundNode.get(compound).getMostProbableState())
						+ "\tCount: " +
						this.compoundToCompoundNode.get(compound).getEdges().size());
				// System.out.println(compound + "\t" +
				// this.compoundToCompoundNode.get(compound).getMostProbableState());
			}
			System.out.println("Total number of compounds: " + this.compoundToCompoundNode.keySet().size());
		}

		public String getMostProbableCompoundType(String compound) {
			return this.compoundToCompoundNode.get(compound).getMostProbableState();
		}
	}

	private static class CompoundNode extends Node<String> {

		private static double EPSILON = 1e-15;

		private Set<String> states;

		private String mostProbableState;

		public CompoundNode(String mostProbableState) {
			this.mostProbableState = mostProbableState;
		}

		public CompoundNode(Set<String> states) {
			this.states = states;
		}

		public void setStates(Set<String> states) {
			this.states = states;
		}

		@Override
		public Set<String> getStates() {
			return this.states;
		}

		@Override
		public double getPriorProbablility(String state) {
			if (this.mostProbableState == null) {
				return 1.0 / this.states.size();
			} else {
				if (this.mostProbableState.equals(state)) {
					return 1.0 - EPSILON;
				} else {
					return EPSILON;
				}
			}
		}
	}

	private static class ReactionNode extends Node<Rule> {

		private static final double EPSILON = 1e-5;

		private Set<Rule> mostProbableStates = null;

		public ReactionNode(Set<Rule> mostProbableStates) {
			this.mostProbableStates = mostProbableStates;
		}

		@Override
		public Set<Rule> getStates() {
			return this.mostProbableStates;
		}

		@Override
		public double getPriorProbablility(Rule state) {
			if (this.mostProbableStates.contains(state)) {
				return 1.0 / this.mostProbableStates.size();
			} else {
				return EPSILON;
			}
		}
	}

	private static class ReagentReactionCompatibilityPotential extends Potential<String, Rule> {

		private static final double EPSILON = 1e-5;

		private final int position;

		public ReagentReactionCompatibilityPotential(int position) {
			this.position = position;
		}

		@Override
		public double getValue(String compoundState, Rule reactionState) {
			if ((this.position < reactionState.getReagentTypes().size()) &&
					(reactionState.getReagentTypes().get(this.position).equals(compoundState))) {
				return 1 - EPSILON;
			} else {
				return EPSILON;
			}
		}
	}

	private static class ProductReactionCompatibilityPotential extends Potential<String, Rule> {

		private static final double EPSILON = 1e-5;

		private final int position;

		public ProductReactionCompatibilityPotential(int position) {
			this.position = position;
		}

		@Override
		public double getValue(String compoundState, Rule reactionState) {
			if ((this.position < reactionState.getProductTypes().size()) &&
					(reactionState.getProductTypes().get(this.position).equals(compoundState))) {
				return 1 - EPSILON;
			} else {
				return EPSILON;
			}
		}
	}
}


text:
<?php

namespace JMS\DebuggingBundle\Kernel;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class NullHttpKernel implements HttpKernelInterface
{
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        return null;
    }
}


text:
<!doctype html>
<html ⚡>
  <head>
    <meta charset="utf-8">
    <title>amp-story-panning-media example</title>
    <link rel="canonical" href="example.html">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-story" src="https://cdn.ampproject.org/v0/amp-story-1.0.js"></script>
    <script async custom-element="amp-story-panning-media" src="https://cdn.ampproject.org/v0/amp-story-panning-media-0.1.js"></script>
  </head>
  <body>
    <amp-story
        standalone
        title="Demo Story"
        publisher="AMP Story"
        publisher-logo-src="example.com/logo.png"
        poster-portrait-src="example.com/poster.jpg">

        <!-- stars example -->
        <amp-story-page id="stars-1">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-1'
              x="10%"
              y="0%"
              zoom='1'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-2'
              x="0%"
              y="0%"
              zoom='1'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="stars-2">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-1'
              x="-10%"
              y="0%"
              zoom='1'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-2'
              x="-15%"
              y="0%"
              zoom='1'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="stars-3">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-1'
              x="-10%"
              y="0%"
              zoom='2'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              group-id='stars-group-2'
              x="-15%"
              y="0%"
              zoom='1.5'
            >
              <amp-img layout="fill" width="2992" height="2550" src="img/stars.png"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <!-- painting example -->
        <amp-story-page id="painting-1">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-2">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="-50%"
              y="-50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-3">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              y="-50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-4">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="50%"
              y="-50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-5">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-6">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="50%"
              y="50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-7">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              y="50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-8">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="-50%"
              y="50%"
            >
              <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
            </amp-story-panning-media>
          </amp-story-grid-layer>
        </amp-story-page>

        <amp-story-page id="painting-9">
          <amp-story-grid-layer template="fill">
            <amp-story-panning-media
              layout="fill"
              x="-50%"
              y="50%"
              zoom="2"
            >
            <amp-img layout="fill" width="4000" height="3059" src="img/conservatory-coords.jpg"></amp-img>
          </amp-story-panning-media>
        </amp-story-grid-layer>
      </amp-story-page>
    </amp-story>
  </body>
</html>


text:
[![Build Status](https://travis-ci.org/nafiesl/SimpleCrudGenerator.svg?branch=master)](https://travis-ci.org/nafiesl/SimpleCrudGenerator)
[![Total Downloads](https://poser.pugx.org/luthfi/simple-crud-generator/downloads)](https://packagist.org/packages/luthfi/simple-crud-generator)

Need faster TDD in Laravel project? This is a simple CRUD generator complete with automated testing suite.

## Documentation

For installation instructions and usage, please take a look at the [official documentation](https://nafiesl.github.io/SimpleCrudGenerator/docs/).

## About this package

This package contains artisan `make:crud` commands to create a simple CRUD feature with test classes on our Laravel 5.5 (and later) application. This package is fairly simple, to **boost test-driven development** method on our laravel application.

With this package installed on local environment, we can use (e.g.) `php artisan make:crud Vehicle` command to generate some files :

- `App\Models\Vehicle.php` eloquent model
- `xxx_create_vehicles_table.php` migration file
- `VehicleController.php`
- `index.blade.php` and `forms.blade.php` view file in `resources/views/vehicles` directory
- `resources/lang/vehicle.php` lang file
- `VehicleFactory.php` model factory file
- `VehiclePolicy.php` model policy file in `app/Policies` directory
- `ManageVehiclesTest.php` feature test class in `tests/Feature` directory
- `VehicleTest.php` unit test class in `tests/Unit/Models` directory
- `VehiclePolicyTest.php` unit test class in `tests/Unit/Policies` directory

It will update some file :

- Update `routes/web.php` to add `vehicles` resource route
- Update `app/providers/AuthServiceProvider.php` to add Vehicle model Policy class in `$policies` property

It will also create this file **if it not exists** :

- `resources/lang/app.php` lang file if it not exists
- `tests/BrowserKitTest.php` base Feature TestCase class if it not exists

#### Main purpose

The main purpose of this package is for **faster Test-driven Development**, it generates model CRUD scaffolds complete **with Testing Classes** which will use [Laravel Browserkit Testing](https://github.com/laravel/browser-kit-testing) package and [PHPUnit](https://packagist.org/packages/phpunit/phpunit).

## How to install

#### For Laravel 8.x

```bash
# Get the package
$ composer require luthfi/simple-crud-generator:^2.0
```

#### For Laravel 5.6 to 7.x

```bash
# Get the package
$ composer require luthfi/simple-crud-generator:^1.0
```

#### For Laravel 5.5

To use this package on laravel 5.5, we need to **add the package** (with browserkit) within `require-dev` in `composer.json` file, like so :

```bash
# Install required package for laravel/browser-kit-testing
$ composer require symfony/css-selector:^3.0

# Get the package
$ composer require luthfi/simple-crud-generator 1.2.* --dev
```

> The package will **auto-discovered**.

## How to use
Just type in terminal `$ php artisan make:crud ModelName` command, it will create simple Laravel CRUD files of given **model name** completed with tests.

For example we want to create CRUD for '**App\Models\Vehicle**' model.

```bash
$ php artisan make:crud-simple Vehicle

Vehicle resource route generated on routes/web.php.
Vehicle model generated.
Vehicle table migration generated.
VehicleController generated.
Vehicle index view file generated.
Vehicle form view file generated.
lang/app.php generated.
vehicle lang files generated.
Vehicle model factory generated.
Vehicle model policy generated.
AuthServiceProvider class has been updated.
BrowserKitTest generated.
ManageVehiclesTest generated.
VehicleTest (model) generated.
VehiclePolicyTest (model policy) generated.
CRUD files generated successfully!
```

Make sure we have **set database credential** on `.env` file, then :

```bash
$ php artisan migrate
$ php artisan serve
```

Then visit our application url: `http://localhost:8000/vehicles`.

#### Usage on Fresh Install Laravel 8.x

In this example, we are using the [laravel installer](https://packagist.org/packages/laravel/installer) package to install new laravel project.

```bash
# This is example commands for Ubuntu users.
$ laravel new project-directory
$ cd project-directory
$ composer require laravel/ui
$ php artisan ui bootstrap --auth
$ npm install && npm run dev # Might need to run twice, minimum requirement: NodeJS v12.x
$ vim .env # Edit your .env file to update database configuration

# Install the package
$ composer require luthfi/simple-crud-generator:^2.0

# I really suggest "git commit" your project right before you run the make:crud command
$ php artisan make:crud Vehicle # Model name in singular

$ php artisan migrate
$ php artisan serve
# Visit your route http://127.0.0.1:8000
# Register as a new user
# Visit your route http://127.0.0.1:8000/vehicles

# Run the unit tests
$ vim phpunit.xml # Remove comments on the DB_CONNECTION and DB_DATABASE lines
$ vendor/bin/phpunit
```

#### Available Commands

```bash
# Create Full CRUD feature with tests
$ php artisan make:crud ModelName

# Create Full CRUD feature with tests and Bootstrap 3 views
$ php artisan make:crud ModelName --bs3

# Create Simple CRUD feature with tests
$ php artisan make:crud-simple ModelName

# Create Simple CRUD feature with tests and Bootstrap 3 views
$ php artisan make:crud-simple ModelName --bs3

# Create API CRUD feature with tests
$ php artisan make:crud-api ModelName
```

#### Model Attribute/column

The Model and table will **only have 2 pre-definded** attributes or columns : **title** and **description** on each generated model and database table. You can continue working on other column on the table.

#### Bootstrap 4 Views

The generated view files **use Bootstrap 4 by default** (for Laravel 5.6 and later).

#### Bootstrap 3 Views

We can also generates views that use Bootstrap 3 with `--bs3` command option, eg for Laravel version 5.5.

#### For API

If we want to generate API Controller with feature tests, we use following command :

```bash
$ php artisan make:crud-api Vehicle
```

By default, we use Laravel **Token Based Authentication**, so we need to update our user model.

1. Add `api_token` **column** on our **users_table_migration**.
2. Add `api_token` as **fillable** property on **User model**.
3. Add `api_token` **field** on our **UserFactory**.

#### API Usage

The generated API is a REST API, using GET and POST verbs, with a URI of `/api/modelname`.

Example code for calling the generated API, using Guzzle:

    // Read data a specific Vehicle record...
    $uri = 'http://your-domain.com/api/vehicles/'.$vehicleID;
    $headers = ['Authorization' => 'Bearer '.$apiToken];

    $client = new \GuzzleHttp\Client();
    $res = $client->request('GET', $uri, ['headers' => $headers]);

    // Create a new Vehicle record...
    $uri = 'http://your-domain.com/api/vehicles';
    $headers = ['Authorization' => 'Bearer '.$apiToken];
    $payload = json_encode([
        'title' => 'Vehicle Name 1',
        'description' => 'Vehicle Description 1',
    ]);

    $client = new \GuzzleHttp\Client();
    $res = $client->request('POST', $uri, ['body' => $payload, 'headers' => $headers]);

The generated functional tests will give you examples of how to adapt this code for other call types.

## Config file

You can configure your own by publishing the config file:

```bash
$ php artisan vendor:publish --provider="Luthfi\CrudGenerator\ServiceProvider" --tag=config
```

That will generate `config/simple-crud.php` file.

By default, this package have some configuration:

```php
<?php

return [
    // The master view layout that generated views will extends
    'default_layout_view' => 'layouts.app',

    // The base test case class path for generated testing classes
    'base_test_path' => 'tests/BrowserKitTest.php',

    // The base test class full name
    'base_test_class' => 'Tests\BrowserKitTest',
];
```

## Publishing Stub Files

Stub files is the templates which we use to generate the code for each model classes and files. We can customize the stub files as we needed by publishing them to our project directory.

```bash
$ php artisan vendor:publish --provider="Luthfi\CrudGenerator\ServiceProvider" --tag=stubs
```

That will generate stub files on `stubs/simple-crud` directory. Now we can change some stub files based on our project needs.

## Attention

- The package will creates the **Model** class file, the command will stop if the **Model already exists**.
- **You need** a `resources/views/layouts/app.blade.php` view file, simply create one with `php artisan make:auth` command. You can change this configuration via the `config/simple-crud.php` file.

## Screenshots

Visit your application in new resource route : `http://127.0.0.1:8000/vehicles`

![Generated CRUD page by Simple CRUD Generator](screenshots/simple-crud-generator-01.jpg)

## Generated testing suite

Next, let us try the generated testing suite. To use the generated testing classes, we can set the database environment using ***in-memory* database SQLite**. Open `phpunit.xml`. Add two lines below on the `env` :

```xml
<phpunit>
    <!-- ..... -->
    <php>
        <!-- ..... -->
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
    </php>
</phpunit>
```

Then run PHPUnit

```bash
$ vendor/bin/phpunit
```

All tests should be passed.

![Generated Testing Suite on Simple CRUD Generator](screenshots/simple-crud-generator-02.jpg)

## Issue/Proposal

If you find any issue, or want to propose some idea to help this package better, please [create an issue](https://github.com/nafiesl/SimpleCrudGenerator/issues) in this github repo.

## License

This package is open-sourced software licensed under the [MIT license](LICENSE).


text:
ractive-adapter-yui
===================

RactiveJS adapter for YUI


text:
'use strict';

var unherit = require('unherit');
var xtend = require('xtend');
var Compiler = require('./lib/compiler.js');

module.exports = stringify;
stringify.Compiler = Compiler;

function stringify(options) {
  var Local = unherit(Compiler);
  Local.prototype.options = xtend(Local.prototype.options, this.data('settings'), options);
  this.Compiler = Local;
}


text:
(function(){
	var openLink 			= document.querySelector('#open-links');
	var closeLink 			= document.querySelector('#close-links');
	var mastheadLink 	= document.querySelector('.mastnav-links');

	openLink.addEventListener('click', function() {
		openLink.classList.remove('show');
		openLink.classList.add('hide');

		closeLink.classList.remove('hide');
		closeLink.classList.add('show');

		mastheadLink.classList.remove('hide');
	}, false);

	closeLink.addEventListener('click', function() {
		openLink.classList.remove('hide');
		openLink.classList.add('show');

		closeLink.classList.remove('show');
		closeLink.classList.add('hide');

		mastheadLink.classList.add('hide');
	}, false);
})();


text:
#ifndef __ASM_SIGINFO_H
#define __ASM_SIGINFO_H

#define __ARCH_SI_PREAMBLE_SIZE	(4 * sizeof(int))

#include <asm-generic/siginfo.h>

#endif


text:
CancelOrders
============

Cancel orders in trading simulation


text:
<?php

/**
 * This file is part of the Branches package.
 * For the full license information, see the file LICENSE.
 *
 * @author   Alberto Piu <alberteddu@gmail.com>
 * @license  MIT
 */
namespace Branches\Extension;

use Branches\Component\ComponentHolder;

/**
 * Interface UrlExtensionInterface.
 */
interface UrlExtensionInterface extends ExtensionInterface
{
    /**
     * @param ComponentHolder $queue
     */
    public function getUrlSegmentVoters(ComponentHolder $queue);
}


text:
using System.Collections.Generic;
using IBM.WatsonDeveloperCloud.Http;
using IBM.WatsonDeveloperCloud.Service;
using IBM.WatsonDeveloperCloud.ToneAnalyzer.v3.Model;
using Newtonsoft.Json;
using System;

namespace IBM.WatsonDeveloperCloud.ToneAnalyzer.v3
{
    public class ToneAnalyzerService : WatsonService, IToneAnalyzerService
    {
        const string SERVICE_NAME = "tone_analyzer";
        const string URL = "https://gateway.watsonplatform.net/tone-analyzer/api";
        private string _versionDate;
        public string VersionDate
        {
            get { return _versionDate; }
            set { _versionDate = value; }
        }

        public ToneAnalyzerService() : base(SERVICE_NAME, URL)
        {
            if(!string.IsNullOrEmpty(this.Endpoint))
                this.Endpoint = URL;
        }

        public ToneAnalyzerService(string userName, string password, string versionDate) : this()
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException(nameof(userName));

            if (string.IsNullOrEmpty(password))
                throw new ArgumentNullException(nameof(password));

            this.SetCredential(userName, password);
            if(string.IsNullOrEmpty(versionDate))
                throw new ArgumentNullException("versionDate cannot be null.");

            VersionDate = versionDate;
        }

        public ToneAnalyzerService(IClient httpClient) : this()
        {
            if (httpClient == null)
                throw new ArgumentNullException(nameof(httpClient));

            this.Client = httpClient;
        }

        public ToneAnalysis Tone(ToneInput body, string tones = null, bool? sentences = null)
        {
            if (body == null)
                throw new ArgumentNullException(nameof(body));

            if(string.IsNullOrEmpty(VersionDate))
                throw new ArgumentNullException("versionDate cannot be null.");

            ToneAnalysis result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                                .PostAsync($"{this.Endpoint}/v3/tone")
                                .WithArgument("version", VersionDate)
                                .WithArgument("tones", tones)
                                .WithArgument("sentences", sentences)
                                .WithBody<ToneInput>(body)
                                .As<ToneAnalysis>()
                                .Result;
            }
            catch(AggregateException ae)
            {
                throw ae.Flatten();
            }

            return result;
        }

        public UtteranceAnalyses ToneChat(ToneChatInput utterances)
        {
            if (utterances == null)
                throw new ArgumentNullException(nameof(utterances));

            if(string.IsNullOrEmpty(VersionDate))
                throw new ArgumentNullException("versionDate cannot be null.");

            UtteranceAnalyses result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                                .PostAsync($"{this.Endpoint}/v3/tone_chat")
                                .WithArgument("version", VersionDate)
                                .WithBody<ToneChatInput>(utterances)
                                .As<UtteranceAnalyses>()
                                .Result;
            }
            catch(AggregateException ae)
            {
                throw ae.Flatten();
            }

            return result;
        }
    }
}


text:
ACCEPTED

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

#### Published in
in Nannenga-Bremekamp, Yamamoto & Sharma, Proc. K. Ned. Akad. Wet. , Ser. C, Biol. Med. Sci. 87(4): 456 (1984)

#### Original name
Stemonaria rufipes Nann.-Bremek. & Y. Yamam., 1984

### Remarks
null


text:
package tictactoe.GameMechanics;

import java.util.ArrayList;
import java.util.List;

public class BoardHistory {

    private List<Board> boards = new ArrayList<Board>();

    /**
     * Ctor: board histories always start with just an empty board.
     */
    public BoardHistory() {
        boards.add(new Board());
    }

    public void addBoard(Board board) {
        boards.add(board);
    }

    public List<Board> getBoards() {
        return boards;
    }

    public int getNumBoards() {
        return boards.size();
    }

    public Board getLatestBoard() {
        int numBoards = boards.size();
        return boards.get(numBoards - 1);
    }

    public void printLatestBoard() {
        Board currentBoard = getLatestBoard();
        String prettyPrintedString = currentBoard.toPrettyString();
        System.out.println(prettyPrintedString + "\n");
    }
}


text:
require 'prime'

class Integer
	#returns all positive factors of an Integer
	def factors
    	(1..self).select { |n| (self % n).zero? }
	end

	#returns true if self is a prime number, false otherwise
	def prime?
		Prime.prime?(self)
	end
end

class PMeth

	# Returns a random integer that array can be divided by to get another integer (other than the array length itself)
	# by getting all the factors of the array length and ditching the array length
	def self.division(array)
		array.length.factors.select {|n| n != array.length}.sample
	end

	# Returns a new permutation that has had a randomly sized sub-section re-ordered by shuffle
	def self.chunk_mutate(permutation)
		if permutation.length.prime? # if there are a prime number of objects in the permutation
			ig = rand(permutation.length) # choose a random object to ignore - to add back at its original index after mutation
			ig_obj = permutation[ig] # save the object
			permutation.delete_at(ig)
		end
		x = 0 # x is the randomly chosen size of chunks that permutation will be split into
		until x >= 2 # the chunk to be re-ordered must have at least 2 objects
			x = division(permutation)
		end
		sliced = permutation.each_slice(x).to_a # permutation is sliced into chunks of size x
		e = rand(sliced.length) # one of the chunks is chosen at random...
		chunk = sliced[e]
		until sliced[e] != chunk
			sliced[e] = sliced[e].shuffle # ... and the objects within are shuffled
		end
		mutant = sliced.flatten
		if ig != nil
			mutant.insert(ig, ig_obj)
		end
		return mutant
	end

	# Returns a new permutation where two of the objects, chosen at random, have swapped positions (indices)
	def self.swap_mutate(permutation)
		a = b = x = y = 0
		until a != b
			x = rand(permutation.length) # randomly choose two indices x and y...
			y = rand(permutation.length)
			a = permutation[x] # ... and call the objects at these indices a and b
			b = permutation[y]
		end
		mutant = permutation.dup # create a new permutation...
		mutant[x] = b # ... with object b at index x...
		mutant[y] = a # ... and object a at index y
		return mutant
	end

	# Returns a new permutation where an object, chosen at random, has swapped position with one of it's immediate neighbours
	def self.adjacent_swap(permutation)
		x = rand(permutation.length) # randomly choose an index
		coin = rand(2) # a 50% chance for an object to swap with it's left or right neighbour
		if x == 0 # object at index 0 of array can only swap with index 1
			y = x + 1
		elsif x == permutation.length-1 # object at index -1 of array can only swap with index -2
			y = x - 1
		elsif coin == 0
			y = x + 1
		elsif coin == 1
			y = x - 1
		end
		mutant = permutation.dup
		mutant[x] = permutation[y]
		mutant[y] = permutation[x]
		return mutant
	end

	# Returns a permutation whose objects are ordered partly like parent_1 permutation, and partly like parent_2 permutation
	def self.recombine(parent_1, parent_2)
		x = division(parent_1) # the randomly chosen size of chunks that permutations will be split into
		if parent_1.length.prime? # to compensate for permutations with a prime number of objects:
			ig = rand(parent_1.length) # choose a random object to ignore - to add back at its original index after mutation
			p2_ig = parent_2.index(parent_1[ig]) # choose the same object from parent_2
			parent_1_reduced, parent_2_reduced = parent_1.dup, parent_2.dup # then create duplicates of the parent arrays...
			parent_1_reduced.delete_at(ig); parent_2_reduced.delete_at(p2_ig) # .. and remove the ignored object from these duplicates
			x = division(parent_1_reduced) # choose a new chunk size for reduced parent permutations, that no longer have a prime number of objects
			p1s, p2s = parent_1_reduced.each_slice(x).to_a, parent_2_reduced.each_slice(x).to_a # slice the reduced parent permutations into chunks of size x
		else
			p1s, p2s = parent_1.each_slice(x).to_a, parent_2.each_slice(x).to_a # if permutation lengths are non-prime, just slice the parent permutations into chunks of size x
		end
		chosen = rand(p2s.length) # choose a chunk to have parent_2 ordered objects in child permutation
		child = p1s.flatten.dup # un-modified child permutation to accept chunk from parent_2 (and possibly ignored object)
		p1s[chosen].each do |i| # place each object in chosen parent_1 chunk into the index it's corresponding object (from parent_2) occupies in parent_1:
			index = p1s[chosen].index(i) # the index of each object in the chosen parent_1 chunk...
			p2_object = p2s[chosen][index] # ... the object at that index in the chosen parent_2 chunk...
			p1_index = p1s.flatten.index(p2_object) # ... the index of that object (from parent_2 chunk) in parent_1
			unless p2s[chosen].include?(p1s[chosen][index]) # unless the chosen chunk from parent_2 includes objects from the chosen parent_1 chunk...
				child[p1_index] = p1s[chosen][index] # ... the object from the chosen chunk in parent_1 is added to p1_index in child
				chosen_index = p1s.flatten.index(p1s[chosen][index]) # index of object from parent_1's chosen chunk in parent_1
				child[chosen_index] = p2s[chosen][index] # swapping the indices of objects in chunks from parents, to give their indices in child
			end
		end
		if ig != nil # if the permutations are a prime number in length, we now add the ignored object from earlier into child
			if p2s[chosen].include?(parent_2[p2_ig]) # add the ignored object from parent_2 if it's in the chosen chunk...
				child.insert(p2_ig, parent_2[p2_ig])
			else
				child.insert(ig, parent_1[ig]) # ...otherwise add the ignored object from parent_1
			end
		end
		return child
	end
end


text:
package vexatos.peccatura.gui;

import cpw.mods.fml.common.network.IGuiHandler;
import fox.spiteful.avaritia.tile.TileEntityDireCrafting;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;

/**
 * @author Vexatos
 */
public class GuiHandler implements IGuiHandler {

	@Override
	public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
		if(ID == 0) {
			return new GUIAutomaTable(player.inventory, world, x, y, z, (TileEntityDireCrafting) world.getTileEntity(x, y, z));
		}
		return null;
	}

	@Override
	public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
		if(ID == 0) {
			return new ContainerAutomaTable(player.inventory, world, x, y, z, (TileEntityDireCrafting) world.getTileEntity(x, y, z));
		}
		return null;
	}
}


text:
@interface UIView (Frame)

// 如果@property在分类里面使用只会自动声明get,set方法,不会实现,并且不会帮你生成成员属性
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGSize size;
@property (nonatomic, assign) CGPoint origin;

@end


text:
pycdec is a Python interface to cdec

## Installation

Build and install pycdec:

	python setup.py install

Alternatively, run `python setup.py build_ext --inplace` and add the `python/` directory to your `PYTHONPATH`.

To re-build pycdec from the cython source, modify setup.py in the following ways:
  * Add this input statement: from Cython.Build import cythonize
  * Change the source file from cdec/\_cdec.cpp to cdec/\_cdec.pyx
  * Add language='c++' as a property to ext\_modules (e.g. right after extra\_link\_args)
  * In the final setup block, change ext\_modules=ext\_modules to ext\_modules=cythonize(ext\_modules)

Then just build and install normally, as described above.

To rebuild cdec/\_cdec.cpp, run:

 	cython --cplus \_cdec.pyx

## Grammar extractor

Compile a parallel corpus and a word alignment into a suffix array representation:

	python -m cdec.sa.compile -f f.txt -e e.txt -a a.txt -o output/ -c extract.ini

Or, if your parallel corpus is in a single-file format (with source and target sentences on a single line, separated by a triple pipe `|||`), use:

	python -m cdec.sa.compile -b f-e.txt -a a.txt -o output/ -c extract.ini

Extract grammar rules from the compiled corpus:

	cat input.txt | python -m cdec.sa.extract -c extract.ini -g grammars/ -z

This will create per-sentence grammar files in the `grammars` directory and output annotated input suitable for translation with cdec.

Extract rules in stream mode:

    python -m cdec.sa.extract -c extract.ini -t -z

This will enable stdio interaction with the following types of lines:

Extract grammar:

    context ||| sentence ||| grammar_file

Learn (online mode, specify context name):

    context ||| sentence ||| reference ||| alignment

Drop (online mode, specify context name):

    context ||| drop

## Library usage

A basic demo of pycdec's features is available in `examples/test.py`.
Other examples are given in [the paper](http://victor.chahuneau.fr/pub/pycdec/) describing pycdec.

More documentation will come as the API becomes stable.

---

pycdec was contributed by [Victor Chahuneau](http://victor.chahuneau.fr)


text:
static __inline__ __attribute__((__clang_arm_builtin_alias(__builtin_arm_nop))) // expected-error {{'__clang_arm_builtin_alias' attribute can only be applied to an ARM builtin}}
void
nop(void);

static __inline__ __attribute__((__clang_arm_builtin_alias)) // expected-error {{'__clang_arm_builtin_alias' attribute takes one argument}}
void
noparens(void);

static __inline__ __attribute__((__clang_arm_builtin_alias())) // expected-error {{'__clang_arm_builtin_alias' attribute takes one argument}}
void
emptyparens(void);

static __inline__ __attribute__((__clang_arm_builtin_alias("string literal"))) // expected-error {{'__clang_arm_builtin_alias' attribute requires parameter 1 to be an identifier}}
void
stringliteral(void);

static __inline__ __attribute__((__clang_arm_builtin_alias(1))) // expected-error {{'__clang_arm_builtin_alias' attribute requires parameter 1 to be an identifier}}
void
integer(void);

static __inline__ __attribute__((__clang_arm_builtin_alias(__builtin_arm_nop, 2))) // expected-error {{'__clang_arm_builtin_alias' attribute takes one argument}}
void
twoargs(void);

static __attribute__((__clang_arm_builtin_alias(__builtin_arm_nop))) // expected-error {{'__clang_arm_builtin_alias' attribute only applies to functions}}
int variable;


text:
import { H2, H6 } from "@blueprintjs/core"
import * as React from 'react';
import { style } from 'typestyle';

const Bio = (props: {className?: string}) => {
  return (

Rootul Patel

          Software Engineer @

            AWS

  );
};

// tslint:disable-next-line
const profilePicture = require('./profile-1.png');

const avatar = style({
  borderRadius: '100%',
  marginBottom: '10px',
  width: '150px',
});

export default Bio;


text:
var $ = jQuery;
$(function () {
    var Page = (function () {
        var $navArrows = $('#nav-arrows'),
                $nav = $('#nav-dots > span'),
                slitslider = $('#slider').slitslider({
            onBeforeChange: function (slide, pos) {

                $nav.removeClass('nav-dot-current');
                $nav.eq(pos).addClass('nav-dot-current');

            }
        }),
                init = function () {

                    initEvents();

                },
                initEvents = function () {

                    // add navigation events
                    $navArrows.children(':last').on('click', function () {

                        slitslider.next();
                        return false;

                    });

                    $navArrows.children(':first').on('click', function () {

                        slitslider.previous();
                        return false;

                    });

                    $nav.each(function (i) {

                        $(this).on('click', function (event) {

                            var $dot = $(this);

                            if (!slitslider.isActive()) {

                                $nav.removeClass('nav-dot-current');
                                $dot.addClass('nav-dot-current');

                            }

                            slitslider.jump(i + 1);
                            return false;

                        });

                    });

                };

        return {init: init};

    })();

    Page.init();

    /**
     * Notes:
     *
     * example how to add items:
     */

    /*

     var $items  = $('

some text

bla bla
Margi Clarke

');

     // call the plugin's add method
     ss.add($items);

     */

});


text:
#ifndef THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_TOCO_CMDLINE_FLAGS_H_
#define THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_TOCO_CMDLINE_FLAGS_H_

#include <string>
#include <vector>
#include "tensorflow/contrib/lite/toco/args.h"
#include "tensorflow/contrib/lite/toco/toco_flags.pb.h"
#include "tensorflow/contrib/lite/toco/types.pb.h"

namespace toco {
// Parse and remove arguments handled from toco. Returns true if parsing
// is successful. msg has the usage string if there was an error or
// "--help" was specified
bool ParseTocoFlagsFromCommandLineFlags(int* argc, char* argv[], string* msg,
                                        ParsedTocoFlags* parsed_toco_flags_ptr);
// Populate the TocoFlags proto with parsed_toco_flags data.
void ReadTocoFlagsFromCommandLineFlags(const ParsedTocoFlags& parsed_toco_flags,
                                       TocoFlags* toco_flags);

}  // namespace toco

#endif  // THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_TOCO_CMDLINE_FLAGS_H_


text:
var str2color = require("./");
var test = require("tape");

test('str2color', function (assert) {
    assert.plan(4);
    assert.strictEqual(str2color(), '#5A1000');
    assert.strictEqual(str2color(''), '#5A1000');
    assert.strictEqual(str2color(' '), '#5A1000');
    assert.strictEqual(str2color('hola'), '#212B78');
});


text:
module.exports = function (app) {
// home route
app.get('/', function(req, res){
  res.render('index', { title: 'Home-SmartStreet'});
});
app.get('/home',function(req, res){
  res.render('index', { title: 'Home-SmartStreet', pageName:'Home'});
});

var vehicles=require('../app/controllers/vehicles')
app.get('/accidentmap',vehicles.index);
app.get('/cyclespot',function(req, res){
  res.render('safemap', { title: 'SafeMap-SmartStreet',pageName:'Demon' });
});
app.get('/cyclespot',vehicles.cyclesafe);

app.get('/contact', function(req, res){
  res.render('contact', { title: 'Contact-SmartStreet',pageName:'Contact' });
});
app.get('/about', function(req, res){
  res.render('about', { title: 'About-SmartStreet',pageName:'About' });
});
}


text:
Spree::PaymentMethod.class_eval do

  scope :loyalty_points_type, -> { where(type: 'Spree::PaymentMethod::LoyaltyPoints') }

  def self.loyalty_points_id_included?(method_ids)
    loyalty_points_type.where(id: method_ids).size != 0
  end

end