text:
using Google.Cloud.ClientTesting;
using Google.Rpc;
using Google.Type;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;

namespace Google.Cloud.Vision.V1.Snippets
{
    [SnippetOutputCollector]
    public class ImageAnnotatorClientSnippets
    {
        [Fact]
        public void Annotate()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: Annotate
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            AnnotateImageRequest request = new AnnotateImageRequest
            {
                Image = image,
                Features =
                {
                    new Feature { Type = Feature.Types.Type.FaceDetection },
                    // By default, no limits are put on the number of results per annotation.
                    // Use the MaxResults property to specify a limit.
                    new Feature { Type = Feature.Types.Type.LandmarkDetection, MaxResults = 5 },
                }
            };
            AnnotateImageResponse response = client.Annotate(request);
            Console.WriteLine("Faces:");
            foreach (FaceAnnotation face in response.FaceAnnotations)
            {
                string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine($"  Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
            }
            Console.WriteLine("Landmarks:");
            foreach (EntityAnnotation landmark in response.LandmarkAnnotations)
            {
                Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}");
            }
            if (response.Error != null)
            {
                Console.WriteLine($"Error detected: {response.Error}");
            }
            // End snippet

            Assert.Equal(3, response.FaceAnnotations.Count);
            Assert.Equal(0, response.LandmarkAnnotations.Count);
        }

        // See-also: Annotate(*, *)
        // Member: AnnotateAsync(*, CallSettings)
        // Member: AnnotateAsync(*, CancellationToken)
        // See [Annotate](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void BatchAnnotateImages()
        {
            Image image1 = LoadResourceImage("SchmidtBrinPage.jpg");
            Image image2 = LoadResourceImage("Chrome.png");
            // Sample: BatchAnnotateImages
            // Additional: BatchAnnotateImages(IEnumerable<AnnotateImageRequest>,*)
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            // Perform face recognition on one image, and logo recognition on another.
            AnnotateImageRequest request1 = new AnnotateImageRequest
            {
                Image = image1,
                Features = { new Feature { Type = Feature.Types.Type.FaceDetection } }
            };
            AnnotateImageRequest request2 = new AnnotateImageRequest
            {
                Image = image2,
                Features = { new Feature { Type = Feature.Types.Type.LogoDetection } }
            };

            BatchAnnotateImagesResponse response = client.BatchAnnotateImages(new[] { request1, request2 });
            Console.WriteLine("Faces in image 1:");
            foreach (FaceAnnotation face in response.Responses[0].FaceAnnotations)
            {
                string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine($"  Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
            }
            Console.WriteLine("Logos in image 2:");
            foreach (EntityAnnotation logo in response.Responses[1].LogoAnnotations)
            {
                Console.WriteLine($"Description: {logo.Description}");
            }
            foreach (Status error in response.Responses.Select(r => r.Error))
            {
                Console.WriteLine($"Error detected: error");
            }
            // End sample

            Assert.Equal(3, response.Responses[0].FaceAnnotations.Count);
            Assert.Equal(1, response.Responses[1].LogoAnnotations.Count);
        }

        [Fact]
        public void DetectFaces()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: DetectFaces
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<FaceAnnotation> result = client.DetectFaces(image);
            foreach (FaceAnnotation face in result)
            {
                string poly = string.Join(" - ", face.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine($"Confidence: {(int)(face.DetectionConfidence * 100)}%; BoundingPoly: {poly}");
            }
            // End snippet

            Assert.Equal(3, result.Count);

            // Check the bounding boxes of the faces, with a tolerance of 5px on each edge.
            var rectangles = result.Select(x => Rectangle.FromBoundingPoly(x.BoundingPoly)).ToList();
            Assert.True(rectangles.All(x => x != null));
            rectangles = rectangles.OrderBy(r => r.Left).ToList();
            Assert.True(rectangles[0].Equals(new Rectangle(196, 64, 293, 177), 5.0));
            Assert.True(rectangles[1].Equals(new Rectangle(721, 162, 846, 308), 5.0));
            Assert.True(rectangles[2].Equals(new Rectangle(1009, 113, 1149, 276), 5.0));
        }

        // See-also: DetectFaces(*, *, *, *)
        // Member: DetectFacesAsync(*, *, *, *)
        // See [DetectFaces](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectLandmarks()
        {
            Image image = LoadResourceImage("SydneyOperaHouse.jpg");
            // Snippet: DetectLandmarks
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<EntityAnnotation> result = client.DetectLandmarks(image);
            foreach (EntityAnnotation landmark in result)
            {
                Console.WriteLine($"Score: {(int)(landmark.Score * 100)}%; Description: {landmark.Description}");
            }
            // End snippet

            Assert.Equal(2, result.Count);
            var descriptions = result.Select(r => r.Description).OrderBy(d => d).ToList();
            Assert.Equal(new[] { "Sydney Harbour Bridge", "Sydney Opera House" }, descriptions);
        }

        // See-also: DetectLandmarks(*, *, *, *)
        // Member: DetectLandmarksAsync(*, *, *, *)
        // See [DetectLandmarks](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectImageProperties()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: DetectImageProperties
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            ImageProperties properties = client.DetectImageProperties(image);
            ColorInfo dominantColor = properties.DominantColors.Colors.OrderByDescending(c => c.PixelFraction).First();
            Console.WriteLine($"Dominant color in image: {dominantColor}");
            // End snippet

            Assert.Equal(0.18, dominantColor.PixelFraction, 2);
            Assert.Equal(new Color { Red = 16, Green = 13, Blue = 8 }, dominantColor.Color);
        }

        // See-also: DetectImageProperties(*, *, *)
        // Member: DetectImagePropertiesAsync(*, *, *)
        // See [DetectImageProperties](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectLabels()
        {
            Image image = LoadResourceImage("Gladiolos.jpg");
            // Snippet: DetectLabels
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<EntityAnnotation> labels = client.DetectLabels(image);
            foreach (EntityAnnotation label in labels)
            {
                Console.WriteLine($"Score: {(int)(label.Score * 100)}%; Description: {label.Description}");
            }
            // End snippet

            // Not exhaustive, but let's check certain basic labels.
            var descriptions = labels.Select(l => l.Description).ToList();
            Assert.Contains("flower", descriptions);
            Assert.Contains("plant", descriptions);
            Assert.Contains("vase", descriptions);
        }

        // See-also: DetectLabels(*, *, *, *)
        // Member: DetectLabelsAsync(*, *, *, *)
        // See [DetectLabels](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectText()
        {
            Image image = LoadResourceImage("Ellesborough.png");
            // Snippet: DetectText
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<EntityAnnotation> textAnnotations = client.DetectText(image);
            foreach (EntityAnnotation text in textAnnotations)
            {
                Console.WriteLine($"Description: {text.Description}");
            }
            // End snippet

            var descriptions = textAnnotations.Select(t => t.Description).ToList();
            Assert.Contains("Ellesborough", descriptions);
        }

