text:
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;

namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
    public class ConvertToProviderTypesMySqlTest : ConvertToProviderTypesTestBase<ConvertToProviderTypesMySqlTest.ConvertToProviderTypesMySqlFixture>
    {
        public ConvertToProviderTypesMySqlTest(ConvertToProviderTypesMySqlFixture fixture, ITestOutputHelper testOutputHelper)
            : base(fixture)
        {
            fixture.TestSqlLoggerFactory.Clear();
            //fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
        }

        public override void Can_perform_query_with_ansi_strings_test()
        {
        }

        // TODO: Needed to customize:
        //          `private bool Equal(DateTimeOffset left, DateTimeOffset right)` Recheck/remove once fixed upstream.
        //       Recheck/remove after `https://github.com/dotnet/efcore/issues/26068` has been fixed upstream.
        #region https://github.com/dotnet/efcore/issues/26068

        [ConditionalFact]
        public override void Can_insert_and_read_back_all_non_nullable_data_types()
        {
            using (var context = CreateContext())
            {
                context.Set<BuiltInDataTypes>().Add(
                    new BuiltInDataTypes
                    {
                        Id = 1,
                        PartitionId = 1,
                        TestInt16 = -1234,
                        TestInt32 = -123456789,
                        TestInt64 = -1234567890123456789L,
                        TestDouble = -1.23456789,
                        TestDecimal = -1234567890.01M,
                        TestDateTime = DateTime.Parse("01/01/2000 12:34:56", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal),
                        TestDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                        TestTimeSpan = new TimeSpan(0, 10, 9, 8, 7),
                        TestSingle = -1.234F,
                        TestBoolean = true,
                        TestByte = 255,
                        TestUnsignedInt16 = 1234,
                        TestUnsignedInt32 = 1234565789U,
                        TestUnsignedInt64 = 1234567890123456789UL,
                        TestCharacter = 'a',
                        TestSignedByte = -128,
                        Enum64 = Enum64.SomeValue,
                        Enum32 = Enum32.SomeValue,
                        Enum16 = Enum16.SomeValue,
                        Enum8 = Enum8.SomeValue,
                        EnumU64 = EnumU64.SomeValue,
                        EnumU32 = EnumU32.SomeValue,
                        EnumU16 = EnumU16.SomeValue,
                        EnumS8 = EnumS8.SomeValue
                    });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var dt = context.Set<BuiltInDataTypes>().Where(e => e.Id == 1).ToList().Single();

                var entityType = context.Model.FindEntityType(typeof(BuiltInDataTypes));
                AssertEqualIfMapped(entityType, (short)-1234, () => dt.TestInt16);
                AssertEqualIfMapped(entityType, -123456789, () => dt.TestInt32);
                AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.TestInt64);
                AssertEqualIfMapped(entityType, -1.23456789, () => dt.TestDouble);
                AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.TestDecimal);
                AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal),
                    () => dt.TestDateTime);
                AssertEqualIfMapped(
                    entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                    () => dt.TestDateTimeOffset);
                AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TestTimeSpan);
                AssertEqualIfMapped(entityType, -1.234F, () => dt.TestSingle);
                AssertEqualIfMapped(entityType, true, () => dt.TestBoolean);
                AssertEqualIfMapped(entityType, (byte)255, () => dt.TestByte);
                AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64);
                AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32);
                AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16);
                AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8);
                AssertEqualIfMapped(entityType, (ushort)1234, () => dt.TestUnsignedInt16);
                AssertEqualIfMapped(entityType, 1234565789U, () => dt.TestUnsignedInt32);
                AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.TestUnsignedInt64);
                AssertEqualIfMapped(entityType, 'a', () => dt.TestCharacter);
                AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.TestSignedByte);
                AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64);
                AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32);
                AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16);
                AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8);
            }
        }

        [ConditionalFact]
        public override void Can_insert_and_read_back_non_nullable_backed_data_types()
        {
            using (var context = CreateContext())
            {
                context.Set<NonNullableBackedDataTypes>().Add(
                    new NonNullableBackedDataTypes
                    {
                        Id = 101,
                        PartitionId = 101,
                        Int16 = -1234,
                        Int32 = -123456789,
                        Int64 = -1234567890123456789L,
                        Double = -1.23456789,
                        Decimal = -1234567890.01M,
                        DateTime = DateTime.Parse("01/01/2000 12:34:56"),
                        DateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                        TimeSpan = new TimeSpan(0, 10, 9, 8, 7),
                        Single = -1.234F,
                        Boolean = true,
                        Byte = 255,
                        UnsignedInt16 = 1234,
                        UnsignedInt32 = 1234565789U,
                        UnsignedInt64 = 1234567890123456789UL,
                        Character = 'a',
                        SignedByte = -128,
                        Enum64 = Enum64.SomeValue,
                        Enum32 = Enum32.SomeValue,
                        Enum16 = Enum16.SomeValue,
                        Enum8 = Enum8.SomeValue,
                        EnumU64 = EnumU64.SomeValue,
                        EnumU32 = EnumU32.SomeValue,
                        EnumU16 = EnumU16.SomeValue,
                        EnumS8 = EnumS8.SomeValue
                    });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var dt = context.Set<NonNullableBackedDataTypes>().Where(ndt => ndt.Id == 101).ToList().Single();

                var entityType = context.Model.FindEntityType(typeof(NonNullableBackedDataTypes));
                AssertEqualIfMapped(entityType, (short)-1234, () => dt.Int16);
                AssertEqualIfMapped(entityType, -123456789, () => dt.Int32);
                AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.Int64);
                AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.Int64);
                AssertEqualIfMapped(entityType, -1.23456789, () => dt.Double);
                AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.Decimal);
                AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56"), () => dt.DateTime);
                AssertEqualIfMapped(
                    entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                    () => dt.DateTimeOffset);
                AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TimeSpan);
                AssertEqualIfMapped(entityType, -1.234F, () => dt.Single);
                AssertEqualIfMapped(entityType, true, () => dt.Boolean);
                AssertEqualIfMapped(entityType, (byte)255, () => dt.Byte);
                AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64);
                AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32);
                AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16);
                AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8);
                AssertEqualIfMapped(entityType, (ushort)1234, () => dt.UnsignedInt16);
                AssertEqualIfMapped(entityType, 1234565789U, () => dt.UnsignedInt32);
                AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.UnsignedInt64);
                AssertEqualIfMapped(entityType, 'a', () => dt.Character);
                AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.SignedByte);
                AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64);
                AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32);
                AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16);
                AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8);
            }
        }

        [ConditionalFact]
        public override void Can_insert_and_read_back_nullable_backed_data_types()
        {
            using (var context = CreateContext())
            {
                context.Set<NullableBackedDataTypes>().Add(
                    new NullableBackedDataTypes
                    {
                        Id = 101,
                        PartitionId = 101,
                        Int16 = -1234,
                        Int32 = -123456789,
                        Int64 = -1234567890123456789L,
                        Double = -1.23456789,
                        Decimal = -1234567890.01M,
                        DateTime = DateTime.Parse("01/01/2000 12:34:56"),
                        DateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                        TimeSpan = new TimeSpan(0, 10, 9, 8, 7),
                        Single = -1.234F,
                        Boolean = false,
                        Byte = 255,
                        UnsignedInt16 = 1234,
                        UnsignedInt32 = 1234565789U,
                        UnsignedInt64 = 1234567890123456789UL,
                        Character = 'a',
                        SignedByte = -128,
                        Enum64 = Enum64.SomeValue,
                        Enum32 = Enum32.SomeValue,
                        Enum16 = Enum16.SomeValue,
                        Enum8 = Enum8.SomeValue,
                        EnumU64 = EnumU64.SomeValue,
                        EnumU32 = EnumU32.SomeValue,
                        EnumU16 = EnumU16.SomeValue,
                        EnumS8 = EnumS8.SomeValue
                    });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var dt = context.Set<NullableBackedDataTypes>().Where(ndt => ndt.Id == 101).ToList().Single();

                var entityType = context.Model.FindEntityType(typeof(NullableBackedDataTypes));
                AssertEqualIfMapped(entityType, (short)-1234, () => dt.Int16);
                AssertEqualIfMapped(entityType, -123456789, () => dt.Int32);
                AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.Int64);
                AssertEqualIfMapped(entityType, -1.23456789, () => dt.Double);
                AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.Decimal);
                AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56"), () => dt.DateTime);
                AssertEqualIfMapped(
                    entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                    () => dt.DateTimeOffset);
                AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TimeSpan);
                AssertEqualIfMapped(entityType, -1.234F, () => dt.Single);
                AssertEqualIfMapped(entityType, false, () => dt.Boolean);
                AssertEqualIfMapped(entityType, (byte)255, () => dt.Byte);
                AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64);
                AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32);
                AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16);
                AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8);
                AssertEqualIfMapped(entityType, (ushort)1234, () => dt.UnsignedInt16);
                AssertEqualIfMapped(entityType, 1234565789U, () => dt.UnsignedInt32);
                AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.UnsignedInt64);
                AssertEqualIfMapped(entityType, 'a', () => dt.Character);
                AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.SignedByte);
                AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64);
                AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32);
                AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16);
                AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8);
            }
        }

        [ConditionalFact]
        public override void Can_insert_and_read_back_object_backed_data_types()
        {
            using (var context = CreateContext())
            {
                context.Set<ObjectBackedDataTypes>().Add(
                    new ObjectBackedDataTypes
                    {
                        Id = 101,
                        PartitionId = 101,
                        String = "TestString",
                        Bytes = new byte[] { 10, 9, 8, 7, 6 },
                        Int16 = -1234,
                        Int32 = -123456789,
                        Int64 = -1234567890123456789L,
                        Double = -1.23456789,
                        Decimal = -1234567890.01M,
                        DateTime = DateTime.Parse("01/01/2000 12:34:56"),
                        DateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                        TimeSpan = new TimeSpan(0, 10, 9, 8, 7),
                        Single = -1.234F,
                        Boolean = false,
                        Byte = 255,
                        UnsignedInt16 = 1234,
                        UnsignedInt32 = 1234565789U,
                        UnsignedInt64 = 1234567890123456789UL,
                        Character = 'a',
                        SignedByte = -128,
                        Enum64 = Enum64.SomeValue,
                        Enum32 = Enum32.SomeValue,
                        Enum16 = Enum16.SomeValue,
                        Enum8 = Enum8.SomeValue,
                        EnumU64 = EnumU64.SomeValue,
                        EnumU32 = EnumU32.SomeValue,
                        EnumU16 = EnumU16.SomeValue,
                        EnumS8 = EnumS8.SomeValue
                    });

                Assert.Equal(1, context.SaveChanges());
            }

            using (var context = CreateContext())
            {
                var dt = context.Set<ObjectBackedDataTypes>().Where(ndt => ndt.Id == 101).ToList().Single();

                var entityType = context.Model.FindEntityType(typeof(ObjectBackedDataTypes));
                AssertEqualIfMapped(entityType, "TestString", () => dt.String);
                AssertEqualIfMapped(entityType, new byte[] { 10, 9, 8, 7, 6 }, () => dt.Bytes);
                AssertEqualIfMapped(entityType, (short)-1234, () => dt.Int16);
                AssertEqualIfMapped(entityType, -123456789, () => dt.Int32);
                AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.Int64);
                AssertEqualIfMapped(entityType, -1.23456789, () => dt.Double);
                AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.Decimal);
                AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56"), () => dt.DateTime);
                AssertEqualIfMapped(
                    entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)),
                    () => dt.DateTimeOffset);
                AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TimeSpan);
                AssertEqualIfMapped(entityType, -1.234F, () => dt.Single);
                AssertEqualIfMapped(entityType, false, () => dt.Boolean);
                AssertEqualIfMapped(entityType, (byte)255, () => dt.Byte);
                AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64);
                AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32);
                AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16);
                AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8);
                AssertEqualIfMapped(entityType, (ushort)1234, () => dt.UnsignedInt16);
                AssertEqualIfMapped(entityType, 1234565789U, () => dt.UnsignedInt32);
                AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.UnsignedInt64);
                AssertEqualIfMapped(entityType, 'a', () => dt.Character);
                AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.SignedByte);
                AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64);
                AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32);
                AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16);
                AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8);
            }
        }

        private void AssertEqualIfMapped<T>(IEntityType entityType, T expected, Expression<Func<T>> actualExpression)
        {
            if (entityType.FindProperty(((MemberExpression)actualExpression.Body).Member.Name) != null)
            {
                var actual = actualExpression.Compile()();
                var type = UnwrapNullableEnumType(typeof(T));
                if (IsSignedInteger(type))
                {
                    Assert.True(Equal(Convert.ToInt64(expected), Convert.ToInt64(actual)), $"Expected:\t{expected}\r\nActual:\t{actual}");
                }
                else if (IsUnsignedInteger(type))
                {
                    Assert.True(Equal(Convert.ToUInt64(expected), Convert.ToUInt64(actual)), $"Expected:\t{expected}\r\nActual:\t{actual}");
                }
                else if(type == typeof(DateTime))
                {
                    Assert.True(Equal((DateTime)(object)expected, (DateTime)(object)actual), $"Expected:\t{expected:O}\r\nActual:\t{actual:O}");
                }
                else if (type == typeof(DateTimeOffset))
                {
                    Assert.True(Equal((DateTimeOffset)(object)expected, (DateTimeOffset)(object)actual), $"Expected:\t{expected:O}\r\nActual:\t{actual:O}");
                }
                else
                {
                    Assert.Equal(expected, actual);
                }
            }
        }

        private static bool IsSignedInteger(Type type)
            => type == typeof(int)
               || type == typeof(long)
               || type == typeof(short)
               || type == typeof(sbyte);

        private static bool IsUnsignedInteger(Type type)
            => type == typeof(byte)
               || type == typeof(uint)
               || type == typeof(ulong)
               || type == typeof(ushort)
               || type == typeof(char);

        private bool Equal(long left, long right)
        {
            if (left >= 0
                && right >= 0)
            {
                return Equal((ulong)left, (ulong)right);
            }

            if (left < 0
                && right < 0)
            {
                return Equal((ulong)-left, (ulong)-right);
            }

            return false;
        }

        private bool Equal(ulong left, ulong right)
        {
            if (Fixture.IntegerPrecision < 64)
            {
                var largestPrecise = 1ul << Fixture.IntegerPrecision;
                while (left > largestPrecise)
                {
                    left >>= 1;
                    right >>= 1;
                }
            }

            return left == right;
        }

        private bool Equal(DateTime left, DateTime right)
            => left.Equals(right) && (!Fixture.PreservesDateTimeKind || left.Kind == right.Kind);

        private bool Equal(DateTimeOffset left, DateTimeOffset right)
            => left.Equals(right); // => left.EqualsExact(right);

        #endregion

        public class ConvertToProviderTypesMySqlFixture : ConvertToProviderTypesFixtureBase
        {
            public override bool StrictEquality => true;

            public override bool SupportsAnsi => true;

            public override bool SupportsUnicodeToAnsiConversion => false;

            public override bool SupportsLargeStringComparisons => true;

            protected override ITestStoreFactory TestStoreFactory => MySqlTestStoreFactory.Instance;
            public TestSqlLoggerFactory TestSqlLoggerFactory => (TestSqlLoggerFactory)ServiceProvider.GetRequiredService<ILoggerFactory>();

            public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
                => base.AddOptions(builder);

            public override bool SupportsBinaryKeys => true;

            public override DateTime DefaultDateTime => new DateTime();

            public override bool PreservesDateTimeKind => false;

            public override bool SupportsDecimalComparisons => true;
        }
    }
}


