text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme.launcher">

        <!-- 启动背景 -->
        <item name="android:windowBackground">@drawable/window_theme</item>
    </style>

    <style name="AppTheme.blank">

        <!-- 空白背景 -->
        <item name="android:windowBackground">@drawable/blank_theme</item>
        <!-- 关闭系统标题 -->
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>


text:
Deface::Override.new(
  virtual_path: 'spree/shared/_products',
  name: 'select_product_type_to_render',
  replace_contents: 'div#products',
  partial: 'spree/products/product_type_selector',
  disabled: false
)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace IPS\calendar\extensions\core\LiveSearch;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * @brief	ACP Live Search Extension
 */
class _Calendars
{
	/**
	 * Check we have access
	 *
	 * @return	void
	 */
	public function hasAccess()
	{
		/* Check Permissions */
		return \IPS\Member::loggedIn()->hasAcpRestriction( 'calendar', 'calendars', 'calendars_manage' );
	}

	/**
	 * Get the search results
	 *
	 * @param	string	Search Term
	 * @return	array 	Array of results
	 */
	public function getResults( $searchTerm )
	{
		/* Init */
		$results = array();
		$searchTerm = mb_strtolower( $searchTerm );

		/* Start with categories */
		if( $this->hasAccess() )
		{
			/* Perform the search */
			$calendars = \IPS\Db::i()->select(
							"*",
							'calendar_calendars',
							array( "word_custom LIKE CONCAT( '%', ?, '%' ) AND lang_id=?", $searchTerm, \IPS\Member::loggedIn()->language()->id ),
							NULL,
							NULL
					)->join(
							'core_sys_lang_words',
							"word_key=CONCAT( 'calendar_calendar_', cal_id )"
						);

			/* Format results */
			foreach ( $calendars as $calendar )
			{
				$calendar = \IPS\calendar\Calendar::constructFromData( $calendar );

				$results[] = \IPS\Theme::i()->getTemplate( 'livesearch', 'calendar', 'admin' )->calendar( $calendar );
			}
		}

		return $results;
	}
}


text:
package cc.acquized.ultimatereport.libs.acquized.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Open Source Java Config API using Annotations
 * @author Acquized
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface BasePath {

    String value();

}


text:
SELECT
*

FROM
view_persediaan_barang4_kehutanan

UNION ALL


text:
{% load admin_static %}{% load i18n grp_tags %}
<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}

    <title>{% block title %}{% endblock %}</title>
    <meta charset="utf-8" />
    {% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %}

    {% block stylesheets %}
        <link href="{% static "grappelli/jquery/ui/jquery-ui.min.css" %}" rel="stylesheet" type="text/css" media="screen" />
        <link href="{% static "grappelli/stylesheets/screen.css" %}" rel="stylesheet" type="text/css" media="all" />
        {% if LANGUAGE_BIDI %}
            <link href="{% static "grappelli/stylesheets/mueller/grid/output-rtl.css" %}" rel="stylesheet" type="text/css" media="screen" />
            <link href="{% block stylesheet_rtl %}{% static "grappelli/stylesheets/rtl.css" %}{% endblock %}" rel="stylesheet" type="text/css" media="screen" />
        {% else %}
            <link href="{% static "grappelli/stylesheets/mueller/grid/output.css" %}" rel="stylesheet" type="text/css" media="screen" />
        {% endif %}
    {% endblock %}

    {% block extrastyle %}{% endblock %}

    {% block javascripts %}

        {% if debug %}

        {% else %}

        {% endif %}

    {% endblock %}

    {% block extrahead %}{% endblock %}

        {% block header %}

                {% if not is_popup %}

                    {% block navigation %}

                            {% block branding %}{% endblock %}
                            {% block admin_title %}
{% if grappelli_admin_title %}{{ grappelli_admin_title }}{% else %}{% get_admin_title %}{% endif %}
{% endblock %}
                            {% block user-tools %}
                                {% if user.is_authenticated and user.is_staff %}

                                        {% block userlinks %}

                                                {% firstof user.get_short_name user.get_username %}

                                                    {% if user.has_usable_password %}

{% trans 'Change password' %}

                                                    {% endif %}

{% trans 'Log out' %}

                                                    {% switch_user_dropdown %}

                                            {% if site_url %}

{% trans 'View site' %}

                                            {% endif %}

                                            {% url 'django-admindocs-docroot' as docsroot %}
                                            {% if docsroot %}

{% trans 'Documentation' %}

                                            {% endif %}
                                        {% endblock %}

                                {% endif %}
                            {% endblock %}

                            {% block nav-global %}{% endblock %}

                    {% endblock %}

                    {% block context-navigation %}

Breadcrumbs

                                {% block breadcrumbs %}

{% trans 'Home' %}

                                        {% if title %}

 › {{ title }}

                                        {% endif %}

                                {% endblock %}

Page Tools

                                {% block page-tools %}{% endblock %}

                    {% endblock %}

                {% endif %}

        {% endblock %}

            {% block messages %}
                {% if messages %}

                        {% for message in messages %}

{{ message }}

                        {% endfor %}

                {% endif %}
            {% endblock %}

                {% block pretitle %}{% endblock %}
                {% block content_title %}{% if title %}
{{ title }}
{% endif %}{% endblock %}
                {% block object-tools %}{% endblock %}

                {% block content %}
                    {{ content }}
                    {% block filters %}{% endblock %}
                {% endblock %}

        {% block footer %}{% endblock %}


text:
require_relative '../../../spec_helper'
require_relative '../fixtures/classes'
require_relative 'shared/basic'
require_relative 'shared/string'
require_relative 'shared/taint'

describe "Array#pack with format 'Z'" do
  it_behaves_like :array_pack_basic, 'Z'
  it_behaves_like :array_pack_basic_non_float, 'Z'
  it_behaves_like :array_pack_no_platform, 'Z'
  it_behaves_like :array_pack_string, 'Z'
  it_behaves_like :array_pack_taint, 'Z'

  it "calls #to_str to convert an Object to a String" do
    obj = mock("pack Z string")
    obj.should_receive(:to_str).and_return("``abcdef")
    [obj].pack("Z*").should == "``abcdef\x00"
  end

  it "will not implicitly convert a number to a string" do
    -> { [0].pack('Z') }.should raise_error(TypeError)
  end

  it "adds all the bytes and appends a NULL byte when passed the '*' modifier" do
    ["abc"].pack("Z*").should == "abc\x00"
  end

  it "padds the output with NULL bytes when the count exceeds the size of the String" do
    ["abc"].pack("Z6").should == "abc\x00\x00\x00"
  end

  it "adds a NULL byte when the value is nil" do
    [nil].pack("Z").should == "\x00"
  end

  it "pads the output with NULL bytes when the value is nil" do
    [nil].pack("Z3").should == "\x00\x00\x00"
  end

  it "does not append a NULL byte when passed the '*' modifier and the value is nil" do
    [nil].pack("Z*").should == "\x00"
  end
end


text:
Repositorio para demostracion

En esta demostración haré lo siguiente:
* Crear el repositorio
  - Subitem 1
  - Subitem 2
* Editar el `readme.txt`
* Guardarlo

## Este es un subtitulo

## Este es un subtitulo

# Esta es una modificación desde el brach

Haga clic [aquí](www.google.com) para ir a google

* Esta es una nueva rama creada desde el Master


text:
<?php

namespace Hermes;

use Collective\Remote\RemoteServiceProvider;
use Illuminate\Support\ServiceProvider;

class HermesServiceProvider extends ServiceProvider
{

	public function boot ()
	{
		if ( $this->app->runningInConsole () )
		{
			$this->registerCommands ();
		}
	}

	public function register ()
	{
		$this->registerRemoteProvider ();

		$this->registerRoutineManager ();

		$this->registerRoutineDriver ();
	}

	protected function registerRemoteProvider ()
	{
		$this->app->register ( RemoteServiceProvider::class );
	}

	protected function registerRoutineManager ()
	{
		$this->app->singleton ( 'hermes', function ( $app )
		{
			return new Drivers\RoutineManager( $app );
		} );
	}

	protected function registerRoutineDriver ()
	{
		$this->app->singleton ( 'hermes.routine', function ( $app )
		{
			return $app[ 'hermes' ]->driver ();
		} );
	}

	protected function registerCommands ()
	{
		$this->commands ( [
							  Commands\Deploy::class,
							  Commands\Setup::class,
							  Commands\Task::class
						  ] );
	}

	public function provides ()
	{
		return [ 'hermes', 'hermes.routine' ];
	}

}


text:
package io.qntfy.nifi.processors;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ProcessorLog;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.FlowFileFilters;
import org.apache.nifi.processor.util.StandardValidators;

import io.qntfy.nifi.util.AttributeFlowFileEnricherImpl;
import io.qntfy.nifi.util.FlowFileEnricher;
import io.qntfy.nifi.util.JSONFlowFileEnricherImpl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