        // See-also: DetectText(*, *, *, *)
        // Member: DetectTextAsync(*, *, *, *)
        // See [DetectText](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectSafeSearch()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: DetectSafeSearch
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            SafeSearchAnnotation annotation = client.DetectSafeSearch(image);
            // Each category is classified as Very Unlikely, Unlikely, Possible, Likely or Very Likely.
            Console.WriteLine($"Adult? {annotation.Adult}");
            Console.WriteLine($"Spoof? {annotation.Spoof}");
            Console.WriteLine($"Violence? {annotation.Violence}");
            Console.WriteLine($"Medical? {annotation.Medical}");
            // End snippet
            Assert.InRange(annotation.Adult, Likelihood.VeryUnlikely, Likelihood.Unlikely);
            Assert.InRange(annotation.Spoof, Likelihood.VeryUnlikely, Likelihood.Unlikely);
            Assert.InRange(annotation.Violence, Likelihood.VeryUnlikely, Likelihood.Unlikely);
            Assert.InRange(annotation.Medical, Likelihood.VeryUnlikely, Likelihood.Unlikely);
        }

        // See-also: DetectSafeSearch(*, *, *)
        // Member: DetectSafeSearchAsync(*, *, *)
        // See [DetectSafeSearch](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectLogos()
        {
            Image image = LoadResourceImage("Chrome.png");
            // Snippet: DetectLogos
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image);
            foreach (EntityAnnotation logo in logos)
            {
                Console.WriteLine($"Description: {logo.Description}");
            }
            // End snippet
            Assert.Equal(1, logos.Count);
            Assert.Equal("Google Chrome", logos[0].Description);
        }

        // See-also: DetectLogos(*, *, *, *)
        // Member: DetectLogosAsync(*, *, *, *)
        // See [DetectLogos](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectCropHints()
        {
            Image image = LoadResourceImage("Gladiolos.jpg");
            // Snippet: DetectCropHints
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            CropHintsAnnotation cropHints = client.DetectCropHints(image);
            foreach (CropHint hint in cropHints.CropHints)
            {
                Console.WriteLine("Crop hint:");
                string poly = string.Join(" - ", hint.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine($"  Poly: {poly}");
                Console.WriteLine($"  Confidence: {hint.Confidence}");
                Console.WriteLine($"  Importance fraction: {hint.ImportanceFraction}");
            }
            // End snippet
            Assert.Equal(1, cropHints.CropHints.Count);
        }

        // See-also: DetectCropHints(*, *, *)
        // Member: DetectCropHintsAsync(*, *, *)
        // See [DetectCropHints](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectDocumentText()
        {
            Image image = LoadResourceImage("DocumentText.png");
            // Snippet: DetectDocumentText
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            TextAnnotation text = client.DetectDocumentText(image);
            Console.WriteLine($"Text: {text.Text}");
            foreach (var page in text.Pages)
            {
                foreach (var block in page.Blocks)
                {
                    string box = string.Join(" - ", block.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
                    Console.WriteLine($"Block {block.BlockType} at {box}");
                    foreach (var paragraph in block.Paragraphs)
                    {
                        box = string.Join(" - ", paragraph.BoundingBox.Vertices.Select(v => $"({v.X}, {v.Y})"));
                        Console.WriteLine($"  Paragraph at {box}");
                        foreach (var word in paragraph.Words)
                        {
                            Console.WriteLine($"    Word: {string.Join("", word.Symbols.Select(s => s.Text))}");
                        }
                    }
                }
            }
            // End snippet
            var lines = text.Pages[0].Blocks
                .Select(b => b.Paragraphs[0].Words.Select(w => string.Join("", w.Symbols.Select(s => s.Text))))
                .ToList();
            Assert.Equal(new[] { "Sample", "text", "line", "1", }, lines[0]);
            Assert.Equal(new[] { "Text", "near", "the", "middle", }, lines[1]);
            Assert.Equal(new[] { "Text", "near", "bottom", "right", }, lines[2]);
        }

        // See-also: DetectDocumentText(*, *, *)
        // Member: DetectDocumentTextAsync(*, *, *)
        // See [DetectDocumentText](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectWebInformation()
        {
            Image image = LoadResourceImage("SchmidtBrinPage.jpg");
            // Snippet: DetectWebInformation
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            WebDetection webDetection = client.DetectWebInformation(image);
            foreach (WebDetection.Types.WebImage webImage in webDetection.FullMatchingImages)
            {
                Console.WriteLine($"Full image: {webImage.Url} ({webImage.Score})");
            }
            foreach (WebDetection.Types.WebImage webImage in webDetection.PartialMatchingImages)
            {
                Console.WriteLine($"Partial image: {webImage.Url} ({webImage.Score})");
            }
            foreach (WebDetection.Types.WebPage webPage in webDetection.PagesWithMatchingImages)
            {
                Console.WriteLine($"Page with matching image: {webPage.Url} ({webPage.Score})");
            }
            foreach (WebDetection.Types.WebEntity entity in webDetection.WebEntities)
            {
                Console.WriteLine($"Web entity: {entity.EntityId} / {entity.Description} ({entity.Score})");
            }
            // End snippet
        }

        // See-also: DetectWebInformation(*, *, *)
        // Member: DetectWebInformationAsync(*, *, *)
        // See [DetectWebInformation](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void DetectLocalizedObjects()
        {
            Image image = Image.FromUri("https://cloud.google.com/vision/docs/images/bicycle_example.png");
            // Snippet: DetectLocalizedObjects
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            IReadOnlyList<LocalizedObjectAnnotation> annotations = client.DetectLocalizedObjects(image);
            foreach (LocalizedObjectAnnotation annotation in annotations)
            {
                string poly = string.Join(" - ", annotation.BoundingPoly.Vertices.Select(v => $"({v.X}, {v.Y})"));
                Console.WriteLine(
                    $"Name: {annotation.Name}; ID: {annotation.Mid}; Score: {annotation.Score}; Bounding poly: {poly}");
            }
            // End snippet

            // TODO: Add assertions about the annotations.
        }

        // See-also: DetectLocalizedObjects(*, *, *, *)
        // Member: DetectLocalizedObjectsAsync(*, *, *, *)
        // See [DetectLocalizedObjects](ref) for a synchronous example.
        // End see-also

        [Fact]
        public void ErrorHandling_SingleImage()
        {
            // Sample: ErrorHandling_SingleImage
            // We create a request which passes simple validation, but isn't a valid image.
            Image image = Image.FromBytes(new byte[10]);
            ImageAnnotatorClient client = ImageAnnotatorClient.Create();
            try
            {
                IReadOnlyList<EntityAnnotation> logos = client.DetectLogos(image);
                // Normally use logos here...
            }
            catch (AnnotateImageException e)
            {
                AnnotateImageResponse response = e.Response;
                Console.WriteLine(response.Error);
            }
            // End sample
        }

        private static Image LoadResourceImage(string name)
        {
            var type = typeof(ImageAnnotatorClientSnippets);
            using (var stream = type.GetTypeInfo().Assembly.GetManifestResourceStream($"{type.Namespace}.{name}"))
            {
                return Image.FromStream(stream);
            }
        }
    }
}


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.network.generated;

import com.azure.core.util.Context;

/** Samples for NetworkWatchers List. */
public final class NetworkWatchersListSamples {
    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/NetworkWatcherListAll.json
     */
    /**
     * Sample code: List all network watchers.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void listAllNetworkWatchers(com.azure.resourcemanager.AzureResourceManager azure) {
        azure.networks().manager().serviceClient().getNetworkWatchers().list(Context.NONE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Gerado por template generation
 * Diretiva de overwrite atual:
 * TemplateName:
 **/
package br.com.dlp.jazzqa.produto;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.dlp.framework.business.IBusiness;
import br.com.dlp.framework.jsf.AbstractJSFBeanImpl;

/**
 * Incluir arquivo com comentários
 *
 * Implementação de Bean JSF para o componente ProdutoVO
 *
 **/
@Component
public class ProdutoJSFBean extends AbstractJSFBeanImpl<ProdutoVO> {

	private static final long serialVersionUID = 2195241915100521959L;

	@Autowired
	private ProdutoBusiness produtoBusiness;

	/**
	 * Replica das propriedades pesquisaveis. Atributos para composicao de formulario de pesquisa
	 */
	private Date dtInclusaoFrom;
 	private Date dtInclusaoTo;
 	private String obs;
 	private String nome;
 	private String dsAreaProduto;

	/**
	 * Pesquisa lista de ProdutoVO e disponibiliza resultados em produtoVOs
	 */
	public String actionPesquisar(){

		List<ProdutoVO> resultados = produtoBusiness.findProdutoVO(dtInclusaoFrom, dtInclusaoTo, obs, nome, dsAreaProduto);
		setResultados(resultados);

		return "exibePesquisa";
	}

	/**
	 * Accessor Method
 	 * @return dtInclusaoFrom
 	 */
	public Date getDtInclusaoFrom(){
		return this.dtInclusaoFrom;
	}

 	/**
	 * Accessor Method
 	 * @return dtInclusaoTo
 	 */
	public Date getDtInclusaoTo(){
		return this.dtInclusaoTo;
	}

 	/**
	 * Accessor Method
 	 * @return obs
 	 */
	public String getObs(){
		return this.obs;
	}

 	/**
	 * Accessor Method
 	 * @return nome
 	 */
	public String getNome(){
		return this.nome;
	}

 	/**
	 * Accessor Method
 	 * @return dsAreaProduto
 	 */
	public String getDsAreaProduto(){
		return this.dsAreaProduto;
	}

	/**
	 * Mutator Method
 	 * @param dtInclusaoFrom
 	 */
	public void setDtInclusaoFrom(Date dtInclusaoFrom){
		this.dtInclusaoFrom = dtInclusaoFrom;
	}

 	/**
	 * Mutator Method
 	 * @param dtInclusaoTo
 	 */
	public void setDtInclusaoTo(Date dtInclusaoTo){
		this.dtInclusaoTo = dtInclusaoTo;
	}

 	/**
	 * Mutator Method
 	 * @param obs
 	 */
	public void setObs(String obs){
		this.obs = obs;
	}

 	/**
	 * Mutator Method
 	 * @param nome
 	 */
	public void setNome(String nome){
		this.nome = nome;
	}

 	/**
	 * Mutator Method
 	 * @param dsAreaProduto
 	 */
	public void setDsAreaProduto(String dsAreaProduto){
		this.dsAreaProduto = dsAreaProduto;
	}

	/* (non-Javadoc)
	 * @see br.com.dlp.framework.jsf.AbstractJSFBeanImpl#getBusiness()
	 */
	@Override
	protected IBusiness<ProdutoVO> getBusiness() {
		return this.produtoBusiness;
	}
}


text:
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Viktor Gal
 */

#include <shogun/preprocessor/RescaleFeatures.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(RescaleFeatures, apply_to_feature_matrix)
{
	index_t num_features = 3;
	index_t num_vectors = 10;
	SGVector<float64_t> min(num_features), range(num_features);
	SGVector<float64_t> v(num_features*num_vectors), ev;
	sg_rand->set_seed(12345);
	v.random(-1024, 1024);
	ev = v.clone();

	SGMatrix<float64_t> m(v.vector, num_features, num_vectors, false);
	SGMatrix<float64_t> em(ev.vector, num_features, num_vectors, false);
	CDenseFeatures<float64_t>* feats = new CDenseFeatures<float64_t>(m);
	CRescaleFeatures* rescaler = new CRescaleFeatures();
	rescaler->init(feats);

	/* find the min and range for each feature among all the vectors */
	for (index_t i = 0; i < num_features; i++)
	{
		SGVector<float64_t> t = em.get_row_vector(i);
		min[i] = CMath::min(t.vector, t.vlen);
		range[i] = CMath::max(t.vector, t.vlen) - min[i];
	}

	feats->add_preprocessor(rescaler);
	feats->apply_preprocessor();
	for (index_t i = 0; i < num_vectors; i++)
	{
		SGVector<float64_t> vec = feats->get_feature_vector(i);
		float64_t* v_orig = em.get_column_vector(i);
		for (index_t j = 0; j < num_features; j++) {
			float64_t e = (v_orig[j]-min[j])/range[j];
			EXPECT_DOUBLE_EQ(e, vec[j]);
		}
	}

	SG_UNREF(feats);
}


text:
/*
 *    Geotools2 - OpenSource mapping toolkit
 *    http://geotools.org
 *    (C) 2003, Geotools Project Managment Committee (PMC)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 */
package com.vividsolutions.jts.io.oracle;

import java.sql.SQLException;
import java.util.*;

import oracle.sql.*;

import com.vividsolutions.jts.algorithm.CGAlgorithms;
import com.vividsolutions.jts.geom.*;

/**
 * Creates a {@link Geometry} from an Oracle MDSYS.GEOMETRY object.
 *
 * A {@link GeometryFactory} may be provided, otherwise
 * a default one will be used.
 * The provided GeometryFactory will be used, with the exception of the SRID field.
 * This will be extracted from the Geometry.
 *

 * If a PrecisionModel is supplied it is the callers's responsibility
 * to ensure that it matches the precision of the incoming data.
 * If a lower precision for the data is required, a subsequent
 * process must be run on the data to reduce its precision.
 *
 * @version 9i
 * @author David Zwiers, Vivid Solutions.
 */
public class OraReader {
	private GeometryFactory geometryFactory;

