text:
package edu.isi.karma.model.serialization;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;

import edu.isi.karma.modeling.Namespaces;
import edu.isi.karma.modeling.Prefixes;
import edu.isi.karma.rep.alignment.Label;
import edu.isi.karma.rep.model.Argument;
import edu.isi.karma.rep.model.ArgumentType;
import edu.isi.karma.rep.model.Atom;
import edu.isi.karma.rep.model.ClassAtom;
import edu.isi.karma.rep.model.IndividualPropertyAtom;
import edu.isi.karma.rep.sources.Attribute;
import edu.isi.karma.rep.sources.AttributeRequirement;
import edu.isi.karma.rep.sources.IOType;
import edu.isi.karma.rep.sources.Source;
import edu.isi.karma.rep.sources.WebService;
import edu.isi.karma.webserver.ServletContextParameterMap;
import edu.isi.karma.webserver.ServletContextParameterMap.ContextParameter;

public class WebServiceLoader extends SourceLoader
{

	private static Logger logger = LoggerFactory.getLogger(WebServiceLoader.class);
	private static WebServiceLoader instance = null;
	private final int DEFAULT_SERVICE_RESULTS_SIZE = 10;

	protected WebServiceLoader() {
		      // Exists only to defeat instantiation.
	}

	public static WebServiceLoader getInstance() {
		if (instance == null) {
			instance = new WebServiceLoader();
		}
		return instance;
	}

    @Override
	public WebService getSourceByUri(String uri) {

		Model m = Repository.Instance().getNamedModel(uri);
		if (m == null)
			return null;

		WebService service = importSourceFromJenaModel(m);
		return service;
	}

    @Override
	public void deleteSourceByUri(String uri) {
		Repository.Instance().clearNamedModel(uri);

		String service_id = uri.substring(uri.lastIndexOf("/") + 1, uri.length() - 1);
		String dir = ServletContextParameterMap.getParameterValue(ContextParameter.USER_DIRECTORY_PATH) + Repository.Instance().SERVICE_REPOSITORY_REL_DIR;
		String fileName = service_id + Repository.Instance().getFileExtension(Repository.Instance().LANG);
		File f = new File(dir + fileName);

		try {
		if (f.exists()) {
			if (!f.delete())
				logger.debug("The file " + fileName + " cannot be deleted from " + dir);
			else
				logger.debug("The file " + fileName + " has been deleted from " + dir);
		} else
			logger.debug("The file " + fileName + " does not exist in " + dir);
		} catch (Throwable t) {
			logger.debug("cannot delete the file " + fileName + " from " + dir + " because " + t.getMessage());
		}
	}

	/**
	 * returns the service id, name, address of all services in the repository
	 * @param serviceLimit: maximum number of results, null value means all the services
	 * @return
	 */
    @Override
	public List<Source> getSourcesAbstractInfo(Integer serviceLimit) {

		List<Source> serviceList = new ArrayList<Source>();

		Model model = Repository.Instance().getModel();

		String service_id = "";
		String service_name = "";
		String service_address = "";

		// Create a new query
		String queryString =
			"PREFIX " + Prefixes.KARMA + ": <" + Namespaces.KARMA + "> \n" +
			"PREFIX " + Prefixes.HRESTS + ": <" + Namespaces.HRESTS + "> \n" +
			"SELECT ?s ?name ?address \n" +
			"WHERE { \n" +
			"      ?s a " + Prefixes.KARMA + ":Service . \n" +
			"      OPTIONAL {?s " + Prefixes.HRESTS + ":hasAddress ?address .} \n" +
			"      OPTIONAL {?s " + Prefixes.KARMA + ":hasName ?name .} \n" +
			"      } \n";

		if (serviceLimit != null) {
			if (serviceLimit.intValue() < 0) serviceLimit = DEFAULT_SERVICE_RESULTS_SIZE;
			queryString += "LIMIT " + String.valueOf(serviceLimit.intValue() + "\n");
		}

		logger.debug("query= \n" + queryString);

		Query query = QueryFactory.create(queryString);
		// Execute the query and obtain results
		QueryExecution qexec = QueryExecutionFactory.create(query, model);

		try {
			ResultSet results = qexec.execSelect() ;

			if (!results.hasNext())
				logger.info("query does not return any answer.");

//			ResultSetFormatter.out(System.out, results, query) ;

			for ( ; results.hasNext() ; )
			{
				QuerySolution soln = results.nextSolution() ;

				RDFNode s = soln.get("s") ;       // Get a result variable by name.
				RDFNode name = soln.get("name") ;       // Get a result variable by name.
				RDFNode address = soln.get("address") ;       // Get a result variable by name.

				if (s == null) {
					logger.info("service id is null.");
					continue;
				}

				String service_uri = s.toString();
				service_id = service_uri.substring(service_uri.lastIndexOf("/") + 1, service_uri.length() - 1);

				logger.debug("service uri: " + service_uri);
				logger.debug("service id: " + service_id);
				if (name != null && name.isLiteral()) service_name = name.asLiteral().getString();
				logger.debug("service name: " + service_name);
				if (address != null && address.isLiteral()) service_address = address.asLiteral().getString();
				logger.debug("service address: " + service_address);

				if (service_id.trim().length() > 0)
					serviceList.add(new WebService(service_id, service_name, service_address));
				else
					logger.info("length of service id is zero.");
			}

			return serviceList;
		} catch (Exception e) {
			logger.info(e.getMessage());
			return null;
		} finally {
			qexec.close() ;
		}
	}

	/**
	 * returns all the services in the repository along with their complete information
	 * probably this method is not useful since fetching all the services with their complete
	 * information takes long time.
	 * @return
	 */
    @Override
	public List<Source> getSourcesDetailedInfo(Integer serviceLimit) {

		List<Source> serviceList = getSourcesAbstractInfo(serviceLimit);
		List<Source> serviceListCompleteInfo = new ArrayList<Source>();
		for (Source s : serviceList) {
			serviceListCompleteInfo.add(getSourceByUri(s.getUri()));
		}
		return serviceListCompleteInfo;
	}

	public WebService getServiceByAddress(String address) {

		String uri = getServiceUriByServiceAddress(address);
		Model m = Repository.Instance().getNamedModel(uri);
		if (m == null)
			return null;

		WebService service = importSourceFromJenaModel(m);
		return service;
	}

	public void deleteServiceByAddress(String address) {

		String uri = getServiceUriByServiceAddress(address);
		Repository.Instance().clearNamedModel(uri);
	}

	private String getServiceUriByServiceAddress(String address) {

		Model model = Repository.Instance().getModel();

		// Create a new query
		String queryString =
			"PREFIX " + Prefixes.KARMA + ": <" + Namespaces.KARMA + "> \n" +
			"PREFIX " + Prefixes.HRESTS + ": <" + Namespaces.HRESTS + "> \n" +
			"SELECT ?s \n" +
			"WHERE { \n" +
			"      ?s a " + Prefixes.KARMA + ":Service . \n" +
			"      ?s " + Prefixes.HRESTS + ":hasAddress \"" + address + "\"^^hrests:URITemplate . \n" +
			"      } \n";

		logger.debug(queryString);

		Query query = QueryFactory.create(queryString);
		// Execute the query and obtain results
		QueryExecution qexec = QueryExecutionFactory.create(query, model);

		try {
			ResultSet results = qexec.execSelect() ;

			if (!results.hasNext())
				logger.info("query does not return any answer.");

//			ResultSetFormatter.out(System.out, results, query) ;

			String serviceURI = "";
			for ( ; results.hasNext() ; )
			{
				QuerySolution soln = results.nextSolution() ;
				RDFNode x = soln.get("s") ;       // Get a result variable by name.
				serviceURI = x.toString();
				logger.info("Service with id " + x.toString() + " has been found with the address " + address);
				break;
			}

			return serviceURI;
		} catch (Exception e) {
			logger.info("Exception in finding a service with the address " + address + " in service repository.");
			return null;
		} finally {
			qexec.close() ;
		}

	}

	/**
	 * Searches the repository to find the services that the semantic model parameter is contained in
	 * their input model.
	 * @param semanticModel The input model whose pattern will be searched in the repository
	 * @return a hashmap of all found services and a mapping from the found service parameters to the model parameters.
	 * This help us later to how to join the model's corresponding source and the matched service
	 */
	public Map<WebService, Map<String, String>> getServicesByInputPattern(edu.isi.karma.rep.model.Model semanticModel,
			Integer serviceLimit) {

		if (semanticModel == null || semanticModel.getAtoms() == null
				|| semanticModel.getAtoms().size() == 0) {
			logger.info("The input model is nul or it does not have any atom");
			return null;
		}

		Map<WebService, Map<String, String>> servicesAndMappings =
			new HashMap<WebService, Map<String,String>>();

		Map<String, Map<String, String>> serviceIdsAndMappings =
			semanticModel.findInServiceInputs(Repository.Instance().getModel(), serviceLimit);

		if (serviceIdsAndMappings == null)
			return null;

		for (String serviceId : serviceIdsAndMappings.keySet()) {
			Model m = Repository.Instance().getNamedModel(serviceId);
			if (m != null)
				servicesAndMappings.put(importSourceFromJenaModel(m), serviceIdsAndMappings.get(serviceId));
		}

		return servicesAndMappings;
	}

	/**
	 * Searches the repository to find the services that the semantic model parameter is contained in
	 * their output model.
	 * @param semanticModel The input model whose pattern will be searched in the repository
	 * @return a hashmap of all found services and a mapping from the found service parameters to the model parameters.
	 * This help us later to how to join the model's corresponding source and the matched service
	 */
	public Map<WebService, Map<String, String>> getServicesByOutputPattern(edu.isi.karma.rep.model.Model semanticModel,
			Integer serviceLimit) {

		if (semanticModel == null || semanticModel.getAtoms() == null
				|| semanticModel.getAtoms().size() == 0) {
			logger.info("The input model is nul or it does not have any atom");
			return null;
		}

		Map<WebService, Map<String, String>> servicesAndMappings =
			new HashMap<WebService, Map<String,String>>();

		Map<String, Map<String, String>> serviceIdsAndMappings =
			semanticModel.findInServiceOutputs(Repository.Instance().getModel(), serviceLimit);

		if (serviceIdsAndMappings == null)
			return null;

		for (String serviceId : serviceIdsAndMappings.keySet()) {
			Model m = Repository.Instance().getNamedModel(serviceId);
			if (m != null)
				servicesAndMappings.put(importSourceFromJenaModel(m), serviceIdsAndMappings.get(serviceId));
		}

		return servicesAndMappings;
	}