text:
package uk.org.taverna.server.client.xml;

import java.net.URI;
import java.util.Map;

public final class ServerResources extends AbstractResources {

	private static final String SNAPSHOT = "-SNAPSHOT";

	private final String version;
	private final String revision;
	private final String timestamp;
	private final int[] versionComponents;

	ServerResources(Map<ResourceLabel, URI> links, String version,
			String revision, String timestamp) {
		super(links);

		this.revision = revision;
		this.timestamp = timestamp;

		// Parse out and rebuild the version string into a normalized
		// major.minor.patch format. This is so that all version strings have
		// three components - 2.4 will be converted to 2.4.0.
		versionComponents = new int[3];
		if (version.endsWith(SNAPSHOT)) {
			version = version.replaceAll(SNAPSHOT, "");
		}
		String[] vs = version.split("\\.", 3);
		versionComponents[0] = Integer.parseInt(vs[0]);
		versionComponents[1] = Integer.parseInt(vs[1]);

		try {
			// We might not have a third component!
			versionComponents[2] = Integer.parseInt(vs[2]);
		} catch (IndexOutOfBoundsException e) {
			versionComponents[2] = 0;
		}

		this.version = String.format("%d.%d.%d", versionComponents[0],
				versionComponents[1], versionComponents[2]);
	}

	public String getVersion() {
		return version;
	}

