text:
package org.mrgeo.image;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.mrgeo.tile.TileNotFoundException;
import org.mrgeo.data.DataProviderFactory;
import org.mrgeo.data.DataProviderFactory.AccessMode;
import org.mrgeo.data.KVIterator;
import org.mrgeo.data.image.MrsImageDataProvider;
import org.mrgeo.data.image.MrsImagePyramidReaderContext;
import org.mrgeo.data.raster.RasterUtils;
import org.mrgeo.data.tile.MrsTileReader;
import org.mrgeo.data.tile.TileIdWritable;
import org.mrgeo.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

/**
 * @author tim.tisler
 *
 */
public class MrsImage
{

  private static final Logger log = LoggerFactory.getLogger(MrsImage.class);

  // create a simple color model
  protected ColorModel colorModel = null;
  protected SampleModel sampleModel = null;
  protected String measurement = "Ratio"; // not sure what this is for...
  private MrsTileReader<Raster> reader = null; // The MrsImageReader for fetching the tiles
  private MrsImagePyramidMetadata metadata = null; // image metadata

  private int zoomlevel = -1; // current zoom level of this image
  private int tilesize = -1; // size of a tile (here for convenience, it is in the metadata)
  private MrsImageDataProvider provider;
  private MrsImagePyramidReaderContext context;

  private MrsImage(MrsImageDataProvider provider, final int zoomlevel)
  {
    context = new MrsImagePyramidReaderContext();
    context.setZoomlevel(zoomlevel);
    this.provider = provider;

    openReader();

    if (System.getProperty("mrgeo.profile", "false").compareToIgnoreCase("true") == 0)
    {
      LeakChecker.instance().add(
        this,
        ExceptionUtils.getFullStackTrace(new Throwable(
            "MrsImage creation stack(ignore the Throwable...)")));
    }
  }

  public static MrsImage open(MrsImageDataProvider provider, final int zoomlevel) throws IOException
  {
    try
    {
      MrsImagePyramidMetadata meta = provider.getMetadataReader(null).read();
      // Check to see if there is an image at this zoom level before opening
      final String name = meta.getName(zoomlevel);
      if (name != null)
      {
        final MrsImage image = new MrsImage(provider, zoomlevel);
        return image;
      }
    }
    // TODO this seems weird to catch and eat these here...
    catch (final MrsImageException e)
    {
      // e.printStackTrace();
    }
    catch (final NullPointerException e)
    {
      // e.printStackTrace();
    }

    return null;
  }

  public static MrsImage open(final String name, final int zoomlevel,
      final Properties providerProperties) throws IOException
  {
    if (name == null)
    {
      throw new IOException("Unable to open image. Resource name is empty.");
    }
    MrsImageDataProvider dp = DataProviderFactory.getMrsImageDataProvider(name,
        AccessMode.READ, providerProperties);
    return open(dp, zoomlevel);
  }

  /**
   * Releases any resources held by this image, in particular its reader. Be sure to call this after
   * done using an MrsImage, and if necessary, in a finally block of a try/catch/finally
   */
  public void close()
  {
    if (reader != null)
    {
      LeakChecker.instance().remove(this);

      reader.close();
      reader = null;
    }
  }

  public LatLng convertToLatLng(final double px, final double py)
  {
    return new LatLng(convertToWorldY(py), convertToWorldX(px));
  }

  public LatLng convertToPixelCenterLatLng(final double px, final double py)
  {
    return new LatLng(convertToWorldY(py + 0.5), convertToWorldX(px + 0.5));
  }

  public final double convertToWorldX(final double px)
  {
    final double resolution = TMSUtils.resolution(getZoomlevel(), getTilesize());
    final Bounds bounds = getMetadata().getBounds();

    return bounds.getMinX() + (px * resolution);
  }

  public final double convertToWorldY(final double py)
  {
    final double resolution = TMSUtils.resolution(getZoomlevel(), getTilesize());
    final Bounds bounds = getMetadata().getBounds();

    return bounds.getMinY() + ((getPixelMaxY() - py) * resolution);
  }

  public Raster getAnyTile()
  {
    if (reader == null)
    {
      openReader();
    }
    final Iterator<Raster> it = reader.get();
    return it.next();
  }

  /**
   * @return
   */
  public Bounds getBounds()
  {
    return getMetadata().getBounds();
  }

  public Bounds getBounds(final int tx, final int ty)
  {
    final double bounds[] = TMSUtils.tileSWNEBoundsArray(tx, ty, getZoomlevel(), getTilesize());

    return new Bounds(bounds[0], bounds[1], bounds[2], bounds[3]);
  }

  /**
   * Retrieves the overall minimum and maximum raster values in the source data
   *
   * @return array with the overall minimum value in first position and overall maximum value in the
   *         second
   */
  public double[] getExtrema()
  {
    final double[] extrema = new double[3];
    final ImageStats stats = getMetadata().getImageStats(getZoomlevel(), 0);
    if (stats != null)
    {
      extrema[1] = stats.max;
      extrema[0] = Math.max(0.0, stats.min);
    }
    else
    {
      extrema[1] = 1.0;
      extrema[0] = 0.0;
    }
    return extrema;
  }

  public long getHeight()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getHeight();
  }

  public Rectangle2D getImageBounds()
  {
    return new Rectangle2D.Double(getPixelMinX(), getPixelMinY(), getWidth(), getHeight());
  }

  public long getMaxTileX()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getMaxX();
  }

  public long getMaxTileY()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getMaxY();
  }

  public int getMaxZoomlevel()
  {
    return getMetadata().getMaxZoomLevel();
  }

  public MrsImagePyramidMetadata getMetadata()
  {
    if (metadata == null)
    {
      try
      {
        metadata = provider.getMetadataReader().read();
      }
      catch (IOException e)
      {
        log.error("Unable to read metadata for " + provider.getResourceName(), e);
      }
    }
    return metadata;
  }

  public long getMinTileX()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getMinX();
  }

  public long getMinTileY()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getMinY();
  }

  public String getName()
  {
    return metadata.getName(zoomlevel);
  }

  public long getNumXTiles()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getWidth();
  }

  public long getNumYTiles()
  {
    return getMetadata().getTileBounds(getZoomlevel()).getHeight();
  }

  public long getPixelMaxX()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getMaxX();
  }

  public long getPixelMaxY()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getMaxY();
  }

  public long getPixelMinX()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getMinX();
  }

  public long getPixelMinY()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getMinY();
  }

  public LongRectangle getPixelRect()
  {
    return new LongRectangle(getPixelMinX(), getPixelMinY(), getWidth(), getHeight());
  }

  /**
   * Returns a rendered image for the MrsImage data
   *
   * @return rendered image
   * @throws IOException
   */
  public RenderedImage getRenderedImage() throws IOException
  {
    return getRenderedImage(null);
  }

  /**
   * Returns a rendered image for the MrsImage data
   *
   * @param bounds
   *          requested bounds
   * @return rendered image
   * @throws IOException
   */
  public RenderedImage getRenderedImage(final Bounds bounds)
  {
    log.debug("Merging to rendered image...");
    Raster mergedRaster = null;
    BufferedImage mergedImage = null;
    try
    {
      log.debug("Merging tiles...");
      if (bounds != null)
      {
        log.debug("with bounds: " + bounds.toString());
        mergedRaster = RasterTileMerger.mergeTiles(this, bounds);
      }
      else
      {
        mergedRaster = RasterTileMerger.mergeTiles(this);
      }
      log.debug("Tiles merged.");
    }
    catch (final MrsImageException e)
    {
      log.error(e.getMessage());
    }
    if (mergedRaster != null)
    {
      log.debug("Rendering merged image...");
      mergedImage = RasterUtils.makeBufferedImage(mergedRaster);
      log.debug("Merged image rendered.");
    }
    return mergedImage;
  }

  public Raster getTile(final long tx, final long ty) throws TileNotFoundException
  {
    if (tx < getMinTileX() || tx > getMaxTileX() || ty < getMinTileY() || ty > getMaxTileY())
    {
      // throw new IllegalArgumentException("x/y out of range. (" + String.valueOf(tx) + ", " +
      // String.valueOf(ty) + ") range: " + String.valueOf(getMinTileX()) + ", " +
      // String.valueOf(getMinTileY()) + " to " + String.valueOf(getMaxTileX()) + ", " +
      // String.valueOf(getMaxTileY()) + " (inclusive)");

      final String msg = String.format(
        "Tile x/y out of range. (%d, %d) range: (%d, %d) to (%d, %d) (inclusive)", tx, ty,
        getMinTileX(), getMinTileY(), getMaxTileX(), getMaxTileY());
      throw new TileNotFoundException(msg);
    }
    if (reader == null)
    {
      openReader();
    }
    return reader.get(new TileIdWritable(TMSUtils.tileid(tx, ty, getZoomlevel())));
  }

  public LongRectangle getTileBounds()
  {
    return getMetadata().getTileBounds(getZoomlevel());
  }

  public int getTileHeight()
  {
    return getTilesize();
  }

  public KVIterator<TileIdWritable, Raster> getTiles(final LongRectangle tileBounds)
  {
    if (reader == null)
    {
      openReader();
    }
    return reader.get(tileBounds);
  }

  public KVIterator<TileIdWritable, Raster> getTiles(final TileIdWritable start,
    final TileIdWritable end)
  {
    if (reader == null)
    {
      openReader();
    }
    return reader.get(start, end);
  }

  public int getTilesize()
  {
    if (tilesize < 0)
    {
      tilesize = getMetadata().getTilesize();
    }
    return tilesize;
  }

  public int getTileType()
  {
    return getMetadata().getTileType();
  }

  public int getTileWidth()
  {
    return getTilesize();
  }

  public long getWidth()
  {
    return getMetadata().getPixelBounds(getZoomlevel()).getWidth();
  }

  public int getZoomlevel()
  {
    if (zoomlevel < 0)
    {
      if (reader == null)
      {
        openReader();
      }
      zoomlevel = reader.getZoomlevel();
    }
    return zoomlevel;
  }

  public boolean isTileEmpty(final long tx, final long ty)
  {
    if (reader == null)
    {
      openReader();
    }
    return !reader.exists(new TileIdWritable(TMSUtils.tileid(tx, ty, getZoomlevel())));
  }

  public void setScaleType(final String measurement)
  {
    // this.measurement = measurement;
    // final FileSystem fs = HadoopUtils.getFileSystem(toc);
    // final FSDataOutputStream dos = fs.create(toc);
    // writeXml(dos);
    // dos.close();
    throw new NotImplementedException("MrsImage2.setScaleType() Not Implemented");

  }

  // @SuppressWarnings({ "unchecked", "rawtypes" })
  // protected Hashtable getProperties()
  // {
  // final Hashtable result = new Hashtable();
  // result.put(ValidRegion.PROPERTY_STRING, this);
  // result.put(GeographicTranslator.PROPERTY_STRING, this);
  // result.put(GeoTiffOpImage.NULL_PROPERTY, Double.NaN);
  // result.put(MEASUREMENT_STRING, measurement);
  // return result;
  // }

  @Override
  public String toString()
  {
    return getClass().getSimpleName() + ": " + getMetadata().getPyramid() + ":" + getZoomlevel();
  }

  // log an error if finalize() is called and close() was not called
  @Override
  protected void finalize() throws Throwable
  {
    try
    {
      if (reader != null)
      {
        log.info("MrsImage.finalize(): looks like close() was not called. This is a potential " +
            "memory leak. Please call close(). The MrsImage points to \"" + metadata.getPyramid() +
            "\" with zoom level " + getZoomlevel());
      }
    }
    finally
    {
      super.finalize();
    }
  }

  private void openReader()
  {
    try
    {
      reader = provider.getMrsTileReader(context);
      if (reader == null)
      {
        throw new MrsImageException("Error Reading Image");
      }
    }
    catch (IOException e)
    {
      throw new MrsImageException(e);
    }
  }
}