	/**
	 * Searches the repository to find the services whose input model is contained in the semantic model parameter.
	 * Note that the services in the return list only include the operations that match the model parameter.
	 * @param semanticModel The input model whose pattern will be searched in the repository
	 * @return a hashmap of all found services and a mapping from the found service parameters to the model parameters.
	 * This help us later to how to join the model's corresponding source and the matched service
	 */
	public Map<WebService, Map<String, String>> getServicesWithInputContainedInModel(
			edu.isi.karma.rep.model.Model semanticModel,
			Integer serviceLimit) {

		List<Source> serviceList = getSourcesDetailedInfo(serviceLimit);

		Map<WebService, Map<String, String>> servicesAndMappings =
			new HashMap<WebService, Map<String,String>>();

		Model jenaModel = semanticModel.getJenaModel();
		for (Source service : serviceList) {

			if (!(service instanceof WebService))
				continue;

			edu.isi.karma.rep.model.Model m = ((WebService)service).getInputModel();

			if (m == null)
				continue;

			Map<String, Map<String, String>> serviceIdsAndMappings =
				m.findInJenaModel(jenaModel, null);

			if (serviceIdsAndMappings == null)
				continue;

			Iterator<String> itr = serviceIdsAndMappings.keySet().iterator();
			if (itr.hasNext()) {
				String key = itr.next();
				servicesAndMappings.put((WebService)service, serviceIdsAndMappings.get(key));
			}
		}

		return servicesAndMappings;
	}

	/**
	 * Searches the repository to find the services whose output model is contained in the semantic model parameter.
	 * Note that the services in the return list only include the operations that match the model parameter.
	 * @param semanticModel The input model whose pattern will be searched in the repository
	 * @return a hashmap of all found services and a mapping from the found service parameters to the model parameters.
	 * This help us later to how to join the model's corresponding source and the matched service
	 */
	public Map<WebService, Map<String, String>> getServicesWithOutputContainedInModel(
			edu.isi.karma.rep.model.Model semanticModel,
			Integer serviceLimit) {

		List<Source> serviceList = getSourcesDetailedInfo(serviceLimit);

		Map<WebService, Map<String, String>> servicesAndMappings =
			new HashMap<WebService, Map<String,String>>();

		Model jenaModel = semanticModel.getJenaModel();
		for (Source service : serviceList) {

			if (!(service instanceof WebService))
				continue;

			edu.isi.karma.rep.model.Model m = ((WebService)service).getOutputModel();

			if (m == null)
				continue;

			Map<String, Map<String, String>> serviceIdsAndMappings =
				m.findInJenaModel(jenaModel, null);

			if (serviceIdsAndMappings == null)
				continue;

			Iterator<String> itr = serviceIdsAndMappings.keySet().iterator();
			if (itr.hasNext()) {
				String key = itr.next();
				servicesAndMappings.put((WebService)service, serviceIdsAndMappings.get(key));
			}
		}

		return servicesAndMappings;
	}

	/**
	 * From the service model, returns the service object
	 * @param model
	 * @return
	 */
	@Override
	public WebService importSourceFromJenaModel(Model model) {
		logger.debug("model size: " + model.getGraph().size());

		String service_name = "";
		String service_uri = "";
		String service_id = "";
		String service_address = "";
		String service_method = "";

		// service id
		service_uri = model.getNsPrefixURI("");
		logger.debug("service uri: " + service_uri);

		// service local id
		service_id = service_uri.substring(service_uri.lastIndexOf("/") + 1, service_uri.length() - 1);
		logger.debug("service id: " + service_id);

		Property has_address_property = model.getProperty(Namespaces.HRESTS + "hasAddress");
		Property has_name_property = model.getProperty(Namespaces.KARMA + "hasName");
		Property has_method_property = model.getProperty(Namespaces.HRESTS + "hasMethod");
		Property has_input_property = model.getProperty(Namespaces.KARMA + "hasInput");
		Property has_output_property = model.getProperty(Namespaces.KARMA + "hasOutput");

		Resource service_resource = model.getResource(service_uri);

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// service name
		nodeIterator = model.listObjectsOfProperty(service_resource, has_name_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isLiteral()) {
			service_name = node.asLiteral().getString();
			logger.debug("service name: " + service_name);
		} else
			logger.debug("service does not have a name.");

		// service address
		nodeIterator = model.listObjectsOfProperty(service_resource, has_address_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isLiteral()) {
			service_address = node.asLiteral().getString();
			logger.debug("service address: " + service_address);
		} else
			logger.debug("service does not have an address.");

		// service method
		nodeIterator = model.listObjectsOfProperty(service_resource, has_method_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isLiteral()) {
			service_method = node.asLiteral().getString();
			logger.debug("service method: " + service_method);
		} else
			logger.debug("service does not have a method.");

		List<String> variables = null;
		List<Attribute> inputAttributes = null;
		List<Attribute> outputAttributes = null;
		edu.isi.karma.rep.model.Model inputModel = null;
		edu.isi.karma.rep.model.Model outputModel = null;

		// service variables
		variables = getVariables(model, service_resource);

		// service input
		nodeIterator = model.listObjectsOfProperty(service_resource, has_input_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isResource()) {
			inputAttributes = getAttributes(model, node.asResource(), IOType.INPUT);
			inputModel = getSemanticModel(model, node.asResource());
		} else
			logger.debug("service does not have an input.");

		// service output
		nodeIterator = model.listObjectsOfProperty(service_resource, has_output_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isResource()) {
			outputAttributes = getAttributes(model, node.asResource(), IOType.OUTPUT );
			outputModel = getSemanticModel(model, node.asResource());
		} else
			logger.info("service does not have an output.");

		WebService service = new WebService(service_id, service_name, service_address);
		service.setMethod(service_method);
		service.setVariables(variables);
		service.setInputAttributes(inputAttributes);
		service.setOutputAttributes(outputAttributes);
		service.setInputModel(inputModel);
		service.setOutputModel(outputModel);

		return service;
	}

	private List<String> getVariables(Model model, Resource service_resource) {

		Property has_variable_property = model.getProperty(Namespaces.KARMA + "hasVariable");

		List<String> variables = new ArrayList<String>();
		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// hasAttribute
		nodeIterator = model.listObjectsOfProperty(service_resource, has_variable_property);
		while ( nodeIterator.hasNext()) {
			node = nodeIterator.next();

			if (!node.isResource()) {
				logger.info("object of the hasAttribute property is not a resource.");
				continue;
			}

			variables.add(node.asResource().getLocalName());
		}

		return variables;

	}

	private List<Attribute> getAttributes(Model model, Resource io_resource, String ioType) {

		Property has_attribute_property = model.getProperty(Namespaces.KARMA + "hasAttribute");
		Property has_mandatory_attribute_property = model.getProperty(Namespaces.KARMA + "hasMandatoryAttribute");
		Property has_optional_attribute_property = model.getProperty(Namespaces.KARMA + "hasOptionalAttribute");

		List<Attribute> attList = new ArrayList<Attribute>();

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// hasAttribute
		nodeIterator = model.listObjectsOfProperty(io_resource, has_attribute_property);
		while ( nodeIterator.hasNext()) {
			node = nodeIterator.next();

			if (!node.isResource()) {
				logger.info("object of the hasAttribute property is not a resource.");
				continue;
			}

			attList.add(getAttribute(model, node.asResource(), ioType, AttributeRequirement.NONE));
		}

		// hasMandatoryAttribute
		nodeIterator = model.listObjectsOfProperty(io_resource, has_mandatory_attribute_property);
		while ( nodeIterator.hasNext()) {
			node = nodeIterator.next();

			if (!node.isResource()) {
				logger.info("object of the hasMandatoryAttribute property is not a resource.");
				continue;
			}

			attList.add(getAttribute(model, node.asResource(), ioType, AttributeRequirement.MANDATORY));
		}

		// hasOptionalAttribute
		nodeIterator = model.listObjectsOfProperty(io_resource, has_optional_attribute_property);
		while ( nodeIterator.hasNext()) {
			node = nodeIterator.next();

			if (!node.isResource()) {
				logger.info("object of the hasOptionalAttribute property is not a resource.");
				continue;
			}

			attList.add(getAttribute(model, node.asResource(), ioType, AttributeRequirement.OPTIONAL));
		}

		return attList;

	}

	private Attribute getAttribute(Model model, Resource att_resource, String ioType, AttributeRequirement requirement) {

		String att_id = "";
		String att_name = "";
		String att_groundedIn = "";

		Property has_name_property = model.getProperty(Namespaces.KARMA + "hasName");
		Property is_gounded_in_property = model.getProperty(Namespaces.HRESTS + "isGroundedIn");

		// attribute id
		att_id = att_resource.getLocalName();
		logger.debug("attribute id: " + att_id);

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// attribute name
		nodeIterator = model.listObjectsOfProperty(att_resource, has_name_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isLiteral()) {
			att_name = node.asLiteral().getString();
			logger.debug("attribute name: " + att_name);
		} else
			logger.debug("attribute does not have a name.");

		// attribute grounded In
		nodeIterator = model.listObjectsOfProperty(att_resource, is_gounded_in_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isLiteral()) {
			att_groundedIn = node.asLiteral().getString();
			logger.debug("attribute grounded in: " + att_groundedIn);
		} else
			logger.debug("attribute does not have agroundedIn value.");

		Attribute att = null;
		if (att_groundedIn.length() > 0)
			att = new Attribute(att_id, att_resource.getNameSpace(), att_name, ioType, requirement, att_groundedIn );
		else
			att = new Attribute(att_id, att_resource.getNameSpace(), att_name, ioType, requirement);

		return att;

	}

	private edu.isi.karma.rep.model.Model getSemanticModel(Model model, Resource io_resource) {

		Property has_model_property = model.getProperty(Namespaces.KARMA + "hasModel");
		Property has_atom_property = model.getProperty(Namespaces.KARMA + "hasAtom");

		NodeIterator nodeIterator = null;
		RDFNode modelNode = null;
		RDFNode atomNode = null;

		// hasModel
		nodeIterator = model.listObjectsOfProperty(io_resource, has_model_property);
		if (!nodeIterator.hasNext() || !(modelNode = nodeIterator.next()).isResource()) {
			logger.info("There is no model resource.");
			return null;
		}

		edu.isi.karma.rep.model.Model semanticModel =
			new edu.isi.karma.rep.model.Model(modelNode.asResource().getLocalName());
		List<Atom> atoms = new ArrayList<Atom>();

		// hasAtom
		nodeIterator = model.listObjectsOfProperty(modelNode.asResource(), has_atom_property);
		while ( nodeIterator.hasNext()) {
			atomNode = nodeIterator.next();

			if (!atomNode.isResource()) {
				logger.info("object of the hasAtom property is not a resource.");
				continue;
			}

			atoms.add(getAtom(model, atomNode.asResource()));
		}

		semanticModel.setAtoms(atoms);
		return semanticModel;

	}

	private Atom getAtom(Model model, Resource atom_resource) {

		Property rdf_type = model.getProperty(Namespaces.RDF + "type");

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		String classAtomUri = Namespaces.SWRL + "ClassAtom";
		String propertyAtomUri = Namespaces.SWRL + "IndividualPropertyAtom";

		// atom type
		nodeIterator = model.listObjectsOfProperty(atom_resource, rdf_type);
		if (!nodeIterator.hasNext() || !(node = nodeIterator.next()).isResource()) {
			logger.info("The atom type is not specified.");
			return null;
		}

		if (node.asResource().getURI().equalsIgnoreCase(classAtomUri)) {
			logger.debug("The atom is a ClassAtom");
			return getClassAtom(model, atom_resource);
		}
		else if (node.asResource().getURI().equalsIgnoreCase(propertyAtomUri)) {
			logger.debug("The atom is an IndividualPropertyAtom");
			return getPropertyAtom(model, atom_resource);
		}

		return null;

	}

