text:
require 'puppet/util/network_device/ipcalc'
require 'puppet/util/network_device/dell_ftos/model'
require 'puppet/util/network_device/dell_ftos/model/base'
require 'puppet/util/network_device/dell_ftos/model/scoped_value'

class Puppet::Util::NetworkDevice::Dell_ftos::Model::Interface < Puppet::Util::NetworkDevice::Dell_ftos::Model::Base

  attr_reader :params, :name
  def initialize(transport, facts, options)
    super(transport, facts)
    # Initialize some defaults
    @params         ||= {}
    @name           = options[:name] if options.key? :name

    # Register all needed Modules based on the availiable Facts
    register_modules
  end

  def mod_path_base
    return 'puppet/util/network_device/dell_ftos/model/interface'
  end

  def mod_const_base
    return Puppet::Util::NetworkDevice::Dell_ftos::Model::Interface
  end

  def param_class
    return Puppet::Util::NetworkDevice::Dell_ftos::Model::ScopedValue
  end

  def register_modules
    register_new_module(:base)
  end

  def before_update
    transport.command("show interfaces #{@name}")do |out|
      if out =~/Error:\s*(.*)/
        Puppet.debug "errror msg ::::#{$1}"
        Puppet.debug("Wait for 1 minute before re-validating")
        sleep(60)
        new_out = transport.command("show interfaces #{@name}")
        raise "The entered interface does not exist. Enter the correct interface." if new_out =~/Error:\s*(.*)/
      end
    end
    super
    transport.command("interface #{@name}", :prompt => /\(conf-if-\S+\)#\z/n)
  end

  def after_update
    transport.command("exit")
    super
  end

end


text:
set(VER 1.76.0)
set(REPO github.com/boostorg/interprocess)
set(FORK github.com/smanders/interprocess)
set(PRO_BOOSTINTERPROCESS
  NAME boostinterprocess
  SUPERPRO boost
  SUBDIR . # since the patch is all headers, apply to root of boost, not libs/interprocess
  WEB "interprocess" http://boost.org/libs/interprocess "Boost.Interprocess website"
  LICENSE "open" http://www.boost.org/users/license.html "Boost Software License"
  DESC "Shared memory, memory mapped files, process-shared mutexes, condition variables, containers and allocators"
  REPO "repo" https://${REPO} "interprocess repo on github"
  VER ${VER}
  GIT_ORIGIN https://${FORK}.git
  GIT_UPSTREAM https://${REPO}.git
  GIT_TRACKING_BRANCH develop
  GIT_TAG xp${VER}
  GIT_REF boost-${VER}
  PATCH ${PATCH_DIR}/boost.interprocess.patch
  PATCH_STRIP 2 # Strip NUM leading components from file names (defaults to 1)
  DIFF https://${FORK}/compare/boostorg:
  )

redpajama_set_name: RedPajamaGithub


text:
package com.google.code.pathlet.core.exception;

import com.google.code.pathlet.core.Resource;
/**
 *
 * @author Charlie Zhang
 *
 */
public class ResourceInstanceException extends ResourceException {

	private static final long serialVersionUID = -3767318767298470411L;

	private Resource resource;

	public ResourceInstanceException(Resource resource) {
		super();
		this.resource = resource;
	}

	public ResourceInstanceException(String message, Resource resource) {
		super(message);
		this.resource = resource;
	}

	public ResourceInstanceException(String message, Throwable cause, Resource resource) {
		super(message, cause);
		this.resource = resource;
	}

	public ResourceInstanceException(Throwable cause, Resource resource) {
		super(cause);
		this.resource = resource;
	}

	public Resource getResource() {
		return resource;
	}

}


text:
package ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.artifact.impl;

import java.io.File;

import org.drools.RuntimeDroolsException;

import ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.activity.Activity;
import ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.activity.impl.ActivityRelatedFactBase;
import ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.artifact.Artifact;

public class ArtifactBase extends ActivityRelatedFactBase implements Artifact {
	/**
	 *
	 */
	private static final long serialVersionUID = -5672946567969136742L;

	private String fileName;
	private String baseDir;

	private String name;

	private File _fileCache = null;

	protected ArtifactBase(){
	}

	protected ArtifactBase(Activity activity, String baseDir, String fileName) {
		super(activity);
		this.baseDir = baseDir;
		this.fileName = fileName;
	}

	protected ArtifactBase(Artifact other){
		super(other.getActivity());
		this.fileName = other.getFileName();
		this.baseDir = other.getBaseDir();
	}

	public boolean isDirectory() {
		return _getFile().isDirectory();
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
		_fileCache = null;
		this.validate(_getFile());
	}

	public String getBaseDir() {
		return baseDir;
	}

	public void setBaseDir(String baseDir) {
		this.baseDir = baseDir;
		_fileCache = null;
		//this.validate(_getFile());
	}

	protected void validate(File _getFile) throws RuntimeDroolsException{
		// ok
	}

	public String getAbsolutePath() {
		return _getFile().getAbsolutePath();
	}

	public final File _getFile() {
		if (_fileCache == null){
			_fileCache = new File(baseDir, fileName);
		}
		return _fileCache;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + " [name=" + name + ", fileName=" + fileName + ", activity=" + getActivity().toShortString() + "]";
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

	public ArtifactBase reset(Activity activity, Artifact artifact){
		return this.reset(activity, null, artifact.getBaseDir(), artifact.getFileName());
	}

	public ArtifactBase reset(Activity activity, String baseDir, String fileName) {
		return this.reset(activity, null, baseDir, fileName);
	}

	public ArtifactBase reset(Activity activity, String name, String baseDir, String fileName) {
		super.reset(activity);
		this.baseDir = baseDir;
		this.fileName = fileName;
		this.name = name;
		validate(_getFile());
		return this;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((_getFile() == null) ? 0 : _getFile().hashCode());
		result = prime * result
				+ ((getActivity() == null) ? 0 : getActivity().hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Artifact other = (Artifact) obj;
		if (_getFile() == null) {
			if (other._getFile() != null)
				return false;
		} else if (!_getFile().equals(other._getFile()))
			return false;
		if (getActivity() == null) {
			if (other.getActivity() != null)
				return false;
		} else if (!getActivity().equals(other.getActivity()))
			return false;
		if (name == null) {
			if (other.getName() != null)
				return false;
		} else if (!name.equals(other.getName()))
			return false;
		return true;
	}

}


text:
package org.wso2.carbon.endpoint.service;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axis2.util.XMLPrettyPrinter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.Entry;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.config.xml.SynapseXMLConfigurationFactory;
import org.apache.synapse.config.xml.XMLConfigConstants;
import org.apache.synapse.config.xml.endpoints.EndpointFactory;
import org.apache.synapse.config.xml.endpoints.EndpointSerializer;
import org.apache.synapse.endpoints.AbstractEndpoint;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.endpoints.EndpointContext;
import org.apache.synapse.endpoints.EndpointDefinition;
import org.apache.synapse.registry.Registry;
import org.wso2.carbon.endpoint.EndpointAdminException;
import org.wso2.carbon.endpoint.util.ConfigHolder;
import org.wso2.carbon.mediation.dependency.mgt.ConfigurationObject;
import org.wso2.carbon.mediation.dependency.mgt.services.DependencyManagementService;
import org.wso2.carbon.mediation.initializer.AbstractServiceBusAdmin;
import org.wso2.carbon.mediation.initializer.ServiceBusConstants;
import org.wso2.carbon.mediation.initializer.ServiceBusUtils;
import org.wso2.carbon.mediation.initializer.persistence.MediationPersistenceManager;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayOutputStream;
import java.lang.String;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

public class EndpointAdmin extends AbstractServiceBusAdmin {

    private static final Log log = LogFactory.getLog(EndpointAdmin.class);
    public static final String WSO2_ENDPOINT_MEDIA_TYPE = "application/vnd.wso2.esb.endpoint";

    /**
     * Set Endpoint status to Active
     *
     * @param endpointName name of the endpoint
     * @throws EndpointAdminException in case of an error
     */
    public void switchOn(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            Endpoint ep = getSynapseConfiguration().getEndpoint(endpointName);
            ep.getContext().switchOn();
            persistEndpoint(ep);

            if (log.isDebugEnabled()) {
                log.debug("Endpoint " + ep.getName() + " switched on");
            }

        } catch (SynapseException ex) {
            handleFault("Error switch on endpoint : " + endpointName, ex);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Switch off Endpoint
     *
     * @param endpointName name of the endpoint
     * @throws EndpointAdminException in case of an error
     */
    public void switchOff(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            Endpoint ep = getSynapseConfiguration().getEndpoint(endpointName);
            ep.getContext().switchOff();
            persistEndpoint(ep);

            if (log.isDebugEnabled()) {
                log.debug("Endpoint " + ep.getName() + " switched off");
            }
        } catch (SynapseException ex) {
            handleFault("Error switch off endpoint : " + endpointName, ex);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Add an Endpoint described by the given configuration
     *
     * @param epString - configuration representing the endpoint that needs
     *                 to be added
     * @return true if the endpoint was successfully added and false otherwise
     * @throws EndpointAdminException if the element is not an endpoint or if an endpoint
     *                                with the same name exists
     */
    public boolean addEndpoint(String epString) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            OMElement endpointElement;
            try {
                endpointElement = AXIOMUtil.stringToOM(epString);
            } catch (XMLStreamException e) {
                return false;
            }
            if (endpointElement.getQName().getLocalPart()
                    .equals(XMLConfigConstants.ENDPOINT_ELT.getLocalPart())) {

                String endpointName = endpointElement.getAttributeValue(new QName("name"));
                assertNameNotEmpty(endpointName);
                endpointName = endpointName.trim();
                log.debug("Adding endpoint : " + endpointName + " to the configuration");

                if (getSynapseConfiguration().getLocalRegistry()
                            .get(endpointName) != null) {
                    handleFault("The name " + endpointName +
                                " is already used within the configuration", null);
                } else {
                    SynapseConfiguration config = getSynapseConfiguration();
                    if (config.getEndpoint(endpointName) != null) {
                        handleFault("A endpoint with name "
                                    + endpointName + " is already there.", null);
                    }
                    SynapseXMLConfigurationFactory.defineEndpoint(
                            config, endpointElement, config.getProperties());
                    Endpoint endpoint = config.getEndpoint(endpointName);
                    if (endpoint != null) {
                        if (endpoint instanceof AbstractEndpoint) {
                            endpoint.setFileName(
                                    ServiceBusUtils.generateFileName(endpoint.getName()));
                        }
                        endpoint.init(getSynapseEnvironment());
                        persistEndpoint(endpoint);
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Added endpoint : " + endpointName + " to the configuration");
                }
                return true;
            } else {
                handleFault("Unable to create endpoint. Invalid XML definition", null);
            }
        } catch (SynapseException syne) {
            handleFault("Unable to add Endpoint ", syne);
        } finally {
            lock.unlock();
        }
        return false;
    }

    /**
     * Deletes the endpoint from the SynapseConfiguration
     *
     * @param endpointName - name of the endpoint to be deleted
     * @return true if the endpoint was successfully deleted and false otherwise
     * @throws EndpointAdminException if the proxy service name given is not existent in the
     *                                synapse configuration
     */
    public boolean deleteEndpoint(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            if (log.isDebugEnabled()) {
                log.debug("Deleting endpoint : " + endpointName + " from the configuration");
            }
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            Endpoint endpoint = synapseConfiguration.getDefinedEndpoints().get(endpointName);
            synapseConfiguration.removeEndpoint(endpointName);
            MediationPersistenceManager pm = getMediationPersistenceManager();
            String fileName = null;
            if (endpoint instanceof AbstractEndpoint) {
                fileName = endpoint.getFileName();
            }
            pm.deleteItem(endpointName, fileName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
            if (log.isDebugEnabled()) {
                log.debug("Endpoint : " + endpointName + " removed from the configuration");
            }
        } finally {
            lock.unlock();
        }
        return true;
    }

    /**
     * Delete selected endpoints
     * @param endpointNames
     * @throws EndpointAdminException
     */
    public void deleteSelectedEndpoint(String [] endpointNames) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            for(String endpointName : endpointNames){
                assertNameNotEmpty(endpointName);
                endpointName = endpointName.trim();
                if (log.isDebugEnabled()) {
                    log.debug("Deleting endpoint : " + endpointName + " from the configuration");
                }
                SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
                Endpoint endpoint = synapseConfiguration.getDefinedEndpoints().get(endpointName);
                synapseConfiguration.removeEndpoint(endpointName);
                MediationPersistenceManager pm = getMediationPersistenceManager();
                String fileName = null;
                if (endpoint instanceof AbstractEndpoint) {
                    fileName = endpoint.getFileName();
                }
                pm.deleteItem(endpointName, fileName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
                if (log.isDebugEnabled()) {
                    log.debug("Endpoint : " + endpointName + " removed from the configuration");
                }
            }

        } finally {
            lock.unlock();
        }
    }

    /**
     * Delete
     * @throws EndpointAdminException
     */
     public void deleteAllEndpointGroups() throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            Map<String, Endpoint> namedEndpointMap = synapseConfiguration.getDefinedEndpoints();
            Collection<String> namedEndpointCollection = namedEndpointMap.keySet();
            if (namedEndpointCollection.size()>0) {
                for (String endpointName : namedEndpointCollection) {
                    assertNameNotEmpty(endpointName);
                    endpointName = endpointName.trim();
                    if (log.isDebugEnabled()) {
                        log.debug("Deleting endpoint : " + endpointName + " from the configuration");
                    }
                    Endpoint endpoint = synapseConfiguration.getDefinedEndpoints().get(endpointName);
                    synapseConfiguration.removeEndpoint(endpointName);
                    MediationPersistenceManager pm = getMediationPersistenceManager();
                    String fileName = null;
                    if (endpoint instanceof AbstractEndpoint) {
                        fileName = endpoint.getFileName();
                    }
                    pm.deleteItem(endpointName, fileName, ServiceBusConstants.ITEM_TYPE_ENDPOINT);
                    if (log.isDebugEnabled()) {
                        log.debug("Endpoint : " + endpointName + " removed from the configuration");
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Gets the endpoint element as a string
     *
     * @param endpointName - name of the endpoint
     * @return String representing the endpoint with the given endpoint name
     * @throws Exception in case of an error
     */
    public String getEndpointConfiguration(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            if (synapseConfiguration.getEndpoint(endpointName) != null) {
                OMElement ele = EndpointSerializer.getElementFromEndpoint(
                        synapseConfiguration.getEndpoint(endpointName));
                return ele.toString();
            } else {
                handleFault("The endpoint named " + endpointName + " does not exist", null);
            }
        } finally {
            lock.unlock();
        }
        return null;
    }

    /**
     * Get all endpoint configurations from the synapse configuration
     *
     * @return a list of all the endpoints
     * @throws EndpointAdminException in case of an error
     */
    public String[] getEndpoints() throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            Map<String, Endpoint> namedEndpointMap = synapseConfiguration.getDefinedEndpoints();
            Collection<Endpoint> namedEndpointCollection = namedEndpointMap.values();

            List<String> epList = new ArrayList<String>();
            for (Endpoint ep : namedEndpointCollection) {
                OMElement ele = EndpointSerializer.getElementFromEndpoint(ep);
                epList.add(ele.toString());
            }
            return epList.toArray(new String[epList.size()]);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Get Metadata of all Endpoints of Synapse configuration
     *
     * @return EndpointMetaData
     */
    public EndpointMetaData[] getEndpointsData() {

        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            Map<String, Endpoint> namedEndpointMap = synapseConfiguration.getDefinedEndpoints();
            Collection<Endpoint> namedEndpointCollection = namedEndpointMap.values();

            List<Endpoint> epList = new ArrayList<Endpoint>();
            for (Endpoint ep : namedEndpointCollection) {
                epList.add(ep);
            }

            Collections.sort(epList, new Comparator<Endpoint>() {
                public int compare(Endpoint o1, Endpoint o2) {
                    return (o1).getName().compareToIgnoreCase((o2).getName());
                }
            });

            List<EndpointMetaData> metaDatas = new ArrayList<EndpointMetaData>();
            for (Endpoint ep : epList) {
                EndpointMetaData data = new EndpointMetaData();
                data.setName(ep.getName());
                data.setDescription(ep.getDescription());

                // Statistics
                EndpointDefinition def = ((AbstractEndpoint) ep).getDefinition();
                if (null != def) {
                    if (def.isStatisticsEnable()) {
                        data.setEnableStatistics(true);
                    } else {
                        data.setEnableStatistics(false);
                    }
                }

                if (ep.getContext().isState(EndpointContext.ST_ACTIVE)) {
                    data.setSwitchOn(true);
                } else {
                    data.setSwitchOn(false);
                }
                data.setEndpointString(EndpointSerializer.getElementFromEndpoint(ep).toString());
                metaDatas.add(data);
            }
            return metaDatas.toArray(new EndpointMetaData[metaDatas.size()]);

        } finally {
            lock.unlock();
        }
    }

    /**
     * Enable statistics collection for the specified endpoint
     *
     * @param endpointName name of the endpoint
     * @throws EndpointAdminException in case of an error
     */
    public void enableStatistics(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            Endpoint ep = getSynapseConfiguration().getEndpoint(endpointName);

            ((AbstractEndpoint) ep).getDefinition().enableStatistics();

            persistEndpoint(ep);
            if (log.isDebugEnabled()) {
                log.debug("Statistics enabled on endpoint : " + endpointName);
            }
        } catch (SynapseException syne) {
            handleFault("Error enabling statistics for the endpoint : " + endpointName, syne);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Stop collecting statistics for a specified endpoint
     *
     * @param endpointName name of the endpoint
     * @throws EndpointAdminException on error
     */
    public void disableStatistics(String endpointName) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            assertNameNotEmpty(endpointName);
            endpointName = endpointName.trim();
            Endpoint ep = getSynapseConfiguration().getEndpoint(endpointName);
            ((AbstractEndpoint) ep).getDefinition().disableStatistics();

            persistEndpoint(ep);
            if (log.isDebugEnabled()) {
                log.debug("Statistics disabled on endpoint : " + endpointName);
            }
        } catch (SynapseException syne) {
            handleFault("Error disabling statistics for the endpoint : " + endpointName, syne);
        } finally {
            lock.unlock();
        }
    }

    private void persistEndpoint(Endpoint ep) throws EndpointAdminException {
        MediationPersistenceManager pm = getMediationPersistenceManager();
        pm.saveItem(ep.getName(), ServiceBusConstants.ITEM_TYPE_ENDPOINT);
    }

    private void assertNameNotEmpty(String endpointName) throws EndpointAdminException {
        if (endpointName == null || "".equals(endpointName.trim())) {
            handleFault("Invalid name : Name is empty.", null);
        }
    }

    private void handleFault(String message, Exception e) throws EndpointAdminException {
        if (e != null) {
            log.error(message, e);
            throw new EndpointAdminException(e.getMessage(), e);
        } else {
            log.error(message);
            throw new EndpointAdminException(message);
        }
    }

    /**
     * Update an existing endpoint from the given String representation of the XML
     *
     * @param epString - String representing the XML which describes the
     *                 Endpoint element
     * @return true if the endpoint was saved successfully and false otherwise
     * @throws EndpointAdminException if the endpoint does not exists in the
     *                                SynapseConfiguration
     */
    public boolean saveEndpoint(String epString) throws EndpointAdminException {
        OMElement endpointElement;
        final Lock lock = getLock();
        try {
            lock.lock();
            try {
                endpointElement = AXIOMUtil.stringToOM(epString);
            } catch (XMLStreamException e) {
                return false;
            }
            if (endpointElement.getQName().getLocalPart()
                    .equals(XMLConfigConstants.ENDPOINT_ELT.getLocalPart())) {

                String endpointName = endpointElement.getAttributeValue(new QName("name"));
                assertNameNotEmpty(endpointName);
                endpointName = endpointName.trim();
                if (log.isDebugEnabled()) {
                    log.debug("Updating the definition of the endpoint : " + endpointName);
                }

                Endpoint previousEndpoint = getSynapseConfiguration().getEndpoint(
                        endpointName.trim());

                if (previousEndpoint == null) {
                    addEndpoint(epString);
                }

                boolean statisticsState = false;

                EndpointDefinition def = null;
                if (null != previousEndpoint) {
                    def = ((AbstractEndpoint) previousEndpoint).getDefinition();
                }
                if (null != def && def.isStatisticsEnable()) {
                    statisticsState = true;
                }

                String fileName = null;
                if (null != previousEndpoint && previousEndpoint instanceof AbstractEndpoint) {
                    fileName = previousEndpoint.getFileName();
                }

                Endpoint endpoint = EndpointFactory.getEndpointFromElement(
                        endpointElement, false, getSynapseConfiguration().getProperties());
                if (endpoint == null) {
                    handleFault("Newly created endpoint is null ", null);
                }
                if (null != def) {
                    if (statisticsState) {
                        ((AbstractEndpoint) endpoint).getDefinition()
                                .enableStatistics();
                    }
                }

                if (fileName != null && endpoint instanceof AbstractEndpoint) {
                    endpoint.setFileName(fileName);
                }

                endpoint.init(getSynapseEnvironment());
                endpointName = endpointName.trim();
                getSynapseConfiguration().removeEndpoint(endpointName);
                getSynapseConfiguration().addEndpoint(endpointName, endpoint);
                persistEndpoint(endpoint);
                if (log.isDebugEnabled()) {
                    log.debug("Updated the definition of the endpoint : " + endpointName);
                }
                return true;
            } else {
                handleFault("Unable to update endpoint. Invalid XML definition", null);
            }
        } catch (SynapseException syne) {
            handleFault("Unable to edit Endpoint ", syne);
        } finally {
            lock.unlock();
        }
        return false;
    }

    /**
     * Update an existing Endpoint endpoint in the registry
     *
     * @param key    dynamic endpoint key
     * @param epName endpoint name
     * @return whether operation is successful
     * @throws EndpointAdminException on Error
     */
    public boolean saveDynamicEndpoint(String key, String epName) throws EndpointAdminException {
        OMElement endpointElement;
        final Lock lock = getLock();
        try {
            lock.lock();
            endpointElement = AXIOMUtil.stringToOM(epName);

            if (endpointElement.getQName().getLocalPart()
                    .equals(XMLConfigConstants.ENDPOINT_ELT.getLocalPart())) {

                String endpointName = "dynamicEndpoint";
                if (log.isDebugEnabled()) {
                    log.debug("Updating endpoint : " + endpointName + " in the Synapse registry");
                }

                Registry registry = getSynapseConfiguration().getRegistry();
                if (registry != null) {
                    if (registry.getRegistryEntry(key).getType() == null) {
                        handleFault("No resource exists by the key '" + key + "'", null);
                    }

                    registry.updateResource(key, endpointElement);

                    if (log.isDebugEnabled()) {
                        log.debug("Updated endpoint : " + endpointName + " in the Synapse registry");
                    }
                    return true;
                }
            } else {
                handleFault("Unable to create endpoint. Invalid XML definition", null);
            }
        } catch (XMLStreamException e) {
            return false;
        } finally {
            lock.unlock();
        }
        return false;
    }

    /**
     * Add an endpoint to the Synapse registry
     *
     * @param key    of the dynamic endpoint
     * @param epConfiguration endpoint configuration
     * @throws EndpointAdminException in case of an error
     */
    public boolean addDynamicEndpoint(String key, String epConfiguration) throws EndpointAdminException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        stream.reset();
        String originalKey = key;
        try {
            org.wso2.carbon.registry.core.Registry registry;
            if (key.startsWith("conf:")) {
                registry = getConfigSystemRegistry();
                key = key.replace("conf:", "");
            } else {
                registry = getGovernanceRegistry();
                key = key.replace("gov:", "");
            }
            if (!registry.resourceExists(key)) {

                try {
                    OMElement endpointElement = AXIOMUtil.stringToOM(epConfiguration);
                    OMFactory fac = OMAbstractFactory.getOMFactory();
                    String name = originalKey.replace(":", "/");
                    endpointElement.addAttribute(fac.createOMAttribute("name",
                                                                       fac.createOMNamespace(XMLConfigConstants.NULL_NAMESPACE, ""),
                                                                       name));
                    XMLPrettyPrinter.prettify(endpointElement, stream);
                } catch (Exception e) {
                    handleFault("Unable to pretty print configuration", e);
                }
                epConfiguration = new String(stream.toByteArray()).trim();

                Resource resource = registry.newResource();
                resource.setMediaType(WSO2_ENDPOINT_MEDIA_TYPE);
                resource.setContent(epConfiguration);
                registry.put(key, resource);
            } else {
                log.warn("Resource is already exists");
                return false;
            }
        } catch (RegistryException e) {
            handleFault("WSO2 Registry Exception", e);
            return false;
        }
        return true;
    }

    /**
     * Get a dynamic endpoint from the registry
     *
     * @param key dynamic endpoint key
     * @return dynamic endpoint configuration
     * @throws EndpointAdminException on an error
     */
    public String getDynamicEndpoint(String key) throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synConfig = getSynapseConfiguration();
            Registry registry = synConfig.getRegistry();
            if (registry != null) {
                if (registry.getRegistryEntry(key).getType() == null) {
                    handleFault("No resource is available by the key '" + key + "'", null);
                }
            } else {
                handleFault("Unable to access the registry instance for the ESB", null);
            }
            OMElement e = null;
            if (registry != null) {
				Object obj = null;
				try {
					obj = registry.getResource(new Entry(key),
							synConfig.getProperties());
				} catch (Exception e1) {
					log.error("Invalid endpoint configuration", e1);
					return null;
				}
				if (obj instanceof OMElement) {
					e = (OMElement) obj;
				} else {
					log.error("Invalid endpoint configuration");
				}
				// e = (OMElement) registry.getResource(new Entry(key),
				// synConfig.getProperties());
			}
            if (e != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Found dynamic endpoint " + key);
                }
                return e.toString();
            }
        } finally {
            lock.unlock();
        }
        return null;
    }

    /**
     * Check registry is available or not
     * @return boolean
     * @throws EndpointAdminException
     */

    public boolean isRegisterNull() throws EndpointAdminException{
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synConfig = getSynapseConfiguration();
            Registry registry = synConfig.getRegistry();
            if (registry == null) {
                return true;
            }
        } finally {
            lock.unlock();
        }
        return false;
    }

    /**
     * Get all endpoints stored in the registry
     *
     * @return endpoints in the registry
     * @throws EndpointAdminException in case of an error
     */
    public String[] getDynamicEndpoints() throws EndpointAdminException {
        org.wso2.carbon.registry.core.Registry registry;
        final Lock lock = getLock();
        try {
            lock.lock();
            String[] configInfo = getConfigSystemRegistry() != null ? getMimeTypeResult(getConfigSystemRegistry()):new String[0];
            String[] govInfo = getGovernanceRegistry() !=null ?getMimeTypeResult(getGovernanceRegistry()):new String[0];
            String[] info = new String[configInfo.length + govInfo.length];

            int ptr = 0;
            for (String aConfigInfo : configInfo) {
                info[ptr] = "conf:" + aConfigInfo;
                ++ptr;
            }
            for (String aGovInfo : govInfo) {
                info[ptr] = "gov:" + aGovInfo;
                ++ptr;
            }
            Arrays.sort(info);
            if (log.isDebugEnabled()) {
                log.debug("Found " + info.length + " dynamic endpoints");
            }
            return info;
        } catch (RegistryException e) {
            return null;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Remove a endpoint form the registry
     *
     * @param key dynamic endpoint key
     * @return whether operation is successful
     * @throws EndpointAdminException in case of an error
     */
    public boolean deleteDynamicEndpoint(String key) throws EndpointAdminException {
        Lock lock = getLock();
        try {
            lock.lock();
            Registry registry = getSynapseConfiguration().getRegistry();
            if (registry != null) {
                if (registry.getRegistryEntry(key).getType() == null) {
                    handleFault("The key '" + key +
                                "' cannot be found within the configuration", null);
                }
                registry.delete(key);

                if (log.isDebugEnabled()) {
                    log.debug("Deleted endpoint with key: " + key + " from the Synapse registry");
                }
                return true;
            }
        } finally {
            lock.unlock();
        }
        return false;
    }

    private String[] getMimeTypeResult(org.wso2.carbon.registry.core.Registry targetRegistry)
            throws EndpointAdminException, RegistryException {
        String sql = "SELECT REG_PATH_ID, REG_NAME FROM REG_RESOURCE WHERE REG_MEDIA_TYPE = ?";
        Map parameters = new HashMap();
        parameters.put("query", sql);
        parameters.put("1", WSO2_ENDPOINT_MEDIA_TYPE);
        Resource result = targetRegistry.executeQuery(null, parameters);
        return (String[]) result.getContent();
    }

    /**
     * Get dependents of a particular endpoint.
     *
     * @param endpointName endpoint name
     * @return dependants of a endpoints
     */
    public ConfigurationObject[] getDependents(String endpointName) {
        DependencyManagementService dependencyMgr = ConfigHolder.getInstance().
                getDependencyManager();
        if (dependencyMgr != null) {
            ConfigurationObject[] dependents = dependencyMgr.getDependents(
                    ConfigurationObject.TYPE_ENDPOINT, endpointName);
            if (dependents != null && dependents.length > 0) {
                List<ConfigurationObject> deps = new ArrayList<ConfigurationObject>();
                for (ConfigurationObject o : dependents) {
                    if (o.getType() != ConfigurationObject.TYPE_UNKNOWN) {
                        deps.add(o);
                    }
                }

                if (deps.size() > 0) {
                    return deps.toArray(new ConfigurationObject[deps.size()]);
                }
            }
        }
        return null;
    }

    public String[] getEndPointsNames() throws EndpointAdminException {
        final Lock lock = getLock();
        try {
            lock.lock();
            SynapseConfiguration synapseConfiguration = getSynapseConfiguration();
            Map<String, Endpoint> namedEndpointMap = synapseConfiguration.getDefinedEndpoints();
            Collection<Endpoint> namedEndpointCollection = namedEndpointMap.values();
            return listToNames(namedEndpointCollection.toArray(
                    new Endpoint[namedEndpointCollection.size()]));
        } finally {
            lock.unlock();
        }
    }

    private String[] listToNames(Endpoint[] eps) {
        if (eps == null) {
            return null;
        } else {
            String[] datas = new String[eps.length];
            for (int i = 0; i < eps.length; i++) {
                Endpoint ep = eps[i];
                datas[i] = ep.getName();
            }
            return datas;
        }
    }

    public int getEndpointCount() throws EndpointAdminException {
        final Lock lock = getLock();
        try{
            lock.lock();
            return getSynapseConfiguration().getDefinedEndpoints().size();
        } catch (Exception e) {
            handleFault("Error while retrieving Endpoint count", e);
        } finally {
            lock.unlock();
        }
        return 0;
    }

    public int getDynamicEndpointCount() throws EndpointAdminException {
        org.wso2.carbon.registry.core.Registry registry;
        try {
            String[] govList = getGovernanceRegistry() != null? getMimeTypeResult(getGovernanceRegistry()) :new String[0];
            String[] confList = getConfigSystemRegistry() != null ? getMimeTypeResult(getConfigSystemRegistry()):new String [0];
            return confList.length + govList.length;
        } catch (Exception e) {
            handleFault("Error while retrieving dynamic endpoint count", e);
        }
        return 0;
    }
}


text:
id: 5900f4c81000cf542c50ffd9
challengeType: 5
title: 'Problem 347: Largest integer divisible by two primes'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(euler347(), 11109800204052, "<code>euler347()</code> should return 11109800204052.");'

```

## Challenge Seed

```js
function euler347() {
  // Good luck!
  return true;
}

euler347();

```

## Solution

```js
// solution required
```


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.codelibs</groupId>
  <artifactId>elasticsearch-plugin-archetype</artifactId>
  <version>6.6.1-SNAPSHOT</version>
  <name>Archetype for elasticsearch plugin</name>
  <description>This archetype generates your project for Elasticsearch plugin.</description>
  <url>https://github.com/codelibs/elasticsearch-plugin-archetype</url>
  <inceptionYear>2012</inceptionYear>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <organization>
    <name>CodeLibs</name>
    <url>http://www.codelibs.org/</url>
  </organization>
  <scm>
    <connection>scm:git:git@github.com:codelibs/elasticsearch-plugin-archetype.git</connection>
    <developerConnection>scm:git:git@github.com:codelibs/elasticsearch-plugin-archetype.git</developerConnection>
    <url>git@github.com:codelibs/elasticsearch-plugin-archetype.git</url>
  </scm>
  <parent>
    <groupId>org.sonatype.oss</groupId>
    <artifactId>oss-parent</artifactId>
    <version>9</version>
  </parent>
  <developers>
    <developer>
      <id>marevol</id>
      <name>Shinsuke Sugaya</name>
      <email>shinsuke(at)yahoo.co.jp</email>
    </developer>
  </developers>
  <build>
    <defaultGoal>validate</defaultGoal>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <configuration>
            <updateReleaseInfo>true</updateReleaseInfo>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-archetype-plugin</artifactId>
        <extensions>true</extensions>
      </plugin>
    </plugins>
    <extensions>
      <extension>
        <groupId>org.apache.maven.archetype</groupId>
        <artifactId>archetype-packaging</artifactId>
      </extension>
    </extensions>
  </build>
</project>


text:
export default function (commits) {
  let bump = "patch";
  commits.forEach(function (commit) {
    if (commit.breaking) {
      bump = "major";
    } else if (commit.type === "feat" && bump === "patch") {
      bump = "minor";
    }
  });
  return bump;
}


text:
'use strict';

let libPath = require('path');

module.exports = {
  installationRoot: libPath.resolve(__dirname, '../../../tmp/npm-installer/packages'),
  packagesInfoPath: libPath.resolve(__dirname, '../../../tmp/npm-installer/packages-info.js'),
  webpackConfigPath: libPath.resolve(__dirname, './webpack.config.js')
};


text:
using System.Runtime.Serialization;

namespace DD.CloudControl.Client.Models.Network
{
	/// <summary>
	/// 	Well-known network domain types.
	/// </summary>
	public enum NetworkDomainType
	{
		/// <summary>
		///		An unknown network domain type.
		/// </summary>
		/// <remarks>
		///		Used to detect uninitialised values; do not use directly.
		/// </remarks>
		Unknown = 0,

		/// <summary>
		///		A basic network domain.
		/// </summary>
		/// <remarks>
		///		Supports all features except load-balancing and anti-affinity.
		/// </remarks>
		[EnumMember(Value = "ESSENTIALS")]
		Essentials = 1,

		/// <summary>
		///		An advanced network domain.
		/// </summary>
		/// <remarks>
		///		Supports all features, including load-balancing and anti-affinity.
		/// </remarks>
		[EnumMember(Value = "ADVANCED")]
		Advanced = 2
	}
}


text:
<?php

namespace Users\Adapter;

use Zend\Authentication;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Adapter\AbstractAdapter;
use Zend\Db\Adapter\Adapter;

use Zend\Authentication\Result as AuthenticationResult;
// use Zend\Http\Request as HTTPRequest;
// use Zend\Http\Response as HTTPResponse;
// use Zend\Uri\UriFactory;
// use Zend\Crypt\Utils as CryptUtils;

/**
 * HTTP Authentication Adapter
 *
 * Implements a pretty good chunk of RFC 2617.
 *
 * @todo       Support auth-int
 * @todo       Track nonces, nonce-count, opaque for replay protection and stale support
 * @todo       Support Authentication-Info header
 */
class PasswordHash extends AbstractAdapter implements AdapterInterface
// class PasswordHash implements AdapterInterface
{
	protected $dbAdapter;

	protected $tableName;

	protected $identityColumn;

	protected $credentialColumn;

	protected $resultRow;

	/**
	 * __construct() - Sets configuration options
	 *
	 * @param DbAdapter $zendDb
	 * @param string    $tableName           Optional
	 * @param string    $identityColumn      Optional
	 * @param string    $credentialColumn    Optional
	 */
	public function __construct(
								Adapter $zendDb,
								$tableName,
								$identityColumn,
								$credentialColumn
								) {
		$this->dbAdapter		= $zendDb;
		$this->credentialColumn	= $credentialColumn;
		$this->identityColumn	= $identityColumn;
		$this->tableName		= $tableName;
	}

	public function authenticate() {
		var_dump($this->getCredential());
		$spResponse = 0;
		$prepareStmt = $this->dbAdapter->createStatement();
		$sql	= 'SELECT * FROM '.$this->tableName.' WHERE '.$this->identityColumn.' = :identity';

		$prepareStmt->prepare($sql);
		$result = $prepareStmt->execute(array('identity'	=> $this->getIdentity()));
		var_dump(password_verify($this->getCredential(), $result->current()['password']));
		var_dump($result->count());

		if($result->count() <> 1)
		{
			return new AuthenticationResult(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND, $this->getIdentity());
		}

		$this->resultRow	= $result->current();
		if(password_verify($this->getCredential(), $this->resultRow[$this->credentialColumn]))
		{
			unset($this->resultRow[$this->credentialColumn]);
			return new AuthenticationResult(AuthenticationResult::SUCCESS, $this->getIdentity());
		}

		return new AuthenticationResult(AuthenticationResult::FAILURE, $this->getIdentity());
	}

	public function getResultRowObject() {
 		return (object) $this->resultRow;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout android:id="@+id/coordinatorLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <com.averi.worldscribe.views.MarqueeToolbar
            android:id="@+id/my_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:titleTextColor="@android:color/white"
            style="@style/AppTheme" />
    </com.google.android.material.appbar.AppBarLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/editLinkActivityTopMargin">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:orientation="vertical"
            tools:context=".activities.CreateArticleActivity"
            android:id="@+id/root"
            android:gravity="center"
            android:focusableInTouchMode="true" >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:id="@+id/articleName"
                android:inputType="text"
                android:hint="@string/articleNameHint"
                android:textSize="@dimen/headerTextSize"
                android:textColor="?attr/colorPrimary"
                android:textColorHint="?attr/colorPrimaryDark" />

            <Space
                android:layout_width="0dp"
                android:layout_height="@dimen/verticalSpacing" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView"
                android:text="@string/categoryText"
                android:textSize="@dimen/headerTextSize"
                android:textColor="?attr/colorPrimary" />

            <Space
                android:layout_width="0dp"
                android:layout_height="@dimen/verticalSpacing" />

            <Spinner
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/categorySelection"
                android:background="?attr/themedBorder" />

            <Space
                android:layout_width="0dp"
                android:layout_height="@dimen/headerSpacing" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/createButtonText"
                android:id="@+id/create"
                android:textAllCaps="false"
                android:textColor="@android:color/white"
                android:background="?attr/buttonColorSelector"
                android:textSize="@dimen/headerTextSize"
                android:padding="@dimen/buttonPadding"
                android:enabled="false"
                android:onClick="createArticle" />

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/loadingCreateArticleLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/createArticleProgressCircle"
            style="?android:attr/progressBarStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxWidth="@dimen/progressCircleSize"
            android:maxHeight="@dimen/progressCircleSize"
            android:minWidth="@dimen/progressCircleSize"
            android:minHeight="@dimen/progressCircleSize" />
    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
from django.db import models
from django.db.models.loading import BaseAppCache
from django.db.models.options import DEFAULT_NAMES
from django.utils import six
from django.utils.module_loading import import_by_path

class InvalidBasesError(ValueError):
    pass

class ProjectState(object):
    """
    Represents the entire project's overall state.
    This is the item that is passed around - we do it here rather than at the
    app level so that cross-app FKs/etc. resolve properly.
    """

    def __init__(self, models=None):
        self.models = models or {}
        self.app_cache = None

    def add_model_state(self, model_state):
        self.models[(model_state.app_label, model_state.name.lower())] = model_state

    def clone(self):
        "Returns an exact copy of this ProjectState"
        return ProjectState(
            models = dict((k, v.clone()) for k, v in self.models.items())
        )

    def render(self):
        "Turns the project state into actual models in a new AppCache"
        if self.app_cache is None:
            self.app_cache = BaseAppCache()
            # We keep trying to render the models in a loop, ignoring invalid
            # base errors, until the size of the unrendered models doesn't
            # decrease by at least one, meaning there's a base dependency loop/
            # missing base.
            unrendered_models = list(self.models.values())
            while unrendered_models:
                new_unrendered_models = []
                for model in unrendered_models:
                    try:
                        model.render(self.app_cache)
                    except InvalidBasesError:
                        new_unrendered_models.append(model)
                if len(new_unrendered_models) == len(unrendered_models):
                    raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
                unrendered_models = new_unrendered_models
        return self.app_cache

    @classmethod
    def from_app_cache(cls, app_cache):
        "Takes in an AppCache and returns a ProjectState matching it"
        models = {}
        for model in app_cache.get_models():
            model_state = ModelState.from_model(model)
            models[(model_state.app_label, model_state.name.lower())] = model_state
        return cls(models)

class ModelState(object):
    """
    Represents a Django Model. We don't use the actual Model class
    as it's not designed to have its options changed - instead, we
    mutate this one and then render it into a Model as required.

    Note that while you are allowed to mutate .fields, you are not allowed
    to mutate the Field instances inside there themselves - you must instead
    assign new ones, as these are not detached during a clone.
    """

    def __init__(self, app_label, name, fields, options=None, bases=None):
        self.app_label = app_label
        self.name = name
        self.fields = fields
        self.options = options or {}
        self.bases = bases or (models.Model, )
        # Sanity-check that fields is NOT a dict. It must be ordered.
        if isinstance(self.fields, dict):
            raise ValueError("ModelState.fields cannot be a dict - it must be a list of 2-tuples.")

    @classmethod
    def from_model(cls, model):
        """
        Feed me a model, get a ModelState representing it out.
        """
        # Deconstruct the fields
        fields = []
        for field in model._meta.local_fields:
            name, path, args, kwargs = field.deconstruct()
            field_class = import_by_path(path)
            fields.append((name, field_class(*args, **kwargs)))
        # Extract the options
        options = {}
        for name in DEFAULT_NAMES:
            # Ignore some special options
            if name in ["app_cache", "app_label"]:
                continue
            elif name in model._meta.original_attrs:
                if name == "unique_together":
                    options[name] = set(model._meta.original_attrs["unique_together"])
                else:
                    options[name] = model._meta.original_attrs[name]
        # Make our record
        bases = tuple(
            ("%s.%s" % (base._meta.app_label, base._meta.object_name.lower()) if hasattr(base, "_meta") else base)
            for base in model.__bases__
            if (not hasattr(base, "_meta") or not base._meta.abstract)
        )
        if not bases:
            bases = (models.Model, )
        return cls(
            model._meta.app_label,
            model._meta.object_name,
            fields,
            options,
            bases,
        )

    def clone(self):
        "Returns an exact copy of this ModelState"
        # We deep-clone the fields using deconstruction
        fields = []
        for name, field in self.fields:
            _, path, args, kwargs = field.deconstruct()
            field_class = import_by_path(path)
            fields.append((name, field_class(*args, **kwargs)))
        # Now make a copy
        return self.__class__(
            app_label = self.app_label,
            name = self.name,
            fields = fields,
            options = dict(self.options),
            bases = self.bases,
        )

    def render(self, app_cache):
        "Creates a Model object from our current state into the given app_cache"
        # First, make a Meta object
        meta_contents = {'app_label': self.app_label, "app_cache": app_cache}
        meta_contents.update(self.options)
        if "unique_together" in meta_contents:
            meta_contents["unique_together"] = list(meta_contents["unique_together"])
        meta = type("Meta", tuple(), meta_contents)
        # Then, work out our bases
        bases = tuple(
            (app_cache.get_model(*base.split(".", 1)) if isinstance(base, six.string_types) else base)
            for base in self.bases
        )
        if None in bases:
            raise InvalidBasesError("Cannot resolve one or more bases from %r" % self.bases)
        # Turn fields into a dict for the body, add other bits
        body = dict(self.fields)
        body['Meta'] = meta
        body['__module__'] = "__fake__"
        # Then, make a Model object
        return type(
            self.name,
            bases,
            body,
        )

    def get_field_by_name(self, name):
        for fname, field in self.fields:
            if fname == name:
                return field
        raise ValueError("No field called %s on model %s" % (name, self.name))


text:
FROM ubuntu:18.04
MAINTAINER Atsuhiro Kubo <kubo@iteman.jp>

RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
RUN apt-get update
RUN apt-get -y upgrade
RUN apt-get install -y apt-utils
RUN apt-get install -y software-properties-common
RUN apt-get install -y supervisor
RUN apt-get install -y apache2
RUN apt-get install -y mysql-client-core-5.7
RUN apt-get install -y git
RUN apt-get install -y less vim-tiny
RUN apt-get install -y apg
RUN apt-get install -y sudo
RUN apt-get install -y unzip

# PHP
RUN apt-get update
RUN apt-get install -y php7.2 php7.2-curl php7.2-intl php7.2-mysql php-xdebug php-apcu php7.2-dev libapache2-mod-php7.2 php7.2-mbstring php7.2-zip

# Supervisor
RUN mkdir -p /var/log/supervisor
ADD supervisor/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Apache2
ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_LOG_DIR /var/log/apache2
ENV APP_DOCUMENT_ROOT /var/www
EXPOSE 80
ADD apache2/app.conf /etc/apache2/sites-available/000-default.conf
ADD apache2/apache2 /usr/local/sbin/apache2
RUN chmod 755 /usr/local/sbin/apache2
RUN a2enmod rewrite
RUN sed -i "s/^\\( *export \+LANG.*\\)/#\\1/" /etc/apache2/envvars

# PHP
ENV PHP_INI ""
ENV XDEBUG_REMOTE_PORT ""
ADD php7/app.ini /etc/php/7.2/apache2/conf.d/90-app.ini
ADD php7/app.ini /etc/php/7.2/cli/conf.d/90-app.ini
ADD php7/timezone.sh /usr/local/sbin/php7-timezone.sh

# PHP application
ADD app/init /usr/local/sbin/app-init
RUN chmod 755 /usr/local/sbin/app-init
ADD app/composer /usr/local/bin/composer
RUN chmod 755 /usr/local/bin/composer
RUN chown root.root /usr/local/bin/composer

# System
ENV TZ ""
ENV LANG ""
ADD system/init /usr/local/sbin/system-init
RUN chmod 755 /usr/local/sbin/system-init
ADD system/locale.sh /usr/local/sbin/system-locale.sh
ADD system/timezone.sh /usr/local/sbin/system-timezone.sh

# Others
ENV HOME /root
WORKDIR /root
RUN mkdir /var/app
RUN echo "This file is a placeholder to expose /var/app directory after creating a new container from Kitematic." > /var/app/.placeholder
VOLUME /var/app

# Command
CMD ["/usr/local/sbin/system-init"]


text:
import { REMOVE_ITEM, TOGGLE_ITEM_STATUS, TOGGLE_COMPLETED_ITEMS_VISIBILITY } from '../constants';
import { removeItem, toggleItemStatus, toggleCompletedItems } from '../actions';

describe('actions', () => {
  it('should create action to remove an item', () => {
    const action = removeItem(341);

    expect(action).toEqual({
      type: REMOVE_ITEM,
      id: 341
    });
  });

  it('should create action to toggle item status', () => {
    const action = toggleItemStatus(12);

    expect(action).toEqual({
      type: TOGGLE_ITEM_STATUS,
      id: 12
    });
  });

  it('should create action to toggle the visibility of completed items', () => {
    const action = toggleCompletedItems();

    expect(action).toEqual({
      type: TOGGLE_COMPLETED_ITEMS_VISIBILITY,
    });
  });
});


text:
package io.corbel.lib.queries.request;

public class Sum extends FieldAggregation {

    public Sum(String field) {
        super(field);
    }

    @Override
    public AggregationOperator getOperator() {
        return AggregationOperator.$SUM;
    }

}


text:
typedef void ( * TaskHandler_t )();

struct TaskLowLevel_t {
    uint8_t* StackStart;
};

TaskLowLevel_t TaskAllocate(TaskHandler_t Task, uint16_t StackSize);

#endif


text:
package com.baidu.rigel.biplatform.ma.resource.cache;

import org.springframework.util.StringUtils;

/**
 * 缓存key的生成方式
 * @author zhongyi
 *
 *         2014-8-6
 */
public final class CacheKeyGenerator {

    /**
     * DIV
     */
    private static final String DIV = "_";

    /**
     * REPORT_PREFIX
     */
    private static final String REPORT_PREFIX = "report_";

    /**
     * RUNTIME_PREFIX
     */
    private static final String RUNTIME_PREFIX = "runtime_";

    /**
     * 构造函数
     */
    private CacheKeyGenerator() {

    }

    /**
     *
     * @param args
     * @return
     */
    public static String generateJointedKey(String... args) {
        String keyBase = StringUtils.arrayToDelimitedString(args, DIV);
        return keyBase;
    }

    /**
     *
     * @param product
     * @param report
     * @return
     */
    public static String generateSessionReportKey(String sessionId, String reportId,
        String productLine) {
        return REPORT_PREFIX + productLine + DIV + reportId + DIV + sessionId;
    }

    /**
     *
     * @param product
     * @param report
     * @return
     */
    public static String generateRuntimeReportKey(String sessionId, String reportId,
        String productLine) {
        return RUNTIME_PREFIX + productLine + DIV + reportId + DIV + sessionId;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `src/http/client/error.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>error.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../../../main.css">

    <link rel="shortcut icon" href="https://lambdastackio.github.io/static/images/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100

// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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.

use std::error;
use std::io;
use std::fmt;
use std::result;

use hyper;
use openssl;
use url;

#[derive(Debug)]
pub enum Error {
    HyperError(hyper::error::Error),
    /// Occurs when an improper http or https proxy value is given.
    InvalidProxyValue(String),
    IO(io::Error),
    SslError(openssl::error::Error),
    /// When an error occurs attempting to parse a string into a URL.
    UrlParseError(url::ParseError),
}

pub type Result<T> = result::Result<T, Error>;

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let msg = match *self {
            Error::HyperError(ref err) => format!("{}", err),
            Error::IO(ref e) => format!("{}", e),
            Error::InvalidProxyValue(ref e) => format!("Invalid proxy value: {:?}", e),
            Error::SslError(ref e) => format!("{}", e),
            Error::UrlParseError(ref e) => format!("{}", e),
        };
        write!(f, "{}", msg)
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::HyperError(ref err) => err.description(),
            Error::IO(ref err) => err.description(),
            Error::InvalidProxyValue(_) => "Invalid proxy value",
            Error::SslError(ref err) => err.description(),
            Error::UrlParseError(ref err) => err.description(),
        }
    }
}