text:
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
    <id>sharding-proxy-bin</id>
    <formats>
        <format>tar.gz</format>
    </formats>
    <includeBaseDirectory>true</includeBaseDirectory>
    <baseDirectory>${project.build.finalName}-sharding-proxy-bin</baseDirectory>

    <fileSets>
        <fileSet>
            <directory>src/main/resources/bin</directory>
            <outputDirectory>bin</outputDirectory>
            <fileMode>0755</fileMode>
        </fileSet>
        <fileSet>
            <directory>src/main/resources/conf</directory>
            <outputDirectory>conf</outputDirectory>
            <fileMode>0644</fileMode>
        </fileSet>
        <fileSet>
            <directory>src/main/resources</directory>
            <includes>
                <include>logback.xml</include>
                <include>jta.properties</include>
            </includes>
            <outputDirectory>conf</outputDirectory>
            <fileMode>0644</fileMode>
        </fileSet>
        <fileSet>
            <directory>../../</directory>
            <includes>
                <include>DISCLAIMER</include>
            </includes>
        </fileSet>
        <fileSet>
            <directory>src/main/release-docs</directory>
            <includes>
                <include>**/*</include>
            </includes>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>

    <dependencySets>
        <dependencySet>
            <outputDirectory>lib</outputDirectory>
            <fileMode>0644</fileMode>
        </dependencySet>
    </dependencySets>
</assembly>

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.8/src/libraries/System.Collections.Immutable/tests/ImmutableSetTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using SetTriad = System.Tuple<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>, bool>;

#pragma warning disable CA1829 // Use Length/Count property instead of Count() when available
#pragma warning disable RS0002 // Use 'SpecializedCollections.SingletonEnumerable()'

namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
    public abstract partial class ImmutableSetTest : ImmutablesTestBase
    {
        [Fact]
        public void AddTest()
        {
            AddTestHelper(this.Empty<int>(), 3, 5, 4, 3);
        }

        [Fact]
        public void AddDuplicatesTest()
        {
            var arrayWithDuplicates = Enumerable.Range(1, 100).Concat(Enumerable.Range(1, 100)).ToArray();
            AddTestHelper(this.Empty<int>(), arrayWithDuplicates);
        }

        [Fact]
        public void RemoveTest()
        {
            RemoveTestHelper(this.Empty<int>().Add(3).Add(5), 5, 3);
        }

        [Fact]
        public void AddRemoveLoadTest()
        {
            var data = GenerateDummyFillData();
            AddRemoveLoadTestHelper(Empty<double>(), data);
        }

        [Fact]
        public void RemoveNonExistingTest()
        {
            System.Collections.Immutable.IImmutableSet<int> emptySet = this.Empty<int>();
            Assert.True(IsSame(emptySet, emptySet.Remove(5)));

            // Also fill up a set with many elements to build up the tree, then remove from various places in the tree.
            const int Size = 200;
            var set = emptySet;
            for (int i = 0; i < Size; i += 2)
            { // only even numbers!
                set = set.Add(i);
            }

            // Verify that removing odd numbers doesn't change anything.
            for (int i = 1; i < Size; i += 2)
            {
                var setAfterRemoval = set.Remove(i);
                Assert.True(IsSame(set, setAfterRemoval));
            }
        }

        [Fact]
        public void AddBulkFromImmutableToEmpty()
        {
            var set = this.Empty<int>().Add(5);
            var empty2 = this.Empty<int>();
            Assert.True(IsSame(set, empty2.Union(set))); // "Filling an empty immutable set with the contents of another immutable set with the exact same comparer should return the other set."
        }

        /// <summary>
        /// Verifies that Except *does* enumerate its argument if the collection is empty.
        /// </summary>
        /// <remarks>
        /// While this would seem an implementation detail and simply lack of an optimization,
        /// it turns out that changing this behavior now *could* represent a breaking change
        /// because if the enumerable were to throw an exception, that exception would be
        /// observed previously, but would no longer be thrown if this behavior changed.
        /// So this is a test to lock the behavior in place or be thoughtful if adding the optimization.
        /// </remarks>
        /// <!--<seealso cref="ImmutableListTest.RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty"/>-->
        [Fact]
        public void ExceptDoesEnumerateSequenceIfThisIsEmpty()
        {
            bool enumerated = false;
            Empty<int>().Except(Enumerable.Range(1, 1).Select(n => { enumerated = true; return n; }));
            Assert.True(enumerated);
        }

        [Fact]
        public void SetEqualsTest()
        {
            Assert.True(this.Empty<int>().SetEquals(this.Empty<int>()));
            var nonEmptySet = this.Empty<int>().Add(5);
            Assert.True(nonEmptySet.SetEquals(nonEmptySet));

            this.SetCompareTestHelper(s => s.SetEquals, s => s.SetEquals, this.GetSetEqualsScenarios());
        }

        [Fact]
        public void IsProperSubsetOfTest()
        {
            this.SetCompareTestHelper(s => s.IsProperSubsetOf, s => s.IsProperSubsetOf, GetIsProperSubsetOfScenarios());
        }

        [Fact]
        public void IsProperSupersetOfTest()
        {
            this.SetCompareTestHelper(s => s.IsProperSupersetOf, s => s.IsProperSupersetOf, GetIsProperSubsetOfScenarios().Select(Flip));
        }

        [Fact]
        public void IsSubsetOfTest()
        {
            this.SetCompareTestHelper(s => s.IsSubsetOf, s => s.IsSubsetOf, GetIsSubsetOfScenarios());
        }

        [Fact]
        public void IsSupersetOfTest()
        {
            this.SetCompareTestHelper(s => s.IsSupersetOf, s => s.IsSupersetOf, GetIsSubsetOfScenarios().Select(Flip));
        }

        [Fact]
        public void OverlapsTest()
        {
            this.SetCompareTestHelper(s => s.Overlaps, s => s.Overlaps, GetOverlapsScenarios());
        }

        [Fact]
        public void EqualsTest()
        {
            Assert.False(Empty<int>().Equals(null));
            Assert.False(Empty<int>().Equals("hi"));
            Assert.True(Empty<int>().Equals(Empty<int>()));
            Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3)));
            Assert.False(Empty<int>().Add(5).Equals(Empty<int>().Add(3)));
            Assert.False(Empty<int>().Add(3).Add(5).Equals(Empty<int>().Add(3)));
            Assert.False(Empty<int>().Add(3).Equals(Empty<int>().Add(3).Add(5)));
        }

        [Fact]
        public void GetHashCodeTest()
        {
            // verify that get hash code is the default address based one.
            Assert.Equal(EqualityComparer<object>.Default.GetHashCode(Empty<int>()), Empty<int>().GetHashCode());
        }

        [Fact]
        public void ClearTest()
        {
            var originalSet = this.Empty<int>();
            var nonEmptySet = originalSet.Add(5);
            var clearedSet = nonEmptySet.Clear();
            Assert.True(IsSame(originalSet, clearedSet));
        }

        [Fact]
        public void ISetMutationMethods()
        {
            var set = (ISet<int>)this.Empty<int>();
            Assert.Throws<NotSupportedException>(() => set.Add(0));
            Assert.Throws<NotSupportedException>(() => set.ExceptWith(null!));
            Assert.Throws<NotSupportedException>(() => set.UnionWith(null!));
            Assert.Throws<NotSupportedException>(() => set.IntersectWith(null!));
            Assert.Throws<NotSupportedException>(() => set.SymmetricExceptWith(null!));
        }

        [Fact]
        public void ICollectionOfTMembers()
        {
            var set = (ICollection<int>)this.Empty<int>();
            Assert.Throws<NotSupportedException>(() => set.Add(1));
            Assert.Throws<NotSupportedException>(() => set.Clear());
            Assert.Throws<NotSupportedException>(() => set.Remove(1));
            Assert.True(set.IsReadOnly);
        }

        [Fact]
        public void ICollectionMethods()
        {
            ICollection builder = (ICollection)this.Empty<string>();
            string[] array = Array.Empty<string>();
            builder.CopyTo(array, 0);

            builder = (ICollection)this.Empty<string>().Add("a");
            array = new string[builder.Count + 1];

            builder.CopyTo(array, 1);
            Assert.Equal(new[] { null, "a" }, array);

            Assert.True(builder.IsSynchronized);
            Assert.NotNull(builder.SyncRoot);
            Assert.Same(builder.SyncRoot, builder.SyncRoot);
        }

        [Fact]
        public void NullHandling()
        {
            var empty = this.Empty<string?>();
            var set = empty.Add(null);
            Assert.True(set.Contains(null));
            Assert.True(set.TryGetValue(null, out var @null));
            Assert.Null(@null);
            Assert.Equal(empty, set.Remove(null));

            set = empty.Union(new[] { null, "a" });
            Assert.True(set.IsSupersetOf(new[] { null, "a" }));
            Assert.True(set.IsSubsetOf(new[] { null, "a" }));
            Assert.True(set.IsProperSupersetOf(new[] { (string?)null }));
            Assert.True(set.IsProperSubsetOf(new[] { null, "a", "b" }));
            Assert.True(set.Overlaps(new[] { null, "b" }));
            Assert.True(set.SetEquals(new[] { null, null, "a", "a" }));

            set = set.Intersect(new[] { (string?)null });
            Assert.Equal(1, set.Count);

            set = set.Except(new[] { (string?)null });
            Assert.False(set.Contains(null));
        }

        protected abstract bool IncludesGetHashCodeDerivative { get; }

        internal static List<T> ToListNonGeneric<T>(System.Collections.IEnumerable sequence)
        {
            Assert.NotNull(sequence);

            var list = new List<T>();
            var enumerator = sequence.GetEnumerator();
            while (enumerator.MoveNext())
            {
                list.Add((T)enumerator.Current);
            }

            return list;
        }

        protected abstract System.Collections.Immutable.IImmutableSet<T> Empty<T>();

        protected abstract ISet<T> EmptyMutable<T>();

        protected System.Collections.Immutable.IImmutableSet<T> SetWith<T>(params T[] items)
        {
            return this.Empty<T>().Union(items);
        }

        protected static void CustomSortTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> emptySet, bool matchOrder, T[] injectedValues, T[] expectedValues)
        {
            Assert.NotNull(emptySet);
            Assert.NotNull(injectedValues);
            Assert.NotNull(expectedValues);

            var set = emptySet;
            foreach (T value in injectedValues)
            {
                set = set.Add(value);
            }

            Assert.Equal(expectedValues.Length, set.Count);
            if (matchOrder)
            {
                Assert.Equal<T>(expectedValues, set.ToList());
            }
            else
            {
                CollectionAssertAreEquivalent(expectedValues, set.ToList());
            }
        }

        /// <summary>
        /// Tests various aspects of a set.  This should be called only from the unordered or sorted overloads of this method.
        /// </summary>
        /// <typeparam name="T">The type of element stored in the set.</typeparam>
        /// <param name="emptySet">The empty set.</param>
        protected static void EmptyTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> emptySet)
        {
            Assert.NotNull(emptySet);

            Assert.Equal(0, emptySet.Count); //, "Empty set should have a Count of 0");
            Assert.Equal(0, emptySet.Count()); //, "Enumeration of an empty set yielded elements.");
            Assert.True(IsSame(emptySet, emptySet.Clear()));
        }

        private IEnumerable<SetTriad> GetSetEqualsScenarios()
        {
            return new List<SetTriad>
            {
                new SetTriad(SetWith<int>(), Array.Empty<int>(), true),
                new SetTriad(SetWith<int>(5), new int[] { 5 }, true),
                new SetTriad(SetWith<int>(5), new int[] { 5, 5 }, true),
                new SetTriad(SetWith<int>(5, 8), new int[] { 5, 5 }, false),
                new SetTriad(SetWith<int>(5, 8), new int[] { 5, 7 }, false),
                new SetTriad(SetWith<int>(5, 8), new int[] { 5, 8 }, true),
                new SetTriad(SetWith<int>(5), Array.Empty<int>(), false),
                new SetTriad(SetWith<int>(), new int[] { 5 }, false),
                new SetTriad(SetWith<int>(5, 8), new int[] { 5 }, false),
                new SetTriad(SetWith<int>(5), new int[] { 5, 8 }, false),
                new SetTriad(SetWith<int>(5, 8), SetWith<int>(5, 8), true),
            };
        }

        private static IEnumerable<SetTriad> GetIsProperSubsetOfScenarios()
        {
            return new List<SetTriad>
            {
                new SetTriad(Array.Empty<int>(), Array.Empty<int>(), false),
                new SetTriad(new int[] { 1 }, Array.Empty<int>(), false),
                new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
                new SetTriad(Array.Empty<int>(), new int[] { 1 }, true),
            };
        }

        private static IEnumerable<SetTriad> GetIsSubsetOfScenarios()
        {
            var results = new List<SetTriad>
            {
                new SetTriad(Array.Empty<int>(), Array.Empty<int>(), true),
                new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
                new SetTriad(new int[] { 1, 2 }, new int[] { 1, 2 }, true),
                new SetTriad(new int[] { 1 }, Array.Empty<int>(), false),
                new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
            };

            // By definition, any proper subset is also a subset.
            // But because a subset may not be a proper subset, we filter the proper- scenarios.
            results.AddRange(GetIsProperSubsetOfScenarios().Where(s => s.Item3));
            return results;
        }

        private static IEnumerable<SetTriad> GetOverlapsScenarios()
        {
            return new List<SetTriad>
            {
                new SetTriad(Array.Empty<int>(), Array.Empty<int>(), false),
                new SetTriad(Array.Empty<int>(), new int[] { 1 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 2 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 2, 3 }, false),
                new SetTriad(new int[] { 1, 2 }, new int[] { 3 }, false),
                new SetTriad(new int[] { 1 }, new int[] { 1, 2 }, true),
                new SetTriad(new int[] { 1, 2 }, new int[] { 1 }, true),
                new SetTriad(new int[] { 1 }, new int[] { 1 }, true),
                new SetTriad(new int[] { 1, 2 }, new int[] { 2, 3, 4 }, true),
            };
        }

        private void SetCompareTestHelper<T>(Func<System.Collections.Immutable.IImmutableSet<T>, Func<IEnumerable<T>, bool>> operation, Func<ISet<T>, Func<IEnumerable<T>, bool>> baselineOperation, IEnumerable<Tuple<IEnumerable<T>, IEnumerable<T>, bool>> scenarios)
        {
            //const string message = "Scenario #{0}: Set 1: {1}, Set 2: {2}";

            int iteration = 0;
            foreach (var scenario in scenarios)
            {
                iteration++;

                // Figure out the response expected based on the BCL mutable collections.
                var baselineSet = this.EmptyMutable<T>();
                baselineSet.UnionWith(scenario.Item1);
                var expectedFunc = baselineOperation(baselineSet);
                bool expected = expectedFunc(scenario.Item2);
                Assert.Equal(expected, scenario.Item3); //, "Test scenario has an expected result that is inconsistent with BCL mutable collection behavior.");

                var actualFunc = operation(this.SetWith(scenario.Item1.ToArray()));
                var args = new object[] { iteration, ToStringDeferred(scenario.Item1), ToStringDeferred(scenario.Item2) };
                Assert.Equal(scenario.Item3, actualFunc(this.SetWith(scenario.Item2.ToArray()))); //, message, args);
                Assert.Equal(scenario.Item3, actualFunc(scenario.Item2)); //, message, args);
            }
        }

        private static Tuple<IEnumerable<T>, IEnumerable<T>, bool> Flip<T>(Tuple<IEnumerable<T>, IEnumerable<T>, bool> scenario)
        {
            return new Tuple<IEnumerable<T>, IEnumerable<T>, bool>(scenario.Item2, scenario.Item1, scenario.Item3);
        }

        private static void RemoveTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> set, params T[] values)
        {
            Assert.NotNull(set);
            Assert.NotNull(values);

            Assert.True(IsSame(set, set.Except(Enumerable.Empty<T>())));

            int initialCount = set.Count;
            int removedCount = 0;
            foreach (T value in values)
            {
                var nextSet = set.Remove(value);
                Assert.NotSame(set, nextSet);
                Assert.Equal(initialCount - removedCount, set.Count);
                Assert.Equal(initialCount - removedCount - 1, nextSet.Count);

                Assert.True(IsSame(nextSet, nextSet.Remove(value))); //, "Removing a non-existing element should not change the set reference.");
                removedCount++;
                set = nextSet;
            }

            Assert.Equal(initialCount - removedCount, set.Count);
        }

        private static void AddRemoveLoadTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> set, T[] data)
        {
            Assert.NotNull(set);
            Assert.NotNull(data);

            foreach (T value in data)
            {
                var newSet = set.Add(value);
                Assert.NotSame(set, newSet);
                set = newSet;
            }

            foreach (T value in data)
            {
                Assert.True(set.Contains(value));
            }

            foreach (T value in data)
            {
                var newSet = set.Remove(value);
                Assert.NotSame(set, newSet);
                set = newSet;
            }
        }

        protected static void EnumeratorTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> emptySet, IComparer<T>? comparer, params T[] values)
        {
            var set = emptySet;
            foreach (T value in values)
            {
                set = set.Add(value);
            }

            var nonGenericEnumerableList = ToListNonGeneric<T>(set);
            CollectionAssertAreEquivalent(nonGenericEnumerableList, values);

            var list = set.ToList();
            CollectionAssertAreEquivalent(list, values);

            if (comparer != null)
            {
                Array.Sort(values, comparer);
                Assert.Equal<T>(values, list);
            }

            // Apply some less common uses to the enumerator to test its metal.
            IEnumerator<T> enumerator;
            using (enumerator = set.GetEnumerator())
            {
                Assert.Equal(default, enumerator.Current);
                enumerator.Reset(); // reset isn't usually called before MoveNext
                Assert.Equal(default, enumerator.Current);
                ManuallyEnumerateTest(list, enumerator);
                Assert.False(enumerator.MoveNext()); // call it again to make sure it still returns false

                enumerator.Reset();
                Assert.Equal(default, enumerator.Current);
                ManuallyEnumerateTest(list, enumerator);
                Assert.Equal(default, enumerator.Current);

                // this time only partially enumerate
                enumerator.Reset();
                enumerator.MoveNext();
                enumerator.Reset();
                ManuallyEnumerateTest(list, enumerator);
            }

            enumerator.Reset();
            Assert.True(enumerator.MoveNext());
            Assert.Equal(set.First(), enumerator.Current);
        }

        private static void AddTestHelper<T>(System.Collections.Immutable.IImmutableSet<T> set, params T[] values)
        {
            Assert.NotNull(set);
            Assert.NotNull(values);

            Assert.True(IsSame(set, set.Union(Enumerable.Empty<T>())));

            int initialCount = set.Count;

            var uniqueValues = new HashSet<T>(values);
            var enumerateAddSet = set.Union(values);
            Assert.Equal(initialCount + uniqueValues.Count, enumerateAddSet.Count);
            foreach (T value in values)
            {
                Assert.True(enumerateAddSet.Contains(value));
            }

            int addedCount = 0;
            foreach (T value in values)
            {
                bool duplicate = set.Contains(value);
                var nextSet = set.Add(value);
                Assert.True(nextSet.Count > 0);
                Assert.Equal(initialCount + addedCount, set.Count);
                int expectedCount = initialCount + addedCount;
                if (!duplicate)
                {
                    expectedCount++;
                }
                Assert.Equal(expectedCount, nextSet.Count);
                Assert.Equal(duplicate, set.Contains(value));
                Assert.True(nextSet.Contains(value));
                if (!duplicate)
                {
                    addedCount++;
                }

                // Next assert temporarily disabled because Roslyn's set doesn't follow this rule.
                Assert.True(IsSame(nextSet, nextSet.Add(value))); //, "Adding duplicate value {0} should keep the original reference.", value);
                set = nextSet;
            }
        }
    }
}


text:
<script type="text/javascript">//<![CDATA[
$(function() {
    // Default to One-time costs
    // Hide the Running Cost inputs
    $("#lms_item_monthly_cost__row").hide();
    $("#lms_item_minute_cost__row").hide();
    $("#lms_item_megabyte_cost__row").hide();

    // When the Cost type changes:
	$("select[name='cost_type']").change(function() {
		// What is the new cost type?
        cost_type=$(this).val();
        if (cost_type==2) {
            // Hide the Category
            $("#lms_item_category_type__row").hide();
            // Hide the Unit Cost input
            $("#lms_item_unit_cost__row").hide();
            // Show the Running Cost inputs
            $("#lms_item_monthly_cost__row").show();
            $("#lms_item_minute_cost__row").show();
            $("#lms_item_megabyte_cost__row").show();
        } else if (cost_type==1) {
            // Hide the Running Cost inputs
            $("#lms_item_monthly_cost__row").hide();
            $("#lms_item_minute_cost__row").hide();
            $("#lms_item_megabyte_cost__row").hide();
            // Show the Category & Unit Cost input
            $("#lms_item_category_type__row").show();
            $("#lms_item_unit_cost__row").show();
        }
	})

    // Set unused values before submitting form
    $("input[type='submit']:last").click(function(event){
        // What is the final cost type?
        cost_type=$("select[name='cost_type']").val();
        if (cost_type==2) {
            // Set the Category
            $('#lms_item_category_type').val("Running Cost")
            // Set the Unit Cost input
            $('#lms_item_unit_cost').val('0.0')
        } else if (cost_type==1) {
            // Set the Running Cost inputs
            $('#lms_item_monthly_cost').val('0.0')
            $('#lms_item_minute_cost').val('0.0')
            $('#lms_item_megabyte_cost').val('0.0')
        }
        // Pass to RESTlike CRUD controller
        event.default();
        return false;
    })
});
//]]></script>


text:
<?php
require_once 'session.php';
require_once 'functions.php';
require_once 'connect.php';

if(!isset($_SESSION['id'])){ // The user must be logged in
  ecvdphp\redirect('login.php');
}

$message = "";
if($_SERVER['REQUEST_METHOD'] === "POST"){
  $newUsername = ($_POST['username'] != null) ? trim($_POST['username']) : "";
  $newEmail = ($_POST['email'] != null) ? trim($_POST['email']) : "";
  $newPassword = ($_POST['password'] != null) ? trim($_POST['password']) : "";
  $newDescription = trim($_POST['description']);

  if($newPassword != ""){
    $stmt = $conn->prepare("UPDATE users SET password = :password WHERE id=:id");
    $stmt->bindParam(':password', password_hash($newPassword, PASSWORD_BCRYPT));
    $stmt->bindParam(':id', $_SESSION['id']);
  } else {
    $stmt = $conn->prepare("UPDATE users SET username = :username, email = :email, description = :description WHERE id=:id");
    $stmt->bindParam(':username', $newUsername);
    $stmt->bindParam(':email', $newEmail);
    $stmt->bindParam(':description', $newDescription);
    $stmt->bindParam(':id', $_SESSION['id']);
  }
  if(!$stmt->execute()){

  }
}

$result = $conn->query("SELECT id, username, email, description,image_id FROM users WHERE id=" . $_SESSION['id'])->fetchAll();
$user = $result[0];
if($user['image_id'] != null){
  $resultImage = $conn->query("SELECT * FROM files WHERE id=" . $user['image_id'])->fetchAll();
  $image = $resultImage[0];
}

include 'header.php';
?>

    <form method="post" action="">
      <fieldset>
        <legend>Your profile</legend>

          Username :
          <input name="username" type="text" id="username" value="<?php echo $user['username']; ?>"/>

          Email :
          <input name="email" type="text" id="email" value="<?php echo $user['email']; ?>"/>

          Password :
          <input name="password" type="password" id="password"/>

          Description:
          <textarea name="description" id="description" rows="10" cols="50"><?php echo $user['description']; ?></textarea>

      </fieldset>

        <input type="submit" value="Update" />

    </form>
    <form enctype="multipart/form-data" action="upload.php" method="post">
      <fieldset>
        <legend>Your personal information</legend>

          <?php
            if(isset($image)){
              echo '
          Picture :
          <input name="filedata" type="file" />
          <input type="submit" value="Send file" />

      </fieldset>
    </form>
    Delete your account now!

<?php
include 'footer.php';
?>


text:
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using JCG = J2N.Collections.Generic;

namespace Lucene.Net.Analysis
{

    /// <summary>
    /// The purpose of this charfilter is to send offsets out of bounds
    /// if the analyzer doesn't use <see cref="CharFilter.CorrectOffset(int)"/> or does incorrect offset math.
    /// </summary>
    public class MockCharFilter : CharFilter
    {
        internal readonly int remainder;

        // for testing only
        public MockCharFilter(TextReader @in, int remainder)
            : base(@in)
        {
            // TODO: instead of fixed remainder... maybe a fixed
            // random seed?
            this.remainder = remainder;
            if (remainder < 0 || remainder >= 10)
            {
                throw new ArgumentOutOfRangeException(nameof(remainder), "invalid remainder parameter (must be 0..10): " + remainder); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
            }
        }

        // for testing only, uses a remainder of 0
        public MockCharFilter(TextReader @in)
            : this(@in, 0)
        { }

        internal int currentOffset = -1;
        internal int delta = 0;
        internal int bufferedCh = -1;

        public override int Read()
        {
            // we have a buffered character, add an offset correction and return it
            if (bufferedCh >= 0)
            {
                int ch = bufferedCh;
                bufferedCh = -1;
                currentOffset++;

                AddOffCorrectMap(currentOffset, delta - 1);
                delta--;
                return ch;
            }

            // otherwise actually read one
            int c = m_input.Read();
            if (c < 0)
            {
                return c;
            }

            currentOffset++;
            if ((c % 10) != remainder || char.IsHighSurrogate((char)c) || char.IsLowSurrogate((char)c))
            {
                return c;
            }

            // we will double this character, so buffer it.
            bufferedCh = c;
            return c;
        }

        public override int Read(char[] cbuf, int off, int len)
        {
            // Java returns -1, maintain compat.
            int numRead = 0;
            for (int i = off; i < off + len; i++)
            {
                int c = Read();
                if (c == -1) break;
                cbuf[i] = (char)c;
                numRead++;
            }
            return numRead == 0 ? -1 : numRead;
        }

        protected override int Correct(int currentOff)
        {
            int ret;
            // LUCENENET NOTE: TryGetPredecessor is equivalent to TreeMap.lowerEntry() in Java
            if (corrections.TryGetPredecessor(currentOff + 1, out KeyValuePair<int, int> lastEntry))
            {
                ret = currentOff + lastEntry.Value;
            }
            else
            {
                ret = currentOff;
            }

            if (Debugging.AssertsEnabled) Debugging.Assert(ret >= 0,"currentOff={0},diff={1}", currentOff, (ret - currentOff));
            return ret;
        }

        protected virtual void AddOffCorrectMap(int off, int cumulativeDiff)
        {
            corrections[off] = cumulativeDiff;
        }

        internal JCG.SortedDictionary<int, int> corrections = new JCG.SortedDictionary<int, int>();
    }
}


text:
<?php

namespace SocialFunding\Core\SharedBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Product
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="SocialFunding\Core\SharedBundle\Repository\ProductRepository")
 */