	private ClassAtom getClassAtom(Model model, Resource atom_resource) {

		String predicateUri = null;
		String predicatePrefix = null;
		String predicateNs = null;

		String argument1Id = null;
		String argument1Type = null;

		Resource attribute = ResourceFactory.createResource(Namespaces.KARMA + "Attribute");
		Resource variable = ResourceFactory.createResource(Namespaces.SWRL + "Variable");

		Property class_predicate_property = model.getProperty(Namespaces.SWRL + "classPredicate");
		Property argument1_property = model.getProperty(Namespaces.SWRL + "argument1");

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// atom class predicate
		nodeIterator = model.listObjectsOfProperty(atom_resource, class_predicate_property);
		if (!nodeIterator.hasNext() || !(node = nodeIterator.next()).isResource()) {
			logger.info("The class predicate resource is not specified.");
			return null;
		}

		predicateUri = node.asResource().getURI();
		logger.debug("The atom predicate is: " + predicateUri);
		predicateNs = node.asResource().getNameSpace();
		predicatePrefix = model.getNsURIPrefix(predicateNs);

		// atom argument1
		nodeIterator = model.listObjectsOfProperty(atom_resource, argument1_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isResource()) {
			argument1Id = node.asResource().getLocalName();
			logger.debug("The atom argument1 is: " + argument1Id);

			if (isInstanceOfTheClass(node.asResource(), attribute))
				argument1Type = ArgumentType.ATTRIBUTE;
			else if (isInstanceOfTheClass(node.asResource(), variable))
				argument1Type = ArgumentType.VARIABLE;

		} else {
			logger.info("atom does not have an argument1.");
			return null;
		}

		Label predicateName = new Label(predicateUri, predicateNs, predicatePrefix);
		Argument arg1 = new Argument(argument1Id, argument1Id, argument1Type);

		ClassAtom classAtom = new ClassAtom(predicateName, arg1);

		return classAtom;

	}

	private IndividualPropertyAtom getPropertyAtom(Model model, Resource atom_resource) {

		String predicateUri = null;
		String predicatePrefix = null;
		String predicateNs = null;

		String argument1Id = null;
		String argument2Id = null;

		String argument1Type = null;
		String argument2Type = null;

		Resource attribute = ResourceFactory.createResource(Namespaces.KARMA + "Attribute");
		Resource variable = ResourceFactory.createResource(Namespaces.SWRL + "Variable");

		Property property_predicate_property = model.getProperty(Namespaces.SWRL + "propertyPredicate");
		Property argument1_property = model.getProperty(Namespaces.SWRL + "argument1");
		Property argument2_property = model.getProperty(Namespaces.SWRL + "argument2");

		NodeIterator nodeIterator = null;
		RDFNode node = null;

		// atom class predicate
		nodeIterator = model.listObjectsOfProperty(atom_resource, property_predicate_property);
		if (!nodeIterator.hasNext() || !(node = nodeIterator.next()).isResource()) {
			logger.info("The property predicate resource is not specified.");
			return null;
		}

		predicateUri = node.asResource().getURI();
		logger.debug("The atom predicate is: " + predicateUri);
		predicateNs = node.asResource().getNameSpace();
		predicatePrefix = model.getNsURIPrefix(predicateNs);

		// atom argument1
		nodeIterator = model.listObjectsOfProperty(atom_resource, argument1_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isResource()) {
			argument1Id = node.asResource().getLocalName();
			logger.debug("The atom argument1 is: " + argument1Id);

			if (isInstanceOfTheClass(node.asResource(), attribute))
				argument1Type = ArgumentType.ATTRIBUTE;
			else if (isInstanceOfTheClass(node.asResource(), variable))
				argument1Type = ArgumentType.VARIABLE;

		} else {
			logger.info("atom does not have an argument1.");
			return null;
		}

		// atom argument2
		nodeIterator = model.listObjectsOfProperty(atom_resource, argument2_property);
		if (nodeIterator.hasNext() && (node = nodeIterator.next()).isResource()) {
			argument2Id = node.asResource().getLocalName();
			logger.debug("The atom argument2 is: " + argument2Id);

			if (isInstanceOfTheClass(node.asResource(), attribute))
				argument2Type = ArgumentType.ATTRIBUTE;
			else if (isInstanceOfTheClass(node.asResource(), variable))
				argument2Type = ArgumentType.VARIABLE;

		} else {
			logger.info("atom does not have an argument2.");
			return null;
		}

		Label predicateName = new Label(predicateUri, predicateNs, predicatePrefix);
		Argument arg1 = new Argument(argument1Id, argument1Id, argument1Type);
		Argument arg2 = new Argument(argument2Id, argument2Id, argument2Type);

		IndividualPropertyAtom propertyAtom = new IndividualPropertyAtom(predicateName, arg1, arg2);

		return propertyAtom;
	}

	private boolean isInstanceOfTheClass(Resource resource, Resource class_resource) {
		Property type_property = ResourceFactory.createProperty(Namespaces.RDF + "type");

		if (resource == null || !resource.isResource())
			return true;

		if (resource.hasProperty(type_property, class_resource))
			return true;
		else
			return false;
	}

	private static void testGetServiceByUri() {
		String uri = "http://isi.edu/integration/karma/services/CDA81BE4-DD77-E0D3-D033-FC771B2F4800#";
		WebService service = WebServiceLoader.getInstance().getSourceByUri(uri);

		if (service != null) {
//			System.out.println(service.getInputModel().getSPARQLConstructQuery());
//			System.out.println(service.getOutputModel().getSPARQLConstructQuery());
			service.print();
		}
	}
	private static void testGetServiceByAddress() {
		String address = "http://api.geonames.org/";
		WebService service = WebServiceLoader.getInstance().getServiceByAddress(address);
		if (service != null) service.print();
	}
	private static void testGetAllServices() {
		List<Source> serviceList = WebServiceLoader.getInstance().getSourcesDetailedInfo(null);
		for (Source s : serviceList) {
			if (s != null) s.print();
		}
	}
	private static void testGetServicesByIOPattern() {
		edu.isi.karma.rep.model.Model semanticModel = new edu.isi.karma.rep.model.Model(null);

//		String geonamesOntology = "http://www.geonames.org/ontology#";
//		String wgs84Ontology = "http://www.w3.org/2003/01/geo/wgs84_pos#";
		String geoOntology = "http://isi.edu/ontologies/geo/current#";

		Label featurePredicatName = new Label(geoOntology + "Feature", geoOntology, "geo");
		Label latPredicatName = new Label(geoOntology + "lat", geoOntology, "geo");
		Label lngPredicatName = new Label(geoOntology + "long", geoOntology, "geo");

		ClassAtom c1 = new ClassAtom(featurePredicatName, new Argument("arg1", "arg1", ArgumentType.ATTRIBUTE));
		IndividualPropertyAtom p1 = new IndividualPropertyAtom(latPredicatName,
				new Argument("arg1", "arg1", ArgumentType.ATTRIBUTE),
				new Argument("arg2", "arg2", ArgumentType.ATTRIBUTE));
		IndividualPropertyAtom p2 = new IndividualPropertyAtom(lngPredicatName,
				new Argument("arg1", "arg1", ArgumentType.ATTRIBUTE),
				new Argument("arg3", "arg3", ArgumentType.ATTRIBUTE));
//		ClassAtom c2 = new ClassAtom(featurePredicatName, new Argument("arg2", "arg2", ArgumentType.ATTRIBUTE));

		semanticModel.getAtoms().add(c1);
//		semanticModel.getAtoms().add(c2);
		semanticModel.getAtoms().add(p1);
		semanticModel.getAtoms().add(p2);

		Map<WebService, Map<String, String>> servicesAndMappings =
				WebServiceLoader.getInstance().getServicesWithInputContainedInModel(semanticModel, null);
//			getServicesByInputPattern(semanticModel, null);

//		Map<Service, Map<String, String>> servicesAndMappings =
//			getServicesByIOPattern(semanticModel, IOType.INPUT, null);

		if (servicesAndMappings == null)
			return;

		for (WebService s : servicesAndMappings.keySet()) {
			if (s != null) System.out.println((s.getUri())); //s.print();
		}

		System.out.println("Mappings from matched source to model arguments:");
		for (WebService s : servicesAndMappings.keySet()) {
			System.out.println("Service: " + s.getId());
			if (servicesAndMappings.get(s) == null)
				continue;
			for (String str : servicesAndMappings.get(s).keySet())
				System.out.println(str + "-------" + servicesAndMappings.get(s).get(str));
		}

	}
	private static void testDeleteServiceByUri() {
		String uri = "http://isi.edu/integration/karma/services/3D579101-2596-2331-53A8-63F949D71C8F#";
		WebServiceLoader.getInstance().deleteSourceByUri(uri);
	}
	public static void main(String[] args) {

//		ServiceBuilder.main(new String[0]);

		boolean test1 = true, test2 = false, test3 = false, test4 = false, test5 = false;
		if (test1) testGetServiceByUri();
		if (test2) testGetServiceByAddress();
		if (test3) testGetServicesByIOPattern();
		if (test4) testGetAllServices();
		if (test5) testDeleteServiceByUri();

	}

}


text:
public class OutputVariableDuplicate {
    String foo() {
        <selection>String var = "";
        if (var == null) {
            return null;
        }</selection>
        System.out.println(var);
        return var;
    }