	public static final int NULL_DIMENSION = -1;
	private int dimension = -1;

	/**
	 * Creates a new reader, with a default GeometryFactory.
	 *
	 * @see #OraReader(GeometryFactory)
	 */
	public OraReader() {
		this(new GeometryFactory());
	}

	/**
	 * Creates a new reader, with the supplied {@link GeometryFactory}.
	 * It is assumed that the supplied {@link PrecisionModel}
	 * matches the precision of the incoming data -
	 * coordinates are not made precise.
	 *
	 * @param gf
	 *            A non-null geometry factory for later use.
	 * @throw NullPointerException when the geometry factory is null.
	 */
	public OraReader(GeometryFactory gf) {
		if (gf == null)
			throw new NullPointerException("Geometry Factory may not be Null");
		this.geometryFactory = gf;
	}

	/**
	 * This method will attempt to create a JTS Geometry for the MDSYS.GEOMETRY
	 * provided. The Type of gemetry returned will depend on the input datum,
	 * where the Geometry type is specified within the STRUCT.
	 *
	 * @param struct The MDSYS.GEOMETRY Object to decode
	 * @return A JTS Geometry if one could be created, null otherwise
	 * @throws SQLException When a read error occured within the struct
	 */
	public Geometry read(STRUCT struct) throws SQLException {

		// Note Returning null for null Datum
		if (struct == null)
			return null;

		Datum data[] = struct.getOracleAttributes();
		int gType = asInteger(data[0], 0);
		int SRID = asInteger(data[1], Constants.SRID_NULL);
		double point[] = asDoubleArray((STRUCT) data[2], Double.NaN);
		int elemInfo[] = asIntArray((ARRAY) data[3], 0);
		double ordinates[] = asDoubleArray((ARRAY) data[4], Double.NaN);
		GeometryFactory gf = geometryFactory;
		if(geometryFactory.getSRID() != SRID){
			// clone it and use the geom's srid
			gf = new GeometryFactory(geometryFactory.getPrecisionModel(),SRID,geometryFactory.getCoordinateSequenceFactory());
		}

		return create(gf, gType, point, elemInfo, ordinates);
	}

	/**
     * Decode geometry from provided SDO encoded information.
     *
     *

     *
     * @param gf Used to construct returned Geometry
     * @param gType SDO_GTEMPLATE represents dimension, LRS, and geometry type
     * @param point
     * @param elemInfo
     * @param ordinates
     *
     * @return Geometry as encoded
     */
    private Geometry create(GeometryFactory gf, int gType,
        double[] point, int[] elemInfo, double[] ordinates) {

        int lrs = (gType%1000)/100;

        // find the dimension: represented by the smaller of the two dimensions
        int dim = 0;
        if(dimension != NULL_DIMENSION){
        	dim = dimension;
        }else{
        	dim = Math.min(gType/1000,gf.getCoordinateSequenceFactory().create(0,0).getDimension()) ;
        }

        if(dim<2){
        	throw new IllegalArgumentException("Dimension D:" + dim + " is not valid for JTS. " +
        			"Either specify a dimension or use Oracle Locator Version 9i or later");
        }

        // extract the geometry template type
        // this is represented as the rightmost two digits
        int geomTemplate = gType - (dim * 1000) - (lrs * 100);

        CoordinateSequence coords = null;

        if (lrs == 0 && geomTemplate == 1 && point != null && elemInfo == null) {
            // Single Point Type Optimization
            coords = coordinates(gf.getCoordinateSequenceFactory(), dim, lrs, geomTemplate, point);
            elemInfo = new int[] { 1, Constants.SDO_ETYPE.POINT, 1 };
        } else {
            coords = coordinates(gf.getCoordinateSequenceFactory(), dim, lrs, geomTemplate, ordinates);
        }

        switch (geomTemplate) {
        case Constants.SDO_GTEMPLATE.POINT:
            return createPoint(gf, dim, lrs, elemInfo, 0, coords);

        case Constants.SDO_GTEMPLATE.LINE:
            return createLine(gf, dim, lrs, elemInfo, 0, coords);

        case Constants.SDO_GTEMPLATE.POLYGON:
            return createPolygon(gf, dim, lrs, elemInfo, 0, coords);

        case Constants.SDO_GTEMPLATE.MULTIPOINT:
            return createMultiPoint(gf, dim, lrs, elemInfo, 0, coords);

        case Constants.SDO_GTEMPLATE.MULTILINE:
            return createMultiLine(gf, dim, lrs, elemInfo, 0, coords, -1);

        case Constants.SDO_GTEMPLATE.MULTIPOLYGON:
            return createMultiPolygon(gf, dim, lrs, elemInfo, 0, coords, -1);

        case Constants.SDO_GTEMPLATE.COLLECTION:
            return createCollection(gf, dim, lrs, elemInfo, 0, coords,-1);

        default:
            return null;
        }
    }

    /**
     * Construct CoordinateList as described by GTYPE.
     *
     * The number of ordinates per coordinate are taken to be lrs+dim, and the
     * number of ordinates should be a multiple of this value.

     * In the Special case of GTYPE 2001 and a three ordinates are interpreted
     * as a single Coordinate rather than an error.
     *
     * @param f CoordinateSequenceFactory used to encode ordiantes for JTS
     * @param ordinates
     *
     * @return protected
     *
     * @throws IllegalArgumentException
     */
    private CoordinateSequence coordinates(CoordinateSequenceFactory f,
        int dim, int lrs, int gtemplate, double[] ordinates) {
        if ((ordinates == null) || (ordinates.length == 0)) {
            return f.create(new Coordinate[0]);
        }

        //      POINT_TYPE Special Case
        //
        if ((dim == 2) && (lrs == 0) && (gtemplate == 01) && (ordinates.length == 3)) {
            return f.create(new Coordinate[] {
                    new Coordinate(ordinates[0], ordinates[1], ordinates[2]),
                });
        }

        int len = dim + lrs;

        if ((len == 0 && ordinates.length!=0 ) || (len != 0 && ((ordinates.length % len) != 0))){
            throw new IllegalArgumentException("Dimension D:" + dim + " and L:"
                + lrs + " denote Coordinates " + "of " + len
                + " ordinates. This cannot be resolved with"
                + "an ordinate array of length " + ordinates.length);
        }

        int length = (len == 0?0:ordinates.length / len);

        // we would have to ask for a dimension which represents all the requested
        // dimension and measures from a mask array in the future
        CoordinateSequence cs = f.create(length,dim);

        int actualDim = cs.getDimension();
        for(int i=0;i<length;i++){
        	int j=0;
        	// in the future change this condition to include ignored dimensions from mask array
        	for(;j<actualDim && j<dim;j++){
        		cs.setOrdinate(i,j,ordinates[i*len+j]);
        		// may not always want to inc. j when we have a mask array
        	}
        	// in the future change this condition to include ignored dimensions from mask array
        	for(int d = j;j<actualDim && (j-d)<lrs;j++){
        		cs.setOrdinate(i,j,ordinates[i*len+j]);
        		// may not always want to inc. j when we have a mask array
        	}
        }
        return cs;
    }

    /**
     * Create MultiGeometry as encoded by elemInfo.
     *
     * @param gf Used to construct MultiLineString
     * @param elemInfo Interpretation of coords
     * @param elemIndex Triplet in elemInfo to process as a Polygon
     * @param coords Coordinates to interpret using elemInfo
     * @param numGeom Number of triplets (or -1 for rest)
     *
     * @return GeometryCollection
     *
     * @throws IllegalArgumentException DWhen faced with an encoding error
     */
    private GeometryCollection createCollection(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords, int numGeom) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);

        int length = coords.size()*dim;