@SupportsBatching
@Tags({ "Redis", "Get", "Consume", "Message", "PubSub" })
@CapabilityDescription("Poll a Kafka set for values reaching a given threshold. Create a flowfile for the content and attributes stored.")
public class GetRedisEnrichment extends AbstractProcessor {
	private volatile JedisPool jedisPool;

	public static final PropertyDescriptor REDIS_CONNECTION_STRING = new PropertyDescriptor.Builder()
            .name("Redis Connection String")
            .description("The Connection String to use in order to connect to Redis.")
            .required(true)
            .addValidator(StandardValidators.URI_VALIDATOR)
            .expressionLanguageSupported(false)
            .build();
	public static final PropertyDescriptor CLIENT_NAME = new PropertyDescriptor.Builder()
            .name("Client Name")
            .description("Client Name to use when communicating with Redis")
            .required(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .expressionLanguageSupported(false)
            .build();
	public static final PropertyDescriptor TOPIC = new PropertyDescriptor.Builder()
            .name("Source Topic")
            .description("Enrichments should be gathered only if they were generated from this source")
            .required(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .expressionLanguageSupported(false)
            .build();
	public static final PropertyDescriptor ENRICHMENTS = new PropertyDescriptor.Builder()
            .name("Number of Required Enrichments")
            .description("Number of enrichment elements required to continue processing")
            .required(true)
            .addValidator(StandardValidators.INTEGER_VALIDATOR)
            .expressionLanguageSupported(false)
            .build();
	public static final AllowableValue VALUE_TRUE = new AllowableValue("True");
    public static final AllowableValue VALUE_FALSE = new AllowableValue("False");
	public static final PropertyDescriptor JSON_CONTENT_MODE = new PropertyDescriptor.Builder()
	        .name("JSON Content Mode")
	        .description("If original message and enrichment data are JSON, this can be enabled to merge based on content")
	        .allowableValues(VALUE_TRUE, VALUE_FALSE)
	        .required(true)
	        .expressionLanguageSupported(false)
	        .build();
	public static final PropertyDescriptor JSON_ENRICHMENT_FIELD = new PropertyDescriptor.Builder()
	        .name("JSON Enrichment Field")
	        .description("If JSON Content Mode is enabled, add enrichment data to this JSON map")
	        .required(true)
	        .expressionLanguageSupported(false)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();
	public static final Relationship REL_SUCCESS = new Relationship.Builder()
            .name("success")
            .description("All FlowFiles that are successfully enriched are routed to this relationship")
            .build();
    public static final Relationship REL_RETRY = new Relationship.Builder()
            .name("retry")
            .description("Any FlowFiles that cannot be enriched, but may be able to in the future, are routed to this relationship")
            .build();
    public static final Relationship REL_FAILURE = new Relationship.Builder()
            .name("failure")
            .description("Any FlowFiles that cannot be enriched are routed to this relationship")
            .build();

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        final PropertyDescriptor clientNameWithDefault = new PropertyDescriptor.Builder()
            .fromPropertyDescriptor(CLIENT_NAME)
            .defaultValue("NiFi-" + getIdentifier())
            .build();

        final List<PropertyDescriptor> props = new ArrayList<>();
        props.add(REDIS_CONNECTION_STRING);
        props.add(ENRICHMENTS);
        props.add(TOPIC);
        props.add(JSON_CONTENT_MODE);
        props.add(JSON_ENRICHMENT_FIELD);
        props.add(clientNameWithDefault);
        return props;
    }

    @Override
    public Set<Relationship> getRelationships() {
        final Set<Relationship> relationships = new HashSet<>(2);
        relationships.add(REL_SUCCESS);
        relationships.add(REL_FAILURE);
        relationships.add(REL_RETRY);
        return relationships;
    }

	@OnScheduled
	public void createRedisPool(final ProcessContext context) {
		try {
            jedisPool = new JedisPool(new JedisPoolConfig(), new URI(context.getProperty(REDIS_CONNECTION_STRING).getValue()));
        } catch (URISyntaxException e) {
            getLogger().error("Unable to establish Redis connection pool.");
            // this should be previously caught by the input validation
        }
	}

	@OnStopped
	public void closeRedisPool(final ProcessContext context) {
		jedisPool.destroy();
	}

	@Override
	public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        String attemptsAttribute = context.getProperty(CLIENT_NAME) + ".attempts";
        String source = context.getProperty(TOPIC).getValue();
        Long requiredEnrichments = context.getProperty(ENRICHMENTS).asLong();

        boolean jsonMode = context.getProperty(JSON_CONTENT_MODE).asBoolean();
        String jsonField = context.getProperty(JSON_ENRICHMENT_FIELD).getValue();

        FlowFileEnricher ffe = null;
        if (jsonMode) {
            ffe = new JSONFlowFileEnricherImpl(jsonField);
        } else {
            ffe = new AttributeFlowFileEnricherImpl();
        }

        final List<FlowFile> flowFiles = session.get(FlowFileFilters.newSizeBasedFilter(1, DataUnit.MB, 100));
        if (flowFiles.isEmpty()) {
            return;
        }

        final ProcessorLog logger = getLogger();
        try (Jedis jedis = jedisPool.getResource()) {
            for (FlowFile flowFile : flowFiles) {
                // try to hit the needed values in redis
                String uuid = flowFile.getAttribute("uuid");
                String flowFileKey = source + ":" + uuid;

                if (requiredEnrichments == 0) {
                    logger.info("Transferred {} to 'success'", new Object[] {flowFile});
                    session.transfer(flowFile, REL_SUCCESS);
                } else if (jedis.hlen(flowFileKey) != requiredEnrichments) {
                    String attemptsStr = flowFile.getAttribute(attemptsAttribute);
                    Integer attempts = (attemptsStr == null) ? 0 : Integer.valueOf(attemptsStr);
                    attempts += 1;

                    flowFile = session.putAttribute(flowFile, attemptsAttribute, String.valueOf(attempts));
                    flowFile = session.penalize(flowFile);
                    logger.info("Transferred {} to 'retry', attempt {}", new Object[] {uuid, attempts});
                    session.getProvenanceReporter().modifyAttributes(flowFile, "FlowFile modified with attempt attribute");
                    session.transfer(flowFile, REL_RETRY);
                } else {
                    Map<String, String> enrichments = jedis.hgetAll(flowFileKey);
                    flowFile = ffe.enrich(session, flowFile, enrichments);
                    logger.info("Transferred {} to 'success'", new Object[] {flowFile});
                    session.transfer(flowFile, REL_SUCCESS);
                    jedis.del(flowFileKey);
                }
            }
        } catch (JedisConnectionException e) {
            logger.error("Failed to connect to Redis due to {}; routing flowfiles to failure", new Object[] { e.getMessage() });
            session.transfer(flowFiles, REL_FAILURE);
        }
	}

}


text:
<?php

namespace Ali\DatatableBundle\Util\Factory\Prototype;

use Symfony\Component\DependencyInjection\ContainerInterface;

class PrototypeBuilder
{

    /** @var \Symfony\Component\DependencyInjection\ContainerInterface */
    protected $container;

    /** @var string */
    protected $_prototype;

    /**
     * class constructor
     *
     * @param ContainerInterface $container
     * @param string             $type
     */
    public function __construct(ContainerInterface $container, $type)
    {
        $this->container = $container;
        $method = "_{$type}";
        $rc = new \ReflectionClass(__CLASS__);
        if ($rc->hasMethod($method))
        {
            $this->_prototype = $this->$method();
        }
        else
        {
            throw new \Exception(sprintf('prototype "%s" not found', $type));
        }
    }

    /**
     * to string class converter
     *
     * @return string
     */
    public function __toString()
    {
        return $this->_prototype;
    }

    /**
     * simple form delete prototype
     *
     * @return string
     */
    protected function _delete_form()
    {
        return $this->container
                        ->get('templating.helper.form')
                        ->widget(
                                $this->container->get('form.factory')->createBuilder('form', array('id' => '@id'), array())
                                ->add('id', 'hidden')
                                ->getForm()
                                ->createView()
        );
    }

}


text:
/**
 * @file
 *
 * @brief   Class definitions to support JSON Schema constraints
 *
 * This file contains class definitions for all of the constraints required to
 * support JSON Schema. These classes all inherit from the BasicConstraint
 * template class, which implements the common parts of the Constraint
 * interface.
 *
 * @see BasicConstraint
 * @see Constraint
 */

#pragma once

#include <limits>
#include <map>
#include <set>
#include <string>
#include <vector>

#include <valijson/constraints/basic_constraint.hpp>
#include <valijson/internal/custom_allocator.hpp>
#include <valijson/internal/frozen_value.hpp>
#include <valijson/schema.hpp>
#include <valijson/exceptions.hpp>

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4702 )
#endif