    String bar() {
        String var = "";
        if (var == null) {
            return null;
        }
        System.out.println(var);
        return var;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/** @jsxRuntime classic */
/** @jsx jsx */
import { HTMLAttributes, useEffect, useState } from 'react';
import { jsx } from '@emotion/react';
import copy from 'clipboard-copy';

import { CheckIcon } from '@keystone-ui/icons/icons/CheckIcon';
import { Copy } from '../icons/Copy';

type CodeBoxProps = {
  code: string;
} & HTMLAttributes<HTMLElement>;

export function CodeBox({ code, ...props }: CodeBoxProps) {
  const [didJustCopy, setDidJustCopy] = useState(false);
  useEffect(() => {
    if (didJustCopy) {
      const timeout = setTimeout(() => setDidJustCopy(false), 1000);
      return () => clearTimeout(timeout);
    }
  }, [didJustCopy]);

  const handleCopy = async () => {
    try {
      await copy(code);
      setDidJustCopy(true);
      // we don't want to do anything if the copy fails
    } catch {}
  };

  return (
    <div
      css={{
        display: 'inline-flex',
        alignItems: 'center',
        border: '1px solid var(--border)',
        borderRadius: '6px',
        background: 'var(--code-bg)',
        fontSize: '1.125rem',
        fontFamily: 'var(--font-mono)',
        padding: '0.75rem 1rem',
        ':before': {
          content: '"$"',
          display: 'inline-block',
          color: 'var(--muted)',
          marginRight: '1rem',
        },
      }}
      {...props}
    >
      {code}
      <button
        onClick={handleCopy}
        css={{
          display: 'inline-flex',
          appearance: 'none',
          border: '0 none',
          borderRadius: '100%',
          boxShadow: 'none',
          background: 'transparent',
          padding: '0.25rem',
          marginLeft: '1rem',
          cursor: 'pointer',
          color: 'var(--muted)',
          alignItems: 'center',
        }}
      >
        {didJustCopy ? <CheckIcon color="green" /> : <Copy css={{ height: '1.5rem' }} />}
      </button>
    </div>
  );
}


text:
var d3 = window.d3 || require('d3');
var px = require('../javascripts/modules/caravel.js');
var wrapSvgText = require('../javascripts/modules/utils.js').wrapSvgText;

require('./sunburst.css');

// Modified from http://bl.ocks.org/kerryrodden/7090426
function sunburstVis(slice) {
  var container = d3.select(slice.selector);

  var render = function () {
    // vars with shared scope within this function
    var margin = { top: 10, right: 5, bottom: 10, left: 5 };
    var containerWidth   = slice.width();
    var containerHeight  = slice.height();
    var breadcrumbHeight = containerHeight * 0.085;
    var visWidth         = containerWidth - margin.left - margin.right;
    var visHeight        = containerHeight - margin.top - margin.bottom - breadcrumbHeight;
    var radius           = Math.min(visWidth, visHeight) / 2;
    var colorByCategory  = true; // color by category if primary/secondary metrics match

    var maxBreadcrumbs, breadcrumbDims, // set based on data
        totalSize, // total size of all segments; set after loading the data.
        colorScale,
        breadcrumbs, vis, arcs, gMiddleText; // dom handles

    // Helper + path gen functions
    var partition = d3.layout.partition()
      .size([2 * Math.PI, radius * radius])
      .value(function (d) { return d.m1; });

    var arc = d3.svg.arc()
      .startAngle(function (d) {
        return d.x;
      })
      .endAngle(function (d) {
        return d.x + d.dx;
      })
      .innerRadius(function (d) {
        return Math.sqrt(d.y);
      })
      .outerRadius(function (d) {
        return Math.sqrt(d.y + d.dy);
      });

    var f = d3.format(".3s");
    var fp = d3.format(".3p");

    container.select("svg").remove();

    var svg = container.append("svg:svg")
      .attr("width", containerWidth)
      .attr("height", containerHeight);

    d3.json(slice.jsonEndpoint(), function (error, rawData) {
      if (error !== null) {
        slice.error(error.responseText);
        return '';
      }

      createBreadcrumbs(rawData);
      createVisualization(rawData);

      slice.done(rawData);
    });

    function createBreadcrumbs(rawData) {
      var firstRowData = rawData.data[0];
      maxBreadcrumbs = (firstRowData.length - 2) + 1; // -2 bc row contains 2x metrics, +extra for %label and buffer

      breadcrumbDims = {
        width: visWidth / maxBreadcrumbs,
        height: breadcrumbHeight *0.8, // more margin
        spacing: 3,
        tipTailWidth: 10
      };

      breadcrumbs = svg.append("svg:g")
        .attr("class", "breadcrumbs")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      breadcrumbs.append("svg:text")
        .attr("class", "end-label");
    }

    // Main function to draw and set up the visualization, once we have the data.
    function createVisualization(rawData) {
      var tree = buildHierarchy(rawData.data);

      vis = svg.append("svg:g")
        .attr("class", "sunburst-vis")
        .attr("transform", "translate(" + (margin.left + (visWidth / 2)) + "," + (margin.top + breadcrumbHeight + (visHeight / 2)) + ")")
        .on("mouseleave", mouseleave);

      arcs = vis.append("svg:g")
        .attr("id", "arcs");

      gMiddleText = vis.append("svg:g")
        .attr("class", "center-label");

      // Bounding circle underneath the sunburst, to make it easier to detect
      // when the mouse leaves the parent g.
      arcs.append("svg:circle")
        .attr("r", radius)
        .style("opacity", 0);

      // For efficiency, filter nodes to keep only those large enough to see.
      var nodes = partition.nodes(tree)
        .filter(function (d) {
          return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
        });

      var ext;

      if (rawData.form_data.metric !== rawData.form_data.secondary_metric) {
        colorByCategory = false;

        ext = d3.extent(nodes, function (d) {
          return d.m2 / d.m1;
        });

        colorScale = d3.scale.linear()
          .domain([ext[0], ext[0] + ((ext[1] - ext[0]) / 2), ext[1]])
          .range(["#00D1C1", "white", "#FFB400"]);
      }

      var path = arcs.data([tree]).selectAll("path")
        .data(nodes)
       .enter().append("svg:path")
        .attr("display", function (d) {
          return d.depth ? null : "none";
        })
        .attr("d", arc)
        .attr("fill-rule", "evenodd")
        .style("fill", function (d) {
          return colorByCategory ? px.color.category21(d.name) : colorScale(d.m2 / d.m1);
        })
        .style("opacity", 1)
        .on("mouseenter", mouseenter);

      // Get total size of the tree = value of root node from partition.
      totalSize = path.node().__data__.value;
    }

    // Fade all but the current sequence, and show it in the breadcrumb trail.
    function mouseenter(d) {

      var percentage = (d.m1 / totalSize).toPrecision(3);
      var percentageString = fp(percentage);
      var metricsMatch = Math.abs(d.m1 - d.m2) < 0.000001;

      gMiddleText.selectAll("*").remove();

      gMiddleText.append("text")
        .attr("class", "path-percent")
        .attr("y", "-10")
        .text(percentageString);

      gMiddleText.append("text")
        .attr("class", "path-metrics")
        .attr("y", "25")
        .text("m1: " + f(d.m1) + (metricsMatch ? "" : ", m2: " + f(d.m2)));

      gMiddleText.append("text")
        .attr("class", "path-ratio")
        .attr("y", "50")
        .text("m2/m1: " + fp(d.m2 / d.m1));

      var sequenceArray = getAncestors(d);

      // Reset and fade all the segments.
      arcs.selectAll("path")
        .style("stroke-width", null)
        .style("stroke", null)
        .style("opacity", 0.3);

      // Then highlight only those that are an ancestor of the current segment.
      arcs.selectAll("path")
        .filter(function (node) {
          return (sequenceArray.indexOf(node) >= 0);
        })
        .style("opacity", 1)
        .style("stroke-width", "2px")
        .style("stroke", "#000");

      updateBreadcrumbs(sequenceArray, percentageString);
    }

    // Restore everything to full opacity when moving off the visualization.
    function mouseleave(d) {

      // Hide the breadcrumb trail
      breadcrumbs.style("visibility", "hidden");

      gMiddleText.selectAll("*").remove();

      // Deactivate all segments during transition.
      arcs.selectAll("path").on("mouseenter", null);
      //gMiddleText.selectAll("*").remove();

      // Transition each segment to full opacity and then reactivate it.
      arcs.selectAll("path")
        .transition()
        .duration(200)
        .style("opacity", 1)
        .style("stroke", null)
        .style("stroke-width", null)
        .each("end", function () {
          d3.select(this).on("mouseenter", mouseenter);
        });
    }

    // Given a node in a partition layout, return an array of all of its ancestor
    // nodes, highest first, but excluding the root.
    function getAncestors(node) {
      var path = [];
      var current = node;
      while (current.parent) {
        path.unshift(current);
        current = current.parent;
      }
      return path;
    }

    // Generate a string that describes the points of a breadcrumb polygon.
    function breadcrumbPoints(d, i) {
      var points = [];
      points.push("0,0");
      points.push(breadcrumbDims.width + ",0");
      points.push(breadcrumbDims.width + breadcrumbDims.tipTailWidth + "," + (breadcrumbDims.height / 2));
      points.push(breadcrumbDims.width+ "," + breadcrumbDims.height);
      points.push("0," + breadcrumbDims.height);
      if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
        points.push(breadcrumbDims.tipTailWidth + "," + (breadcrumbDims.height / 2));
      }
      return points.join(" ");
    }

    function updateBreadcrumbs(sequenceArray, percentageString) {
      var g = breadcrumbs.selectAll("g")
        .data(sequenceArray, function (d) {
          return d.name + d.depth;
        });

      // Add breadcrumb and label for entering nodes.
      var entering = g.enter().append("svg:g");

      entering.append("svg:polygon")
          .attr("points", breadcrumbPoints)
          .style("fill", function (d) {
            return colorByCategory ? px.color.category21(d.name) : colorScale(d.m2 / d.m1);
          });

      entering.append("svg:text")
          .attr("x", (breadcrumbDims.width + breadcrumbDims.tipTailWidth) / 2)
          .attr("y", breadcrumbDims.height / 4)
          .attr("dy", "0.35em")
          .attr("class", "step-label")
          .text(function (d) { return d.name; })
          .call(wrapSvgText, breadcrumbDims.width, breadcrumbDims.height / 2);

      // Set position for entering and updating nodes.
      g.attr("transform", function (d, i) {
        return "translate(" + i * (breadcrumbDims.width + breadcrumbDims.spacing) + ", 0)";
      });

      // Remove exiting nodes.
      g.exit().remove();

      // Now move and update the percentage at the end.
      breadcrumbs.select(".end-label")
          .attr("x", (sequenceArray.length + 0.5) * (breadcrumbDims.width + breadcrumbDims.spacing))
          .attr("y", breadcrumbDims.height / 2)
          .attr("dy", "0.35em")
          .text(percentageString);

      // Make the breadcrumb trail visible, if it's hidden.
      breadcrumbs.style("visibility", null);
    }

    function buildHierarchy(rows) {
      var root = {
        name: "root",
        children: []
      };
      for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        var m1 = Number(row[row.length - 2]);
        var m2 = Number(row[row.length - 1]);
        var levels = row.slice(0, row.length - 2);
        if (isNaN(m1)) { // e.g. if this is a header row
          continue;
        }
        var currentNode = root;
        for (var j = 0; j < levels.length; j++) {
          var children = currentNode.children || [];
          var nodeName = levels[j];
          // If the next node has the name "0", it will
          var isLeafNode = (j >= levels.length - 1) || levels[j+1] === 0;
          var childNode;

          if (!isLeafNode) {
            // Not yet at the end of the sequence; move down the tree.
            var foundChild = false;
            for (var k = 0; k < children.length; k++) {
              if (children[k].name === nodeName) {
                childNode = children[k];
                foundChild = true;
                break;
              }
            }
            // If we don't already have a child node for this branch, create it.
            if (!foundChild) {
              childNode = {
                name: nodeName,
                children: []
              };
              children.push(childNode);
            }
            currentNode = childNode;
          } else if (nodeName !== 0) {
            // Reached the end of the sequence; create a leaf node.
            childNode = {
              name: nodeName,
              m1: m1,
              m2: m2
            };
            children.push(childNode);
          }
        }
      }

      function recurse(node) {
        if (node.children) {
          var sums;
          var m1 = 0;
          var m2 = 0;
          for (var i = 0; i < node.children.length; i++) {
            sums = recurse(node.children[i]);
            m1 += sums[0];
            m2 += sums[1];
          }
          node.m1 = m1;
          node.m2 = m2;
        }
        return [node.m1, node.m2];
      }
      recurse(root);
      return root;
    }
  };

