text:
package net.sourceforge.schemaspy.view;

import java.sql.DatabaseMetaData;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import net.sourceforge.schemaspy.model.Database;
import net.sourceforge.schemaspy.model.Table;
import net.sourceforge.schemaspy.util.CaseInsensitiveMap;
import net.sourceforge.schemaspy.util.HtmlEncoder;

/**
 * Default implementation of {@link SqlFormatter}
 *
 * @author John Currier
 */
public class DefaultSqlFormatter implements SqlFormatter {
    private Set<String> keywords;
    private Map<String, Table> tablesByPossibleNames;
    private static String TOKENS = " \t\n\r\f()<>|,";

    /**
     * Return a HTML-formatted representation of the specified SQL.
     *
     * @param sql SQL to be formatted
     * @param db Database
     * @return HTML-formatted representation of the specified SQL
     */
    public String format(String sql, Database db, Set
 references) {
        StringBuilder formatted = new StringBuilder(sql.length() * 2);

        boolean alreadyFormatted = sql.contains("\n") || sql.contains("\r");
        if (alreadyFormatted)
        {
            // apparently already formatted, so dump it as is
            formatted.append("
");

            int len = sql.length();
            for (int i = 0; i < len; i++) {
                char ch = sql.charAt(i);

                // encode everything except whitespace
                if (Character.isWhitespace(ch)) {
                    formatted.append(ch);
                } else {
                    formatted.append(HtmlEncoder.encodeToken(ch));
                }
            }
        }
        else
        {
            formatted.append("
");
            @SuppressWarnings("hiding")
            Set<String> keywords = getKeywords(db.getMetaData());
            StringTokenizer tokenizer = new StringTokenizer(sql, TOKENS, true);
            while (tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                if (keywords.contains(token.toUpperCase())) {
                    formatted.append("");
                    formatted.append(token);
                    formatted.append("");
                } else {
                    formatted.append(HtmlEncoder.encodeToken(token));
                }
            }
        }

        formatted.append("
");

        references.addAll(getReferencedTables(sql, db));

        return formatted.toString();
    }

    /**
     * Returns a {@link Set} of tables/views that are possibly referenced
     * by the specified SQL.
     *
     * @param sql
     * @param db
     * @return
     */
    protected Set
 getReferencedTables(String sql, Database db) {
        Set
 referenced = new HashSet
();

        Map<String, Table> tables = getTableMap(db);
        @SuppressWarnings("hiding")
        Set<String> keywords = getKeywords(db.getMetaData());

        StringTokenizer tokenizer = new StringTokenizer(sql, TOKENS, true);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (!keywords.contains(token.toUpperCase())) {
                Table t = tables.get(token);

                if (t == null) {
                    int lastDot = token.lastIndexOf('.');
                    if (lastDot != -1) {
                        t = tables.get(token.substring(0, lastDot));
                    }
                }

                if (t != null) {
                    referenced.add(t);
                }
            }
        }

        return referenced;
    }

    /**
     * Returns a {@link Map} of all tables/views in the database
     * keyed by several possible ways to refer to the table.
     *
     * @param db
     * @return
     */
    protected Map<String, Table> getTableMap(Database db)
    {
        if (tablesByPossibleNames == null)
        {
            tablesByPossibleNames = new CaseInsensitiveMap
();

            tablesByPossibleNames.putAll(getTableMap(db.getTables(), db.getName()));
            tablesByPossibleNames.putAll(getTableMap(db.getViews(), db.getName()));
        }

        return tablesByPossibleNames;
    }

    /**
     * Returns a {@link Map} of the specified tables/views
     * keyed by several possible ways to refer to the table.
     *
     * @param tables
     * @param dbName
     * @return
     */
    protected Map<String, Table> getTableMap(Collection<? extends Table> tables, String dbName) {
        Map<String, Table> map = new CaseInsensitiveMap
();
        for (Table t : tables) {
            String name = t.getName();
            String schema = t.getSchema();
            if (schema == null)
                schema = dbName;

            map.put(name, t);
            map.put("`" + name + "`", t);
            map.put("'" + name + "'", t);
            map.put("\"" + name + "\"", t);
            map.put(schema + "." + name, t);
            map.put("`" + schema + "`.`" + name + "`", t);
            map.put("'" + schema + "'.'" + name + "'", t);
            map.put("\"" + schema + "\".\"" + name + "\"", t);
            map.put("`" + schema + '.' + name + "`", t);
            map.put("'" + schema + '.' + name + "'", t);
            map.put("\"" + schema + '.' + name + "\"", t);
        }

        return map;
    }

    /**
     * @param meta
     * @return
     */
    public Set<String> getKeywords(DatabaseMetaData meta) {
        if (keywords == null) {
            keywords = new HashSet<String>(Arrays.asList(new String[] {
                "ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND",
                "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG",
                "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY",
                "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER",
                "CHAR_LENGTH", "CHARACTER_LENGTH", "CHECK", "CLOSE", "COALESCE",
                "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION",
                "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING",
                "COUNT", "CREATE", "CROSS", "CURRENT", "CURRENT_DATE", "CURRENT_TIME",
                "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR",
                "DATE", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT",
                "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DESCRIPTOR",
                "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOMAIN", "DOUBLE", "DROP",
                "ELSE", "END", "END - EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC",
                "EXECUTE", "EXISTS", "EXTERNAL", "EXTRACT",
                "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL",
                "GET", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP",
                "HAVING", "HOUR",
                "IDENTITY", "IMMEDIATE", "IN", "INDICATOR", "INITIALLY", "INNER", "INPUT",
                "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTERVAL", "INTO",
                "IS", "ISOLATION",
                "JOIN",
                "KEY",
                "LANGUAGE", "LAST", "LEADING", "LEFT", "LEVEL", "LIKE", "LOCAL", "LOWER",
                "MATCH", "MAX", "MIN", "MINUTE", "MODULE", "MONTH",
                "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NEXT", "NO", "NOT", "NULL",
                "NULLIF", "NUMERIC",
                "OCTET_LENGTH", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER",
                "OUTER", "OUTPUT", "OVERLAPS",
                "PAD", "PARTIAL", "POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY",
                "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC",
                "READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT",
                "ROLLBACK", "ROWS",
                "SCHEMA", "SCROLL", "SECOND", "SECTION", "SELECT", "SESSION", "SESSION_USER",
                "SET", "SIZE", "SMALLINT", "SOME", "SPACE", "SQL", "SQLCODE", "SQLERROR",
                "SQLSTATE", "SUBSTRING", "SUM", "SYSTEM_USER",
                "TABLE", "TEMPORARY", "THEN", "TIME", "TIMESTAMP", "TIMEZONE_HOUR",
                "TIMEZONE_MINUTE", "TO", "TRAILING", "TRANSACTION", "TRANSLATE",
                "TRANSLATION", "TRIM", "TRUE",
                "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USAGE", "USER", "USING",
                "VALUE", "VALUES", "VARCHAR", "VARYING", "VIEW",
                "WHEN", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE",
                "YEAR",
                "ZONE"
            }));

            try {
                String keywordsArray[] = new String[] {
                    meta.getSQLKeywords(),
                    meta.getSystemFunctions(),
                    meta.getNumericFunctions(),
                    meta.getStringFunctions(),
                    meta.getTimeDateFunctions()
                };
                for (int i = 0; i < keywordsArray.length; ++i) {
                    StringTokenizer tokenizer = new StringTokenizer(keywordsArray[i].toUpperCase(), ",");

                    while (tokenizer.hasMoreTokens()) {
                        keywords.add(tokenizer.nextToken().trim());
                    }
                }
            } catch (Exception exc) {
                // don't totally fail just because we can't extract these details...
                System.err.println(exc);
            }
        }

        return keywords;
    }
}


text:
    <blc:one_page_checkout orderInfoForm="${orderInfoForm}"
                           shippingInfoForm="${shippingInfoForm}"
                           billingInfoForm="${billingInfoForm}"
                           orderInfoHelpMessage="#{cart.fillOutBasicOrder}"
                           billingInfoHelpMessage="#{cart.fillOutBillingAddress}"
                           shippingInfoHelpMessage="#{cart.fillOutShippingAddress}"
                           th:remove="tag">

                Your cart is empty

                Continue Shopping

                    ...

    </blc:one_page_checkout>

redpajama_set_name: RedPajamaGithub


text:
package com.google.gson.stream;

/**
 * A pool of string instances. Unlike the {@link String#intern() VM's
 * interned strings}, this pool provides no guarantee of reference equality.
 * It is intended only to save allocations. This class is not thread safe.
 */
final class StringPool {

  private final String[] pool = new String[512];

  /**
   * Returns a string equal to {@code new String(array, start, length)}.
   */
  public String get(char[] array, int start, int length) {
    // Compute an arbitrary hash of the content
    int hashCode = 0;
    for (int i = start; i < start + length; i++) {
      hashCode = (hashCode * 31) + array[i];
    }

    // Pick a bucket using Doug Lea's supplemental secondaryHash function (from HashMap)
    hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
    hashCode ^= (hashCode >>> 7) ^ (hashCode >>> 4);
    int index = hashCode & (pool.length - 1);

    String pooled = pool[index];
    if (pooled == null || pooled.length() != length) {
      String result = new String(array, start, length);
      pool[index] = result;
      return result;
    }

    for (int i = 0; i < length; i++) {
      if (pooled.charAt(i) != array[start + i]) {
        String result = new String(array, start, length);
        pool[index] = result;
        return result;
      }
    }

    return pooled;
  }
}


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { AdvancedComponent } from './advanced.component';

describe('Component: Advanced', () => {
  it('should create an instance', () => {
    let component = new AdvancedComponent();
    expect(component).toBeTruthy();
  });
});


text:
require File.join(File.expand_path(File.dirname(__FILE__)), 'test_helper.rb')

class TestAssetCompiler < Minitest::Test
  include CompilationAssertions

  def setup
    super
    Ichiban.project_root = File.expand_path(File.join(File.dirname(__FILE__), '..', 'example'))
  end

  def teardown
    super
    Dir.glob(File.join(Ichiban.project_root, 'compiled', '**/*')).each do |path|
      FileUtils.rm_rf path
    end
    Ichiban.project_root = nil
  end

  def test_scss_compilation
    FileUtils.mkdir(::File.join(Ichiban.project_root, 'compiled/css'))
    file = Ichiban::SCSSFile.new('assets/css/screen.scss')
    Ichiban::AssetCompiler.new(file).compile
    assert_compiled('css/screen.css')
  end

  def test_image_copying
    FileUtils.mkdir(::File.join(Ichiban.project_root, 'compiled/img'))
    file = Ichiban::ImageFile.new('assets/img/test.png')
    Ichiban::AssetCompiler.new(file).compile
    assert_compiled('img/test.png')
  end

  def test_misc_asset_copying
    file = Ichiban::MiscAssetFile.new('assets/misc/test.txt.gz')
    Ichiban::AssetCompiler.new(file).compile
    assert_compiled('test.txt.gz')
  end

  def test_misplaced_asset_copying
    file = Ichiban::MisplacedAssetFile.new('html/subfolder/misplaced.txt')
    Ichiban::AssetCompiler.new(file).compile
    assert_compiled('subfolder/misplaced.txt')
  end

  def test_htaccess_copying
    file = Ichiban::HtaccessFile.new('webserver/htaccess.txt')
    Ichiban::AssetCompiler.new(file).compile
    '.htaccess'
  end
end


text:
package org.rest.common.persistence.event;

import org.rest.common.persistence.model.IEntity;
import org.springframework.context.ApplicationEvent;

import com.google.common.base.Preconditions;

public final class BeforeEntityCreateEvent<T extends IEntity> extends ApplicationEvent {
    private final Class<T> clazz;
    private final T entity;

    public BeforeEntityCreateEvent(final Object sourceToSet, final Class<T> clazzToSet, final T entityToSet) {
        super(sourceToSet);

        Preconditions.checkNotNull(clazzToSet);
        clazz = clazzToSet;

        Preconditions.checkNotNull(entityToSet);
        entity = entityToSet;
    }

    // API

    public final Class<T> getClazz() {
        return clazz;
    }

    public final T getEntity() {
        return Preconditions.checkNotNull(entity);
    }

}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - HostFileSystemMountInfo

Property of

HostFileSystemVolumeInfo

Extends

DynamicData

See also

HostFileSystemVolume, HostMountInfo

Data Object
                  Description

         The HostFileSystemMountInfo data object describes
  a host mount point for a file system.

Properties

	          Name

	          Type

	          Description

mountInfo	HostMountInfo

         Information about the mount point.

volume	HostFileSystemVolume

         Information about the mounted volume.

vStorageSupport*	xsd:string

         vStorage hardware acceleration support status. This property
  represents the volume's capability for storage acceleration.
  See FileSystemMountInfoVStorageSupportStatus for valid
  values.

  If the ESX Server supports hardware acceleration, the Server
  can offload specific virtual machine management operations
  to a storage device with the hardware acceleration feature.
  With hardware assistance, the host performs storage operations
  faster and consumes less CPU, memory, and storage fabric bandwidth.

  For vSphere 4.0 or earlier hosts, this value will be unset.

Since vSphere API 4.1

						Properties inherited from DynamicData

dynamicProperty, dynamicType

*Need not be set

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="HostFileSystemMountInfo">
            <complexContent>
               <extension base="vim25:DynamicData">
                  <sequence>
                     <element name="mountInfo" type="vim25:HostMountInfo"/>
                     <element name="volume" type="vim25:HostFileSystemVolume"/>
                     <element name="vStorageSupport" type="xsd:string" minOccurs="0"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods


text:
module Api
  class UserTokenService
    TYPES = %w(api ui ws).freeze
    # Additional Requester type token ttl's for authentication
    TYPE_TO_TTL_OVERRIDE = {'ui' => ::Settings.session.timeout}.freeze

    def initialize(config = Settings, args = {})
      @config = config
      @svc_options = args
    end

    def token_mgr(type)
      @token_mgr ||= {}
      case type
      when 'api', 'ui' # The default API token and UI token share the same TokenStore
        @token_mgr['api'] ||= new_token_mgr(base_config[:module], base_config[:name], api_config)
      when 'ws'
        @token_mgr['ws'] ||= TokenManager.new('ws', :token_ttl => ::Settings.session.timeout)
      end
    end

    # API Settings with additional token ttl's
    #
    def api_config
      @api_config ||= ::Settings[base_config[:module]].to_hash
    end

    def generate_token(userid, requester_type)
      validate_userid(userid)
      validate_requester_type(requester_type)

      $api_log.info("Generating Authentication Token for userid: #{userid} requester_type: #{requester_type}")

      token_mgr(requester_type).gen_token(:userid             => userid,
                                          :token_ttl_override => TYPE_TO_TTL_OVERRIDE[requester_type])
    end

    def validate_requester_type(requester_type)
      return if TYPES.include?(requester_type)
      requester_types = TYPES.join(', ')
      raise "Invalid requester_type #{requester_type} specified, valid types are: #{requester_types}"
    end

    private

    def base_config
      @config[:base]
    end

    def log_kv(key, val, pref = "")
      $api_log.info("#{pref}  #{key.to_s.ljust([24, key.to_s.length].max, ' ')}: #{val}")
    end

    def new_token_mgr(mod, name, api_config)
      token_ttl = api_config[:token_ttl]

      options                = {}
      options[:token_ttl]    = token_ttl.to_i_with_method if token_ttl

      log_init(mod, name, options) if @svc_options[:log_init]
      TokenManager.new(mod, options)
    end

    def log_init(mod, name, options)
      $api_log.info("")
      $api_log.info("Creating new Token Manager for the #{name}")
      $api_log.info("   Token Manager  module: #{mod}")
      $api_log.info("   Token Manager options:")
      options.each { |key, val| log_kv(key, val, "    ") }
      $api_log.info("")
    end

    def validate_userid(userid)
      raise "Invalid userid #{userid} specified" unless User.exists?(:userid => userid)
    end
  end
end


text:
package org.springframework.cloud.stream.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.test.binder.MessageCollector;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.SendTo;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Marius Bogoevici
 * @author Ilayaperumal Gopinathan
 */
@RunWith(Parameterized.class)
public class StreamListenerMessageArgumentTests {

	private Class<?> configClass;

	public StreamListenerMessageArgumentTests(Class<?> configClass) {
		this.configClass = configClass;
	}

	@Parameterized.Parameters
	public static Collection InputConfigs() {
		return Arrays.asList(new Class[] {TestPojoWithMessageArgument1.class, TestPojoWithMessageArgument2.class});
	}

	@Test
	@SuppressWarnings("unchecked")
	public void testMessageArgument() throws Exception {
		ConfigurableApplicationContext context = SpringApplication
				.run(this.configClass, "--server.port=0");
		MessageCollector collector = context.getBean(MessageCollector.class);
		Processor processor = context.getBean(Processor.class);
		String id = UUID.randomUUID().toString();
		processor.input().send(MessageBuilder.withPayload("barbar" + id)
				.setHeader("contentType", "text/plain").build());
		TestPojoWithMessageArgument testPojoWithMessageArgument = context
				.getBean(TestPojoWithMessageArgument.class);
		assertThat(testPojoWithMessageArgument.receivedMessages).hasSize(1);
		assertThat(testPojoWithMessageArgument.receivedMessages.get(0).getPayload()).isEqualTo("barbar" + id);
		Message<StreamListenerTestUtils.BarPojo> message = (Message<StreamListenerTestUtils.BarPojo>) collector
				.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
		assertThat(message).isNotNull();
		assertThat(message.getPayload().getBar()).isEqualTo("barbar" + id);
		context.close();
	}

	@EnableBinding(Processor.class)
	@EnableAutoConfiguration
	public static class TestPojoWithMessageArgument1 extends TestPojoWithMessageArgument {

		@StreamListener(Processor.INPUT)
		@SendTo(Processor.OUTPUT)
		public StreamListenerTestUtils.BarPojo receive(Message<String> fooMessage) {
			this.receivedMessages.add(fooMessage);
			StreamListenerTestUtils.BarPojo barPojo = new StreamListenerTestUtils.BarPojo();
			barPojo.setBar(fooMessage.getPayload());
			return barPojo;
		}
	}

	@EnableBinding(Processor.class)
	@EnableAutoConfiguration
	public static class TestPojoWithMessageArgument2 extends TestPojoWithMessageArgument {

		@StreamListener(Processor.INPUT)
		@Output(Processor.OUTPUT)
		public StreamListenerTestUtils.BarPojo receive(Message<String> fooMessage) {
			this.receivedMessages.add(fooMessage);
			StreamListenerTestUtils.BarPojo barPojo = new StreamListenerTestUtils.BarPojo();
			barPojo.setBar(fooMessage.getPayload());
			return barPojo;
		}
	}

	public static class TestPojoWithMessageArgument {
		List<Message<String>> receivedMessages = new ArrayList<>();
	}

}


text:
using ExtendedXmlSerializer.ReflectionModel;
using System;
using System.IO;

namespace ExtendedXmlSerializer.ExtensionModel.Xml
{
	class InstanceFormatter : IInstanceFormatter
	{
		readonly static Func<Stream> Stream = DefaultConstructedActivators.Default.New<MemoryStream>;

		readonly IExtendedXmlSerializer _serializer;
		readonly IXmlWriterFactory      _factory;
		readonly Func<Stream>           _stream;

		public InstanceFormatter(IExtendedXmlSerializer serializer) : this(serializer, Stream) {}

		public InstanceFormatter(IExtendedXmlSerializer serializer, Func<Stream> stream)
			: this(serializer, XmlWriterFactory.Default, stream) {}

		public InstanceFormatter(IExtendedXmlSerializer serializer, IXmlWriterFactory factory, Func<Stream> stream)
		{
			_serializer = serializer;
			_factory    = factory;
			_stream     = stream;
		}

		public string Get(object parameter)
		{
			var stream = _stream();
			using (var writer = _factory.Get(stream))
			{
				_serializer.Serialize(writer, parameter);
				writer.Flush();
				stream.Seek(0, SeekOrigin.Begin);
				var result = new StreamReader(stream).ReadToEnd();
				return result;
			}
		}
	}
}


text:
package limmen.integration.repositories;

import limmen.integration.entities.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * CRUD-repository for the "Employee" table in the chinook database.
 *
 * @author Kim Hammar on 2016-03-22.
 */
@Repository
public class EmployeeRepository {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JdbcTemplate jdbc;

    /**
     * Method to query the database for a employee with a certain id.
     *
     * @param employeeId id of the employee.
     * @return Employee with the id.
     */
    public Employee getEmployee(int employeeId) {
        log.debug("getEmployee {} from Database", employeeId);
        return jdbc.queryForObject("SELECT * FROM \"Employee\" WHERE \"EmployeeId\"=?", employeeMapper, employeeId);
    }

    /**
     * Method to query the database for a list of all employees.
     *
     * @return list of employees.
     */
    public List<Employee> getAllEmployees(){
        log.debug("getAllEmployees from Database");
        return jdbc.query("SELECT * FROM \"Employee\";", employeeMapper);
    }

    /**
     * Method to update the database with a new employee.
     *
     * @param employee employee to insert
     * @return the inserted employee
     */
    public Employee createNewEmployee(Employee employee) {
        log.info("Update Database with new Employee. employeeId: {}, firstName: {}, lastName: {}, title: {}, " +
                "reportsTo: {}, birthDate: {}, hireDate: {}, address: {}, city: {}, state: {}, country: {}, postalCode: {}, phone: {}," +
                "fax: {}, email: {}", employee.getEmployeeId(), employee.getFirstName(), employee.getLastName(),
                employee.getTitle(), employee.getReportsTo(), employee.getBirthDate(), employee.getHireDate(),
                employee.getAddress(), employee.getCity(), employee.getState(), employee.getCountry(), employee.getPostalCode(),
                employee.getPhone(), employee.getFax(), employee.getEmail());
        jdbc.update("INSERT INTO \"Employee\" (\"EmployeeId\", \"FirstName\", \"LastName\", \"Title\", \"ReportsTo\"," +
                "\"BirthDate\", \"HireDate\", \"Address\", \"City\", \"State\", \"Country\", \"PostalCode\"," +
                "\"Phone\", \"Fax\", \"Email\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",
                employee.getEmployeeId(), employee.getFirstName(), employee.getLastName(),
                employee.getTitle(), employee.getReportsTo(), employee.getBirthDate(), employee.getHireDate(),
                employee.getAddress(), employee.getCity(), employee.getState(), employee.getCountry(), employee.getPostalCode(),
                employee.getPhone(), employee.getFax(), employee.getEmail());
        return employee;
    }

    /**
     * Method to query the database for the maximum id of all employees
     *
     * @return maxmum id
     */
    public int getMaxId() {
        log.debug("get max Id of employees");
        return jdbc.queryForObject("SELECT COALESCE(MAX(\"EmployeeId\"),0) FROM \"Employee\";", maxIdMapper);
    }

    /**
     * Method to update the database with new data for a certain employee.
     *
     * @param employee data to update
     * @return updated employee
     */
    public Employee updateEmployee(Employee employee) {
        log.debug("update employee {}", employee.getEmployeeId());
        jdbc.update("UPDATE \"Employee\" SET \"FirstName\" = ?, \"LastName\" = ?, \"Title\" = ?, \"ReportsTo\" = ?," +
                "\"BirthDate\" = ?, \"HireDate\" = ?, \"Address\" = ?, \"City\" = ?, \"State\" = ?, \"Country\" = ?," +
                "\"PostalCode\" = ?, \"Phone\" = ?, \"Fax\" = ?, \"Email\" = ? WHERE \"EmployeeId\" = ?;",
                employee.getFirstName(), employee.getLastName(),
                employee.getTitle(), employee.getReportsTo(), employee.getBirthDate(), employee.getHireDate(),
                employee.getAddress(), employee.getCity(), employee.getState(), employee.getCountry(),
                employee.getPostalCode(),
                employee.getPhone(), employee.getFax(), employee.getEmail(), employee.getEmployeeId());
        return employee;
    }

    /**
     * Method to delete employee from the database.
     *
     * @param employeeId id of the employee to delete
     */
    public void deleteEmployee(int employeeId) {
        log.debug("delete employee {}", employeeId);
        jdbc.update("DELETE FROM \"Employee\" WHERE \"EmployeeId\" = ?;", employeeId);
    }

    /**
     * Method to delete all employees from the database.
     */
    public void deleteEmployees() {
        log.debug("delete all employees");
        jdbc.update("DELETE  * FROM \"Employee\";");
    }

    private static final RowMapper<Employee> employeeMapper = new RowMapper<Employee>() {
        public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
            Employee employee = new Employee(rs.getInt("EmployeeId"), rs.getString("LastName"), rs.getString("FirstName"),
                    rs.getString("Title"), rs.getInt("ReportsTo"), rs.getTimestamp("BirthDate"),
                    rs.getTimestamp("HireDate"), rs.getString("Address"), rs.getString("City"), rs.getString("State"),
                    rs.getString("Country"), rs.getString("PostalCode"), rs.getString("Phone"), rs.getString("Fax"),
                    rs.getString("Email"));
            return employee;
        }
    };

    private static final RowMapper<Integer> maxIdMapper = new RowMapper<Integer>() {
        public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
            int id = rs.getInt(1);
            return id;
        }
    };
}