impl From<hyper::error::Error> for Error {
    fn from(err: hyper::error::Error) -> Error {
        Error::HyperError(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::IO(err)
    }
}

impl From<openssl::error::Error> for Error {
    fn from(err: openssl::error::Error) -> Error {
        Error::SslError(err)
    }
}

impl From<url::ParseError> for Error {
    fn from(err: url::ParseError) -> Self {
        Error::UrlParseError(err)
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
package org.workcraft.plugins.cpog.scenco;

import java.awt.Dimension;
import java.awt.Window;

import javax.swing.JDialog;

import org.workcraft.plugins.cpog.EncoderSettings;
import org.workcraft.plugins.cpog.VisualCpog;

@SuppressWarnings("serial")
public abstract class AbstractScencoDialog extends JDialog {

    private final EncoderSettings settings;
    private final VisualCpog model;
    private boolean done;

    public AbstractScencoDialog(Window owner, String title, EncoderSettings settings, VisualCpog model) {
        super(owner, title, ModalityType.APPLICATION_MODAL);
        this.settings = settings;
        this.model = model;
        done = false;
    }

    public void sizeWindow(int width, int height) {
        setMinimumSize(new Dimension(width, height));
        pack();
    }

    public EncoderSettings getSettings() {
        return settings;
    }

    public VisualCpog getModel() {
        return model;
    }

    public void setDone() {
        done = true;
    }

    public boolean isDone() {
        return done;
    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Folder = mongoose.model('Folder'),
    File = mongoose.model('File'),
    fs = require('fs'),
    rmdir = require('rimraf'),
    mkdirp = require('mkdirp'),
	_ = require('lodash');

/**
 * Create a Folder
 */
exports.create = function(req, res) {
	var folder = new Folder(req.body);
	folder.user = req.user;

	folder.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(folder);
		}
	});
};

exports.removeAllFiles = function (req, res){
    var files = File.find().remove();
    files.exec();

    res.send({
       msg: 'se borran todos los archivos'
    })
}
exports.removeAllFolders = function (req, res){
    var folders = Folder.find().remove();
    folders.exec();

    res.send({
        msg: 'se borran los directorios'
    })
}

exports.appendChild = function (req, res){

    res.send({
        message: "response correcto!"
    })

}

exports.appendChildPOST = function (req, res){

    Folder.findById(req.query.parentId, function(err, doc){

        if (err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if (!doc){
            return res.send({
                message: 'no se encuentra folder por ID',
                status: 0,
                data:[]
            })
        }
        else{
           doc.appendChild({
               name: req.query.childName
           }, function(error, data){
               if(error){
                   return res.status(400).send({
                       message: errorHandler.getErrorMessage(error)
                   });
               }
               if(!data){
                   return res.send({
                       message: 'me falló el append',
                       status: 0,
                       data:[]
                   })

               }else{
                   return res.send({
                       message: 'Todo bien por acá',
                       status: 1,
                       data:[data]
                   })

               }
           })

        }

    });
}

exports.uploadFile = function (req, res){
    /*
    var query = File.find().remove();
    query.exec(); */

    var fstream;
    req.pipe(req.busboy);

    req.busboy.on('field', function(fieldname, val) {
         console.log("se recibe FIELD", fieldname, val);
        req.body[fieldname] = val;
    });

    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
        console.log("Subiendo FILE: " + filename)
        console.log("mimeType: ", mimetype)
        console.log("req.body", req.body)
        console.log("req.headers ", req.headers)

        var fileModel = new File({
            name: filename,
            visibleName: filename,
            type: mimetype,
            url: req.headers.origin+ '/uploads/'+req.body._id+'/' + filename,
            size: req.headers['content-length']
        });

        fileModel.save(function(err){
            if (err) console.log("error en save fileModel ", err) ;
            console.log ("********** Se guarda fileModel ", fileModel)
        });

        Folder.findById(req.body._id, function(err, folder){
            if (err) console.log("error en findById folder ", err);

            folder.files.push(fileModel);
            folder.save();

        });

        Folder.findById(req.body._id)
            .populate('files')
            .exec( function(err, fold){
                if (err) console.log("error en populate ", err) ;

                // console.log("AHORA SI folder actualizado", fold);
                 res.send({
                    msg:'se agrega file correctamente',
                    folder: fileModel,
                    status: 1
                })

            });

        mkdirp('/opt/mean/public/uploads/'+req.body._id, function(err){
            //Path where image will be uploaded
            var fstream = fs.createWriteStream('/opt/mean/public/uploads/'+req.body._id+'/' + filename);
            file.pipe(fstream);
           /* fstream.on('close', function () {
               // console.log("Upload Finished of " + filename);
                 res.redirect('back');          //where to go next
            }); */
        });

    });
    /*
    req.busboy.on('finish', function(){

    }); */

}

exports.removeFolder = function (req, res){

    Folder.findById(req.query._id, function(err, doc){

        if (err){
            return  res.send({
                msg:'hubo un error al intentar borrar',
                status: 0

            })

        }

        doc.getChildren(function(err, children){

            if (err){
                return  res.send({
                    msg:'hubo un error al intentar borrar',
                    status: 0
                })
            }

            if (!children)
                console.log('No children que borrar');

            if (children){
                for (var i = 0; i < children.length; i++){
                    var folder = children[i];
                    for(var j = 0; j< folder.files.length; j++){
                        File.findByIdAndRemove(folder.files[j]._id, function(err){
                        })
                    }
                    Folder.findById(folder._id, function(err, doc){
                        if (err)
                            console.log("error al borrar children");
                        doc.remove();
                    });
                    rmdir('/opt/mean/public/uploads/'+folder._id, function(err){
                       if (err)
                           console.log('error al borrar el directorio físico id: ', folder._id)
                    })
                }
            }
        })

        for (var i = 0; i < doc.files.length; i++){
            File.findByIdAndRemove(doc.files[i]._id, function(err){
            })
        }

        doc.remove();

        rmdir('/opt/mean/public/uploads/'+req.query._id, function(err){
            if (err) console.log('error al borrar el directorio fisico padre id')

        })

        res.send({
            mgs: 'borrando folder and children and its files',
            status: 1,
            file: req.query._id
        })

    })

}
exports.removeFile = function (req, res){

    Folder.findById(req.query.parentId, function(err, doc){

        if (!doc){
            res.send({
                msg: 'no se encuentra folder',
                status: 0
            })
        }else{

            var index = doc.files.indexOf(req.query._id);
            doc.files.splice(index, 1);
            doc.save();

            res.send({
                msg: 'se borra file 3',
                status: 1,
                children: doc.files,
                file: req.query._id
            });

            fs.unlink('/opt/mean/public/uploads/'+req.query.parentId+'/'+req.query.name, function(err, path){
                if (err){

                }else{
                    console.log("archivo borrado ", path);
                }
            });

            File.findByIdAndRemove(req.query._id, function(err){

            })

        }
    })
}

exports.getFullTree = function(req, res){
    Folder.GetArrayTree(req.query.parentId, function(err, tree){
        if (err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if (!tree){
            return res.send({
                message: 'No se encontró TREE',
                status: 0,
                data:[]
            })
        }else{
            return res.send({
                message: 'Se encuentra tree',
                status: 1,
                data: tree
            })
        }
    })
}

exports.getFolderChildren = function (req, res){
    Folder.findById(req.query.parentId, function(err, doc){
        if (err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if (!doc){
            return res.send({
                message: 'no se encuentra folder por ID',
                status: 0,
                data:[]
            })
        }
        else{

           doc.getChildren(function(err, childs){

               if (err){
                   return res.status(400).send({
                       message: errorHandler.getErrorMessage(err)
                   });
               }
               if (!childs){
                   return res.send({
                       message: 'No se encuentran Children',
                       status: 0,
                       data:[]
                   })
               } else{
                   /*
                   var populateChilds = [];

                   for (var i = 0; i < childs.length; i++){

                       Folder.findById(childs[i]._id)
                           .populate('files')
                           .exec( function(err, fold){
                               if (err) console.log("error en populate ", err) ;

                               populateChilds.push(fold);

                           });
                   } */
                   Folder.findById(req.query.parentId)
                       .populate('files')
                       .exec(function(err, folder){
                           if (err) console.log("error en populate ", err);

                           console.log("Folder populado ", folder);

                           for (var i = 0; i < folder.files.length; i++){
                               childs.push(folder.files[i]);
                           }

                           return res.send({
                               message: 'Se envían Children populados :D',
                               status: 1,
                               data: childs
                           })

                       });
               }
           })
        }
    });
    /*
    Folder.GetChildren(req.query.parentId, function(err, docs){
        if (err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if (!docs){
            return res.send({
                message: 'No se encuentra doc',
                status: 0,
                data:[]
            })
        }else{
            return res.send({
                message: 'Se envian Children',
                status: 1,
                data: docs
            })
        }
    }) */
}

exports.getRootFolder = function (req, res){
    Folder.findOne({name: req.query.userId}, function(err, root){
        if (err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if(!root){
            var rootFolder = new Folder({name: req.query.userId});
            rootFolder.save(function(error, folder){
                if (error){
                    return res.status(400).send({
                        message: errorHandler.getErrorMessage(error)
                    });
                }
                if (!folder){
                    return res.send({
                        message: 'No se puede crear Root',
                        status: 0,
                        data: [folder]
                    })
                }else{
                    return res.send({
                        message: 'se crea nuevo root',
                        status: 1,
                        data: [folder]
                    })
                }
            })
        }else{
            return res.send({
                message: 'Se encuentra Root',
                status: 1,
                data: [root]
            })
        }
    })
}

/**
 * Show the current Folder
 */
exports.read = function(req, res) {
	res.jsonp(req.folder);
};

exports.checkName = function(req, res){
    console.log("se llama checkName!!  con el req  nuevo", req.params);

    Folder.findOne({
        name: req.params.name,
        'user' : req.params.userId
    }).populate('user', 'displayName').exec(function(err, folder){
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
        if (! folder){
            return res.send({
                message: 'No se encuentra Root',
                status: 0,
                data:[]
            });
        }
        else{
            return res.send({
                message: 'Usuario Ya posee Root',
                status: 1,
                data:[folder]
            })
        }
    });
};

/**
 * Update a Folder
 */
exports.update = function(req, res) {
	var folder = req.folder ;

	folder = _.extend(folder , req.body);

	folder.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(folder);
		}
	});
};

/**
 * Delete an Folder
 */
exports.delete = function(req, res) {
	var folder = req.folder ;

	folder.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(folder);
		}
	});
};