	public String getRevision() {
		return revision;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public int[] getVersionComponents() {
		return versionComponents;
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * task_execution.proto
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: version not set
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package nextflow.ga4gh.tes.client.auth;

public enum OAuthFlow {
    accessCode, implicit, password, application
}


text:
arrayname = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# The index for an array starts with 0, so in the array above a[0] is 1

# Some methods you can use on arrays:

    arrayname.empty?
    arrayname.include?("itemname")
    arrayname.reverse
    arrayname.reverse! # use ! at the end to change the original array
    arrayname.shuffle
    arrayname.push(30) # will append new element 30 to the end array
    arrayname << 25 # << known as shovel operator will also append new element to the end of the array
    arrayname.unshift(27) # will add element "some element" to the beginning of the array
    arrayname.pop # will remove the last element of the array and return 1
    arrayname.uniq # will remove all the duplicates and display (will not change the original array)
    arrayname.uniq! # will remove all the duplicates in the original array

# A range:
    (0..25).to_a
    # will create an array with elements from value 0 to 25

    (0..99).to_a.shuffle!
    # will create an array with elements from value 0 to 99 in random order

# To loop through an array named y using the .each method and print out the value of each element:

    arrayname.each { |i| puts i }
    # In plain terms: For each element i in array y print the value of i

# To execute iteration through an array called names using a block:

arrayNameString = ["Zeaph", "Buddy", "Ely", "Marcus", "Raymond", "Ebe"]

arrayNameString.each do |randomvariablename| # starts the do block
    puts "Hello #{randomvariablename}" # executes code for each element
end # ends the do block

# To capitalize (or use another method) on each element of array called names:
    arrayNameString.each { |randomvariablename| puts "Hello #{randomvariablename.capitalize}" }

# Using the select method to pickup all the odd numbers from an array arrayname:
    arrayname.select { |number| number.odd? }
    # selects the value and returns it only if the condition is met

# To join the elements of an array named arrayNameString:
puts arrayNameString.join

# To join the elements of an array with space in between each element:
puts arrayNameString.join(" ")

# To join the elements of an array with dash in between each element:
puts arrayNameString.join("-")


text:
/*
 * @author Paul Smith <psmith@apache.org>
 *
*/
package org.apache.log4j.chainsaw;

import java.awt.Component;
import java.awt.EventQueue;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SettingsListener;
import org.apache.log4j.chainsaw.prefs.SettingsManager;

/**
 * The only reason this class is needed is because
 * of a stupid 'issue' with the JTabbedPane.
 *
 * If the currently selected tab is the first tab,
 * and we insert a new tab at the front, then as
 * far as the JTabbedPane is concerned, NO STATE has
 * changed, as the currently selected tab index is still
 * the same (even though the TAB is different - go figure)
 * and therefore no ChangeEvent is generated and sent
 * to listeners.  Thanks very much Sun!
 *
 * For more information on the issue:
 * http://developer.java.sun.com/developer/bugParade/bugs/4253819.html
 *
 * @author Paul Smith <psmith@apache.org>
 * @author Scott Deboy <sdeboy@apache.org>
 *
 */

class ChainsawTabbedPane extends JTabbedPane implements SettingsListener {
  public SavableTabSetting tabSetting;
  public static final String WELCOME_TAB = "Welcome";
  public static final String ZEROCONF = "Zeroconf";
  /**
   *
   * Create the tabbed pane.
   *
   */
  public ChainsawTabbedPane() {
    super();
  }

  /**
   * Returns true if this TabbedPane has an instance of the WelcomePanel
   * in it
   * @return true/false
   */
  boolean containsWelcomePanel() {
    return indexOfTab("Welcome") > -1;
  }

  /**
   * Our custom implementation of inserting a new tab,
   * this method ALWAYS inserts it at the front because
   * we get an ArrayIndexOutOfBoundsException otherwise
   * under some JDK implementations.
   *
   * This method also causes a fireStateChange() to be
   * called so that listeners get notified of the event.
   * See the class level comments for the reason why...
   * @param name
   * @param component
   */
  public void addANewTab(String name, JComponent component, Icon icon) {
    super.insertTab(name, icon, component, null, getTabCount());

    super.fireStateChanged();
    if (!"chainsaw-log".equals(name)) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                setSelectedTab(getTabCount() - 1);
            }
        });
    }
  }

  public void setSelectedTab(int index) {
    if (getTabCount() >= index) {
      setSelectedIndex(index);
    }

    getSelectedComponent().setVisible(true);
    getSelectedComponent().validate();
    super.fireStateChanged();
  }

  public void addANewTab(
    String name, JComponent component, Icon icon, String tooltip) {
    super.insertTab(name, icon, component, tooltip, getTabCount());
    super.fireStateChanged();
  }

  public void remove(Component component) {
    super.remove(component);
    super.fireStateChanged();
  }

  /**
   * Saves the state of the currently active tabs to an XML file.
   * Only considers the Welcome, Drag and Drop and chainsaw-log
   * panels as they are the panel which are always running. Saves
   * whether they are hidden or not....
   */

  public void saveSettings(SaveSettingsEvent event){
   File file = new File(SettingsManager.getInstance().getSettingsDirectory(), "tab-settings.xml");
   XStream stream = new XStream(new DomDriver());
   try {
     FileWriter writer = new FileWriter(file);
     int count = super.getTabCount();
     String title;
     SavableTabSetting setting = new SavableTabSetting();
     for(int i = 0 ; i < count ; i++){
       title = super.getTitleAt(i);
       if(title.equals(WELCOME_TAB)){
         setting.setWelcome(true);
       } else if (title.equals("chainsaw-log")){
         setting.setChainsawLog(true);
       } else if (title.equals(ZEROCONF)){
         setting.setZeroconf(true);
       }
     }

     stream.toXML(setting, writer);
     writer.close();

   } catch (Exception e) {
     file.delete();
     e.printStackTrace();
   }
  }

  /**
   * Loads the saved tab setting by reading the XML file.
   * If the file doesn't exist, all three panels should be
   * shown as the default setting....
   */

  public void loadSettings(LoadSettingsEvent event){
    File file = new File(SettingsManager.getInstance().getSettingsDirectory(), "tab-settings.xml");
    XStream stream = new XStream(new DomDriver());
    try {
      if (file.exists()) {
        FileReader reader = new FileReader(file);
        tabSetting = (SavableTabSetting) stream.fromXML(reader);
        reader.close();
      } else {
        tabSetting = new SavableTabSetting();
        tabSetting.setWelcome(true);
        tabSetting.setChainsawLog(true);
        tabSetting.setZeroconf(true);
      }
    } catch (Exception e) {
      e.printStackTrace();
      file.delete();
    }
  }
}


text:
from __future__ import print_function, absolute_import, division

import glob
import os
import numpy as np

from .utils import expand_path, num_samples

class BaseDatasetLoader(object):
    short_name = None

    def load(self):
        raise NotImplementedError('should be implemented in subclass')

class MSMBuilderDatasetLoader(BaseDatasetLoader):
    short_name = 'msmbuilder'

    def __init__(self, path, fmt=None, verbose=False):
        self.path = path
        self.fmt = fmt
        self.verbose = verbose

    def load(self):
        from msmbuilder.dataset import dataset
        ds = dataset(self.path, mode='r', fmt=self.fmt, verbose=self.verbose)
        print('Dataset provenance:\n')
        print(ds.provenance)
        return ds, None

class NumpyDatasetLoader(BaseDatasetLoader):
    short_name = 'numpy'

    def __init__(self, filenames):
        self.filenames = filenames

    def load(self):
        filenames = sorted(glob.glob(expand_path(self.filenames)))
        if len(filenames) == 0:
            raise RuntimeError('no filenames matched by pattern: %s' %
                               self.filenames)
        ds = [np.load(f) for f in filenames]
        return ds, None

class HDF5DatasetLoader(BaseDatasetLoader):
    short_name = 'hdf5'

    def __init__(self, filenames, y_col=None, stride=1, concat=False):
        self.filenames = filenames
        self.y_col = y_col
        self.stride = stride
        self.concat = concat

    def transform(self, X):
        n_rows = X.shape[0]
        X = np.atleast_2d(X)
        if X.shape[0] != n_rows:
            X = X.T
        if self.y_col is not None:
            cols = range(X.shape[1])
            x_idx = [i for i, val in enumerate(cols) if val != self.y_col]
            y_idx = [i for i, val in enumerate(cols) if val == self.y_col]
            return X[::self.stride, x_idx], X[::self.stride, y_idx].ravel()
        return X[::self.stride, :], None

    def loader(self, fn):
        from mdtraj import io
        dataset = io.loadh(fn)
        for key in dataset.iterkeys():
            yield dataset[key]

    def load(self):
        X = []
        y = []
        filenames = sorted(glob.glob(expand_path(self.filenames)))
        for fn in filenames:
            for data in self.loader(fn):
                data = self.transform(data)
                X.append(data[0])
                y.append(data[1])

        if self.concat:
            X = np.concatenate(X, axis=0)
            y = np.concatenate(y, axis=0)
        if num_samples(X) == 1:
            X = X[0]
            y = y[0]
        if self.y_col is not None:
            return X, y

        return X, None

class DSVDatasetLoader(BaseDatasetLoader):
    short_name = 'dsv'

    def __init__(self, filenames, y_col=None, delimiter=',', skip_header=0,
                 skip_footer=0, filling_values=np.nan, usecols=None, stride=1,
                 concat=False):
        self.filenames = filenames
        self.y_col = y_col
        self.delimiter = delimiter
        self.skip_header = skip_header
        self.skip_footer = skip_footer
        self.filling_values = filling_values
        if usecols and isinstance(usecols, str):
            usecols = list(map(int, usecols.strip().split(',')))
        elif usecols and isinstance(usecols, (tuple, set)):
            usecols = sorted(list(usecols))
        if usecols and y_col:
            if y_col not in usecols:
                usecols.append(y_col)
        self.usecols = usecols
        self.stride = stride
        self.concat = concat

    def transform(self, X):
        n_rows = X.shape[0]
        X = np.atleast_2d(X)
        if X.shape[0] != n_rows:
            X = X.T
        if self.y_col is not None:
            cols = list(range(X.shape[1]))
            if self.usecols:
                cols = self.usecols
            x_idx = [i for i, val in enumerate(cols) if val != self.y_col]
            y_idx = [i for i, val in enumerate(cols) if val == self.y_col]
            return X[::self.stride, x_idx], X[::self.stride, y_idx].ravel()
        return X[::self.stride, :], None

    def loader(self, fn):
        return np.genfromtxt(fn, delimiter=self.delimiter,
                             skip_header=self.skip_header,
                             skip_footer=self.skip_footer,
                             filling_values=self.filling_values,
                             usecols=self.usecols)

    def load(self):
        X = []
        y = []
        filenames = sorted(glob.glob(expand_path(self.filenames)))
        for fn in filenames:
            data = self.transform(self.loader(fn))
            X.append(data[0])
            y.append(data[1])

        if self.concat:
            X = np.concatenate(X, axis=0)
            y = np.concatenate(y, axis=0)
        if num_samples(X) == 1:
            X = X[0]
            y = y[0]
        if self.y_col is not None:
            return X, y

        return X, None

class MDTrajDatasetLoader(BaseDatasetLoader):
    short_name = 'mdtraj'

    def __init__(self, trajectories, topology=None, stride=1, verbose=False):
        self.trajectories = trajectories
        self.topology = topology
        self.stride = stride
        self.verbose = verbose

    def load(self):
        import mdtraj

        filenames = sorted(glob.glob(expand_path(self.trajectories)))
        if len(filenames) == 0:
            raise RuntimeError('no filenames matched by pattern: %s' %
                               self.trajectories)

        top = self.topology
        kwargs = {}
        if top is not None:
            top = expand_path(self.topology)
            kwargs = {'top': top}

        X = []
        y = None

        for fn in filenames:
            if self.verbose:
                print('[mdtraj] loading %s' % fn)
            X.append(mdtraj.load(fn, stride=self.stride, **kwargs))

        return X, y

class FilenameDatasetLoader(BaseDatasetLoader):
    """Just pass a bunch of filenames to the first step of the pipeline

    The pipeline will do the loading.
    """
    short_name = 'filename'

    def __init__(self, trajectories, abs_path=True):
        self.traj_glob = trajectories
        self.abs_path = abs_path

    def load(self):
        filenames = sorted(glob.glob(expand_path(self.traj_glob)))
        if len(filenames) == 0:
            raise RuntimeError('no filenames matched by pattern: %s' %
                               self.traj_glob)

        if self.abs_path:
            filenames = [os.path.abspath(fn) for fn in filenames]
        return filenames, None