text:
<?php

namespace common\models\base;

use Yii;

/**
 * This is the model class for table "{{%tag}}".
 *
 * @property string $id
 * @property string $classify
 * @property string $language
 * @property string $name
 * @property string $url
 * @property string $title
 * @property string $description
 * @property string $texttop
 * @property string $text
 * @property string $status
 * @property string $created
 *
 * @property Language $language0
 */
class Tag extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%tag}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['language', 'name', 'url'], 'required'],
            [['language'], 'integer'],
            [['texttop', 'text', 'status'], 'string'],
            [['created'], 'safe'],
            [['classify', 'name', 'url', 'title', 'description'], 'string', 'max' => 255],
            [['name'], 'unique'],
            [['url'], 'unique'],
            [['language', 'url'], 'unique', 'targetAttribute' => ['language', 'url'], 'message' => 'The combination of Language and Url has already been taken.'],
            [['language'], 'exist', 'skipOnError' => true, 'targetClass' => Language::className(), 'targetAttribute' => ['language' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'classify' => Yii::t('app', 'Classify'),
            'language' => Yii::t('app', 'Language'),
            'name' => Yii::t('app', 'Name'),
            'url' => Yii::t('app', 'Url'),
            'title' => Yii::t('app', 'Title'),
            'description' => Yii::t('app', 'Description'),
            'texttop' => Yii::t('app', 'Texttop'),
            'text' => Yii::t('app', 'Text'),
            'status' => Yii::t('app', 'Status'),
            'created' => Yii::t('app', 'Created'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLanguage0()
    {
        return $this->hasOne(Language::className(), ['id' => 'language']);
    }
}


text:
package org.b3log.solo.model;

/**
 * This class defines all article model relevant keys.
 *
 * @author Liang Ding
 * @version 1.0.1.5, Apr 29, 2012
 * @since 0.3.1
 */
public final class Article {

    /**
     * Article.
     */
    public static final String ARTICLE = "article";
    /**
     * Articles.
     */
    public static final String ARTICLES = "articles";
    /**
     * Key of title.
     */
    public static final String ARTICLE_TITLE = "articleTitle";
    /**
     * Key of abstract.
     */
    public static final String ARTICLE_ABSTRACT = "articleAbstract";
    /**
     * Key of content.
     */
    public static final String ARTICLE_CONTENT = "articleContent";
    /**
     * Key of create date.
     */
    public static final String ARTICLE_CREATE_DATE = "articleCreateDate";
    /**
     * Key of create time.
     */
    public static final String ARTICLE_CREATE_TIME = "articleCreateTime";
    /**
     * Key of update date.
     */
    public static final String ARTICLE_UPDATE_DATE = "articleUpdateDate";
    /**
     * Key of tags.
     */
    public static final String ARTICLE_TAGS_REF = "articleTags";
    /**
     * Key of comment count.
     */
    public static final String ARTICLE_COMMENT_COUNT = "articleCommentCount";
    /**
     * Key of view count.
     */
    public static final String ARTICLE_VIEW_COUNT = "articleViewCount";
    /**
     * Key of comments.
     */
    public static final String ARTICLE_COMMENTS_REF = "articleComments";
    /**
     * Key of sign id.
     */
    public static final String ARTICLE_SIGN_ID = "articleSignId";
    /**
     * Key of permalink.
     */
    public static final String ARTICLE_PERMALINK = "articlePermalink";
    /**
     * Key of put top.
     */
    public static final String ARTICLE_PUT_TOP = "articlePutTop";
    /**
     * Key of is published.
     */
    public static final String ARTICLE_IS_PUBLISHED = "articleIsPublished";
    /**
     * Key of author email.
     */
    public static final String ARTICLE_AUTHOR_EMAIL = "articleAuthorEmail";
    /**
     * Key of had been published.
     */
    public static final String ARTICLE_HAD_BEEN_PUBLISHED = "articleHadBeenPublished";
    /**
     * Key of random double.
     */
    public static final String ARTICLE_RANDOM_DOUBLE = "articleRandomDouble";
    /**
     * Key of comment-able.
     */
    public static final String ARTICLE_COMMENTABLE = "articleCommentable";
    /**
     * Key of view password.
     */
    public static final String ARTICLE_VIEW_PWD = "articleViewPwd";
    /**
     * Key of article editor type.
     *
     * @see Preference#EDITOR_TYPE
     */
    public static final String ARTICLE_EDITOR_TYPE = "articleEditorType";

    /**
     * Private default constructor.
     */
    private Article() {
    }
}


text:
using System;

namespace LMS.Configuration
{
    public static class ConfigurationManager
    {
        public static DatabaseConfiguration Database
        {
            get
            {
                return (DatabaseConfiguration)((ConfigurationSectionHandler)System.Configuration.ConfigurationManager.GetSection("lms")).Database;
            }
        }

        public static HttpRouteConfiguration HttpRoute
        {
            get
            {
                return (HttpRouteConfiguration)((ConfigurationSectionHandler)System.Configuration.ConfigurationManager.GetSection("lms")).HttpRoute;
            }
        }
    }
}


text:
<?php

/**
 * TblCeinture filter form base class.
 *
 * @package    sallesport
 * @subpackage filter
 * @author     Your name here
 */
abstract class BaseTblCeintureFormFilter extends BaseFormFilterPropel
{
  public function setup()
  {
    $this->setWidgets(array(
      'adherent_id'         => new sfWidgetFormPropelChoice(array('model' => 'TblAdherent', 'add_empty' => true)),
      'grade_id'            => new sfWidgetFormPropelChoice(array('model' => 'RefGradeCeinture', 'add_empty' => true)),
      'competance_id'       => new sfWidgetFormPropelChoice(array('model' => 'RefCompetance', 'add_empty' => true)),
      'titre_entraineur_id' => new sfWidgetFormPropelChoice(array('model' => 'RefTitreEntraineur', 'add_empty' => true)),
      'ceinture_couleur_id' => new sfWidgetFormPropelChoice(array('model' => 'RefCeintureCouleur', 'add_empty' => true)),
      'date_acquisition'    => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate())),
      'created_at'          => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate())),
      'deleted_at'          => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate())),
    ));

    $this->setValidators(array(
      'adherent_id'         => new sfValidatorPropelChoice(array('required' => false, 'model' => 'TblAdherent', 'column' => 'id_adherent')),
      'grade_id'            => new sfValidatorPropelChoice(array('required' => false, 'model' => 'RefGradeCeinture', 'column' => 'grade_id')),
      'competance_id'       => new sfValidatorPropelChoice(array('required' => false, 'model' => 'RefCompetance', 'column' => 'competance_id')),
      'titre_entraineur_id' => new sfValidatorPropelChoice(array('required' => false, 'model' => 'RefTitreEntraineur', 'column' => 'titre_entraineur_id')),
      'ceinture_couleur_id' => new sfValidatorPropelChoice(array('required' => false, 'model' => 'RefCeintureCouleur', 'column' => 'ceinture_couleur_id')),
      'date_acquisition'    => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDate(array('required' => false)), 'to_date' => new sfValidatorDate(array('required' => false)))),
      'created_at'          => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDate(array('required' => false)), 'to_date' => new sfValidatorDate(array('required' => false)))),
      'deleted_at'          => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDate(array('required' => false)), 'to_date' => new sfValidatorDate(array('required' => false)))),
    ));

    $this->widgetSchema->setNameFormat('tbl_ceinture_filters[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }

  public function getModelName()
  {
    return 'TblCeinture';
  }

  public function getFields()
  {
    return array(
      'ceinture_id'         => 'Number',
      'adherent_id'         => 'ForeignKey',
      'grade_id'            => 'ForeignKey',
      'competance_id'       => 'ForeignKey',
      'titre_entraineur_id' => 'ForeignKey',
      'ceinture_couleur_id' => 'ForeignKey',
      'date_acquisition'    => 'Date',
      'created_at'          => 'Date',
      'deleted_at'          => 'Date',
    );
  }
}