class Product
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="IntegrationEnginePartner", inversedBy="products")
     * @ORM\JoinColumn(name="integration_engine_partner_id", referencedColumnName="id")
     */
    private $integrationEnginePartner;

    /**
     * @ORM\OneToMany(targetEntity="CampaignProducts", mappedBy="product")
     */
    private $campaignProducts;

    /**
     * @var integer
     *
     * @ORM\Column(name="code", type="integer")
     */
    private $code;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @ORM\Column(name="integration_engine_category_id", type="integer")
     */
    private $integrationEngineCategory;

    /**
     * @var integer
     *
     * @ORM\Column(name="code_manufacturer", type="integer")
     */
    private $codeManufacturer;

    /**
     * @var string
     *
     * @ORM\Column(name="name_manufacturer", type="string", length=255)
     */
    private $nameManufacturer;

    /**
     * @var integer
     *
     * @ORM\Column(name="image_small", type="integer")
     */
    private $imageSmall;

    /**
     * @var integer
     *
     * @ORM\Column(name="image_average", type="integer")
     */
    private $imageAverage;

    /**
     * @var integer
     *
     * @ORM\Column(name="image_big", type="integer")
     */
    private $imageBig;

    /**
     * @var string
     *
     * @ORM\Column(name="keywords", type="string", length=255)
     */
    private $keywords;

    /**
     * @var integer
     *
     * @ORM\Column(name="code_sku", type="integer")
     */
    private $codeSku;

    /**
     * @var float
     *
     * @ORM\Column(name="price_from", type="float")
     */
    private $priceFrom;

    /**
     * @var float
     *
     * @ORM\Column(name="price_to", type="float", nullable=true)
     */
    private $priceTo;

    /**
     * @var boolean
     *
     * @ORM\Column(name="available", type="boolean")
     */
    private $available;

    /**
     * @var boolean
     *
     * @ORM\Column(name="availability", type="integer", nullable=true)
     */
    private $availability;

    /**
     * @var string
     *
     * @ORM\Column(name="specification", type="text", nullable=true)
     */
    private $specification;

    /**
     * @var string
     *
     * @ORM\Column(name="technical_specification", type="text", nullable=true)
     */
    private $technicalSpecification;

    /**
     * @var string
     *
     * @ORM\Column(name="in_database", type="boolean")
     */
    private $inDatabase = false;

    public function __construct()
    {
        $this->campaignProducts = new ArrayCollection();
    }

    /**
     * Set id
     *
     * @return integer
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set integrationEnginePartner
     *
     * @param \stdClass $integrationEnginePartner
     * @return Product
     */
    public function setIntegrationEnginePartner($integrationEnginePartner)
    {
        $this->integrationEnginePartner = $integrationEnginePartner;

        return $this;
    }

    /**
     * Get integrationEnginePartner
     *
     * @return \stdClass
     */
    public function getIntegrationEnginePartner()
    {
        return $this->integrationEnginePartner;
    }

    /**
     * Set code
     *
     * @param integer $code
     * @return Product
     */
    public function setCode($code)
    {
        $this->code = $code;

        return $this;
    }

    /**
     * Get code
     *
     * @return integer
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set codeManufacturer
     *
     * @param integer $codeManufacturer
     * @return Product
     */
    public function setCodeManufacturer($codeManufacturer)
    {
        $this->codeManufacturer = $codeManufacturer;

        return $this;
    }

    /**
     * Get codeManufacturer
     *
     * @return integer
     */
    public function getCodeManufacturer()
    {
        return $this->codeManufacturer;
    }

    /**
     * Set nameManufacturer
     *
     * @param string $nameManufacturer
     * @return Product
     */
    public function setNameManufacturer($nameManufacturer)
    {
        $this->nameManufacturer = $nameManufacturer;

        return $this;
    }

    /**
     * Get nameManufacturer
     *
     * @return string
     */
    public function getNameManufacturer()
    {
        return $this->nameManufacturer;
    }

    /**
     * Set imageSmall
     *
     * @param integer $imageSmall
     * @return Product
     */
    public function setImageSmall($imageSmall)
    {
        $this->imageSmall = $imageSmall;

        return $this;
    }

    /**
     * Get imageSmall
     *
     * @return integer
     */
    public function getImageSmall()
    {
        return $this->imageSmall;
    }

    /**
     * Set imageAverage
     *
     * @param integer $imageAverage
     * @return Product
     */
    public function setImageAverage($imageAverage)
    {
        $this->imageAverage = $imageAverage;

        return $this;
    }

    /**
     * Get imageAverage
     *
     * @return integer
     */
    public function getImageAverage()
    {
        return $this->imageAverage;
    }

    /**
     * Set imageBig
     *
     * @param integer $imageBig
     * @return Product
     */
    public function setImageBig($imageBig)
    {
        $this->imageBig = $imageBig;

        return $this;
    }

    /**
     * Get imageBig
     *
     * @return integer
     */
    public function getImageBig()
    {
        return $this->imageBig;
    }

    /**
     * Set keywords
     *
     * @param string $keywords
     * @return Product
     */
    public function setKeywords($keywords)
    {
        $this->keywords = $keywords;

        return $this;
    }

    /**
     * Get keywords
     *
     * @return string
     */
    public function getKeywords()
    {
        return $this->keywords;
    }

    /**
     * Set codeSku
     *
     * @param integer $codeSku
     * @return Product
     */
    public function setCodeSku($codeSku)
    {
        $this->codeSku = $codeSku;

        return $this;
    }

    /**
     * Get codeSku
     *
     * @return integer
     */
    public function getCodeSku()
    {
        return $this->codeSku;
    }

    /**
     * Set priceFrom
     *
     * @param float $priceFrom
     * @return Product
     */
    public function setPriceFrom($priceFrom)
    {
        $this->priceFrom = $priceFrom;

        return $this;
    }

    /**
     * Get priceFrom
     *
     * @return float
     */
    public function getPriceFrom()
    {
        return $this->priceFrom;
    }

    /**
     * Set priceTo
     *
     * @param float $priceTo
     * @return Product
     */
    public function setPriceTo($priceTo)
    {
        $this->priceTo = $priceTo;

        return $this;
    }

    /**
     * Get priceTo
     *
     * @return float
     */
    public function getPriceTo()
    {
        return $this->priceTo;
    }

    /**
     * Set available
     *
     * @param boolean $available
     * @return Product
     */
    public function setAvailable($available)
    {
        $this->available = $available;

        return $this;
    }

    /**
     * Get available
     *
     * @return boolean
     */
    public function getAvailable()
    {
        return $this->available;
    }

    /**
     * Set available
     *
     * @param boolean $available
     * @return Product
     */
    public function setAvailability($availability)
    {
        $this->availability = $availability;

        return $this;
    }

    /**
     * Get available
     *
     * @return boolean
     */
    public function getAvailability()
    {
        return $this->availability;
    }

    /**
     * Set specification
     *
     * @param string $specification
     * @return Product
     */
    public function setSpecification($specification)
    {
        $this->specification = $specification;

        return $this;
    }

    /**
     * Get specification
     *
     * @return string
     */
    public function getSpecification()
    {
        return $this->specification;
    }

    /**
     * Set technicalSpecification
     *
     * @param string $technicalSpecification
     * @return Product
     */
    public function setTechnicalSpecification($technicalSpecification)
    {
        $this->technicalSpecification = $technicalSpecification;

        return $this;
    }

    /**
     * Get technicalSpecification
     *
     * @return string
     */
    public function getTechnicalSpecification()
    {
        return $this->technicalSpecification;
    }

    /**
     * Set integrationEngineCategory
     *
     * @param \SocialFunding\Core\SharedBundle\Entity\IntegrationEngineCategory $integrationEngineCategory
     * @return Product
     */
    public function setIntegrationEngineCategory($integrationEngineCategory = null)
    {
        $this->integrationEngineCategory = $integrationEngineCategory;

        return $this;
    }

    /**
     * Get integrationEngineCategory
     *
     * @return \SocialFunding\Core\SharedBundle\Entity\IntegrationEngineCategory
     */
    public function getIntegrationEngineCategory()
    {
        return $this->integrationEngineCategory;
    }

    /**
     * Add campaignProducts
     *
     * @param \SocialFunding\Core\SharedBundle\Entity\CampaignProducts $campaignProducts
     * @return Product
     */
    public function addCampaignProduct(\SocialFunding\Core\SharedBundle\Entity\CampaignProducts $campaignProducts)
    {
        $this->campaignProducts[] = $campaignProducts;

        return $this;
    }

    /**
     * Remove campaignProducts
     *
     * @param \SocialFunding\Core\SharedBundle\Entity\CampaignProducts $campaignProducts
     */
    public function removeCampaignProduct(\SocialFunding\Core\SharedBundle\Entity\CampaignProducts $campaignProducts)
    {
        $this->campaignProducts->removeElement($campaignProducts);
    }

    /**
     * Get campaignProducts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCampaignProducts()
    {
        return $this->campaignProducts;
    }

    /**
     * @param string $inDatabase
     */
    public function setInDatabase($inDatabase)
    {
        $this->inDatabase = $inDatabase;
    }

    /**
     * @return string
     */
    public function getInDatabase()
    {
        return $this->inDatabase;
    }

}