		if (!(sOffset <= length))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());

        int endTriplet = (numGeom != -1) ? elemIndex + numGeom : elemInfo.length / 3 + 1;

        List list = new LinkedList();
        int etype;
        int interpretation;
        Geometry geom;

        boolean cont = true;
        for (int i = elemIndex; cont && i < endTriplet; i++) {
            etype = eType(elemInfo, i);
            interpretation = interpretation(elemInfo, i);

            switch (etype) {
            case -1:
                cont = false; // We are the of the list - get out of here

            case Constants.SDO_ETYPE.POINT:

                if (interpretation == 1) {
                    geom = createPoint(gf, dim, lrs, elemInfo, i, coords);
                } else if (interpretation > 1) {
                    geom = createMultiPoint(gf, dim, lrs, elemInfo, i, coords);
                } else {
                    throw new IllegalArgumentException(
                        "ETYPE.POINT requires INTERPRETATION >= 1");
                }

                break;

            case Constants.SDO_ETYPE.LINE:
                geom = createLine(gf, dim, lrs, elemInfo, i, coords);

                break;

            case Constants.SDO_ETYPE.POLYGON:
            case Constants.SDO_ETYPE.POLYGON_EXTERIOR:
                geom = createPolygon(gf, dim, lrs, elemInfo, i, coords);
                i += ((Polygon) geom).getNumInteriorRing();

                break;

            case Constants.SDO_ETYPE.POLYGON_INTERIOR:
                throw new IllegalArgumentException(
                    "ETYPE 2003 (Polygon Interior) no expected in a GeometryCollection"
                    + "(2003 is used to represent polygon holes, in a 1003 polygon exterior)");

            default:
                throw new IllegalArgumentException("ETYPE " + etype
                    + " not representable as a JTS Geometry."
                    + "(Custom and Compound Straight and Curved Geometries not supported)");
            }

            list.add(geom);
        }

        GeometryCollection geoms = gf.createGeometryCollection((Geometry[]) list.toArray(new Geometry[list.size()]));

        return geoms;
    }

    /**
     * Create MultiPolygon as encoded by elemInfo.
     *
     *
     * @param gf Used to construct MultiLineString
     * @param elemInfo Interpretation of coords
     * @param elemIndex Triplet in elemInfo to process as a Polygon
     * @param coords Coordinates to interpret using elemInfo
     * @param numGeom Number of triplets (or -1 for rest)
     *
     * @return MultiPolygon
     */
    private MultiPolygon createMultiPolygon(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords, int numGeom){

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

        int length = coords.size()*dim;

		if (!(sOffset >= 1) || !(sOffset <= length))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());
		if(!(etype == Constants.SDO_ETYPE.POLYGON) && !(etype == Constants.SDO_ETYPE.POLYGON_EXTERIOR))
		    throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected POLYGON or POLYGON_EXTERIOR");
		if (interpretation != 1 && interpretation != 3){
			return null;
		}

        int endTriplet = (numGeom != -1) ? elemIndex + numGeom : (elemInfo.length / 3) + 1;

        List list = new LinkedList();
        boolean cont = true;

        for (int i = elemIndex; cont && i < endTriplet && (etype = eType(elemInfo, i)) != -1; i++) {
            if ((etype == Constants.SDO_ETYPE.POLYGON) || (etype == Constants.SDO_ETYPE.POLYGON_EXTERIOR)) {
                Polygon poly = createPolygon(gf, dim, lrs, elemInfo, i, coords);
                i += poly.getNumInteriorRing(); // skip interior rings
                list.add(poly);
            } else { // not a Polygon - get out here
            	cont = false;
            }
        }

        MultiPolygon polys = gf.createMultiPolygon((Polygon[]) list.toArray(new Polygon[list.size()]));

        return polys;
    }

    /**
     * Create MultiLineString as encoded by elemInfo.
     *
     *
     * @param gf Used to construct MultiLineString
     * @param elemInfo Interpretation of coords
     * @param elemIndex Triplet in elemInfo to process as a Polygon
     * @param coords Coordinates to interpret using elemInfo
     * @param numGeom Number of triplets (or -1 for rest)
     *
     * @return MultiLineString
     */
    private MultiLineString createMultiLine(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords, int numGeom) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

        int length = coords.size()*dim;

		if (!(sOffset >= 1) || !(sOffset <= length))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());
		if(!(etype == Constants.SDO_ETYPE.LINE))
		    throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected LINE");
		if (!(interpretation == 1)){
            // we cannot represent INTERPRETATION > 1
			return null;
		}

        int endTriplet = (numGeom != -1) ? (elemIndex + numGeom) : (elemInfo.length / 3);

        List list = new LinkedList();

        boolean cont = true;
        for (int i = elemIndex; cont && i < endTriplet && (etype = eType(elemInfo, i)) != -1 ;i++) {
            if (etype == Constants.SDO_ETYPE.LINE) {
                list.add(createLine(gf, dim, lrs, elemInfo, i, coords));
            } else { // not a LineString - get out of here
                cont = false;
            }
        }

        MultiLineString lines = gf.createMultiLineString((LineString[]) list.toArray(new LineString[list.size()]));

        return lines;
    }

    /**
     * Create MultiPoint as encoded by elemInfo.
     *
     *
     * @param gf Used to construct polygon
     * @param elemInfo Interpretation of coords
     * @param elemIndex Triplet in elemInfo to process as a Polygon
     * @param coords Coordinates to interpret using elemInfo
     *
     * @return MultiPoint
     */
    private MultiPoint createMultiPoint(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

		if (!(sOffset >= 1) || !(sOffset <= coords.size()))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());
		if(!(etype == Constants.SDO_ETYPE.POINT))
		    throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected POINT");
		if (!(interpretation > 1)){
			return null;
		}

        int len = dim + lrs;

        int start = (sOffset - 1) / len;
        int end = start + interpretation;

        MultiPoint points = gf.createMultiPoint(subList(gf.getCoordinateSequenceFactory(), coords, start, end));

        return points;
    }

    /**
     * Create Polygon as encoded.
     *
     * @see #interpretation(int[], int)
     *
     * @param gf Used to construct polygon
     * @param elemInfo Interpretation of coords
     * @param elemIndex Triplet in elemInfo to process as a Polygon
     * @param coords Coordinates to interpret using elemInfo
     *
     * @return Polygon as encoded by elemInfo, or null when faced with and
     *         encoding that can not be captured by JTS
     * @throws IllegalArgumentException When faced with an invalid SDO encoding
     */
    private Polygon createPolygon(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

        if( !(1 <= sOffset && sOffset <= (coords.size() * dim))){
            throw new IllegalArgumentException(
                    "ELEM_INFO STARTING_OFFSET "+sOffset+
                    "inconsistent with COORDINATES length "+(coords.size() * dim) );
        }

		if(!(etype == Constants.SDO_ETYPE.POLYGON) && !(etype == Constants.SDO_ETYPE.POLYGON_EXTERIOR)){
			throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected POLYGON or POLYGON_EXTERIOR");
		}
		if (!(interpretation == 1) && !(interpretation == 3)){
			return null;
		}

        LinearRing exteriorRing = createLinearRing(gf, dim, lrs, elemInfo, elemIndex, coords);

        List rings = new LinkedList();

        boolean cont = true;
        for (int i = elemIndex + 1; cont && (etype = eType(elemInfo, i)) != -1; i++) {
            if (etype == Constants.SDO_ETYPE.POLYGON_INTERIOR) {
                rings.add(createLinearRing(gf, dim, lrs, elemInfo, i, coords));
            } else if (etype == Constants.SDO_ETYPE.POLYGON) { // need to test Clockwiseness of Ring to see if it is
                                                 // interior or not - (use POLYGON_INTERIOR to avoid pain)

                LinearRing ring = createLinearRing(gf, dim, lrs, elemInfo, i, coords);

                if (CGAlgorithms.isCCW(ring.getCoordinates())) { // it is an Interior Hole
                    rings.add(ring);
                } else { // it is the next Polygon! - get out of here
                    cont = false;
                }
            } else { // not a LinearRing - get out of here
                cont = false;
            }
        }

        Polygon poly = gf.createPolygon(exteriorRing, (LinearRing[]) rings.toArray(new LinearRing[rings.size()]));

        return poly;
    }

    /**
     * Create Linear Ring for exterior/interior polygon ELEM_INFO triplets.
     *
     * @param gf
     * @param elemInfo
     * @param elemIndex
     * @param coords
     *
     * @return LinearRing
     *
     * @throws IllegalArgumentException If circle, or curve is requested
     */
    private LinearRing createLinearRing(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);
        int length = coords.size()*dim;

		if (!(sOffset <= length))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());
		if(!(etype == Constants.SDO_ETYPE.POLYGON) && !(etype == Constants.SDO_ETYPE.POLYGON_EXTERIOR) && !(etype == Constants.SDO_ETYPE.POLYGON_INTERIOR)){
		    throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected POLYGON, POLYGON_EXTERIOR or POLYGON_INTERIOR");
		}
		if (!(interpretation == 1) && !(interpretation == 3)){
			return null;
		}
        LinearRing ring;

		int len = (dim+lrs);
		int start = (sOffset - 1) / len;
		int eOffset = StartingOffset(elemInfo, elemIndex+1); // -1 for end
        int end = (eOffset != -1) ? ((eOffset - 1) / len) : coords.size();

        if (interpretation == 1) {
            ring = gf.createLinearRing(subList(gf.getCoordinateSequenceFactory(),coords, start,end));
        } else { // interpretation == 3
            // rectangle does not maintain measures
            //
            CoordinateSequence ext = subList(gf.getCoordinateSequenceFactory(),coords, start,end);
            Coordinate min = ext.getCoordinate(0);
            Coordinate max = ext.getCoordinate(1);
            ring = gf.createLinearRing(new Coordinate[] {
                        min, new Coordinate(max.x, min.y), max,
                        new Coordinate(min.x, max.y), min
                    });
        }

        return ring;
    }

    /**
     * Create LineString as encoded.
     *
     * @param gf
     * @param elemInfo
     * @param coords
     *
     * @return LineString
     *
     * @throws IllegalArgumentException If asked to create a curve
     */
    private LineString createLine(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords) {

    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

		if (etype != Constants.SDO_ETYPE.LINE)
			return null;

        if (interpretation != 1) {
            throw new IllegalArgumentException("ELEM_INFO INTERPRETAION "
                + interpretation + " not supported"
                + "by JTS LineString.  Straight edges"
                + "( ELEM_INFO INTERPRETAION 1) is supported");
        }

		int len = (dim+lrs);
		int start = (sOffset - 1) / len;
		int eOffset = StartingOffset(elemInfo, elemIndex+1); // -1 for end
        int end = (eOffset != -1) ? ((eOffset - 1) / len) : coords.size();

        LineString line = gf.createLineString(subList(gf.getCoordinateSequenceFactory(),coords, start,end));

        return line;
    }

    /**
     * Create Point as encoded.
     *
     * @param gf
     * @param dim The number of Dimensions
     * @param elemInfo
     * @param elemIndex
     * @param coords
     *
     * @return Point
     */
    private Point createPoint(GeometryFactory gf, int dim, int lrs, int[] elemInfo, int elemIndex, CoordinateSequence coords) {
    	int sOffset = StartingOffset(elemInfo, elemIndex);
        int etype = eType(elemInfo, elemIndex);
        int interpretation = interpretation(elemInfo, elemIndex);

		if (!(sOffset >= 1) || !(sOffset <= coords.size()))
		    throw new IllegalArgumentException("ELEM_INFO STARTING_OFFSET "+sOffset+" inconsistent with ORDINATES length "+coords.size());
		if (etype != Constants.SDO_ETYPE.POINT)
		    throw new IllegalArgumentException("ETYPE "+etype+" inconsistent with expected POINT");
		if (interpretation != 1){
			return null;
		}

		int len = (dim+lrs);
		int start = (sOffset - 1) / len;
		int eOffset = StartingOffset(elemInfo, elemIndex+1); // -1 for end

		Point point = null;
        if ((sOffset == 1) && (eOffset == -1)) {
            // Use all Coordinates
        	point = gf.createPoint( coords);
        }else{
	        int end = (eOffset != -1) ? ((eOffset - 1) / len) : coords.size();
	        point = gf.createPoint(subList(gf.getCoordinateSequenceFactory(),coords,start,end));
        }

        return point;
    }

    /**
     * Version of List.subList() that returns a CoordinateSequence.
     *
     *

     * Returns from start (inclusive) to end (exlusive):
     *

     *
     * @param factory Manages CoordinateSequences for JTS
     * @param coords coords to sublist
     * @param start starting offset
     * @param end upper bound of sublist
     *
     * @return CoordianteSequence
     */
    private CoordinateSequence subList(CoordinateSequenceFactory factory, CoordinateSequence coords, int start, int end) {
        if ((start == 0) && (end == coords.size())) {
            return coords;
        }

        if (coords instanceof List) {
            List sublist = ((List) coords).subList(start, end);

            if (sublist instanceof CoordinateSequence) {
                return (CoordinateSequence) sublist;
            }
        }

        CoordinateList list = new CoordinateList(coords.toCoordinateArray());

        Coordinate[] array = new Coordinate[end - start];
        int index = 0;

        for (Iterator i = list.subList(start, end).iterator(); i.hasNext(); index++) {
            array[index] = (Coordinate) i.next();
        }

        return factory.create(array);
    }

    /**
     * ETYPE access for the elemInfo triplet indicated.
     *

     * @see Constants.SDO_ETYPE for an indication of possible values
     *
     * @param elemInfo
     * @param tripletIndex
     * @return ETYPE for indicated triplet
     */
    private int eType(int[] elemInfo, int tripletIndex) {
        if (((tripletIndex * 3) + 1) >= elemInfo.length) {
            return -1;
        }

        return elemInfo[(tripletIndex * 3) + 1];
    }

    /**
     * Accesses the interpretation value for the current geometry
     *
     * JTS valid interpretation is: 1 for strait edges, 3 for rectangle
     *
     * Other interpretations include: 2 for arcs, 4 for circles
     *
     * mostly useful for polygons
     *
     * @param elemInfo
     * @param tripletIndex
     * @return Starting Offset for the ordinates of the geometry
     */
    private int interpretation(int[] elemInfo, int tripletIndex) {
        if (((tripletIndex * 3) + 2) >= elemInfo.length) {
            return -1;
        }

        return elemInfo[(tripletIndex * 3) + 2];
    }

    /**
     * Accesses the starting index in the ordinate array for the current geometry
     *
     * mostly useful for polygons
     *
     * @param elemInfo
     * @param tripletIndex
     * @return Starting Offset for the ordinates of the geometry
     */
    private int StartingOffset(int[] elemInfo, int tripletIndex) {
        if (((tripletIndex * 3) + 0) >= elemInfo.length) {
            return -1;
        }

        return elemInfo[(tripletIndex * 3) + 0];
    }

	/** Presents datum as an int */
	private int asInteger(Datum datum, final int DEFAULT)
			throws SQLException {
		if (datum == null)
			return DEFAULT;
		return ((NUMBER) datum).intValue();
	}

	/** Presents datum as a double */
	private double asDouble(Datum datum, final double DEFAULT) {
		if (datum == null)
			return DEFAULT;
		return ((NUMBER) datum).doubleValue();
	}

	/** Presents struct as a double[] */
	private double[] asDoubleArray(STRUCT struct, final double DEFAULT)
			throws SQLException {
		if (struct == null)
			return null;
		return asDoubleArray(struct.getOracleAttributes(), DEFAULT);
	}

	/** Presents array as a double[] */
	private double[] asDoubleArray(ARRAY array, final double DEFAULT)
			throws SQLException {
		if (array == null)
			return null;
		if (DEFAULT == 0)
			return array.getDoubleArray();

		return asDoubleArray(array.getOracleArray(), DEFAULT);
	}

	/** Presents Datum[] as a double[] */
	private double[] asDoubleArray(Datum data[], final double DEFAULT) {
		if (data == null)
			return null;
		double array[] = new double[data.length];
		for (int i = 0; i < data.length; i++) {
			array[i] = asDouble(data[i], DEFAULT);
		}
		return array;
	}

	private int[] asIntArray(ARRAY array, int DEFAULT)
			throws SQLException {
		if (array == null)
			return null;
		if (DEFAULT == 0)
			return array.getIntArray();

		return asIntArray(array.getOracleArray(), DEFAULT);
	}

	/** Presents Datum[] as a int[] */
	private int[] asIntArray(Datum data[], final int DEFAULT)
			throws SQLException {
		if (data == null)
			return null;
		int array[] = new int[data.length];
		for (int i = 0; i < data.length; i++) {
			array[i] = asInteger(data[i], DEFAULT);
		}
		return array;
	}

	public int getDimension() {
		return dimension;
	}

	public void setDimension(int dimension) {
		this.dimension = dimension;
	}

}