text:
package org.apache.parquet.proto;

import com.google.protobuf.ByteString;
import org.junit.Test;
import org.apache.parquet.proto.test.TestProto3;
import org.apache.parquet.proto.test.TestProtobuf;

import java.util.List;

import static org.apache.parquet.proto.TestUtils.testData;
import static org.apache.parquet.proto.test.TestProtobuf.SchemaConverterAllDatatypes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

public class ProtoRecordConverterTest {

  @Test
  public void testAllTypes() throws Exception {
    SchemaConverterAllDatatypes.Builder data;
    data = SchemaConverterAllDatatypes.newBuilder();

    data.setOptionalBool(true);
    data.setOptionalBytes(ByteString.copyFrom("someText", "UTF-8"));
    data.setOptionalDouble(0.577);
    data.setOptionalFloat(3.1415f);
    data.setOptionalEnum(SchemaConverterAllDatatypes.TestEnum.FIRST);
    data.setOptionalFixed32(1000 * 1000 * 1);
    data.setOptionalFixed64(1000 * 1000 * 1000 * 2);
    data.setOptionalInt32(1000 * 1000 * 3);
    data.setOptionalInt64(1000L * 1000 * 1000 * 4);
    data.setOptionalSFixed32(1000 * 1000 * 5);
    data.setOptionalSFixed64(1000L * 1000 * 1000 * 6);
    data.setOptionalSInt32(1000 * 1000 * 56);
    data.setOptionalSInt64(1000L * 1000 * 1000 * 7);
    data.setOptionalString("Good Will Hunting");
    data.setOptionalUInt32(1000 * 1000 * 8);
    data.setOptionalUInt64(1000L * 1000 * 1000 * 9);
    data.getOptionalMessageBuilder().setSomeId(1984);
    data.getPbGroupBuilder().setGroupInt(1492);

    SchemaConverterAllDatatypes dataBuilt = data.build();
    data.clear();

    List<TestProtobuf.SchemaConverterAllDatatypes> result;
    result = testData(dataBuilt);

    //data are fully checked in testData function. Lets do one more check.
    SchemaConverterAllDatatypes o = result.get(0);
    assertEquals("Good Will Hunting", o.getOptionalString());

    assertEquals(true, o.getOptionalBool());
    assertEquals(ByteString.copyFrom("someText", "UTF-8"), o.getOptionalBytes());
    assertEquals(0.577, o.getOptionalDouble(), 0.00001);
    assertEquals(3.1415f, o.getOptionalFloat(), 0.00001);
    assertEquals(SchemaConverterAllDatatypes.TestEnum.FIRST, o.getOptionalEnum());
    assertEquals(1000 * 1000 * 1, o.getOptionalFixed32());
    assertEquals(1000 * 1000 * 1000 * 2, o.getOptionalFixed64());
    assertEquals(1000 * 1000 * 3, o.getOptionalInt32());
    assertEquals(1000L * 1000 * 1000 * 4, o.getOptionalInt64());
    assertEquals(1000 * 1000 * 5, o.getOptionalSFixed32());
    assertEquals(1000L * 1000 * 1000 * 6, o.getOptionalSFixed64());
    assertEquals(1000 * 1000 * 56, o.getOptionalSInt32());
    assertEquals(1000L * 1000 * 1000 * 7, o.getOptionalSInt64());
    assertEquals(1000 * 1000 * 8, o.getOptionalUInt32());
    assertEquals(1000L * 1000 * 1000 * 9, o.getOptionalUInt64());
    assertEquals(1984, o.getOptionalMessage().getSomeId());
    assertEquals(1492, o.getPbGroup().getGroupInt());
  }