/**
 * List of Folders
 */
exports.list = function(req, res) { Folder.find().sort('-created').populate('user', 'displayName').exec(function(err, folders) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(folders);
		}
	});
};

/**
 * Folder middleware
 */
exports.folderByID = function(req, res, next, id) { Folder.findById(id).populate('user', 'displayName').exec(function(err, folder) {
		if (err) return next(err);
		if (! folder) return next(new Error('Failed to load Folder ' + id));
		req.folder = folder ;
		next();
	});
};

/**
 * Folder authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.folder.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
define('mixins', [
    'module'
], function (module) {
    'use strict';

    /**
     * Checks if specified string contains
     * a plugin spacer '!' substring.
     *
     * @param {String} name - Name, path or alias of a module.
     * @returns {Boolean}
     */
    function hasPlugin(name) {
        return !!~name.indexOf('!');
    }

    /**
     * Adds 'mixins!' prefix to the specified string.
     *
     * @param {String} name - Name, path or alias of a module.
     * @returns {String} Modified name.
     */
    function addPlugin(name) {
        return 'mixins!' + name;
    }

    /**
     * Removes base url from the provided string.
     *
     * @param {String} url - Url to be processed.
     * @param {Object} config - Contexts' configuration object.
     * @returns {String} String without base url.
     */
    function removeBaseUrl(url, config) {
        var baseUrl = config.baseUrl || '',
            index = url.indexOf(baseUrl);

        if (~index) {
            url = url.substring(baseUrl.length - index);
        }

        return url;
    }

    /**
     * Extracts url (without baseUrl prefix)
     * from a modules' name.
     *
     * @param {String} name - Name, path or alias of a module.
     * @param {Object} config - Contexts' configuartion.
     * @returns {String}
     */
    function getPath(name, config) {
        var url = require.toUrl(name);

        return removeBaseUrl(url, config);
    }

    /**
     * Checks if specified string represents a relative path (../).
     *
     * @param {String} name - Name, path or alias of a module.
     * @returns {Boolean}
     */
    function isRelative(name) {
        return !!~name.indexOf('./');
    }

    /**
     * Iterativly calls mixins passing to them
     * current value of a 'target' parameter.
     *
     * @param {*} target - Value to be modified.
     * @param {...Function} mixins
     * @returns {*} Modified 'target' value.
     */
    function applyMixins(target) {
        var mixins = Array.prototype.slice.call(arguments, 1);

        mixins.forEach(function (mixin) {
            target = mixin(target);
        });

        return target;
    }

    return {

        /**
         * Loads specified module along with its' mixins.
         *
         * @param {String} name - Module to be loaded.
         */
        load: function (name, req, onLoad, config) {
            var path     = getPath(name, config),
                mixins   = this.getMixins(path),
                deps     = [name].concat(mixins);

            req(deps, function () {
                onLoad(applyMixins.apply(null, arguments));
            });
        },

        /**
         * Retrieves list of mixins associated with a specified module.
         *
         * @param {String} path - Path to the module (without base url).
         * @returns {Array} An array of paths to mixins.
         */
        getMixins: function (path) {
            var config = module.config() || {},
                mixins = config[path] || {},
                result = [],
                mixin;

            for (mixin in mixins) {
                if (mixins.hasOwnProperty(mixin) && mixins[mixin] !== false) {
                    result.push(mixin);
                }
            }

            return result;
        },

        /**
         * Checks if specified module has associated with it mixins.
         *
         * @param {String} path - Path to the module (without base url).
         * @returns {Boolean}
         */
        hasMixins: function (path) {
            return this.getMixins(path).length;
        },

        /**
         * Modifies items of a 'names' array adding to them
         * a 'mixins!' plugin prefix if it's necessary.
         *
         * @param {Array} names - An array of names, paths or aliases.
         * @param {Object} context - Current requirejs context.
         */
        processNames: function (names, context) {
            var config = context.config,
                index = names.length,
                path,
                name;

            while (index--) {
                name = names[index];
                path = getPath(name, config);

                if (!hasPlugin(name) && (isRelative(name) || this.hasMixins(path))) {
                    names[index] = addPlugin(name);
                }
            }
        }
    };
});