text:
using SampleApplication.Resources;

namespace SampleApplication
{
    /// <summary>
    /// Provides access to string resources.
    /// </summary>
    public class LocalizedStrings
    {
        private static AppResources _localizedResources = new AppResources();

        public AppResources LocalizedResources { get { return _localizedResources; } }
    }
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
-- |

module Stack.Types.Package where

import           Control.DeepSeq
import           Control.Exception hiding (try,catch)
import           Control.Monad.Catch
import           Control.Monad.IO.Class
import           Control.Monad.Logger (MonadLogger)
import           Control.Monad.Reader
import           Data.Binary
import           Data.Binary.VersionTagged
import qualified Data.ByteString as S
import           Data.Data
import           Data.Function
import           Data.List
import           Data.Map.Strict (Map)
import           Data.Maybe
import           Data.Monoid
import           Data.Set (Set)
import           Data.Text (Text)
import           Data.Text.Encoding (encodeUtf8)
import           Distribution.InstalledPackageInfo (PError)
import           Distribution.ModuleName (ModuleName)
import           Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier)
import           Distribution.System (Platform (..))
import           GHC.Generics
import           Path as FL
import           Prelude
import           Stack.Types.Compiler
import           Stack.Types.Config
import           Stack.Types.FlagName
import           Stack.Types.PackageName
import           Stack.Types.Version