  @Test
  public void testProto3AllTypes() throws Exception {
    TestProto3.SchemaConverterAllDatatypes.Builder data;
    data = TestProto3.SchemaConverterAllDatatypes.newBuilder();

    data.setOptionalBool(true);
    data.setOptionalBytes(ByteString.copyFrom("someText", "UTF-8"));
    data.setOptionalDouble(0.577);
    data.setOptionalFloat(3.1415f);
    data.setOptionalEnum(TestProto3.SchemaConverterAllDatatypes.TestEnum.FIRST);
    data.setOptionalFixed32(1000 * 1000 * 1);
    data.setOptionalFixed64(1000 * 1000 * 1000 * 2);
    data.setOptionalInt32(1000 * 1000 * 3);
    data.setOptionalInt64(1000L * 1000 * 1000 * 4);
    data.setOptionalSFixed32(1000 * 1000 * 5);
    data.setOptionalSFixed64(1000L * 1000 * 1000 * 6);
    data.setOptionalSInt32(1000 * 1000 * 56);
    data.setOptionalSInt64(1000L * 1000 * 1000 * 7);
    data.setOptionalString("Good Will Hunting");
    data.setOptionalUInt32(1000 * 1000 * 8);
    data.setOptionalUInt64(1000L * 1000 * 1000 * 9);
    data.getOptionalMessageBuilder().setSomeId(1984);

    TestProto3.SchemaConverterAllDatatypes dataBuilt = data.build();
    data.clear();

    List<TestProto3.SchemaConverterAllDatatypes> result;
    result = testData(dataBuilt);

    //data are fully checked in testData function. Lets do one more check.
    TestProto3.SchemaConverterAllDatatypes o = result.get(0);
    assertEquals("Good Will Hunting", o.getOptionalString());

    assertEquals(true, o.getOptionalBool());
    assertEquals(ByteString.copyFrom("someText", "UTF-8"), o.getOptionalBytes());
    assertEquals(0.577, o.getOptionalDouble(), 0.00001);
    assertEquals(3.1415f, o.getOptionalFloat(), 0.00001);
    assertEquals(TestProto3.SchemaConverterAllDatatypes.TestEnum.FIRST, o.getOptionalEnum());
    assertEquals(1000 * 1000 * 1, o.getOptionalFixed32());
    assertEquals(1000 * 1000 * 1000 * 2, o.getOptionalFixed64());
    assertEquals(1000 * 1000 * 3, o.getOptionalInt32());
    assertEquals(1000L * 1000 * 1000 * 4, o.getOptionalInt64());
    assertEquals(1000 * 1000 * 5, o.getOptionalSFixed32());
    assertEquals(1000L * 1000 * 1000 * 6, o.getOptionalSFixed64());
    assertEquals(1000 * 1000 * 56, o.getOptionalSInt32());
    assertEquals(1000L * 1000 * 1000 * 7, o.getOptionalSInt64());
    assertEquals(1000 * 1000 * 8, o.getOptionalUInt32());
    assertEquals(1000L * 1000 * 1000 * 9, o.getOptionalUInt64());
    assertEquals(1984, o.getOptionalMessage().getSomeId());
  }