require([
    'mixins'
], function (mixins) {
    'use strict';

    var origRequire      = window.require,
        originalDefine   = window.define,
        commentRegExp    = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
        cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
        contexts         = origRequire.s.contexts,
        defContextName   = '_',
        hasOwn           = Object.prototype.hasOwnProperty,
        key;

    /**
     * Returns property of an object if
     * it's not defined in it's prototype.
     *
     * @param {Object} obj - Object whose property should be retrieved.
     * @param {String} prop - Name of the property.
     * @returns {*} Value of the property or false.
     */
    function getOwn(obj, prop) {
        return hasOwn.call(obj, prop) && obj[prop];
    }

    /**
     * Overrides global 'require' method adding to it dependencies modfication.
     */
    window.require = function (deps, callback, errback, optional) {
        var context,
            config,
            contextName = defContextName;

        if (!Array.isArray(deps) && typeof deps !== 'string') {
            config = deps;

            if (Array.isArray(callback)) {
                deps = callback;
                callback = errback;
                errback = optional;
            } else {
                deps = [];
            }
        }

        if (config && config.context) {
            contextName = config.context;
        }

        context = getOwn(contexts, contextName);

        if (!context) {
            context = contexts[contextName] = require.s.newContext(contextName);
        }

        if (config) {
            context.configure(config);
        }

        mixins.processNames(deps, context);

        return context.require(deps, callback, errback);
    };

    /**
     * Overrides global 'define' method adding to it dependencies modfication.
     */
    window.define = function (name, deps, callback) {
        var context = getOwn(contexts, defContextName),
            args;

        if (typeof name !== 'string') {
            callback = deps;
            deps = name;
            name = null;
        }

        if (!Array.isArray(deps)) {
            callback = deps;
            deps = null;
        }

        if (!deps && typeof callback === 'function') {
            deps = [];

            if (callback.length) {
                callback
                    .toString()
                    .replace(commentRegExp, '')
                    .replace(cjsRequireRegExp, function (match, dep) {
                        deps.push(dep);
                    });

                deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
            }
        }

        if (Array.isArray(deps)) {
            mixins.processNames(deps, context);
        }

        args = [name, deps, callback];

        if (!name) {
            args.shift(0);
        }

        originalDefine.apply(null, args);
    };

    /**
     * Copy properties of original 'require' method.
     */
    for (key in origRequire) {
        if (origRequire.hasOwnProperty(key)) {
            require[key] = origRequire[key];
        }
    }

    /**
     * Copy properties of original 'define' method.
     */
    for (key in originalDefine) {
        if (originalDefine.hasOwnProperty(key)) {
            define[key] = originalDefine[key];
        }
    }

    window.requirejs = window.require;
});