  return {
    render: render,
    resize: render
  };
}

module.exports = sunburstVis;


text:
using System;

namespace Lucene.Net.Search
{

	/// Expert: Returned by low-level search implementations.
	/// <seealso cref="TopDocs">
	/// </seealso>
	[Serializable]
	public class ScoreDoc
	{
		/// Expert: The score of this document for the query.
		public float score;

		/// Expert: A hit document's number.
		/// <seealso cref="Searcher#Doc(int)">
		/// </seealso>
		public int doc;

		/// Expert: Constructs a ScoreDoc.
		public ScoreDoc(int doc, float score)
		{
			this.doc = doc;
			this.score = score;
		}
	}
}


text:
<?php

use Illuminate\Database\Migrations\Migration;

class CreateHtmlModelsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('models', function ($table) {
            $table->increments('id');
            $table->string('string');
            $table->string('email');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('models');
    }
}


text:
MathJax.Localization.addTranslation("nl","HelpDialog",{
        version: "2.7.0",
        isLoaded: true,
        strings: {
          Help: "MathJax-hulp",
          MathJax: "*MathJax* is een JavaScript bibliotheek die het mogelijk maakt dat auteurs wiskunde kunnen toevoegen aan hun web-pagina's. Als een lezer hoeft u niks te doen om dat mogelijk te maken.",
          Browsers: "*Browsers*: MathJax werkt met alle moderne browsers, inclusief IE6+, Firefox 3+, Chrome 0.2+, Safari 2+, Opera 9.6+ en de meeste mobiele browsers.",
          Menu: "*Math menu*:MathJax voegt een context menu toe aan vergelijkingen. Rechtsklik of Ctrl-klik op willekeurige wiskunde om het menu weer te geven.",
          ShowMath: "*Wiskunde weergeven als* geeft de formule in bron opmaak weer voor knippen en plakken (als MathML of in de originele opmaak).",
          Settings: "Via *Instellingen* kunt u de functionaliteit van MathJax beheersen, zoals de grootte van de wiskunde en het mechanisme dat gebruikt wordt om vergelijkingen weer te geven.",
          Language: "Via *Taal* kunt u de taal kiezen die MathJax gebruikt voor de menu's en waarschuwingsboodschappen.",
          Zoom: "*Wiskunde zoom*: Als u moeite heeft met het lezen van een vergelijking dan kan MathJax deze vergroten zodat u het beter kunt zien.",
          Accessibilty: "*Toegankelijkheid*: MathJax werkt automatisch samen met schermlezers waardoor wiskunde toegankelijk wordt voor slechtzienden.",
          Fonts: "*Lettertypes*: MathJax gebruikt bepaalde wiskunde lettertypes als die ge\u00EFnstalleerd zijn op uw computer; anders gebruikt het webgebaseerde lettertypes. Alhoewel het niet noodzakelijk is, versnellen lokaal ge\u00EFnstalleerde lettertypes het zetwerk. We raden aan om de [STIX fonts](%1) te installeren."
        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/nl/HelpDialog.js");


text:
package com.futureplatforms.kirin.extensions.networking;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.client.HttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.util.Log;

import com.futureplatforms.kirin.C;
import com.futureplatforms.kirin.R;
import com.futureplatforms.kirin.extensions.KirinExtensionAdapter;
import com.futureplatforms.kirin.helpers.IKirinExtensionHelper;
import com.futureplatforms.kirin.internal.JSONUtils;
import com.futureplatforms.kirin.internal.attic.IOUtils;
import com.futureplatforms.kirin.internal.attic.SDCardFileUtils;

public class NetworkingBackend extends KirinExtensionAdapter implements INetworkingBackend {

	private final Context mContext;

	private final SDCardFileUtils mFileUtils;

	private BroadcastReceiver mReceiver;

	private AtomicInteger mDownloadingCount;

	private HttpClient mHttpClient;

	public NetworkingBackend(Context context) {
		this(context, null, null);
	}

	public NetworkingBackend(Context context, IKirinExtensionHelper kirinHelper,
			String saveFileLocation) {
		super(context, "Networking", kirinHelper);
		mContext = context;

        String packageName = mContext.getPackageName();
        String sdCardPrefix = Environment.getExternalStorageDirectory().getPath();
        String path = sdCardPrefix + MessageFormat.format("/Android/data/{0}/files", packageName);
        if (!path.endsWith("/")) {
            path += "/";
        }
		mFileUtils = new SDCardFileUtils(path);

		mDownloadingCount = new AtomicInteger(0);
	}

	protected String downloadString(JSONObject config) throws IOException {
		incrementDownloadCount();
		InputStream in = null;
		ByteArrayOutputStream baos = null;
		HttpClient client = null;
		try {
			client = getClient();
			in = makeConnection(config, client);
			baos = new ByteArrayOutputStream(8 * 1024);
			IOUtils.copy(in, baos);
			return baos.toString("UTF-8");
		} finally {
			IOUtils.close(in);
			IOUtils.close(baos);
			IOUtils.cleanupHttpClient(client);
			decrementDownloadCount();
		}
	}

	private synchronized HttpClient getClient() {
		if (mHttpClient == null) {
			mHttpClient = IOUtils.newHttpClient();
		}
		return mHttpClient;
	}

	private InputStream makeConnection(JSONObject config, HttpClient client)
			throws MalformedURLException, IOException {

		URL url = new URL(config.optString("url"));
		String method = config.optString("method", "GET");
		if (method.equalsIgnoreCase("GET")) {
			return IOUtils.connectTo(mContext, url, client);
		} else {
			return IOUtils.postConnection(mContext, url, method,
					config.optString("params"));
		}
	}

	protected void downloadFile(String urlString, String pathSuffix)
			throws IOException {

		InputStream in = null;
		OutputStream out = null;
		HttpClient client = getClient();
		File file = mFileUtils.readableFile(mContext, pathSuffix);
		if (file.exists()) {
			return;
		}
		try {
			incrementDownloadCount();
			URL url = new URL(urlString);
			in = IOUtils.connectTo(mContext, url, client);
			out = mFileUtils.outputStream(mContext, pathSuffix);

			IOUtils.copy(in, out);

		} finally {
			IOUtils.close(in);
			IOUtils.close(out);
			IOUtils.cleanupHttpClient(client);
			decrementDownloadCount();
		}
	}

	@Override
	public void deleteDownloadedFile_(JSONObject config) {
		String filename = JSONUtils.stringOrNull(config, "filename", null);
		try {
			mFileUtils.deleteFile(mContext, filename);
			mKirinHelper.jsCallback(config, "onFinish");
		} catch (Exception e) {
			Log.e(C.TAG, "Can't delete " + filename);
			reportExceptionToJavascript(config, e);
		} finally {
			cleanup(config, "onFinish", "onError");
		}
	}

	private void reportExceptionToJavascript(JSONObject config, Exception e) {
		Log.e(C.TAG, "Backend reported exception " + e, e);
		mKirinHelper.jsCallback(config, "onError", e.getLocalizedMessage());
	}

	@Override
	public void downloadFile_(JSONObject config) {
		try {
			downloadFile(config.optString("url"), config.optString("filename"));
			mKirinHelper.jsCallback(config, "onFinish");
		} catch (IOException e) {
			reportExceptionToJavascript(config, e);
		} finally {
			cleanup(config, "onFinish", "onError");
		}
	}

	private void incrementDownloadCount() {
		int count = mDownloadingCount.getAndIncrement();
		Log.i(C.TAG, "NetworkingBackend.incrementDownloadCount: " + count);
		if (count == 0) {
			listenForChangeInNetworkStatus();
		}
	}

	private void decrementDownloadCount() {
		int count = mDownloadingCount.decrementAndGet();
		Log.i(C.TAG, "NetworkingBackend.decrementDownloadCount: " + count);
		if (count == 0) {
			zeroCountReached();
		}
	}

	protected void zeroCountReached() {
		Log.i(C.TAG, "NetworkingBackend.zeroCountReached: ");
		if (mReceiver != null) {
			mContext.unregisterReceiver(mReceiver);
		}
		mReceiver = null;

		cleanupHttpClient();
	}

    protected void cleanupHttpClient() {
        HttpClient client = null;
		synchronized (this) {
			if (mHttpClient != null) {
				client = mHttpClient;
				mHttpClient = null;
			}
		}
		IOUtils.closeHttpClient(client);
    }

	public JSONArray isolateArrayFromObject(JSONObject object, JSONArray path) {

		JSONArray list = null;
		JSONObject parent = object;

		for (int i = 0, max = path.length(); i < max; i++) {

			String pathSegment = JSONUtils.stringOrNull(path, i, null);
			if (pathSegment == null) {
				continue;
			}

			Object obj = parent.opt(pathSegment);

			if (obj == null) {
				// not found.
				return null;
			} else if (obj instanceof JSONArray) {
				list = (JSONArray) obj;
				parent.remove(pathSegment);
				break;
			} else if (obj instanceof JSONObject) {
				parent = (JSONObject) obj;
			} else {
				// not found
				return null;
			}
		}

		return list;
	}

	@Override
	public void downloadJSONList_(JSONObject config) {
		String jsonString = null;

		try {
			jsonString = downloadString(config);

			JSONArray array = null;
			JSONObject envelope = null;
			int arraySize = 0;

			String eachCallback = JSONUtils.stringOrNull(config, "each", null);

			Object obj = new JSONTokener(jsonString).nextValue();
			if (obj instanceof JSONArray) {
				array = (JSONArray) obj;
			} else if (obj instanceof JSONObject) {
				envelope = (JSONObject) obj;
				JSONArray path = config.optJSONArray("path");
				if (path != null) {
					array = isolateArrayFromObject(envelope, path);
				}
			}

			if (envelope != null) {
				mKirinHelper.jsCallback(config, "envelope", envelope);
			}
			if (array != null && eachCallback != null) {
				for (int i = 0, max = array.length(); i < max; i++) {
					Object item = array.get(i);
					if (item != null) {
						mKirinHelper.jsCallback(eachCallback, item);
					}
				}
				arraySize = array.length();
			}

			if (array == null && envelope == null) {
				Log.e(C.TAG, "Server provided badly formatted JSON: "
						+ jsonString);
				mKirinHelper.jsCallback(config, "onError", "Invalid JSON");
			} else {
				mKirinHelper.jsCallback(config, "onFinish", arraySize);
			}
		} catch (IOException e) {
			Log.e(C.TAG, "Couldn't connect to the server", e);
			reportExceptionToJavascript(config, e);
		} catch (JSONException e) {
			Log.e(C.TAG, "Server provided badly formatted JSON: " + jsonString);
			reportExceptionToJavascript(config, e);
		} finally {
			cleanup(config, "envelope", "each", "onError", "onFinish");
		}
	}

	@Override
	public void downloadJSON_(JSONObject config) {
		try {
			String jsonString = downloadString(config);
			Log.i(C.TAG, "NetworkingBackend.downloadJSON_: downloadJSON_ : "
					+ jsonString);
			Object obj = new JSONTokener(jsonString).nextValue();
            if (!(obj instanceof JSONArray) && !(obj instanceof JSONObject)) {
            	mKirinHelper.jsCallback(config, "onError", "Invalid JSON response received");
            } else {
            	mKirinHelper.jsCallback(config, "payload", new JSONTokener(jsonString).nextValue());
            }
		} catch (IOException e) {
			reportExceptionToJavascript(config, e);
		} catch (JSONException e) {
			reportExceptionToJavascript(config, e);
		} finally {
			cleanup(config, "payload", "onError");
		}
	}

	private void cleanup(JSONObject config, String... callbacks) {
		mKirinHelper.cleanupCallback(config, callbacks);
	}

	private void listenForChangeInNetworkStatus() {
		Log.i(C.TAG, "NetworkingBackend.listenForChangeInNetworkStatus: ");
		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.getBooleanExtra(
						ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
					String reason = intent
							.getStringExtra(ConnectivityManager.EXTRA_REASON);
					if (reason == null || reason.trim().length() == 0) {
						reason = mContext
								.getString(R.string.networking_connection_lost);
					}
					cancelAllDownloads(reason);
				}
			}

		};
		mContext.registerReceiver(mReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));

	}

	protected void cancelAllDownloads(String reason) {
		Log.i(C.TAG,
				"NetworkingBackend.cancelAllDownloads: NETWORK CONNECTIVITY LOST, shutting down HttpClient");

		cleanupHttpClient();
	}

}