  @Test
  public void testAllTypesMultiple() throws Exception {
    int count = 100;
    SchemaConverterAllDatatypes[] input = new SchemaConverterAllDatatypes[count];

    for (int i = 0; i < count; i++) {
      SchemaConverterAllDatatypes.Builder d = SchemaConverterAllDatatypes.newBuilder();

      if (i % 2 != 0) d.setOptionalBool(true);
      if (i % 3 != 0) d.setOptionalBytes(ByteString.copyFrom("someText " + i, "UTF-8"));
      if (i % 4 != 0) d.setOptionalDouble(0.577 * i);
      if (i % 5 != 0) d.setOptionalFloat(3.1415f * i);
      if (i % 6 != 0) d.setOptionalEnum(SchemaConverterAllDatatypes.TestEnum.FIRST);
      if (i % 7 != 0) d.setOptionalFixed32(1000 * i * 1);
      if (i % 8 != 0) d.setOptionalFixed64(1000 * i * 1000 * 2);
      if (i % 9 != 0) d.setOptionalInt32(1000 * i * 3);
      if (i % 2 != 1) d.setOptionalSFixed32(1000 * i * 5);
      if (i % 3 != 1) d.setOptionalSFixed64(1000 * i * 1000 * 6);
      if (i % 4 != 1) d.setOptionalSInt32(1000 * i * 56);
      if (i % 5 != 1) d.setOptionalSInt64(1000 * i * 1000 * 7);
      if (i % 6 != 1) d.setOptionalString("Good Will Hunting " + i);
      if (i % 7 != 1) d.setOptionalUInt32(1000 * i * 8);
      if (i % 8 != 1) d.setOptionalUInt64(1000 * i * 1000 * 9);
      if (i % 9 != 1) d.getOptionalMessageBuilder().setSomeId(1984 * i);
      if (i % 2 != 1) d.getPbGroupBuilder().setGroupInt(1492 * i);
      if (i % 3 != 1) d.setOptionalInt64(1000 * i * 1000 * 4);
      input[i] = d.build();
    }

    List<TestProtobuf.SchemaConverterAllDatatypes> result;
    result = testData(input);

    //data are fully checked in testData function. Lets do one more check.
    assertEquals("Good Will Hunting 0", result.get(0).getOptionalString());
    assertEquals("Good Will Hunting 90", result.get(90).getOptionalString());
  }

  @Test
  public void testProto3AllTypesMultiple() throws Exception {
    int count = 100;
    TestProto3.SchemaConverterAllDatatypes[] input = new TestProto3.SchemaConverterAllDatatypes[count];

    for (int i = 0; i < count; i++) {
      TestProto3.SchemaConverterAllDatatypes.Builder d = TestProto3.SchemaConverterAllDatatypes.newBuilder();

      if (i % 2 != 0) d.setOptionalBool(true);
      if (i % 3 != 0) d.setOptionalBytes(ByteString.copyFrom("someText " + i, "UTF-8"));
      if (i % 4 != 0) d.setOptionalDouble(0.577 * i);
      if (i % 5 != 0) d.setOptionalFloat(3.1415f * i);
      if (i % 6 != 0) d.setOptionalEnum(TestProto3.SchemaConverterAllDatatypes.TestEnum.FIRST);
      if (i % 7 != 0) d.setOptionalFixed32(1000 * i * 1);
      if (i % 8 != 0) d.setOptionalFixed64(1000 * i * 1000 * 2);
      if (i % 9 != 0) d.setOptionalInt32(1000 * i * 3);
      if (i % 2 != 1) d.setOptionalSFixed32(1000 * i * 5);
      if (i % 3 != 1) d.setOptionalSFixed64(1000 * i * 1000 * 6);
      if (i % 4 != 1) d.setOptionalSInt32(1000 * i * 56);
      if (i % 5 != 1) d.setOptionalSInt64(1000 * i * 1000 * 7);
      if (i % 6 != 1) d.setOptionalString("Good Will Hunting " + i);
      if (i % 7 != 1) d.setOptionalUInt32(1000 * i * 8);
      if (i % 8 != 1) d.setOptionalUInt64(1000 * i * 1000 * 9);
      if (i % 9 != 1) d.getOptionalMessageBuilder().setSomeId(1984 * i);
      if (i % 3 != 1) d.setOptionalInt64(1000 * i * 1000 * 4);
      input[i] = d.build();
    }

    List<TestProto3.SchemaConverterAllDatatypes> result;
    result = testData(input);

    //data are fully checked in testData function. Lets do one more check.
    assertEquals("Good Will Hunting 0", result.get(0).getOptionalString());
    assertEquals("Good Will Hunting 90", result.get(90).getOptionalString());
  }

  @Test
  public void testDefaults() throws Exception {
    SchemaConverterAllDatatypes.Builder data;
    data = SchemaConverterAllDatatypes.newBuilder();

    List<SchemaConverterAllDatatypes> result = testData(data.build());
    SchemaConverterAllDatatypes message = result.get(0);
    assertEquals("", message.getOptionalString());
    assertEquals(false, message.getOptionalBool());
    assertEquals(0, message.getOptionalFixed32());
  }

  @Test
  public void testProto3Defaults() throws Exception {
    TestProto3.SchemaConverterAllDatatypes.Builder data;
    data = TestProto3.SchemaConverterAllDatatypes.newBuilder();

    List<TestProto3.SchemaConverterAllDatatypes> result = testData(data.build());
    TestProto3.SchemaConverterAllDatatypes message = result.get(0);
    assertEquals("", message.getOptionalString());
    assertEquals(false, message.getOptionalBool());
    assertEquals(0, message.getOptionalFixed32());
  }

  @Test
  public void testRepeatedMessages() throws Exception {
    TestProtobuf.TopMessage.Builder top = TestProtobuf.TopMessage.newBuilder();
    top.addInnerBuilder().setOne("First inner");
    top.addInnerBuilder().setTwo("Second inner");
    top.addInnerBuilder().setThree("Third inner");

    TestProtobuf.TopMessage result = testData(top.build()).get(0);

    assertEquals(3, result.getInnerCount());

    TestProtobuf.InnerMessage first = result.getInner(0);
    TestProtobuf.InnerMessage second = result.getInner(1);
    TestProtobuf.InnerMessage third = result.getInner(2);

    assertEquals("First inner", first.getOne());
    assertFalse(first.hasTwo());
    assertFalse(first.hasThree());

    assertEquals("Second inner", second.getTwo());
    assertFalse(second.hasOne());
    assertFalse(second.hasThree());

    assertEquals("Third inner", third.getThree());
    assertFalse(third.hasOne());
    assertFalse(third.hasTwo());
  }

  @Test
  public void testProto3RepeatedMessages() throws Exception {
    TestProto3.TopMessage.Builder top = TestProto3.TopMessage.newBuilder();
    top.addInnerBuilder().setOne("First inner");
    top.addInnerBuilder().setTwo("Second inner");
    top.addInnerBuilder().setThree("Third inner");

    TestProto3.TopMessage result = testData(top.build()).get(0);

    assertEquals(3, result.getInnerCount());

    TestProto3.InnerMessage first = result.getInner(0);
    TestProto3.InnerMessage second = result.getInner(1);
    TestProto3.InnerMessage third = result.getInner(2);

    assertEquals("First inner", first.getOne());
    assertTrue(first.getTwo().isEmpty());
    assertTrue(first.getThree().isEmpty());

    assertEquals("Second inner", second.getTwo());
    assertTrue(second.getOne().isEmpty());
    assertTrue(second.getThree().isEmpty());

    assertEquals("Third inner", third.getThree());
    assertTrue(third.getOne().isEmpty());
    assertTrue(third.getTwo().isEmpty());
  }

  @Test
  public void testRepeatedInt() throws Exception {
    TestProtobuf.RepeatedIntMessage.Builder top = TestProtobuf.RepeatedIntMessage.newBuilder();

    top.addRepeatedInt(1);
    top.addRepeatedInt(2);
    top.addRepeatedInt(3);

    TestProtobuf.RepeatedIntMessage result = testData(top.build()).get(0);

    assertEquals(3, result.getRepeatedIntCount());

    assertEquals(1, result.getRepeatedInt(0));
    assertEquals(2, result.getRepeatedInt(1));
    assertEquals(3, result.getRepeatedInt(2));
  }