text:
package views

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/satori/go.uuid"

	"github.com/LastCalamity/Core/core"
	"github.com/dgrijalva/jwt-go"
)

func init() {
	core.AddAuthRoute("logout", "GET", "/logout", logout)
	core.AddAuthRoute("login", "GET", "/login", login)
	core.AddAuthRoute("loginAnswer", "GET", "/LoginAnswer", loginAnswer)
	core.AddAuthRoute("callback", "GET", "/auth/eveonline/callback", loginAnswer)
}

func logout(w http.ResponseWriter, r *http.Request) {
	setCache(w, 0)
	userSession := core.SessionFromContext(r.Context())
	userSession.Options.MaxAge = -1
	err := userSession.Save(r, w)
	if err != nil {
		httpErr(w, err)
		return
	}

	http.Redirect(w, r, "/", 302)
}

func login(w http.ResponseWriter, r *http.Request) {
	setCache(w, 0)
	userSession := core.SessionFromContext(r.Context())
	globals := core.GlobalsFromContext(r.Context())
	b := make([]byte, 16)
	rand.Read(b)
	state := base64.URLEncoding.EncodeToString(b)

	userSession.Values["state"] = state

	err := userSession.Save(r, w)
	if err != nil {
		httpErr(w, err)
		return
	}
	url := globals.LoginAuthenticator.AuthorizeURL(state, true, nil)
	http.Redirect(w, r, url, 302)
}

func loginAnswer(w http.ResponseWriter, r *http.Request) {
	setCache(w, 0)
	userSession := core.SessionFromContext(r.Context())
	globals := core.GlobalsFromContext(r.Context())

	code := r.FormValue("code")
	state := r.FormValue("state")

	if userSession.Values["state"] != state {
		httpErr(w, errors.New("state does not match. We likely could not read the session cookie. Please make sure cookies are enabled"))
		return
	}

	tok, err := globals.LoginAuthenticator.TokenExchange(code)
	if err != nil {
		httpErr(w, err)
		return
	}

	tokSrc, err := globals.LoginAuthenticator.TokenSource(tok)
	if err != nil {
		httpErr(w, err)
		return
	}

	v, err := globals.LoginAuthenticator.Verify(tokSrc)
	if err != nil {
		httpErr(w, err)
		return
	}
	userSession.Values["character"] = v
	userSession.Values["characterID"] = v.CharacterID
	userSession.Values["token"] = tok
	userSession.Values["expiresAt"] = int64(time.Now().Add(time.Hour * 8).Unix())
	userSession.Values["issuedAt"] = int64(time.Now().Unix())

	claims := core.JWTClaims{
		Name:   v.CharacterName,
		CharID: int64(v.CharacterID),
	}
	claims.ExpiresAt = int64(time.Now().Add(time.Hour * 8).Unix())
	claims.IssuedAt = int64(time.Now().Unix())
	claims.Issuer = "core.lastcalamity"
	claimid, err := uuid.NewV4()
	if err != nil {
		fmt.Println(err)
	}
	claims.Id = claimid.String()
	claims.IsAdmin = true
	claims.IsDirector = true
	claims.Groups = []string{"TestGroup1", "TestGroup2"}

	jwttok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
	jwtTokenString, err := jwttok.SignedString(globals.JwtSignKey)
	if err != nil {
		log.Printf("Error: Failed to create jwt: %s", err.Error())
	}
	userSession.Values["jwt"] = jwtTokenString
	if err = userSession.Save(r, w); err != nil {
		httpErr(w, err)
		return
	}
	expireCookie := time.Now().Add(time.Hour * 8)
	cookie := http.Cookie{Name: "Auth", Value: jwtTokenString, Expires: expireCookie, HttpOnly: false}
	http.SetCookie(w, &cookie)
	http.Redirect(w, r, fmt.Sprintf("http://core.devknoll.com:3001/loggedin/%s", jwtTokenString), 302)
}