class JoblibDatasetLoader(BaseDatasetLoader):
    short_name = 'joblib'

    def __init__(self, filenames, x_name=None, y_name=None,
                 system_joblib=False):
        self.filenames = filenames
        self.x_name = x_name
        self.y_name = y_name
        self.system_joblib = system_joblib

    def load(self):
        if self.system_joblib:
            import joblib
        else:
            from sklearn.externals import joblib

        X, y = [], []

        filenames = sorted(glob.glob(expand_path(self.filenames)))
        if len(filenames) == 0:
            raise RuntimeError('no filenames matched by pattern: %s' %
                               self.filenames)

        for fn in filenames:
            obj = joblib.load(fn)
            if isinstance(obj, (list, np.ndarray)):
                X.append(obj)
            else:
                X.append(obj[self.x_name])
                y.append(obj[self.y_name])

        if num_samples(X) == 1:
            X = X[0]
        if len(y) == 1:
            y = y[0]
        elif len(y) == 0:
            y = None

        return X, y

class SklearnDatasetLoader(BaseDatasetLoader):
    short_name = 'sklearn_dataset'

    def __init__(self, method, x_name='data', y_name='target', **kwargs):
        self.method = method
        self.x_name = x_name
        self.y_name = y_name
        self.kwargs = kwargs

    def load(self):
        import sklearn.datasets

        try:
            loader = getattr(sklearn.datasets, self.method)
        except AttributeError:
            raise RuntimeError('no %s in sklearn.datasets' % self.method)

        bunch = loader(**self.kwargs)

        X = bunch[self.x_name]
        y = bunch[self.y_name]

        return X, y

class FsPeptideDatasetLoader(BaseDatasetLoader):
    short_name = 'fspeptide'

    def __init__(self):
        pass

    def load(self):
        from msmbuilder.example_datasets import FsPeptide

        trajectories = FsPeptide(verbose=False).get().trajectories
        return trajectories, None

class AlanineDipeptideDatasetLoader(BaseDatasetLoader):
    short_name = 'alaninedipeptide'

    def __init__(self):
        pass

    def load(self):
        from msmbuilder.example_datasets import AlanineDipeptide

        trajectories = AlanineDipeptide(verbose=False).get().trajectories
        return trajectories, None

class MullPotentialDatasetLoader(BaseDatasetLoader):
    short_name = 'muller'

    def __init__(self, random_state=None):
        self.random_state = random_state

    def load(self):
        from msmbuilder.example_datasets import MullerPotential


text:
<?php

namespace SweetTooth\Bundle\ContactBundle\Controller;

// use OroCRM\Bundle\CallBundle\Entity\Call;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;

use Oro\Bundle\SecurityBundle\Annotation\Acl;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class LoyaltyController extends Controller
{
    /**
     * @Route("/widget/points_balance", name="sweettooth_loyalty_widget_points_balance")
     * @Template("SweetToothContactBundle:Loyalty:widget/points_balance.html.twig")
     *
     * @param Request $request
     * @return array
     */
    public function pointsBalanceAction(Request $request)
    {
        $points_balance = '0';
        $params = $request->query->all();
        $contactId = $params['contactId'];

        $contactBroker = $this->get('sweettooth_binding.contact_broker');

        // Fetch contact's points balance from ST
        $binding = $contactBroker->retrieve($contactId);

        if ($binding && $binding->getRemoteObject()) {
            $points_balance = $binding->getRemoteObject()->points_balance;
        }

        return array(
            'points_balance' => $points_balance
        );
    }

    /**
     * @Route("/widget/points_history", name="sweettooth_loyalty_widget_points_history")
     * @Template("SweetToothContactBundle:Loyalty:widget/points_history.html.twig")
     *
     * @param Request $request
     * @return array
     */
    public function pointsHistoryAction(Request $request)
    {
        return array(
            'datagridParameters' => $request->query->all()
        );
    }
}


text:
f = CurrentFont()

master1 = f["b"]
master2 = f["b.bold"]

isCompatible, errorMessage = master1.isCompatible(master2)

if isCompatible:
    factor = (1.22, 1.76)
    #result = master1 * (1 - factor)  + (master2 * factor)
    diff = master2 - master1
    result = master1 + factor * (master2 - master1)

    drawGlyph(result)

    f.insertGlyph(result, "b.interpol")

else:
    print errorMessage


text:
<?php

namespace Koalamon\WebhookBundle\Formats;

use Koalamon\IncidentDashboardBundle\Entity\Event;
use Koalamon\IncidentDashboardBundle\Entity\RawEvent;
use Symfony\Component\HttpFoundation\Request;

class TravisFormat implements Format
{
    const STATUS_SUCCESS = 0;

    public function createEvent(Request $request, $payload)
    {
        $newEvent = json_decode($request->get('payload'));

        $event = new RawEvent();

        $system = $newEvent->repository->owner_name . ':' . $newEvent->repository->name . ':' . $newEvent->branch;

        if ($newEvent->result == self::STATUS_SUCCESS) {
            $event->setStatus(Event::STATUS_SUCCESS);
            $event->setMessage("");
        } else {
            $event->setStatus(Event::STATUS_FAILURE);
            $event->setMessage("Building " . $system . " failed. Last commit by " . $newEvent->committer_name . '.');
        }

        $event->setSystem($system);
        $event->setIdentifier('travis_' . $system);
        $event->setUrl($newEvent->build_url);

        $event->setType('travis');

        return $event;
    }
}


text:
import { Route } from './route.annotation.js'
import { Type } from '@ingress/di'

export interface ControllerOptions {
  routePrefix?: string
}

export interface Controller {
  (options?: ControllerOptions | string): ClassDecorator
}

export type ControllerDependencyCollector = Controller & ClassDecorator

export class ControllerCollector {
  public items = new Set<Type<any>>()
  public collect: ControllerDependencyCollector
  private _collector: ClassDecorator
  constructor() {
    this._collector = (target: any) => {
      this.items.add(target)
    }
    this.collect = ((options?: ControllerOptions | any) => {
      if (!options) {
        return this._collector
      }
      const routePrefix: string = (typeof options === 'string' && options) || options.routePrefix
      if (routePrefix) {
        return ((target: any) => {
          Route(routePrefix)(target)
          this._collector(target)
        }) as ClassDecorator
      }

      return this._collector(options) as ClassDecorator
    }) as ControllerDependencyCollector
  }
}


text:
from __future__ import absolute_import
from builtins import object
from django.db import models
from django.utils.translation import gettext_lazy as _

from bluebottle.funding.models import Payment, PaymentProvider, BankAccount

class PledgePayment(Payment):
    provider = 'pledge'

    def refund(self):
        pass

class PledgePaymentProvider(PaymentProvider):

    title = 'Pledges only'

    @property
    def payment_methods(self):
        return []

    class Meta(object):
        verbose_name = 'Pledge payment provider'

class PledgeBankAccount(BankAccount):
    provider_class = PledgePaymentProvider

    account_holder_name = models.CharField(
        _("Account holder name"), max_length=100, null=True, blank=True)
    account_holder_address = models.CharField(
        _("Account holder address"), max_length=255, null=True, blank=True)
    account_holder_postal_code = models.CharField(
        _("Account holder postal code"), max_length=20, null=True, blank=True)
    account_holder_city = models.CharField(
        _("Account holder city"), max_length=255, null=True, blank=True)
    account_holder_country = models.ForeignKey(
        'geo.Country',
        verbose_name=_('Account holder country'),
        blank=True, null=True,
        related_name="pledge_account_holder_country",
        on_delete=models.CASCADE
    )

    account_number = models.CharField(
        _("Account number"),
        max_length=255, null=True, blank=True)
    account_details = models.CharField(
        _("Account details"),
        max_length=500, null=True, blank=True)
    account_bank_country = models.ForeignKey(
        'geo.Country',
        verbose_name=_('Account bank country'),
        blank=True, null=True,
        related_name="pledge_account_bank_country",
        on_delete=models.CASCADE
    )

    def save(self, *args, **kwargs):
        super(PledgeBankAccount, self).save(*args, **kwargs)

    class Meta(object):
        verbose_name = _('Pledge bank account')
        verbose_name_plural = _('Pledge bank accounts')

    class JSONAPIMeta(object):
        resource_name = 'payout-accounts/pledge-external-accounts'

    def __str__(self):
        return u"Pledge bank account {}".format(self.account_holder_name)

from .states import *  # noqa


text:
var c = require('./circulo');
var r = require('./rectangulo');
var t = require('./triangulo');

var CalculadoraDeArea = (function() {
    var CalculadoraDeArea = function() {

    };

    CalculadoraDeArea.prototype.calcularArea = function(figura, a, b) {

        switch (figura) {
            case 'circulo':
                return c(a, b).calcularArea();

            case 'rectangulo':
                return r(a, b).calcularArea();

            case 'triangulo':
                return t(a, b).calcularArea();
        }

        return 0;
    }

    return CalculadoraDeArea;
})();

module.exports = function() {
    return new CalculadoraDeArea();
}


text:
import React, { Component } from 'react';
import renderer from 'react-test-renderer';
import asyncComponent from '../asyncComponent';

function TestComponent() {
  return 'test';
}

const esComponentLoader = async () => {
  await new Promise(r => setTimeout(r, 300));
  return { __esModule: true, default: TestComponent };
};

const jsComponentLoader = async () => {
  await new Promise(r => setTimeout(r, 300));
  return TestComponent;
};