  @Test
  public void testProto3RepeatedInt() throws Exception {
    TestProto3.RepeatedIntMessage.Builder top = TestProto3.RepeatedIntMessage.newBuilder();

    top.addRepeatedInt(1);
    top.addRepeatedInt(2);
    top.addRepeatedInt(3);

    TestProto3.RepeatedIntMessage result = testData(top.build()).get(0);

    assertEquals(3, result.getRepeatedIntCount());

    assertEquals(1, result.getRepeatedInt(0));
    assertEquals(2, result.getRepeatedInt(1));
    assertEquals(3, result.getRepeatedInt(2));
  }

  @Test
  public void testLargeProtobufferFieldId() throws Exception {
    TestProtobuf.HighIndexMessage.Builder builder = TestProtobuf.HighIndexMessage.newBuilder();
    builder.addRepeatedInt(1);
    builder.addRepeatedInt(2);

    testData(builder.build());
  }

  @Test
  public void testProto3LargeProtobufferFieldId() throws Exception {
    TestProto3.HighIndexMessage.Builder builder = TestProto3.HighIndexMessage.newBuilder();
    builder.addRepeatedInt(1);
    builder.addRepeatedInt(2);

    testData(builder.build());
  }

  @Test
  public void testUnknownEnum() throws Exception {
    TestProto3.SchemaConverterAllDatatypes.Builder data;
    data = TestProto3.SchemaConverterAllDatatypes.newBuilder();
    data.setOptionalEnumValue(42);

    TestProto3.SchemaConverterAllDatatypes dataBuilt = data.build();
    data.clear();

    List<TestProto3.SchemaConverterAllDatatypes> result;
    result = testData(dataBuilt);

    //data are fully checked in testData function. Lets do one more check.
    TestProto3.SchemaConverterAllDatatypes o = result.get(0);
    assertSame(o.getOptionalEnum(), TestProto3.SchemaConverterAllDatatypes.TestEnum.UNRECOGNIZED);
    assertEquals(o.getOptionalEnumValue(), 42);
  }
}


text:
from __future__ import unicode_literals

import datetime

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as pg
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.mutable import MutableDict, MutableList

from hyputils.memex.db import Base, types
from hyputils.memex.util import markdown, uri
from hyputils.memex.util.user import split_user

class Annotation(Base):

    """Model class representing a single annotation."""

    __tablename__ = "annotation"
    __table_args__ = (
        # Tags are stored in an array-type column, and indexed using a
        # generalised inverted index. For more information on the use of GIN
        # indices for array columns, see:
        #
        #   http://www.databasesoup.com/2015/01/tag-all-things.html
        #   http://www.postgresql.org/docs/9.5/static/gin-intro.html
        #
        sa.Index("ix__annotation_tags", "tags", postgresql_using="gin"),
        sa.Index("ix__annotation_updated", "updated"),
        # This is a functional index on the *first* of the annotation's
        # references, pointing to the top-level annotation it refers to. We're
        # using 1 here because Postgres uses 1-based array indexing.
        sa.Index("ix__annotation_thread_root", sa.text('("references"[1])')),
    )

    #: Annotation ID: these are stored as UUIDs in the database, and mapped
    #: transparently to a URL-safe Base64-encoded string.
    id = sa.Column(
        types.URLSafeUUID, server_default=sa.func.uuid_generate_v1mc(), primary_key=True
    )

    #: The timestamp when the annotation was created.
    created = sa.Column(
        sa.DateTime,
        default=datetime.datetime.utcnow,
        server_default=sa.func.now(),
        nullable=False,
    )

    #: The timestamp when the user edited the annotation last.
    updated = sa.Column(
        sa.DateTime,
        server_default=sa.func.now(),
        default=datetime.datetime.utcnow,
        nullable=False,
    )

    #: The full userid (e.g. 'acct:foo@example.com') of the owner of this
    #: annotation.
    userid = sa.Column(sa.UnicodeText, nullable=False, index=True)
    #: The string id of the group in which this annotation is published.
    #: Defaults to the global public group, "__world__".
    groupid = sa.Column(
        sa.UnicodeText,
        default="__world__",
        server_default="__world__",
        nullable=False,
        index=True,
    )

    #: The textual body of the annotation.
    _text = sa.Column("text", sa.UnicodeText)
    #: The Markdown-rendered and HTML-sanitized textual body of the annotation.
    _text_rendered = sa.Column("text_rendered", sa.UnicodeText)

    #: The tags associated with the annotation.
    tags = sa.Column(
        MutableList.as_mutable(pg.ARRAY(sa.UnicodeText, zero_indexes=True))
    )

    #: A boolean indicating whether this annotation is shared with members of
    #: the group it is published in. "Private"/"Only me" annotations have
    #: shared=False.
    shared = sa.Column(
        sa.Boolean,
        nullable=False,
        default=False,
        server_default=sa.sql.expression.false(),
    )

    #: The URI of the annotated page, as provided by the client.
    _target_uri = sa.Column("target_uri", sa.UnicodeText)
    #: The URI of the annotated page in normalized form.
    _target_uri_normalized = sa.Column("target_uri_normalized", sa.UnicodeText)
    #: The serialized selectors for the annotation on the annotated page.
    target_selectors = sa.Column(
        types.AnnotationSelectorJSONB, default=list, server_default=sa.func.jsonb("[]")
    )

    #: An array of annotation IDs which are ancestors of this annotation.
    references = sa.Column(
        pg.ARRAY(types.URLSafeUUID, zero_indexes=True),
        default=list,
        server_default=sa.text("ARRAY[]::uuid[]"),
    )

    #: Any additional serialisable data provided by the client.
    extra = sa.Column(
        MutableDict.as_mutable(pg.JSONB),
        default=dict,
        server_default=sa.func.jsonb("{}"),
        nullable=False,
    )

    #: Has the annotation been deleted?
    deleted = sa.Column(
        sa.Boolean,
        nullable=False,
        default=False,
        server_default=sa.sql.expression.false(),
    )

    document_id = sa.Column(sa.Integer, sa.ForeignKey("document.id"), nullable=False)

    document = sa.orm.relationship("Document", backref="annotations")

    thread = sa.orm.relationship(
        "Annotation",
        primaryjoin=(sa.orm.foreign(id) == sa.orm.remote(references[0])),
        viewonly=True,
        uselist=True,
    )

    @hybrid_property
    def target_uri(self):
        return self._target_uri

    @target_uri.setter
    def target_uri(self, value):
        self._target_uri = value
        self._target_uri_normalized = uri.normalize(value)

    @hybrid_property
    def target_uri_normalized(self):
        return self._target_uri_normalized

    @hybrid_property
    def text(self):
        return self._text

    @text.setter
    def text(self, value):
        self._text = value
        # N.B. We MUST take care here of appropriately escaping the user
        # input. Code elsewhere will assume that the content of the
        # `text_rendered` field is safe for printing without further escaping.
        #
        # `markdown.render` does the hard work for now.
        self._text_rendered = markdown.render(value)

    @hybrid_property
    def text_rendered(self):
        return self._text_rendered

    @property
    def thread_ids(self):
        return [thread_annotation.id for thread_annotation in self.thread]

    @property
    def is_reply(self):
        return bool(self.references)

    @property
    def parent_id(self):
        """
        Return the ID of the annotation that this annotation is a reply to.

        Return None if this annotation is not a reply.

        """
        if self.references:
            return self.references[-1]

    @property
    def thread_root_id(self):
        """
        Return the ID of the root annotation of this annotation's thread.

        Return the ID of the root annotation of the thread to which this
        annotation belongs. May be this annotation's own ID if it is the root
        annotation of its thread.

        """
        if self.references:
            return self.references[0]
        else:
            return self.id

    @property
    def authority(self):
        """
        Return the authority of the user and group this annotation belongs to.

        For example, returns "hypothes.is" for Hypothesis first-party
        annotations, or "elifesciences.org" for eLife third-party annotations.

        If this annotation doesn't have a userid (which is possible for
        annotations that haven't been saved to the DB yet) then return None.

        :raises ValueError: if the annotation's userid is invalid

        """
        if self.userid is None:
            return None
        return split_user(self.userid)["domain"]

    def __repr__(self):
        return "<Annotation %s>" % self.id


text:
declare namespace pc {

    /**
    * @name pc.Asset
    * @class An asset record of a file or data resource that can be loaded by the engine.
    * The asset contains three important fields:

    * file: contains the details of a file (filename, url) which contains the resource data, e.g. an image file for a texture asset

    * data: contains a JSON blob which contains either the resource data for the asset (e.g. material data) or additional data for the file (e.g. material mappings for a model)

    * resource: contains the final resource when it is loaded. (e.g. a {@link pc.StandardMaterial} or a {@link pc.Texture})

    *
    * See the {@link pc.AssetRegistry} for details on loading resources from assets.
    * @property {String} name The name of the asset
    * @property {Number} id The asset id
    * @property {String} type The type of the asset. One of ["animation", "audio", "binary", "cubemap", "css", "font", "json", "html", "material", "model", "script", "shader", "text", "texture"]
    * @property {pc.Tags} tags Interface for tagging. Allows to find assets by tags using {@link pc.AssetRegistry#findByTag} method.
    * @property {Object} file The file details or null if no file
    * @property {String} [file.url] The URL of the resource file that contains the asset data
    * @property {String} [file.filename] The filename of the resource file
    * @property {Number} [file.size] The size of the resource file
    * @property {String} [file.hash] The MD5 hash of the resource file data and the Asset data field
    * @property {Object} data JSON data that contains either the complete resource data (e.g. in the case of a material) or additional data (e.g. in the case of a model it contains mappings from mesh to material)
    * @property {Object} resource A reference to the resource when the asset is loaded. e.g. a {@link pc.Texture} or a {@link pc.Model}
    * @property {Array} resources A reference to the resources of the asset when it's loaded. An asset can hold more runtime resources than one e.g. cubemaps
    * @property {Boolean} preload If true the asset will be loaded during the preload phase of application set up.
    * @property {Boolean} loaded True if the resource is loaded. e.g. if asset.resource is not null
    * @property {pc.AssetRegistry} registry The asset registry that this Asset belongs to
    * @description Create a new Asset record. Generally, Assets are created in the loading process and you won't need to create them by hand.
    * @param {String} name A non-unique but human-readable name which can be later used to retrieve the asset.
    * @param {String} type Type of asset. One of ["animation", "audio", "binary", "cubemap", "css", "font", "json", "html", "material", "model", "script", "shader", "text", "texture"]
    * @param {Object} file Details about the file the asset is made from. At the least must contain the 'url' field. For assets that don't contain file data use null.
    * @example
    * var file = {
    *   filename: "filename.txt",
    *   url: "/example/filename.txt",
    * }
    * @param {Object} [data] JSON object with additional data about the asset (e.g. for texture and model assets) or contains the asset data itself (e.g. in the case of materials)
    * @example
    * var asset = new pc.Asset("a texture", "texture", {
    *     url: "http://example.com/my/assets/here/texture.png"
    * });
    */
    class Asset {
        constructor(name: string, type: string, file: { url: string, filename?: string, size?: number, hash?: string } | null, data?: {})