namespace valijson {

class ValidationResults;

namespace constraints {

/**
 * @brief  Represents an 'allOf' constraint.
 *
 * An allOf constraint provides a collection of sub-schemas that a value must
 * validate against. If a value fails to validate against any of these sub-
 * schemas, then validation fails.
 */
class AllOfConstraint: public BasicConstraint<AllOfConstraint>
{
public:
    AllOfConstraint()
      : m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    AllOfConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    void addSubschema(const Subschema *subschema)
    {
        m_subschemas.push_back(subschema);
    }

    template<typename FunctorType>
    void applyToSubschemas(const FunctorType &fn) const
    {
        unsigned int index = 0;
        for (const Subschema *subschema : m_subschemas) {
            if (!fn(index, subschema)) {
                return;
            }

            index++;
        }
    }

private:
    typedef std::vector<const Subschema *, internal::CustomAllocator<const Subschema *>> Subschemas;

    /// Collection of sub-schemas, all of which must be satisfied
    Subschemas m_subschemas;
};

/**
 * @brief  Represents an 'anyOf' constraint
 *
 * An anyOf constraint provides a collection of sub-schemas that a value can
 * validate against. If a value validates against one of these sub-schemas,
 * then the validation passes.
 */
class AnyOfConstraint: public BasicConstraint<AnyOfConstraint>
{
public:
    AnyOfConstraint()
      : m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    AnyOfConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    void addSubschema(const Subschema *subschema)
    {
        m_subschemas.push_back(subschema);
    }

    template<typename FunctorType>
    void applyToSubschemas(const FunctorType &fn) const
    {
        unsigned int index = 0;
        for (const Subschema *subschema : m_subschemas) {
            if (!fn(index, subschema)) {
                return;
            }

            index++;
        }
    }

private:
    typedef std::vector<const Subschema *, internal::CustomAllocator<const Subschema *>> Subschemas;

    /// Collection of sub-schemas, at least one of which must be satisfied
    Subschemas m_subschemas;
};

/**
 * @brief  Represents a combination 'if', 'then' and 'else' constraints
 *
 * The schema provided by an 'if' constraint is used as the expression for a conditional. When the
 * target validates against that schema, the 'then' subschema will be also be tested. Otherwise,
 * the 'else' subschema will be tested.
 */
class ConditionalConstraint: public BasicConstraint<ConditionalConstraint>
{
public:
    ConditionalConstraint()
      : m_ifSubschema(nullptr),
        m_thenSubschema(nullptr),
        m_elseSubschema(nullptr) { }

    ConditionalConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_ifSubschema(nullptr),
        m_thenSubschema(nullptr),
        m_elseSubschema(nullptr) { }

    const Subschema * getIfSubschema() const
    {
        return m_ifSubschema;
    }

    const Subschema * getThenSubschema() const
    {
        return m_thenSubschema;
    }

    const Subschema * getElseSubschema() const
    {
        return m_elseSubschema;
    }

    void setIfSubschema(const Subschema *subschema)
    {
        m_ifSubschema = subschema;
    }

    void setThenSubschema(const Subschema *subschema)
    {
        m_thenSubschema = subschema;
    }

    void setElseSubschema(const Subschema *subschema)
    {
        m_elseSubschema = subschema;
    }

private:
    const Subschema *m_ifSubschema;
    const Subschema *m_thenSubschema;
    const Subschema *m_elseSubschema;
};

class ConstConstraint: public BasicConstraint<ConstConstraint>
{
public:
    ConstConstraint()
      : m_value(nullptr) { }

    ConstConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_value(nullptr) { }

    ConstConstraint(const ConstConstraint &other)
      : BasicConstraint(other),
        m_value(other.m_value->clone()) { }

    adapters::FrozenValue * getValue() const
    {
        return m_value.get();
    }

    void setValue(const adapters::Adapter &value)
    {
        m_value = std::unique_ptr<adapters::FrozenValue>(value.freeze());
    }

private:
    std::unique_ptr<adapters::FrozenValue> m_value;
};

/**
 * @brief  Represents a 'contains' constraint
 *
 * A 'contains' constraint specifies a schema that must be satisfied by at least one
 * of the values in an array.
 */
class ContainsConstraint: public BasicConstraint<ContainsConstraint>
{
public:
    ContainsConstraint()
      : m_subschema(nullptr) { }

    ContainsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschema(nullptr) { }

    const Subschema * getSubschema() const
    {
        return m_subschema;
    }

    void setSubschema(const Subschema *subschema)
    {
        m_subschema = subschema;
    }

private:
    const Subschema *m_subschema;
};

/**
 * @brief  Represents a 'dependencies' constraint.
 *
 * A dependency constraint ensures that a given property is valid only if the
 * properties that it depends on are present.
 */
class DependenciesConstraint: public BasicConstraint<DependenciesConstraint>
{
public:
    DependenciesConstraint()
      : m_propertyDependencies(std::less<String>(), m_allocator),
        m_schemaDependencies(std::less<String>(), m_allocator)
    { }

    DependenciesConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_propertyDependencies(std::less<String>(), m_allocator),
        m_schemaDependencies(std::less<String>(), m_allocator)
    { }

    template<typename StringType>
    DependenciesConstraint & addPropertyDependency(
            const StringType &propertyName,
            const StringType &dependencyName)
    {
        const String key(propertyName.c_str(), m_allocator);
        auto itr = m_propertyDependencies.find(key);
        if (itr == m_propertyDependencies.end()) {
            itr = m_propertyDependencies.insert(PropertyDependencies::value_type(
                    key, PropertySet(std::less<String>(), m_allocator))).first;
        }

        itr->second.insert(String(dependencyName.c_str(), m_allocator));

        return *this;
    }

    template<typename StringType, typename ContainerType>
    DependenciesConstraint & addPropertyDependencies(
            const StringType &propertyName,
            const ContainerType &dependencyNames)
    {
        const String key(propertyName.c_str(), m_allocator);
        auto itr = m_propertyDependencies.find(key);
        if (itr == m_propertyDependencies.end()) {
            itr = m_propertyDependencies.insert(PropertyDependencies::value_type(
                    key, PropertySet(std::less<String>(), m_allocator))).first;
        }

        typedef typename ContainerType::value_type ValueType;
        for (const ValueType &dependencyName : dependencyNames) {
            itr->second.insert(String(dependencyName.c_str(), m_allocator));
        }

        return *this;
    }

    template<typename StringType>
    DependenciesConstraint & addSchemaDependency(const StringType &propertyName, const Subschema *schemaDependency)
    {
        if (m_schemaDependencies.insert(SchemaDependencies::value_type(
                String(propertyName.c_str(), m_allocator),
                schemaDependency)).second) {
            return *this;
        }

        throwRuntimeError("Dependencies constraint already contains a dependent "
                "schema for the property '" + propertyName + "'");
    }

    template<typename FunctorType>
    void applyToPropertyDependencies(const FunctorType &fn) const
    {
        for (const PropertyDependencies::value_type &v : m_propertyDependencies) {
            if (!fn(v.first, v.second)) {
                return;
            }
        }
    }

    template<typename FunctorType>
    void applyToSchemaDependencies(const FunctorType &fn) const
    {
        for (const SchemaDependencies::value_type &v : m_schemaDependencies) {
            if (!fn(v.first, v.second)) {
                return;
            }
        }
    }

private:
    typedef std::set<String, std::less<String>, internal::CustomAllocator<String>> PropertySet;

    typedef std::map<String, PropertySet, std::less<String>,
            internal::CustomAllocator<std::pair<const String, PropertySet>>> PropertyDependencies;

    typedef std::map<String, const Subschema *, std::less<String>,
            internal::CustomAllocator<std::pair<const String, const Subschema *>>> SchemaDependencies;

    /// Mapping from property names to their property-based dependencies
    PropertyDependencies m_propertyDependencies;

    /// Mapping from property names to their schema-based dependencies
    SchemaDependencies m_schemaDependencies;
};

/**
 * @brief  Represents an 'enum' constraint
 *
 * An enum constraint provides a collection of permissible values for a JSON
 * node. The node will only validate against this constraint if it matches one
 * or more of the values in the collection.
 */
class EnumConstraint: public BasicConstraint<EnumConstraint>
{
public:
    EnumConstraint()
      : m_enumValues(Allocator::rebind<const EnumValue *>::other(m_allocator)) { }

    EnumConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_enumValues(Allocator::rebind<const EnumValue *>::other(m_allocator)) { }

    EnumConstraint(const EnumConstraint &other)
      : BasicConstraint(other),
        m_enumValues(Allocator::rebind<const EnumValue *>::other(m_allocator))
    {
#if VALIJSON_USE_EXCEPTIONS
        try {
#endif
            // Clone individual enum values
            for (const EnumValue *otherValue : other.m_enumValues) {
                const EnumValue *value = otherValue->clone();
#if VALIJSON_USE_EXCEPTIONS
                try {
#endif
                    m_enumValues.push_back(value);
#if VALIJSON_USE_EXCEPTIONS
                } catch (...) {
                    delete value;
                    value = nullptr;
                    throw;
                }
            }
        } catch (...) {
            // Delete values already added to constraint
            for (const EnumValue *value : m_enumValues) {
                delete value;
            }
            throw;
#endif
        }
    }