test('ES6 asyncComponent', async () => {
  const context = {};
  const loading = new Promise(r => context.r = r);
  const EsComponent = asyncComponent(esComponentLoader, {
    loader: () => 'loading',
    onLoad: context.r,
  });
  context.component = renderer.create(<EsComponent />);
  context.tree = context.component.toTree();
  expect(context.component.toJSON()).toContain('loading');
  await loading;
  expect(context.component.toJSON()).toContain('test');
});

test('JS asyncComponent', async () => {
  const context = {};
  const loading = new Promise(r => context.r = r);
  const JSComponent = asyncComponent(jsComponentLoader, {
    loader: () => 'loading',
    onLoad: context.r,
  });
  context.component = renderer.create(<JSComponent />);
  context.tree = context.component.toTree();
  expect(context.component.toJSON()).toContain('loading');
  await loading;
  expect(context.component.toJSON()).toContain('test');
});


text:
if [ -d "sites/" ]; then
    echo "Add alias as below, than you can run phpunit in your project folder."
    echo 'alias phpunit="../../phpunit.sh"'
    exit;
fi
docker-compose -f "../../docker-compose.yml" exec -u dlaravel php $(basename `pwd`)/vendor/bin/phpunit -c $(basename `pwd`)/phpunit.xml


text:
if( DEFINED REALTIME_PATH )
    find_library(RT_LIB rt PATHS ${REALTIME_PATH}/lib NO_DEFAULT_PATH )
endif()

find_library( RT_LIB rt )

mark_as_advanced( RT_LIB )

include(FindPackageHandleStandardArgs)
# Handle the QUIET and REQUIRED arguments and set REALTIME_FOUND to TRUE
# if all listed variables are TRUE
# Note: capitalisation of the package name must be the same as in the file name
find_package_handle_standard_args(Realtime  DEFAULT_MSG RT_LIB )


text:
let template = require('babel-template');
let types = require('babel-types');

let clearRectTemplate = template(`
  DIRTYCHECK;
  CTX.clearRect(X, Y, WIDTH, HEIGHT);
`)

module.exports = (path, _types, attrs, children, internalState) => {
  path.replaceWithMultiple(
    clearRectTemplate(
      Object.assign({
        X: attrs.x || types.numericLiteral(0),
        Y: attrs.y || types.numericLiteral(0),
        WIDTH: attrs.width,
        HEIGHT: attrs.height
      },
        internalState.identifiers
      )
    )
  );
};


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
J. Bot. (Hooker) 2:141. 1840

#### Original name
null

### Remarks
null


text:
#include "qglobal.h"

#if !defined(QT_NO_RAWFONT)

#include "qrawfont.h"
#include "qrawfont_p.h"
#include "qplatformfontdatabase.h"

#include <QtCore/qendian.h>

QT_BEGIN_NAMESPACE

/*!
   \class QRawFont
   \brief The QRawFont class provides access to a single physical instance of a font.
   \since 4.8
   \inmodule QtGui

   \ingroup text
   \ingroup shared
   \mainclass

   \note QRawFont is a low level class. For most purposes QFont is a more appropriate class.

   Most commonly, when presenting text in a user interface, the exact fonts used
   to render the characters is to some extent unknown. This can be the case for several
   reasons: For instance, the actual, physical fonts present on the target system could be
   unexpected to the developers, or the text could contain user selected styles, sizes or
   writing systems that are not supported by font chosen in the code.

   Therefore, Qt's QFont class really represents a query for fonts. When text is interpreted,
   Qt will do its best to match the text to the query, but depending on the support, different
   fonts can be used behind the scenes.

   For most use cases, this is both expected and necessary, as it minimizes the possibility of
   text in the user interface being undisplayable. In some cases, however, more direct control
   over the process might be useful. It is for these use cases the QRawFont class exists.

   A QRawFont object represents a single, physical instance of a given font in a given pixel size.
   I.e. in the typical case it represents a set of TrueType or OpenType font tables and uses a
   user specified pixel size to convert metrics into logical pixel units. It can be used in
   combination with the QGlyphRun class to draw specific glyph indexes at specific positions, and
   also have accessors to some relevant data in the physical font.

   QRawFont only provides support for the main font technologies: GDI and DirectWrite on Windows
   platforms, FreeType on Linux platforms and CoreText on Mac OS X. For other
   font back-ends, the APIs will be disabled.

   QRawFont can be constructed in a number of ways:
   \list
   \li It can be constructed by calling QTextLayout::glyphs() or QTextFragment::glyphs(). The
      returned QGlyphs objects will contain QRawFont objects which represent the actual fonts
      used to render each portion of the text.
   \li It can be constructed by passing a QFont object to QRawFont::fromFont(). The function
      will return a QRawFont object representing the font that will be selected as response to
      the QFont query and the selected writing system.
   \li It can be constructed by passing a file name or QByteArray directly to the QRawFont
      constructor, or by calling loadFromFile() or loadFromData(). In this case, the
      font will not be registered in QFontDatabase, and it will not be available as part of
      regular font selection.
   \endlist

   QRawFont is considered local to the thread in which it is constructed (either using a
   constructor, or by calling loadFromData() or loadFromFile()). The QRawFont cannot be moved to a
   different thread, but will have to be recreated in the thread in question.

   \note For the requirement of caching glyph indexes and font selections for static text to avoid
   reshaping and relayouting in the inner loop of an application, a better choice is the QStaticText
   class, since it optimizes the memory cost of the cache and also provides the possibility of paint
   engine specific caches for an additional speed-up.
*/

/*!
    \enum QRawFont::AntialiasingType

    This enum represents the different ways a glyph can be rasterized in the function
    alphaMapForGlyph().

    \value PixelAntialiasing Will rasterize by measuring the coverage of the shape on whole pixels.
           The returned image contains the alpha values of each pixel based on the coverage of
           the glyph shape.
    \value SubPixelAntialiasing Will rasterize by measuring the coverage of each subpixel,
           returning a separate alpha value for each of the red, green and blue components of
           each pixel.
*/

/*!
    \enum QRawFont::LayoutFlag
    \since 5.1

    This enum tells the function advancesForGlyphIndexes() how to calculate the advances.

    \value SeparateAdvances Will calculate the advance for each glyph separately.
    \value KernedAdvances Will apply kerning between adjacent glyphs. Note that OpenType GPOS based
           kerning is currently not supported.
    \value UseDesignMetrics Use design metrics instead of hinted metrics adjusted to the resolution
           of the paint device.
           Can be OR-ed with any of the options above.
*/

/*!
   Constructs an invalid QRawFont.
*/
QRawFont::QRawFont()
    : d(new QRawFontPrivate)
{
}

/*!
   Constructs a QRawFont representing the font contained in the file referenced
   by \a fileName for the size (in pixels) given by \a pixelSize, and using the
   hinting preference specified by \a hintingPreference.

   \note The referenced file must contain a TrueType or OpenType font.
*/
QRawFont::QRawFont(const QString &fileName,
                   qreal pixelSize,
                   QFont::HintingPreference hintingPreference)
    : d(new QRawFontPrivate)
{
    loadFromFile(fileName, pixelSize, hintingPreference);
}

/*!
   Constructs a QRawFont representing the font contained in the supplied
   \a fontData for the size (in pixels) given by \a pixelSize, and using the
   hinting preference specified by \a hintingPreference.

   \note The data must contain a TrueType or OpenType font.
*/
QRawFont::QRawFont(const QByteArray &fontData,
                   qreal pixelSize,
                   QFont::HintingPreference hintingPreference)
    : d(new QRawFontPrivate)
{
    loadFromData(fontData, pixelSize, hintingPreference);
}

/*!
   Creates a QRawFont which is a copy of \a other.
*/
QRawFont::QRawFont(const QRawFont &other)
{
    d = other.d;
}

/*!
   Destroys the QRawFont
*/
QRawFont::~QRawFont()
{
}

/*!
  Assigns \a other to this QRawFont.
*/
QRawFont &QRawFont::operator=(const QRawFont &other)
{
    d = other.d;
    return *this;
}

/*!
  \fn void QRawFont::swap(QRawFont &other)
  \since 5.0

  Swaps this raw font with \a other. This function is very fast and
  never fails.
*/

/*!
   Returns \c true if the QRawFont is valid and false otherwise.
*/
bool QRawFont::isValid() const
{
    return d->isValid();
}

/*!
   Replaces the current QRawFont with the contents of the file referenced
   by \a fileName for the size (in pixels) given by \a pixelSize, and using the
   hinting preference specified by \a hintingPreference.

   The file must reference a TrueType or OpenType font.

   \sa loadFromData()
*/
void QRawFont::loadFromFile(const QString &fileName,
                            qreal pixelSize,
                            QFont::HintingPreference hintingPreference)
{
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly))
        loadFromData(file.readAll(), pixelSize, hintingPreference);
}

/*!
   Replaces the current QRawFont with the font contained in the supplied
   \a fontData for the size (in pixels) given by \a pixelSize, and using the
   hinting preference specified by \a hintingPreference.

   The \a fontData must contain a TrueType or OpenType font.

   \sa loadFromFile()
*/
void QRawFont::loadFromData(const QByteArray &fontData,
                            qreal pixelSize,
                            QFont::HintingPreference hintingPreference)
{
    d.detach();
    d->cleanUp();
    d->hintingPreference = hintingPreference;
    d->thread = QThread::currentThread();
    d->platformLoadFromData(fontData, pixelSize, hintingPreference);
}

/*!
   This function returns a rasterized image of the glyph at the given
   \a glyphIndex in the underlying font, using the \a transform specified.
   If the QRawFont is not valid, this function will return an invalid QImage.

   If \a antialiasingType is set to QRawFont::SubPixelAntialiasing, then the resulting image will be
   in QImage::Format_RGB32 and the RGB values of each pixel will represent the subpixel opacities of
   the pixel in the rasterization of the glyph. Otherwise, the image will be in the format of
   QImage::Format_Indexed8 and each pixel will contain the opacity of the pixel in the
   rasterization.

   \sa pathForGlyph(), QPainter::drawGlyphRun()
*/
QImage QRawFont::alphaMapForGlyph(quint32 glyphIndex, AntialiasingType antialiasingType,
                                  const QTransform &transform) const
{
    if (!d->isValid())
        return QImage();

    if (antialiasingType == SubPixelAntialiasing)
        return d->fontEngine->alphaRGBMapForGlyph(glyphIndex, QFixed(), transform);

    return d->fontEngine->alphaMapForGlyph(glyphIndex, QFixed(), transform);
}