        name: string;
        id: number;
        type: string;
        tags: pc.Tags;
        file: { url: string, filename?: string, size?: number, hash?: string } | null;
        data: {};
        resource: pc.Texture | pc.Model | pc.Material;
        resources: Array<pc.Texture | pc.Model | pc.Material>;
        preload: boolean;
        loaded: boolean;
        registry: pc.AssetRegistry;

        /**
        * @name pc.Asset#getFileUrl
        * @function
        * @description Return the URL required to fetch the file for this asset.
        * @returns {String} The URL
        * @example
        * var assets = app.assets.find("My Image", "texture");
        * var img = "<img src='" + assets[0].getFileUrl() + "'>";
        */
        getFileUrl(): string;

        /**
        * @function
        * @name pc.Asset#ready
        * @description Take a callback which is called as soon as the asset is loaded. If the asset is already loaded the callback is called straight away
        * @param {Function} callback The function called when the asset is ready. Passed the (asset) arguments
        * @example
        * var asset = app.assets.find("My Asset");
        * asset.ready(function (asset) {
        *   // asset loaded
        * });
        * app.assets.load(asset);
        */
        ready(callback: (...args: any[]) => {}, scope: any): void;

        /**
        * @function
        * @name pc.Asset#unload
        * @description Destroys the associated resource and marks asset as unloaded.
        * @example
        * var asset = app.assets.find("My Asset");
        * asset.unload();
        * // asset.resource is null
        */
        unload(): void;

        // Events

        /**
         * @function
         * @name pc.Asset#on
         * @description Attach an event handler to an event
         * @param {String} name Name of the event to bind the callback to
         * @param {Function} callback Function that is called when event is fired. Note the callback is limited to 8 arguments.
         * @param {Object} [scope] Object to use as 'this' when the event is fired, defaults to current this
         * @example
         * obj.on('test', function (a, b) {
         *     console.log(a + b);
         * });
         * obj.fire('test', 1, 2); // prints 3 to the console
         */
        on(name: string, callback: (...args: any[]) => void, scope: any): any;

        /**
         * @function
         * @name pc.Asset#off
         * @description Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event,
         * if scope is not provided then all events with the callback will be unbound.
         * @param {String} [name] Name of the event to unbind
         * @param {Function} [callback] Function to be unbound
         * @param {Object} [scope] Scope that was used as the this when the event is fired
         * @example
         * var handler = function () {
         * };
         * obj.on('test', handler);
         *
         * obj.off(); // Removes all events
         * obj.off('test'); // Removes all events called 'test'
         * obj.off('test', handler); // Removes all handler functions, called 'test'
         * obj.off('test', handler, this); // Removes all hander functions, called 'test' with scope this
         */
        off(name: string, callback: (...args: any[]) => void, scope: any): any;

        /**
         * @function
         * @name pc.Asset#fire
         * @description Fire an event, all additional arguments are passed on to the event listener
         * @param {Object} name Name of event to fire
         * @param {*} [...] Arguments that are passed to the event handler
         * @example
         * obj.fire('test', 'This is the message');
         */
        fire(name: string, arg1: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): any;

        /**
         * @function
         * @name pc.Asset#once
         * @description Attach an event handler to an event. This handler will be removed after being fired once.
         * @param {String} name Name of the event to bind the callback to
         * @param {Function} callback Function that is called when event is fired. Note the callback is limited to 8 arguments.
         * @param {Object} [scope] Object to use as 'this' when the event is fired, defaults to current this
         * @example
         * obj.once('test', function (a, b) {
         *     console.log(a + b);
         * });
         * obj.fire('test', 1, 2); // prints 3 to the console
         * obj.fire('test', 1, 2); // not going to get handled
         */
        once(name: string, callback: (...args: any[]) => void, scope: any): any;

        /**
        * @function
        * @name pc.Asset#hasEvent
        * @description Test if there are any handlers bound to an event name
        * @param {String} name The name of the event to test
        * @example
        * obj.on('test', function () { }); // bind an event to 'test'
        * obj.hasEvent('test'); // returns true
        */
        hasEvent(name: string): boolean;
    }
}


text:
namespace BehaviorTree
{
	using namespace Microsoft::VisualStudio::CppUnitTestFramework;

	TEST_CLASS(ActionCheckVariableExistsTests)
	{
	public:
		TEST_METHOD(TestActionCheckVariableExistsFailsOnEmptyBlackboard)
		{
			std::shared_ptr<TreeFactory> treeFactory = TreeFactory::create(TextAccess::createFromString(
				"<BEHAVIOR_SPECIFICATION>"
				"	<MODULES>"
				"		<MODULE name=\"core\" />"
				"		<MODULE name=\"blackboard\" />"
				"	</MODULES>"
				"	<TREES>"
				"		<ROOT name=\"main\">"
				"			<CHECK_VARIABLE_EXISTS name=\"variable\"/>"
				"		</ROOT>"
				"	</TREES>"
				"</BEHAVIOR_SPECIFICATION>"
			));

			std::shared_ptr<Blackboard> blackboard = std::make_shared<Blackboard>();
			Task::StatusType status = treeFactory->createBehaviorTree("main")->evaluate(blackboard);

			Assert::AreEqual(Task::STATUS_FAILURE, status);
		}

		TEST_METHOD(TestActionCheckVariableExistsFailsOnBlackboardWithDifferentVariable)
		{
			std::shared_ptr<TreeFactory> treeFactory = TreeFactory::create(TextAccess::createFromString(
				"<BEHAVIOR_SPECIFICATION>"
				"	<MODULES>"
				"		<MODULE name=\"core\" />"
				"		<MODULE name=\"blackboard\" />"
				"	</MODULES>"
				"	<TREES>"
				"		<ROOT name=\"main\">"
				"			<CHECK_VARIABLE_EXISTS name=\"variable\"/>"
				"		</ROOT>"
				"	</TREES>"
				"</BEHAVIOR_SPECIFICATION>"
			));

			std::shared_ptr<Blackboard> blackboard = std::make_shared<Blackboard>();
			blackboard->set("different_variable", 42);
			Task::StatusType status = treeFactory->createBehaviorTree("main")->evaluate(blackboard);

			Assert::AreEqual(Task::STATUS_FAILURE, status);
		}

		TEST_METHOD(TestActionCheckVariableExistsSucceedsOnBlackboardWithMatchingVariable)
		{
			std::shared_ptr<TreeFactory> treeFactory = TreeFactory::create(TextAccess::createFromString(
				"<BEHAVIOR_SPECIFICATION>"
				"	<MODULES>"
				"		<MODULE name=\"core\" />"
				"		<MODULE name=\"blackboard\" />"
				"	</MODULES>"
				"	<TREES>"
				"		<ROOT name=\"main\">"
				"			<CHECK_VARIABLE_EXISTS name=\"variable\"/>"
				"		</ROOT>"
				"	</TREES>"
				"</BEHAVIOR_SPECIFICATION>"
			));

			std::shared_ptr<Blackboard> blackboard = std::make_shared<Blackboard>();
			blackboard->set("variable", 42);
			Task::StatusType status = treeFactory->createBehaviorTree("main")->evaluate(blackboard);

			Assert::AreEqual(Task::STATUS_SUCCESS, status);
		}
	};
}


text:
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

from platform import system

from setuptools import find_packages, setup

from platformio import (__author__, __description__, __email__, __license__,
                        __title__, __url__, __version__)

setup(
    name=__title__,
    version=__version__,
    description=__description__,
    long_description=open("README.rst").read(),
    author=__author__,
    author_email=__email__,
    url=__url__,
    license=__license__,
    install_requires=[
        "bottle",
        "click>=3.0",
        "pyserial",
        "requests>=2.4.0",
        # "SCons"
    ] + (["colorama"] if system() == "Windows" else []),
    packages=find_packages(),
    package_data={
        "platformio": [
            "projectconftpl.ini",
            "boards/*.json",
            "ide/tpls/*/.*.tpl",
            "ide/tpls/*/*.tpl"
        ]
    },
    entry_points={
        "console_scripts": [
            "platformio = platformio.__main__:main"
        ]
    },
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: C",
        "Programming Language :: Python",
        "Topic :: Software Development",
        "Topic :: Software Development :: Build Tools",
        "Topic :: Software Development :: Compilers"
    ],
    keywords=(
        "builder library manager embedded development ide continuous "
        "integration atmel avr sam espressif esp freescale kinetis nordic "
        "nrf51 nxp lpc silicon labs efm32 st stm32 ti msp430 tiva teensy "
        "arduino mbed libopencm3"
    )
)