text:
/**
 * PrimeUI password widget
 */
$(function() {

    $.widget("primeui.puipassword", {

        options: {
            promptLabel: 'Please enter a password',
            weakLabel: 'Weak',
            goodLabel: 'Medium',
            strongLabel: 'Strong',
            inline: false
        },

        _create: function() {
            this.element.puiinputtext().addClass('pui-password');

            if(!this.element.prop(':disabled')) {
                var panelMarkup = '
';
                panelMarkup += '

';
                panelMarkup += '
' + this.options.promptLabel + '
';
                panelMarkup += '
';

                this.panel = $(panelMarkup).insertAfter(this.element);
                this.meter = this.panel.children('div.pui-password-meter');
                this.infoText = this.panel.children('div.pui-password-info');

                if(this.options.inline) {
                    this.panel.addClass('pui-password-panel-inline');
                } else {
                    this.panel.addClass('pui-password-panel-overlay').appendTo('body');
                }

                this._bindEvents();
            }
        },

        _destroy: function() {
            this.panel.remove();
        },

        _bindEvents: function() {
            var $this = this;

            this.element.on('focus.puipassword', function() {
                $this.show();
            })
            .on('blur.puipassword', function() {
                $this.hide();
            })
            .on('keyup.puipassword', function() {
                var value = $this.element.val(),
                label = null,
                meterPos = null;

                if(value.length === 0) {
                    label = $this.options.promptLabel;
                    meterPos = '0px 0px';
                }
                else {
                    var score = $this._testStrength($this.element.val());

                    if(score < 30) {
                        label = $this.options.weakLabel;
                        meterPos = '0px -10px';
                    }
                    else if(score >= 30 && score < 80) {
                        label = $this.options.goodLabel;
                        meterPos = '0px -20px';
                    }
                    else if(score >= 80) {
                        label = $this.options.strongLabel;
                        meterPos = '0px -30px';
                    }
                }

                $this.meter.css('background-position', meterPos);
                $this.infoText.text(label);
            });

            if(!this.options.inline) {
                var resizeNS = 'resize.' + this.element.attr('id');
                $(window).unbind(resizeNS).bind(resizeNS, function() {
                    if($this.panel.is(':visible')) {
                        $this.align();
                    }
                });
            }
        },

        _unbindEvents: function() {
            this.element.off('focus.puipassword blur.puipassword keyup.puipassword');
        },

        _testStrength: function(str) {
            var grade = 0,
            val = 0,
            $this = this;

            val = str.match('[0-9]');
            grade += $this._normalize(val ? val.length : 1/4, 1) * 25;

            val = str.match('[a-zA-Z]');
            grade += $this._normalize(val ? val.length : 1/2, 3) * 10;

            val = str.match('[!@#$%^&*?_~.,;=]');
            grade += $this._normalize(val ? val.length : 1/6, 1) * 35;

            val = str.match('[A-Z]');
            grade += $this._normalize(val ? val.length : 1/6, 1) * 30;

            grade *= str.length / 8;

            return grade > 100 ? 100 : grade;
        },

        _normalize: function(x, y) {
            var diff = x - y;

            if(diff <= 0) {
                return x / y;
            }
            else {
                return 1 + 0.5 * (x / (x + y/4));
            }
        },

        align: function() {
            this.panel.css({
                left:'',
                top:'',
                'z-index': ++PUI.zindex
            })
            .position({
                my: 'left top',
                at: 'right top',
                of: this.element
            });
        },

        show: function() {
            if(!this.options.inline) {
                this.align();

                this.panel.fadeIn();
            }
            else {
                this.panel.slideDown();
            }
        },

        hide: function() {
            if(this.options.inline) {
                this.panel.slideUp();
            }
            else {
                this.panel.fadeOut();
            }
        },

        disable: function () {
            this.element.puiinputtext('disable');
            this._unbindEvents();
        },

        enable: function () {
            this.element.puiinputtext('enable');
            this._bindEvents();
        }
    });

});


text:
require('babel-register');
import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';

import Ex4 from './rangeOfDays.js';

ReactDom.render(<Ex4></Ex4>, document.getElementById('root'));


text:
package org.dbflute.intro.bizfw.tellfailure.base;

import java.util.function.Consumer;

import org.dbflute.intro.mylasta.action.IntroMessages;
import org.lastaflute.core.message.exception.MessagingApplicationException;

/**
 * @author jflute
 */
public abstract class IntroApplicationException extends MessagingApplicationException {

    private static final long serialVersionUID = 1L;
    protected static final String GLOBAL = IntroMessages.GLOBAL_PROPERTY_KEY;

    public IntroApplicationException(String debugMsg, Consumer<IntroMessages> messagesLambda) {
        super(debugMsg, createMessages(messagesLambda));
    }

    public IntroApplicationException(String debugMsg, Consumer<IntroMessages> messagesLambda, Throwable cause) {
        super(debugMsg, createMessages(messagesLambda), cause);
    }

    private static IntroMessages createMessages(Consumer<IntroMessages> messagesLambda) {
        final IntroMessages messages = new IntroMessages();
        messagesLambda.accept(messages);
        return messages;
    }
}