-- | All exceptions thrown by the library.
data PackageException
  = PackageInvalidCabalFile (Maybe (Path Abs File)) PError
  | PackageNoCabalFileFound (Path Abs Dir)
  | PackageMultipleCabalFilesFound (Path Abs Dir) [Path Abs File]
  | MismatchedCabalName (Path Abs File) PackageName
  deriving Typeable
instance Exception PackageException
instance Show PackageException where
    show (PackageInvalidCabalFile mfile err) =
        "Unable to parse cabal file" ++
        (case mfile of
            Nothing -> ""
            Just file -> ' ' : toFilePath file) ++
        ": " ++
        show err
    show (PackageNoCabalFileFound dir) =
        "No .cabal file found in directory " ++
        toFilePath dir
    show (PackageMultipleCabalFilesFound dir files) =
        "Multiple .cabal files found in directory " ++
        toFilePath dir ++
        ": " ++
        intercalate ", " (map (toFilePath . filename) files)
    show (MismatchedCabalName fp name) = concat
        [ "cabal file path "
        , toFilePath fp
        , " does not match the package name it defines.\n"
        , "Please rename the file to: "
        , packageNameString name
        , ".cabal\n"
        , "For more information, see: https://github.com/commercialhaskell/stack/issues/317"
        ]

-- | Some package info.
data Package =
  Package {packageName :: !PackageName                    -- ^ Name of the package.
          ,packageVersion :: !Version                     -- ^ Version of the package
          ,packageFiles :: !GetPackageFiles               -- ^ Get all files of the package.
          ,packageDeps :: !(Map PackageName VersionRange) -- ^ Packages that the package depends on.
          ,packageTools :: ![Dependency]                  -- ^ A build tool name.
          ,packageAllDeps :: !(Set PackageName)           -- ^ Original dependencies (not sieved).
          ,packageFlags :: !(Map FlagName Bool)           -- ^ Flags used on package.
          ,packageHasLibrary :: !Bool                     -- ^ does the package have a buildable library stanza?
          ,packageTests :: !(Set Text)                    -- ^ names of test suites
          ,packageBenchmarks :: !(Set Text)               -- ^ names of benchmarks
          ,packageExes :: !(Set Text)                     -- ^ names of executables
          ,packageOpts :: !GetPackageOpts                 -- ^ Args to pass to GHC.
          ,packageHasExposedModules :: !Bool              -- ^ Does the package have exposed modules?
          ,packageSimpleType :: !Bool                     -- ^ Does the package of build-type: Simple
          ,packageDefinedFlags :: !(Set FlagName)         -- ^ All flags defined in the .cabal file
          }
 deriving (Show,Typeable)