text:
using namespace llvm;
using namespace dwarf;
typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;

void DWARFDebugInfoEntryMinimal::dump(raw_ostream &OS, const DWARFUnit *u,
                                      unsigned recurseDepth,
                                      unsigned indent) const {
  DataExtractor debug_info_data = u->getDebugInfoExtractor();
  uint32_t offset = Offset;

  if (debug_info_data.isValidOffset(offset)) {
    uint32_t abbrCode = debug_info_data.getULEB128(&offset);

    OS << format("\n0x%8.8x: ", Offset);
    if (abbrCode) {
      if (AbbrevDecl) {
        const char *tagString = TagString(getTag());
        if (tagString)
          OS.indent(indent) << tagString;
        else
          OS.indent(indent) << format("DW_TAG_Unknown_%x", getTag());
        OS << format(" [%u] %c\n", abbrCode,
                     AbbrevDecl->hasChildren() ? '*' : ' ');

        // Dump all data in the DIE for the attributes.
        for (const auto &AttrSpec : AbbrevDecl->attributes()) {
          dumpAttribute(OS, u, &offset, AttrSpec.Attr, AttrSpec.Form, indent);
        }

        const DWARFDebugInfoEntryMinimal *child = getFirstChild();
        if (recurseDepth > 0 && child) {
          while (child) {
            child->dump(OS, u, recurseDepth-1, indent+2);
            child = child->getSibling();
          }
        }
      } else {
        OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
           << abbrCode << '\n';
      }
    } else {
      OS.indent(indent) << "NULL\n";
    }
  }
}

void DWARFDebugInfoEntryMinimal::dumpAttribute(raw_ostream &OS,
                                               const DWARFUnit *u,
                                               uint32_t *offset_ptr,
                                               uint16_t attr, uint16_t form,
                                               unsigned indent) const {
  OS << "            ";
  OS.indent(indent+2);
  const char *attrString = AttributeString(attr);
  if (attrString)
    OS << attrString;
  else
    OS << format("DW_AT_Unknown_%x", attr);
  const char *formString = FormEncodingString(form);
  if (formString)
    OS << " [" << formString << ']';
  else
    OS << format(" [DW_FORM_Unknown_%x]", form);

  DWARFFormValue formValue(form);

  if (!formValue.extractValue(u->getDebugInfoExtractor(), offset_ptr, u))
    return;

  OS << "\t(";
  formValue.dump(OS, u);
  OS << ")\n";
}

bool DWARFDebugInfoEntryMinimal::extractFast(const DWARFUnit *U,
                                             uint32_t *OffsetPtr) {
  Offset = *OffsetPtr;
  DataExtractor DebugInfoData = U->getDebugInfoExtractor();
  uint32_t UEndOffset = U->getNextUnitOffset();
  if (Offset >= UEndOffset || !DebugInfoData.isValidOffset(Offset))
    return false;
  uint64_t AbbrCode = DebugInfoData.getULEB128(OffsetPtr);
  if (0 == AbbrCode) {
    // NULL debug tag entry.
    AbbrevDecl = nullptr;
    return true;
  }
  AbbrevDecl = U->getAbbreviations()->getAbbreviationDeclaration(AbbrCode);
  if (nullptr == AbbrevDecl) {
    // Restore the original offset.
    *OffsetPtr = Offset;
    return false;
  }
  ArrayRef<uint8_t> FixedFormSizes = DWARFFormValue::getFixedFormSizes(
      U->getAddressByteSize(), U->getVersion());
  assert(FixedFormSizes.size() > 0);

  // Skip all data in the .debug_info for the attributes
  for (const auto &AttrSpec : AbbrevDecl->attributes()) {
    uint16_t Form = AttrSpec.Form;

    uint8_t FixedFormSize =
        (Form < FixedFormSizes.size()) ? FixedFormSizes[Form] : 0;
    if (FixedFormSize)
      *OffsetPtr += FixedFormSize;
    else if (!DWARFFormValue::skipValue(Form, DebugInfoData, OffsetPtr, U)) {
      // Restore the original offset.
      *OffsetPtr = Offset;
      return false;
    }
  }
  return true;
}

bool DWARFDebugInfoEntryMinimal::isSubprogramDIE() const {
  return getTag() == DW_TAG_subprogram;
}

bool DWARFDebugInfoEntryMinimal::isSubroutineDIE() const {
  uint32_t Tag = getTag();
  return Tag == DW_TAG_subprogram ||
         Tag == DW_TAG_inlined_subroutine;
}

bool DWARFDebugInfoEntryMinimal::getAttributeValue(
    const DWARFUnit *U, const uint16_t Attr, DWARFFormValue &FormValue) const {
  if (!AbbrevDecl)
    return false;

  uint32_t AttrIdx = AbbrevDecl->findAttributeIndex(Attr);
  if (AttrIdx == -1U)
    return false;

  DataExtractor DebugInfoData = U->getDebugInfoExtractor();
  uint32_t DebugInfoOffset = getOffset();

  // Skip the abbreviation code so we are at the data for the attributes
  DebugInfoData.getULEB128(&DebugInfoOffset);

  // Skip preceding attribute values.
  for (uint32_t i = 0; i < AttrIdx; ++i) {
    DWARFFormValue::skipValue(AbbrevDecl->getFormByIndex(i),
                              DebugInfoData, &DebugInfoOffset, U);
  }

  FormValue = DWARFFormValue(AbbrevDecl->getFormByIndex(AttrIdx));
  return FormValue.extractValue(DebugInfoData, &DebugInfoOffset, U);
}

const char *DWARFDebugInfoEntryMinimal::getAttributeValueAsString(
    const DWARFUnit *U, const uint16_t Attr, const char *FailValue) const {
  DWARFFormValue FormValue;
  if (!getAttributeValue(U, Attr, FormValue))
    return FailValue;
  Optional<const char *> Result = FormValue.getAsCString(U);
  return Result.hasValue() ? Result.getValue() : FailValue;
}

uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsAddress(
    const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
  DWARFFormValue FormValue;
  if (!getAttributeValue(U, Attr, FormValue))
    return FailValue;
  Optional<uint64_t> Result = FormValue.getAsAddress(U);
  return Result.hasValue() ? Result.getValue() : FailValue;
}

uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsUnsignedConstant(
    const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
  DWARFFormValue FormValue;
  if (!getAttributeValue(U, Attr, FormValue))
    return FailValue;
  Optional<uint64_t> Result = FormValue.getAsUnsignedConstant();
  return Result.hasValue() ? Result.getValue() : FailValue;
}

uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsReference(
    const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
  DWARFFormValue FormValue;
  if (!getAttributeValue(U, Attr, FormValue))
    return FailValue;
  Optional<uint64_t> Result = FormValue.getAsReference(U);
  return Result.hasValue() ? Result.getValue() : FailValue;
}

uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsSectionOffset(
    const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
  DWARFFormValue FormValue;
  if (!getAttributeValue(U, Attr, FormValue))
    return FailValue;
  Optional<uint64_t> Result = FormValue.getAsSectionOffset();
  return Result.hasValue() ? Result.getValue() : FailValue;
}

uint64_t
DWARFDebugInfoEntryMinimal::getRangesBaseAttribute(const DWARFUnit *U,
                                                   uint64_t FailValue) const {
  uint64_t Result =
      getAttributeValueAsSectionOffset(U, DW_AT_ranges_base, -1ULL);
  if (Result != -1ULL)
    return Result;
  return getAttributeValueAsSectionOffset(U, DW_AT_GNU_ranges_base, FailValue);
}

bool DWARFDebugInfoEntryMinimal::getLowAndHighPC(const DWARFUnit *U,
                                                 uint64_t &LowPC,
                                                 uint64_t &HighPC) const {
  LowPC = getAttributeValueAsAddress(U, DW_AT_low_pc, -1ULL);
  if (LowPC == -1ULL)
    return false;
  HighPC = getAttributeValueAsAddress(U, DW_AT_high_pc, -1ULL);
  if (HighPC == -1ULL) {
    // Since DWARF4, DW_AT_high_pc may also be of class constant, in which case
    // it represents function size.
    HighPC = getAttributeValueAsUnsignedConstant(U, DW_AT_high_pc, -1ULL);
    if (HighPC != -1ULL)
      HighPC += LowPC;
  }
  return (HighPC != -1ULL);
}