/*!
   This function returns the shape of the glyph at a given \a glyphIndex in the underlying font
   if the QRawFont is valid. Otherwise, it returns an empty QPainterPath.

   The returned glyph will always be unhinted.

   \sa alphaMapForGlyph(), QPainterPath::addText()
*/
QPainterPath QRawFont::pathForGlyph(quint32 glyphIndex) const
{
    if (!d->isValid())
        return QPainterPath();

    QFixedPoint position;
    QPainterPath path;
    d->fontEngine->addGlyphsToPath(&glyphIndex, &position, 1, &path, 0);
    return path;
}

/*!
   Returns \c true if this QRawFont is equal to \a other. Otherwise, returns \c false.
*/
bool QRawFont::operator==(const QRawFont &other) const
{
    return d->fontEngine == other.d->fontEngine;
}

/*!
    \fn bool QRawFont::operator!=(const QRawFont &other) const

    Returns \c true if this QRawFont is not equal to \a other. Otherwise, returns \c false.
*/

/*!
   Returns the ascent of this QRawFont in pixel units.

   \sa QFontMetricsF::ascent()
*/
qreal QRawFont::ascent() const
{
    return d->isValid() ? d->fontEngine->ascent().toReal() : 0.0;
}

/*!
   Returns the descent of this QRawFont in pixel units.

   \sa QFontMetricsF::descent()
*/
qreal QRawFont::descent() const
{
    return d->isValid() ? d->fontEngine->descent().toReal() : 0.0;
}

/*!
   Returns the xHeight of this QRawFont in pixel units.

   \sa QFontMetricsF::xHeight()
*/
qreal QRawFont::xHeight() const
{
    return d->isValid() ? d->fontEngine->xHeight().toReal() : 0.0;
}

/*!
   Returns the leading of this QRawFont in pixel units.

   \sa QFontMetricsF::leading()
*/
qreal QRawFont::leading() const
{
    return d->isValid() ? d->fontEngine->leading().toReal() : 0.0;
}

/*!
   Returns the average character width of this QRawFont in pixel units.

   \sa QFontMetricsF::averageCharWidth()
*/
qreal QRawFont::averageCharWidth() const
{
    return d->isValid() ? d->fontEngine->averageCharWidth().toReal() : 0.0;
}

/*!
   Returns the width of the widest character in the font.

   \sa QFontMetricsF::maxWidth()
*/
qreal QRawFont::maxCharWidth() const
{
    return d->isValid() ? d->fontEngine->maxCharWidth() : 0.0;
}

/*!
   Returns the pixel size set for this QRawFont. The pixel size affects how glyphs are
   rasterized, the size of glyphs returned by pathForGlyph(), and is used to convert
   internal metrics from design units to logical pixel units.

   \sa setPixelSize()
*/
qreal QRawFont::pixelSize() const
{
    return d->isValid() ? d->fontEngine->fontDef.pixelSize : 0.0;
}

/*!
   Returns the number of design units define the width and height of the em square
   for this QRawFont. This value is used together with the pixel size when converting design metrics
   to pixel units, as the internal metrics are specified in design units and the pixel size gives
   the size of 1 em in pixels.

   \sa pixelSize(), setPixelSize()
*/
qreal QRawFont::unitsPerEm() const
{
    return d->isValid() ? d->fontEngine->emSquareSize().toReal() : 0.0;
}

/*!
   Returns the thickness for drawing lines (underline, overline, etc.)
   along with text drawn in this font.
 */
qreal QRawFont::lineThickness() const
{
    return d->isValid() ? d->fontEngine->lineThickness().toReal() : 0.0;
}

/*!
   Returns the position from baseline for drawing underlines below the text
   rendered with this font.
 */
qreal QRawFont::underlinePosition() const
{
    return d->isValid() ? d->fontEngine->underlinePosition().toReal() : 0.0;
}

/*!
   Returns the family name of this QRawFont.
*/
QString QRawFont::familyName() const
{
    return d->isValid() ? d->fontEngine->fontDef.family : QString();
}

/*!
   Returns the style name of this QRawFont.

   \sa QFont::styleName()
*/
QString QRawFont::styleName() const
{
    return d->isValid() ? d->fontEngine->fontDef.styleName : QString();
}

/*!
   Returns the style of this QRawFont.

   \sa QFont::style()
*/
QFont::Style QRawFont::style() const
{
    return d->isValid() ? QFont::Style(d->fontEngine->fontDef.style) : QFont::StyleNormal;
}

/*!
   Returns the weight of this QRawFont.

   \sa QFont::weight()
*/
int QRawFont::weight() const
{
    return d->isValid() ? int(d->fontEngine->fontDef.weight) : -1;
}

/*!
   Converts the string of unicode points given by \a text to glyph indexes
   using the CMAP table in the underlying font, and returns a vector containing
   the result.

   Note that, in cases where there are other tables in the font that affect the
   shaping of the text, the returned glyph indexes will not correctly represent
   the rendering of the text. To get the correctly shaped text, you can use
   QTextLayout to lay out and shape the text, then call QTextLayout::glyphs()
   to get the set of glyph index list and QRawFont pairs.

   \sa advancesForGlyphIndexes(), glyphIndexesForChars(), QGlyphRun, QTextLayout::glyphRuns(), QTextFragment::glyphRuns()
*/
QVector<quint32> QRawFont::glyphIndexesForString(const QString &text) const
{
    QVector<quint32> glyphIndexes;
    if (!d->isValid() || text.isEmpty())
        return glyphIndexes;

    int numGlyphs = text.size();
    glyphIndexes.resize(numGlyphs);

    QGlyphLayout glyphs;
    glyphs.numGlyphs = numGlyphs;
    glyphs.glyphs = glyphIndexes.data();
    if (!d->fontEngine->stringToCMap(text.data(), text.size(), &glyphs, &numGlyphs, QFontEngine::GlyphIndicesOnly)) {
        glyphIndexes.resize(numGlyphs);

        glyphs.numGlyphs = numGlyphs;
        glyphs.glyphs = glyphIndexes.data();
        if (!d->fontEngine->stringToCMap(text.data(), text.size(), &glyphs, &numGlyphs, QFontEngine::GlyphIndicesOnly)) {
            Q_ASSERT_X(false, Q_FUNC_INFO, "stringToCMap shouldn't fail twice");
            return QVector<quint32>();
        }
    }

    glyphIndexes.resize(numGlyphs);
    return glyphIndexes;
}

/*!
   Converts a string of unicode points to glyph indexes using the CMAP table in the
   underlying font. The function works like glyphIndexesForString() except it take
   an array (\a chars), the results will be returned though \a glyphIndexes array
   and number of glyphs will be set in \a numGlyphs. The size of \a glyphIndexes array
   must be at least \a numChars, if that's still not enough, this function will return
   false, then you can resize \a glyphIndexes from the size returned in \a numGlyphs.

   \sa glyphIndexesForString(), advancesForGlyphIndexes(), QGlyphRun, QTextLayout::glyphRuns(), QTextFragment::glyphRuns()
*/
bool QRawFont::glyphIndexesForChars(const QChar *chars, int numChars, quint32 *glyphIndexes, int *numGlyphs) const
{
    Q_ASSERT(numGlyphs);
    if (!d->isValid() || numChars <= 0) {
        *numGlyphs = 0;
        return false;
    }

    if (*numGlyphs <= 0 || !glyphIndexes) {
        *numGlyphs = numChars;
        return false;
    }

    QGlyphLayout glyphs;
    glyphs.numGlyphs = *numGlyphs;
    glyphs.glyphs = glyphIndexes;
    return d->fontEngine->stringToCMap(chars, numChars, &glyphs, numGlyphs, QFontEngine::GlyphIndicesOnly);
}

/*!
   \fn QVector<QPointF> QRawFont::advancesForGlyphIndexes(const QVector<quint32> &glyphIndexes, LayoutFlags layoutFlags) const
   \since 5.1

   Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances
   give the distance from the position of a given glyph to where the next glyph should be drawn
   to make it appear as if the two glyphs are unspaced. How the advances are calculated is
   controlled by \a layoutFlags.

   \sa QTextLine::horizontalAdvance(), QFontMetricsF::width()
*/

/*!
   \fn QVector<QPointF> QRawFont::advancesForGlyphIndexes(const QVector<quint32> &glyphIndexes) const

   \overload

   Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances
   give the distance from the position of a given glyph to where the next glyph should be drawn
   to make it appear as if the two glyphs are unspaced. The advance of each glyph is calculated
   separately.

   \sa QTextLine::horizontalAdvance(), QFontMetricsF::width()
*/