text:
_A little about how to play the jsonDoc way_

## introduction

_jsonDoc_ was created to offer a performant way to operate on [JSON](https://json.org/) data with concise [Delphi](https://www.embarcadero.com/products/delphi) syntax, based on variants and interfaces.

This document provides a set of typical use-cases when handing JSON document structure, and ways to handle them with _jsonDoc_, leveraging the concise syntax, and the tricks _jsonDoc_ got up its sleeve to re-use allocated memory when enumerating series of similar documents.

## create documents

Use the `JSON` function to create a document. You can pass an array of variants, with a sequence of keys and values.

    var
      d:IJSONDocument;
    begin
      d:=JSON;
      //d.ToString gives '{}'
      d:=JSON(['hello','world']);
      //d.ToString gives '{"hello":"world"}'

A variant of VarType varUnknown can also contain any interface reference including `IJSONDocument`, so you could write:

      d:=JSON(['parent',JSON(['child',true])]);
      //d.ToString gives '{"parent":{"child":true}}'

but if it's a fixed structure the code needs to build every time, you can suffix key names with `{` to start an embedded document and use key name `}` to close it:

      d:=JSON(['a{','b{','c',1,'}}','d',2]);
      //d.ToString gives '{"a":{"b":{"c":1}},"d":2}'

If you have a string value holding JSON data, use `Parse` to load the data into an `IJSONDocument` instance:

      d:=JSON.Parse(freshJsonData);
      //or use the function JSON(Variant) overload as shorthand:
      d:=JSON(freshJsonData);

You can call `Parse` on an existing instance, but you need to call `Clear` first to remove the values that were already there (unless that's exactly what you need):

      d.Clear;
      d.Parse(freshJSONData);

`Clear` doesn't deallocate the memory used by keys and values, so when the new document, even only partially, has the same set of keys (including in embedded documents!), it will perform better than creating a fully new instance for every iteration.

## retrieve values

Use `IJSONDocument`'s default indexed property to make it look like you're using an array:

      if d["x"]=1 then
        d["y"]:='hello';

If you expect a certain key to have an embedded document, use the `JSON` function:

    var
      d1,d2:IJSONDocument;
    begin
      d1:=JSON(['a{','b',1,'}']);
      d2:=JSON(d1['a']);
      //d2.ToString='{"b":1}'

If you want to list the keys and values of a document, use `JSONEnum`:

    var
      d:IJSONDocument;
      e:IJSONEnumerator;
    begin
      d:=JSON.Parse(freshJSONData);
      e:=JSONEnum(d);
      while e.Next do
       begin
        displayInfo(e.Key,e.Value);
       end;

If you want to convert the content to something that also supports Variants, use `ToVarArray` to store keys and values in a 2-dimensional array:

    var
      d:IJSONDocument;
      v:Variant;
    begin
      d:=JSON(['x',1,'y',2,'z',3]);
      v:=d.ToVarArray;
      //v[0,0]='x' v[0,1]=1
      //v[1,0]='y' v[1,1]=2
      //v[2,0]='z' v[2,1]=3

## arrays

Variants can have a VarType combined with varArray, jsonDoc tries to support that as seamlessly as possible:

    uses jsonDoc, Variants;
    var
      d:IJSONDocument;
    begin
      d:=JSON(['x':VarArrayOf([1,2,3])]);
      //d.ToString='{"x",[1,2,3]}'
      d:=JSON(['x',VarArrayOf([JSON(['a',1],JSON(['b',1]))])]);
      //d.ToString='{'x',[{"a":1},{"b":2}]}'
      JSON(d['x'][1])['c']:=3;
      //d.ToString='{'x',[{"a":1},{"b":2,"c":3}]}'

Function `JSONEnum` also supports variant arrays:

    var
      v:Variant;
      e:IJSONEnumerator;
    begin
      v:=VarArrayOf(['hello','world']);
      e:=JSONEnum(v);
      while e.Next do
       begin
        displayInfo(e.Key,e.Value);
       end;
      //calls displayInfo('0','hello'); displayInfo('1','world');

By default `VarArrayOf` uses a SafeArray internally for storage, which performs deep copies when assigning the variant values. This costs both time (because of the locking) and memory (because of the duplicates created). Avoid this by using `IJSONArray`. Use the `ja` function to create instances:

      d:=JSON(['x',ja([1,2,3])]);
      //d.ToString='{"x":[1,2,3]}'

A minor inconvenience is that the array indexing into variants no longer works, but that's what the other overload of function `ja` is for:

      d:=JSON(['x',ja([1,2,3])]);
      ja(d['x'])[1]:=99;
      //d.ToString='{"x":[1,99,3]}'

By setting `JSON_UseIJSONArray:=true;` (or compiling with define `JSONDOC_DEFAULT_USE_IJSONARRAY`) you can make _jsonDoc_ use `IJSONArray` instances.

      JSON_UseIJSONArray:=true;
      d:=JSON.Parse('{"x":[1,2,3]}');
      ja(d['x'])[1]:=99;
      //d.ToString='{"x":[1,99,3]}'

And function `JSONEnum` supports `IJSONArray` just fine:

    var
      d:IJSONDocument;
      e:IJSONEnumerator;
    begin
      JSON_UseIJSONArray:=true;
      d:=JSON.Parse('{"x":[100,200]}');
      e:=JSONEnum(d['x']);
      while e.Next do
       begin
        displayInfo(e.Key,e.Value);
       end;
      //calls displayInfo('0',100); displayInfo('1',200);

Both ways of handing arrays can be used together:

    var
      d:IJSONDocument;
      a1,a2:IJSONArray;
    begin
      d:=JSON(['x',VarArrayOf([1,2]),'y',ja([3,4])]);
      a1:=ja(d['x']);  // an IJSONArray instance that works
                       // on the variant array is created for you
      a2:=ja(d['y']);
      a1[1]:=3;
      a2[1]:=7;
      //d.ToString='{"x":[1,3],"y":[3,7]}'

## arrays of documents

If you know on beforehand, a document will contain a (potentially large) array of embedded documents, and you'll be processing them one by one, it makes little sense to have the parser allocate memory for all of the separate documents. In most practical applications, these documents will typically have about the same set of keys but with different values, so it makes extra sense to re-use a single `IJSONDocument` instance and load the subsequent documents into it.

In cases like this, pre-load the parent document with an `IJSONDocArray` instance you get from the `JSONDocArray` function:

    var
      d,d1:IJSONDocument;
      da:IJSONDocArray;
      i:integer;
    begin
      da:=JSONDocArray;
      d:=JSON(['items',da]);
      d.Parse(bigJsonBlobFromNetwork);
      d1:=JSON;
      for i:=0 to da.Count-1 do
       begin
        da.LoadItem(i,d1);
        displayInfo(d1['id'],d1['name']);
       end;

Also when constructing an array of documents, use an `IJSONDocArray` instance and re-use a single `IJSONDocument` instance to fill the array:

    var
      d,d1:IJSONDocument;
      da:IJSONDocArray;
      s1,s2:string;
    begin
      da:=JSONDocArray;
      d1:=JSON;
      while readItem(s1,s2) do //or any way you prefer to get your data
       begin
        d1['id']:=s1;
        d1['name']:=s2;
        da.Add(d1);
       end;
      d:=JSON(['x',da]);
      //d.ToString starts with '{"x":[{"id":...

## conditional defines

`JSONDOC_JSON_STRICT`
to disallow missing quotes around key names

`JSONDOC_JSON_LOOSE`
to allow missing colons and comma's

`JSONDOC_JSON_PASCAL_STRINGS`
to allow pascal-style strings in JSON data

`JSONDOC_STOREINDENTING`
to make `ToString` write indentation EOL's and tabs

`JSONDOC_THREADSAFE`
to make `IJSONDocument` instances thread-safe

`JSONDOC_DEFAULT_USE_IJSONARRAY`
to set `JSON_UseIJSONArray` to true by default


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mysqlflexibleserver.fluent.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;

/** The properties of a server backup. */
@Fluent
public final class ServerBackupProperties {
    /*
     * Backup type.
     */
    @JsonProperty(value = "backupType")
    private String backupType;

    /*
     * Backup completed time (ISO8601 format).
     */
    @JsonProperty(value = "completedTime")
    private OffsetDateTime completedTime;

    /*
     * Backup source
     */
    @JsonProperty(value = "source")
    private String source;

    /**
     * Get the backupType property: Backup type.
     *
     * @return the backupType value.
     */
    public String backupType() {
        return this.backupType;
    }

    /**
     * Set the backupType property: Backup type.
     *
     * @param backupType the backupType value to set.
     * @return the ServerBackupProperties object itself.
     */
    public ServerBackupProperties withBackupType(String backupType) {
        this.backupType = backupType;
        return this;
    }

    /**
     * Get the completedTime property: Backup completed time (ISO8601 format).
     *
     * @return the completedTime value.
     */
    public OffsetDateTime completedTime() {
        return this.completedTime;
    }

    /**
     * Set the completedTime property: Backup completed time (ISO8601 format).
     *
     * @param completedTime the completedTime value to set.
     * @return the ServerBackupProperties object itself.
     */
    public ServerBackupProperties withCompletedTime(OffsetDateTime completedTime) {
        this.completedTime = completedTime;
        return this;
    }

    /**
     * Get the source property: Backup source.
     *
     * @return the source value.
     */
    public String source() {
        return this.source;
    }

    /**
     * Set the source property: Backup source.
     *
     * @param source the source value to set.
     * @return the ServerBackupProperties object itself.
     */
    public ServerBackupProperties withSource(String source) {
        this.source = source;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}