DWARFAddressRangesVector
DWARFDebugInfoEntryMinimal::getAddressRanges(const DWARFUnit *U) const {
  if (isNULL())
    return DWARFAddressRangesVector();
  // Single range specified by low/high PC.
  uint64_t LowPC, HighPC;
  if (getLowAndHighPC(U, LowPC, HighPC)) {
    return DWARFAddressRangesVector(1, std::make_pair(LowPC, HighPC));
  }
  // Multiple ranges from .debug_ranges section.
  uint32_t RangesOffset =
      getAttributeValueAsSectionOffset(U, DW_AT_ranges, -1U);
  if (RangesOffset != -1U) {
    DWARFDebugRangeList RangeList;
    if (U->extractRangeList(RangesOffset, RangeList))
      return RangeList.getAbsoluteRanges(U->getBaseAddress());
  }
  return DWARFAddressRangesVector();
}

void DWARFDebugInfoEntryMinimal::collectChildrenAddressRanges(
    const DWARFUnit *U, DWARFAddressRangesVector& Ranges) const {
  if (isNULL())
    return;
  if (isSubprogramDIE()) {
    const auto &DIERanges = getAddressRanges(U);
    Ranges.insert(Ranges.end(), DIERanges.begin(), DIERanges.end());
  }

  const DWARFDebugInfoEntryMinimal *Child = getFirstChild();
  while (Child) {
    Child->collectChildrenAddressRanges(U, Ranges);
    Child = Child->getSibling();
  }
}

bool DWARFDebugInfoEntryMinimal::addressRangeContainsAddress(
    const DWARFUnit *U, const uint64_t Address) const {
  for (const auto& R : getAddressRanges(U)) {
    if (R.first <= Address && Address < R.second)
      return true;
  }
  return false;
}

const char *
DWARFDebugInfoEntryMinimal::getSubroutineName(const DWARFUnit *U,
                                              FunctionNameKind Kind) const {
  if (!isSubroutineDIE() || Kind == FunctionNameKind::None)
    return nullptr;
  // Try to get mangled name only if it was asked for.
  if (Kind == FunctionNameKind::LinkageName) {
    if (const char *name =
            getAttributeValueAsString(U, DW_AT_MIPS_linkage_name, nullptr))
      return name;
    if (const char *name =
            getAttributeValueAsString(U, DW_AT_linkage_name, nullptr))
      return name;
  }
  if (const char *name = getAttributeValueAsString(U, DW_AT_name, nullptr))
    return name;
  // Try to get name from specification DIE.
  uint32_t spec_ref =
      getAttributeValueAsReference(U, DW_AT_specification, -1U);
  if (spec_ref != -1U) {
    DWARFDebugInfoEntryMinimal spec_die;
    if (spec_die.extractFast(U, &spec_ref)) {
      if (const char *name = spec_die.getSubroutineName(U, Kind))
        return name;
    }
  }
  // Try to get name from abstract origin DIE.
  uint32_t abs_origin_ref =
      getAttributeValueAsReference(U, DW_AT_abstract_origin, -1U);
  if (abs_origin_ref != -1U) {
    DWARFDebugInfoEntryMinimal abs_origin_die;
    if (abs_origin_die.extractFast(U, &abs_origin_ref)) {
      if (const char *name = abs_origin_die.getSubroutineName(U, Kind))
        return name;
    }
  }
  return nullptr;
}

void DWARFDebugInfoEntryMinimal::getCallerFrame(const DWARFUnit *U,
                                                uint32_t &CallFile,
                                                uint32_t &CallLine,
                                                uint32_t &CallColumn) const {
  CallFile = getAttributeValueAsUnsignedConstant(U, DW_AT_call_file, 0);
  CallLine = getAttributeValueAsUnsignedConstant(U, DW_AT_call_line, 0);
  CallColumn = getAttributeValueAsUnsignedConstant(U, DW_AT_call_column, 0);
}

DWARFDebugInfoEntryInlinedChain
DWARFDebugInfoEntryMinimal::getInlinedChainForAddress(
    const DWARFUnit *U, const uint64_t Address) const {
  DWARFDebugInfoEntryInlinedChain InlinedChain;
  InlinedChain.U = U;
  if (isNULL())
    return InlinedChain;
  for (const DWARFDebugInfoEntryMinimal *DIE = this; DIE; ) {
    // Append current DIE to inlined chain only if it has correct tag
    // (e.g. it is not a lexical block).
    if (DIE->isSubroutineDIE()) {
      InlinedChain.DIEs.push_back(*DIE);
    }
    // Try to get child which also contains provided address.
    const DWARFDebugInfoEntryMinimal *Child = DIE->getFirstChild();
    while (Child) {
      if (Child->addressRangeContainsAddress(U, Address)) {
        // Assume there is only one such child.
        break;
      }
      Child = Child->getSibling();
    }
    DIE = Child;
  }
  // Reverse the obtained chain to make the root of inlined chain last.
  std::reverse(InlinedChain.DIEs.begin(), InlinedChain.DIEs.end());
  return InlinedChain;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using HyperQube.Library.Questions;
using HyperQube.Providers.ControlChain;

namespace HyperQube.Providers
{
    [Export(typeof (IControlFactory))]
    internal class ControlFactory : IControlFactory
    {
        internal static readonly Size MaximumLabelSize = new Size(135, 23);
        internal static readonly Size MaximumSize = new Size(180, 23);
        internal static readonly Size MinimumSize = new Size(80, 23);
        private readonly IEnumerable<IBuilder> _builders;

        [ImportingConstructor]
        public ControlFactory([ImportMany] IEnumerable<IBuilder> builders)
        {
            _builders = builders;
        }

        public Control[] Build(IEnumerable<IQuestion> questions, ErrorProvider errorProvider)
        {
            //While grouping might be more performant, we would influence the order by doing so.
            //Instead, we'll just do a dumb build.
            return questions.Select(x => Build(x, errorProvider)).ToArray();
        }

        public Control Build(IQuestion question, ErrorProvider errorProvider)
        {
            var control = GetBuilder(question.QuestionType).Build(question, errorProvider);

            control.Tag = question.Tag;

            return control;
        }

        public void MapTo(IEnumerable<Control> controls, IEnumerable<IQuestion> questions)
        {
            var groups = controls.Select(x => Tuple.Create(x, questions.FirstOrDefault(y => Equals(x.Tag, y.Tag))))
                                 .Where(x => x.Item2 != null)
                                 .GroupBy(x => x.Item2.QuestionType);

            foreach (var group in groups)
            {
                var builder = GetBuilder(group.Key);

                foreach (var tuple in group)
                    tuple.Item2.Result = builder.GetValue(tuple.Item1);
            }
        }

        private IBuilder GetBuilder(QuestionType questionType)
        {
            var builder = _builders.FirstOrDefault(x => x.IsCompatible(questionType));

            if (builder == null)
                throw new NotSupportedException("No compatible builder found.");

            return builder;
        }

        public static void DisposeControl(IEnumerable<Control> controls)
        {
            foreach (var control in controls)
                DisposeControl(control);
        }

        public static void DisposeControl(Control control)
        {
            if (control == null) return;

            var panel = control as Panel;
            if (panel != null)
            {
                foreach (var child in panel.Controls.OfType<Control>())
                    DisposeControl(child);
            }

            control.Tag = null;
            control.Dispose();
        }
    }
}


text:
package ticketline.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.TextComponent;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;

import com.toedter.calendar.JDateChooser;

import ticketline.bl.GuiMemory;
import ticketline.bl.ITrail;
import ticketline.bl.Trail;
import ticketline.dao.DAOFactory;
import ticketline.dao.hibernate.KundeDAOHibernate;
import ticketline.dao.interfaces.KundeDAO;
import ticketline.db.Kunde;

/**
 * Costumer Edit GUI
 *
 * @author AndiS, PatrickF, DanielZ, ReneN
 * @version 0.3
 */

public class KundeAendernGui extends KundeGui implements ActionListener,ITrail{

	private static final long serialVersionUID = 1L;
	private KundeDAOHibernate dao = new KundeDAOHibernate();
	private KundeDAO kDAO = DAOFactory.getKundeDAO();
	private Kunde customer;

	public KundeAendernGui()
	{
		btn_execute.addActionListener(this);
		btn_execute.setActionCommand("edit");
		btn_back.setActionCommand("back");
		btn_back.addActionListener(this);

		reloadChanges();

		logger.debug("KundeAendernGui Created Successfully.");

		setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		execute(e);
	}
	private void execute(ActionEvent e) {
		if(e.getActionCommand().equalsIgnoreCase("edit")){
			customer = kDAO.get(new Integer(tf_cardnumber.getText()));

			if(testFields()){ //test if all required fields are filled and then save all
				customer.setTyp("K");
				customer.setErmaechtigung(false);
				customer.setGruppe("Standard");
				customer.setGesperrt(false);
				customer.setTkgueltigbis(new Date());
				if(rb_gender_male.getSelectedObjects() == null){
					customer.setGeschlecht("W");
				}
				else{
					customer.setGeschlecht("M");
				}

				dao.update(customer);
				JOptionPane.showMessageDialog(this, lang.getString("OPH_EDITCOSTUMER_SUCCESS"),lang.getString("OPT_EDITCOSTUMER_SUCCESS2"),JOptionPane.INFORMATION_MESSAGE);
				logger.info("Customer edited");
			}
		}
		if(e.getActionCommand().equals("back")){
			Gui.load((Component)trail.getPrevious(this));
			setVisible(true);
		}
	}
	private boolean testFields(){
		boolean ok = true;
		String justNumbersCheck = "[0-9]+";
		String justLettersCheck = "[a-zA-Z-äöüßÖÄÜéè\\s]+";
		String reductionCheck = "([0-9]+([.][0-9]+)?)";
		String digitsCheck = "[0-9]*";
		String emailCheck = "([a-zA-Z0-9]+[@][a-zA-Z0-9]+[.][a-z]+)*";
		String lettersCheck = "[a-zA-ZäöüßÖÄÜ,\\-\\s]*";

		if(tf_firstname.getText().matches(justLettersCheck)){
			customer.setVname(tf_firstname.getText().trim());
			tf_firstname.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray)); //set border to previous state
		}
		else{
			tf_firstname.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red)); //change border to show that field is required
			ok = false;
		}
		if(tf_surname.getText().matches(justLettersCheck)){
			customer.setNname(tf_surname.getText().trim());
			tf_surname.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			tf_surname.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
			ok = false;
		}
		if(tf_plz.getText().trim().matches(digitsCheck)){
			customer.setPlz(tf_plz.getText().trim());
			tf_plz.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			tf_plz.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
			ok = false;
		}
		if(tf_phone.getText().matches(digitsCheck)){
			customer.setTelnr(tf_phone.getText().trim());
			tf_phone.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			ok = false;
			tf_phone.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_mail.getText().matches(emailCheck)){
			customer.setEmail(tf_mail.getText());
			tf_mail.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			ok = false;
			tf_mail.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_account.getText().matches(justNumbersCheck)){
			customer.setKontonr(tf_account.getText());
			tf_account.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			ok = false;
			tf_account.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_balance.getText().matches(justNumbersCheck)){
			customer.setKontostand(new java.math.BigDecimal(tf_balance.getText()));
			tf_balance.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			ok = false;
			tf_balance.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_reduction.getText().matches(reductionCheck)){
			customer.setErmaessigung(new java.math.BigDecimal(tf_reduction.getText()));
			tf_reduction.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			tf_reduction.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
			ok = false;
		}
		if(jdc_birthday.getDate() != null && jdc_birthday.getDate().before(new Date())){
			Date birthDate = jdc_birthday.getDate();
			customer.setGeburtsdatum(birthDate);
			jdc_birthday.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			jdc_birthday.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
			ok = false;
		}
		if(jdc_validDate.getDate() != null && jdc_validDate.getDate().after(new Date())){
			Date validDate = jdc_validDate.getDate();
			customer.setKkgueltigbis(validDate);
			jdc_validDate.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		}
		else{
			jdc_validDate.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
			ok = false;
		}
		if(tf_street.getText().matches(lettersCheck)){
			tf_street.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
			customer.setStrasse(tf_street.getText().trim());
		}
		else{
			ok = false;
			tf_street.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_location.getText().matches(lettersCheck)){
			tf_location.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
			customer.setOrt(tf_location.getText().trim());
		}
		else{
			ok = false;
			tf_location.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}
		if(tf_preferences.getText().matches(lettersCheck)){
			tf_preferences.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
			customer.setVorlieben(tf_preferences.getText().trim());
		}
		else{
			ok = false;
			tf_preferences.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
		}

		if(!ok){
			JOptionPane.showMessageDialog(this, lang.getString("OPH_CREATECOSTUMER_INPUTERROR"),lang.getString("OPT_CREATECOSTUMER_INPUTERROR_NUMBER"),JOptionPane.WARNING_MESSAGE);
			logger.debug("One/Some field(s) is/are not filled.");
			return false;
		}
		logger.info("Required fields are filled");
		return true;

	}

	@Override
	public void dummySearch() {
		// TODO Auto-generated method stub
	}

	@Override
	public void reloadChanges() {
		try{
			setDefaultButton();
			//retrieving costumer from gui memory
			if(GuiMemory.isKundeSet()) {
				k = GuiMemory.getKunde();
				tf_cardnumber.setText(k.getKartennr().toString());
				tf_firstname.setText(k.getVname());
				tf_surname.setText(k.getNname());
				rb_gender_male = new JRadioButton(lang.getString("RB_CUSTOMER_MALE"),true);
				rb_gender_female = new JRadioButton(lang.getString("RB_CUSTOMER_FEMALE"),false);
				jdc_birthday.setDate(k.getGeburtsdatum());
				tf_street.setText(k.getStrasse());
				tf_plz.setText(k.getPlz());
				tf_mail.setText(k.getEmail());
				tf_location.setText(k.getOrt());
				tf_phone.setText(k.getTelnr());
				tf_account.setText(k.getKontonr());
				tf_balance.setText(k.getKontostand().toString());
				tf_reduction.setText(k.getErmaessigung().toString());
				jdc_validDate.setDate(k.getKkgueltigbis());
				tf_preferences.setText(k.getVorlieben());
			}
		}catch(Exception e){
			logger.warn("No customer found");
		}

		//Customize the Panel for Edit Costumer
		setBorder(new TitledBorder(lang.getString("PNL_CUSTOMER_EDIT")));
		tf_cardnumber.setEditable(false);
		btn_reset.setVisible(false);
		btn_execute.setText(lang.getString("BTN_SEARCHCUSTOMER_SAVE"));
	}
	@Override
	public void setTrail(Trail trail) {
		this.trail = trail;
	}
	public void setDefaultButton(){
		tf_cardnumber.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_firstname.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_surname.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		rb_gender_male.setSelected(true);
		rb_gender_female.setSelected(false);
		tf_street.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_plz.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_mail.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_location.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_phone.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_account.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_balance.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_reduction.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		tf_preferences.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		jdc_birthday.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));
		jdc_validDate.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.gray));

	}
}