/*!
   \since 5.1

   Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances
   give the distance from the position of a given glyph to where the next glyph should be drawn
   to make it appear as if the two glyphs are unspaced. The glyph indexes are given with the
   array \a glyphIndexes while the results are returned through \a advances, both of them must
   have \a numGlyphs elements. How the advances are calculated is controlled by \a layoutFlags.

   \sa QTextLine::horizontalAdvance(), QFontMetricsF::width()
*/
bool QRawFont::advancesForGlyphIndexes(const quint32 *glyphIndexes, QPointF *advances, int numGlyphs, LayoutFlags layoutFlags) const
{
    Q_ASSERT(glyphIndexes && advances);
    if (!d->isValid() || numGlyphs <= 0)
        return false;

    QGlyphLayout glyphs;
    glyphs.glyphs = const_cast<glyph_t *>(glyphIndexes);
    glyphs.numGlyphs = numGlyphs;
    QVarLengthArray<QFixed> advances_x(numGlyphs);
    QVarLengthArray<QFixed> advances_y(numGlyphs);
    glyphs.advances_x = advances_x.data();
    glyphs.advances_y = advances_y.data();

    bool design = layoutFlags & UseDesignMetrics;

    d->fontEngine->recalcAdvances(&glyphs, design ? QFontEngine::DesignMetrics : QFontEngine::ShaperFlag(0));
    if (layoutFlags & KernedAdvances)
        d->fontEngine->doKerning(&glyphs, design ? QFontEngine::DesignMetrics : QFontEngine::ShaperFlag(0));

    for (int i=0; i<numGlyphs; ++i)
        advances[i] = QPointF(glyphs.advances_x[i].toReal(), glyphs.advances_y[i].toReal());

    return true;
}

/*!
   \overload

   Returns the QRawFont's advances for each of the \a glyphIndexes in pixel units. The advances
   give the distance from the position of a given glyph to where the next glyph should be drawn
   to make it appear as if the two glyphs are unspaced. The glyph indexes are given with the
   array \a glyphIndexes while the results are returned through \a advances, both of them must
   have \a numGlyphs elements. The advance of each glyph is calculated separately

   \sa QTextLine::horizontalAdvance(), QFontMetricsF::width()
*/
bool QRawFont::advancesForGlyphIndexes(const quint32 *glyphIndexes, QPointF *advances, int numGlyphs) const
{
    return QRawFont::advancesForGlyphIndexes(glyphIndexes, advances, numGlyphs, SeparateAdvances);
}

/*!
   Returns the hinting preference used to construct this QRawFont.

   \sa QFont::hintingPreference()
*/
QFont::HintingPreference QRawFont::hintingPreference() const
{
    return d->isValid() ? d->hintingPreference : QFont::PreferDefaultHinting;
}

/*!
   Retrieves the sfnt table named \a tagName from the underlying physical font, or an empty
   byte array if no such table was found. The returned font table's byte order is Big Endian, like
   the sfnt format specifies. The \a tagName must be four characters long and should be formatted
   in the default endianness of the current platform.
*/
QByteArray QRawFont::fontTable(const char *tagName) const
{
    if (!d->isValid())
        return QByteArray();

    const quint32 *tagId = reinterpret_cast<const quint32 *>(tagName);
    return d->fontEngine->getSfntTable(qToBigEndian(*tagId));
}

/*!
   Returns a list of writing systems supported by the font according to designer supplied
   information in the font file. Please note that this does not guarantee support for a
   specific unicode point in the font. You can use the supportsCharacter() to check support
   for a single, specific character.

   \note The list is determined based on the unicode ranges and codepage ranges set in the font's
   OS/2 table and requires such a table to be present in the underlying font file.

   \sa supportsCharacter()
*/
QList<QFontDatabase::WritingSystem> QRawFont::supportedWritingSystems() const
{
    QList<QFontDatabase::WritingSystem> writingSystems;
    if (d->isValid()) {
        QByteArray os2Table = fontTable("OS/2");
        if (os2Table.size() > 86) {
            char *data = os2Table.data();
            quint32 *bigEndianUnicodeRanges = reinterpret_cast<quint32 *>(data + 42);
            quint32 *bigEndianCodepageRanges = reinterpret_cast<quint32 *>(data + 78);

            quint32 unicodeRanges[4];
            quint32 codepageRanges[2];

            for (int i=0; i<4; ++i) {
                if (i < 2)
                    codepageRanges[i] = qFromBigEndian(bigEndianCodepageRanges[i]);
                unicodeRanges[i] = qFromBigEndian(bigEndianUnicodeRanges[i]);
            }

            QSupportedWritingSystems ws = QPlatformFontDatabase::writingSystemsFromTrueTypeBits(unicodeRanges, codepageRanges);
            for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
                if (ws.supported(QFontDatabase::WritingSystem(i)))
                    writingSystems.append(QFontDatabase::WritingSystem(i));
            }
        }
    }

    return writingSystems;
}

/*!
    Returns \c true if the font has a glyph that corresponds to the given \a character.

    \sa supportedWritingSystems()
*/
bool QRawFont::supportsCharacter(QChar character) const
{
    return d->isValid() && d->fontEngine->canRender(&character, 1);
}

/*!
    \overload

   Returns \c true if the font has a glyph that corresponds to the UCS-4 encoded character \a ucs4.

   \sa supportedWritingSystems()
*/
bool QRawFont::supportsCharacter(uint ucs4) const
{
    return d->isValid() && d->fontEngine->canRender(ucs4);
}

// qfontdatabase.cpp
extern int qt_script_for_writing_system(QFontDatabase::WritingSystem writingSystem);

/*!
   Fetches the physical representation based on a \a font query. The physical font returned is
   the font that will be preferred by Qt in order to display text in the selected \a writingSystem.

   \warning This function is potentially expensive and should not be called in performance
   sensitive code.
*/
QRawFont QRawFont::fromFont(const QFont &font, QFontDatabase::WritingSystem writingSystem)
{
    QRawFont rawFont;
    QFontPrivate *font_d = QFontPrivate::get(font);
    int script = qt_script_for_writing_system(writingSystem);
    QFontEngine *fe = font_d->engineForScript(script);

    if (fe != 0 && fe->type() == QFontEngine::Multi) {
        QFontEngineMulti *multiEngine = static_cast<QFontEngineMulti *>(fe);
        fe = multiEngine->engine(0);
        if (fe == 0) {
            multiEngine->loadEngine(0);
            fe = multiEngine->engine(0);
        }
    }

    if (fe != 0) {
        rawFont.d.data()->fontEngine = fe;
        rawFont.d.data()->fontEngine->ref.ref();
        rawFont.d.data()->hintingPreference = font.hintingPreference();
    }
    return rawFont;
}

/*!
   Sets the pixel size with which this font should be rendered to \a pixelSize.
*/
void QRawFont::setPixelSize(qreal pixelSize)
{
    if (d->fontEngine == 0 || qFuzzyCompare(d->fontEngine->fontDef.pixelSize, pixelSize))
        return;

    d.detach();
    QFontEngine *oldFontEngine = d->fontEngine;

    d->fontEngine = d->fontEngine->cloneWithSize(pixelSize);
    if (d->fontEngine != 0)
        d->fontEngine->ref.ref();

    if (!oldFontEngine->ref.deref())
        delete oldFontEngine;
}

/*!
    \internal
*/
void QRawFontPrivate::cleanUp()
{
    platformCleanUp();
    if (fontEngine != 0) {
        if (!fontEngine->ref.deref())
            delete fontEngine;
        fontEngine = 0;
    }
    hintingPreference = QFont::PreferDefaultHinting;
}

/*!
  Returns the smallest rectangle containing the glyph with the given \a glyphIndex.

  \since 5.0
*/
QRectF QRawFont::boundingRect(quint32 glyphIndex) const
{
    if (!isValid())
        return QRectF();

    glyph_metrics_t gm = d->fontEngine->boundingBox(glyphIndex);
    return QRectF(gm.x.toReal(), gm.y.toReal(), gm.width.toReal(), gm.height.toReal());
}

#endif // QT_NO_RAWFONT

QT_END_NAMESPACE


text:
<?php
namespace zeus\base\exception;

class ClassNotFoundException extends NestedException
{
	public function __construct ($message = null, $code = null, $previous = null)
	{
		parent::__construct($message,$code,$previous);
	}
}


text:
/// <reference path="../../typings/index.d.ts" />
"use strict";

import * as events from "events";
import * as child_process from "child_process";
import * as stream from "stream";
import * as fs from "fs";
import * as util from "util";
import * as common from "./common";
import * as log from "./log";
import * as config from "./config";
import status from "./status";
import Event from "./Event";
import ChannelItem from "./ChannelItem";

const Queue = require("promise-queue");
const pt2Queue = new Queue(1, Infinity);

interface User extends common.User {
    _stream?: stream.Writable;
}

interface Status {
    index: number;
    name: string;
    types: common.ChannelType[];
    command: string;
    pid: number;
    users: common.User[];
    isAvailable: boolean;
    isFree: boolean;
    isUsing: boolean;
}

export default class TunerDevice extends events.EventEmitter {

    private _channel: ChannelItem = null;
    private _command: string = null;
    private _process: child_process.ChildProcess = null;
    private _stream: stream.Readable = null;

    private _users: User[] = [];

    private _isAvailable: boolean = true;
    private _exited: boolean = false;
    private _closing: boolean = false;

    constructor(private _index: number, private _config: config.Tuner) {
        super();
        Event.emit("tuner", "create", this.export());
        log.debug("TunerDevice#%d initialized", this._index);
    }

    get index(): number {
        return this._index;
    }

    get config(): config.Tuner {
        return this._config;
    }

    get channel(): ChannelItem {
        return this._channel;
    }

    get command(): string {
        return this._command;
    }

    get pid(): number {
        return this._process ? this._process.pid : null;
    }

    get users(): User[] {
        return this._users.map(user => {
            return {
                id: user.id,
                priority: user.priority,
                agent: user.agent
            };
        });
    }

    get decoder(): string {
        return this._config.decoder || null;
    }

    get isAvailable(): boolean {
        return this._isAvailable;
    }

    get isFree(): boolean {
        return this._isAvailable === true && this._channel === null && this._users.length === 0;
    }

    get isUsing(): boolean {
        return this._isAvailable === true && this._channel !== null && this._users.length !== 0;
    }

    getPriority(): number {

        let priority = -2;

        for (const user of this._users) {
            if (user.priority > priority) {
                priority = user.priority;
            }
        }

        return priority;
    }