    ~EnumConstraint() override
    {
        for (const EnumValue *value : m_enumValues) {
            delete value;
        }
    }

    void addValue(const adapters::Adapter &value)
    {
        // TODO: Freeze value using custom alloc/free functions
        m_enumValues.push_back(value.freeze());
    }

    void addValue(const adapters::FrozenValue &value)
    {
        // TODO: Clone using custom alloc/free functions
        m_enumValues.push_back(value.clone());
    }

    template<typename FunctorType>
    void applyToValues(const FunctorType &fn) const
    {
        for (const EnumValue *value : m_enumValues) {
            if (!fn(*value)) {
                return;
            }
        }
    }

private:
    typedef adapters::FrozenValue EnumValue;

    typedef std::vector<const EnumValue *, internal::CustomAllocator<const EnumValue *>> EnumValues;

    EnumValues m_enumValues;
};

/**
 * @brief  Represent a 'format' constraint
 *
 * A format constraint restricts the content of string values, as defined by a set of commonly used formats.
 *
 * As this is an optional feature in JSON Schema, unrecognised formats will be treated as valid for any string value.
 */
class FormatConstraint: public BasicConstraint<FormatConstraint>
{
public:
    FormatConstraint()
        : m_format() { }

    const std::string & getFormat() const
    {
        return m_format;
    }

    void setFormat(const std::string & format)
    {
        m_format = format;
    }

private:
    std::string m_format;
};

/**
 * @brief  Represents non-singular 'items' and 'additionalItems' constraints
 *
 * Unlike the SingularItemsConstraint class, this class represents an 'items'
 * constraint that specifies an array of sub-schemas, which should be used to
 * validate each item in an array, in sequence. It also represents an optional
 * 'additionalItems' sub-schema that should be used when an array contains
 * more values than there are sub-schemas in the 'items' constraint.
 *
 * The prefix 'Linear' comes from the fact that this class contains a list of
 * sub-schemas that corresponding array items must be validated against, and
 * this validation is performed linearly (i.e. in sequence).
 */
class LinearItemsConstraint: public BasicConstraint<LinearItemsConstraint>
{
public:
    LinearItemsConstraint()
      : m_itemSubschemas(Allocator::rebind<const Subschema *>::other(m_allocator)),
        m_additionalItemsSubschema(nullptr) { }

    LinearItemsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_itemSubschemas(Allocator::rebind<const Subschema *>::other(m_allocator)),
        m_additionalItemsSubschema(nullptr) { }

    void addItemSubschema(const Subschema *subschema)
    {
        m_itemSubschemas.push_back(subschema);
    }

    template<typename FunctorType>
    void applyToItemSubschemas(const FunctorType &fn) const
    {
        unsigned int index = 0;
        for (const Subschema *subschema : m_itemSubschemas) {
            if (!fn(index, subschema)) {
                return;
            }

            index++;
        }
    }

    const Subschema * getAdditionalItemsSubschema() const
    {
        return m_additionalItemsSubschema;
    }

    size_t getItemSubschemaCount() const
    {
        return m_itemSubschemas.size();
    }

    void setAdditionalItemsSubschema(const Subschema *subschema)
    {
        m_additionalItemsSubschema = subschema;
    }

private:
    typedef std::vector<const Subschema *, internal::CustomAllocator<const Subschema *>> Subschemas;

    Subschemas m_itemSubschemas;

    const Subschema* m_additionalItemsSubschema;
};

/**
 * @brief   Represents 'maximum' and 'exclusiveMaximum' constraints
 */
class MaximumConstraint: public BasicConstraint<MaximumConstraint>
{
public:
    MaximumConstraint()
      : m_maximum(std::numeric_limits<double>::infinity()),
        m_exclusiveMaximum(false) { }

    MaximumConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_maximum(std::numeric_limits<double>::infinity()),
        m_exclusiveMaximum(false) { }

    bool getExclusiveMaximum() const
    {
        return m_exclusiveMaximum;
    }

    void setExclusiveMaximum(bool newExclusiveMaximum)
    {
        m_exclusiveMaximum = newExclusiveMaximum;
    }

    double getMaximum() const
    {
        return m_maximum;
    }

    void setMaximum(double newMaximum)
    {
        m_maximum = newMaximum;
    }

private:
    double m_maximum;
    bool m_exclusiveMaximum;
};

/**
 * @brief   Represents a 'maxItems' constraint
 */
class MaxItemsConstraint: public BasicConstraint<MaxItemsConstraint>
{
public:
    MaxItemsConstraint()
      : m_maxItems(std::numeric_limits<uint64_t>::max()) { }

    MaxItemsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_maxItems(std::numeric_limits<uint64_t>::max()) { }

    uint64_t getMaxItems() const
    {
        return m_maxItems;
    }

    void setMaxItems(uint64_t newMaxItems)
    {
        m_maxItems = newMaxItems;
    }

private:
    uint64_t m_maxItems;
};

/**
 * @brief   Represents a 'maxLength' constraint
 */
class MaxLengthConstraint: public BasicConstraint<MaxLengthConstraint>
{
public:
    MaxLengthConstraint()
      : m_maxLength(std::numeric_limits<uint64_t>::max()) { }

    MaxLengthConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_maxLength(std::numeric_limits<uint64_t>::max()) { }

    uint64_t getMaxLength() const
    {
        return m_maxLength;
    }

    void setMaxLength(uint64_t newMaxLength)
    {
        m_maxLength = newMaxLength;
    }

private:
    uint64_t m_maxLength;
};

/**
 * @brief   Represents a 'maxProperties' constraint
 */
class MaxPropertiesConstraint: public BasicConstraint<MaxPropertiesConstraint>
{
public:
    MaxPropertiesConstraint()
      : m_maxProperties(std::numeric_limits<uint64_t>::max()) { }

    MaxPropertiesConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_maxProperties(std::numeric_limits<uint64_t>::max()) { }

    uint64_t getMaxProperties() const
    {
        return m_maxProperties;
    }

    void setMaxProperties(uint64_t newMaxProperties)
    {
        m_maxProperties = newMaxProperties;
    }

private:
    uint64_t m_maxProperties;
};

/**
 * @brief   Represents 'minimum' and 'exclusiveMinimum' constraints
 */
class MinimumConstraint: public BasicConstraint<MinimumConstraint>
{
public:
    MinimumConstraint()
      : m_minimum(-std::numeric_limits<double>::infinity()),
        m_exclusiveMinimum(false) { }

    MinimumConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_minimum(-std::numeric_limits<double>::infinity()),
        m_exclusiveMinimum(false) { }

    bool getExclusiveMinimum() const
    {
        return m_exclusiveMinimum;
    }

    void setExclusiveMinimum(bool newExclusiveMinimum)
    {
        m_exclusiveMinimum = newExclusiveMinimum;
    }

    double getMinimum() const
    {
        return m_minimum;
    }

    void setMinimum(double newMinimum)
    {
        m_minimum = newMinimum;
    }

private:
    double m_minimum;
    bool m_exclusiveMinimum;
};

/**
 * @brief   Represents a 'minItems' constraint
 */
class MinItemsConstraint: public BasicConstraint<MinItemsConstraint>
{
public:
    MinItemsConstraint()
      : m_minItems(0) { }

    MinItemsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_minItems(0) { }

    uint64_t getMinItems() const
    {
        return m_minItems;
    }

    void setMinItems(uint64_t newMinItems)
    {
        m_minItems = newMinItems;
    }

private:
    uint64_t m_minItems;
};

/**
 * @brief   Represents a 'minLength' constraint
 */
class MinLengthConstraint: public BasicConstraint<MinLengthConstraint>
{
public:
    MinLengthConstraint()
      : m_minLength(0) { }

    MinLengthConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_minLength(0) { }

    uint64_t getMinLength() const
    {
        return m_minLength;
    }

    void setMinLength(uint64_t newMinLength)
    {
        m_minLength = newMinLength;
    }

private:
    uint64_t m_minLength;
};

/**
 * @brief   Represents a 'minProperties' constraint
 */
class MinPropertiesConstraint: public BasicConstraint<MinPropertiesConstraint>
{
public:
    MinPropertiesConstraint()
      : m_minProperties(0) { }

    MinPropertiesConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_minProperties(0) { }

    uint64_t getMinProperties() const
    {
        return m_minProperties;
    }