-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageOpts = GetPackageOpts
    { getPackageOpts :: forall env m. (MonadIO m,HasEnvConfig env, HasPlatform env, MonadThrow m, MonadReader env m)
                     => SourceMap
                     -> [PackageName]
                     -> Path Abs File
                     -> m (Map NamedComponent [String],[String])
    }
instance Show GetPackageOpts where
    show _ = "<GetPackageOpts>"

-- | Files to get for a cabal package.
data CabalFileType
    = AllFiles
    | Modules

-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageFiles = GetPackageFiles
    { getPackageFiles :: forall m env. (MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m, MonadReader env m, HasPlatform env, HasEnvConfig env)
                      => Path Abs File
                      -> m (Map NamedComponent (Set ModuleName)
                           ,Map NamedComponent (Set (Path Abs File))
                           ,Map NamedComponent (Set (Path Abs File))
                           ,Map NamedComponent (Set MainIs)
                           ,Set (Path Abs File))
    }
instance Show GetPackageFiles where
    show _ = "<GetPackageFiles>"

-- | A file specified as @main-is@ in a .cabal file.
newtype MainIs = MainIs
    { mainIsFile :: Path Abs File
    }
  deriving (Ord,Eq)

-- | Package build configuration
data PackageConfig =
  PackageConfig {packageConfigEnableTests :: !Bool                -- ^ Are tests enabled?
                ,packageConfigEnableBenchmarks :: !Bool           -- ^ Are benchmarks enabled?
                ,packageConfigFlags :: !(Map FlagName Bool)       -- ^ Package config flags.
                ,packageConfigCompilerVersion :: !CompilerVersion -- ^ GHC version
                ,packageConfigPlatform :: !Platform               -- ^ host platform
                }
 deriving (Show,Typeable)