text:
<?php

return [
    'adminEmail' => 'admin@example.com',
    'uploadFolder' => 'uploads',
];


text:
<?php

namespace DvsaCommon\ApiClient\Statistics\TesterPerformance;

use DvsaCommon\ApiClient\Statistics\AePerformance\Dto\AuthorisedExaminerSitesPerformanceDto;
use DvsaCommon\Factory\AutoWire\AutoWireableInterface;
use DvsaCommon\HttpRestJson\AbstractApiResource;

class AuthorisedExaminerSitePerformanceApiResource extends AbstractApiResource implements AutoWireableInterface
{
    /**
     * @param int $organisationId
     * @param $page
     * @param $itemsPerPage
     * @return AuthorisedExaminerSitesPerformanceDto
     */
    public function getData($organisationId, $page, $itemsPerPage)
    {
        return $this->getSingle(
            AuthorisedExaminerSitesPerformanceDto::class,
            sprintf('statistic/tester-performance/authorised-examiner/%s', $organisationId),
            $this->getParams($page, $itemsPerPage)
        );
    }

    private function getParams($page, $itemsPerPage)
    {
        return [
            'page'          => $page,
            'itemsPerPage'  => $itemsPerPage,
        ];
    }
}


text:
@interface StorTabBarController : UITabBarController <UITabBarControllerDelegate>

@end


text:
package io.tracee.binding.jaxws;

import io.tracee.TraceeBackend;
import io.tracee.TraceeConstants;
import org.junit.Before;
import org.junit.Test;

import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;

public class AbstractTraceeHandlerTest {

	private TestTraceeHandler unit;

	private final TraceeBackend traceeBackend = mock(TraceeBackend.class);

	@Before
	public void setupMocks() {
		unit = spy(new TestTraceeHandler(traceeBackend));
	}

	@Test
	public void shouldHandleOutgoingContextInOutgoingMethod() {
		final SOAPMessageContext messageContext = mock(SOAPMessageContext.class);
		when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(Boolean.TRUE);
		unit.handleMessage(messageContext);

		verify(unit).handleOutgoing(messageContext);
	}

	@Test
	public void shouldHandleIncomingContextInIncomingMethod() {
		final SOAPMessageContext messageContext = mock(SOAPMessageContext.class);
		unit.handleMessage(messageContext);
		verify(unit).handleIncoming(messageContext);
	}

	@Test
	public void shouldHandleNoContextPropertyInIncomingMethod() {
		final SOAPMessageContext messageContext = mock(SOAPMessageContext.class);
		when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(Boolean.FALSE);
		unit.handleMessage(messageContext);

		verify(unit).handleIncoming(messageContext);
	}

	@Test
	public void shouldRegisterForTraceeHeaders() {
		assertThat(unit.getHeaders(), hasItem(TraceeConstants.SOAP_HEADER_QNAME));
	}

	@Test
	public void shouldReturnTraceeBackendFromInitializiation() {
		assertThat(unit.traceeBackend, is(traceeBackend));
	}

	private static class TestTraceeHandler extends AbstractTraceeHandler {

		public TestTraceeHandler(TraceeBackend traceeBackend) {
			super(traceeBackend);
		}

		@Override
		protected void handleIncoming(SOAPMessageContext context) {

		}

		@Override
		protected void handleOutgoing(SOAPMessageContext context) {

		}

		@Override
		public boolean handleFault(SOAPMessageContext context) {
			return false;
		}
	}
}


text:
#ifndef wss_comm_h
#define wss_comm_h

#if !defined(uthash_malloc) || !defined(uthash_free)
#include "alloc.h"

#ifndef uthash_malloc
#define uthash_malloc(sz) WSS_malloc(sz)   /* malloc fcn */
#endif

#ifndef uthash_free
#define uthash_free(ptr,sz) WSS_free((void **)&ptr) /* free fcn */
#endif
#endif

#include "server.h"
#include "session.h"
#include "uthash.h"

#define MAGIC_WEBSOCKET_KEY         "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#define GMT_FORMAT_LENGTH           30
#define HTTP_STATUS_LINE            "%s %d %s\r\n"
#define HTTP_ICO_HEADERS            "Content-Type: image/x-icon\r\n"\
                                    "Content-Length: %d\r\n"\
                                    "Connection: close\r\n"\
                                    "Date: %s\r\n"\
                                    "Server: WSServer/%s\r\n"\
                                    "Etag: %s\r\n"\
                                    "Accept-Ranges: bytes\r\n"\
                                    "Last-Modified: %s\r\n"\
                                    "\r\n"
#define HTTP_HTML_HEADERS           "Content-Type: text/html; charset=utf-8\r\n"\
                                    "Content-Length: %d\r\n"\
                                    "Connection: Closed\r\n"\
                                    "Date: %s\r\n"\
                                    "Server: WSServer/%s\r\n"\
                                    "\r\n"
#define HTTP_WS_VERSION_HEADER      "Sec-WebSocket-Version: %d, %d, %d\r\n"
#define HTTP_UPGRADE_HEADERS        "Content-Type: text/plain\r\n"\
                                    "Content-Length: %d\r\n"\
                                    "Connection: Upgrade\r\n"\
                                    "Upgrade: websocket\r\n"\
                                    "Sec-WebSocket-Version: 13\r\n"\
                                    "Server: WSServer/%s\r\n"\
                                    "\r\n"
#define HTTP_HANDSHAKE_EXTENSIONS   "Sec-Websocket-Extensions: "
#define HTTP_HANDSHAKE_SUBPROTOCOL  "Sec-Websocket-Protocol: "
#define HTTP_HANDSHAKE_ACCEPT       "Sec-Websocket-Accept: "
#define HTTP_HANDSHAKE_HEADERS      "Upgrade: websocket\r\n"\
                                    "Connection: Upgrade\r\n"\
                                    "Server: WSServer/%s\r\n"\
                                    "\r\n"
#define HTTP_BODY                   "<!doctype html>"\
                                    ""\
                                    ""\
                                    "<meta charset=\"utf-8\">"\
                                    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">"\
                                    "<title>%d %s</title>"\
                                    ""\
                                    ""\
                                    "
%s
"\
                                    "
%s
"\
                                    ""\
                                    ""

/**
 * Structure used to find receivers
 */
typedef struct {
    int fd;
    UT_hash_handle hh;
} wss_receiver_t;

/**
 * Function that disconnects a session and freeing any allocated memory used by
 * the session.
 *
 * @param 	server	[wss_server_t *] 	"The server structure"
 * @param 	session	[wss_session_t *] 	"The session structure"
 * @return          [void]
 */
void WSS_disconnect(wss_server_t *server, wss_session_t *session);

/**
 * Function that handles new connections. This function creates a new session and
 * associates the sessions filedescriptor to the epoll instance such that we can
 * start communicating with the session.
 *
 * @param 	server	[wss_server_t *] 	"The server structure"
 * @param 	session	[wss_session_t *] 	"The session structure"
 * @return          [void]
 */
//void WSS_connect(void *arg);

/**
 * Function that reads information from a session.
 *
 * @param 	server	[wss_server_t *] 	"The server structure"
 * @param 	session	[wss_session_t *] 	"The session structure"
 * @return          [void]
 */
//void WSS_read(void *args);

/**
 * Function that writes information to a session
 *
 * @param 	server	[wss_server_t *] 	"The server structure"
 * @param 	session	[wss_session_t *] 	"The session structure"
 * @return          [void]
 */
void WSS_write(wss_server_t *server, wss_session_t *session);

/**
 * Function that performs and distributes the IO work.
 *
 * @param 	args	[void *] 	"Is a args_t structure holding server_t, filedescriptor, and the state"
 * @return          [void]
 */
void WSS_work(void *args);

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   ====================================================================
-->
<!DOCTYPE book PUBLIC "-//APACHE//DTD Cocoon Documentation Book V1.0//EN" "../dtd/book-cocoon-v10.dtd">

<book software="POI"
      title="POI Project Documentation"
      copyright="@year@ POI Project"
      xmlns:xlink="http://www.w3.org/1999/xlink">

  <menu label="Apache POI">
    <menu-item label="Top" href="../index.html"/>
  </menu>

  <menu label="References">
    <menu-item label="Live Sites" href="index.html"/>
    <menu-item label="XLS spec [PDF]" href="http://sc.openoffice.org/excelfileformat.pdf"/>
    <menu-item label="Apache Cocoon" href="http://xml.apache.org/cocoon/"/>
  </menu>

</book>


text:
'use strict';

/**
 * @ngdoc overview
 * @name scenetagApp
 * @description
 * # scenetagApp
 *
 * Main module of the application.
 */
angular
  .module('tagmyclip', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ui.bootstrap',
    'youtube',
    'angular-jqcloud',
    'YouTubeApp'
  ])
  .config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'SceneTagController'
      })
      .when('/toptags', {
        templateUrl: 'tagcloud.html',
        controller: 'TagCouldController'
      })
      .otherwise({
        redirectTo: '/'
      });

    $locationProvider.html5Mode(true);
  });


text:
from crits.vocabulary.vocab import vocab