    void setMinProperties(uint64_t newMinProperties)
    {
        m_minProperties = newMinProperties;
    }

private:
    uint64_t m_minProperties;
};

/**
 * @brief  Represents either 'multipleOf' or 'divisibleBy' constraints where
 *         the divisor is a floating point number
 */
class MultipleOfDoubleConstraint:
        public BasicConstraint<MultipleOfDoubleConstraint>
{
public:
    MultipleOfDoubleConstraint()
      : m_value(1.) { }

    MultipleOfDoubleConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_value(1.) { }

    double getDivisor() const
    {
        return m_value;
    }

    void setDivisor(double newValue)
    {
        m_value = newValue;
    }

private:
    double m_value;
};

/**
 * @brief  Represents either 'multipleOf' or 'divisibleBy' constraints where
 *         the divisor is of integer type
 */
class MultipleOfIntConstraint:
        public BasicConstraint<MultipleOfIntConstraint>
{
public:
    MultipleOfIntConstraint()
      : m_value(1) { }

    MultipleOfIntConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_value(1) { }

    int64_t getDivisor() const
    {
        return m_value;
    }

    void setDivisor(int64_t newValue)
    {
        m_value = newValue;
    }

private:
    int64_t m_value;
};

/**
 * @brief   Represents a 'not' constraint
 */
class NotConstraint: public BasicConstraint<NotConstraint>
{
public:
    NotConstraint()
      : m_subschema(nullptr) { }

    NotConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschema(nullptr) { }

    const Subschema * getSubschema() const
    {
        return m_subschema;
    }

    void setSubschema(const Subschema *subschema)
    {
        m_subschema = subschema;
    }

private:
    const Subschema *m_subschema;
};

/**
 * @brief   Represents a 'oneOf' constraint.
 */
class OneOfConstraint: public BasicConstraint<OneOfConstraint>
{
public:
    OneOfConstraint()
      : m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    OneOfConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschemas(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    void addSubschema(const Subschema *subschema)
    {
        m_subschemas.push_back(subschema);
    }

    template<typename FunctorType>
    void applyToSubschemas(const FunctorType &fn) const
    {
        unsigned int index = 0;
        for (const Subschema *subschema : m_subschemas) {
            if (!fn(index, subschema)) {
                return;
            }

            index++;
        }
    }

private:
    typedef std::vector<const Subschema *, internal::CustomAllocator<const Subschema *>> Subschemas;

    /// Collection of sub-schemas, exactly one of which must be satisfied
    Subschemas m_subschemas;
};

/**
 * @brief   Represents a 'pattern' constraint
 */
class PatternConstraint: public BasicConstraint<PatternConstraint>
{
public:
    PatternConstraint()
      : m_pattern(Allocator::rebind<char>::other(m_allocator)) { }

    PatternConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_pattern(Allocator::rebind<char>::other(m_allocator)) { }

    template<typename AllocatorType>
    bool getPattern(std::basic_string<char, std::char_traits<char>, AllocatorType> &result) const
    {
        result.assign(m_pattern.c_str());
        return true;
    }

    template<typename AllocatorType>
    std::basic_string<char, std::char_traits<char>, AllocatorType> getPattern(
            const AllocatorType &alloc = AllocatorType()) const
    {
        return std::basic_string<char, std::char_traits<char>, AllocatorType>(m_pattern.c_str(), alloc);
    }

    template<typename AllocatorType>
    void setPattern(const std::basic_string<char, std::char_traits<char>, AllocatorType> &pattern)
    {
        m_pattern.assign(pattern.c_str());
    }

private:
    String m_pattern;
};

class PolyConstraint : public Constraint
{
public:
    bool accept(ConstraintVisitor &visitor) const override
    {
        return visitor.visit(*static_cast<const PolyConstraint*>(this));
    }

    OwningPointer clone(CustomAlloc allocFn, CustomFree freeFn) const override
    {
        // smart pointer to automatically free raw memory on exception
        typedef std::unique_ptr<Constraint, CustomFree> RawOwningPointer;
        auto ptr = RawOwningPointer(static_cast<Constraint*>(allocFn(sizeOf())), freeFn);
        if (!ptr) {
            throwRuntimeError("Failed to allocate memory for cloned constraint");
        }

        // constructor might throw but the memory will be taken care of anyways
        (void)cloneInto(ptr.get());

        // implicitly convert to smart pointer that will also destroy object instance
        return ptr;
    }

    virtual bool validate(const adapters::Adapter &target,
            const std::vector<std::string>& context,
            valijson::ValidationResults *results) const = 0;

private:
    virtual Constraint * cloneInto(void *) const = 0;

    virtual size_t sizeOf() const = 0;
};

/**
 * @brief   Represents a combination of 'properties', 'patternProperties' and
 *          'additionalProperties' constraints
 */
class PropertiesConstraint: public BasicConstraint<PropertiesConstraint>
{
public:
    PropertiesConstraint()
      : m_properties(std::less<String>(), m_allocator),
        m_patternProperties(std::less<String>(), m_allocator),
        m_additionalProperties(nullptr) { }

    PropertiesConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_properties(std::less<String>(), m_allocator),
        m_patternProperties(std::less<String>(), m_allocator),
        m_additionalProperties(nullptr) { }

    bool addPatternPropertySubschema(const char *patternProperty, const Subschema *subschema)
    {
        return m_patternProperties.insert(PropertySchemaMap::value_type(
                String(patternProperty, m_allocator), subschema)).second;
    }

    template<typename AllocatorType>
    bool addPatternPropertySubschema(const std::basic_string<char,
            std::char_traits<char>, AllocatorType> &patternProperty,
            const Subschema *subschema)
    {
        return addPatternPropertySubschema(patternProperty.c_str(), subschema);
    }

    bool addPropertySubschema(const char *propertyName,
            const Subschema *subschema)
    {
        return m_properties.insert(PropertySchemaMap::value_type(
                String(propertyName, m_allocator), subschema)).second;
    }

    template<typename AllocatorType>
    bool addPropertySubschema(const std::basic_string<char,
            std::char_traits<char>, AllocatorType> &propertyName,
            const Subschema *subschema)
    {
        return addPropertySubschema(propertyName.c_str(), subschema);
    }

    template<typename FunctorType>
    void applyToPatternProperties(const FunctorType &fn) const
    {
        typedef typename PropertySchemaMap::value_type ValueType;
        for (const ValueType &value : m_patternProperties) {
            if (!fn(value.first, value.second)) {
                return;
            }
        }
    }

    template<typename FunctorType>
    void applyToProperties(const FunctorType &fn) const
    {
        typedef typename PropertySchemaMap::value_type ValueType;
        for (const ValueType &value : m_properties) {
            if (!fn(value.first, value.second)) {
                return;
            }
        }
    }

    const Subschema * getAdditionalPropertiesSubschema() const
    {
        return m_additionalProperties;
    }

    void setAdditionalPropertiesSubschema(const Subschema *subschema)
    {
        m_additionalProperties = subschema;
    }

private:
    typedef std::map<
            String,
            const Subschema *,
            std::less<String>,
            internal::CustomAllocator<std::pair<const String, const Subschema *>>
        > PropertySchemaMap;

    PropertySchemaMap m_properties;
    PropertySchemaMap m_patternProperties;

    const Subschema *m_additionalProperties;
};

class PropertyNamesConstraint: public BasicConstraint<PropertyNamesConstraint>
{
public:
    PropertyNamesConstraint()
      : m_subschema(nullptr) { }

    PropertyNamesConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_subschema(nullptr) { }

    const Subschema * getSubschema() const
    {
        return m_subschema;
    }

    void setSubschema(const Subschema *subschema)
    {
        m_subschema = subschema;
    }

private:
    const Subschema *m_subschema;
};

/**
 * @brief   Represents a 'required' constraint
 */
class RequiredConstraint: public BasicConstraint<RequiredConstraint>
{
public:
    RequiredConstraint()
      : m_requiredProperties(std::less<String>(), m_allocator) { }

    RequiredConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_requiredProperties(std::less<String>(), m_allocator) { }

    bool addRequiredProperty(const char *propertyName)
    {
        return m_requiredProperties.insert(String(propertyName,
                Allocator::rebind<char>::other(m_allocator))).second;
    }

    template<typename AllocatorType>
    bool addRequiredProperty(const std::basic_string<char, std::char_traits<char>, AllocatorType> &propertyName)
    {
        return addRequiredProperty(propertyName.c_str());
    }

    template<typename FunctorType>
    void applyToRequiredProperties(const FunctorType &fn) const
    {
        for (const String &propertyName : m_requiredProperties) {
            if (!fn(propertyName)) {
                return;
            }
        }
    }

private:
    typedef std::set<String, std::less<String>,
            internal::CustomAllocator<String>> RequiredProperties;

    RequiredProperties m_requiredProperties;
};

/**
 * @brief  Represents an 'items' constraint that specifies one sub-schema
 *
 * A value is considered valid against this constraint if it is an array, and
 * each item in the array validates against the sub-schema specified by this
 * constraint.
 *
 * The prefix 'Singular' comes from the fact that array items must validate
 * against exactly one sub-schema.
 */
class SingularItemsConstraint: public BasicConstraint<SingularItemsConstraint>
{
public:
    SingularItemsConstraint()
      : m_itemsSubschema(nullptr) { }

    SingularItemsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_itemsSubschema(nullptr) { }

    const Subschema * getItemsSubschema() const
    {
        return m_itemsSubschema;
    }

    void setItemsSubschema(const Subschema *subschema)
    {
        m_itemsSubschema = subschema;
    }

private:
    const Subschema *m_itemsSubschema;
};

/**
 * @brief   Represents a 'type' constraint.
 */
class TypeConstraint: public BasicConstraint<TypeConstraint>
{
public:
    enum JsonType {
        kAny,
        kArray,
        kBoolean,
        kInteger,
        kNull,
        kNumber,
        kObject,
        kString
    };

    TypeConstraint()
      : m_namedTypes(std::less<JsonType>(), m_allocator),
        m_schemaTypes(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    TypeConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn),
        m_namedTypes(std::less<JsonType>(), m_allocator),
        m_schemaTypes(Allocator::rebind<const Subschema *>::other(m_allocator)) { }

    void addNamedType(JsonType type)
    {
        m_namedTypes.insert(type);
    }

    void addSchemaType(const Subschema *subschema)
    {
        m_schemaTypes.push_back(subschema);
    }

    template<typename FunctorType>
    void applyToNamedTypes(const FunctorType &fn) const
    {
        for (const JsonType namedType : m_namedTypes) {
            if (!fn(namedType)) {
                return;
            }
        }
    }

    template<typename FunctorType>
    void applyToSchemaTypes(const FunctorType &fn) const
    {
        unsigned int index = 0;
        for (const Subschema *subschema : m_schemaTypes) {
            if (!fn(index, subschema)) {
                return;
            }

            index++;
        }
    }

    template<typename AllocatorType>
    static JsonType jsonTypeFromString(const std::basic_string<char,
            std::char_traits<char>, AllocatorType> &typeName)
    {
        if (typeName.compare("any") == 0) {
            return kAny;
        } else if (typeName.compare("array") == 0) {
            return kArray;
        } else if (typeName.compare("boolean") == 0) {
            return kBoolean;
        } else if (typeName.compare("integer") == 0) {
            return kInteger;
        } else if (typeName.compare("null") == 0) {
            return kNull;
        } else if (typeName.compare("number") == 0) {
            return kNumber;
        } else if (typeName.compare("object") == 0) {
            return kObject;
        } else if (typeName.compare("string") == 0) {
            return kString;
        }

        throwRuntimeError("Unrecognised JSON type name '" +
                std::string(typeName.c_str()) + "'");
        abort();
    }

private:
    typedef std::set<JsonType, std::less<JsonType>, internal::CustomAllocator<JsonType>> NamedTypes;

    typedef std::vector<const Subschema *,
            Allocator::rebind<const Subschema *>::other> SchemaTypes;

    /// Set of named JSON types that serve as valid types
    NamedTypes m_namedTypes;

    /// Set of sub-schemas that serve as valid types
    SchemaTypes m_schemaTypes;
};

/**
 * @brief   Represents a 'uniqueItems' constraint
 */
class UniqueItemsConstraint: public BasicConstraint<UniqueItemsConstraint>
{
public:
    UniqueItemsConstraint() = default;

    UniqueItemsConstraint(CustomAlloc allocFn, CustomFree freeFn)
      : BasicConstraint(allocFn, freeFn) { }
};

} // namespace constraints
} // namespace valijson

#ifdef _MSC_VER
#pragma warning( pop )
#endif


text:
package jsoniter

import (
	"fmt"
	"reflect"
	"sort"
	"strings"
	"unicode"
	"unsafe"
)

var typeDecoders = map[string]ValDecoder{}
var fieldDecoders = map[string]ValDecoder{}
var typeEncoders = map[string]ValEncoder{}
var fieldEncoders = map[string]ValEncoder{}
var extensions = []Extension{}

// StructDescriptor describe how should we encode/decode the struct
type StructDescriptor struct {
	onePtrEmbedded     bool
	onePtrOptimization bool
	Type               reflect.Type
	Fields             []*Binding
}

// GetField get one field from the descriptor by its name.
// Can not use map here to keep field orders.
func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding {
	for _, binding := range structDescriptor.Fields {
		if binding.Field.Name == fieldName {
			return binding
		}
	}
	return nil
}

// Binding describe how should we encode/decode the struct field
type Binding struct {
	levels    []int
	Field     *reflect.StructField
	FromNames []string
	ToNames   []string
	Encoder   ValEncoder
	Decoder   ValDecoder
}

// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder.
// Can also rename fields by UpdateStructDescriptor.
type Extension interface {
	UpdateStructDescriptor(structDescriptor *StructDescriptor)
	CreateDecoder(typ reflect.Type) ValDecoder
	CreateEncoder(typ reflect.Type) ValEncoder
	DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder
	DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder
}

// DummyExtension embed this type get dummy implementation for all methods of Extension
type DummyExtension struct {
}

// UpdateStructDescriptor No-op
func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) {
}

// CreateDecoder No-op
func (extension *DummyExtension) CreateDecoder(typ reflect.Type) ValDecoder {
	return nil
}

// CreateEncoder No-op
func (extension *DummyExtension) CreateEncoder(typ reflect.Type) ValEncoder {
	return nil
}

// DecorateDecoder No-op
func (extension *DummyExtension) DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder {
	return decoder
}

// DecorateEncoder No-op
func (extension *DummyExtension) DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder {
	return encoder
}

type funcDecoder struct {
	fun DecoderFunc
}

func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) {
	decoder.fun(ptr, iter)
}

type funcEncoder struct {
	fun         EncoderFunc
	isEmptyFunc func(ptr unsafe.Pointer) bool
}

func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
	encoder.fun(ptr, stream)
}

func (encoder *funcEncoder) EncodeInterface(val interface{}, stream *Stream) {
	WriteToStream(val, stream, encoder)
}

func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool {
	if encoder.isEmptyFunc == nil {
		return false
	}
	return encoder.isEmptyFunc(ptr)
}

// DecoderFunc the function form of TypeDecoder
type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator)

// EncoderFunc the function form of TypeEncoder
type EncoderFunc func(ptr unsafe.Pointer, stream *Stream)

// RegisterTypeDecoderFunc register TypeDecoder for a type with function
func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) {
	typeDecoders[typ] = &funcDecoder{fun}
}

// RegisterTypeDecoder register TypeDecoder for a typ
func RegisterTypeDecoder(typ string, decoder ValDecoder) {
	typeDecoders[typ] = decoder
}

// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function
func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) {
	RegisterFieldDecoder(typ, field, &funcDecoder{fun})
}

// RegisterFieldDecoder register TypeDecoder for a struct field
func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) {
	fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder
}

// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function
func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
	typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc}
}

// RegisterTypeEncoder register TypeEncoder for a type
func RegisterTypeEncoder(typ string, encoder ValEncoder) {
	typeEncoders[typ] = encoder
}

// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function
func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) {
	RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc})
}

// RegisterFieldEncoder register TypeEncoder for a struct field
func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) {
	fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder
}

// RegisterExtension register extension
func RegisterExtension(extension Extension) {
	extensions = append(extensions, extension)
}

func getTypeDecoderFromExtension(typ reflect.Type) ValDecoder {
	decoder := _getTypeDecoderFromExtension(typ)
	if decoder != nil {
		for _, extension := range extensions {
			decoder = extension.DecorateDecoder(typ, decoder)
		}
	}
	return decoder
}
func _getTypeDecoderFromExtension(typ reflect.Type) ValDecoder {
	for _, extension := range extensions {
		decoder := extension.CreateDecoder(typ)
		if decoder != nil {
			return decoder
		}
	}
	typeName := typ.String()
	decoder := typeDecoders[typeName]
	if decoder != nil {
		return decoder
	}
	if typ.Kind() == reflect.Ptr {
		decoder := typeDecoders[typ.Elem().String()]
		if decoder != nil {
			return &optionalDecoder{typ.Elem(), decoder}
		}
	}
	return nil
}

func getTypeEncoderFromExtension(typ reflect.Type) ValEncoder {
	encoder := _getTypeEncoderFromExtension(typ)
	if encoder != nil {
		for _, extension := range extensions {
			encoder = extension.DecorateEncoder(typ, encoder)
		}
	}
	return encoder
}

func _getTypeEncoderFromExtension(typ reflect.Type) ValEncoder {
	for _, extension := range extensions {
		encoder := extension.CreateEncoder(typ)
		if encoder != nil {
			return encoder
		}
	}
	typeName := typ.String()
	encoder := typeEncoders[typeName]
	if encoder != nil {
		return encoder
	}
	if typ.Kind() == reflect.Ptr {
		encoder := typeEncoders[typ.Elem().String()]
		if encoder != nil {
			return &optionalEncoder{encoder}
		}
	}
	return nil
}