    export(): Status {
        return {
            index: this._index,
            name: this._config.name,
            types: this._config.types,
            command: this._command,
            pid: this.pid,
            users: this.users,
            isAvailable: this.isAvailable,
            isFree: this.isFree,
            isUsing: this.isUsing
        };
    }

    kill(): Promise<void> {
        return this._kill(true);
    }

    startStream(user: User, stream: stream.Writable, channel?: ChannelItem): Promise<void> {

        log.debug("TunerDevice#%d start stream for user `%s` (priority=%d)...", this._index, user.id, user.priority);

        if (this._isAvailable === false) {
            return Promise.reject(new Error(util.format("TunerDevice#%d is not available", this._index)));
        }

        const resolve = () => {

            log.info("TunerDevice#%d streaming to user `%s` (priority=%d)", this._index, user.id, user.priority);

            user._stream = stream;
            this._users.push(user);

            stream.once("close", () => this.endStream(user));

            this._updated();

            return Promise.resolve();
        };

        if (!channel) {
            if (!this._stream) {
                return Promise.reject(new Error(util.format("TunerDevice#%d has not stream", this._index)));
            } else {
                return resolve();
            }
        }

        if (this._config.types.indexOf(channel.type) === -1) {
            return Promise.reject(
                new Error(util.format("TunerDevice#%d is not supported for channel type `%s`", this._index, channel.type))
            );
        }

        if (this._stream) {
            if (channel.channel === this._channel.channel) {
                return resolve();
            } else if (user.priority <= this.getPriority()) {
                return Promise.reject(new Error(util.format("TunerDevice#%d has higher priority user", this._index)));
            }

            return this._kill(true)
                .then(() => this._spawn(channel))
                .catch(err => Promise.reject(err))
                .then(resolve);
        } else {
            return this._spawn(channel).then(resolve);
        }
    }

    endStream(user: User): void {

        log.debug("TunerDevice#%d end stream for user `%s` (priority=%d)...", this._index, user.id, user.priority);

        for (let i = 0, l = this._users.length; i < l; i++) {
            if (this._users[i].id === user.id && this._users[i].priority === user.priority) {
                this._users[i]._stream.end();
                this._users.splice(i, 1);
                break;
            }
        }

        if (this._users.length === 0) {
            setTimeout(() => {
                if (this._users.length === 0 && this._process) {
                    this._kill(true).catch(log.error);
                }
            }, 3000);
        }

        log.info("TunerDevice#%d end streaming to user `%s` (priority=%d)", this._index, user.id, user.priority);

        this._updated();
    }

    private _spawn(ch: ChannelItem): Promise<void> {

        if (process.platform !== "win32" && this._config.isPT2 === true && !this._config.dvbDevicePath) {
            // PT2 support
            return new Promise<void>(resolve => {
                pt2Queue.add(() => {
                    return new Promise(_resolve => {
                        resolve();
                        setTimeout(_resolve, 500);
                    });
                }).then(() => this.__spawn(ch));
            });
        } else {
            // regular way
            return this.__spawn(ch);
        }
    }

    private __spawn(ch: ChannelItem): Promise<void> {

        log.debug("TunerDevice#%d spawn...", this._index);

        if (this._process) {
            return Promise.reject(new Error(util.format("TunerDevice#%d has process", this._index)));
        }

        let cmd = this._config.command;

        cmd = cmd.replace("<channel>", ch.channel);

        if (ch.satelite) {
            cmd = cmd.replace("<satelite>", ch.satelite);
        }

        this._process = child_process.spawn(cmd.split(" ")[0], cmd.split(" ").slice(1));
        this._command = cmd;
        this._channel = ch;

        if (this._config.dvbDevicePath) {
            const cat = child_process.spawn("cat", [this._config.dvbDevicePath]);

            cat.once("error", (err) => {

                log.error("TunerDevice#%d cat process error `%s` (pid=%d)", this._index, err.code, cat.pid);

                this._kill(false);
            });

            cat.once("close", (code, signal) => {

                log.debug(
                    "TunerDevice#%d cat process has closed with code=%d by signal `%s` (pid=%d)",
                    this._index, code, signal, cat.pid
                );

                if (this._exited === false) {
                    this._kill(false);
                }
            });

            this._process.once("exit", () => cat.kill("SIGKILL"));

            this._stream = cat.stdout;
        } else {
            this._stream = this._process.stdout;
        }

        this._process.once("exit", () => this._exited = true);

        this._process.once("error", (err) => {

            log.fatal("TunerDevice#%d process error `%s` (pid=%d)", this._index, err.code, this._process.pid);

            this._end();
            setTimeout(this._release.bind(this), this._config.dvbDevicePath ? 1000 : 100);
        });

        this._process.once("close", (code, signal) => {

            log.info(
                "TunerDevice#%d process has closed with exit code=%d by signal `%s` (pid=%d)",
                this._index, code, signal, this._process.pid
            );

            this._end();
            setTimeout(this._release.bind(this), this._config.dvbDevicePath ? 1000 : 100);
        });

        this._process.stderr.on("data", data => {
            log.info("TunerDevice#%d > %s", this._index, data.toString().trim());
        });

        // flowing start
        this._stream.on("data", this._streamOnData.bind(this));

        this._updated();
        log.info("TunerDevice#%d process has spawned by command `%s` (pid=%d)", this._index, cmd, this._process.pid);

        return Promise.resolve();
    }

    private _streamOnData(chunk: Buffer): void {

        for (let i = 0, l = this._users.length; i < l; i++) {
            this._users[i]._stream.write(chunk);
        }
    }

    private _end(): void {

        this._isAvailable = false;

        this._stream.removeAllListeners("data");

        if (this._closing === true) {
            for (const user of this._users) {
                user._stream.end();
            }
            this._users.length = 0;
        }

        this._updated();
    }

    private _kill(close: boolean): Promise<void> {

        log.debug("TunerDevice#%d kill...", this._index);

        if (!this._process || !this._process.pid) {
            return Promise.reject(new Error(util.format("TunerDevice#%d has not process", this._index)));
        }

        this._isAvailable = false;
        this._closing = close;

        this._updated();

        return new Promise<void>(resolve => {

            this.once("release", resolve);

            if (process.platform === "win32") {
                const timer = setTimeout(() => this._process.kill(), 3000);
                this._process.once("exit", () => clearTimeout(timer));

                this._process.stdin.write("\n");
            } else if (this._config.isPT2 === true && !this._config.dvbDevicePath) {
                // PT2 support
                pt2Queue.add(() => {
                    return new Promise(resolve => {
                        this._process.kill("SIGTERM");
                        setTimeout(resolve, 500);
                    });
                });
            } else {
                // regular way
                this._process.kill("SIGTERM");
            }
        });
    }

    private _release(): void {

        if (this._process) {
            this._process.stderr.removeAllListeners();
            this._process.removeAllListeners();
        }
        if (this._stream) {
            this._stream.removeAllListeners();
        }

        this._command = null;
        this._process = null;
        this._stream = null;

        if (this._closing === true) {
            this._channel = null;
            this._users = [];
        }

        this._isAvailable = true;
        this._closing = false;
        this._exited = false;

        this.emit("release");

        log.debug("TunerDevice#%d released", this._index);

        this._updated();

        if (this._closing === false && this._users.length !== 0) {
            log.debug("TunerDevice#%d respawning because request has not closed", this._index);
            ++status.errorCount.tunerDeviceRespawn;

            this._spawn(this._channel);
        }
    }

    private _updated(): void {
        Event.emit("tuner", "update", this.export());
    }
}


text:
using AutoMapper;
using MvcTemplate.Tests.Objects;

namespace MvcTemplate.Tests.Data.Mapping
{
    public static class TestObjectMapper
    {
        public static void MapObjects()
        {
            Mapper.CreateMap<TestModel, TestView>();
            Mapper.CreateMap<TestView, TestModel>();
        }
    }
}


text:
title: IconButton
---

Like icon buttons

## Examples

```jsx
<Icon name="thumb-up" />
```

## API

### Props

Name | Description | Type | Optional value | Default
--- | --- | --- | --- | ---
`iconName` | -| string | - | Empty string ('')
`iconStyle` | - | style | - | -
`disabled` | - | bool | - | `false`
`size` | - | enum | `mini`,
`small`,
`medium`,
`large`,
`big` | `medium`

### Event

Name | Description
--- | ---
`onPress` | -

Based on https://github.com/oblador/react-native-vector-icons/


text:
package com.mijackstudio.servlet;

import com.mijackstudio.base.Result;
import com.mijackstudio.bean.NetAPK;
import com.mijackstudio.bean.STATUS;
import com.mijackstudio.pool.DownloadTaskPool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author MiJack
 * @since 2016/5/5
 */
@WebServlet(name = "CreateTaskServlet", urlPatterns = {"/createTask"})
public class CreateTaskServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String apkUrl = request.getParameter("apk_url");
        PrintWriter writer = response.getWriter();
        DownloadTaskPool taskPool = DownloadTaskPool.getInstance();
        Result<String, NetAPK> result = taskPool.addData(apkUrl);
        if (result != null) {
            STATUS status = getStatus(result);
            writer.write("status=" + status + "\n");
            switch (status) {
                case FINISH:
                    NetAPK apk = result.getR();
                    writer.write("file md5="+apk.getFileMD5()+"\n");
                    writer.write("local path="+apk.getLocalPath()+"\n");
                    writer.write("task id="+apk.getTaskId()+"\n");
                case WAIT:
                case NEW:
                    writer.write("url="+apkUrl);
            }
        }
        writer.flush();
        writer.close();
    }

    private STATUS getStatus(Result<String, NetAPK> result) {
        NetAPK r = result.getR();
        String p = result.getP();
        if (r == null && p == null) {
            return STATUS.NEW;
        } else if (p != null && r == null) {
            return STATUS.WAIT;
        } else if (p != null && r != null) {
            return STATUS.FINISH;
        }
        return STATUS.UNKNOWN;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}