-- | Compares the package name.
instance Ord Package where
  compare = on compare packageName

-- | Compares the package name.
instance Eq Package where
  (==) = on (==) packageName

type SourceMap = Map PackageName PackageSource

-- | Where the package's source is located: local directory or package index
data PackageSource
    = PSLocal LocalPackage
    | PSUpstream Version InstallLocation (Map FlagName Bool)
    -- ^ Upstream packages could be installed in either local or snapshot
    -- databases; this is what 'InstallLocation' specifies.
    deriving Show

instance PackageInstallInfo PackageSource where
    piiVersion (PSLocal lp) = packageVersion $ lpPackage lp
    piiVersion (PSUpstream v _ _) = v

    piiLocation (PSLocal _) = Local
    piiLocation (PSUpstream _ loc _) = loc

-- | Datatype which tells how which version of a package to install and where
-- to install it into
class PackageInstallInfo a where
    piiVersion :: a -> Version
    piiLocation :: a -> InstallLocation

-- | Second-stage build information: tests and benchmarks
data LocalPackageTB = LocalPackageTB
    { lptbPackage :: !Package
    -- ^ Package resolved with dependencies for tests and benchmarks, depending
    -- on which components are active
    , lptbTests   :: !(Set Text)
    -- ^ Test components
    , lptbBenches :: !(Set Text)
    -- ^ Benchmark components
    }
    deriving Show

-- | Information on a locally available package of source code
data LocalPackage = LocalPackage
    { lpPackage        :: !Package         -- ^ The @Package@ info itself, after resolution with package flags, not including any tests or benchmarks
    , lpTestDeps       :: !(Map PackageName VersionRange)
    -- ^ Used for determining if we can use --enable-tests in a normal build
    , lpBenchDeps      :: !(Map PackageName VersionRange)
    -- ^ Used for determining if we can use --enable-benchmarks in a normal build
    , lpExeComponents  :: !(Maybe (Set Text)) -- ^ Executable components to build, Nothing if not a target

    , lpTestBench      :: !(Maybe LocalPackageTB)

    , lpDir            :: !(Path Abs Dir)  -- ^ Directory of the package.
    , lpCabalFile      :: !(Path Abs File) -- ^ The .cabal file
    , lpDirtyFiles     :: !Bool            -- ^ are there files that have changed since the last build?
    , lpNewBuildCache  :: !(Map FilePath FileCacheInfo) -- ^ current state of the files
    , lpFiles          :: !(Set (Path Abs File)) -- ^ all files used by this package
    , lpComponents     :: !(Set NamedComponent)
    }
    deriving Show

-- | Is the given local a target
lpWanted :: LocalPackage -> Bool
lpWanted lp = isJust (lpExeComponents lp) || isJust (lpTestBench lp)

-- | A single, fully resolved component of a package
data NamedComponent
    = CLib
    | CExe !Text
    | CTest !Text
    | CBench !Text
    deriving (Show, Eq, Ord)

renderComponent :: NamedComponent -> S.ByteString
renderComponent CLib = "lib"
renderComponent (CExe x) = "exe:" <> encodeUtf8 x
renderComponent (CTest x) = "test:" <> encodeUtf8 x
renderComponent (CBench x) = "bench:" <> encodeUtf8 x

-- | A location to install a package into, either snapshot or local
data InstallLocation = Snap | Local
    deriving (Show, Eq)
instance Monoid InstallLocation where
    mempty = Snap
    mappend Local _ = Local
    mappend _ Local = Local
    mappend Snap Snap = Snap

data FileCacheInfo = FileCacheInfo
    { fciModTime :: !ModTime
    , fciSize :: !Word64
    , fciHash :: !S.ByteString
    }
    deriving (Generic, Show)
instance Binary FileCacheInfo
instance NFData FileCacheInfo where
    rnf = genericRnf

-- | Used for storage and comparison.
newtype ModTime = ModTime (Integer,Rational)
  deriving (Ord,Show,Generic,Eq,NFData,Binary)


text:
package org.jboss.as.quickstarts.kitchensink.rest;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.as.quickstarts.kitchensink.data.MemberRepository;
import org.jboss.as.quickstarts.kitchensink.model.Member;
import org.jboss.as.quickstarts.kitchensink.service.MemberRegistration;

/**
 * JAX-RS Example
 *

 * This class produces a RESTful service to read/write the contents of the members table.
 */
@Path("/members")
@RequestScoped
public class MemberResourceRESTService {

    @Inject
    private Validator validator;

    @Inject
    private MemberRepository repository;

    @Inject
    private MemberRegistration registration;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Member> listAllMembers() {
        return repository.findAllOrderedByName();
    }

    @GET
    @Path("/{id:[0-9][0-9]*}")
    @Produces(MediaType.APPLICATION_JSON)
    public Member lookupMemberById(@PathParam("id") long id) {
        Member member = repository.findById(id);
        if (member == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return member;
    }

    /**
     * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
     * or with a map of fields, and related errors.
     * @throws Exception
     */
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createMember(Member member) throws Exception {

        // Validates member using bean validation
        validateMember(member);

        registration.register(member);

        // Create an "ok" response
        return Response.ok().build();
    }

    /**
     *

     * Validates the given Member variable and throws validation exceptions based on the type of error. If the error is standard
     * bean validation errors then it will throw a ConstraintValidationException with the set of the constraints violated.
     *

     *

     * If the error is caused because an existing member with the same email is registered it throws a regular validation
     * exception so that it can be interpreted separately.
     *

     *
     * @param member Member to be validated
     * @throws ConstraintViolationException If Bean Validation errors exist
     * @throws ValidationException If member with the same email already exists
     */
    private void validateMember(Member member) throws ConstraintViolationException, ValidationException {
        // Create a bean validator and check for issues.
        Set<ConstraintViolation<Member>> violations = validator.validate(member);

        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
        }

        // Check the uniqueness of the email address
        if (emailAlreadyExists(member.getEmail())) {
            throw new ValidationException("Unique Email Violation");
        }
    }

    /**
     * Checks if a member with the same email address is already registered. This is the only way to easily capture the
     * "@UniqueConstraint(columnNames = "email")" constraint from the Member class.
     *
     * @param email The email to check
     * @return True if the email already exists, and false otherwise
     */
    public boolean emailAlreadyExists(String email) {
        Member member = null;
        try {
            member = repository.findByEmail(email);
        } catch (NoResultException e) {
            // ignore
        }
        return member != null;
    }
}


text:
#include "setup.h"

#include <stdio.h>
#include <string.h>

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#include <curl/curl.h>

#define _MPRINTF_REPLACE /* we want curl-functions instead of native ones */
#include <curl/mprintf.h>

#include "writeout.h"

typedef enum {
  VAR_NONE,       /* must be the first */
  VAR_TOTAL_TIME,
  VAR_NAMELOOKUP_TIME,
  VAR_CONNECT_TIME,
  VAR_PRETRANSFER_TIME,
  VAR_STARTTRANSFER_TIME,
  VAR_SIZE_DOWNLOAD,
  VAR_SIZE_UPLOAD,
  VAR_SPEED_DOWNLOAD,
  VAR_SPEED_UPLOAD,
  VAR_HTTP_CODE,
  VAR_HEADER_SIZE,
  VAR_REQUEST_SIZE,
  VAR_EFFECTIVE_URL,
  VAR_CONTENT_TYPE,
  VAR_NUM_OF_VARS /* must be the last */
} replaceid;

struct variable {
  const char *name;
  replaceid id;
};