func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, error) {
	embeddedBindings := []*Binding{}
	bindings := []*Binding{}
	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)
		tag := field.Tag.Get(cfg.getTagKey())
		tagParts := strings.Split(tag, ",")
		if tag == "-" {
			continue
		}
		if field.Anonymous && (tag == "" || tagParts[0] == "") {
			if field.Type.Kind() == reflect.Struct {
				structDescriptor, err := describeStruct(cfg, field.Type)
				if err != nil {
					return nil, err
				}
				for _, binding := range structDescriptor.Fields {
					binding.levels = append([]int{i}, binding.levels...)
					omitempty := binding.Encoder.(*structFieldEncoder).omitempty
					binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty}
					binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
					embeddedBindings = append(embeddedBindings, binding)
				}
				continue
			} else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
				structDescriptor, err := describeStruct(cfg, field.Type.Elem())
				if err != nil {
					return nil, err
				}
				for _, binding := range structDescriptor.Fields {
					binding.levels = append([]int{i}, binding.levels...)
					omitempty := binding.Encoder.(*structFieldEncoder).omitempty
					binding.Encoder = &optionalEncoder{binding.Encoder}
					binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty}
					binding.Decoder = &deferenceDecoder{field.Type.Elem(), binding.Decoder}
					binding.Decoder = &structFieldDecoder{&field, binding.Decoder}
					embeddedBindings = append(embeddedBindings, binding)
				}
				continue
			}
		}
		fieldNames := calcFieldNames(field.Name, tagParts[0], tag)
		fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name)
		decoder := fieldDecoders[fieldCacheKey]
		if decoder == nil {
			var err error
			decoder, err = decoderOfType(cfg, field.Type)
			if len(fieldNames) > 0 && err != nil {
				return nil, err
			}
		}
		encoder := fieldEncoders[fieldCacheKey]
		if encoder == nil {
			var err error
			encoder, err = encoderOfType(cfg, field.Type)
			if len(fieldNames) > 0 && err != nil {
				return nil, err
			}
			// map is stored as pointer in the struct,
			// and treat nil or empty map as empty field
			if encoder != nil && field.Type.Kind() == reflect.Map {
				encoder = &optionalMapEncoder{encoder}
			}
		}
		binding := &Binding{
			Field:     &field,
			FromNames: fieldNames,
			ToNames:   fieldNames,
			Decoder:   decoder,
			Encoder:   encoder,
		}
		binding.levels = []int{i}
		bindings = append(bindings, binding)
	}
	return createStructDescriptor(cfg, typ, bindings, embeddedBindings), nil
}
func createStructDescriptor(cfg *frozenConfig, typ reflect.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor {
	onePtrEmbedded := false
	onePtrOptimization := false
	if typ.NumField() == 1 {
		firstField := typ.Field(0)
		switch firstField.Type.Kind() {
		case reflect.Ptr:
			if firstField.Anonymous && firstField.Type.Elem().Kind() == reflect.Struct {
				onePtrEmbedded = true
			}
			fallthrough
		case reflect.Map:
			onePtrOptimization = true
		case reflect.Struct:
			onePtrOptimization = isStructOnePtr(firstField.Type)
		}
	}
	structDescriptor := &StructDescriptor{
		onePtrEmbedded:     onePtrEmbedded,
		onePtrOptimization: onePtrOptimization,
		Type:               typ,
		Fields:             bindings,
	}
	for _, extension := range extensions {
		extension.UpdateStructDescriptor(structDescriptor)
	}
	processTags(structDescriptor, cfg)
	// merge normal & embedded bindings & sort with original order
	allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...))
	sort.Sort(allBindings)
	structDescriptor.Fields = allBindings
	return structDescriptor
}

func isStructOnePtr(typ reflect.Type) bool {
	if typ.NumField() == 1 {
		firstField := typ.Field(0)
		switch firstField.Type.Kind() {
		case reflect.Ptr:
			return true
		case reflect.Map:
			return true
		case reflect.Struct:
			return isStructOnePtr(firstField.Type)
		}
	}
	return false
}

type sortableBindings []*Binding

func (bindings sortableBindings) Len() int {
	return len(bindings)
}

func (bindings sortableBindings) Less(i, j int) bool {
	left := bindings[i].levels
	right := bindings[j].levels
	k := 0
	for {
		if left[k] < right[k] {
			return true
		} else if left[k] > right[k] {
			return false
		}
		k++
	}
}

func (bindings sortableBindings) Swap(i, j int) {
	bindings[i], bindings[j] = bindings[j], bindings[i]
}

func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) {
	for _, binding := range structDescriptor.Fields {
		shouldOmitEmpty := false
		tagParts := strings.Split(binding.Field.Tag.Get(cfg.getTagKey()), ",")
		for _, tagPart := range tagParts[1:] {
			if tagPart == "omitempty" {
				shouldOmitEmpty = true
			} else if tagPart == "string" {
				if binding.Field.Type.Kind() == reflect.String {
					binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg}
					binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg}
				} else {
					binding.Decoder = &stringModeNumberDecoder{binding.Decoder}
					binding.Encoder = &stringModeNumberEncoder{binding.Encoder}
				}
			}
		}
		binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder}
		binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty}
	}
}

func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string {
	// ignore?
	if wholeTag == "-" {
		return []string{}
	}
	// rename?
	var fieldNames []string
	if tagProvidedFieldName == "" {
		fieldNames = []string{originalFieldName}
	} else {
		fieldNames = []string{tagProvidedFieldName}
	}
	// private?
	isNotExported := unicode.IsLower(rune(originalFieldName[0]))
	if isNotExported {
		fieldNames = []string{}
	}
	return fieldNames
}


text:
package com.github.ninerules.parameters;

import java.util.Objects;

import com.github.ninerules.entities.Message;

abstract class IntegerParameter implements Parameter{
    private static final long serialVersionUID = 9066650843731685566L;

    int value;

    public IntegerParameter(int value){
        this.value = value;
    }

    @Override
    public int hashCode(){
        return value;
    }

    @Override
    public boolean equals(Object object){
        return object instanceof IntegerParameter && Objects.equals(
                        getClass(), object.getClass())
                && isEqualTo((Parameter)object);
    }

    @Override
    public boolean isEqualTo(Parameter parameter){
        return value == ((IntegerParameter)parameter).value;
    }

    @Override
    public boolean isLessThan(Parameter parameter){
        return value < ((IntegerParameter)parameter).value;
    }

    @Override
    public String format(Message message){
        return message.format(value);
    }
}


text:
Ext.define('Webdesktop.view.logmsg.LogPieStaticsChart', {
    extend: 'Ext.chart.Chart',
    alias:'widget.logpiestaticschart',
    requires: [
    ],

    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            width: 300,
            height: 280,
            animate: false,
            store: 'logmsg.LoggridpieCharts',
            shadow: false,
            insetPadding: 0,
            //theme: 'Base:gradients',
            series: [{
                type: 'pie',
                field: 'counts',
                showInLegend: false,
                label: {
                    field: 'statustype',
                    display: 'rotate',
                    contrast: true,
                    font: '9px Arial'
                }
            }]

        });
        me.callParent(arguments);
    }
});