class RelationshipTypes(vocab):
    """
    Vocabulary for Relationship Types.
    """

    COMPRESSED_FROM = "Compressed From"
    COMPRESSED_INTO = "Compressed Into"

    CONNECTED_FROM = "Connected From"
    CONNECTED_TO = "Connected To"

    CONTAINS = "Contains"
    CONTAINED_WITHIN = "Contained Within"

    CREATED = "Created"
    CREATED_BY = "Created By"

    DECODED = "Decoded"
    DECODED_BY = "Decoded By"

    DECRYPTED = "Decrypted"
    DECRYPTED_BY = "Decrypted By"

    DOWNLOADED = "Downloaded"
    DOWNLOADED_BY = "Downloaded By"

    DOWNLOADED_FROM = "Downloaded From"
    DOWNLOADED_TO = "Downloaded To"

    DROPPED = "Dropped"
    DROPPED_BY = "Dropped By"

    INSTALLED = "Installed"
    INSTALLED_BY = "Installed By"

    LOADED_FROM = "Loaded From"
    LOADED_INTO = "Loaded Into"

    PACKED_FROM = "Packed From"
    PACKED_INTO = "Packed Into"

    RECEIVED_FROM = "Received From"
    SENT_TO = "Sent To"

    REGISTERED = "Registered"
    REGISTERED_TO = "Registered To"

    RELATED_TO = "Related To"

    RESOLVED_TO = "Resolved To"

    SENT = "Sent"
    SENT_BY = "Sent By"

    SUB_DOMAIN_OF = "Sub-domain Of"
    SUPRA_DOMAIN_OF = "Supra-domain Of"

    @classmethod
    def inverse(cls, relationship=None):
        """
        Return the inverse relationship of the provided relationship.

        :param relationship: The relationship to get the inverse of.
        :type relationship: str
        :returns: str or None
        """

        if relationship is None:
            return None

        if relationship == cls.COMPRESSED_FROM:
            return cls.COMPRESSED_INTO
        elif relationship == cls.COMPRESSED_INTO:
            return cls.COMPRESSED_FROM
        elif relationship == cls.CONNECTED_FROM:
            return cls.CONNECTED_TO
        elif relationship == cls.CONNECTED_TO:
            return cls.CONNECTED_FROM
        elif relationship == cls.CONTAINS:
            return cls.CONTAINED_WITHIN
        elif relationship == cls.CONTAINED_WITHIN:
            return cls.CONTAINS
        elif relationship == cls.CREATED:
            return cls.CREATED_BY
        elif relationship == cls.CREATED_BY:
            return cls.CREATED
        elif relationship == cls.DECODED:
            return cls.DECODED_BY
        elif relationship == cls.DECODED_BY:
            return cls.DECODED
        elif relationship == cls.DECRYPTED:
            return cls.DECRYPTED_BY
        elif relationship == cls.DECRYPTED_BY:
            return cls.DECRYPTED
        elif relationship == cls.DOWNLOADED:
            return cls.DOWNLOADED_BY
        elif relationship == cls.DOWNLOADED_BY:
            return cls.DOWNLOADED
        elif relationship == cls.DOWNLOADED_FROM:
            return cls.DOWNLOADED_TO
        elif relationship == cls.DOWNLOADED_TO:
            return cls.DOWNLOADED_FROM
        elif relationship == cls.DROPPED:
            return cls.DROPPED_BY
        elif relationship == cls.DROPPED_BY:
            return cls.DROPPED
        elif relationship == cls.INSTALLED:
            return cls.INSTALLED_BY
        elif relationship == cls.INSTALLED_BY:
            return cls.INSTALLED
        elif relationship == cls.LOADED_FROM:
            return cls.LOADED_INTO
        elif relationship == cls.LOADED_INTO:
            return cls.LOADED_FROM
        elif relationship == cls.PACKED_FROM:
            return cls.PACKED_INTO
        elif relationship == cls.PACKED_INTO:
            return cls.PACKED_FROM
        elif relationship == cls.RECEIVED_FROM:
            return cls.SENT_TO
        elif relationship == cls.SENT_TO:
            return cls.RECEIVED_FROM
        elif relationship == cls.REGISTERED:
            return cls.REGISTERED_TO
        elif relationship == cls.REGISTERED_TO:
            return cls.REGISTERED
        elif relationship == cls.RELATED_TO:
            return cls.RELATED_TO
        elif relationship == cls.RESOLVED_TO:
            return cls.RESOLVED_TO
        elif relationship == cls.SENT:
            return cls.SENT_BY
        elif relationship == cls.SENT_BY:
            return cls.SENT
        elif relationship == cls.SUB_DOMAIN_OF:
            return cls.SUPRA_DOMAIN_OF
        elif relationship == cls.SUPRA_DOMAIN_OF:
            return cls.SUB_DOMAIN_OF
        else:
            return None


text:
FastqReader::FastqReader(const char* path)
    : file_(path) {

    if (!file_.is_open()) {
        std::cerr << "Unable to open file: " << path << std::endl;
        exit(EXIT_FAILURE);
    }
}

void FastqReader::invalid_format(const std::string& line) {
    std::cerr << "Unsupported FASTQ file format" << std::endl;
    if (line.size() > 0)
        std::cerr << "->line: " << line << std::endl;
    exit(EXIT_FAILURE);
}

std::auto_ptr<FastaSequence> FastqReader::next() {

    std::string line;
    std::auto_ptr<FastaSequence> fs(new FastaSequence());

    // read identifier
    if (!getline(file_, line)) {
        // if we can't read idenfitier, there is no more sequences
        return std::auto_ptr<FastaSequence>(NULL);
    }
    if (line.size() < 1 || line[0] != '@') invalid_format(line);
    fs->name_ += line.substr(1);

    // read sequence
    while (getline(file_, line)) {
        if (line[0] == '+') break;

        fs->sequence_ += line;
    }

    // read sequence identifiers
    if (line[0] != '+') invalid_format(line);
    // read quality values
    if (!getline(file_, line)) invalid_format(line);

    return fs;
}


text:
@interface Activity :  NSManagedObject
{
}

@property (nonatomic, retain) NSDate * startTime;
@property (nonatomic, retain) NSNumber * currentHours;
@property (nonatomic, retain) NSDate * endTime;
@property (nonatomic, retain) NSNumber * goalHours;
@property (nonatomic, retain) NSString * name;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Mus. nac. Hist. nat. B. Aires 26: 129 (1914)

#### Original name
Phyllosticta penicillariae Speg.

### Remarks
null


text:
// Copyright 2020 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*! THIS FILE IS AUTO-GENERATED */

import {AuthPlus, getAPI, GoogleConfigurable} from 'googleapis-common';
import {recommender_v1} from './v1';
import {recommender_v1beta1} from './v1beta1';

export const VERSIONS = {
  v1: recommender_v1.Recommender,
  v1beta1: recommender_v1beta1.Recommender,
};

export function recommender(version: 'v1'): recommender_v1.Recommender;
export function recommender(
  options: recommender_v1.Options
): recommender_v1.Recommender;
export function recommender(
  version: 'v1beta1'
): recommender_v1beta1.Recommender;
export function recommender(
  options: recommender_v1beta1.Options
): recommender_v1beta1.Recommender;
export function recommender<
  T = recommender_v1.Recommender | recommender_v1beta1.Recommender
>(
  this: GoogleConfigurable,
  versionOrOptions:
    | 'v1'
    | recommender_v1.Options
    | 'v1beta1'
    | recommender_v1beta1.Options
) {
  return getAPI<T>('recommender', versionOrOptions, VERSIONS, this);
}

const auth = new AuthPlus();
export {auth};
export {recommender_v1};
export {recommender_v1beta1};
export {
  AuthPlus,
  GlobalOptions,
  APIRequestContext,
  GoogleConfigurable,
  StreamMethodOptions,
  GaxiosPromise,
  MethodOptions,
  BodyResponseCallback,
} from 'googleapis-common';


text:
Simple application with a few REST endpoints, which takes a URL, parses the content, indexes it in an embedded Elasticsearch instance and provides a REST endpoint to search the index.

## Package and run the application
This project includes the Maven Wrapper. To build the project, just run

`./mvnw clean package`

The wrapper will automatically download the required Maven distribution (unrestricted internet access necessary).

After that, run `java -jar target/webcrawler*.jar`

## Index a webpage

The application exposes a REST endpoint at `http://localhost:8080/import?url=`, which expects an encoded URL as parameter value.

## Search for results

For a search use the endpoint `http://localhost:8080/search?q={searchterm}`

The result is returned as JSON.


text:
class ContinuousFailureException(Exception):
    pass

class TimeoutException(Exception):
    pass

class ConnectionCutException(Exception):
    pass


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import java.nio.ByteBuffer;

/**
 * 64-bit integer value
 **/
public class Int64Value extends Value
{
    private long value;

    /**
     * Create from a Java-type value
     *
     * @param value the value
     **/
    public Int64Value(long value) { this.value = value; }

    /**
     * Create by decoding the value from the given buffer
     *
     * @param src buffer where the value is stored
     **/
    Int64Value(ByteBuffer src) {
        value = src.getLong();
    }

    /**
     * @return INT64
     **/
    public byte type() { return INT64; }
    public int count() { return 1; }

    int bytes() { return 8; }
    void encode(ByteBuffer dst) {
        dst.putLong(value);
    }

    public long asInt64() { return value; }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

}


text:
#region Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Kodestruct.Steel.AISC.FloorVibrations.EffectiveProperties
{
    /// <summary>
    /// Interaction logic for Kodestruct.Steel.AISC10.BeamLocationSelectionView.xaml
    /// </summary>
    public partial class BeamLocationSelectionView: UserControl
    {
        public BeamLocationSelectionView()
        {
            InitializeComponent();
        }
    }
}


text:
#ifndef AliPHOSEventCuts_cxx
#define AliPHOSEventCuts_cxx

//Author: Daiki Sekihata (Hiroshima University)
//this analsyis class provides event selection.
//e.g., reject pileup event, Incomplete event, |zvtx|>10cm.

#include "AliAnalysisCuts.h"

class AliPHOSEventCuts : public AliAnalysisCuts {

  public:
    AliPHOSEventCuts(const char *name = "AliPHOSEventCuts");
    virtual ~AliPHOSEventCuts();

    virtual Bool_t IsSelected(TObject* obj) {return AcceptEvent((AliVEvent*)obj);}
    virtual Bool_t IsSelected(TList* /*list*/) {return kTRUE;}
    Bool_t AcceptEvent(AliVEvent *event);

    void SetMCFlag(Bool_t mc) {fIsMC = mc;}
    void SetMaxAbsZvtx(Double_t maxZ) {fMaxAbsZvtx = maxZ;}
    void SetRejectPileup(Bool_t reject) {fRejectPileup = reject;}
    void SetRejectDAQIncompleteEvent(Bool_t reject) {fRejectDAQIncomplete = reject;}

    Bool_t IsMC() {return fIsMC;}

  private:
    Bool_t fIsMC;
    Double_t fMaxAbsZvtx;
    Bool_t fRejectPileup;
    Bool_t fRejectDAQIncomplete;

  private:
    AliPHOSEventCuts(const AliPHOSEventCuts&);
    AliPHOSEventCuts& operator=(const AliPHOSEventCuts&);

    ClassDef(AliPHOSEventCuts, 8);
};

#endif


text:
import * as React from "react"
import { useSafeLayoutEffect } from "./use-safe-layout-effect"

/**
 * React hook to persist any value between renders,
 * but keeps it up-to-date if it changes.
 *
 * @param value the value or function to persist
 */
export function useCallbackRef<T extends (...args: any[]) => any>(fn: T | undefined): T {
  const ref = React.useRef(fn)

  useSafeLayoutEffect(() => {
    ref.current = fn
  })

  // eslint-disable-next-line react-hooks/exhaustive-deps
  return React.useCallback(((...args) => ref.current?.(...args)) as T, [])
}