text:
set :stages, %w(jaguar production jaguar-pit1 jaguar-production demo)
set :rvm_type, :system
set :rvm_ruby_string, '1.9.3'
require 'capistrano/ext/multistage'
require 'bundler/capistrano'
require "rvm/capistrano"                  # Load RVM's capistrano plugin.


text:
<?php
/**
 * This is the template for generating the model class of a specified table.
 * In addition to the default model Code, this adds the CSaveRelationsBehavior
 * to the model class definition.
 * - $this: the ModelCode object
 * - $tableName: the table name for this class (prefix is already removed if necessary)
 * - $modelClass: the model class name
 * - $columns: list of table columns (name=>CDbColumnSchema)
 * - $labels: list of attribute labels (name=>label)
 * - $rules: list of validation rules
 * - $relations: list of relations (name=>relation declaration)
 * - $representingColumn: the name of the representing column for the table (string) or
 *   the names of the representing columns (array)
 */
?>
<?php echo "<?php\n"; ?>

namespace api\models;

use Yii;

class <?= $className ?> extends <?= '\\common\models\\' . $className . "Base {\n" ?>

}


text:
package org.ehcache.osgi;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.impl.config.copy.DefaultCopierConfiguration;
import org.ehcache.impl.copy.ReadWriteCopier;
import org.ehcache.impl.copy.SerializingCopier;
import org.ehcache.xml.XmlConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;

import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;
import static org.ehcache.config.builders.ResourcePoolsBuilder.heap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.ops4j.pax.exam.CoreOptions.bundle;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;

/**
 * SimpleOsgiTest
 */
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class SimpleOsgiTest {

  @Configuration
  public Option[] config() {
    return options(
        mavenBundle("org.slf4j", "slf4j-api", System.getProperty("ehcache.osgi.slf4j.version")),
        mavenBundle("org.slf4j", "slf4j-simple", System.getProperty("ehcache.osgi.slf4j.version")).noStart(),
        bundle("file:" + System.getProperty("ehcache.osgi.jar")),
        junitBundles()
    );
  }

  @Test
  public void testEhcache3AsBundle() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .build())
        .build(true);

    Cache<Long, String> myCache = cacheManager.getCache("myCache", Long.class, String.class);

    myCache.put(42L, "DaAnswer!");
    assertEquals("DaAnswer!", myCache.get(42L));
  }

  @Test
  public void testEhcache3WithSerializationAndClientClass() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("myCache", newCacheConfigurationBuilder(Long.class, Person.class, heap(10))
            .add(new DefaultCopierConfiguration<Person>((Class) SerializingCopier.class, DefaultCopierConfiguration.Type.VALUE))
            .withClassLoader(getClass().getClassLoader())
            .build())
        .build(true);

    Cache<Long, Person> myCache = cacheManager.getCache("myCache", Long.class, Person.class);

    myCache.put(42L, new Person("Arthur"));
    assertTrue(myCache.get(42L) instanceof Person);
  }

  @Test
  public void testCustomCopier() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .add(new DefaultCopierConfiguration<String>(StringCopier.class, DefaultCopierConfiguration.Type.VALUE))
            .withClassLoader(getClass().getClassLoader())
            .build())
        .build(true);

    Cache<Long, String> cache = cacheManager.getCache("myCache", Long.class, String.class);

    cache.put(42L, "What's the question again?");
    cache.get(42L);
  }

  @Test
  public void testEhcacheXMLConfig() throws Exception {
    XmlConfiguration configuration = new XmlConfiguration(getClass().getResource("/org/ehcache/osgi/ehcache-osgi.xml").toURI().toURL(), getClass().getClassLoader());

    assertEquals(Person.class, configuration.getCacheConfigurations().get("bar").getValueType());
  }

  public static class StringCopier extends ReadWriteCopier<String> {

    @Override
    public String copy(String obj) {
      return new String(obj);
    }
  }

}


text:
<?php

namespace Oro\Bundle\EntityConfigBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType as SymfonyChoiceType;

/**
 * This form type is just a wrapper around standard 'choice' form type, but
 * this form type can handle 'immutable' behaviour. It means that you can use it
 * if you need to disable changing of an attribute value in case if there is
 * 'immutable' attribute set to true in the same config scope as your attribute.
 */
class ChoiceType extends AbstractConfigType
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'oro_entity_config_choice';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return SymfonyChoiceType::class;
    }
}