static struct variable replacements[]={
  {"url_effective", VAR_EFFECTIVE_URL},
  {"http_code", VAR_HTTP_CODE},
  {"time_total", VAR_TOTAL_TIME},
  {"time_namelookup", VAR_NAMELOOKUP_TIME},
  {"time_connect", VAR_CONNECT_TIME},
  {"time_pretransfer", VAR_PRETRANSFER_TIME},
  {"time_starttransfer", VAR_STARTTRANSFER_TIME},
  {"size_header", VAR_HEADER_SIZE},
  {"size_request", VAR_REQUEST_SIZE},
  {"size_download", VAR_SIZE_DOWNLOAD},
  {"size_upload", VAR_SIZE_UPLOAD},
  {"speed_download", VAR_SPEED_DOWNLOAD},
  {"speed_upload", VAR_SPEED_UPLOAD},
  {"content_type", VAR_CONTENT_TYPE},
  {NULL, VAR_NONE}
};

void ourWriteOut(CURL *curl, char *writeinfo)
{
  FILE *stream = stdout;
  char *ptr=writeinfo;
  char *stringp;
  long longinfo;
  double doubleinfo;

  while(*ptr) {
    if('%' == *ptr) {
      if('%' == ptr[1]) {
        /* an escaped %-letter */
        fputc('%', stream);
        ptr+=2;
      }
      else {
        /* this is meant as a variable to output */
        char *end;
        char keepit;
        int i;
        if(('{' == ptr[1]) && (end=strchr(ptr, '}'))) {
          ptr+=2; /* pass the % and the { */
          keepit=*end;
          *end=0; /* zero terminate */
          for(i=0; replacements[i].name; i++) {
            if(curl_strequal(ptr, replacements[i].name)) {
              switch(replacements[i].id) {
              case VAR_EFFECTIVE_URL:
                if((CURLE_OK ==
                    curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &stringp))
                   && stringp)
                  fputs(stringp, stream);
                break;
              case VAR_HTTP_CODE:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &longinfo))
                  fprintf(stream, "%03ld", longinfo);
                break;
              case VAR_HEADER_SIZE:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &longinfo))
                  fprintf(stream, "%ld", longinfo);
                break;
              case VAR_REQUEST_SIZE:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &longinfo))
                  fprintf(stream, "%ld", longinfo);
                break;
              case VAR_TOTAL_TIME:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_NAMELOOKUP_TIME:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME,
                                     &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_CONNECT_TIME:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_PRETRANSFER_TIME:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_STARTTRANSFER_TIME:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_STARTTRANSFER_TIME, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_SIZE_UPLOAD:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &doubleinfo))
                  fprintf(stream, "%.0f", doubleinfo);
                break;
              case VAR_SIZE_DOWNLOAD:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &doubleinfo))
                  fprintf(stream, "%.0f", doubleinfo);
                break;
              case VAR_SPEED_DOWNLOAD:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_SPEED_UPLOAD:
                if(CURLE_OK ==
                   curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &doubleinfo))
                  fprintf(stream, "%.3f", doubleinfo);
                break;
              case VAR_CONTENT_TYPE:
                if((CURLE_OK ==
                    curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &stringp))
                   && stringp)
                  fputs(stringp, stream);
                break;
              default:
                /* -Wunreachable-code wrongly complains on this */
                break;
              }
              break;
            }
          }
          ptr=end+1; /* pass the end */
          *end = keepit;
        }
        else {
          /* illegal syntax, then just output the characters that are used */
          fputc('%', stream);
          fputc(ptr[1], stream);
          ptr+=2;
        }
      }
    }
    else if('\\' == *ptr) {
      switch(ptr[1]) {
      case 'r':
        fputc('\r', stream);
        break;
      case 'n':
        fputc('\n', stream);
        break;
      case 't':
        fputc('\t', stream);
        break;
      default:
        /* unknown, just output this */
        fputc(*ptr, stream);
        fputc(ptr[1], stream);
        break;
      }
      ptr+=2;
    }
    else {
      fputc(*ptr, stream);
      ptr++;
    }
  }

}


text:
<?php
require_once('../tcpdf/config/lang/eng.php');
require_once('../tcpdf/tcpdf.php');

$Titlu = $_REQUEST["docName"];
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator('SignME');
$pdf->SetAuthor('SignME');
$pdf->SetTitle($Titlu);
//$pdf->SetSubject('TCPDF Tutorial');
//$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
// $pdf->SetHeaderData("nova/nova_logo.PNG", PDF_HEADER_LOGO_WIDTH-5, $Titlu, "\nhttp://www.novaintermed.ro/");

// set header and footer fonts
// $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
// $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
$pdf->setLanguageArray($l);

// ---------------------------------------------------------

/*
NOTES:
 - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
 - To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
 - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
*/

// set certificate file
//$certificate = 'file://../tcpdf/tcpdf.crt';

// set additional information
/*$info = array(
	'Name' => 'TCPDF',
	'Location' => 'Office',
	'Reason' => 'Testing TCPDF',
	'ContactInfo' => 'http://www.tcpdf.org',
	);
*/
// set document signature
//$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2, $info);

// set font
$pdf->SetFont('helvetica', '', 10);

// add a page
$pdf->AddPage();

// print a line of text
//$postData = json_decode($HTTP_RAW_POST_DATA);
//$html = $postData["bodyHTML"];

$html = $_REQUEST['bodyHTML'];
$pdf->writeHTML($html, true, false, true,false, '');

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// *** set signature appearance ***

// create content for signature (image and/or text)
//$pdf->Image('../tcpdf/images/tcpdf_signature.png', 180, 60, 15, 15, 'PNG');

// define active area for signature appearance
//$pdf->setSignatureAppearance(180, 60, 15, 15);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// *** set an empty signature appearance ***
//$pdf->addEmptySignatureAppearance(180, 80, 15, 15);

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output('../data/PDF/'.$_GET["user"].'/'.$_REQUEST["docName"].'.pdf', 'F');

//============================================================+
// END OF FILE
//============================================================+


text:
package no.deichman.labelpdf;

/**
 * Responsibility: provide field types & parameters for label fields.
 */
enum FieldType {
    TITLE(25),
    CREATOR(25),
    CALLNUMER(15);

    private final int maxlength;

    FieldType(int maxlength) {
        this.maxlength = maxlength;
    }

    public final int maxlength() {
        return maxlength;
    }
}


text:
package org.zstack.network.service.vip;

/**
 */
public interface VipBackend {
    String getServiceProviderTypeForVip();
}


text:
module FormHelper
  def form_errors(record)
    return if record.errors.blank?

    content_tag(:ul, class: 'list-group') do
      record.errors.full_messages.map { |error|
        content_tag(:li, class: 'list-group-item list-group-item-danger') do
          error
        end
      }.join("\n").html_safe
    end
  end
end


text:
<?php

/*
CREATE TABLE tt_lessons (
	id INT NOT NULL AUTO_INCREMENT,
	activity_id INT NOT NULL,
	period_id INT NOT NULL,
 	room_id INT,
	staff_id INT,

	PRIMARY KEY(id),
	FOREIGN KEY(activity_id) REFERENCES tt_activities(id),
	FOREIGN KEY(period_id) REFERENCES tt_periods(id),
	FOREIGN KEY(room_id) REFERENCES tt_rooms(id),
	FOREIGN KEY(staff_id) REFERENCES users(id)
) ENGINE=InnoDB;

*/

class TimetableLesson extends Model
{
	protected static $table_name = TABLENAME_TTLESSON;

	public function getId()
	{
		return $this->get_field('id');
	}

	public function getActivityId()
	{
		return $this->get_field('activity_id');
	}

	public function setActivityId($id)
	{
		$this->set_field('activity_id', $id);
	}

	public function getPeriodId()
	{
		return $this->get_field('period_id');
	}

	public function setPeriodId($id)
	{
		$this->set_field('period_id', $id);
	}

	public function getWeekday()
	{
		return $this->get_field('weekday');
	}

	public function setWeekday($wd)
	{
		$this->set_field('weekday', $wd);
	}

	public function getWeekBlock()
	{
		return $this->get_field('week_block');
	}

	public function setWeekBlock($weekblock)
	{
		$this->set_field('week_block', $weekblock);
	}

	public function getRoomId()
	{
		return $this->get_field('room_id');
	}

	public function setRoomId($id)
	{
		$this->set_field('room_id', $id);
	}

	public function getStaffId()
	{
		return $this->get_field('staff_id');
	}

	public function setStaffId($id)
	{
		$this->set_field('staff_id', $id);
	}
}

?>


text:
void packet_send_entity_properties(struct client *client, const char *property, double value)
{
	bedrock_packet packet;

	packet_init(&packet, SERVER_ENTITY_PROPERTIES);

	packet_pack_varint(&packet, client->id);
	packet_pack_int(&packet, 1);
	packet_pack_string(&packet, property);
	packet_pack_double(&packet, value);
	packet_pack_varint(&packet, 0);

	client_send_packet(client, &packet);
}