text:
package SimpleEncrypt;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Class {
	private static JTextField txtTest;
	//public static String out; old char read method
	public static byte[] read;
	public static String rn;
	public static String dePass;
	public static JFrame frame;
	public static byte[] data = null;
	public static JLabel lblProgress;
	public static int on = 0;
	public static int of = 0;
	public static double per = 0;
	public static String type = "";
	static JButton btnNewButton_1;
	static JButton btnDecrypt;

	public static void main(final String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (InstantiationException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (IllegalAccessException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (UnsupportedLookAndFeelException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		frame = new JFrame("hello there");
		frame.setSize(500, 500);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);

		JButton btnNewButton = new JButton("Browse");
		btnNewButton.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				Open of = new Open();

				try {
					of.PickFile();
				} catch (Exception ex) {

				}
			}
		});
		btnNewButton.setBounds(358, 82, 117, 50);
		frame.getContentPane().add(btnNewButton);

		txtTest = new JTextField();
		txtTest.setText("test");
		txtTest.setBounds(22, 91, 324, 34);
		frame.getContentPane().add(txtTest);
		txtTest.setColumns(10);

		btnNewButton_1 = new JButton("Encrypt");
		btnNewButton_1.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				String s = (String)JOptionPane.showInputDialog(
	                    frame,
	                    "Encryption Key:\n"
	                    + "",
	                    "Encrypt",
	                    JOptionPane.DEFAULT_OPTION,
	                    null,
	                    null,
	                    null);

				if ((s != null) && (s.length() > 0)) {

					rn = genKey(s);

				    Path path = Paths.get(txtTest.getText());
				    data = null;
					try {
						data = Files.readAllBytes(path);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					System.out.println(data.length);
					try {
						EncryptFile();
						bDis();
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (UnsupportedEncodingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		btnNewButton_1.setBounds(47, 228, 200, 50);
		frame.getContentPane().add(btnNewButton_1);

		frame.setVisible(true);

		btnDecrypt = new JButton("Decrypt");
		btnDecrypt.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				String s = (String)JOptionPane.showInputDialog(
				                    frame,
				                    "Encryption Key:\n"
				                    + "",
				                    "Decrypt",
				                    JOptionPane.DEFAULT_OPTION,
				                    null,
				                    null,
				                    null);

				if ((s != null) && (s.length() > 0)) {

					dePass = genKey(s);

					 Path path = Paths.get(txtTest.getText());
				     read = null;

				     if (chkKey(dePass, new File(path.toString())) == -1) { // Check if decryption key is valid
				    	 JOptionPane.showMessageDialog(frame, "The encryption key is invalid.", "Error", JOptionPane.ERROR_MESSAGE);
				     } else {
						try {
							read = Files.readAllBytes(path);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

						try {
							DecryptFile();
							bDis();
						} catch (FileNotFoundException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (UnsupportedEncodingException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				     }
				}
			}
		});
		btnDecrypt.setBounds(292, 228, 141, 50);
		frame.getContentPane().add(btnDecrypt);

		lblProgress = new JLabel("Progress:");
		lblProgress.setBounds(103, 165, 318, 15);
		frame.getContentPane().add(lblProgress);

		String testvar = "%߃est";
		System.out.println((int)testvar.charAt(0));

		Runnable updateProg = new Runnable() {
		    public void run() {
		    	lblProgress.setText(type + " Progress: " + on + " of " + of + "  (" + (int)per + "%)");
		    }
		};

		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		executor.scheduleAtFixedRate(updateProg, 0, 100, TimeUnit.MILLISECONDS);
	}

	public JTextField getTextField()
	{
	    return txtTest;
	}

	public static void EncryptFile() throws FileNotFoundException, UnsupportedEncodingException {
		Thread t = new Thread(new Runnable() {
		    public void run() {
				FileOutputStream fos = null;
				String number = String.valueOf(rn);
				try {
					fos = new FileOutputStream(txtTest.getText() + ".encrypted");
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				byte[] enbyts;
				enbyts = new byte[data.length + String.valueOf(sumD(number)).length() + 1]; // embed key sum
				for (int i=0; i < String.valueOf(sumD(number)).length(); i++) {
					enbyts[i] = (byte)String.valueOf(sumD(number)).charAt(i);
				}
				enbyts[String.valueOf(sumD(number)).length()] = '*'; // sum terminator

				int datc = 0;
				int numc = 0;
				int step = 0;
				int lastStdCount = 0;
				boolean lastStd = true; // first byte is standard

				for (int i = 0; i < enbyts.length; i++) {

					on = i;
					of = data.length;
					type = "[Encrypting]";

					try {
						double tmp = (double)100 / (double)of;
						per = tmp * on;
						per = Math.round(per);
						//System.out.println(per + "%");
					} catch (Exception ex) {
						ex.printStackTrace();
					}

					//Digit Encryption:
					int calc1 = 0;
					if (i > String.valueOf(sumD(number)).length()) {
						calc1 = data[datc] - (int)number.charAt(numc);
						datc++;
					} else {
						calc1 = enbyts[i] - (int)number.charAt(numc);
					}

					//Full Encryption:
					int sum = sumD(number);
					calc1 = calc1 - sum;

					enbyts[i] = (byte)calc1; //put encrypted byte in array

					if (lastStd == false) {
						if (lastStdCount == number.length() - 1) {
							lastStdCount = 0;
						} else {
							lastStdCount++;
						}
						numc = lastStdCount;

						lastStd = true;
					} else {
						step = numc;
						for (int ic = 0; ic < (int)number.charAt(numc); ic++) {
							if (step == number.length() - 1) {
								step = 0;
							} else {
								step++;
							}
						}
						numc = step;

						lastStd = false;
					}
				}

				try {
					fos.write(enbyts); // write array to file
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//writer.close();
				enbyts = null;
				data = null;
				System.gc();
				new File(txtTest.getText()).delete();
				JOptionPane.showMessageDialog(frame, "Encryption was successful!", "Success", JOptionPane.INFORMATION_MESSAGE);
				txtTest.setText(txtTest.getText() + ".encrypted");
				bEn();
		    }
		});
		t.start();
	}

	public static void DecryptFile() throws IOException {

		Thread t = new Thread(new Runnable() {
		    public void run() {
		    	String str = txtTest.getText();
				str = str.substring(0, str.length()-10);
				String number = String.valueOf(dePass);
				//PrintWriter writer = new PrintWriter(str);
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(str);
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		        DataOutputStream dos = new DataOutputStream(fos);

		        byte[] debyts;
				debyts = new byte[read.length];
		        //String sizeList = String.valueOf(read.length() - 1);

				int bcount = 0;
				int ci = chkKey(number, new File(txtTest.getText()));
		        int numc = 0;
		        int step = 0;
		        int lastStdCount = 0;
				boolean lastStd = true; // first byte is standard

				for (int i=0; i < read.length; i++) {

					on = i;
					of = read.length;
					type = "[Decrypting]";

					try {
						double tmp = (double)100 / (double)of;
						per = tmp * on;
						per = Math.round(per);
						//System.out.println(per + "%");
					} catch (Exception ex) {
						ex.printStackTrace();
					}

					//Full Encryption:
					int sum = sumD(number);
					int result = read[i] + sum;

					// Digit Encryption:
					//int big = (int)read[i];
					result = result + (int)number.charAt(numc);

					if (i > ci) {
						debyts[bcount] = (byte)result;
						bcount++;
					}

					if (lastStd == false) {
						if (lastStdCount == number.length() - 1) {
							lastStdCount = 0;
						} else {
							lastStdCount++;
						}
						numc = lastStdCount;

						lastStd = true;
					} else {
						step = numc;
						for (int ic = 0; ic < (int)number.charAt(numc); ic++) {
							if (step == number.length() - 1) {
								step = 0;
							} else {
								step++;
							}
						}
						numc = step;

						lastStd = false;
					}
				}

				try {
					dos.write(debyts);
					dos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//out = "";
				debyts = null;
				read = null;
				System.gc();
				new File(txtTest.getText()).delete();
				JOptionPane.showMessageDialog(frame, "Decryption was successful!", "Success", JOptionPane.INFORMATION_MESSAGE);
				txtTest.setText(str);
				bEn();
		    }
		});

		t.start(); // begin thread
	}

	public static int sumD(String num) {
		int sum = 0;
		for (int i = 0; i < num.length(); i++) {
			sum = sum + (int)num.charAt(i);
		}
		return sum;
	}

	public static void bEn() {
		btnNewButton_1.setEnabled(true);
		btnDecrypt.setEnabled(true);
	}

	public static void bDis() {
		btnNewButton_1.setEnabled(false);
		btnDecrypt.setEnabled(false);
	}

	public static int chkKey(String key, File file) {
		byte[] tf = null;
		try {
			tf = Files.readAllBytes(file.toPath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] debyts;
		debyts = new byte[tf.length];
        //String sizeList = String.valueOf(read.length() - 1);

        int numc = 0;
        int step = 0;
        int lastStdCount = 0;
		boolean lastStd = true; // first byte is standard

		for (int i=0; i < 512; i++) { // only decrypt first 512 bytes

			String number = String.valueOf(dePass);

			//Full Encryption:
			int sum = sumD(number);
			int result = 0;
			try {
				result = tf[i] + sum;
			} catch (Exception e) {
				break;
			}

			// Digit Encryption:
			result = result + (int)number.charAt(numc);

			debyts[i] = (byte)result;

			if (lastStd == false) {
				if (lastStdCount == number.length() - 1) {
					lastStdCount = 0;
				} else {
					lastStdCount++;
				}
				numc = lastStdCount;

				lastStd = true;
			} else {
				step = numc;
				for (int ic = 0; ic < (int)number.charAt(numc); ic++) {
					if (step == number.length() - 1) {
						step = 0;
					} else {
						step++;
					}
				}
				numc = step;

				lastStd = false;
			}
		}

		String enSum = "";
		int index = 0;
		for (int i=0; i < 512; i++) {
			try {
				if ((char)debyts[i] == '*') {
					index = i;
					break;
				} else {
					enSum = enSum + (char)debyts[i];
				}
			} catch (Exception e) {
				break;
			}
		}

		if (enSum.equals(String.valueOf(sumD(key)))) {
			System.out.println("KEY IS VALID");
			return index;
		} else {
			System.out.println("KEY IS NOT VALID");
			return -1;
		}
	}

	public static String genKey(String input) {
		String ret = "";
		for (int i = 0; i < input.length(); i++) {
			ret = ret + (int)input.charAt(i);
		}
		return ret;
	}

}