text:
author: slowe
comments: true
date: 2009-02-19 18:55:02+00:00
layout: post
slug: citrix-open-sources-their-vhd-implementation
title: Citrix Open Sources Their VHD Implementation
wordpress_id: 1205
categories: News
tags:
- Citrix
- HyperV
- Virtualization
- Xen
---

One sticking point I've had with Citrix since the XenSource acquisition has been the perception of a failure to give back to the open source Xen community. Note that I said _perception_. It appeared, following the XenSource acquisition, that Citrix was all about using open source Xen as a base but failing to return any of enhancements they made to the code base. No, I don't have any concrete examples; again, this was the _perception._

It appears that Citrix is now taking steps to remedy that perception. In a blog entry posted last night, Simon Crosby announced that Citrix has [open sourced their optimized VHD support](http://community.citrix.com/blogs/citrite/simoncr/2009/02/18/We%27ve+Open+Sourced+Our+Optimized+VHD+Support). This means that XenServer's robust VHD implementation is now available to any developer under the BSD license. In case you don't already know, VHD is the same virtual disk technology Microsoft uses in Hyper-V, and which Microsoft is using even more extensively in future versions of Windows.

In my opinion, this is an excellent move. It addresses the perception of failing to give back to the open source community, and it puts what appears to be a valuable piece of technology into the open source world. Making XenServer's VHD implementation available for other open source developers to use in their projects puts VHD on the fast track to being the _de facto_ virtual disk standard. Assuming that other virtualization platforms adopt VHD support---and I'm not sure why many of them wouldn't adopt VHD support, except for VMware---we've now removed a huge barrier to interoperability. That's a good thing.

Not being a lawyer, I'm a bit worried about the compatibility of the BSD license---which is generally regarded as quite generous---and the [Microsoft Open Specification Promise](http://www.microsoft.com/Interop/osp/default.mspx), but I'll leave that for others to hash out.

It will be interesting to see if Citrix also open sources some of their other XenServer-related technologies. Time will tell...


text:
package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Chant_HardenSkin extends Chant
{
	@Override public String ID() { return "Chant_HardenSkin"; }
	private final static String localizedName = CMLib.lang()._("Harden Skin");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang()._("(Harden Skin)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_SHAPE_SHIFTING;}
	@Override public int abstractQuality(){return Ability.QUALITY_BENEFICIAL_SELF;}

	@Override
	public void affectPhyStats(Physical affected, PhyStats affectableStats)
	{
		super.affectPhyStats(affected,affectableStats);
		affectableStats.setArmor(affectableStats.armor() - 10 - (2*getXLEVELLevel(invoker())));
	}

	@Override
	public void affectCharStats(MOB affected, CharStats affectableStats)
	{
		super.affectCharStats(affected,affectableStats);
		final int bonus=(2*super.getXLEVELLevel(invoker()));
		affectableStats.setStat(CharStats.STAT_SAVE_COLD,affectableStats.getStat(CharStats.STAT_SAVE_COLD)+10+affected.phyStats().level()+bonus);
		affectableStats.setStat(CharStats.STAT_SAVE_FIRE,affectableStats.getStat(CharStats.STAT_SAVE_FIRE)+affected.phyStats().level()+bonus);
		affectableStats.setStat(CharStats.STAT_SAVE_WATER,affectableStats.getStat(CharStats.STAT_SAVE_WATER)+25+affected.phyStats().level()+bonus);
	}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;
		super.unInvoke();
		if(canBeUninvoked())
			if((mob.location()!=null)&&(!mob.amDead()))
				mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,_("<S-YOUPOSS> skin softens."));
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		MOB target=mob;
		if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
			target=(MOB)givenTarget;

		if(target.fetchEffect(this.ID())!=null)
		{
			mob.tell(target,null,null,_("<S-YOUPOSS> skin is already hard."));
			return false;
		}

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			invoker=mob;
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?_("<T-YOUPOSS> skin hardens!"):_("^S<S-NAME> chant(s) to <T-NAMESELF> and <T-HIS-HER> skin hardens!^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				success=beneficialAffect(mob,target,asLevel,0);
				target.location().recoverRoomStats();
			}
		}
		else
			return beneficialWordsFizzle(mob,target,_("<S-NAME> chant(s) to <T-NAMESELF>, but nothing happens"));

		// return whether it worked
		return success;
	}
}


text: Element.alias('isDisplayed', 'isVisible');


text:
package callete.test;

import callete.api.Callete;
import org.junit.Test;

import java.io.IOException;

/**
 */
public class MonitoringTest {

  @Test
  public void test() throws IOException {
    int result = Callete.getMonitoringService().httpPing("www.google.de");
    assert(result == 200);
  }
}


text:
void CollectEvents(field_t *f, event_table_t *tab)
{
	unsigned int iprt;
	for (iprt = 0; iprt < NUM_SITES; iprt++)
	{
		event_t ev;
		PredictEvent(f, iprt, &ev);
		if (ev.active)
		{
			assert(ev.time >= 0);

			// insert event into table and store event index
			f->pts[iprt].ievent = EventTable_InsertEvent(&ev, tab);
		}
	}
}

//_______________________________________________________________________________________________________________________
///
/// \brief Update event associated with particle 'iprt' (remove associated event and predict new event)
///
static void UpdateFieldEvent(const int iprt, field_t *f, event_table_t *tab)
{
	// remove event associated with particle, if any
	if (f->pts[iprt].ievent >= 0) {
		EventTable_RemoveEvent(f->pts[iprt].ievent, tab);
		// will be set below
		// f->pts[iprt].ievent = -1;
	}

	// predict new event, if any
	event_t ev;
	PredictEvent(f, iprt, &ev);
	f->pts[iprt].ievent = EventTable_InsertEvent(&ev, tab);
}

//_______________________________________________________________________________________________________________________
///
/// \brief Process all active events within current time period and return total current
///
current_t SweepTable(field_t *f, event_table_t *tab)
{
	// time period
	const double period = NUM_SLOTS * tab->dt;

	// record cumulative momentum and energy current
	current_t J = { 0 };

	unsigned int islot;
	for (islot = 0; islot < NUM_SLOTS; islot++)
	{
		// reference to time slot
		event_slot_t *slot = &tab->slots[islot];

		while (slot->num > 0)	// as long as there are active events in current time slot
		{
			// process and update all events within current period

			// find earliest active event within time slot
			double tmin = period;	// ignore events beyond current time period
			int imin = -1;
			int i;
			for (i = 0; i < EVENTS_PER_SLOT; i++)
			{
				if (slot->events[i].active && slot->events[i].time < tmin)
				{
					tmin = slot->events[i].time;
					imin = i;
				}
			}
			// active event found?
			if (imin < 0) {
				break;	// next slot
			}

			// reference to event
			const event_t *ev = &slot->events[imin];

			// consistency check: particle of event must link back to event
			assert(f->pts[ev->iprt].ievent == (int)islot*EVENTS_PER_SLOT + imin);
			// consistency check: appropriate time slot
			assert(islot*tab->dt <= ev->time && ev->time < (islot + 1)*tab->dt);

			current_coll_t J_cur = PerformCollision(ev, f);
			// accumulate current
			J.r += J_cur.r_prev + J_cur.r + J_cur.r_next;
			J.p += J_cur.p_next;
			J.e += J_cur.e_next;

			// copy particle index since event pointer might be overwritten by 'UpdateFieldEvent' below
			int iprt = ev->iprt;

			// update events associated with current particle and neighbors since momenta might have changed;
			// note that this process might re-insert events into current time slot
			UpdateFieldEvent( iprt,                  f, tab);
			UpdateFieldEvent((iprt + 1) & SITE_MASK, f, tab);
			UpdateFieldEvent((iprt - 1) & SITE_MASK, f, tab);
		}
	}

	// normalize total current
	J.r /= (NUM_SITES * period);
	J.p /= (NUM_SITES * period);
	J.e /= (NUM_SITES * period);

	return J;
}

//_______________________________________________________________________________________________________________________
///
/// \brief Process all active events within current time period and return current for each lattice site
///
void SweepTableJSite(field_t *f, event_table_t *tab, current_t J[NUM_SITES])
{
	// time period
	const double period = NUM_SLOTS * tab->dt;

	// initially set to zero
	memset(J, 0, NUM_SITES * sizeof(current_t));

	unsigned int islot;
	for (islot = 0; islot < NUM_SLOTS; islot++)
	{
		// reference to time slot
		event_slot_t *slot = &tab->slots[islot];

		while (slot->num > 0)	// as long as there are active events in current time slot
		{
			// process and update all events within current period

			// find earliest active event within time slot
			double tmin = period;	// ignore events beyond current time period
			int imin = -1;
			int i;
			for (i = 0; i < EVENTS_PER_SLOT; i++)
			{
				if (slot->events[i].active && slot->events[i].time < tmin)
				{
					tmin = slot->events[i].time;
					imin = i;
				}
			}
			// active event found?
			if (imin < 0) {
				break;	// next slot
			}

			// reference to event
			const event_t *ev = &slot->events[imin];

			// consistency check: particle of event must link back to event
			assert(f->pts[ev->iprt].ievent == (int)islot*EVENTS_PER_SLOT + imin);
			// consistency check: appropriate time slot
			assert(islot*tab->dt <= ev->time && ev->time < (islot + 1)*tab->dt);

			// copy particle index since event pointer might be overwritten by 'UpdateFieldEvent' below
			int iprt = ev->iprt;
			int iprt_next = (iprt + 1) & SITE_MASK;
			int iprt_prev = (iprt - 1) & SITE_MASK;

			current_coll_t J_cur = PerformCollision(ev, f);
			// accumulate current
			J[iprt_prev].r += J_cur.r_prev;
			J[iprt     ].r += J_cur.r;
			J[iprt_next].r += J_cur.r_next;
			J[iprt_next].p += J_cur.p_next;
			J[iprt_next].e += J_cur.e_next;

			// update events associated with current particle and neighbors since momenta might have changed;
			// note that this process might re-insert events into current time slot
			UpdateFieldEvent( iprt,                  f, tab);
			UpdateFieldEvent((iprt + 1) & SITE_MASK, f, tab);
			UpdateFieldEvent((iprt - 1) & SITE_MASK, f, tab);
		}
	}
}

//_______________________________________________________________________________________________________________________
///
/// \brief Subtract 't_shift' from all timing events (to avoid overflow)
///
void GlobalTimeshift(const double t_shift, field_t *f, event_table_t *tab)
{
	// event table
	unsigned int islot;
	for (islot = 0; islot < NUM_SLOTS; islot++)
	{
		// reference to time slot
		event_slot_t *slot = &tab->slots[islot];

		int i;
		for (i = 0; i < EVENTS_PER_SLOT; i++) {
			slot->events[i].time -= t_shift;
		}
	}

	// lattice field
	unsigned int iprt;
	for (iprt = 0; iprt < NUM_SITES; iprt++)
	{
		f->pts[iprt].t -= t_shift;
	}
}